rearrage_stuff

This commit is contained in:
Kim Ravn Hansen
2025-09-16 11:26:40 +02:00
parent 40e8c5e0ab
commit 3f11ebe6dc
4937 changed files with 1146031 additions and 134 deletions

View File

@@ -0,0 +1,9 @@
import type { DescField, DescOneof } from "../descriptors.js";
declare const errorNames: string[];
export declare class FieldError extends Error {
readonly name: (typeof errorNames)[number];
constructor(fieldOrOneof: DescField | DescOneof, message: string, name?: (typeof errorNames)[number]);
readonly field: () => DescField | DescOneof;
}
export declare function isFieldError(arg: unknown): arg is FieldError;
export {};

View File

@@ -0,0 +1,36 @@
"use strict";
// Copyright 2021-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.FieldError = void 0;
exports.isFieldError = isFieldError;
const errorNames = [
"FieldValueInvalidError",
"FieldListRangeError",
"ForeignFieldError",
];
class FieldError extends Error {
constructor(fieldOrOneof, message, name = "FieldValueInvalidError") {
super(message);
this.name = name;
this.field = () => fieldOrOneof;
}
}
exports.FieldError = FieldError;
function isFieldError(arg) {
return (arg instanceof Error &&
errorNames.includes(arg.name) &&
"field" in arg &&
typeof arg.field == "function");
}

View File

@@ -0,0 +1,20 @@
import type { Message } from "../types.js";
import type { ScalarValue } from "./scalar.js";
import type { ReflectList, ReflectMap, ReflectMessage } from "./reflect-types.js";
import type { DescField, DescMessage } from "../descriptors.js";
export declare function isObject(arg: unknown): arg is Record<string, unknown>;
export declare function isOneofADT(arg: unknown): arg is OneofADT;
export type OneofADT = {
case: undefined;
value?: undefined;
} | {
case: string;
value: Message | ScalarValue;
};
export declare function isReflectList(arg: unknown, field?: DescField & {
fieldKind: "list";
}): arg is ReflectList;
export declare function isReflectMap(arg: unknown, field?: DescField & {
fieldKind: "map";
}): arg is ReflectMap;
export declare function isReflectMessage(arg: unknown, messageDesc?: DescMessage): arg is ReflectMessage;

View File

@@ -0,0 +1,78 @@
"use strict";
// Copyright 2021-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.isObject = isObject;
exports.isOneofADT = isOneofADT;
exports.isReflectList = isReflectList;
exports.isReflectMap = isReflectMap;
exports.isReflectMessage = isReflectMessage;
const unsafe_js_1 = require("./unsafe.js");
function isObject(arg) {
return arg !== null && typeof arg == "object" && !Array.isArray(arg);
}
function isOneofADT(arg) {
return (arg !== null &&
typeof arg == "object" &&
"case" in arg &&
((typeof arg.case == "string" && "value" in arg && arg.value != null) ||
(arg.case === undefined &&
(!("value" in arg) || arg.value === undefined))));
}
function isReflectList(arg, field) {
var _a, _b, _c, _d;
if (isObject(arg) &&
unsafe_js_1.unsafeLocal in arg &&
"add" in arg &&
"field" in arg &&
typeof arg.field == "function") {
if (field !== undefined) {
const a = field;
const b = arg.field();
return (a.listKind == b.listKind &&
a.scalar === b.scalar &&
((_a = a.message) === null || _a === void 0 ? void 0 : _a.typeName) === ((_b = b.message) === null || _b === void 0 ? void 0 : _b.typeName) &&
((_c = a.enum) === null || _c === void 0 ? void 0 : _c.typeName) === ((_d = b.enum) === null || _d === void 0 ? void 0 : _d.typeName));
}
return true;
}
return false;
}
function isReflectMap(arg, field) {
var _a, _b, _c, _d;
if (isObject(arg) &&
unsafe_js_1.unsafeLocal in arg &&
"has" in arg &&
"field" in arg &&
typeof arg.field == "function") {
if (field !== undefined) {
const a = field, b = arg.field();
return (a.mapKey === b.mapKey &&
a.mapKind == b.mapKind &&
a.scalar === b.scalar &&
((_a = a.message) === null || _a === void 0 ? void 0 : _a.typeName) === ((_b = b.message) === null || _b === void 0 ? void 0 : _b.typeName) &&
((_c = a.enum) === null || _c === void 0 ? void 0 : _c.typeName) === ((_d = b.enum) === null || _d === void 0 ? void 0 : _d.typeName));
}
return true;
}
return false;
}
function isReflectMessage(arg, messageDesc) {
return (isObject(arg) &&
unsafe_js_1.unsafeLocal in arg &&
"desc" in arg &&
isObject(arg.desc) &&
arg.desc.kind === "message" &&
(messageDesc === undefined || arg.desc.typeName == messageDesc.typeName));
}

View File

@@ -0,0 +1,8 @@
export * from "./error.js";
export * from "./names.js";
export * from "./nested-types.js";
export * from "./reflect.js";
export * from "./reflect-types.js";
export * from "./scalar.js";
export * from "./path.js";
export { isReflectList, isReflectMap, isReflectMessage } from "./guard.js";

View File

@@ -0,0 +1,41 @@
"use strict";
// Copyright 2021-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.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.isReflectMessage = exports.isReflectMap = exports.isReflectList = void 0;
__exportStar(require("./error.js"), exports);
__exportStar(require("./names.js"), exports);
__exportStar(require("./nested-types.js"), exports);
__exportStar(require("./reflect.js"), exports);
__exportStar(require("./reflect-types.js"), exports);
__exportStar(require("./scalar.js"), exports);
__exportStar(require("./path.js"), exports);
var guard_js_1 = require("./guard.js");
Object.defineProperty(exports, "isReflectList", { enumerable: true, get: function () { return guard_js_1.isReflectList; } });
Object.defineProperty(exports, "isReflectMap", { enumerable: true, get: function () { return guard_js_1.isReflectMap; } });
Object.defineProperty(exports, "isReflectMessage", { enumerable: true, get: function () { return guard_js_1.isReflectMessage; } });

View File

@@ -0,0 +1,19 @@
import type { AnyDesc } from "../descriptors.js";
/**
* Return a fully-qualified name for a Protobuf descriptor.
* For a file descriptor, return the original file path.
*
* See https://protobuf.com/docs/language-spec#fully-qualified-names
*/
export declare function qualifiedName(desc: AnyDesc): string;
/**
* Converts snake_case to protoCamelCase according to the convention
* used by protoc to convert a field name to a JSON name.
*/
export declare function protoCamelCase(snakeCase: string): string;
/**
* Escapes names that are reserved for ECMAScript built-in object properties.
*
* Also see safeIdentifier() from @bufbuild/protoplugin.
*/
export declare function safeObjectProperty(name: string): string;

View File

@@ -0,0 +1,101 @@
"use strict";
// Copyright 2021-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.qualifiedName = qualifiedName;
exports.protoCamelCase = protoCamelCase;
exports.safeObjectProperty = safeObjectProperty;
/**
* Return a fully-qualified name for a Protobuf descriptor.
* For a file descriptor, return the original file path.
*
* See https://protobuf.com/docs/language-spec#fully-qualified-names
*/
function qualifiedName(desc) {
switch (desc.kind) {
case "field":
case "oneof":
case "rpc":
return desc.parent.typeName + "." + desc.name;
case "enum_value": {
const p = desc.parent.parent
? desc.parent.parent.typeName
: desc.parent.file.proto.package;
return p + (p.length > 0 ? "." : "") + desc.name;
}
case "service":
case "message":
case "enum":
case "extension":
return desc.typeName;
case "file":
return desc.proto.name;
}
}
/**
* Converts snake_case to protoCamelCase according to the convention
* used by protoc to convert a field name to a JSON name.
*/
function protoCamelCase(snakeCase) {
let capNext = false;
const b = [];
for (let i = 0; i < snakeCase.length; i++) {
let c = snakeCase.charAt(i);
switch (c) {
case "_":
capNext = true;
break;
case "0":
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
b.push(c);
capNext = false;
break;
default:
if (capNext) {
capNext = false;
c = c.toUpperCase();
}
b.push(c);
break;
}
}
return b.join("");
}
/**
* Names that cannot be used for object properties because they are reserved
* by built-in JavaScript properties.
*/
const reservedObjectProperties = new Set([
// names reserved by JavaScript
"constructor",
"toString",
"toJSON",
"valueOf",
]);
/**
* Escapes names that are reserved for ECMAScript built-in object properties.
*
* Also see safeIdentifier() from @bufbuild/protoplugin.
*/
function safeObjectProperty(name) {
return reservedObjectProperties.has(name) ? name + "$" : name;
}

