Skip to main content

@versionzero/schema / CompiledSchema

Class: CompiledSchema

Defined in: src/compiled-schema.js:72

CompiledSchema - the resolved version of a schema usable for processing input values into output values

The SchemaResolver compiler takes an input Schema and constructs a CompiledSchema:

  • The base schema hierarchy is resolved and flattened.
  • Handlers have their input specifications converted into value processor executors.
  • Unions may trigger property hoisting and discriminator synthesis.
  • Core options are converted to standardized forms.
  • Metadata is expanded by introspecting the resolved schema.
  • Errors are thrown if the input Schema is invalid, inconsistent, or missing required data.

Constructors​

Constructor​

new CompiledSchema(token): CompiledSchema

Defined in: src/compiled-schema.js:102

CompiledSchema constructor - do not call directly (use SchemaResolver.compile())

Parameters​

ParameterTypeDescription
tokensymbolmagic to reduce shenanigans

Returns​

CompiledSchema

Accessors​

options​

Get Signature​

get options(): ISchemaOptions

Defined in: src/compiled-schema.js:113

Options contains information that changes schema parsing and processing.

Returns​

ISchemaOptions


metadata​

Get Signature​

get metadata(): ISchemaMetadata

Defined in: src/compiled-schema.js:122

Metadata contains information for describing the schema behavior to users and hints for tools.

Returns​

ISchemaMetadata


properties​

Get Signature​

get properties(): CompiledSchemaProperties

Defined in: src/compiled-schema.js:133

Properties are named child schemas, defining a hierarchical schema structure.

This is an (inefficient) cache for compatibility with the ISchema "interface".

Returns​

CompiledSchemaProperties


propertyEntries​

Get Signature​

get propertyEntries(): IteratorObject<[string, CompiledSchema], any, any>

Defined in: src/compiled-schema.js:142

Returns​

IteratorObject<[string, CompiledSchema], any, any>


handlers​

Get Signature​

get handlers(): CompiledSchemaHandlers

Defined in: src/compiled-schema.js:162

Handlers are associated with value processors.

The "friendly" handler definitions from the source Schema are each compiled into an array of functions (sync or async) that run as a pipeline.

All value processors have the same signature, receiving:

  1. a value to be processed by the current schema
  2. the top-level aggregate target value being built or processed by the entire schema hierarchy
  3. a location cursor referencing the associated schema and the traversal path to where it was encountered
  4. any (unmanaged / developer defined) options passed to whatever invoked the handler processing

The compiled handlers may vary in their return types and exception handling behavior.

Returns​

CompiledSchemaHandlers


unionSchemas​

Get Signature​

get unionSchemas(): CompiledSchemaUnionSchemas

Defined in: src/compiled-schema.js:202

If this schema defines a union, return the schema member elements of the union.

Unions use a discriminator handler to attempt to resolve to one of the unionSchema member elements based on either the value being processed or the overall aggregated data. The key of the unionSchema in this collection is sometimes used as part of this process.

Once the discriminator succeeds, the active schema switches to the resolved unionSchema.

Returns​

CompiledSchemaUnionSchemas


unionSchemaEntries​

Get Signature​

get unionSchemaEntries(): IteratorObject<[string, CompiledSchema], any, any>

Defined in: src/compiled-schema.js:211

Returns​

IteratorObject<[string, CompiledSchema], any, any>


hasChildren​

Get Signature​

get hasChildren(): boolean

Defined in: src/compiled-schema.js:231

Return true if this schema has any child schemas.

Returns​

boolean


isContainer​

Get Signature​

get isContainer(): boolean

Defined in: src/compiled-schema.js:242

Return true if this schema should be treated as a container.

Any schema that has children is a container, but also those explicitly marked as a container.

Returns​

boolean


hasWildcard​

Get Signature​

get hasWildcard(): boolean

Defined in: src/compiled-schema.js:251

Return true if this schema supports wildcard properties.

Returns​

boolean


isArray​

Get Signature​

get isArray(): boolean

Defined in: src/compiled-schema.js:262

Return true if this schema defines an array.

Arrays sometimes need special treatment; the built-in 'array' base schema sets this option.

Returns​

boolean


isFunction​

Get Signature​

get isFunction(): boolean

Defined in: src/compiled-schema.js:274

Return true if this schema defines a function value.

Functions passed to most operations are interpreted as dynamic values (called to retrieve actual value). This setting overrides that behavior, and forces a passed function to be treated as a simple value.

