UNPKG

@litert/typeguard

Version:

An easy and powerful data validation code generator by JavaScript.

84 lines (83 loc) 2.99 kB
"use strict"; /** * Copyright 2023 Angus Fenying <fenying@litert.org> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.createInlineCompiler = void 0; const Compiler_1 = require("./Compiler"); const JavaScript_1 = require("./langs/JavaScript"); const I = require("./Internal"); class InlineCompiler { constructor() { this._defTypes = {}; this._missingTypes = {}; const lang = (0, JavaScript_1.createJavaScriptLanguageBuilder)(); this._compiler = (0, Compiler_1.createCompiler)(lang); } compile(options) { const result = this._compiler.compile(options); this._prepareDefinedTypes(result.referredTypes, options.stopOnEntry); return this._wrapCheckerCode(result, options.stopOnEntry); } _prepareDefinedTypes(types, stopOnEntry) { for (const x of types) { if (this._defTypes[x]) { continue; } const info = this._compiler.getPredefinedType(x); if (!info) { this._missingTypes[x] = true; continue; } this._defTypes[x] = this._wrapCheckerCode(info, stopOnEntry); this._prepareDefinedTypes(info.referredTypes); delete this._missingTypes[x]; } } addPredefinedType(name, checker) { I.validateTypeName(name); this._defTypes[name] = checker; return this; } detectUndefinedTypes() { return Object.keys(this._missingTypes); } hasPredefinedType(name) { return !!this._defTypes[name]; } getPredefinedType(name) { if (!this._defTypes[name]) { throw new Error(`Pre-defined type "${name}" doesn't exist.`); } return this._defTypes[name]; } _wrapCheckerCode(info, stopOnEntry = false) { const soe = stopOnEntry ? 'debugger;' : ''; return (new Function(info.typeSlotName, `return function(${info.arguments .map((a) => a.initial ? `${a.name} = ${a.initial}` : a.name) .join(',')}) { ${soe} return ${info.source}; };`))(this._defTypes); } } /** * Create a compiler object that compiles the rule into JavaScript lambda code. */ function createInlineCompiler() { return new InlineCompiler(); } exports.createInlineCompiler = createInlineCompiler; //# sourceMappingURL=InlineCompiler.js.map