View File

@@ -0,0 +1,35 @@
import type { AnyDesc, DescEnum, DescExtension, DescFile, DescMessage, DescService } from "../descriptors.js";
/**
* Iterate over all types - enumerations, extensions, services, messages -
* and enumerations, extensions and messages nested in messages.
*/
export declare function nestedTypes(desc: DescFile | DescMessage): Iterable<DescMessage | DescEnum | DescExtension | DescService>;
/**
* Iterate over types referenced by fields of the given message.
*
* For example:
*
* ```proto
* syntax="proto3";
*
* message Example {
* Msg singular = 1;
* repeated Level list = 2;
* }
*
* message Msg {}
*
* enum Level {
* LEVEL_UNSPECIFIED = 0;
* }
* ```
*
* The message Example references the message Msg, and the enum Level.
*/
export declare function usedTypes(descMessage: DescMessage): Iterable<DescMessage | DescEnum>;
/**
* Returns the ancestors of a given Protobuf element, up to the file.
*/
export declare function parentTypes(desc: AnyDesc): Parent[];
type Parent = DescFile | DescEnum | DescMessage | DescService;
export {};

View File

@@ -0,0 +1,110 @@
"use strict";
// Copyright 2021-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.nestedTypes = nestedTypes;
exports.usedTypes = usedTypes;
exports.parentTypes = parentTypes;
/**
* Iterate over all types - enumerations, extensions, services, messages -
* and enumerations, extensions and messages nested in messages.
*/
function* nestedTypes(desc) {
switch (desc.kind) {
case "file":
for (const message of desc.messages) {
yield message;
yield* nestedTypes(message);
}
yield* desc.enums;
yield* desc.services;
yield* desc.extensions;
break;
case "message":
for (const message of desc.nestedMessages) {
yield message;
yield* nestedTypes(message);
}
yield* desc.nestedEnums;
yield* desc.nestedExtensions;
break;
}
}
/**
* Iterate over types referenced by fields of the given message.
*
* For example:
*
* ```proto
* syntax="proto3";
*
* message Example {
* Msg singular = 1;
* repeated Level list = 2;
* }
*
* message Msg {}
*
* enum Level {
* LEVEL_UNSPECIFIED = 0;
* }
* ```
*
* The message Example references the message Msg, and the enum Level.
*/
function usedTypes(descMessage) {
return usedTypesInternal(descMessage, new Set());
}
function* usedTypesInternal(descMessage, seen) {
var _a, _b;
for (const field of descMessage.fields) {
const ref = (_b = (_a = field.enum) !== null && _a !== void 0 ? _a : field.message) !== null && _b !== void 0 ? _b : undefined;
if (!ref || seen.has(ref.typeName)) {
continue;
}
seen.add(ref.typeName);
yield ref;
if (ref.kind == "message") {
yield* usedTypesInternal(ref, seen);
}
}
}
/**
* Returns the ancestors of a given Protobuf element, up to the file.
*/
function parentTypes(desc) {
const parents = [];
while (desc.kind !== "file") {
const p = parent(desc);
desc = p;
parents.push(p);
}
return parents;
}
function parent(desc) {
var _a;
switch (desc.kind) {
case "enum_value":
case "field":
case "oneof":
case "rpc":
return desc.parent;
case "service":
return desc.file;
case "extension":
case "enum":
case "message":
return (_a = desc.parent) !== null && _a !== void 0 ? _a : desc.file;
}
}

View File

@@ -0,0 +1,107 @@
import { type DescExtension, type DescField, type DescMessage, type DescOneof } from "../descriptors.js";
import type { Registry } from "../registry.js";
/**
* A path to a (nested) member of a Protobuf message, such as a field, oneof,
* extension, list element, or map entry.
*
* Note that we may add additional types to this union in the future to support
* more use cases.
*/
export type Path = (DescField | DescExtension | DescOneof | {
kind: "list_sub";
index: number;
} | {
kind: "map_sub";
key: string | number | bigint | boolean;
})[];
/**
* Builds a Path.
*/
export type PathBuilder = {
/**
* The root message of the path.
*/
readonly schema: DescMessage;
/**
* Add field access.
*
* Throws an InvalidPathError if the field cannot be added to the path.
*/
field(field: DescField): PathBuilder;
/**
* Access a oneof.
*
* Throws an InvalidPathError if the oneof cannot be added to the path.
*
*/
oneof(oneof: DescOneof): PathBuilder;
/**
* Access an extension.
*
* Throws an InvalidPathError if the extension cannot be added to the path.
*/
extension(extension: DescExtension): PathBuilder;
/**
* Access a list field by index.
*
* Throws an InvalidPathError if the list access cannot be added to the path.
*/
list(index: number): PathBuilder;
/**
* Access a map field by key.
*
* Throws an InvalidPathError if the map access cannot be added to the path.
*/
map(key: string | number | bigint | boolean): PathBuilder;
/**
* Append a path.
*
* Throws an InvalidPathError if the path cannot be added.
*/
add(path: Path | PathBuilder): PathBuilder;
/**
* Return the path.
*/
toPath(): Path;
/**
* Create a copy of this builder.
*/
clone(): PathBuilder;
/**
* Get the current container - a list, map, or message.
*/
getLeft(): DescMessage | (DescField & {
fieldKind: "list";
}) | (DescField & {
fieldKind: "map";
}) | undefined;
};
/**
* Create a PathBuilder.
*/
export declare function buildPath(schema: DescMessage): PathBuilder;
/**
* Parse a Path from a string.
*
* Throws an InvalidPathError if the path is invalid.
*
* Note that a Registry must be provided via the options argument to parse
* paths that refer to an extension.
*/
export declare function parsePath(schema: DescMessage, path: string, options?: {
registry?: Registry;
}): Path;
/**
* Stringify a path.
*/
export declare function pathToString(path: Path): string;
/**
* InvalidPathError is thrown for invalid Paths, for example during parsing from
* a string, or when a new Path is built.
*/
export declare class InvalidPathError extends Error {
name: string;
readonly schema: DescMessage;
readonly path: Path | string;
constructor(schema: DescMessage, message: string, path: string | Path);
}

View File

