Debian Codegraph @

node/@bufbuild/protobuf/dist/commonjs/from-json.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.fromJsonString = fromJsonString;
17 exports.mergeFromJsonString = mergeFromJsonString;
18 exports.fromJson = fromJson;
19 exports.mergeFromJson = mergeFromJson;
20 exports.enumFromJson = enumFromJson;
21 exports.isEnumJson = isEnumJson;
22 const descriptors_js_1 = require("./descriptors.js");
23 const proto_int64_js_1 = require("./proto-int64.js");
24 const create_js_1 = require("./create.js");
25 const error_js_1 = require("./reflect/error.js");
26 const reflect_check_js_1 = require("./reflect/reflect-check.js");
27 const names_js_1 = require("./reflect/names.js");
28 const scalar_js_1 = require("./reflect/scalar.js");
29 const unsafe_js_1 = require("./reflect/unsafe.js");
30 const message_js_1 = require("./reflect/message.js");
31 const base64_encoding_js_1 = require("./wire/base64-encoding.js");
32 const index_js_1 = require("./wkt/index.js");
33 const extensions_js_1 = require("./extensions.js");
34 const json_js_1 = require("./wkt/json.js");
35 // bootstrap-inject google.protobuf.FeatureSet.FieldPresence.IMPLICIT: const $name = $number;
36 const IMPLICIT = 2;
37 function makeReadContext(options) {
38 return Object.assign(Object.assign({ ignoreUnknownFields: false, recursionLimit: 100 }, options), { depth: 0 });
39 }
40 /**
41 * Parse a message from a JSON string.
42 *
43 * Duplicate keys are rejected.
44 */
45 function fromJsonString(schema, json, options) {
46 return fromJson(schema, parseJsonString(json, schema.typeName), options);
47 }
48 /**
49 * Parse a message from a JSON string, merging fields into the target.
50 *
51 * Repeated fields are appended. Map entries are added, overwriting
52 * existing keys.
53 *
54 * If a message field is already present, it will be merged with the
55 * new data.
56 *
57 * Duplicate keys in the JSON are rejected, as in `fromJsonString`.
58 */
59 function mergeFromJsonString(schema, target, json, options) {
60 return mergeFromJson(schema, target, parseJsonString(json, schema.typeName), options);
61 }
62 /**
63 * Parse a message from a JSON value.
64 *
65 * Duplicate keys are rejected, but a value parsed by JSON.parse has already
66 * dropped duplicates (the last one wins). Use `fromJsonString` for strict
67 * duplicate-key checking.
68 */
69 function fromJson(schema, json, options) {
70 const message = (0, create_js_1.create)(schema);
71 readMessage(schema, message, json, options);
72 return message;
73 }
74 /**
75 * Parse a message from a JSON value, merging fields into the target.
76 *
77 * Repeated fields are appended. Map entries are added, overwriting
78 * existing keys.
79 *
80 * If a message field is already present, it will be merged with the
81 * new data.
82 *
83 * Duplicate keys are rejected as in `fromJson`; use `mergeFromJsonString`
84 * for strict checking.
85 */
86 function mergeFromJson(schema, target, json, options) {
87 if (target.$typeName !== schema.typeName &&
88 schema.fields.length > 0) {
89 throw new error_js_1.FieldError(schema.fields[0], `cannot use ${schema.fields[0]} with message ${target.$typeName}`, "ForeignFieldError");
90 }
91 readMessage(schema, target, json, options);
92 return target;
93 }
94 /**
95 * Run the compiled decoder for the message, wrapping FieldErrors with the
96 * standard error message.
97 */
98 function readMessage(schema, message, json, options) {
99 try {
100 compiledReader(schema)(message, json, makeReadContext(options));
101 }
102 catch (e) {
103 if ((0, error_js_1.isFieldError)(e)) {
104 // @ts-expect-error we use the ES2022 error CTOR option "cause" for better stack traces
105 throw new Error(`cannot decode ${e.field()} from JSON: ${e.message}`, {
106 cause: e,
107 });
108 }
109 throw e;
110 }
111 }
112 /**
113 * Parses an enum value from JSON.
114 */
115 function enumFromJson(descEnum, json) {
116 // With ignoreUnknownFields false, the converter never returns the token
117 // for ignored unknown enum values.
118 return compileEnumConverter(descEnum)(json, false);
119 }
120 /**
121 * Is the given value a JSON enum value?
122 */
123 function isEnumJson(descEnum, value) {
124 return undefined !== descEnum.values.find((v) => v.name === value);
125 }
126 const compiledReaders = new WeakMap();
127 /**
128 * Return the compiled decoder for a message, compiling it on first use.
129 */
130 function compiledReader(desc) {
131 let compiled = compiledReaders.get(desc);
132 if (compiled === undefined) {
133 compiled = compileMessage(desc);
134 }
135 return compiled;
136 }
137 function compileMessage(desc) {
138 const descString = String(desc);
139 const readWkt = compileWkt(desc);
140 if (readWkt !== undefined) {
141 // All message decoders count against the recursion limit, including
142 // well-known types with a custom JSON representation.
143 const compiled = (message, json, ctx) => {
144 if (++ctx.depth > ctx.recursionLimit) {
145 throw new Error(`cannot decode ${descString} from JSON: maximum recursion depth of ${ctx.recursionLimit} reached`);
146 }
147 readWkt(message, json, ctx);
148 ctx.depth--;
149 };
150 compiledReaders.set(desc, compiled);
151 return compiled;
152 }
153 const typeName = desc.typeName;
154 // Fields are looked up by their proto name and their JSON name.
155 const fieldsByJsonKey = new Map();
156 const compiled = (message, json, ctx) => {
157 var _a;
158 if (++ctx.depth > ctx.recursionLimit) {
159 throw new Error(`cannot decode ${descString} from JSON: maximum recursion depth of ${ctx.recursionLimit} reached`);
160 }
161 if (json == null || Array.isArray(json) || typeof json != "object") {
162 throw new Error(`cannot decode ${descString} from JSON: ${(0, reflect_check_js_1.formatVal)(json)}`);
163 }
164 const oneofSeen = new Map();
165 const fieldSeen = new Set();
166 const jsonKeys = Object.keys(json);
167 for (let i = 0; i < jsonKeys.length; i++) {
168 const jsonKey = jsonKeys[i];
169 const jsonValue = json[jsonKey];
170 const entry = fieldsByJsonKey.get(jsonKey);
171 if (entry !== undefined) {
172 const field = entry.field;
173 if (fieldSeen.has(field)) {
174 // The same field may be set by its proto name and its JSON name, or by
175 // a duplicate or unicode-escaped key that JSON.parse already collapsed.
176 // Checked before the null-skip below so that a null entry still counts.
177 throw new error_js_1.FieldError(field, "set multiple times");
178 }
179 fieldSeen.add(field);
180 if (entry.oneofScalarNullSkip && jsonValue === null) {
181 continue;
182 }
183 if (entry.oneof) {
184 const seen = oneofSeen.get(entry.oneof);
185 if (seen !== undefined) {
186 throw new error_js_1.FieldError(entry.oneof, `oneof set multiple times by ${seen.name} and ${field.name}`);
187 }
188 oneofSeen.set(entry.oneof, field);
189 }
190 entry.read(message, jsonValue, ctx);
191 }
192 else {
193 const extension = jsonKey.startsWith("[") && jsonKey.endsWith("]")
194 ? (_a = ctx.registry) === null || _a === void 0 ? void 0 : _a.getExtension(jsonKey.substring(1, jsonKey.length - 1))
195 : undefined;
196 if ((extension === null || extension === void 0 ? void 0 : extension.extendee.typeName) == typeName) {
197 const [container, field, get] = (0, extensions_js_1.createExtensionContainer)(extension);
198 compileFieldReader(field)(container[unsafe_js_1.unsafeLocal], jsonValue, ctx);
199 (0, extensions_js_1.setExtension)(message, extension, get());
200 }
201 if (extension === undefined && !ctx.ignoreUnknownFields) {
202 throw new Error(`cannot decode ${descString} from JSON: key "${jsonKey}" is unknown`);
203 }
204 }
205 }
206 ctx.depth--;
207 };
208 // Register before compiling fields, so that recursive message types
209 // resolve to this instance instead of compiling endlessly.
210 compiledReaders.set(desc, compiled);
211 for (const field of desc.fields) {
212 const entry = {
213 read: compileFieldReader(field),
214 field,
215 oneof: field.oneof,
216 oneofScalarNullSkip: field.oneof !== undefined && field.fieldKind == "scalar",
217 };
218 fieldsByJsonKey.set(field.name, entry).set(field.jsonName, entry);
219 }
220 return compiled;
221 }
222 /**
223 * Compile a decoder for a well-known type with a custom JSON representation,
224 * or return undefined for other messages. The recursion limit is enforced by
225 * the caller.
226 */
227 function compileWkt(desc) {
228 if (!desc.typeName.startsWith("google.protobuf.")) {
229 return undefined;
230 }
231 switch (desc.typeName) {
232 case "google.protobuf.Any":
233 return (message, json, ctx) => anyFromJson(message, json, ctx);
234 case "google.protobuf.Timestamp":
235 return (message, json) => timestampFromJson(message, json);
236 case "google.protobuf.Duration":
237 return (message, json) => durationFromJson(message, json);
238 case "google.protobuf.FieldMask":
239 return (message, json) => fieldMaskFromJson(message, json);
240 case "google.protobuf.Struct":
241 return (message, json, ctx) => structFromJson(message, json, ctx);
242 case "google.protobuf.Value":
243 return (message, json, ctx) => valueFromJson(message, json, ctx);
244 case "google.protobuf.ListValue":
245 return (message, json, ctx) => listValueFromJson(message, json, ctx);
246 default:
247 if ((0, index_js_1.isWrapperDesc)(desc)) {
248 const valueField = desc.fields[0];
249 const localName = valueField.localName;
250 const scalar = valueField.scalar;
251 const longAsString = valueField.longAsString;
252 const readScalar = compileScalarConverter(valueField);
253 return (message, json) => {
254 if (json === null) {
255 message[localName] = (0, scalar_js_1.scalarZeroValue)(scalar, longAsString);
256 }
257 else {
258 message[localName] = readScalar(json);
259 }
260 };
261 }
262 return undefined;
263 }
264 }
265 function compileFieldReader(field) {
266 switch (field.fieldKind) {
267 case "scalar":
268 return compileScalarFieldReader(field);
269 case "enum":
270 return compileEnumFieldReader(field);
271 case "message":
272 return compileMessageFieldReader(field);
273 case "list":
274 return compileListFieldReader(field);
275 case "map":
276 return compileMapFieldReader(field);
277 }
278 }
279 function compileScalarFieldReader(field) {
280 const readScalar = compileScalarConverter(field);
281 const localName = field.localName;
282 if (field.oneof) {
283 // JSON null for a oneof scalar member is skipped by the message decoder.
284 const oneofLocalName = field.oneof.localName;
285 return (message, json) => {
286 message[oneofLocalName] = {
287 case: localName,
288 value: readScalar(json),
289 };
290 };
291 }
292 const clear = compileClear(field);
293 return (message, json) => {
294 if (json === null) {
295 clear(message);
296 }
297 else {
298 message[localName] = readScalar(json);
299 }
300 };
301 }
302 /**
303 * Compile a function that resets the field to unset, mirroring the clear
304 * operation of the reflect API for fields that are not part of a oneof.
305 */
306 function compileClear(field) {
307 const localName = field.localName;
308 if (field.presence != IMPLICIT) {
309 // Fields with explicit presence have properties on the prototype chain
310 // for default / zero values (except for proto3). By deleting their own
311 // property, the field is reset.
312 return (message) => {
313 delete message[localName];
314 };
315 }
316 if (field.fieldKind == "enum") {
317 const zero = field.enum.values[0].number;
318 return (message) => {
319 message[localName] = zero;
320 };
321 }
322 const scalar = field.scalar;
323 const longAsString = field.longAsString;
324 return (message) => {
325 message[localName] = (0, scalar_js_1.scalarZeroValue)(scalar, longAsString);
326 };
327 }
328 function compileEnumFieldReader(field) {
329 const readEnumValue = compileEnumConverter(field.enum);
330 const checkEnum = compileEnumCheck(field.enum);
331 const localName = field.localName;
332 // Fields with enum google.protobuf.NullValue permit a Protobuf-serializable
333 // null; for all other enums, JSON null resets the field.
334 const nullResets = field.enum.typeName != "google.protobuf.NullValue";
335 if (field.oneof) {
336 const oneofLocalName = field.oneof.localName;
337 return (message, json, ctx) => {
338 if (json === null && nullResets) {
339 const oneof = message[oneofLocalName];
340 if (oneof.case === localName) {
341 message[oneofLocalName] = { case: undefined };
342 }
343 return;
344 }
345 const value = readEnumValue(json, ctx.ignoreUnknownFields);
346 if (value === tokenIgnoredUnknownEnum) {
347 return;
348 }
349 const check = checkEnum(value);
350 if (check !== true) {
351 throw new error_js_1.FieldError(field, (0, reflect_check_js_1.reasonSingular)(field, value, check));
352 }
353 message[oneofLocalName] = { case: localName, value };
354 };
355 }
356 const clear = compileClear(field);
357 return (message, json, ctx) => {
358 if (json === null && nullResets) {
359 clear(message);
360 return;
361 }
362 const value = readEnumValue(json, ctx.ignoreUnknownFields);
363 if (value === tokenIgnoredUnknownEnum) {
364 return;
365 }
366 const check = checkEnum(value);
367 if (check !== true) {
368 throw new error_js_1.FieldError(field, (0, reflect_check_js_1.reasonSingular)(field, value, check));
369 }
370 message[localName] = value;
371 };
372 }
373 function compileMessageFieldReader(field) {
374 const localName = field.localName;
375 const { toMessage, toLocal } = (0, message_js_1.localMessageMapper)(field);
376 const readChild = compiledReader(field.message);
377 // Fields with message google.protobuf.Value permit a Protobuf-serializable
378 // null; for all other messages, JSON null resets the field.
379 const nullResets = field.message.typeName != "google.protobuf.Value";
380 if (field.oneof) {
381 const oneofLocalName = field.oneof.localName;
382 return (message, json, ctx) => {
383 const oneof = message[oneofLocalName];
384 if (json === null && nullResets) {
385 if (oneof.case === localName) {
386 message[oneofLocalName] = { case: undefined };
387 }
388 return;
389 }
390 const child = toMessage(oneof.case === localName ? oneof.value : undefined);
391 readChild(child, json, ctx);
392 message[oneofLocalName] = { case: localName, value: toLocal(child) };
393 };
394 }
395 return (message, json, ctx) => {
396 if (json === null && nullResets) {
397 delete message[localName];
398 return;
399 }
400 const child = toMessage(message[localName]);
401 readChild(child, json, ctx);
402 message[localName] = toLocal(child);
403 };
404 }
405 function compileListFieldReader(field) {
406 const localName = field.localName;
407 const readItem = compileListItemReader(field);
408 return (message, json, ctx) => {
409 if (json === null) {
410 return;
411 }
412 if (!Array.isArray(json)) {
413 throw new error_js_1.FieldError(field, "expected Array, got " + (0, reflect_check_js_1.formatVal)(json));
414 }
415 const items = message[localName];
416 for (let i = 0; i < json.length; i++) {
417 const value = readItem(json[i], ctx, items.length);
418 if (value !== tokenIgnoredUnknownEnum) {
419 items.push(value);
420 }
421 }
422 };
423 }
424 /**
425 * Compile a decoder for a list item. The index is only used in errors, and
426 * accounts for previously merged items.
427 */
428 function compileListItemReader(field) {
429 switch (field.listKind) {
430 case "scalar": {
431 const parseScalar = compileScalarParse(field);
432 const checkValue = (0, reflect_check_js_1.checkScalarValue)(field.scalar);
433 const toLocal = compileScalarToLocal(field);
434 return (json, ctx, index) => {
435 if (json === null) {
436 throw new error_js_1.FieldError(field, "list item must not be null");
437 }
438 const value = parseScalar(json);
439 const check = checkValue(value);
440 if (check !== true) {
441 throw new error_js_1.FieldError(field, `list item #${index + 1}: ${(0, reflect_check_js_1.reasonSingular)(field, value, check)}`);
442 }
443 return toLocal(value);
444 };
445 }
446 case "enum": {
447 const readEnumValue = compileEnumConverter(field.enum);
448 const checkEnum = compileEnumCheck(field.enum);
449 const nullResets = field.enum.typeName != "google.protobuf.NullValue";
450 return (json, ctx, index) => {
451 if (json === null && nullResets) {
452 throw new error_js_1.FieldError(field, "list item must not be null");
453 }
454 const value = readEnumValue(json, ctx.ignoreUnknownFields);
455 if (value === tokenIgnoredUnknownEnum) {
456 return value;
457 }
458 const check = checkEnum(value);
459 if (check !== true) {
460 throw new error_js_1.FieldError(field, `list item #${index + 1}: ${(0, reflect_check_js_1.reasonSingular)(field, value, check)}`);
461 }
462 return value;
463 };
464 }
465 case "message": {
466 const { toMessage, toLocal } = (0, message_js_1.localMessageMapper)(field);
467 const readChild = compiledReader(field.message);
468 const nullResets = field.message.typeName != "google.protobuf.Value";
469 return (json, ctx) => {
470 if (json === null && nullResets) {
471 throw new error_js_1.FieldError(field, "list item must not be null");
472 }
473 const child = toMessage(undefined);
474 readChild(child, json, ctx);
475 return toLocal(child);
476 };
477 }
478 }
479 }
480 function compileMapFieldReader(field) {
481 const localName = field.localName;
482 const mapKey = field.mapKey;
483 const parseMapKey = compileMapKeyParse(mapKey);
484 const checkMapKey = (0, reflect_check_js_1.checkScalarValue)(mapKey);
485 let parseValue;
486 // Additional validation for scalar and enum values, matching the checks
487 // of the reflect API. Message values need no validation.
488 let checkValue;
489 let toLocalValue = (value) => value;
490 // Fields with google.protobuf.Value or google.protobuf.NullValue values
491 // permit a Protobuf-serializable null.
492 let nullResets = true;
493 switch (field.mapKind) {
494 case "scalar": {
495 parseValue = compileScalarParse(field);
496 checkValue = (0, reflect_check_js_1.checkScalarValue)(field.scalar);
497 toLocalValue = compileScalarToLocal(field);
498 break;
499 }
500 case "enum": {
501 const readEnumValue = compileEnumConverter(field.enum);
502 parseValue = (json, ctx) => readEnumValue(json, ctx.ignoreUnknownFields);
503 checkValue = compileEnumCheck(field.enum);
504 nullResets = field.enum.typeName != "google.protobuf.NullValue";
505 break;
506 }
507 case "message": {
508 const { toMessage, toLocal } = (0, message_js_1.localMessageMapper)(field);
509 const readChild = compiledReader(field.message);
510 nullResets = field.message.typeName != "google.protobuf.Value";
511 parseValue = (json, ctx) => {
512 const child = toMessage(undefined);
513 readChild(child, json, ctx);
514 return toLocal(child);
515 };
516 break;
517 }
518 }
519 return (message, json, ctx) => {
520 if (json === null) {
521 return;
522 }
523 if (typeof json != "object" || Array.isArray(json)) {
524 throw new error_js_1.FieldError(field, "expected object, got " + (0, reflect_check_js_1.formatVal)(json));
525 }
526 const record = message[localName];
527 const seen = new Set();
528 const jsonMapKeys = Object.keys(json);
529 for (let i = 0; i < jsonMapKeys.length; i++) {
530 const jsonMapKey = jsonMapKeys[i];
531 const jsonMapValue = json[jsonMapKey];
532 const key = parseMapKey(jsonMapKey);
533 if (seen.has(key)) {
534 throw new error_js_1.FieldError(field, `duplicate map key "${jsonMapKey}"`);
535 }
536 seen.add(key);
537 if (jsonMapValue === null && nullResets) {
538 throw new error_js_1.FieldError(field, "map value must not be null");
539 }
540 const value = parseValue(jsonMapValue, ctx);
541 if (value === tokenIgnoredUnknownEnum) {
542 continue;
543 }
544 const checkKey = checkMapKey(key);
545 if (checkKey !== true) {
546 throw new error_js_1.FieldError(field, `invalid map key: ${(0, reflect_check_js_1.reasonSingular)({ scalar: mapKey }, key, checkKey)}`);
547 }
548 if (checkValue !== undefined) {
549 const check = checkValue(value);
550 if (check !== true) {
551 throw new error_js_1.FieldError(field, `map entry ${(0, reflect_check_js_1.formatVal)(key)}: ${(0, reflect_check_js_1.reasonSingular)(field, value, check)}`);
552 }
553 }
554 // Object property keys are always strings or symbols. Assigning with a
555 // boolean, number, or bigint key implicitly converts it to a string.
556 record[key] = toLocalValue(value);
557 }
558 };
559 }
560 const tokenIgnoredUnknownEnum = Symbol();
561 /**
562 * Compile a converter from a JSON value to an enum value. JSON null returns
563 * the enum's first value. With ignoreUnknownFields false, unknown string
564 * values raise an error; with true, they return tokenIgnoredUnknownEnum.
565 * The value is not checked against the enum's values, see compileEnumCheck.
566 */
567 function compileEnumConverter(desc) {
568 const zero = desc.values[0].number;
569 const values = desc.values;
570 return (json, ignoreUnknownFields) => {
571 if (json === null) {
572 return zero;
573 }
574 switch (typeof json) {
575 case "number":
576 if (Number.isInteger(json)) {
577 return json;
578 }
579 break;
580 case "string": {
581 const value = values.find((ev) => ev.name === json);
582 if (value !== undefined) {
583 return value.number;
584 }
585 if (ignoreUnknownFields) {
586 return tokenIgnoredUnknownEnum;
587 }
588 break;
589 }
590 }
591 throw new Error(`cannot decode ${desc} from JSON: ${(0, reflect_check_js_1.formatVal)(json)}`);
592 };
593 }
594 /**
595 * Compile the check that the reflect API performs for enum values: open
596 * enums accept any int32 value, closed enums accept only declared values.
597 */
598 function compileEnumCheck(desc) {
599 if (desc.open) {
600 return (0, reflect_check_js_1.checkScalarValue)(descriptors_js_1.ScalarType.INT32);
601 }
602 const values = desc.values;
603 return (value) => values.some((v) => v.number === value);
604 }
605 /**
606 * Compile a converter from a JSON value to the local representation of a
607 * scalar, fusing JSON parsing, the validation of the reflect API, and the
608 * conversion to the local 64-bit integer representation.
609 */
610 function compileScalarConverter(field) {
611 const parseScalar = compileScalarParse(field);
612 const checkValue = (0, reflect_check_js_1.checkScalarValue)(field.scalar);
613 const toLocal = compileScalarToLocal(field);
614 return (json) => {
615 const value = parseScalar(json);
616 const check = checkValue(value);
617 if (check !== true) {
618 throw new error_js_1.FieldError(field, (0, reflect_check_js_1.reasonSingular)(field, value, check));
619 }
620 return toLocal(value);
621 };
622 }
623 /**
624 * Compile the JSON-specific parsing step for a scalar value: the special
625 * string values of float and double, string-encoded numbers, and base64
626 * bytes. Returns the input unchanged if the JSON value cannot be converted;
627 * the validation step raises an error for it.
628 */
629 function compileScalarParse(field) {
630 switch (field.scalar) {
631 // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity".
632 // Either numbers or strings are accepted. Exponent notation is also accepted.
633 case descriptors_js_1.ScalarType.DOUBLE:
634 case descriptors_js_1.ScalarType.FLOAT:
635 return (json) => {
636 if (json === "NaN")
637 return NaN;
638 if (json === "Infinity")
639 return Number.POSITIVE_INFINITY;
640 if (json === "-Infinity")
641 return Number.NEGATIVE_INFINITY;
642 if (typeof json == "number") {
643 if (Number.isNaN(json)) {
644 // NaN must be encoded with string constants
645 throw new error_js_1.FieldError(field, "unexpected NaN number");
646 }
647 if (!Number.isFinite(json)) {
648 // Infinity must be encoded with string constants
649 throw new error_js_1.FieldError(field, "unexpected infinite number");
650 }
651 return json;
652 }
653 if (typeof json == "string") {
654 if (json === "") {
655 // empty string is not a number
656 return json;
657 }
658 if (json.trim().length !== json.length) {
659 // extra whitespace
660 return json;
661 }
662 const float = Number(json);
663 if (!Number.isFinite(float)) {
664 // Infinity and NaN must be encoded with string constants
665 return json;
666 }
667 return float;
668 }
669 return json;
670 };
671 // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted.
672 case descriptors_js_1.ScalarType.INT32:
673 case descriptors_js_1.ScalarType.FIXED32:
674 case descriptors_js_1.ScalarType.SFIXED32:
675 case descriptors_js_1.ScalarType.SINT32:
676 case descriptors_js_1.ScalarType.UINT32:
677 return int32FromJson;
678 // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings.
679 // Either standard or URL-safe base64 encoding with/without paddings are accepted.
680 case descriptors_js_1.ScalarType.BYTES:
681 return (json) => {
682 if (typeof json == "string") {
683 if (json === "") {
684 return new Uint8Array(0);
685 }
686 try {
687 return (0, base64_encoding_js_1.base64Decode)(json);
688 }
689 catch (e) {
690 const message = e instanceof Error ? e.message : String(e);
691 throw new error_js_1.FieldError(field, message);
692 }
693 }
694 return json;
695 };
696 // int64, sfixed64, sint64, fixed64, uint64: The validation step accepts
697 // string and number. string, bool: no conversion.
698 default:
699 return (json) => json;
700 }
701 }
702 /**
703 * Compile the conversion of a validated scalar value to its local
704 * representation: 64-bit integers become bigint, or string with the
705 * longAsString option.
706 */
707 function compileScalarToLocal(field) {
708 const longAsString = field.fieldKind !== "map" && field.longAsString;
709 switch (field.scalar) {
710 case descriptors_js_1.ScalarType.INT64:
711 case descriptors_js_1.ScalarType.SFIXED64:
712 case descriptors_js_1.ScalarType.SINT64:
713 if (longAsString) {
714 return (value) => String(value);
715 }
716 return (value) => typeof value == "string" || typeof value == "number"
717 ? proto_int64_js_1.protoInt64.parse(value)
718 : value;
719 case descriptors_js_1.ScalarType.FIXED64:
720 case descriptors_js_1.ScalarType.UINT64:
721 if (longAsString) {
722 return (value) => String(value);
723 }
724 return (value) => typeof value == "string" || typeof value == "number"
725 ? proto_int64_js_1.protoInt64.uParse(value)
726 : value;
727 default:
728 return (value) => value;
729 }
730 }
731 /**
732 * Return a parser from a JSON value to a map key for the given key type.
733 * Canonicalizes 64-bit integers given as string, so that "01" and "1" are
734 * one key, and duplicates can raise an error.
735 * The parser returns the input if the JSON value cannot be converted.
736 */
737 function compileMapKeyParse(type) {
738 switch (type) {
739 case descriptors_js_1.ScalarType.BOOL:
740 return (jsonString) => {
741 switch (jsonString) {
742 case "true":
743 return true;
744 case "false":
745 return false;
746 }
747 return jsonString;
748 };
749 case descriptors_js_1.ScalarType.INT32:
750 case descriptors_js_1.ScalarType.FIXED32:
751 case descriptors_js_1.ScalarType.UINT32:
752 case descriptors_js_1.ScalarType.SFIXED32:
753 case descriptors_js_1.ScalarType.SINT32:
754 return int32FromJson;
755 case descriptors_js_1.ScalarType.INT64:
756 case descriptors_js_1.ScalarType.SINT64:
757 case descriptors_js_1.ScalarType.SFIXED64:
758 case descriptors_js_1.ScalarType.UINT64:
759 case descriptors_js_1.ScalarType.FIXED64:
760 return (jsonString) => /^-?0+$/.test(jsonString)
761 ? "0"
762 : jsonString.replace(/^(-?)0+(?=\d)/, "$1");
763 default:
764 // ScalarType.STRING
765 return (jsonString) => jsonString;
766 }
767 }
768 /**
769 * Try to parse a JSON value to a 32-bit integer for the reflect API.
770 *
771 * Returns the input if the JSON value cannot be converted.
772 */
773 function int32FromJson(json) {
774 if (typeof json == "string") {
775 if (json === "") {
776 // empty string is not a number
777 return json;
778 }
779 if (json.trim().length !== json.length) {
780 // extra whitespace
781 return json;
782 }
783 const num = Number(json);
784 if (Number.isNaN(num)) {
785 // not a number
786 return json;
787 }
788 return num;
789 }
790 return json;
791 }
792 /**
793 * Parse a JSON string, rejecting duplicate object keys (which JSON.parse would
794 * otherwise silently merge).
795 */
796 function parseJsonString(jsonString, typeName) {
797 let json;
798 try {
799 json = JSON.parse(jsonString);
800 }
801 catch (e) {
802 const message = e instanceof Error ? e.message : String(e);
803 throw new Error(`cannot decode message ${typeName} from JSON: ${message}`,
804 // @ts-expect-error we use the ES2022 error CTOR option "cause" for better stack traces
805 { cause: e });
806 }
807 checkDuplicateKeys(jsonString, typeName);
808 return json;
809 }
810 /**
811 * Scan a JSON string for duplicate object member names at any depth, throwing
812 * if any are found. JSON.parse() silently keeps the last of duplicate keys, so
813 * this raw-string scan is the only way to reject them. It must only be called
814 * with a string that JSON.parse() has already accepted, so it can assume the
815 * input is well-formed.
816 */
817 function checkDuplicateKeys(jsonString, typeName) {
818 // One Set of seen member names for each open object; arrays push null.
819 const stack = [];
820 // Whether the next string token is an object member name.
821 let expectKey = false;
822 let i = 0;
823 while (i < jsonString.length) {
824 switch (jsonString[i]) {
825 case "{":
826 stack.push(new Set());
827 expectKey = true;
828 i++;
829 break;
830 case "[":
831 stack.push(null);
832 expectKey = false;
833 i++;
834 break;
835 case "}":
836 case "]":
837 stack.pop();
838 expectKey = false;
839 i++;
840 break;
841 case ",":
842 expectKey = stack[stack.length - 1] != null;
843 i++;
844 break;
845 case ":":
846 expectKey = false;
847 i++;
848 break;
849 case '"': {
850 const open = i++;
851 let escaped = false;
852 while (i < jsonString.length) {
853 if (jsonString[i] == "\\") {
854 escaped = true;
855 i += 2; // skip the backslash and the character it escapes
856 continue;
857 }
858 if (jsonString[i] == '"') {
859 break;
860 }
861 i++;
862 }
863 const close = i++;
864 const seen = stack[stack.length - 1];
865 if (expectKey && seen) {
866 // Decode escapes (rare) so that, for example, a key written with a
867 // unicode escape collides with the same key written literally.
868 const name = escaped
869 ? JSON.parse(jsonString.substring(open, close + 1))
870 : jsonString.substring(open + 1, close);
871 if (seen.has(name)) {
872 throw new Error(`cannot decode message ${typeName} from JSON: duplicate object key "${name}"`);
873 }
874 seen.add(name);
875 }
876 expectKey = false;
877 break;
878 }
879 default:
880 i++;
881 break;
882 }
883 }
884 }
885 function anyFromJson(any, json, ctx) {
886 var _a;
887 if (json === null || Array.isArray(json) || typeof json != "object") {
888 throw new Error(`cannot decode message ${any.$typeName} from JSON: expected object but got ${(0, reflect_check_js_1.formatVal)(json)}`);
889 }
890 if (Object.keys(json).length == 0) {
891 return;
892 }
893 const typeUrl = json["@type"];
894 if (typeof typeUrl != "string" || typeUrl == "") {
895 throw new Error(`cannot decode message ${any.$typeName} from JSON: "@type" is empty`);
896 }
897 const typeName = typeUrl.includes("/")
898 ? typeUrl.substring(typeUrl.lastIndexOf("/") + 1)
899 : typeUrl;
900 if (!typeName.length) {
901 throw new Error(`cannot decode message ${any.$typeName} from JSON: "@type" is invalid`);
902 }
903 const desc = (_a = ctx.registry) === null || _a === void 0 ? void 0 : _a.getMessage(typeName);
904 if (!desc) {
905 throw new Error(`cannot decode message ${any.$typeName} from JSON: ${typeUrl} is not in the type registry`);
906 }
907 const message = (0, create_js_1.create)(desc);
908 if ((0, index_js_1.hasCustomJsonRepresentation)(desc) &&
909 Object.prototype.hasOwnProperty.call(json, "value")) {
910 compiledReader(desc)(message, json.value, ctx);
911 }
912 else {
913 const copy = Object.assign({}, json);
914 // biome-ignore lint/performance/noDelete: <explanation>
915 delete copy["@type"];
916 compiledReader(desc)(message, copy, ctx);
917 }
918 (0, index_js_1.anyPack)(desc, message, any);
919 }
920 function timestampFromJson(timestamp, json) {
921 if (typeof json !== "string") {
922 throw new Error(`cannot decode message ${timestamp.$typeName} from JSON: ${(0, reflect_check_js_1.formatVal)(json)}`);
923 }
924 const matches = json.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\.([0-9]{1,9}))?(?:Z|([+-][0-9][0-9]:[0-9][0-9]))$/);
925 if (!matches) {
926 throw new Error(`cannot decode message ${timestamp.$typeName} from JSON: invalid RFC 3339 string`);
927 }
928 const ms = Date.parse(
929 // biome-ignore format: want this to read well
930 matches[1] + "-" + matches[2] + "-" + matches[3] + "T" + matches[4] + ":" + matches[5] + ":" + matches[6] + (matches[8] ? matches[8] : "Z"));
931 if (Number.isNaN(ms)) {
932 throw new Error(`cannot decode message ${timestamp.$typeName} from JSON: invalid RFC 3339 string`);
933 }
934 if (ms < json_js_1.timestampMsMin || ms > json_js_1.timestampMsMax) {
935 throw new Error(`cannot decode message ${timestamp.$typeName} from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive`);
936 }
937 timestamp.seconds = proto_int64_js_1.protoInt64.parse(ms / 1000);
938 timestamp.nanos = 0;
939 if (matches[7]) {
940 timestamp.nanos =
941 parseInt("1" + matches[7] + "0".repeat(9 - matches[7].length)) -
942 1000000000;
943 }
944 }
945 function durationFromJson(duration, json) {
946 if (typeof json !== "string") {
947 throw new Error(`cannot decode message ${duration.$typeName} from JSON: ${(0, reflect_check_js_1.formatVal)(json)}`);
948 }
949 const match = json.match(/^(-?[0-9]+)(?:\.([0-9]+))?s/);
950 if (match === null) {
951 throw new Error(`cannot decode message ${duration.$typeName} from JSON: ${(0, reflect_check_js_1.formatVal)(json)}`);
952 }
953 const longSeconds = Number(match[1]);
954 if (longSeconds > json_js_1.durationSecondsMax || longSeconds < json_js_1.durationSecondsMin) {
955 throw new Error(`cannot decode message ${duration.$typeName} from JSON: ${(0, reflect_check_js_1.formatVal)(json)}`);
956 }
957 duration.seconds = proto_int64_js_1.protoInt64.parse(longSeconds);
958 if (typeof match[2] !== "string") {
959 return;
960 }
961 const nanosStr = match[2] + "0".repeat(9 - match[2].length);
962 duration.nanos = parseInt(nanosStr);
963 if (longSeconds < 0 || Object.is(longSeconds, -0)) {
964 duration.nanos = -duration.nanos;
965 }
966 }
967 function fieldMaskFromJson(fieldMask, json) {
968 if (typeof json !== "string") {
969 throw new Error(`cannot decode message ${fieldMask.$typeName} from JSON: ${(0, reflect_check_js_1.formatVal)(json)}`);
970 }
971 if (json === "") {
972 return;
973 }
974 fieldMask.paths = json.split(",").map((path) => {
975 if (path.includes("_")) {
976 throw new Error(`cannot decode message ${fieldMask.$typeName} from JSON: path names must be lowerCamelCase`);
977 }
978 return (0, names_js_1.protoSnakeCase)(path);
979 });
980 }
981 function structFromJson(struct, json, ctx) {
982 if (typeof json != "object" || json == null || Array.isArray(json)) {
983 throw new Error(`cannot decode message ${struct.$typeName} from JSON ${(0, reflect_check_js_1.formatVal)(json)}`);
984 }
985 const keys = Object.keys(json);
986 for (let i = 0; i < keys.length; i++) {
987 const key = keys[i];
988 const parsedValue = (0, create_js_1.create)(index_js_1.ValueSchema);
989 valueFromJson(parsedValue, json[key], ctx);
990 struct.fields[key] = parsedValue;
991 }
992 }
993 function valueFromJson(value, json, ctx) {
994 if (++ctx.depth > ctx.recursionLimit) {
995 throw new Error(`cannot decode ${value.$typeName} from JSON: maximum recursion depth of ${ctx.recursionLimit} reached`);
996 }
997 switch (typeof json) {
998 case "number":
999 value.kind = { case: "numberValue", value: json };
1000 break;
1001 case "string":
1002 value.kind = { case: "stringValue", value: json };
1003 break;
1004 case "boolean":
1005 value.kind = { case: "boolValue", value: json };
1006 break;
1007 case "object":
1008 if (json === null) {
1009 value.kind = { case: "nullValue", value: index_js_1.NullValue.NULL_VALUE };
1010 }
1011 else if (Array.isArray(json)) {
1012 const listValue = (0, create_js_1.create)(index_js_1.ListValueSchema);
1013 listValueFromJson(listValue, json, ctx);
1014 value.kind = { case: "listValue", value: listValue };
1015 }
1016 else {
1017 const struct = (0, create_js_1.create)(index_js_1.StructSchema);
1018 structFromJson(struct, json, ctx);
1019 value.kind = { case: "structValue", value: struct };
1020 }
1021 break;
1022 default:
1023 throw new Error(`cannot decode message ${value.$typeName} from JSON ${(0, reflect_check_js_1.formatVal)(json)}`);
1024 }
1025 ctx.depth--;
1026 return value;
1027 }
1028 function listValueFromJson(listValue, json, ctx) {
1029 if (!Array.isArray(json)) {
1030 throw new Error(`cannot decode message ${listValue.$typeName} from JSON ${(0, reflect_check_js_1.formatVal)(json)}`);
1031 }
1032 for (let i = 0; i < json.length; i++) {
1033 const value = (0, create_js_1.create)(index_js_1.ValueSchema);
1034 valueFromJson(value, json[i], ctx);
1035 listValue.values.push(value);
1036 }
1037 }