@travetto/schema 7.0.0-rc.0 → 7.0.0-rc.2

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.
@@ -8,13 +8,13 @@ import {
8
8
  } from './types';
9
9
 
10
10
  const classToDiscriminatedType = (cls: Class): string => cls.name
11
- .replace(/([A-Z])([A-Z][a-z])/g, (all, l, r) => `${l}_${r.toLowerCase()}`)
12
- .replace(/([a-z]|\b)([A-Z])/g, (all, l, r) => l ? `${l}_${r.toLowerCase()}` : r.toLowerCase())
11
+ .replace(/([A-Z])([A-Z][a-z])/g, (all, left, right) => `${left}_${right.toLowerCase()}`)
12
+ .replace(/([a-z]|\b)([A-Z])/g, (all, left, right) => left ? `${left}_${right.toLowerCase()}` : right.toLowerCase())
13
13
  .toLowerCase();
14
14
 
15
15
  function assignMetadata<T>(key: symbol, base: SchemaCoreConfig, data: Partial<T>[]): T {
16
- const md = base.metadata ??= {};
17
- const out = md[key] ??= {};
16
+ const metadata = base.metadata ??= {};
17
+ const out = metadata[key] ??= {};
18
18
  for (const d of data) {
19
19
  safeAssign(out, d);
20
20
  }
@@ -92,8 +92,8 @@ function combineClassWithParent<T extends SchemaClassConfig>(base: T, parent: T)
92
92
  case 'Required':
93
93
  case 'Partial': {
94
94
  base.fields = Object.fromEntries(
95
- Object.entries(base.fields).map(([k, v]) => [k, {
96
- ...v,
95
+ Object.entries(parent.fields).map(([key, value]) => [key, {
96
+ ...value,
97
97
  required: {
98
98
  active: base.mappedOperation === 'Required'
99
99
  }
@@ -105,8 +105,8 @@ function combineClassWithParent<T extends SchemaClassConfig>(base: T, parent: T)
105
105
  case 'Omit': {
106
106
  const keys = new Set<string>(base.mappedFields ?? []);
107
107
  base.fields = Object.fromEntries(
108
- Object.entries(parent.fields).filter(([k]) =>
109
- base.mappedOperation === 'Pick' ? keys.has(k) : !keys.has(k)
108
+ Object.entries(parent.fields).filter(([key]) =>
109
+ base.mappedOperation === 'Pick' ? keys.has(key) : !keys.has(key)
110
110
  )
111
111
  );
112
112
  break;
@@ -145,7 +145,7 @@ export class SchemaRegistryAdapter implements RegistryAdapter<SchemaClassConfig>
145
145
  }
146
146
 
147
147
  register(...data: Partial<SchemaClassConfig>[]): SchemaClassConfig {
148
- const cfg = this.#config ??= {
148
+ const config = this.#config ??= {
149
149
  methods: {},
150
150
  class: this.#cls,
151
151
  views: {},
@@ -153,38 +153,38 @@ export class SchemaRegistryAdapter implements RegistryAdapter<SchemaClassConfig>
153
153
  interfaces: [],
154
154
  fields: {},
155
155
  };
156
- return combineClasses(cfg, data);
156
+ return combineClasses(config, data);
157
157
  }
158
158
 
159
159
  registerMetadata<T>(key: symbol, ...data: Partial<T>[]): T {
160
- const cfg = this.register({});
161
- return assignMetadata(key, cfg, data);
160
+ const config = this.register({});
161
+ return assignMetadata(key, config, data);
162
162
  }
163
163
 
164
164
  getMetadata<T>(key: symbol): T | undefined {
165
- const md = this.#config?.metadata;
166
- return castTo<T>(md?.[key]);
165
+ const metadata = this.#config?.metadata;
166
+ return castTo<T>(metadata?.[key]);
167
167
  }
168
168
 
169
- registerField(field: string | symbol, ...data: Partial<SchemaFieldConfig>[]): SchemaFieldConfig {
170
- const config = this.register({});
171
- const cfg = config.fields[field] ??= { name: field, owner: this.#cls, type: null! };
172
- const combined = combineInputs(cfg, data);
169
+ registerField(field: string, ...data: Partial<SchemaFieldConfig>[]): SchemaFieldConfig {
170
+ const classConfig = this.register({});
171
+ const config = classConfig.fields[field] ??= { name: field, owner: this.#cls, type: null! };
172
+ const combined = combineInputs(config, data);
173
173
  return combined;
174
174
  }
175
175
 
176
- registerFieldMetadata<T>(field: string | symbol, key: symbol, ...data: Partial<T>[]): T {
177
- const cfg = this.registerField(field);
178
- return assignMetadata(key, cfg, data);
176
+ registerFieldMetadata<T>(field: string, key: symbol, ...data: Partial<T>[]): T {
177
+ const config = this.registerField(field);
178
+ return assignMetadata(key, config, data);
179
179
  }
180
180
 
181
- getFieldMetadata<T>(field: string | symbol, key: symbol): T | undefined {
182
- const md = this.#config?.fields[field]?.metadata;
183
- return castTo<T>(md?.[key]);
181
+ getFieldMetadata<T>(field: string, key: symbol): T | undefined {
182
+ const metadata = this.#config?.fields[field]?.metadata;
183
+ return castTo<T>(metadata?.[key]);
184
184
  }
185
185
 
186
- registerClass({ methods, ...cfg }: Partial<SchemaClassConfig> = {}): SchemaClassConfig {
187
- this.register({ ...cfg });
186
+ registerClass({ methods, ...config }: Partial<SchemaClassConfig> = {}): SchemaClassConfig {
187
+ this.register({ ...config });
188
188
  if (methods?.[CONSTRUCTOR_PROPERTY]) {
189
189
  const { parameters, ...rest } = methods[CONSTRUCTOR_PROPERTY];
190
190
  this.registerMethod(CONSTRUCTOR_PROPERTY, rest);
@@ -195,36 +195,36 @@ export class SchemaRegistryAdapter implements RegistryAdapter<SchemaClassConfig>
195
195
  return this.#config;
196
196
  }
197
197
 
198
- registerMethod(method: string | symbol, ...data: Partial<SchemaMethodConfig>[]): SchemaMethodConfig {
199
- const config = this.register();
200
- const cfg = config.methods[method] ??= { parameters: [], validators: [] };
201
- return combineMethods(cfg, data);
198
+ registerMethod(method: string, ...data: Partial<SchemaMethodConfig>[]): SchemaMethodConfig {
199
+ const classConfig = this.register();
200
+ const config = classConfig.methods[method] ??= { parameters: [], validators: [] };
201
+ return combineMethods(config, data);
202
202
  }
203
203
 
204
- registerMethodMetadata<T>(method: string | symbol, key: symbol, ...data: Partial<T>[]): T {
205
- const cfg = this.registerMethod(method);
206
- return assignMetadata(key, cfg, data);
204
+ registerMethodMetadata<T>(method: string, key: symbol, ...data: Partial<T>[]): T {
205
+ const config = this.registerMethod(method);
206
+ return assignMetadata(key, config, data);
207
207
  }
208
208
 
209
- getMethodMetadata<T>(method: string | symbol, key: symbol): T | undefined {
210
- const md = this.#config?.methods[method]?.metadata;
211
- return castTo<T>(md?.[key]);
209
+ getMethodMetadata<T>(method: string, key: symbol): T | undefined {
210
+ const metadata = this.#config?.methods[method]?.metadata;
211
+ return castTo<T>(metadata?.[key]);
212
212
  }
213
213
 
214
- registerParameter(method: string | symbol, idx: number, ...data: Partial<SchemaParameterConfig>[]): SchemaParameterConfig {
214
+ registerParameter(method: string, idx: number, ...data: Partial<SchemaParameterConfig>[]): SchemaParameterConfig {
215
215
  const params = this.registerMethod(method, {}).parameters;
216
- const cfg = params[idx] ??= { method, index: idx, owner: this.#cls, array: false, type: null! };
217
- return combineInputs(cfg, data);
216
+ const config = params[idx] ??= { method, index: idx, owner: this.#cls, array: false, type: null! };
217
+ return combineInputs(config, data);
218
218
  }
219
219
 
220
- registerParameterMetadata<T>(method: string | symbol, idx: number, key: symbol, ...data: Partial<T>[]): T {
221
- const cfg = this.registerParameter(method, idx);
222
- return assignMetadata(key, cfg, data);
220
+ registerParameterMetadata<T>(method: string, idx: number, key: symbol, ...data: Partial<T>[]): T {
221
+ const config = this.registerParameter(method, idx);
222
+ return assignMetadata(key, config, data);
223
223
  }
224
224
 
225
- getParameterMetadata<T>(method: string | symbol, idx: number, key: symbol): T | undefined {
226
- const md = this.#config?.methods[method]?.parameters[idx]?.metadata;
227
- return castTo<T>(md?.[key]);
225
+ getParameterMetadata<T>(method: string, idx: number, key: symbol): T | undefined {
226
+ const metadata = this.#config?.methods[method]?.parameters[idx]?.metadata;
227
+ return castTo<T>(metadata?.[key]);
228
228
  }
229
229
 
230
230
  finalize(parent?: SchemaClassConfig): void {
@@ -256,13 +256,13 @@ export class SchemaRegistryAdapter implements RegistryAdapter<SchemaClassConfig>
256
256
  const fields = config.views[view];
257
257
  const withoutSet = 'without' in fields ? new Set<string>(fields.without) : undefined;
258
258
  const fieldList = withoutSet ?
259
- Object.keys(config.fields).filter(x => !withoutSet.has(x)) :
259
+ Object.keys(config.fields).filter(field => !withoutSet.has(field)) :
260
260
  ('with' in fields ? fields.with : []);
261
261
 
262
262
  this.#views.set(view,
263
- fieldList.reduce<SchemaFieldMap>((acc, v) => {
264
- acc[v] = config.fields[v];
265
- return acc;
263
+ fieldList.reduce<SchemaFieldMap>((map, value) => {
264
+ map[value] = config.fields[value];
265
+ return map;
266
266
  }, {})
267
267
  );
268
268
  }
@@ -278,23 +278,23 @@ export class SchemaRegistryAdapter implements RegistryAdapter<SchemaClassConfig>
278
278
  return this.#config;
279
279
  }
280
280
 
281
- getField(field: string | symbol): SchemaFieldConfig {
281
+ getField(field: string): SchemaFieldConfig {
282
282
  return this.#config.fields[field];
283
283
  }
284
284
 
285
- getMethod(method: string | symbol): SchemaMethodConfig {
286
- const res = this.#config.methods[method];
287
- if (!res) {
285
+ getMethod(method: string): SchemaMethodConfig {
286
+ const methodConfig = this.#config.methods[method];
287
+ if (!methodConfig) {
288
288
  throw new AppError(`Unknown method ${String(method)} on class ${this.#cls.Ⲑid}`);
289
289
  }
290
- return res;
290
+ return methodConfig;
291
291
  }
292
292
 
293
- getMethodReturnType(method: string | symbol): Class {
293
+ getMethodReturnType(method: string): Class {
294
294
  return this.getMethod(method).returnType!.type;
295
295
  }
296
296
 
297
- getSchema(view?: string): SchemaFieldMap {
297
+ getFields(view?: string): SchemaFieldMap {
298
298
  if (!view) {
299
299
  return this.#config.fields;
300
300
  }
@@ -321,13 +321,13 @@ export class SchemaRegistryAdapter implements RegistryAdapter<SchemaClassConfig>
321
321
  /**
322
322
  * Ensure type is set properly
323
323
  */
324
- ensureInstanceTypeField<T>(o: T): T {
324
+ ensureInstanceTypeField<T>(value: T): T {
325
325
  const config = this.getDiscriminatedConfig();
326
326
  if (config) {
327
327
  const typeField = castKey<T>(config.discriminatedField);
328
- o[typeField] ??= castTo(config.discriminatedType); // Assign if missing
328
+ value[typeField] ??= castTo(config.discriminatedType); // Assign if missing
329
329
  }
330
- return o;
330
+ return value;
331
331
  }
332
332
 
333
333
  getDiscriminatedConfig(): Required<Pick<SchemaClassConfig, 'discriminatedType' | 'discriminatedField' | 'discriminatedBase'>> | undefined {
@@ -1,7 +1,7 @@
1
1
  import { ChangeEvent, RegistrationMethods, RegistryIndex, RegistryIndexStore, Registry } from '@travetto/registry';
2
2
  import { AppError, castKey, castTo, Class, classConstruct, getParentClass, Util } from '@travetto/runtime';
3
3
 
4
- import { SchemaFieldConfig, SchemaClassConfig, SchemaFieldMap, SchemaMethodConfig } from './types.ts';
4
+ import { SchemaFieldConfig, SchemaClassConfig } from './types.ts';
5
5
  import { SchemaRegistryAdapter } from './registry-adapter.ts';
6
6
  import { SchemaChangeListener } from './changes.ts';
7
7
 
@@ -24,14 +24,6 @@ export class SchemaRegistryIndex implements RegistryIndex {
24
24
  return this.#instance.store.get(cls).getDiscriminatedConfig();
25
25
  }
26
26
 
27
- static getFieldMap(cls: Class, view?: string): SchemaFieldMap {
28
- return this.#instance.store.get(cls).getSchema(view);
29
- }
30
-
31
- static getMethodConfig(cls: Class, method: string | symbol): SchemaMethodConfig {
32
- return this.#instance.store.get(cls).getMethod(method);
33
- }
34
-
35
27
  static has(cls: Class): boolean {
36
28
  return this.#instance.store.has(cls);
37
29
  }
@@ -44,8 +36,8 @@ export class SchemaRegistryIndex implements RegistryIndex {
44
36
  return this.#instance.getDiscriminatedTypes(cls);
45
37
  }
46
38
 
47
- static resolveInstanceType<T>(cls: Class<T>, o: T): Class {
48
- return this.#instance.resolveInstanceType(cls, o);
39
+ static resolveInstanceType<T>(cls: Class<T>, item: T): Class {
40
+ return this.#instance.resolveInstanceType(cls, item);
49
41
  }
50
42
 
51
43
  static visitFields<T>(cls: Class<T>, onField: (field: SchemaFieldConfig, path: SchemaFieldConfig[]) => void): void {
@@ -64,8 +56,8 @@ export class SchemaRegistryIndex implements RegistryIndex {
64
56
  return this.#instance.store.get(cls);
65
57
  }
66
58
 
67
- static getOptionalConfig(cls: Class): SchemaClassConfig | undefined {
68
- return this.#instance.store.getOptional(cls)?.get();
59
+ static getOptional(cls: Class): Omit<SchemaRegistryAdapter, RegistrationMethods> | undefined {
60
+ return this.#instance.store.getOptional(cls);
69
61
  }
70
62
 
71
63
  static getClasses(): Class[] {
@@ -96,21 +88,21 @@ export class SchemaRegistryIndex implements RegistryIndex {
96
88
  Util.queueMacroTask().then(() => {
97
89
  SchemaChangeListener.emitFieldChanges({
98
90
  type: 'changed',
99
- curr: this.getClassConfig(event.curr),
100
- prev: this.getClassConfig(event.prev)
91
+ current: this.getClassConfig(event.current),
92
+ previous: this.getClassConfig(event.previous)
101
93
  });
102
94
  });
103
95
  }
104
96
 
105
97
  #onRemoving(event: ChangeEvent<Class> & { type: 'removing' }): void {
106
- SchemaChangeListener.clearSchemaDependency(event.prev);
98
+ SchemaChangeListener.clearSchemaDependency(event.previous);
107
99
  }
108
100
 
109
101
  #onAdded(event: ChangeEvent<Class> & { type: 'added' }): void {
110
102
  Util.queueMacroTask().then(() => {
111
103
  SchemaChangeListener.emitFieldChanges({
112
104
  type: 'added',
113
- curr: this.getClassConfig(event.curr)
105
+ current: this.getClassConfig(event.current)
114
106
  });
115
107
  });
116
108
  }
@@ -128,8 +120,8 @@ export class SchemaRegistryIndex implements RegistryIndex {
128
120
 
129
121
  // Rebuild indices after every "process" batch
130
122
  this.#byDiscriminatedTypes.clear();
131
- for (const el of this.store.getClasses()) {
132
- this.#registerDiscriminatedTypes(el);
123
+ for (const cls of this.store.getClasses()) {
124
+ this.#registerDiscriminatedTypes(cls);
133
125
  }
134
126
  }
135
127
 
@@ -142,15 +134,15 @@ export class SchemaRegistryIndex implements RegistryIndex {
142
134
  */
143
135
  getBaseClass(cls: Class): Class {
144
136
  if (!this.#baseSchema.has(cls)) {
145
- let conf = this.getClassConfig(cls);
137
+ let config = this.getClassConfig(cls);
146
138
  let parent: Class | undefined = cls;
147
- while (parent && conf.discriminatedType && !conf.discriminatedBase) {
139
+ while (parent && config.discriminatedType && !config.discriminatedBase) {
148
140
  parent = getParentClass(parent);
149
141
  if (parent) {
150
- conf = this.store.getOptional(parent)?.get() ?? conf;
142
+ config = this.store.getOptional(parent)?.get() ?? config;
151
143
  }
152
144
  }
153
- this.#baseSchema.set(cls, conf.class);
145
+ this.#baseSchema.set(cls, config.class);
154
146
  }
155
147
  return this.#baseSchema.get(cls)!;
156
148
  }
@@ -158,18 +150,16 @@ export class SchemaRegistryIndex implements RegistryIndex {
158
150
  /**
159
151
  * Find the resolved type for a given instance
160
152
  * @param cls Class for instance
161
- * @param o Actual instance
153
+ * @param item Actual instance
162
154
  */
163
- resolveInstanceType<T>(requestedCls: Class<T>, o: T): Class {
164
- const cls = this.store.getClassById(requestedCls.Ⲑid); // Resolve by id to handle any stale references
165
- const adapter = this.store.get(cls);
166
- const { discriminatedField, discriminatedType } = adapter.get();
155
+ resolveInstanceType<T>(cls: Class<T>, item: T): Class {
156
+ const { discriminatedField, discriminatedType, class: targetClass } = this.store.get(cls).get();
167
157
  if (!discriminatedField) {
168
- return cls;
158
+ return targetClass;
169
159
  } else {
170
- const base = this.getBaseClass(cls);
160
+ const base = this.getBaseClass(targetClass);
171
161
  const map = this.#byDiscriminatedTypes.get(base);
172
- const type = castTo<string>(o[castKey<T>(discriminatedField)]) ?? discriminatedType;
162
+ const type = castTo<string>(item[castKey<T>(discriminatedField)]) ?? discriminatedType;
173
163
  if (!type) {
174
164
  throw new AppError(`Unable to resolve discriminated type for class ${base.name} without a type`);
175
165
  }
@@ -177,8 +167,8 @@ export class SchemaRegistryIndex implements RegistryIndex {
177
167
  throw new AppError(`Unable to resolve discriminated type '${type}' for class ${base.name}`);
178
168
  }
179
169
  const requested = map.get(type)!;
180
- if (!(classConstruct(requested) instanceof requestedCls)) {
181
- throw new AppError(`Resolved discriminated type '${type}' for class ${base.name} is not an instance of requested type ${requestedCls.name}`);
170
+ if (!(classConstruct(requested) instanceof targetClass)) {
171
+ throw new AppError(`Resolved discriminated type '${type}' for class ${base.name} is not an instance of requested type ${targetClass.name}`);
182
172
  }
183
173
  return requested;
184
174
  }
@@ -187,13 +177,13 @@ export class SchemaRegistryIndex implements RegistryIndex {
187
177
  /**
188
178
  * Track changes to schemas, and track the dependent changes
189
179
  * @param cls The root class of the hierarchy
190
- * @param curr The new class
180
+ * @param current The new class
191
181
  * @param path The path within the object hierarchy
192
182
  */
193
- trackSchemaDependencies(cls: Class, curr: Class = cls, path: SchemaFieldConfig[] = []): void {
194
- const config = this.getClassConfig(curr);
183
+ trackSchemaDependencies(cls: Class, current: Class = cls, path: SchemaFieldConfig[] = []): void {
184
+ const config = this.getClassConfig(current);
195
185
 
196
- SchemaChangeListener.trackSchemaDependency(curr, cls, path, this.getClassConfig(cls));
186
+ SchemaChangeListener.trackSchemaDependency(current, cls, path, this.getClassConfig(cls));
197
187
 
198
188
  // Read children
199
189
  for (const field of Object.values(config.fields)) {
@@ -3,7 +3,7 @@ import { Any, Class, Primitive } from '@travetto/runtime';
3
3
  import { MethodValidatorFn, ValidatorFn } from '../validate/types.ts';
4
4
 
5
5
  type TemplateLiteralPart = string | NumberConstructor | StringConstructor | BooleanConstructor;
6
- export type TemplateLiteral = { op: 'and' | 'or', values: (TemplateLiteralPart | TemplateLiteral)[] };
6
+ export type TemplateLiteral = { operation: 'and' | 'or', values: (TemplateLiteralPart | TemplateLiteral)[] };
7
7
 
8
8
  export const CONSTRUCTOR_PROPERTY = 'CONSTRUCTOR';
9
9
 
@@ -83,7 +83,7 @@ export interface SchemaFieldMap {
83
83
  /**
84
84
  * List of all fields
85
85
  */
86
- [key: string | symbol]: SchemaFieldConfig;
86
+ [key: string]: SchemaFieldConfig;
87
87
  }
88
88
 
89
89
  /**
@@ -121,7 +121,7 @@ export interface SchemaClassConfig extends SchemaCoreConfig {
121
121
  /**
122
122
  * Method configs
123
123
  */
124
- methods: Record<string | symbol, SchemaMethodConfig>;
124
+ methods: Record<string, SchemaMethodConfig>;
125
125
  /**
126
126
  * Interfaces that the class implements
127
127
  */
@@ -209,7 +209,7 @@ export interface SchemaParameterConfig extends SchemaInputConfig {
209
209
  /**
210
210
  * Method the parameter belongs to
211
211
  */
212
- method: string | symbol;
212
+ method: string;
213
213
  /**
214
214
  * Source text for the parameter
215
215
  */
@@ -223,7 +223,7 @@ export interface SchemaFieldConfig extends SchemaInputConfig {
223
223
  /**
224
224
  * Field name
225
225
  */
226
- name: string | symbol;
226
+ name: string;
227
227
  /**
228
228
  * Is the field readonly, or write only?, defaults to no restrictions
229
229
  */
package/src/types.ts CHANGED
@@ -3,6 +3,6 @@ export class UnknownType { }
3
3
  /**
4
4
  * Geometric Point as [number,number] with validation and binding support
5
5
  *
6
- * @concrete ./internal/types.ts#PointImpl
6
+ * @concrete ./internal/types.ts#PointImplementation
7
7
  */
8
8
  export type Point = [number, number];
@@ -22,6 +22,6 @@ export class TypeMismatchError extends AppError {
22
22
  }
23
23
  }
24
24
 
25
- export function isValidationError(err: unknown): err is ValidationError {
26
- return !!err && err instanceof Error && 'path' in err;
25
+ export function isValidationError(error: unknown): error is ValidationError {
26
+ return !!error && error instanceof Error && 'path' in error;
27
27
  }
@@ -15,8 +15,8 @@ export const CommonRegExp = {
15
15
  export const CommonRegExpToName = new Map<RegExp, string>();
16
16
 
17
17
  // Rebind regexes
18
- for (const k of TypedObject.keys(CommonRegExp)) {
19
- const name = `[[:${k}:]]`;
20
- CommonRegExpToName.set(CommonRegExp[k], name);
21
- Messages.set(name, Messages.get(k)!);
18
+ for (const key of TypedObject.keys(CommonRegExp)) {
19
+ const name = `[[:${key}:]]`;
20
+ CommonRegExpToName.set(CommonRegExp[key], name);
21
+ Messages.set(name, Messages.get(key)!);
22
22
  }