@@ -0,0 +1,376 @@
"use strict";
// Copyright 2021-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.InvalidPathError = void 0;
exports.buildPath = buildPath;
exports.parsePath = parsePath;
exports.pathToString = pathToString;
const descriptors_js_1 = require("../descriptors.js");
/**
* Create a PathBuilder.
*/
function buildPath(schema) {
return new PathBuilderImpl(schema, schema, []);
}
/**
* Parse a Path from a string.
*
* Throws an InvalidPathError if the path is invalid.
*
* Note that a Registry must be provided via the options argument to parse
* paths that refer to an extension.
*/
function parsePath(schema, path, options) {
var _a, _b;
const builder = new PathBuilderImpl(schema, schema, []);
const err = (message, i) => new InvalidPathError(schema, message + " at column " + (i + 1), path);
for (let i = 0; i < path.length;) {
const token = nextToken(i, path);
const left = builder.getLeft();
let right = undefined;
if ("field" in token) {
right =
(left === null || left === void 0 ? void 0 : left.kind) != "message"
? undefined
: ((_a = left.fields.find((field) => field.name === token.field)) !== null && _a !== void 0 ? _a : left.oneofs.find((oneof) => oneof.name === token.field));
if (!right) {
throw err(`Unknown field "${token.field}"`, i);
}
}
else if ("ext" in token) {
right = (_b = options === null || options === void 0 ? void 0 : options.registry) === null || _b === void 0 ? void 0 : _b.getExtension(token.ext);
if (!right) {
throw err(`Unknown extension "${token.ext}"`, i);
}
}
else if ("val" in token) {
// list or map
right =
(left === null || left === void 0 ? void 0 : left.kind) == "field" &&
left.fieldKind == "list" &&
typeof token.val == "bigint"
? { kind: "list_sub", index: Number(token.val) }
: { kind: "map_sub", key: token.val };
}
else if ("err" in token) {
throw err(token.err, token.i);
}
if (right) {
try {
builder.add([right]);
}
catch (e) {
throw err(e instanceof InvalidPathError ? e.message : String(e), i);
}
}
i = token.i;
}
return builder.toPath();
}
/**
* Stringify a path.
*/
function pathToString(path) {
const str = [];
for (const ele of path) {
switch (ele.kind) {
case "field":
case "oneof":
if (str.length > 0) {
str.push(".");
}
str.push(ele.name);
break;
case "extension":
str.push("[", ele.typeName, "]");
break;
case "list_sub":
str.push("[", ele.index, "]");
break;
case "map_sub":
if (typeof ele.key == "string") {
str.push('["', ele.key
.split("\\")
.join("\\\\")
.split('"')
.join('\\"')
.split("\r")
.join("\\r")
.split("\n")
.join("\\n"), '"]');
}
else {
str.push("[", ele.key, "]");
}
break;
}
}
return str.join("");
}
/**
* InvalidPathError is thrown for invalid Paths, for example during parsing from
* a string, or when a new Path is built.
*/
class InvalidPathError extends Error {
constructor(schema, message, path) {
super(message);
this.name = "InvalidPathError";
this.schema = schema;
this.path = path;
// see https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#example
Object.setPrototypeOf(this, new.target.prototype);
}
}
exports.InvalidPathError = InvalidPathError;
class PathBuilderImpl {
constructor(schema, left, path) {
this.schema = schema;
this.left = left;
this.path = path;
}
getLeft() {
return this.left;
}
field(field) {
return this.push(field);
}
oneof(oneof) {
return this.push(oneof);
}
extension(extension) {
return this.push(extension);
}
list(index) {
return this.push({ kind: "list_sub", index });
}
map(key) {
return this.push({ kind: "map_sub", key });
}
add(pathOrBuilder) {
const path = Array.isArray(pathOrBuilder)
? pathOrBuilder
: pathOrBuilder.toPath();
const l = this.path.length;
try {
for (const ele of path) {
this.push(ele);
}
}
catch (e) {
// undo pushes
this.path.splice(l);
throw e;
}
return this;
}
toPath() {
return this.path.concat();
}
clone() {
return new PathBuilderImpl(this.schema, this.left, this.path.concat());
}
push(ele) {
switch (ele.kind) {
case "field":
if (!this.left ||
this.left.kind != "message" ||
this.left.typeName != ele.parent.typeName) {
throw this.err("field access");
}
this.path.push(ele);
this.left =
ele.fieldKind == "message"
? ele.message
: ele.fieldKind == "list" || ele.fieldKind == "map"
? ele
: undefined;
return this;
case "oneof":
if (!this.left ||
this.left.kind != "message" ||
this.left.typeName != ele.parent.typeName) {
throw this.err("oneof access");
}
this.path.push(ele);
this.left = undefined;
return this;
case "extension":
if (!this.left ||
this.left.kind != "message" ||
this.left.typeName != ele.extendee.typeName) {
throw this.err("extension access");
}
this.path.push(ele);
this.left = ele.fieldKind == "message" ? ele.message : undefined;
return this;
case "list_sub":
if (!this.left ||
this.left.kind != "field" ||
this.left.fieldKind != "list") {
throw this.err("list access");
}
if (ele.index < 0 || !Number.isInteger(ele.index)) {
throw this.err("list index");
}
this.path.push(ele);
this.left =
this.left.listKind == "message" ? this.left.message : undefined;
return this;
case "map_sub":
if (!this.left ||
this.left.kind != "field" ||
this.left.fieldKind != "map") {
throw this.err("map access");
}
if (!checkKeyType(ele.key, this.left.mapKey)) {
throw this.err("map key");
}
this.path.push(ele);
this.left =
this.left.mapKind == "message" ? this.left.message : undefined;
return this;
}
}
err(what) {
return new InvalidPathError(this.schema, "Invalid " + what, this.path);
}
}
function checkKeyType(key, type) {
switch (type) {
case descriptors_js_1.ScalarType.STRING:
return typeof key == "string";
case descriptors_js_1.ScalarType.INT32:
case descriptors_js_1.ScalarType.UINT32:
case descriptors_js_1.ScalarType.SINT32:
case descriptors_js_1.ScalarType.SFIXED32:
case descriptors_js_1.ScalarType.FIXED32:
return typeof key == "number";
case descriptors_js_1.ScalarType.UINT64:
case descriptors_js_1.ScalarType.INT64:
case descriptors_js_1.ScalarType.FIXED64:
case descriptors_js_1.ScalarType.SFIXED64:
case descriptors_js_1.ScalarType.SINT64:
return typeof key == "bigint";
case descriptors_js_1.ScalarType.BOOL:
return typeof key == "boolean";
}
}
function nextToken(i, path) {
const re_extension = /^[A-Za-z_][A-Za-z_0-9]*(?:\.[A-Za-z_][A-Za-z_0-9]*)*$/;
const re_field = /^[A-Za-z_][A-Za-z_0-9]*$/;
if (path[i] == "[") {
i++;
while (path[i] == " ") {
// skip leading whitespace
i++;
}
if (i >= path.length) {
return { err: "Premature end", i: path.length - 1 };
}
let token;
if (path[i] == `"`) {
// string literal
i++;
let val = "";
for (;;) {
if (path[i] == `"`) {
// end of string literal
i++;
break;
}
if (path[i] == "\\") {
switch (path[i + 1]) {
case `"`:
case "\\":
val += path[i + 1];
break;
case "r":
val += "\r";
break;
case "n":
val += "\n";
break;
default:
return { err: "Invalid escape sequence", i };
}
i++;
}
else {
val += path[i];
}
if (i >= path.length) {
return { err: "Premature end of string", i: path.length - 1 };
}
i++;
}
token = { val };
}
else if (path[i].match(/\d/)) {
// integer literal
const start = i;
while (i < path.length && /\d/.test(path[i])) {
i++;
}
token = { val: BigInt(path.substring(start, i)) };
}
else if (path[i] == "]") {
return { err: "Premature ]", i };
}
else {
// extension identifier or bool literal
const start = i;
while (i < path.length && path[i] != " " && path[i] != "]") {
i++;
}
const name = path.substring(start, i);
if (name === "true") {
token = { val: true };
}
else if (name === "false") {
token = { val: false };
}
else if (re_extension.test(name)) {
token = { ext: name };
}
else {
return { err: "Invalid ident", i: start };
}
}
while (path[i] == " ") {
// skip trailing whitespace
i++;
}
if (path[i] != "]") {
return { err: "Missing ]", i };
}
i++;
return Object.assign(Object.assign({}, token), { i });
}
// field identifier
if (i > 0) {
if (path[i] != ".") {
return { err: `Expected "."`, i };
}
i++;
}
const start = i;
while (i < path.length && path[i] != "." && path[i] != "[") {
i++;
}
const field = path.substring(start, i);
return re_field.test(field)
? { field, i }
: { err: "Invalid ident", i: start };
}

View File

@@ -0,0 +1,19 @@
import { type DescField } from "../descriptors.js";
import { FieldError } from "./error.js";
/**
* Check whether the given field value is valid for the reflect API.
*/
export declare function checkField(field: DescField, value: unknown): FieldError | undefined;
/**
* Check whether the given list item is valid for the reflect API.
*/
export declare function checkListItem(field: DescField & {
fieldKind: "list";
}, index: number, value: unknown): FieldError | undefined;
/**
* Check whether the given map key and value are valid for the reflect API.
*/
export declare function checkMapEntry(field: DescField & {
fieldKind: "map";
}, key: unknown, value: unknown): FieldError | undefined;
export declare function formatVal(val: unknown): string;

