Debian Codegraph @

node/@bufbuild/protobuf/dist/esm/extensions.js

raw
1 // Copyright 2021-2026 Buf Technologies, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 import { create } from "./create.js";
15 import { makeReadContext, readField } from "./from-binary.js";
16 import { reflect } from "./reflect/reflect.js";
17 import { scalarZeroValue } from "./reflect/scalar.js";
18 import { writeField } from "./to-binary.js";
19 import { BinaryReader, BinaryWriter } from "./wire/binary-encoding.js";
20 import { isWrapperDesc } from "./wkt/wrappers.js";
21 /**
22 * Retrieve an extension value from a message.
23 *
24 * The function never returns undefined. Use hasExtension() to check whether an
25 * extension is set. If the extension is not set, this function returns the
26 * default value (if one was specified in the protobuf source), or the zero value
27 * (for example `0` for numeric types, `[]` for repeated extension fields, and
28 * an empty message instance for message fields).
29 *
30 * Extensions are stored as unknown fields on a message. To mutate an extension
31 * value, make sure to store the new value with setExtension() after mutating.
32 *
33 * If the extension does not extend the given message, an error is raised.
34 */
35 export function getExtension(message, extension, options) {
36 assertExtendee(extension, message);
37 const ufs = filterUnknownFields(message.$unknown, extension);
38 const [container, field, get] = createExtensionContainer(extension);
39 const ctx = makeReadContext(options);
40 for (const uf of ufs) {
41 readField(container, new BinaryReader(uf.data), field, uf.wireType, ctx);
42 }
43 return get();
44 }
45 /**
46 * Set an extension value on a message. If the message already has a value for
47 * this extension, the value is replaced.
48 *
49 * If the extension does not extend the given message, an error is raised.
50 */
51 export function setExtension(message, extension, value) {
52 var _a;
53 assertExtendee(extension, message);
54 const ufs = ((_a = message.$unknown) !== null && _a !== void 0 ? _a : []).filter((uf) => uf.no !== extension.number);
55 const [container, field] = createExtensionContainer(extension, value);
56 const writer = new BinaryWriter();
57 writeField(writer, { writeUnknownFields: true }, container, field);
58 const reader = new BinaryReader(writer.finish());
59 while (reader.pos < reader.len) {
60 const [no, wireType] = reader.tag();
61 const data = reader.skip(wireType, no);
62 ufs.push({ no, wireType, data });
63 }
64 message.$unknown = ufs;
65 }
66 /**
67 * Remove an extension value from a message.
68 *
69 * If the extension does not extend the given message, an error is raised.
70 */
71 export function clearExtension(message, extension) {
72 assertExtendee(extension, message);
73 if (message.$unknown === undefined) {
74 return;
75 }
76 message.$unknown = message.$unknown.filter((uf) => uf.no !== extension.number);
77 }
78 /**
79 * Check whether an extension is set on a message.
80 */
81 export function hasExtension(message, extension) {
82 var _a;
83 return (extension.extendee.typeName === message.$typeName &&
84 !!((_a = message.$unknown) === null || _a === void 0 ? void 0 : _a.find((uf) => uf.no === extension.number)));
85 }
86 /**
87 * Check whether an option is set on a descriptor.
88 *
89 * Options are extensions to the `google.protobuf.*Options` messages defined in
90 * google/protobuf/descriptor.proto. This function gets the option message from
91 * the descriptor, and calls hasExtension().
92 */
93 export function hasOption(element, option) {
94 const message = element.proto.options;
95 if (!message) {
96 return false;
97 }
98 return hasExtension(message, option);
99 }
100 /**
101 * Retrieve an option value from a descriptor.
102 *
103 * Options are extensions to the `google.protobuf.*Options` messages defined in
104 * google/protobuf/descriptor.proto. This function gets the option message from
105 * the descriptor, and calls getExtension(). Same as getExtension(), this
106 * function never returns undefined.
107 */
108 export function getOption(element, option) {
109 const message = element.proto.options;
110 if (!message) {
111 const [, , get] = createExtensionContainer(option);
112 return get();
113 }
114 return getExtension(message, option);
115 }
116 function filterUnknownFields(unknownFields, extension) {
117 if (unknownFields === undefined)
118 return [];
119 if (extension.fieldKind === "enum" || extension.fieldKind === "scalar") {
120 // singular scalar fields do not merge, we pick the last
121 for (let i = unknownFields.length - 1; i >= 0; --i) {
122 if (unknownFields[i].no == extension.number) {
123 return [unknownFields[i]];
124 }
125 }
126 return [];
127 }
128 return unknownFields.filter((uf) => uf.no === extension.number);
129 }
130 /**
131 * @private
132 */
133 export function createExtensionContainer(extension, value) {
134 const localName = extension.typeName;
135 const field = Object.assign(Object.assign({}, extension), { kind: "field", parent: extension.extendee, localName });
136 const desc = Object.assign(Object.assign({}, extension.extendee), { fields: [field], members: [field], oneofs: [] });
137 const container = create(desc, value !== undefined ? { [localName]: value } : undefined);
138 return [
139 reflect(desc, container),
140 field,
141 () => {
142 const value = container[localName];
143 if (value === undefined) {
144 // biome-ignore lint/style/noNonNullAssertion: Only message fields are undefined, rest will have a zero value.
145 const desc = extension.message;
146 if (isWrapperDesc(desc)) {
147 return scalarZeroValue(desc.fields[0].scalar, desc.fields[0].longAsString);
148 }
149 return create(desc);
150 }
151 return value;
152 },
153 ];
154 }
155 function assertExtendee(extension, message) {
156 if (extension.extendee.typeName != message.$typeName) {
157 throw new Error(`extension ${extension.typeName} can only be applied to message ${extension.extendee.typeName}`);
158 }
159 }