UNPKG

@opra/common

Version:
65 lines (64 loc) 2.4 kB
import { omitUndefined } from '@jsopen/objects'; import { asMutable } from 'ts-gems'; import { DocumentElement } from '../common/document-element.js'; import { CLASS_NAME_PATTERN } from '../constants.js'; import { colorFgMagenta, colorFgYellow, colorReset, nodeInspectCustom, } from '../utils/inspect.util.js'; import { testScopeMatch } from '../utils/test-scope-match.js'; /** * DataType constructor */ export const DataType = function (owner, initArgs, // eslint-disable-next-line @typescript-eslint/no-unused-vars context) { if (!this) throw new TypeError('"this" should be passed to call class constructor'); if (initArgs?.name && !CLASS_NAME_PATTERN.test(initArgs.name)) { throw new TypeError(`"${initArgs.name}" is not a valid DataType name`); } DocumentElement.call(this, owner); const _this = asMutable(this); _this.kind = initArgs.kind; _this.scopePattern = initArgs.scopePattern ? Array.isArray(initArgs.scopePattern) ? initArgs.scopePattern : [initArgs.scopePattern] : undefined; _this.name = initArgs.name; _this.description = initArgs.description; _this.abstract = initArgs.abstract; _this.examples = initArgs.examples; }; /** * * @class DataType */ class DataTypeClass extends DocumentElement { get embedded() { return !this.name; } inScope(scope) { return testScopeMatch(scope, this.scopePattern); } toJSON(options) { /** Locate base model which is not available for given scope */ const outOfScope = this._locateBase(dt => !dt.inScope(options?.scope)); if (outOfScope) { const baseName = this.node.getDataTypeNameWithNs(outOfScope); throw new TypeError(`"${baseName}" model is not available for "${options?.scope || 'null'}" scope`); } return omitUndefined({ kind: this.kind, description: this.description, abstract: this.abstract, examples: this.examples, }); } toString() { return `[${Object.getPrototypeOf(this).constructor.name} ${this.name || '#Embedded'}]`; } [nodeInspectCustom]() { return (`[${colorFgYellow + Object.getPrototypeOf(this).constructor.name + colorReset}` + ` ${colorFgMagenta + this.name + colorReset}]`); } } DataType.prototype = DataTypeClass.prototype;