View File

@@ -0,0 +1,266 @@
"use strict";
// Copyright 2021-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.checkField = checkField;
exports.checkListItem = checkListItem;
exports.checkMapEntry = checkMapEntry;
exports.formatVal = formatVal;
const descriptors_js_1 = require("../descriptors.js");
const is_message_js_1 = require("../is-message.js");
const error_js_1 = require("./error.js");
const guard_js_1 = require("./guard.js");
const binary_encoding_js_1 = require("../wire/binary-encoding.js");
const text_encoding_js_1 = require("../wire/text-encoding.js");
const proto_int64_js_1 = require("../proto-int64.js");
/**
* Check whether the given field value is valid for the reflect API.
*/
function checkField(field, value) {
const check = field.fieldKind == "list"
? (0, guard_js_1.isReflectList)(value, field)
: field.fieldKind == "map"
? (0, guard_js_1.isReflectMap)(value, field)
: checkSingular(field, value);
if (check === true) {
return undefined;
}
let reason;
switch (field.fieldKind) {
case "list":
reason = `expected ${formatReflectList(field)}, got ${formatVal(value)}`;
break;
case "map":
reason = `expected ${formatReflectMap(field)}, got ${formatVal(value)}`;
break;
default: {
reason = reasonSingular(field, value, check);
}
}
return new error_js_1.FieldError(field, reason);
}
/**
* Check whether the given list item is valid for the reflect API.
*/
function checkListItem(field, index, value) {
const check = checkSingular(field, value);
if (check !== true) {
return new error_js_1.FieldError(field, `list item #${index + 1}: ${reasonSingular(field, value, check)}`);
}
return undefined;
}
/**
* Check whether the given map key and value are valid for the reflect API.
*/
function checkMapEntry(field, key, value) {
const checkKey = checkScalarValue(key, field.mapKey);
if (checkKey !== true) {
return new error_js_1.FieldError(field, `invalid map key: ${reasonSingular({ scalar: field.mapKey }, key, checkKey)}`);
}
const checkVal = checkSingular(field, value);
if (checkVal !== true) {
return new error_js_1.FieldError(field, `map entry ${formatVal(key)}: ${reasonSingular(field, value, checkVal)}`);
}
return undefined;
}
function checkSingular(field, value) {
if (field.scalar !== undefined) {
return checkScalarValue(value, field.scalar);
}
if (field.enum !== undefined) {
if (field.enum.open) {
return Number.isInteger(value);
}
return field.enum.values.some((v) => v.number === value);
}
return (0, guard_js_1.isReflectMessage)(value, field.message);
}
function checkScalarValue(value, scalar) {
switch (scalar) {
case descriptors_js_1.ScalarType.DOUBLE:
return typeof value == "number";
case descriptors_js_1.ScalarType.FLOAT:
if (typeof value != "number") {
return false;
}
if (Number.isNaN(value) || !Number.isFinite(value)) {
return true;
}
if (value > binary_encoding_js_1.FLOAT32_MAX || value < binary_encoding_js_1.FLOAT32_MIN) {
return `${value.toFixed()} out of range`;
}
return true;
case descriptors_js_1.ScalarType.INT32:
case descriptors_js_1.ScalarType.SFIXED32:
case descriptors_js_1.ScalarType.SINT32:
// signed
if (typeof value !== "number" || !Number.isInteger(value)) {
return false;
}
if (value > binary_encoding_js_1.INT32_MAX || value < binary_encoding_js_1.INT32_MIN) {
return `${value.toFixed()} out of range`;
}
return true;
case descriptors_js_1.ScalarType.FIXED32:
case descriptors_js_1.ScalarType.UINT32:
// unsigned
if (typeof value !== "number" || !Number.isInteger(value)) {
return false;
}
if (value > binary_encoding_js_1.UINT32_MAX || value < 0) {
return `${value.toFixed()} out of range`;
}
return true;
case descriptors_js_1.ScalarType.BOOL:
return typeof value == "boolean";
case descriptors_js_1.ScalarType.STRING:
if (typeof value != "string") {
return false;
}
return (0, text_encoding_js_1.getTextEncoding)().checkUtf8(value) || "invalid UTF8";
case descriptors_js_1.ScalarType.BYTES:
return value instanceof Uint8Array;
case descriptors_js_1.ScalarType.INT64:
case descriptors_js_1.ScalarType.SFIXED64:
case descriptors_js_1.ScalarType.SINT64:
// signed
if (typeof value == "bigint" ||
typeof value == "number" ||
(typeof value == "string" && value.length > 0)) {
try {
proto_int64_js_1.protoInt64.parse(value);
return true;
}
catch (_) {
return `${value} out of range`;
}
}
return false;
case descriptors_js_1.ScalarType.FIXED64:
case descriptors_js_1.ScalarType.UINT64:
// unsigned
if (typeof value == "bigint" ||
typeof value == "number" ||
(typeof value == "string" && value.length > 0)) {
try {
proto_int64_js_1.protoInt64.uParse(value);
return true;
}
catch (_) {
return `${value} out of range`;
}
}
return false;
}
}
function reasonSingular(field, val, details) {
details =
typeof details == "string" ? `: ${details}` : `, got ${formatVal(val)}`;
if (field.scalar !== undefined) {
return `expected ${scalarTypeDescription(field.scalar)}` + details;
}
if (field.enum !== undefined) {
return `expected ${field.enum.toString()}` + details;
}
return `expected ${formatReflectMessage(field.message)}` + details;
}
function formatVal(val) {
switch (typeof val) {
case "object":
if (val === null) {
return "null";
}
if (val instanceof Uint8Array) {
return `Uint8Array(${val.length})`;
}
if (Array.isArray(val)) {
return `Array(${val.length})`;
}
if ((0, guard_js_1.isReflectList)(val)) {
return formatReflectList(val.field());
}
if ((0, guard_js_1.isReflectMap)(val)) {
return formatReflectMap(val.field());
}
if ((0, guard_js_1.isReflectMessage)(val)) {
return formatReflectMessage(val.desc);
}
if ((0, is_message_js_1.isMessage)(val)) {
return `message ${val.$typeName}`;
}
return "object";
case "string":
return val.length > 30 ? "string" : `"${val.split('"').join('\\"')}"`;
case "boolean":
return String(val);
case "number":
return String(val);
case "bigint":
return String(val) + "n";
default:
// "symbol" | "undefined" | "object" | "function"
return typeof val;
}
}
function formatReflectMessage(desc) {
return `ReflectMessage (${desc.typeName})`;
}
function formatReflectList(field) {
switch (field.listKind) {
case "message":
return `ReflectList (${field.message.toString()})`;
case "enum":
return `ReflectList (${field.enum.toString()})`;
case "scalar":
return `ReflectList (${descriptors_js_1.ScalarType[field.scalar]})`;
}
}
function formatReflectMap(field) {
switch (field.mapKind) {
case "message":
return `ReflectMap (${descriptors_js_1.ScalarType[field.mapKey]}, ${field.message.toString()})`;
case "enum":
return `ReflectMap (${descriptors_js_1.ScalarType[field.mapKey]}, ${field.enum.toString()})`;
case "scalar":
return `ReflectMap (${descriptors_js_1.ScalarType[field.mapKey]}, ${descriptors_js_1.ScalarType[field.scalar]})`;
}
}
function scalarTypeDescription(scalar) {
switch (scalar) {
case descriptors_js_1.ScalarType.STRING:
return "string";
case descriptors_js_1.ScalarType.BOOL:
return "boolean";
case descriptors_js_1.ScalarType.INT64:
case descriptors_js_1.ScalarType.SINT64:
case descriptors_js_1.ScalarType.SFIXED64:
return "bigint (int64)";
case descriptors_js_1.ScalarType.UINT64:
case descriptors_js_1.ScalarType.FIXED64:
return "bigint (uint64)";
case descriptors_js_1.ScalarType.BYTES:
return "Uint8Array";
case descriptors_js_1.ScalarType.DOUBLE:
return "number (float64)";
case descriptors_js_1.ScalarType.FLOAT:
return "number (float32)";
case descriptors_js_1.ScalarType.FIXED32:
case descriptors_js_1.ScalarType.UINT32:
return "number (uint32)";
case descriptors_js_1.ScalarType.INT32:
case descriptors_js_1.ScalarType.SFIXED32:
case descriptors_js_1.ScalarType.SINT32:
return "number (int32)";
}
}