Returns​

boolean


isUnion​

Get Signature​

get isUnion(): boolean

Defined in: src/compiled-schema.js:285

Return true if this schema defines a union. Unions adopt the behavior of one of their unionSchema member elements based on a discriminator handler function.

Returns​

boolean


isUnionKey​

Get Signature​

get isUnionKey(): boolean

Defined in: src/compiled-schema.js:297

Return true if this schema is used to select union keys.

(This doesn't guarantee that there is a matching discriminator on the parent that uses it!) todo - convert this option into a generated normalizer that enforces union key values at runtime?

Returns​

boolean


isSelector​

Get Signature​

get isSelector(): boolean

Defined in: src/compiled-schema.js:309

Return true if the schema acts as a selector.

Selectors control the activation or deactivation of peer selection schemas using a conditional handler synthesized during compilation.

Returns​

boolean


hasChildSelector​

Get Signature​

get hasChildSelector(): boolean

Defined in: src/compiled-schema.js:317

Return true if this schema contains a selector as a child.

Returns​

boolean


isSelection​

Get Signature​

get isSelection(): boolean

Defined in: src/compiled-schema.js:331

Return true if this schema is a selection conditionally activated by a peer selector.

Returns​

boolean


hasChildSelection​

Get Signature​

get hasChildSelection(): boolean

Defined in: src/compiled-schema.js:339

Return true if this schema contains a selection as a child.

Returns​

boolean


selection​

Get Signature​

get selection(): string | boolean | undefined

Defined in: src/compiled-schema.js:353

Get the selector value that triggers this selection. The default value for a selection is its own property name.

Returns​

string | boolean | undefined


values​

Get Signature​

get values(): any[] | undefined

Defined in: src/compiled-schema.js:364

Return the legal (normalized) values this schema accepts, if defined.

(This acts as an "upstream" check before calling any transform handlers.)

Returns​

any[] | undefined


hasValues​

Get Signature​

get hasValues(): boolean

Defined in: src/compiled-schema.js:373

Returns true if this schema defines any values it accepts.

Returns​

boolean


strict​

Get Signature​

get strict(): boolean | undefined

Defined in: src/compiled-schema.js:397

Returns whether this schema enforces strict/lax checking.

  • returns true if the schema uses strict checking
  • returns false if the schema uses lax checking
  • if undefined, it depends on the traversal context and the behavior of individual processors

This setting is useful for preventing validation errors when transforms return new objects that contain extra properties that don't match the schema.

In most contexts (e.g. assignment processing and validation) strict processing is the default. Setting lax mode changes several behaviors:

  • If a union is marked lax, it is not an error to fail to resolve the union
  • If a leaf schema is marked lax, it is not an error if a value fails to assign to it

Lax mode does not mean that errors during normalization

Returns​

boolean | undefined


required​

Get Signature​

get required(): boolean

Defined in: src/compiled-schema.js:418

Returns true if the value defined by this schema is required to exist in the output to be valid.

Under the normal pathways, this is a shallow requirement:

  • Each schema checks its own input; if the required flag is set, the input must not be undefined.
  • If the input value is defined and the schema defines child properties, the input will be traversed and recursively checked against the child property schemas.
  • If the input value is undefined, child property schemas are NOT checked.

If the "deep" flag is set on the schema, this behavior changes:

  • If the input value is undefined on a schema with "deep" set, child properties ARE checked.

If a schema sets a default value, it will generally satisfy the required setting (unless set to a value function that returns undefined!)

Returns​

boolean


default​

Get Signature​

get default(): any

Defined in: src/compiled-schema.js:443

Returns the default value this schema provides if the input is undefined.

This is normally interpreted as a "shallow" default;

  • If the schema being actively processed has a default value and the input value is undefined, the default is used.
  • If the schema being actively processed defines child properties, and is passed an input value that does not contain a value for a specific child that defines a default, the child's default will be used.
  • If the schema being actively processed defines child properties, but is passed an undefined input value, the child property schemas will not be traversed, and thus any child defaults will not take effect.

This last behavior changes if the "deep" schema option is set:

  • If the schema being actively processed defines child properties is passed an undefined input value when the "deep" option is enabled, child property schemas will be traversed and any defaults will be used.

The default may also be set to a value function: async (value: any, target: any, location:SchemaLocation, options: Object): any that will be called during the normalization phase. This can be useful for late binding, remote lookups, side effects, or lazy evaluation of expensive values.

Returns​

any


deep​

Get Signature​

get deep(): boolean | undefined

Defined in: src/compiled-schema.js:458

Returns whether this schema should be deeply traversed even when the input is empty.

This is useful for triggering required/defaults settings. (Note that a schema with child properties that is marked required is deep by default, because that's almost always what is wanted/expected.)

Returns undefined if unset, signaling that the traversal context will decide.

Returns​

boolean | undefined


isReference​

Get Signature​

get isReference(): boolean

Defined in: src/compiled-schema.js:476

Return true if the schema always returns an inherited or referenced value.

Referenced properties never accept a direct assignment, and will always return the value corresponding to the first matching property name found higher in the schema.

Returns​

boolean


isImplicit​

Get Signature​

get isImplicit(): boolean

Defined in: src/compiled-schema.js:487

Returns true if this schema defines a value that can be assumed to always exist and be valid.

The implicit setting implies that values passed to this schema should not be visited or validated.

Returns​

boolean


allowIncremental​

Get Signature​

get allowIncremental(): boolean

Defined in: src/compiled-schema.js:498

Returns true if the container allows incremental assignment to children. Deprecated - use "opaque" as a more accurate signal of intent.

Deprecated​
Returns​

boolean


isOpaque​

Get Signature​

get isOpaque(): boolean

Defined in: src/compiled-schema.js:513

Returns true if the schema defines a value whose internals are hidden after transformation.

Opaque schemas will typically need a custom validator that understands the post-transform contract.

Transformation of opaque schemas is delayed until all known child assignments have been staged into a pending container. Once an opaque schema is transformed, it no longer accepts assignments. (This may cause sequencing issues with late-resolved conditional assignments!)

Returns​

boolean


hasConditions​

Get Signature​

get hasConditions(): boolean

Defined in: src/compiled-schema.js:588

Return true if this schema is conditional

Returns​

boolean


requiresFinalization​

Get Signature​

get requiresFinalization(): boolean

Defined in: src/compiled-schema.js:598

Return true if this schema requires finalization

Returns​

boolean

Methods​

toData()​

toData(): SchemaData | undefined

Defined in: src/compiled-schema.js:222

Extract this schema as a raw data object usable for cloning this schema.

Note that the data may include handler functions, so it cannot be assumed to be serializable to JSON!

Returns​

SchemaData | undefined


ensureAccepts()​

ensureAccepts(value): void

Defined in: src/compiled-schema.js:1153

Throw an exception if this schema seems able to handle a given input value.

Parameters​

ParameterTypeDescription
valueany-

Returns​

void


checkAccepts()​

checkAccepts(value): boolean

Defined in: src/compiled-schema.js:1182

Parameters​

ParameterTypeDescription
valueany-

Returns​

boolean


validate()​

validate(value, options?): Promise<any>

Defined in: src/compiled-schema.js:1233

Return a validated output if and only if the input fully matches the schema definition.

Note: depending on the processors used for validation, the input value may be mutated during validation! (todo - create an option that prevents this from happening?)

Parameters​

ParameterTypeDescription
valueanyinput value to validate
options?ValidateOptionsany tweaks to the validator behavior

Returns​

Promise<any>

  • validated value

process()​

process(input, target?, options?): Promise<any>

Defined in: src/compiled-schema.js:1307

Process an input value to an output value based on this schema.

Errors are thrown if:

  • the input value doesn't match the schema
  • a value processor throws an error
  • a value cannot be processed (value processors return undefined) after repeated attempts
  • a union cannot be resolved

If an output target is provided, it is assumed to already be valid. A few traversal options are supported; pass in a TraversalContext instance for full customization.

(This is an async wrapper around the internal _process executor function.)

Note: this method makes CompiledSchema look somewhat like a FunctionValueProcessor, but it has a slightly different signature.

Parameters​

ParameterTypeDescription
inputanythe value to process
target?anypreexisting output value to build upon, if any
options?ProcessOptionsoptions to customize the traversal

Returns​

Promise<any>

  • returns the output value

processAssignments()​

processAssignments(assignments, target?, options?): Promise<any>

Defined in: src/compiled-schema.js:1333

Process input path/value assignments into an output value based on the schema.

Paths are dotted references into the schema hierarchy. Assignment values are normalized, transformed, validated, and then used to build the output value.

If a value for the output target is provided, it is assumed to already be valid.

Errors are thrown if:

  • unexpected paths are provided that don't match the schema
  • a value is incompatible with the schema referenced by the path
  • a value processor throws an error
  • a value cannot be processed (value processors return undefined) after repeated attempts
  • a union cannot be resolved

(This an async convenience wrapper around the internal _process executor function.)

Parameters​

ParameterTypeDescription
assignmentsMap<string, any>path/value associations
target?anypreexisting output value to build upon, if any
options?ProcessAssignmentsOptionsoptions to customize the traversal

Returns​

Promise<any>

  • returns the output value

serialize()​

serialize(value, options?): Promise<any>

Defined in: src/compiled-schema.js:1352

Serialize the config data as if you were going to use the result for a config file.

Runs all serialization processors in a pipeline. By default, if any processor returns undefined or throws an error, serialization of that value returns undefined and will be omitted from the output. If you set the "strict" option, errors are re-thrown.

Serializers attempt to convert resolved values back to an input-friendly value, first via the "serialize" schema option, or alternatively by trusting that each value is either already compatible, or implements toJSON().

Parameters​

ParameterTypeDescription
valueany-
options?SerializeOptions-

Returns​

Promise<any>


findUnionKey()​

findUnionKey(unionSchema): string | undefined

Defined in: src/compiled-schema.js:1374

Given a reference to a union schema member, return the matching key, or undefined if it cannot be found.

Parameters​

ParameterTypeDescription
unionSchemaCompiledSchema-

Returns​

string | undefined


getUnionSchema()​

getUnionSchema(lookup): CompiledSchema | undefined

Defined in: src/compiled-schema.js:1392

Given a union key or schema, retrieve the matching union schema, or undefined if it cannot be found or is invalid

Parameters​

ParameterTypeDescription
lookupstring | CompiledSchema-

Returns​

CompiledSchema | undefined


find()​

find(path): CompiledSchema | undefined

Defined in: src/compiled-schema.js:1451

Find the schema at a given path, falling back to the wildcard schema if one exists.

The root schema may be found at '', the empty string. Array members are referenced with dotted integer indexes. Note that find() does not check union members; use SchemaLocation for finding schemas resolved during traversal.

Parameters​

ParameterTypeDescription
pathstring-

Returns​

CompiledSchema | undefined


toAssignments()​

toAssignments(object, prefix?): Map<string, any>

Defined in: src/compiled-schema.js:1477

toAssignments - attempt to convert input data to a map of assignments.

Parameters​

ParameterTypeDefault valueDescription
objectanyundefinedinput
prefixstring''prefix to add to any path generated

Returns​

Map<string, any>

  • output map of path-to-value associations

visitSchema()​

visitSchema(visitor, options?): boolean

Defined in: src/compiled-schema.js:1519

Invoke a provided visitor function on every schema node; if visitor returns false (explicitly), abort early.

Parameters​

ParameterTypeDescription
visitor(schema, path) => anyvisitor function
options?{ onlySerializable?: boolean; }-
options.onlySerializable?boolean-

Returns​

boolean

  • returns true if visitors all returned true, false if any exited early

getPropertyPaths()​

getPropertyPaths(): Set<string>

Defined in: src/compiled-schema.js:1562

Compute all possible schema paths (including union schema properties)

Returns​

Set<string>


getPropertySchema()​

getPropertySchema(propertyName): CompiledSchema | undefined

Defined in: src/compiled-schema.js:1579

Return a named property schema (possibly via wildcard)

Parameters​

ParameterTypeDescription
propertyNamestring-

Returns​

CompiledSchema | undefined


getTagged()​

getTagged(tag): CompiledSchema[]

Defined in: src/compiled-schema.js:1621

Return all child schemas that have a particular option tag

Parameters​

ParameterTypeDescription
tagstring-

Returns​

CompiledSchema[]

Deprecated​


getFirstTagged()​

getFirstTagged(tag): CompiledSchema | undefined

Defined in: src/compiled-schema.js:1638

Get the first child schema that has a particular option tag

Parameters​

ParameterTypeDescription
tagstring-

Returns​

CompiledSchema | undefined

Deprecated​


isValidPath()​

isValidPath(path): boolean

Defined in: src/compiled-schema.js:1653

Return true if the path is legal within the schema (including all union schemas)

Parameters​

ParameterTypeDescription
pathstring-

Returns​

boolean