@alexify/metaschema 0.0.0-stage → 1.0.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/CHANGELOG.md +452 -0
- package/LICENSE +22 -0
- package/README.md +178 -2
- package/SECURITY.md +60 -0
- package/browser.js +4 -0
- package/index.d.ts +226 -0
- package/index.js +1 -0
- package/package.json +90 -3
- package/src/errors.js +28 -0
- package/src/index.js +23 -0
- package/src/kinds.js +68 -0
- package/src/metadata.js +168 -0
- package/src/metautil.js +23 -0
- package/src/model.js +92 -0
- package/src/preprocessor.js +110 -0
- package/src/prototypes/abstract.js +84 -0
- package/src/prototypes/collections.js +98 -0
- package/src/prototypes/json.js +15 -0
- package/src/prototypes/reference.js +42 -0
- package/src/prototypes/scalars.js +44 -0
- package/src/prototypes/schema.js +31 -0
- package/src/prototypes/tuple.js +45 -0
- package/src/runtime/browser.js +6 -0
- package/src/runtime/node.js +5 -0
- package/src/schema.js +187 -0
- package/src/struct.js +63 -0
- package/src/types.js +127 -0
- package/src/util.js +97 -0
package/src/schema.js
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
const { isFirstUpper } = require('./metautil.js');
|
|
2
|
+
|
|
3
|
+
const { BRAND, INSPECT, hasBrand, ancestors, limits } = require('./util.js');
|
|
4
|
+
const { TYPES } = require('./types.js');
|
|
5
|
+
const { Preprocessor } = require('./preprocessor.js');
|
|
6
|
+
const { SchemaMetadata, ValidationResult } = require('./metadata.js');
|
|
7
|
+
const { SchemaDefinitionError } = require('./errors.js');
|
|
8
|
+
const { createStruct, checkStruct } = require('./struct.js');
|
|
9
|
+
|
|
10
|
+
const TS_SCALARS = { string: 'string', number: 'number', boolean: 'boolean', bigint: 'bigint' };
|
|
11
|
+
|
|
12
|
+
const maxErrorsOf = ({ maxErrors }) => {
|
|
13
|
+
const valid = typeof maxErrors === 'number' && maxErrors >= 1;
|
|
14
|
+
if (!valid) throw new TypeError(`maxErrors must be a number of at least 1, got ${maxErrors}`);
|
|
15
|
+
return maxErrors;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
const listOf = (element) => (element.includes(' | ') ? `(${element})[]` : `${element}[]`);
|
|
19
|
+
|
|
20
|
+
// The TypeScript type of a field. A reference is stored as an id, so it
|
|
21
|
+
// renders as a string (an array of them for `many`); a custom scalar with its
|
|
22
|
+
// own check has no known shape and renders as a string too.
|
|
23
|
+
const tsType = (def) => {
|
|
24
|
+
if (isFirstUpper(def.type)) return def.many ? 'string[]' : 'string';
|
|
25
|
+
if (def.enum) return def.enum.map((value) => JSON.stringify(value)).join(' | ');
|
|
26
|
+
if (def.scalar) return TS_SCALARS[def.scalar] || 'string';
|
|
27
|
+
if (def.schema) return `{ ${tsFields(def.schema).join('; ')} }`;
|
|
28
|
+
if (Array.isArray(def.value)) return `[${def.value.map(tsType).join(', ')}]`;
|
|
29
|
+
if (def.key !== undefined && def.value) {
|
|
30
|
+
const entries = `${def.key}, ${tsType(def.value)}`;
|
|
31
|
+
return def.isInstance({}) ? `Record<${entries}>` : `Map<${entries}>`;
|
|
32
|
+
}
|
|
33
|
+
if (def.value) return listOf(tsType(def.value));
|
|
34
|
+
if (def.kind === 'struct') return 'unknown';
|
|
35
|
+
return 'string';
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const tsFields = (fields) => {
|
|
39
|
+
const lines = [];
|
|
40
|
+
for (const pair of Object.entries(fields)) {
|
|
41
|
+
const key = pair[0];
|
|
42
|
+
const def = pair[1];
|
|
43
|
+
if (!hasBrand(def, 'Type')) continue;
|
|
44
|
+
const optional = def.required ? '' : '?';
|
|
45
|
+
const name = isFirstUpper(def.type) ? `${key}Id` : key;
|
|
46
|
+
lines.push(`${name}${optional}: ${tsType(def)}`);
|
|
47
|
+
}
|
|
48
|
+
return lines;
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
class Schema extends SchemaMetadata {
|
|
52
|
+
// The merged type table of the attached namespaces, rebuilt only when they
|
|
53
|
+
// change.
|
|
54
|
+
#types = null;
|
|
55
|
+
|
|
56
|
+
static from(source, namespaces) {
|
|
57
|
+
return new Schema('', source, namespaces);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
static extractSchema(def) {
|
|
61
|
+
if (hasBrand(def, 'Schema')) return def;
|
|
62
|
+
if (hasBrand(def.schema, 'Schema')) return def.schema;
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
constructor(name, raw, namespaces = []) {
|
|
67
|
+
// A Schema instance is reused, not copied: it keeps its own name, and the
|
|
68
|
+
// namespaces it is given here are attached so a model can resolve its
|
|
69
|
+
// references through it.
|
|
70
|
+
if (hasBrand(raw, 'Schema')) {
|
|
71
|
+
if (name && raw.name && raw.name !== name) {
|
|
72
|
+
const reason = `Schema "${raw.name}" cannot be used as "${name}"`;
|
|
73
|
+
throw new SchemaDefinitionError('ERR_INVALID_DEFINITION', reason);
|
|
74
|
+
}
|
|
75
|
+
raw.attach(...namespaces);
|
|
76
|
+
return raw;
|
|
77
|
+
}
|
|
78
|
+
super();
|
|
79
|
+
this.name = name;
|
|
80
|
+
this.namespaces = new Set(namespaces);
|
|
81
|
+
const preprocessor = new Preprocessor(this);
|
|
82
|
+
const { Type, defs, kindMeta } = preprocessor.parse(raw);
|
|
83
|
+
const isSchemaType = Type.type === 'schema';
|
|
84
|
+
if (!isSchemaType) {
|
|
85
|
+
this.kind = Type.kind;
|
|
86
|
+
this.fields = new Type(defs, preprocessor);
|
|
87
|
+
} else {
|
|
88
|
+
const fields = this.extractMetadata(defs.schema);
|
|
89
|
+
let extras = Object.create(null);
|
|
90
|
+
if (kindMeta) extras = this.updateFromKind(kindMeta);
|
|
91
|
+
const combined = { ...fields, ...extras };
|
|
92
|
+
this.fields = createStruct(combined, preprocessor);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
get types() {
|
|
97
|
+
if (this.namespaces.size === 0) return TYPES;
|
|
98
|
+
if (this.#types === null) {
|
|
99
|
+
const types = Array.from(this.namespaces).map((ns) => ns.types);
|
|
100
|
+
this.#types = Object.assign(Object.create(null), ...types);
|
|
101
|
+
}
|
|
102
|
+
return this.#types;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
checkConsistency() {
|
|
106
|
+
const warn = [];
|
|
107
|
+
const { name, references } = this;
|
|
108
|
+
for (const ref of references) {
|
|
109
|
+
if (isFirstUpper(ref)) {
|
|
110
|
+
const entity = this.findReference(ref);
|
|
111
|
+
if (!entity) {
|
|
112
|
+
warn.push(`Warning: "${ref}" referenced by "${name}" is not found`);
|
|
113
|
+
}
|
|
114
|
+
} else if (!this.types[ref]) {
|
|
115
|
+
warn.push(`Warning: type "${ref}" is not found in "${name}"`);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return warn;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
findReference(name) {
|
|
122
|
+
for (const ns of this.namespaces) {
|
|
123
|
+
const entity = ns.entities.get(name);
|
|
124
|
+
if (entity) return entity;
|
|
125
|
+
}
|
|
126
|
+
return null;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
check(source, path = this.name, options = {}) {
|
|
130
|
+
const result = new ValidationResult(path);
|
|
131
|
+
const { fields } = this;
|
|
132
|
+
const isStruct = hasBrand(fields, 'Struct');
|
|
133
|
+
// The root of a struct joins the path too, unless a field check already put
|
|
134
|
+
// it there (a reference checks its target through this method). A schema
|
|
135
|
+
// of any other type delegates to that type's check, which tracks itself.
|
|
136
|
+
const isObject = typeof source === 'object' && source !== null;
|
|
137
|
+
const track = isStruct && isObject && !ancestors.has(source);
|
|
138
|
+
if (track) ancestors.add(source);
|
|
139
|
+
const previous = limits.maxErrors;
|
|
140
|
+
if (options.maxErrors !== undefined) limits.maxErrors = maxErrorsOf(options);
|
|
141
|
+
try {
|
|
142
|
+
const custom = this.validate(source, path);
|
|
143
|
+
result.add(custom);
|
|
144
|
+
if (result.full) return result;
|
|
145
|
+
const nested = isStruct ? checkStruct(fields, source, path) : fields.check(source, path);
|
|
146
|
+
return result.add(nested);
|
|
147
|
+
} finally {
|
|
148
|
+
limits.maxErrors = previous;
|
|
149
|
+
if (track) ancestors.delete(source);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
toInterface() {
|
|
154
|
+
const { name, fields } = this;
|
|
155
|
+
if (!hasBrand(fields, 'Struct')) return `type ${name} = ${tsType(fields)};`;
|
|
156
|
+
const lines = tsFields(fields).map((line) => ` ${line};`);
|
|
157
|
+
return [`interface ${name} {`, ...lines, '}'].join('\n');
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
attach(...namespaces) {
|
|
161
|
+
for (const ns of namespaces) this.namespaces.add(ns);
|
|
162
|
+
this.#types = null;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
detach(...namespaces) {
|
|
166
|
+
for (const ns of namespaces) this.namespaces.delete(ns);
|
|
167
|
+
this.#types = null;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
toString() {
|
|
171
|
+
return JSON.stringify(this);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
toJSON() {
|
|
175
|
+
const { fields } = this;
|
|
176
|
+
return hasBrand(fields, 'Struct') ? { ...fields } : fields.toJSON();
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
[INSPECT](depth, options, inspect) {
|
|
180
|
+
const label = this.name ? `Schema(${this.name})` : 'Schema';
|
|
181
|
+
return `${label} ${inspect(this.toJSON(), options)}`;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
Schema.prototype[BRAND] = 'Schema';
|
|
186
|
+
|
|
187
|
+
module.exports = { Schema };
|
package/src/struct.js
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
const { ValidationResult } = require('./metadata.js');
|
|
2
|
+
const { BRAND, hasBrand, issue, shorten, formatters } = require('./util.js');
|
|
3
|
+
const { SchemaDefinitionError } = require('./errors.js');
|
|
4
|
+
|
|
5
|
+
// The field names of a struct, computed once at construction. A global symbol
|
|
6
|
+
// like BRAND, so a struct built by another copy of the package exposes them too.
|
|
7
|
+
const KEYS = Symbol.for('alexify.metaschema.keys');
|
|
8
|
+
|
|
9
|
+
// A struct is a null-prototype dictionary of field name -> Type (or the
|
|
10
|
+
// function of a calculated field), not a class instance with methods: a field
|
|
11
|
+
// may be named `check`, `name` or `constructor`, and an input key such as
|
|
12
|
+
// `__proto__` or `toString` must be reported as unexpected instead of silently
|
|
13
|
+
// resolving to something on Object.prototype.
|
|
14
|
+
const createStruct = (defs, prep) => {
|
|
15
|
+
const fields = Object.create(null);
|
|
16
|
+
for (const key of Object.keys(defs)) {
|
|
17
|
+
const entry = defs[key];
|
|
18
|
+
const { field, required } = formatters.key(key, entry?.required);
|
|
19
|
+
try {
|
|
20
|
+
const { Type, defs: typeDefs } = prep.parse(entry);
|
|
21
|
+
if (!Type) {
|
|
22
|
+
fields[key] = entry;
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
const child = new Type(typeDefs, prep);
|
|
26
|
+
child.required &&= required;
|
|
27
|
+
fields[field] = child;
|
|
28
|
+
} catch (error) {
|
|
29
|
+
if (error instanceof SchemaDefinitionError) error.locate(prep.root.name, field);
|
|
30
|
+
throw error;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
Object.defineProperty(fields, BRAND, { value: 'Struct' });
|
|
34
|
+
Object.defineProperty(fields, KEYS, { value: Object.keys(fields) });
|
|
35
|
+
return fields;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const checkStruct = (fields, source, path = '') => {
|
|
39
|
+
const result = new ValidationResult(path);
|
|
40
|
+
const isObject = source !== null && typeof source === 'object';
|
|
41
|
+
if (!isObject) return result.add(issue('type', path, 'not of expected type: object'));
|
|
42
|
+
const keys = fields[KEYS] || Object.keys(fields);
|
|
43
|
+
for (const name of keys) {
|
|
44
|
+
if (result.full) break;
|
|
45
|
+
const type = fields[name];
|
|
46
|
+
if (!hasBrand(type, 'Type')) continue;
|
|
47
|
+
const nestedPath = path ? `${path}.${name}` : name;
|
|
48
|
+
if (!Object.hasOwn(source, name)) {
|
|
49
|
+
if (type.required) result.add(issue('required', nestedPath, 'is required'));
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
result.add(type.check(source[name], nestedPath));
|
|
53
|
+
}
|
|
54
|
+
for (const name of Object.keys(source)) {
|
|
55
|
+
if (result.full) break;
|
|
56
|
+
if (name in fields) continue;
|
|
57
|
+
const nestedPath = path ? `${path}.${shorten(name)}` : shorten(name);
|
|
58
|
+
result.add(issue('unexpected', nestedPath, 'is not expected'));
|
|
59
|
+
}
|
|
60
|
+
return result;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
module.exports = { createStruct, checkStruct };
|
package/src/types.js
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
const { AbstractType } = require('./prototypes/abstract.js');
|
|
2
|
+
const scalars = require('./prototypes/scalars.js');
|
|
3
|
+
const collections = require('./prototypes/collections.js');
|
|
4
|
+
const { reference } = require('./prototypes/reference.js');
|
|
5
|
+
const { schema } = require('./prototypes/schema.js');
|
|
6
|
+
const { tuple } = require('./prototypes/tuple.js');
|
|
7
|
+
const { json } = require('./prototypes/json.js');
|
|
8
|
+
const { SchemaDefinitionError } = require('./errors.js');
|
|
9
|
+
|
|
10
|
+
const PROTOTYPES = {
|
|
11
|
+
...scalars,
|
|
12
|
+
...collections,
|
|
13
|
+
reference,
|
|
14
|
+
many: reference,
|
|
15
|
+
one: reference,
|
|
16
|
+
schema,
|
|
17
|
+
tuple,
|
|
18
|
+
json,
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
const customTypeError = (name, reason) =>
|
|
22
|
+
new SchemaDefinitionError('ERR_INVALID_CUSTOM_TYPE', `Custom type "${name}" ${reason}`);
|
|
23
|
+
|
|
24
|
+
const createType = (name, prototype) => {
|
|
25
|
+
class Type extends AbstractType {
|
|
26
|
+
static metadata = {};
|
|
27
|
+
static type = name;
|
|
28
|
+
static kind = prototype.kind;
|
|
29
|
+
|
|
30
|
+
static assign(key, value) {
|
|
31
|
+
this.metadata[key] = value;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
constructor(def, preprocessor) {
|
|
35
|
+
super(def, preprocessor);
|
|
36
|
+
const { type } = this;
|
|
37
|
+
this.type = type;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
const { rules } = prototype;
|
|
41
|
+
if (rules) Type.setRules(rules);
|
|
42
|
+
Object.assign(Type.prototype, prototype, { type: name });
|
|
43
|
+
return Type;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const createTypes = (prototypes) => {
|
|
47
|
+
const types = Object.create(null);
|
|
48
|
+
for (const pair of Object.entries(prototypes)) {
|
|
49
|
+
const name = pair[0];
|
|
50
|
+
const proto = pair[1];
|
|
51
|
+
types[name] = createType(name, proto);
|
|
52
|
+
}
|
|
53
|
+
return types;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
// The shared, process-wide registry. A model may ask for its own instead.
|
|
57
|
+
const TYPES = createTypes(PROTOTYPES);
|
|
58
|
+
|
|
59
|
+
const createRegistry = () => createTypes(PROTOTYPES);
|
|
60
|
+
|
|
61
|
+
const updateTypeMetadata = (Type, metadata = {}) => {
|
|
62
|
+
for (const pair of Object.entries(metadata)) {
|
|
63
|
+
const key = pair[0];
|
|
64
|
+
const value = pair[1];
|
|
65
|
+
Type.assign(key, value);
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
const checkCustomType = (name, proto) => {
|
|
70
|
+
const { checkType, construct } = proto;
|
|
71
|
+
if (!checkType || !construct) {
|
|
72
|
+
throw customTypeError(name, 'must contain "construct" and "checkType" methods');
|
|
73
|
+
}
|
|
74
|
+
const checkIsFn = typeof checkType === 'function';
|
|
75
|
+
const constructIsFn = typeof construct === 'function';
|
|
76
|
+
if (!checkIsFn || !constructIsFn) {
|
|
77
|
+
throw customTypeError(name, 'methods "construct" and "checkType" must be functions');
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
// The same table is usually registered by every Model in the process, so an
|
|
82
|
+
// entry that repeats the definition a type was created from (same `js`, same
|
|
83
|
+
// `construct` and `checkType` functions) or only adds metadata is accepted; a
|
|
84
|
+
// different definition for a registered name is an error, not a silent no-op.
|
|
85
|
+
const redefines = (Type, { js, construct, checkType }) => {
|
|
86
|
+
const metadataOnly = js === undefined && construct === undefined && checkType === undefined;
|
|
87
|
+
if (metadataOnly) return false;
|
|
88
|
+
const source = Type.source || {};
|
|
89
|
+
return js !== source.js || construct !== source.construct || checkType !== source.checkType;
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
const typeFactory = (customTypes, registry = TYPES) => {
|
|
93
|
+
for (const pair of Object.entries(customTypes)) {
|
|
94
|
+
const name = pair[0];
|
|
95
|
+
const value = pair[1];
|
|
96
|
+
if (value === null || typeof value !== 'object') {
|
|
97
|
+
throw customTypeError(name, 'must be an object with methods "construct" and "checkType"');
|
|
98
|
+
}
|
|
99
|
+
const { js, metadata, ...rest } = value;
|
|
100
|
+
const registered = registry[name];
|
|
101
|
+
if (registered) {
|
|
102
|
+
if (redefines(registered, value)) {
|
|
103
|
+
const reason = `Type "${name}" is already registered; only { metadata } may be added`;
|
|
104
|
+
throw new SchemaDefinitionError('ERR_TYPE_REGISTERED', reason);
|
|
105
|
+
}
|
|
106
|
+
updateTypeMetadata(registered, metadata);
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
let proto = rest;
|
|
110
|
+
if (js !== undefined) {
|
|
111
|
+
const base = registry[js];
|
|
112
|
+
if (!base) {
|
|
113
|
+
const reason = `Unknown js type "${js}" for custom type "${name}"`;
|
|
114
|
+
throw new SchemaDefinitionError('ERR_UNKNOWN_JS_TYPE', reason);
|
|
115
|
+
}
|
|
116
|
+
proto = base.prototype;
|
|
117
|
+
}
|
|
118
|
+
checkCustomType(name, proto);
|
|
119
|
+
const Type = createType(name, proto);
|
|
120
|
+
Type.source = { js, construct: rest.construct, checkType: rest.checkType };
|
|
121
|
+
updateTypeMetadata(Type, metadata);
|
|
122
|
+
registry[name] = Type;
|
|
123
|
+
}
|
|
124
|
+
return registry;
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
module.exports = { TYPES, createRegistry, typeFactory };
|
package/src/util.js
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// Identity brand for the package's own classes. A global symbol is shared by every copy of the
|
|
2
|
+
// package in a process and by every realm, and it survives bundlers that rename a class
|
|
3
|
+
// (`class _Schema`) and minifiers that mangle it, none of which `constructor.name` does.
|
|
4
|
+
const BRAND = Symbol.for('alexify.metaschema.brand');
|
|
5
|
+
|
|
6
|
+
// Node's util.inspect looks this symbol up; a plain Symbol.for keeps the
|
|
7
|
+
// browser build free of any Node import.
|
|
8
|
+
const INSPECT = Symbol.for('nodejs.util.inspect.custom');
|
|
9
|
+
|
|
10
|
+
const hasBrand = (value, name) => value?.[BRAND] === name;
|
|
11
|
+
|
|
12
|
+
// The objects on the current validation path. Validation is synchronous, so
|
|
13
|
+
// one set per process is enough; a value met again while it is still being
|
|
14
|
+
// checked is a cycle and is reported instead of recursed into.
|
|
15
|
+
const ancestors = new Set();
|
|
16
|
+
|
|
17
|
+
// A result stops collecting once it holds this many messages. Schema#check
|
|
18
|
+
// sets it from its options for the duration of the call (validation is
|
|
19
|
+
// synchronous) and restores it afterwards.
|
|
20
|
+
const limits = { maxErrors: Infinity };
|
|
21
|
+
|
|
22
|
+
// A validation problem with a code, built by the library's own checks. A
|
|
23
|
+
// message from a custom validator gets the code 'custom' (or 'type' from a
|
|
24
|
+
// custom checkType) when the result adds it.
|
|
25
|
+
const issue = (code, path, detail) => ({ code, path, message: `Field "${path}" ${detail}` });
|
|
26
|
+
|
|
27
|
+
// Key names taken from the value under check go into messages; a huge key
|
|
28
|
+
// must not become a huge message.
|
|
29
|
+
const KEY_LIMIT = 100;
|
|
30
|
+
|
|
31
|
+
const shorten = (key) => {
|
|
32
|
+
const name = String(key);
|
|
33
|
+
return name.length > KEY_LIMIT ? `${name.slice(0, KEY_LIMIT)}...` : name;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
const { SchemaDefinitionError } = require('./errors.js');
|
|
37
|
+
|
|
38
|
+
const isBound = (value) => value === undefined || typeof value === 'number';
|
|
39
|
+
|
|
40
|
+
const invalidLength = () =>
|
|
41
|
+
new SchemaDefinitionError(
|
|
42
|
+
'ERR_INVALID_LENGTH',
|
|
43
|
+
'Rule "length" needs a number, [min, max] or { min, max }',
|
|
44
|
+
);
|
|
45
|
+
|
|
46
|
+
const formatters = {
|
|
47
|
+
type: (type, req = true) => {
|
|
48
|
+
const required = !type.startsWith('?');
|
|
49
|
+
if (required) return { type, required: req };
|
|
50
|
+
const name = type.substring(1);
|
|
51
|
+
return { type: name, required: false };
|
|
52
|
+
},
|
|
53
|
+
|
|
54
|
+
key: (key, req = true) => {
|
|
55
|
+
const required = !key.endsWith('?');
|
|
56
|
+
if (required) return { field: key, required: req };
|
|
57
|
+
const field = key.slice(0, -1);
|
|
58
|
+
return { field, required: false };
|
|
59
|
+
},
|
|
60
|
+
|
|
61
|
+
length: (length) => {
|
|
62
|
+
if (typeof length === 'number') return { max: length };
|
|
63
|
+
if (length === null || typeof length !== 'object') throw invalidLength();
|
|
64
|
+
const min = Array.isArray(length) ? length[0] : length.min;
|
|
65
|
+
const max = Array.isArray(length) ? length[1] : length.max;
|
|
66
|
+
if (!isBound(min) || !isBound(max)) throw invalidLength();
|
|
67
|
+
return { min, max };
|
|
68
|
+
},
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
const checks = {
|
|
72
|
+
length: (src, type, path) => {
|
|
73
|
+
const { length, entries } = type;
|
|
74
|
+
const value = entries ? entries(src) : src;
|
|
75
|
+
const size = value?.size;
|
|
76
|
+
const count = value?.length;
|
|
77
|
+
let len = Number(value);
|
|
78
|
+
if (typeof size === 'number') len = size;
|
|
79
|
+
else if (typeof count === 'number') len = count;
|
|
80
|
+
const { min, max } = length;
|
|
81
|
+
if (min !== undefined && len < min) return issue('length', path, 'value is too short');
|
|
82
|
+
if (max !== undefined && len > max) return issue('length', path, 'exceeds the maximum length');
|
|
83
|
+
return null;
|
|
84
|
+
},
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
module.exports = {
|
|
88
|
+
BRAND,
|
|
89
|
+
INSPECT,
|
|
90
|
+
hasBrand,
|
|
91
|
+
ancestors,
|
|
92
|
+
limits,
|
|
93
|
+
issue,
|
|
94
|
+
shorten,
|
|
95
|
+
formatters,
|
|
96
|
+
checks,
|
|
97
|
+
};
|