View File

@@ -0,0 +1,217 @@
import type { DescField, DescMessage, DescOneof } from "../descriptors.js";
import { unsafeLocal } from "./unsafe.js";
import type { Message, UnknownField } from "../types.js";
import type { ScalarValue } from "./scalar.js";
/**
* ReflectMessage provides dynamic access and manipulation of a message.
*/
export interface ReflectMessage {
/**
* The underlying message instance.
*/
readonly message: Message;
/**
* The descriptor for the message.
*/
readonly desc: DescMessage;
/**
* The fields of the message. This is a shortcut to message.fields.
*/
readonly fields: readonly DescField[];
/**
* The fields of the message, sorted by field number ascending.
*/
readonly sortedFields: readonly DescField[];
/**
* Oneof groups of the message. This is a shortcut to message.oneofs.
*/
readonly oneofs: readonly DescOneof[];
/**
* Fields and oneof groups for this message. This is a shortcut to message.members.
*/
readonly members: readonly (DescField | DescOneof)[];
/**
* Find a field by number.
*/
findNumber(number: number): DescField | undefined;
/**
* Returns true if the field is set.
*
* - Scalar and enum fields with implicit presence (proto3):
* Set if not a zero value.
*
* - Scalar and enum fields with explicit presence (proto2, oneof):
* Set if a value was set when creating or parsing the message, or when a
* value was assigned to the field's property.
*
* - Message fields:
* Set if the property is not undefined.
*
* - List and map fields:
* Set if not empty.
*/
isSet(field: DescField): boolean;
/**
* Resets the field, so that isSet() will return false.
*/
clear(field: DescField): void;
/**
* Return the selected field of a oneof group.
*/
oneofCase(oneof: DescOneof): DescField | undefined;
/**
* Returns the field value. Values are converted or wrapped to make it easier
* to manipulate messages.
*
* - Scalar fields:
* Returns the value, but converts 64-bit integer fields with the option
* `jstype=JS_STRING` to a bigint value.
* If the field is not set, the default value is returned. If no default
* value is set, the zero value is returned.
*
* - Enum fields:
* Returns the numeric value. If the field is not set, the default value is
* returned. If no default value is set, the zero value is returned.
*
* - Message fields:
* Returns a ReflectMessage. If the field is not set, a new message is
* returned, but not set on the field.
*
* - List fields:
* Returns a ReflectList object.
*
* - Map fields:
* Returns a ReflectMap object.
*
* Note that get() never returns `undefined`. To determine whether a field is
* set, use isSet().
*/
get<Field extends DescField>(field: Field): ReflectMessageGet<Field>;
/**
* Set a field value.
*
* Expects values in the same form that get() returns:
*
* - Scalar fields:
* 64-bit integer fields with the option `jstype=JS_STRING` as a bigint value.
*
* - Message fields:
* ReflectMessage.
*
* - List fields:
* ReflectList.
*
* - Map fields:
* ReflectMap.
*
* Throws an error if the value is invalid for the field. `undefined` is not
* a valid value. To reset a field, use clear().
*/
set<Field extends DescField>(field: Field, value: unknown): void;
/**
* Returns the unknown fields of the message.
*/
getUnknown(): UnknownField[] | undefined;
/**
* Sets the unknown fields of the message, overwriting any previous values.
*/
setUnknown(value: UnknownField[]): void;
[unsafeLocal]: Message;
}
/**
* ReflectList provides dynamic access and manipulation of a list field on a
* message.
*
* ReflectList is iterable - you can loop through all items with a for...of loop.
*
* Values are converted or wrapped to make it easier to manipulate them:
* - Scalar 64-bit integer fields with the option `jstype=JS_STRING` are
* converted to bigint.
* - Messages are wrapped in a ReflectMessage.
*/
export interface ReflectList<V = unknown> extends Iterable<V> {
/**
* Returns the list field.
*/
field(): DescField & {
fieldKind: "list";
};
/**
* The size of the list.
*/
readonly size: number;
/**
* Retrieves the item at the specified index, or undefined if the index
* is out of range.
*/
get(index: number): V | undefined;
/**
* Adds an item at the end of the list.
* Throws an error if an item is invalid for this list.
*/
add(item: V): void;
/**
* Replaces the item at the specified index with the specified item.
* Throws an error if the index is out of range (index < 0 || index >= size).
* Throws an error if the item is invalid for this list.
*/
set(index: number, item: V): void;
/**
* Removes all items from the list.
*/
clear(): void;
[Symbol.iterator](): IterableIterator<V>;
entries(): IterableIterator<[number, V]>;
keys(): IterableIterator<number>;
values(): IterableIterator<V>;
[unsafeLocal]: unknown[];
}
/**
* ReflectMap provides dynamic access and manipulation of a map field on a
* message.
*
* ReflectMap is iterable - you can loop through all entries with a for...of loop.
*
* Keys and values are converted or wrapped to make it easier to manipulate them:
* - A map field is a record object on a message, where keys are always strings.
* ReflectMap converts keys to their closest possible type in TypeScript.
* - Messages are wrapped in a ReflectMessage.
*/
export interface ReflectMap<K = unknown, V = unknown> extends ReadonlyMap<K, V> {
/**
* Returns the map field.
*/
field(): DescField & {
fieldKind: "map";
};
/**
* Removes the entry for the specified key.
* Returns false if the key is unknown.
*/
delete(key: K): boolean;
/**
* Sets or replaces the item at the specified key with the specified value.
* Throws an error if the key or value is invalid for this map.
*/
set(key: K, value: V): this;
/**
* Removes all entries from the map.
*/
clear(): void;
[unsafeLocal]: Record<string, unknown>;
}
/**
* The return type of ReflectMessage.get()
*/
export type ReflectMessageGet<Field extends DescField = DescField> = (Field extends {
fieldKind: "map";
} ? ReflectMap : Field extends {
fieldKind: "list";
} ? ReflectList : Field extends {
fieldKind: "enum";
} ? number : Field extends {
fieldKind: "message";
} ? ReflectMessage : Field extends {
fieldKind: "scalar";
scalar: infer T;
} ? ScalarValue<T> : never);

View File

@@ -0,0 +1,16 @@
"use strict";
// Copyright 2021-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 });
const unsafe_js_1 = require("./unsafe.js");

View File

@@ -0,0 +1,43 @@
import { type DescField, type DescMessage } from "../descriptors.js";
import type { MessageShape } from "../types.js";
import type { ReflectList, ReflectMap, ReflectMessage } from "./reflect-types.js";
/**
* Create a ReflectMessage.
*/
export declare function reflect<Desc extends DescMessage>(messageDesc: Desc, message?: MessageShape<Desc>,
/**
* By default, field values are validated when setting them. For example,
* a value for an uint32 field must be a ECMAScript Number >= 0.
*
* When field values are trusted, performance can be improved by disabling
* checks.
*/
check?: boolean): ReflectMessage;
/**
* Create a ReflectList.
*/
export declare function reflectList<V>(field: DescField & {
fieldKind: "list";
}, unsafeInput?: unknown[],
/**
* By default, field values are validated when setting them. For example,
* a value for an uint32 field must be a ECMAScript Number >= 0.
*
* When field values are trusted, performance can be improved by disabling
* checks.
*/
check?: boolean): ReflectList<V>;
/**
* Create a ReflectMap.
*/
export declare function reflectMap<K = unknown, V = unknown>(field: DescField & {
fieldKind: "map";
}, unsafeInput?: Record<string, unknown>,
/**
* By default, field values are validated when setting them. For example,
* a value for an uint32 field must be a ECMAScript Number >= 0.
*
* When field values are trusted, performance can be improved by disabling
* checks.
*/
check?: boolean): ReflectMap<K, V>;

View File

