Debian Codegraph @

node/@bufbuild/protobuf/dist/commonjs/txtpb/to-text.js

raw
1 "use strict";
2 // Copyright 2021-2026 Buf Technologies, Inc.
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 Object.defineProperty(exports, "__esModule", { value: true });
16 exports.toText = toText;
17 const descriptors_js_1 = require("../descriptors.js");
18 const proto_int64_js_1 = require("../proto-int64.js");
19 const reflect_js_1 = require("../reflect/reflect.js");
20 const extensions_js_1 = require("../extensions.js");
21 const index_js_1 = require("../wire/index.js");
22 const index_js_2 = require("../wkt/index.js");
23 const is_group_like_js_1 = require("./is-group-like.js");
24 const writer_js_1 = require("./writer.js");
25 const textWriteDefaults = {
26 printUnknownFields: false,
27 };
28 function makeWriteOptions(options) {
29 return options ? Object.assign(Object.assign({}, textWriteDefaults), options) : textWriteDefaults;
30 }
31 // A bound on nested unknown-field rendering. The known-field tree is a finite,
32 // valid in-memory message and needs no limit, but printUnknownFields re-parses
33 // bytes and recurses (the length-delimited and group heuristics), so we cap
34 // that path as defense-in-depth.
35 const unknownFieldDepthLimit = 100;
36 /**
37 * Serialize a message to the protobuf text format.
38 *
39 * The output matches the default formatting of txtpbfmt: two-space indentation,
40 * one field per line, and a trailing newline.
41 *
42 * Requires BigInt: throws immediately if the environment does not support it.
43 */
44 function toText(schema, message, options) {
45 if (!proto_int64_js_1.protoInt64.supported) {
46 throw new Error("the protobuf text format requires BigInt, which is unavailable in this environment");
47 }
48 const writer = new writer_js_1.Writer();
49 writeMessage(writer, (0, reflect_js_1.reflect)(schema, message), makeWriteOptions(options));
50 return writer.toString();
51 }
52 /**
53 * Write the body of a message: regular fields in declaration order, then
54 * resolvable extensions sorted by full name, then unknown fields by number
55 * (only when printUnknownFields is enabled). For `google.protobuf.Any`, the
56 * expanded form replaces all of this.
57 */
58 function writeMessage(writer, msg, opts) {
59 var _a;
60 if (writeAny(writer, msg, opts)) {
61 return;
62 }
63 for (const field of msg.fields) {
64 // Unset fields are omitted, including unset required fields; like
65 // protobuf-go, we do not validate required fields when serializing.
66 if (msg.isSet(field)) {
67 writeField(writer, fieldTextName(field), field, msg, opts);
68 }
69 }
70 const extensionNumbers = writeExtensions(writer, msg, opts);
71 if (opts.printUnknownFields) {
72 for (const field of (_a = msg.getUnknown()) !== null && _a !== void 0 ? _a : []) {
73 if (!extensionNumbers.has(field.no)) {
74 writeUnknownField(writer, field, 0);
75 }
76 }
77 }
78 }
79 function writeField(writer, name, field, msg, opts) {
80 // Narrowing on fieldKind lets msg.get(field) return the precise reflect type
81 // for each case — ReflectMessage, ReflectList, ReflectMap, number, or a scalar
82 // value — so none of the branches need a cast.
83 switch (field.fieldKind) {
84 case "scalar":
85 writer.scalar(name, scalarToText(field.scalar, msg.get(field)));
86 break;
87 case "enum":
88 writer.scalar(name, enumToText(field.enum, msg.get(field)));
89 break;
90 case "message":
91 writeMessageValue(writer, name, msg.get(field), opts);
92 break;
93 case "list":
94 writeList(writer, name, field, msg.get(field), opts);
95 break;
96 case "map":
97 writeMap(writer, name, field, msg.get(field), opts);
98 break;
99 }
100 }
101 /**
102 * Write a message value as `name: { ... }`, or `name: {}` when it has no body.
103 * The body is rendered speculatively and rolled back if it turns out empty.
104 */
105 function writeMessageValue(writer, name, msg, opts) {
106 const mark = writer.mark();
107 writer.openMessage(name);
108 writeMessage(writer, msg, opts);
109 if (writer.writesSince(mark) === 1) {
110 // Only the opener was written, so the message is empty.
111 writer.reset(mark);
112 writer.emptyMessage(name);
113 }
114 else {
115 writer.end();
116 }
117 }
118 function writeList(writer, name, field, list, opts) {
119 switch (field.listKind) {
120 case "scalar":
121 for (const item of list) {
122 writer.scalar(name, scalarToText(field.scalar, item));
123 }
124 break;
125 case "enum":
126 for (const item of list) {
127 writer.scalar(name, enumToText(field.enum, item));
128 }
129 break;
130 case "message":
131 for (const item of list) {
132 writeMessageValue(writer, name, item, opts);
133 }
134 break;
135 }
136 }
137 function writeMap(writer, name, field, map, opts) {
138 // Map entries are emitted in iteration (insertion) order; unlike protobuf-go,
139 // we deliberately do not sort them.
140 for (const [key, value] of map) {
141 writer.openMessage(name);
142 writer.scalar("key", scalarToText(field.mapKey, key));
143 switch (field.mapKind) {
144 case "scalar":
145 writer.scalar("value", scalarToText(field.scalar, value));
146 break;
147 case "enum":
148 writer.scalar("value", enumToText(field.enum, value));
149 break;
150 case "message":
151 writeMessageValue(writer, "value", value, opts);
152 break;
153 }
154 writer.end();
155 }
156 }
157 /**
158 * Write `google.protobuf.Any` in its expanded form `[type.url]: { ... }`.
159 * Returns false (so the generic path writes `type_url`/`value` instead) when
160 * the message is not an Any, has no type URL, or the type cannot be resolved.
161 */
162 function writeAny(writer, msg, opts) {
163 if (msg.desc.typeName !== "google.protobuf.Any" ||
164 opts.registry === undefined) {
165 return false;
166 }
167 const any = msg.message;
168 if (any.typeUrl === "") {
169 return false;
170 }
171 const unpacked = (0, index_js_2.anyUnpack)(any, opts.registry);
172 if (unpacked === undefined) {
173 return false;
174 }
175 const desc = opts.registry.getMessage(unpacked.$typeName);
176 if (desc === undefined) {
177 return false;
178 }
179 // The bracketed name preserves the exact type URL, including a custom domain.
180 writeMessageValue(writer, "[" + any.typeUrl + "]", (0, reflect_js_1.reflect)(desc, unpacked), opts);
181 return true;
182 }
183 /**
184 * Write resolvable extensions, sorted by full name, and return their field
185 * numbers so writeMessage does not also emit them as raw unknown fields.
186 */
187 function writeExtensions(writer, msg, opts) {
188 const numbers = new Set();
189 const unknown = msg.getUnknown();
190 if (opts.registry === undefined || unknown === undefined) {
191 return numbers;
192 }
193 const extensions = [];
194 for (const { no } of unknown) {
195 if (numbers.has(no)) {
196 continue;
197 }
198 const extension = opts.registry.getExtensionFor(msg.desc, no);
199 if (extension !== undefined) {
200 numbers.add(no);
201 extensions.push(extension);
202 }
203 }
204 extensions.sort((a, b) => a.typeName < b.typeName ? -1 : a.typeName > b.typeName ? 1 : 0);
205 for (const extension of extensions) {
206 const value = (0, extensions_js_1.getExtension)(msg.message, extension);
207 const [container, field] = (0, extensions_js_1.createExtensionContainer)(extension, value);
208 writeField(writer, "[" + extension.typeName + "]", field, container, opts);
209 }
210 return numbers;
211 }
212 /**
213 * Write an unknown field by its field number, mirroring protobuf-go: varints as
214 * decimal, fixed-width values as hexadecimal, length-delimited data as a nested
215 * message when it parses cleanly as one and a quoted byte string otherwise, and
216 * groups recursively.
217 */
218 function writeUnknownField(writer, field, depth) {
219 const name = field.no.toString();
220 const reader = new index_js_1.BinaryReader(field.data);
221 switch (field.wireType) {
222 case index_js_1.WireType.Varint:
223 writer.scalar(name, reader.uint64().toString());
224 break;
225 case index_js_1.WireType.Bit32:
226 writer.scalar(name, "0x" + (reader.fixed32() >>> 0).toString(16).padStart(8, "0"));
227 break;
228 case index_js_1.WireType.Bit64:
229 writer.scalar(name, "0x" + BigInt(reader.fixed64()).toString(16).padStart(16, "0"));
230 break;
231 case index_js_1.WireType.LengthDelimited: {
232 const bytes = reader.bytes();
233 const nested = depth < unknownFieldDepthLimit ? parseUnknownMessage(bytes) : undefined;
234 if (nested === undefined) {
235 writer.scalar(name, (0, writer_js_1.quoteBytes)(bytes));
236 }
237 else {
238 writeUnknownGroup(writer, name, nested, depth);
239 }
240 break;
241 }
242 case index_js_1.WireType.StartGroup: {
243 const fields = [];
244 while (reader.pos < reader.len) {
245 const [no, wireType] = reader.tag();
246 if (wireType === index_js_1.WireType.EndGroup) {
247 break;
248 }
249 fields.push({ no, wireType, data: reader.skip(wireType, no) });
250 }
251 writeUnknownGroup(writer, name, fields, depth);
252 break;
253 }
254 }
255 }
256 function writeUnknownGroup(writer, name, fields, depth) {
257 if (fields.length === 0) {
258 writer.emptyMessage(name);
259 return;
260 }
261 writer.openMessage(name);
262 for (const field of fields) {
263 writeUnknownField(writer, field, depth + 1);
264 }
265 writer.end();
266 }
267 /**
268 * Try to interpret length-delimited bytes as a nested message. Returns its
269 * unknown fields if the bytes parse cleanly and completely, otherwise undefined
270 * (in which case the data is rendered as a quoted byte string).
271 */
272 function parseUnknownMessage(bytes) {
273 if (bytes.length === 0) {
274 return undefined;
275 }
276 const reader = new index_js_1.BinaryReader(bytes);
277 const fields = [];
278 try {
279 while (reader.pos < reader.len) {
280 const [no, wireType] = reader.tag();
281 if (no <= 0 || wireType === index_js_1.WireType.EndGroup) {
282 return undefined;
283 }
284 fields.push({ no, wireType, data: reader.skip(wireType, no) });
285 }
286 }
287 catch (_a) {
288 return undefined;
289 }
290 return reader.pos === reader.len ? fields : undefined;
291 }
292 /**
293 * The name a field is addressed by in the text format: a group-like (delimited)
294 * field uses its message type name, every other field its proto name.
295 */
296 function fieldTextName(field) {
297 return (0, is_group_like_js_1.isGroupLike)(field) ? field.message.name : field.name;
298 }
299 function scalarToText(type, value) {
300 switch (type) {
301 case descriptors_js_1.ScalarType.STRING:
302 return (0, writer_js_1.quoteString)(value);
303 case descriptors_js_1.ScalarType.BYTES:
304 return (0, writer_js_1.quoteBytes)(value);
305 case descriptors_js_1.ScalarType.BOOL:
306 return value === true ? "true" : "false";
307 case descriptors_js_1.ScalarType.FLOAT:
308 return floatToText(value, true);
309 case descriptors_js_1.ScalarType.DOUBLE:
310 return floatToText(value, false);
311 default:
312 // All integer types print as decimal with no prefix. 64-bit values are
313 // bigint; String() gives the decimal form for both bigint and number.
314 return String(value);
315 }
316 }
317 function enumToText(descEnum, value) {
318 // Emit the first-declared name for a value, so allow_alias enums match
319 // protobuf-go (the by-number record can resolve to a non-first alias). An
320 // unknown value prints as a decimal.
321 for (const v of descEnum.values) {
322 if (v.number === value) {
323 return v.name;
324 }
325 }
326 return value.toString();
327 }
328 function floatToText(value, single) {
329 // Round to 32-bit precision first so an overflow becomes inf (not the JS
330 // "Infinity") and the value is the true 32-bit value before we test it.
331 const n = single ? Math.fround(value) : value;
332 if (Number.isNaN(n)) {
333 return "nan";
334 }
335 if (n === Number.POSITIVE_INFINITY) {
336 return "inf";
337 }
338 if (n === Number.NEGATIVE_INFINITY) {
339 return "-inf";
340 }
341 if (Object.is(n, -0)) {
342 return "-0";
343 }
344 if (!single) {
345 // Number.prototype.toString already yields the shortest decimal that
346 // round-trips to the same 64-bit value.
347 return n.toString();
348 }
349 // For 32-bit floats, find the shortest decimal that round-trips to the same
350 // float32, mirroring strconv.AppendFloat(n, 'g', -1, 32) in protobuf-go.
351 for (let precision = 1; precision <= 9; precision++) {
352 const candidate = Number(n.toPrecision(precision));
353 if (Math.fround(candidate) === n) {
354 return candidate.toString();
355 }
356 }
357 return n.toString();
358 }