UNPKG

@bufbuild/protovalidate

Version:

Protocol Buffer Validation for ECMAScript

86 lines (85 loc) 3.41 kB
"use strict"; // Copyright 2024-2025 Buf Technologies, Inc. // // 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 // // http://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.createValidator = createValidator; const protobuf_1 = require("@bufbuild/protobuf"); const reflect_1 = require("@bufbuild/protobuf/reflect"); const cursor_js_1 = require("./cursor.js"); const error_js_1 = require("./error.js"); const planner_js_1 = require("./planner.js"); const cel_js_1 = require("./cel.js"); const validate_pb_js_1 = require("./gen/buf/validate/validate_pb.js"); /** * Create a validator. */ function createValidator(opt) { const registry = opt?.registry ? (0, protobuf_1.createMutableRegistry)(opt.registry, validate_pb_js_1.file_buf_validate_validate) : (0, protobuf_1.createMutableRegistry)(validate_pb_js_1.file_buf_validate_validate); const failFast = opt?.failFast ?? false; const celMan = new cel_js_1.CelManager(registry, opt?.regexMatch); const planner = new planner_js_1.Planner(celMan, opt?.legacyRequired ?? false); return { validate(schema, message) { try { validateUnsafe(registry, celMan, planner, schema, message, failFast); } catch (e) { if (e instanceof error_js_1.ValidationError) { return { kind: "invalid", message, error: e, violations: e.violations, }; } if (e instanceof error_js_1.CompilationError || e instanceof error_js_1.RuntimeError) { return { kind: "error", message, error: e, }; } return { kind: "error", message, error: new error_js_1.RuntimeError("unexpected error: " + e, { cause: e }), }; } return { kind: "valid", message: message, }; }, }; } function validateUnsafe(registry, celMan, planner, schema, message, failFast) { const messageTypeName = message.$typeName; if (!(0, protobuf_1.isMessage)(message, schema)) { throw new error_js_1.RuntimeError(`Cannot validate message ${messageTypeName} with schema ${schema.typeName}`); } if (!registry.get(schema.typeName)) { registry.add(schema); for (const type of (0, reflect_1.usedTypes)(schema)) { registry.add(type); } } const plan = planner.plan(schema); const msg = (0, reflect_1.reflect)(schema, message); const cursor = cursor_js_1.Cursor.create(schema, failFast); celMan.updateCelNow(); plan.eval(msg, cursor); cursor.throwIfViolated(); }