@@ -0,0 +1,541 @@
"use strict";
// Copyright 2021-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.reflect = reflect;
exports.reflectList = reflectList;
exports.reflectMap = reflectMap;
const descriptors_js_1 = require("../descriptors.js");
const reflect_check_js_1 = require("./reflect-check.js");
const error_js_1 = require("./error.js");
const unsafe_js_1 = require("./unsafe.js");
const create_js_1 = require("../create.js");
const wrappers_js_1 = require("../wkt/wrappers.js");
const scalar_js_1 = require("./scalar.js");
const proto_int64_js_1 = require("../proto-int64.js");
const guard_js_1 = require("./guard.js");
/**
* Create a ReflectMessage.
*/
function reflect(messageDesc, message,
/**
* By default, field values are validated when setting them. For example,
* a value for an uint32 field must be a ECMAScript Number >= 0.
*
* When field values are trusted, performance can be improved by disabling
* checks.
*/
check = true) {
return new ReflectMessageImpl(messageDesc, message, check);
}
class ReflectMessageImpl {
get sortedFields() {
var _a;
return ((_a = this._sortedFields) !== null && _a !== void 0 ? _a :
// biome-ignore lint/suspicious/noAssignInExpressions: no
(this._sortedFields = this.desc.fields
.concat()
.sort((a, b) => a.number - b.number)));
}
constructor(messageDesc, message, check = true) {
this.lists = new Map();
this.maps = new Map();
this.check = check;
this.desc = messageDesc;
this.message = this[unsafe_js_1.unsafeLocal] = message !== null && message !== void 0 ? message : (0, create_js_1.create)(messageDesc);
this.fields = messageDesc.fields;
this.oneofs = messageDesc.oneofs;
this.members = messageDesc.members;
}
findNumber(number) {
if (!this._fieldsByNumber) {
this._fieldsByNumber = new Map(this.desc.fields.map((f) => [f.number, f]));
}
return this._fieldsByNumber.get(number);
}
oneofCase(oneof) {
assertOwn(this.message, oneof);
return (0, unsafe_js_1.unsafeOneofCase)(this.message, oneof);
}
isSet(field) {
assertOwn(this.message, field);
return (0, unsafe_js_1.unsafeIsSet)(this.message, field);
}
clear(field) {
assertOwn(this.message, field);
(0, unsafe_js_1.unsafeClear)(this.message, field);
}
get(field) {
assertOwn(this.message, field);
const value = (0, unsafe_js_1.unsafeGet)(this.message, field);
switch (field.fieldKind) {
case "list":
// eslint-disable-next-line no-case-declarations
let list = this.lists.get(field);
if (!list || list[unsafe_js_1.unsafeLocal] !== value) {
this.lists.set(field,
// biome-ignore lint/suspicious/noAssignInExpressions: no
(list = new ReflectListImpl(field, value, this.check)));
}
return list;
case "map":
let map = this.maps.get(field);
if (!map || map[unsafe_js_1.unsafeLocal] !== value) {
this.maps.set(field,
// biome-ignore lint/suspicious/noAssignInExpressions: no
(map = new ReflectMapImpl(field, value, this.check)));
}
return map;
case "message":
return messageToReflect(field, value, this.check);
case "scalar":
return (value === undefined
? (0, scalar_js_1.scalarZeroValue)(field.scalar, false)
: longToReflect(field, value));
case "enum":
return (value !== null && value !== void 0 ? value : field.enum.values[0].number);
}
}
set(field, value) {
assertOwn(this.message, field);
if (this.check) {
const err = (0, reflect_check_js_1.checkField)(field, value);
if (err) {
throw err;
}
}
let local;
if (field.fieldKind == "message") {
local = messageToLocal(field, value);
}
else if ((0, guard_js_1.isReflectMap)(value) || (0, guard_js_1.isReflectList)(value)) {
local = value[unsafe_js_1.unsafeLocal];
}
else {
local = longToLocal(field, value);
}
(0, unsafe_js_1.unsafeSet)(this.message, field, local);
}
getUnknown() {
return this.message.$unknown;
}
setUnknown(value) {
this.message.$unknown = value;
}
}
function assertOwn(owner, member) {
if (member.parent.typeName !== owner.$typeName) {
throw new error_js_1.FieldError(member, `cannot use ${member.toString()} with message ${owner.$typeName}`, "ForeignFieldError");
}
}
/**
* Create a ReflectList.
*/
function reflectList(field, unsafeInput,
/**
* By default, field values are validated when setting them. For example,
* a value for an uint32 field must be a ECMAScript Number >= 0.
*
* When field values are trusted, performance can be improved by disabling
* checks.
*/
check = true) {
return new ReflectListImpl(field, unsafeInput !== null && unsafeInput !== void 0 ? unsafeInput : [], check);
}
class ReflectListImpl {
field() {
return this._field;
}
get size() {
return this._arr.length;
}
constructor(field, unsafeInput, check) {
this._field = field;
this._arr = this[unsafe_js_1.unsafeLocal] = unsafeInput;
this.check = check;
}
get(index) {
const item = this._arr[index];
return item === undefined
? undefined
: listItemToReflect(this._field, item, this.check);
}
set(index, item) {
if (index < 0 || index >= this._arr.length) {
throw new error_js_1.FieldError(this._field, `list item #${index + 1}: out of range`);
}
if (this.check) {
const err = (0, reflect_check_js_1.checkListItem)(this._field, index, item);
if (err) {
throw err;
}
}
this._arr[index] = listItemToLocal(this._field, item);
}
add(item) {
if (this.check) {
const err = (0, reflect_check_js_1.checkListItem)(this._field, this._arr.length, item);
if (err) {
throw err;
}
}
this._arr.push(listItemToLocal(this._field, item));
return undefined;
}
clear() {
this._arr.splice(0, this._arr.length);
}
[Symbol.iterator]() {
return this.values();
}
keys() {
return this._arr.keys();
}
*values() {
for (const item of this._arr) {
yield listItemToReflect(this._field, item, this.check);
}
}
*entries() {
for (let i = 0; i < this._arr.length; i++) {
yield [i, listItemToReflect(this._field, this._arr[i], this.check)];
}
}
}
/**
* Create a ReflectMap.
*/
function reflectMap(field, unsafeInput,
/**
* By default, field values are validated when setting them. For example,
* a value for an uint32 field must be a ECMAScript Number >= 0.
*
* When field values are trusted, performance can be improved by disabling
* checks.
*/
check = true) {
return new ReflectMapImpl(field, unsafeInput, check);
}
class ReflectMapImpl {
constructor(field, unsafeInput, check = true) {
this.obj = this[unsafe_js_1.unsafeLocal] = unsafeInput !== null && unsafeInput !== void 0 ? unsafeInput : {};
this.check = check;
this._field = field;
}
field() {
return this._field;
}
set(key, value) {
if (this.check) {
const err = (0, reflect_check_js_1.checkMapEntry)(this._field, key, value);
if (err) {
throw err;
}
}
this.obj[mapKeyToLocal(key)] = mapValueToLocal(this._field, value);
return this;
}
delete(key) {
const k = mapKeyToLocal(key);
const has = Object.prototype.hasOwnProperty.call(this.obj, k);
if (has) {
delete this.obj[k];
}
return has;
}
clear() {
for (const key of Object.keys(this.obj)) {
delete this.obj[key];
}
}
get(key) {
let val = this.obj[mapKeyToLocal(key)];
if (val !== undefined) {
val = mapValueToReflect(this._field, val, this.check);
}
return val;
}
has(key) {
return Object.prototype.hasOwnProperty.call(this.obj, mapKeyToLocal(key));
}
*keys() {
for (const objKey of Object.keys(this.obj)) {
yield mapKeyToReflect(objKey, this._field.mapKey);
}
}
*entries() {
for (const objEntry of Object.entries(this.obj)) {
yield [
mapKeyToReflect(objEntry[0], this._field.mapKey),
mapValueToReflect(this._field, objEntry[1], this.check),
];
}
}
[Symbol.iterator]() {
return this.entries();
}
get size() {
return Object.keys(this.obj).length;
}
*values() {
for (const val of Object.values(this.obj)) {
yield mapValueToReflect(this._field, val, this.check);
}
}
forEach(callbackfn, thisArg) {
for (const mapEntry of this.entries()) {
callbackfn.call(thisArg, mapEntry[1], mapEntry[0], this);
}
}
}
function messageToLocal(field, value) {
if (!(0, guard_js_1.isReflectMessage)(value)) {
return value;
}
if ((0, wrappers_js_1.isWrapper)(value.message) &&
!field.oneof &&
field.fieldKind == "message") {
// Types from google/protobuf/wrappers.proto are unwrapped when used in
// a singular field that is not part of a oneof group.
return value.message.value;
}
if (value.desc.typeName == "google.protobuf.Struct" &&
field.parent.typeName != "google.protobuf.Value") {
// google.protobuf.Struct is represented with JsonObject when used in a
// field, except when used in google.protobuf.Value.
return wktStructToLocal(value.message);
}
return value.message;
}
function messageToReflect(field, value, check) {
if (value !== undefined) {
if ((0, wrappers_js_1.isWrapperDesc)(field.message) &&
!field.oneof &&
field.fieldKind == "message") {
// Types from google/protobuf/wrappers.proto are unwrapped when used in
// a singular field that is not part of a oneof group.
value = {
$typeName: field.message.typeName,
value: longToReflect(field.message.fields[0], value),
};
}
else if (field.message.typeName == "google.protobuf.Struct" &&
field.parent.typeName != "google.protobuf.Value" &&
(0, guard_js_1.isObject)(value)) {
// google.protobuf.Struct is represented with JsonObject when used in a
// field, except when used in google.protobuf.Value.
value = wktStructToReflect(value);
}
}
return new ReflectMessageImpl(field.message, value, check);
}
function listItemToLocal(field, value) {
if (field.listKind == "message") {
return messageToLocal(field, value);
}
return longToLocal(field, value);
}
function listItemToReflect(field, value, check) {
if (field.listKind == "message") {
return messageToReflect(field, value, check);
}
return longToReflect(field, value);
}
function mapValueToLocal(field, value) {
if (field.mapKind == "message") {
return messageToLocal(field, value);
}
return longToLocal(field, value);
}
function mapValueToReflect(field, value, check) {
if (field.mapKind == "message") {
return messageToReflect(field, value, check);
}
return value;
}
function mapKeyToLocal(key) {
return typeof key == "string" || typeof key == "number" ? key : String(key);
}
/**
* Converts a map key (any scalar value except float, double, or bytes) from its
* representation in a message (string or number, the only possible object key
* types) to the closest possible type in ECMAScript.
*/
function mapKeyToReflect(key, type) {
switch (type) {
case descriptors_js_1.ScalarType.STRING:
return key;
case descriptors_js_1.ScalarType.INT32:
case descriptors_js_1.ScalarType.FIXED32:
case descriptors_js_1.ScalarType.UINT32:
case descriptors_js_1.ScalarType.SFIXED32:
case descriptors_js_1.ScalarType.SINT32: {
const n = Number.parseInt(key);
if (Number.isFinite(n)) {
return n;
}
break;
}
case descriptors_js_1.ScalarType.BOOL:
switch (key) {
case "true":
return true;
case "false":
return false;
}
break;
case descriptors_js_1.ScalarType.UINT64:
case descriptors_js_1.ScalarType.FIXED64:
try {
return proto_int64_js_1.protoInt64.uParse(key);
}
catch (_a) {
//
}
break;
default:
// INT64, SFIXED64, SINT64
try {
return proto_int64_js_1.protoInt64.parse(key);
}
catch (_b) {
//
}
break;
}
return key;
}
function longToReflect(field, value) {
switch (field.scalar) {
case descriptors_js_1.ScalarType.INT64:
case descriptors_js_1.ScalarType.SFIXED64:
case descriptors_js_1.ScalarType.SINT64:
if ("longAsString" in field &&
field.longAsString &&
typeof value == "string") {
value = proto_int64_js_1.protoInt64.parse(value);
}
break;
case descriptors_js_1.ScalarType.FIXED64:
case descriptors_js_1.ScalarType.UINT64:
if ("longAsString" in field &&
field.longAsString &&
typeof value == "string") {
value = proto_int64_js_1.protoInt64.uParse(value);
}
break;
}
return value;
}
function longToLocal(field, value) {
switch (field.scalar) {
case descriptors_js_1.ScalarType.INT64:
case descriptors_js_1.ScalarType.SFIXED64:
case descriptors_js_1.ScalarType.SINT64:
if ("longAsString" in field && field.longAsString) {
value = String(value);
}
else if (typeof value == "string" || typeof value == "number") {
value = proto_int64_js_1.protoInt64.parse(value);
}
break;
case descriptors_js_1.ScalarType.FIXED64:
case descriptors_js_1.ScalarType.UINT64:
if ("longAsString" in field && field.longAsString) {
value = String(value);
}
else if (typeof value == "string" || typeof value == "number") {
value = proto_int64_js_1.protoInt64.uParse(value);
}
break;
}
return value;
}
function wktStructToReflect(json) {
const struct = {
$typeName: "google.protobuf.Struct",
fields: {},
};
if ((0, guard_js_1.isObject)(json)) {
for (const [k, v] of Object.entries(json)) {
struct.fields[k] = wktValueToReflect(v);
}
}
return struct;
}
function wktStructToLocal(val) {
const json = {};
for (const [k, v] of Object.entries(val.fields)) {
json[k] = wktValueToLocal(v);
}
return json;
}
function wktValueToLocal(val) {
switch (val.kind.case) {
case "structValue":
return wktStructToLocal(val.kind.value);
case "listValue":
return val.kind.value.values.map(wktValueToLocal);
case "nullValue":
case undefined:
return null;
default:
return val.kind.value;
}
}
function wktValueToReflect(json) {
const value = {
$typeName: "google.protobuf.Value",
kind: { case: undefined },
};
switch (typeof json) {
case "number":
value.kind = { case: "numberValue", value: json };
break;
case "string":
value.kind = { case: "stringValue", value: json };
break;
case "boolean":
value.kind = { case: "boolValue", value: json };
break;
case "object":
if (json === null) {
const nullValue = 0;
value.kind = { case: "nullValue", value: nullValue };
}
else if (Array.isArray(json)) {
const listValue = {
$typeName: "google.protobuf.ListValue",
values: [],
};
if (Array.isArray(json)) {
for (const e of json) {
listValue.values.push(wktValueToReflect(e));
}
}
value.kind = {
case: "listValue",
value: listValue,
};
}
else {
value.kind = {
case: "structValue",
value: wktStructToReflect(json),
};
}
break;
}
return value;
}

