@bufbuild/cel
Version:
A CEL evaluator for ECMAScript
106 lines (105 loc) • 3.44 kB
JavaScript
;
// 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.accessByIndex = accessByIndex;
exports.accessByName = accessByName;
exports.isSet = isSet;
const reflect_1 = require("@bufbuild/protobuf/reflect");
const wkt_1 = require("@bufbuild/protobuf/wkt");
const list_js_1 = require("./list.js");
const map_js_1 = require("./map.js");
const proto_js_1 = require("./proto.js");
const value_js_1 = require("./value.js");
function accessByIndex(obj, index) {
if (typeof obj !== "object" || obj === null) {
return undefined;
}
if ((0, map_js_1.isCelMap)(obj)) {
return obj.get(index);
}
if ((0, list_js_1.isCelList)(obj)) {
return obj.get(Number(index));
}
return undefined;
}
/**
* Access fields on Maps and Message by name.
*/
function accessByName(obj, name) {
if (typeof obj !== "object" || obj === null) {
return undefined;
}
if ((0, map_js_1.isCelMap)(obj)) {
return obj.get(name);
}
// Message
obj = (0, value_js_1.unwrapAny)(obj);
if (!(0, reflect_1.isReflectMessage)(obj)) {
return undefined;
}
const field = obj.desc.fields.find((f) => f.name === name);
if (!field) {
return undefined;
}
switch (field.fieldKind) {
case "enum":
return BigInt(obj.get(field));
case "list":
return (0, list_js_1.celList)(obj.get(field));
case "map":
return (0, map_js_1.celMap)(obj.get(field));
case "scalar":
return (0, proto_js_1.celFromScalar)(field.scalar, obj.get(field));
case "message":
if (obj.isSet(field)) {
return (0, value_js_1.reflectMsgToCel)(obj.get(field));
}
if ((0, wkt_1.isWrapperDesc)(field.message)) {
return null;
}
switch (field.message.typeName) {
case wkt_1.StructSchema.typeName:
return map_js_1.EMPTY_MAP;
case wkt_1.ListValueSchema.typeName:
return list_js_1.EMPTY_LIST;
case wkt_1.ValueSchema.typeName:
return null;
}
return (0, reflect_1.reflect)(field.message);
}
}
/**
* Check to see if a field is set.
*
* It returns undefined if the field name is not valid.
*/
function isSet(obj, name) {
if (typeof obj !== "object" || obj === null) {
return false;
}
if ((0, map_js_1.isCelMap)(obj)) {
return obj.has(name);
}
// Message
obj = (0, value_js_1.unwrapAny)(obj);
if ((0, reflect_1.isReflectMessage)(obj)) {
const field = obj.desc.fields.find((f) => f.name === name);
if (!field) {
return undefined;
}
return obj.isSet(field);
}
return false;
}