@bufbuild/protovalidate
Version:
Protocol Buffer Validation for ECMAScript
72 lines (71 loc) • 2.39 kB
JavaScript
"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.Cursor = void 0;
const reflect_1 = require("@bufbuild/protobuf/reflect");
const error_js_1 = require("./error.js");
/**
* Cursor maintains a field path and tracks violations.
*/
class Cursor {
static create(root, failFast) {
return new Cursor(root, failFast, [], (0, reflect_1.buildPath)(root));
}
constructor(root, failFast, violations, builder) {
this.root = root;
this.failFast = failFast;
this.violations = violations;
this.builder = builder;
}
get violated() {
return this.violations.length > 0;
}
violate(message, ruleId, rulePath, forMapKey = false) {
this.violations.push(new error_js_1.Violation(message, ruleId, this.builder.toPath(), rulePath, forMapKey));
if (this.failFast) {
this.throwIfViolated();
}
}
throwIfViolated() {
if (this.violated) {
throw new error_js_1.ValidationError(this.violations);
}
}
getPath() {
return this.builder.toPath();
}
add(path) {
return this.cloneWith(this.builder.clone().add(path));
}
field(field) {
return this.cloneWith(this.builder.clone().field(field));
}
oneof(oneof) {
return this.cloneWith(this.builder.clone().oneof(oneof));
}
extension(ext) {
return this.cloneWith(this.builder.clone().extension(ext));
}
list(index) {
return this.cloneWith(this.builder.clone().list(index));
}
mapKey(key) {
return this.cloneWith(this.builder.clone().map(key));
}
cloneWith(path) {
return new Cursor(this.root, this.failFast, this.violations, path);
}
}
exports.Cursor = Cursor;