View File

@@ -0,0 +1,21 @@
import { ScalarType } from "../descriptors.js";
/**
* ScalarValue maps from a scalar field type to a TypeScript value type.
*/
export type ScalarValue<T = ScalarType, LongAsString extends boolean = false> = T extends ScalarType.STRING ? string : T extends ScalarType.INT32 ? number : T extends ScalarType.UINT32 ? number : T extends ScalarType.SINT32 ? number : T extends ScalarType.FIXED32 ? number : T extends ScalarType.SFIXED32 ? number : T extends ScalarType.FLOAT ? number : T extends ScalarType.DOUBLE ? number : T extends ScalarType.INT64 ? LongAsString extends true ? string : bigint : T extends ScalarType.SINT64 ? LongAsString extends true ? string : bigint : T extends ScalarType.SFIXED64 ? LongAsString extends true ? string : bigint : T extends ScalarType.UINT64 ? LongAsString extends true ? string : bigint : T extends ScalarType.FIXED64 ? LongAsString extends true ? string : bigint : T extends ScalarType.BOOL ? boolean : T extends ScalarType.BYTES ? Uint8Array : never;
/**
* Returns true if both scalar values are equal.
*/
export declare function scalarEquals(type: ScalarType, a: ScalarValue | undefined, b: ScalarValue | undefined): boolean;
/**
* Returns the zero value for the given scalar type.
*/
export declare function scalarZeroValue<T extends ScalarType, LongAsString extends boolean>(type: T, longAsString: LongAsString): ScalarValue<T, LongAsString>;
/**
* Returns true for a zero-value. For example, an integer has the zero-value `0`,
* a boolean is `false`, a string is `""`, and bytes is an empty Uint8Array.
*
* In proto3, zero-values are not written to the wire, unless the field is
* optional or repeated.
*/
export declare function isScalarZeroValue(type: ScalarType, value: unknown): boolean;

View File

@@ -0,0 +1,102 @@
"use strict";
// Copyright 2021-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.scalarEquals = scalarEquals;
exports.scalarZeroValue = scalarZeroValue;
exports.isScalarZeroValue = isScalarZeroValue;
const proto_int64_js_1 = require("../proto-int64.js");
const descriptors_js_1 = require("../descriptors.js");
/**
* Returns true if both scalar values are equal.
*/
function scalarEquals(type, a, b) {
if (a === b) {
// This correctly matches equal values except BYTES and (possibly) 64-bit integers.
return true;
}
// Special case BYTES - we need to compare each byte individually
if (type == descriptors_js_1.ScalarType.BYTES) {
if (!(a instanceof Uint8Array) || !(b instanceof Uint8Array)) {
return false;
}
if (a.length !== b.length) {
return false;
}
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
// Special case 64-bit integers - we support number, string and bigint representation.
switch (type) {
case descriptors_js_1.ScalarType.UINT64:
case descriptors_js_1.ScalarType.FIXED64:
case descriptors_js_1.ScalarType.INT64:
case descriptors_js_1.ScalarType.SFIXED64:
case descriptors_js_1.ScalarType.SINT64:
// Loose comparison will match between 0n, 0 and "0".
return a == b;
}
// Anything that hasn't been caught by strict comparison or special cased
// BYTES and 64-bit integers is not equal.
return false;
}
/**
* Returns the zero value for the given scalar type.
*/
function scalarZeroValue(type, longAsString) {
switch (type) {
case descriptors_js_1.ScalarType.STRING:
return "";
case descriptors_js_1.ScalarType.BOOL:
return false;
case descriptors_js_1.ScalarType.DOUBLE:
case descriptors_js_1.ScalarType.FLOAT:
return 0.0;
case descriptors_js_1.ScalarType.INT64:
case descriptors_js_1.ScalarType.UINT64:
case descriptors_js_1.ScalarType.SFIXED64:
case descriptors_js_1.ScalarType.FIXED64:
case descriptors_js_1.ScalarType.SINT64:
return (longAsString ? "0" : proto_int64_js_1.protoInt64.zero);
case descriptors_js_1.ScalarType.BYTES:
return new Uint8Array(0);
default:
// Handles INT32, UINT32, SINT32, FIXED32, SFIXED32.
// We do not use individual cases to save a few bytes code size.
return 0;
}
}
/**
* Returns true for a zero-value. For example, an integer has the zero-value `0`,
* a boolean is `false`, a string is `""`, and bytes is an empty Uint8Array.
*
* In proto3, zero-values are not written to the wire, unless the field is
* optional or repeated.
*/
function isScalarZeroValue(type, value) {
switch (type) {
case descriptors_js_1.ScalarType.BOOL:
return value === false;
case descriptors_js_1.ScalarType.STRING:
return value === "";
case descriptors_js_1.ScalarType.BYTES:
return value instanceof Uint8Array && !value.byteLength;
default:
return value == 0; // Loose comparison matches 0n, 0 and "0"
}
}

View File

@@ -0,0 +1,39 @@
import type { DescField, DescOneof } from "../descriptors.js";
export declare const unsafeLocal: unique symbol;
/**
* Return the selected field of a oneof group.
*
* @private
*/
export declare function unsafeOneofCase(target: Record<string, any>, oneof: DescOneof): DescField | undefined;
/**
* Returns true if the field is set.
*
* @private
*/
export declare function unsafeIsSet(target: Record<string, any>, field: DescField): boolean;
/**
* Returns true if the field is set, but only for singular fields with explicit
* presence (proto2).
*
* @private
*/
export declare function unsafeIsSetExplicit(target: object, localName: string): boolean;
/**
* Return a field value, respecting oneof groups.
*
* @private
*/
export declare function unsafeGet(target: Record<string, unknown>, field: DescField): unknown;
/**
* Set a field value, respecting oneof groups.
*
* @private
*/
export declare function unsafeSet(target: Record<string, unknown>, field: DescField, value: unknown): void;
/**
* Resets the field, so that unsafeIsSet() will return false.
*
* @private
*/
export declare function unsafeClear(target: Record<string, any>, field: DescField): void;

View File

@@ -0,0 +1,149 @@
"use strict";
// Copyright 2021-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.unsafeLocal = void 0;
exports.unsafeOneofCase = unsafeOneofCase;
exports.unsafeIsSet = unsafeIsSet;
exports.unsafeIsSetExplicit = unsafeIsSetExplicit;
exports.unsafeGet = unsafeGet;
exports.unsafeSet = unsafeSet;
exports.unsafeClear = unsafeClear;
const scalar_js_1 = require("./scalar.js");
// bootstrap-inject google.protobuf.FeatureSet.FieldPresence.IMPLICIT: const $name: FeatureSet_FieldPresence.$localName = $number;
const IMPLICIT = 2;
exports.unsafeLocal = Symbol.for("reflect unsafe local");
/**
* Return the selected field of a oneof group.
*
* @private
*/
function unsafeOneofCase(
// biome-ignore lint/suspicious/noExplicitAny: `any` is the best choice for dynamic access
target, oneof) {
const c = target[oneof.localName].case;
if (c === undefined) {
return c;
}
return oneof.fields.find((f) => f.localName === c);
}
/**
* Returns true if the field is set.
*
* @private
*/
function unsafeIsSet(
// biome-ignore lint/suspicious/noExplicitAny: `any` is the best choice for dynamic access
target, field) {
const name = field.localName;
if (field.oneof) {
return target[field.oneof.localName].case === name;
}
if (field.presence != IMPLICIT) {
// Fields with explicit presence have properties on the prototype chain
// for default / zero values (except for proto3).
return (target[name] !== undefined &&
Object.prototype.hasOwnProperty.call(target, name));
}
switch (field.fieldKind) {
case "list":
return target[name].length > 0;
case "map":
return Object.keys(target[name]).length > 0;
case "scalar":
return !(0, scalar_js_1.isScalarZeroValue)(field.scalar, target[name]);
case "enum":
return target[name] !== field.enum.values[0].number;
}
throw new Error("message field with implicit presence");
}
/**
* Returns true if the field is set, but only for singular fields with explicit
* presence (proto2).
*
* @private
*/
function unsafeIsSetExplicit(target, localName) {
return (Object.prototype.hasOwnProperty.call(target, localName) &&
target[localName] !== undefined);
}
/**
* Return a field value, respecting oneof groups.
*
* @private
*/
function unsafeGet(target, field) {
if (field.oneof) {
const oneof = target[field.oneof.localName];
if (oneof.case === field.localName) {
return oneof.value;
}
return undefined;
}
return target[field.localName];
}
/**
* Set a field value, respecting oneof groups.
*
* @private
*/
function unsafeSet(target, field, value) {
if (field.oneof) {
target[field.oneof.localName] = {
case: field.localName,
value: value,
};
}
else {
target[field.localName] = value;
}
}
/**
* Resets the field, so that unsafeIsSet() will return false.
*
* @private
*/
function unsafeClear(
// biome-ignore lint/suspicious/noExplicitAny: `any` is the best choice for dynamic access
target, field) {
const name = field.localName;
if (field.oneof) {
const oneofLocalName = field.oneof.localName;
if (target[oneofLocalName].case === name) {
target[oneofLocalName] = { case: undefined };
}
}
else if (field.presence != IMPLICIT) {
// Fields with explicit presence have properties on the prototype chain
// for default / zero values (except for proto3). By deleting their own
// property, the field is reset.
delete target[name];
}
else {
switch (field.fieldKind) {
case "map":
target[name] = {};
break;
case "list":
target[name] = [];
break;
case "enum":
target[name] = field.enum.values[0].number;
break;
case "scalar":
target[name] = (0, scalar_js_1.scalarZeroValue)(field.scalar, field.longAsString);
break;
}
}
}