Add existing to tracked

This commit is contained in:
Jay
2026-08-11 09:53:42 -04:00
parent afe07f3055
commit ffd6e3d73c
8531 changed files with 4396230 additions and 0 deletions
+70
View File
@@ -0,0 +1,70 @@
# protobuf.js Extensions
## descriptor
Optional `descriptor.proto` support for converting reflected protobuf.js roots and objects to and from descriptor messages.
```js
import protobuf from "protobufjs";
import descriptor from "protobufjs/ext/descriptor.js";
// Convert an existing root to a FileDescriptorSet message.
const root = ...;
const set = root.toDescriptor("proto2");
// Encode descriptor buffers.
const buffer = descriptor.FileDescriptorSet.encode(set).finish();
// Convert a FileDescriptorSet message or buffer back to a root.
const decodedRoot = protobuf.Root.fromDescriptor(buffer);
```
The extension requires reflection metadata and also works with `protobufjs/light.js` when schemas are loaded from JSON or otherwise provided as reflection objects.
Importing the extension adds `.fromDescriptor(descriptor[, editionOrContext])` and `#toDescriptor([syntaxOrEdition])` methods to reflection objects and exports the bundled descriptor types from `google.protobuf`. Descriptor inputs can be decoded messages, readers, or buffers of the corresponding descriptor messages. Direct object descriptor imports accept either an edition string or a descriptor context with `edition`, `features` and `keepCase`.
The conversion covers descriptor messages that correspond to protobuf.js reflection objects: files and file sets, messages, fields and map fields, oneofs, enums, services and methods. Descriptor-only metadata such as source locations, generated-code annotations and uninterpreted options remains available through the exported descriptor message types, but is not mapped onto reflection objects. File names are inferred when generating descriptors because roots do not retain exact file/package boundaries.
## protojson
Optional ProtoJSON support for reflected message types.
> [!NOTE]
> Specialized code generation for the `pbjs` static-module target is a potential future extension. If you need this for high-throughput JSON transcoding or REST fallbacks in production, consider getting in touch and supporting the codegen and conformance work.
```js
import protobuf from "protobufjs";
import protojson from "protobufjs/ext/protojson.js";
const root = ...;
const MyType = root.lookupType("MyType");
const message = protojson.fromJson(MyType, { value: 1 });
const json = protojson.toJson(MyType, message);
```
```js
const messageFromString = protojson.fromJsonString(MyType, '{"value":1}');
const jsonString = protojson.toJsonString(MyType, messageFromString);
```
Importing the extension has no prototype side effects. Calling `protojson.install()` installs `fromJson`, `fromJsonString`, `toJson` and `toJsonString` convenience methods on `protobuf.Type.prototype`. It works with `protobufjs/light.js` when schemas are loaded from JSON or otherwise provided as reflection objects.
Unknown fields can be ignored while parsing by passing `{ ignoreUnknownFields: true }` to `fromJson` or `fromJsonString`.
## textformat
Optional Text Format support for reflected message types.
```js
import protobuf from "protobufjs";
import textformat from "protobufjs/ext/textformat.js";
const root = ...;
const MyType = root.lookupType("MyType");
const message = textformat.fromText(MyType, "value: 1");
const text = textformat.toText(MyType, message);
```
Importing the extension has no prototype side effects. Calling `textformat.install()` installs `fromText` and `toText` convenience methods on `protobuf.Type.prototype`. It works with `protobufjs/light.js` when schemas are loaded from JSON or otherwise provided as reflection objects.
Unknown fields can be printed with numeric field names by passing `{ unknowns: true }` to `toText`.
+4
View File
@@ -0,0 +1,4 @@
protobufjs/ext/debug
=========================
Experimental debugging extension.
+71
View File
@@ -0,0 +1,71 @@
"use strict";
var protobuf = require("../..");
/**
* Debugging utility functions. Only present in debug builds.
* @namespace
*/
var debug = protobuf.debug = module.exports = {};
var codegen = protobuf.util.codegen;
var debugFnRe = /function ([^(]+)\(([^)]*)\) {/g;
// Counts number of calls to any generated function
function codegen_debug() {
codegen_debug.supported = codegen.supported;
codegen_debug.verbose = codegen.verbose;
var gen = codegen.apply(null, Array.prototype.slice.call(arguments));
gen.str = (function(str) { return function str_debug() {
return str.apply(null, Array.prototype.slice.call(arguments)).replace(debugFnRe, "function $1($2) {\n\t$1.calls=($1.calls|0)+1");
};})(gen.str);
return gen;
}
/**
* Returns a list of unused types within the specified root.
* @param {NamespaceBase} ns Namespace to search
* @returns {Type[]} Unused types
*/
debug.unusedTypes = function unusedTypes(ns) {
/* istanbul ignore if */
if (!(ns instanceof protobuf.Namespace))
throw TypeError("ns must be a Namespace");
/* istanbul ignore if */
if (!ns.nested)
return [];
var unused = [];
for (var names = Object.keys(ns.nested), i = 0; i < names.length; ++i) {
var nested = ns.nested[names[i]];
if (nested instanceof protobuf.Type) {
var calls = (nested.encode.calls|0)
+ (nested.decode.calls|0)
+ (nested.verify.calls|0)
+ (nested.toObject.calls|0)
+ (nested.fromObject.calls|0);
if (!calls)
unused.push(nested);
} else if (nested instanceof protobuf.Namespace)
Array.prototype.push.apply(unused, unusedTypes(nested));
}
return unused;
};
/**
* Enables debugging extensions.
* @returns {undefined}
*/
debug.enable = function enable() {
protobuf.util.codegen = codegen_debug;
};
/**
* Disables debugging extensions.
* @returns {undefined}
*/
debug.disable = function disable() {
protobuf.util.codegen = codegen;
};
+87
View File
@@ -0,0 +1,87 @@
import * as $protobuf from "..";
import {
IDescriptorProto,
IDescriptorContext,
IEnumDescriptorProto,
IFieldDescriptorProto,
IFileDescriptorSet,
IMethodDescriptorProto,
IOneofDescriptorProto,
IServiceDescriptorProto
} from "./descriptor.generated";
export * from "./descriptor.generated";
type DescriptorInput<T> = T | $protobuf.Reader | Uint8Array;
declare module ".." {
namespace Root {
/** Creates a root from a descriptor set. */
function fromDescriptor(descriptor: DescriptorInput<IFileDescriptorSet>, options?: { keepCase?: boolean }): $protobuf.Root;
}
interface Root {
/** Converts this root to a descriptor set. */
toDescriptor(edition?: string): $protobuf.Message<IFileDescriptorSet> & IFileDescriptorSet;
}
namespace Type {
/** Creates a type from a descriptor. */
function fromDescriptor(descriptor: DescriptorInput<IDescriptorProto>, editionOrContext?: string | IDescriptorContext): $protobuf.Type;
}
interface Type {
/** Converts this type to a descriptor. */
toDescriptor(edition?: string): $protobuf.Message<IDescriptorProto> & IDescriptorProto;
}
namespace Field {
/** Creates a field from a descriptor. */
function fromDescriptor(descriptor: DescriptorInput<IFieldDescriptorProto>, editionOrContext?: string | IDescriptorContext): $protobuf.Field;
}
interface Field {
/** Converts this field to a descriptor. */
toDescriptor(edition?: string): $protobuf.Message<IFieldDescriptorProto> & IFieldDescriptorProto;
}
namespace Enum {
/** Creates an enum from a descriptor. */
function fromDescriptor(descriptor: DescriptorInput<IEnumDescriptorProto>, editionOrContext?: string | IDescriptorContext): $protobuf.Enum;
}
interface Enum {
/** Converts this enum to a descriptor. */
toDescriptor(): $protobuf.Message<IEnumDescriptorProto> & IEnumDescriptorProto;
}
namespace OneOf {
/** Creates a oneof from a descriptor. */
function fromDescriptor(descriptor: DescriptorInput<IOneofDescriptorProto>, editionOrContext?: string | IDescriptorContext): $protobuf.OneOf;
}
interface OneOf {
/** Converts this oneof to a descriptor. */
toDescriptor(): $protobuf.Message<IOneofDescriptorProto> & IOneofDescriptorProto;
}
namespace Service {
/** Creates a service from a descriptor. */
function fromDescriptor(descriptor: DescriptorInput<IServiceDescriptorProto>, editionOrContext?: string | IDescriptorContext): $protobuf.Service;
}
interface Service {
/** Converts this service to a descriptor. */
toDescriptor(): $protobuf.Message<IServiceDescriptorProto> & IServiceDescriptorProto;
}
namespace Method {
/** Creates a method from a descriptor. */
function fromDescriptor(descriptor: DescriptorInput<IMethodDescriptorProto>, editionOrContext?: string | IDescriptorContext): $protobuf.Method;
}
interface Method {
/** Converts this method to a descriptor. */
toDescriptor(): $protobuf.Message<IMethodDescriptorProto> & IMethodDescriptorProto;
}
}
+417
View File
@@ -0,0 +1,417 @@
// DO NOT EDIT! This is a generated file. Edit the source file instead and regenerate.
import * as $protobuf from "..";
/** Reflected file descriptor set. */
export const FileDescriptorSet: $protobuf.Type;
/** Reflected file descriptor proto. */
export const FileDescriptorProto: $protobuf.Type;
/** Reflected descriptor proto. */
export const DescriptorProto: $protobuf.Type & {
ExtensionRange: $protobuf.Type,
ReservedRange: $protobuf.Type
};
/** Reflected field descriptor proto. */
export const FieldDescriptorProto: $protobuf.Type & {
Label: $protobuf.Enum,
Type: $protobuf.Enum
};
/** Reflected oneof descriptor proto. */
export const OneofDescriptorProto: $protobuf.Type;
/** Reflected enum descriptor proto. */
export const EnumDescriptorProto: $protobuf.Type;
/** Reflected service descriptor proto. */
export const ServiceDescriptorProto: $protobuf.Type;
/** Reflected enum value descriptor proto. */
export const EnumValueDescriptorProto: $protobuf.Type;
/** Reflected method descriptor proto. */
export const MethodDescriptorProto: $protobuf.Type;
/** Reflected file options. */
export const FileOptions: $protobuf.Type & {
OptimizeMode: $protobuf.Enum
};
/** Reflected message options. */
export const MessageOptions: $protobuf.Type;
/** Reflected field options. */
export const FieldOptions: $protobuf.Type & {
CType: $protobuf.Enum,
JSType: $protobuf.Enum
};
/** Reflected oneof options. */
export const OneofOptions: $protobuf.Type;
/** Reflected enum options. */
export const EnumOptions: $protobuf.Type;
/** Reflected enum value options. */
export const EnumValueOptions: $protobuf.Type;
/** Reflected service options. */
export const ServiceOptions: $protobuf.Type;
/** Reflected method options. */
export const MethodOptions: $protobuf.Type;
/** Reflected feature set. */
export const FeatureSet: $protobuf.Type & {
FieldPresence: $protobuf.Enum,
EnumType: $protobuf.Enum,
RepeatedFieldEncoding: $protobuf.Enum,
Utf8Validation: $protobuf.Enum,
MessageEncoding: $protobuf.Enum,
JsonFormat: $protobuf.Enum,
EnforceNamingStyle: $protobuf.Enum,
VisibilityFeature: $protobuf.Type
};
/** Reflected feature set defaults. */
export const FeatureSetDefaults: $protobuf.Type & {
FeatureSetEditionDefault: $protobuf.Type
};
/** Reflected uninterpretet option. */
export const UninterpretedOption: $protobuf.Type & {
NamePart: $protobuf.Type
};
/** Reflected source code info. */
export const SourceCodeInfo: $protobuf.Type & {
Location: $protobuf.Type
};
/** Reflected generated code info. */
export const GeneratedCodeInfo: $protobuf.Type & {
Annotation: $protobuf.Type
};
/** Properties of a FileDescriptorSet message. */
export interface IFileDescriptorSet {
/** Files */
file: IFileDescriptorProto[];
}
/** Properties of a FileDescriptorProto message. */
export interface IFileDescriptorProto {
/** File name */
name?: string;
/** Package */
package?: string;
/** Not supported */
dependency?: any;
/** Not supported */
publicDependency?: any;
/** Not supported */
weakDependency?: any;
/** Nested message types */
messageType?: IDescriptorProto[];
/** Nested enums */
enumType?: IEnumDescriptorProto[];
/** Nested services */
service?: IServiceDescriptorProto[];
/** Nested extension fields */
extension?: IFieldDescriptorProto[];
/** Options */
options?: IFileOptions;
/** Not supported */
sourceCodeInfo?: any;
/** Syntax */
syntax?: string;
/** Edition */
edition?: IEdition;
}
/** Values of the Edition enum. */
export type IEdition = number;
/** Properties of a FileOptions message. */
export interface IFileOptions {
javaPackage?: string;
javaOuterClassname?: string;
javaMultipleFiles?: boolean;
javaGenerateEqualsAndHash?: boolean;
javaStringCheckUtf8?: boolean;
optimizeFor?: IFileOptionsOptimizeMode;
goPackage?: string;
ccGenericServices?: boolean;
javaGenericServices?: boolean;
pyGenericServices?: boolean;
deprecated?: boolean;
ccEnableArenas?: boolean;
objcClassPrefix?: string;
csharpNamespace?: string;
}
/** Values of he FileOptions.OptimizeMode enum. */
export type IFileOptionsOptimizeMode = number;
/** Descriptor context. */
export interface IDescriptorContext {
/** Syntax or edition to use for direct object descriptor imports */
edition?: string;
/** File-level features to apply for direct object descriptor imports */
features?: IFeatureSet;
/** Uses proto field names as reflected field names */
keepCase?: boolean;
}
/** Properties of a DescriptorProto message. */
export interface IDescriptorProto {
/** Message type name */
name?: string;
/** Fields */
field?: IFieldDescriptorProto[];
/** Extension fields */
extension?: IFieldDescriptorProto[];
/** Nested message types */
nestedType?: IDescriptorProto[];
/** Nested enums */
enumType?: IEnumDescriptorProto[];
/** Extension ranges */
extensionRange?: IDescriptorProtoExtensionRange[];
/** Oneofs */
oneofDecl?: IOneofDescriptorProto[];
/** Not supported */
options?: IMessageOptions;
/** Reserved ranges */
reservedRange?: IDescriptorProtoReservedRange[];
/** Reserved names */
reservedName?: string[];
}
/** Properties of a MessageOptions message. */
export interface IMessageOptions {
/** Whether this message is a map entry */
mapEntry?: boolean;
}
/** Properties of an ExtensionRange message. */
export interface IDescriptorProtoExtensionRange {
/** Start field id */
start?: number;
/** End field id */
end?: number;
}
/** Properties of a ReservedRange message. */
export interface IDescriptorProtoReservedRange {
/** Start field id */
start?: number;
/** End field id */
end?: number;
}
/** Properties of a FieldDescriptorProto message. */
export interface IFieldDescriptorProto {
/** Field name */
name?: string;
/** Field id */
number?: number;
/** Field rule */
label?: IFieldDescriptorProtoLabel;
/** Field basic type */
type?: IFieldDescriptorProtoType;
/** Field type name */
typeName?: string;
/** Extended type name */
extendee?: string;
/** Literal default value */
defaultValue?: string;
/** Oneof index if part of a oneof */
oneofIndex?: number;
/** JSON name (lowerCamelCase) */
jsonName?: string;
/** Field options */
options?: IFieldOptions;
/** Whether this is a proto3 optional field */
proto3Optional?: boolean;
}
/** Values of the FieldDescriptorProto.Label enum. */
export type IFieldDescriptorProtoLabel = number;
/** Values of the FieldDescriptorProto.Type enum. */
export type IFieldDescriptorProtoType = number;
/** Properties of a FieldOptions message. */
export interface IFieldOptions {
/** Whether packed or not (defaults to `false` for proto2 and `true` for proto3) */
packed?: boolean;
/** JavaScript value type (not used by protobuf.js) */
jstype?: IFieldOptionsJSType;
}
/** Values of the FieldOptions.JSType enum. */
export type IFieldOptionsJSType = number;
/** Properties of an EnumDescriptorProto message. */
export interface IEnumDescriptorProto {
/** Enum name */
name?: string;
/** Enum values */
value?: IEnumValueDescriptorProto[];
/** Enum options */
options?: IEnumOptions;
}
/** Properties of an EnumValueDescriptorProto message. */
export interface IEnumValueDescriptorProto {
/** Name */
name?: string;
/** Value */
number?: number;
/** Enum value options */
options?: IEnumValueOptions;
}
/** Properties of an EnumValueOptions message. */
export interface IEnumValueOptions {
deprecated?: boolean;
features?: IFeatureSet;
debugRedact?: boolean;
featureSupport?: any;
uninterpretedOption?: any[];
}
/** Properties of an EnumOptions message. */
export interface IEnumOptions {
/** Whether aliases are allowed */
allowAlias?: boolean;
deprecated?: boolean;
}
/** Properties of a FeatureSet message. */
export interface IFeatureSet {
fieldPresence?: number;
enumType?: number;
repeatedFieldEncoding?: number;
utf8Validation?: number;
messageEncoding?: number;
jsonFormat?: number;
enforceNamingStyle?: number;
defaultSymbolVisibility?: number;
}
/** Properties of a OneofDescriptorProto message. */
export interface IOneofDescriptorProto {
/** Oneof name */
name?: string;
/** Oneof options */
options?: IOneofOptions;
}
/** Properties of a OneofOptions message. */
export interface IOneofOptions {
features?: IFeatureSet;
uninterpretedOption?: any[];
}
/** Properties of a ServiceDescriptorProto message. */
export interface IServiceDescriptorProto {
/** Service name */
name?: string;
/** Methods */
method?: IMethodDescriptorProto[];
/** Options */
options?: IServiceOptions;
}
/** Properties of a ServiceOptions message. */
export interface IServiceOptions {
deprecated?: boolean;
}
/** Properties of a MethodDescriptorProto message. */
export interface IMethodDescriptorProto {
/** Method name */
name?: string;
/** Request type name */
inputType?: string;
/** Response type name */
outputType?: string;
/** Not supported */
options?: IMethodOptions;
/** Whether requests are streamed */
clientStreaming?: boolean;
/** Whether responses are streamed */
serverStreaming?: boolean;
}
/** Properties of a MethodOptions message. */
export interface IMethodOptions {
deprecated?: boolean;
}
+1356
View File
File diff suppressed because it is too large Load Diff
+5
View File
@@ -0,0 +1,5 @@
# protobufjs/ext/descriptor
This directory is kept as a backwards-compatible shim for `protobufjs/ext/descriptor` and may be removed in a future major release.
The descriptor extension documentation now lives in [../README.md](../README.md#descriptor).
+2
View File
@@ -0,0 +1,2 @@
import * as $protobuf from "../..";
import Long = require("long");
+2
View File
@@ -0,0 +1,2 @@
"use strict";
module.exports = require("../descriptor");
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.
+20
View File
@@ -0,0 +1,20 @@
import * as $protobuf from "..";
import { IProtoJsonOptions } from "./protojson.generated";
export * from "./protojson.generated";
declare module ".." {
interface Type {
/** Installed by `protojson.install()`. Parses an already-parsed ProtoJSON value. */
fromJson(json: any, options?: IProtoJsonOptions): $protobuf.Message<{}>;
/** Installed by `protojson.install()`. Parses ProtoJSON text. */
fromJsonString(json: string, options?: IProtoJsonOptions): $protobuf.Message<{}>;
/** Installed by `protojson.install()`. Formats a message as ProtoJSON. */
toJson(message: ($protobuf.Message<{}>|{ [k: string]: any }), options?: IProtoJsonOptions): any;
/** Installed by `protojson.install()`. Formats a message as ProtoJSON text. */
toJsonString(message: ($protobuf.Message<{}>|{ [k: string]: any }), options?: IProtoJsonOptions): string;
}
}
+49
View File
@@ -0,0 +1,49 @@
// DO NOT EDIT! This is a generated file. Edit the source file instead and regenerate.
import * as $protobuf from "..";
/** ProtoJSON conversion options. */
export interface IProtoJsonOptions {
/** Ignores unknown object members and unrecognized enum names while parsing. */
ignoreUnknownFields?: boolean;
}
/**
* Parses a message from an already-parsed ProtoJSON value using the specified reflected type.
* @param type Reflected message type
* @param json Already-parsed ProtoJSON value
* @param [options] Conversion options
* @returns Message instance
*/
export function fromJson(type: $protobuf.Type, json: any, options?: IProtoJsonOptions): $protobuf.Message<{}>;
/**
* Parses a message from ProtoJSON text using the specified reflected type.
* @param type Reflected message type
* @param json ProtoJSON text
* @param [options] Conversion options
* @returns Message instance
*/
export function fromJsonString(type: $protobuf.Type, json: string, options?: IProtoJsonOptions): $protobuf.Message<{}>;
/**
* Formats a message as ProtoJSON using the specified reflected type.
* @param type Reflected message type
* @param message Message instance or plain object
* @param [options] Conversion options
* @returns ProtoJSON value (object, array, string, number, boolean or null)
*/
export function toJson(type: $protobuf.Type, message: ($protobuf.Message<{}>|{ [k: string]: any }), options?: IProtoJsonOptions): any;
/**
* Formats a message as ProtoJSON text using the specified reflected type.
* @param type Reflected message type
* @param message Message instance or plain object
* @param [options] Conversion options
* @returns ProtoJSON text
*/
export function toJsonString(type: $protobuf.Type, message: ($protobuf.Message<{}>|{ [k: string]: any }), options?: IProtoJsonOptions): string;
/** Installs reflected {@link Type} convenience methods. */
export function install(): void;
+951
View File
@@ -0,0 +1,951 @@
// Copyright 2021 Google LLC
// Copyright 2026 The protobuf.js Authors
//
// 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.
// Derived from proto3-json-serializer v3.0.4 and modified by The protobuf.js Authors.
"use strict";
var protobuf = require("../light");
/* global BigInt */
var Type = protobuf.Type,
Enum = protobuf.Enum,
util = protobuf.util;
var protojson = protobuf.protojson = module.exports = {};
function isExtension(field) {
return Boolean(field.declaringField) || field.name.charAt(0) === ".";
}
function extensionName(field) {
var df = field.declaringField || field,
full = df.fullName.charAt(0) === "." ? df.fullName.slice(1) : df.fullName;
return "[" + (df.protoName ? full.replace(/[^.]+$/, df.protoName) : full) + "]";
}
function indexField(index, key, field, type) {
var existing = index[key];
if (existing !== undefined && existing !== field)
throw Error(type.fullName + ": duplicate ProtoJSON field name " + JSON.stringify(key));
index[key] = field;
}
function fieldsByJsonName(type) {
if (type._fieldsByJsonName)
return type._fieldsByJsonName;
var index = Object.create(null),
fields = type.fieldsArray,
i = 0;
for (; i < fields.length; ++i) {
var field = fields[i].resolve();
if (isExtension(field))
indexField(index, extensionName(field), field, type);
else {
indexField(index, field.name, field, type);
indexField(index, field.jsonName, field, type);
indexField(index, field.protoName, field, type);
}
}
type._fieldsByJsonName = index;
return index;
}
// --- reading scalars ---
var INT_RANGE = {
int32: ["-2147483648", "2147483647"],
sint32: ["-2147483648", "2147483647"],
sfixed32: ["-2147483648", "2147483647"],
uint32: ["0", "4294967295"],
fixed32: ["0", "4294967295"],
int64: ["-9223372036854775808", "9223372036854775807"],
sint64: ["-9223372036854775808", "9223372036854775807"],
sfixed64: ["-9223372036854775808", "9223372036854775807"],
uint64: ["0", "18446744073709551615"],
fixed64: ["0", "18446744073709551615"]
};
var LONG_TYPE = { int64: 1, uint64: 1, sint64: 1, fixed64: 1, sfixed64: 1 };
var MAX_FLOAT = 3.4028234663852886e38;
var hasBigInt = typeof BigInt !== "undefined";
var NUMERIC_RE = /^[+-]?(?:[0-9]*\.[0-9]+|[0-9]+\.?)(?:[eE][+-]?[0-9]+)?$/;
var SKIP = {};
function invalid(name, value, what) {
return Error(name + ": " + what + ": " + JSON.stringify(value));
}
function parseIntegerString(value, type, name) {
var str;
if (typeof value === "number") {
if (!isFinite(value) || Math.floor(value) !== value)
throw invalid(name, value, "not an integer");
str = numberToIntString(value);
} else if (typeof value === "string") {
if (value.length === 0 || /^\s|\s$/.test(value))
throw invalid(name, value, "invalid integer");
if (/^[+-]?[0-9]+$/.test(value))
str = value;
else if (NUMERIC_RE.test(value)) {
var num = Number(value);
if (!isFinite(num) || Math.floor(num) !== num)
throw invalid(name, value, "not an integer");
str = numberToIntString(num);
} else
throw invalid(name, value, "invalid integer");
} else
throw invalid(name, value, "expected integer (number or string)");
var range = INT_RANGE[type];
if (LONG_TYPE[type]) {
if (hasBigInt) {
var big = BigInt(str);
if (big < BigInt(range[0]) || big > BigInt(range[1]))
throw invalid(name, value, "out of range for " + type);
}
} else if (Number(str) < Number(range[0]) || Number(str) > Number(range[1]))
throw invalid(name, value, "out of range for " + type);
return str;
}
function parseMapIntegerKey(key, type, name) {
var unsigned = type === "uint32" || type === "fixed32" || type === "uint64" || type === "fixed64";
if (!(unsigned ? /^[0-9]+$/ : /^-?[0-9]+$/).test(key))
throw invalid(name, key, "invalid " + type + " map key");
if (hasBigInt) {
var big = BigInt(key),
range = INT_RANGE[type];
if (big < BigInt(range[0]) || big > BigInt(range[1]))
throw invalid(name, key, "out of range for " + type + " map key");
return big.toString();
}
parseIntegerString(key, type, name);
if (LONG_TYPE[type]) {
var normalized = key.replace(/^-?0+(?=\d)/, key.charAt(0) === "-" ? "-" : "");
return normalized === "-0" ? "0" : normalized;
}
return String(Number(key));
}
function numberToIntString(num) {
if (num >= -9007199254740991 && num <= 9007199254740991)
return String(num);
return num.toFixed(0);
}
function parseFloat32Or64(value, isFloat, name) {
var num;
if (typeof value === "number") {
if (!isFinite(value))
throw invalid(name, value, "number out of range");
num = value;
} else if (value === "NaN")
return NaN;
else if (value === "Infinity")
return Infinity;
else if (value === "-Infinity")
return -Infinity;
else if (typeof value === "string") {
if (value.length === 0 || /^\s|\s$/.test(value) || !NUMERIC_RE.test(value))
throw invalid(name, value, "invalid number");
num = Number(value);
if (!isFinite(num))
throw invalid(name, value, "invalid number");
} else
throw invalid(name, value, "expected number");
if (isFloat && Math.abs(num) > MAX_FLOAT)
throw invalid(name, value, "out of range for float");
return num;
}
function validateUtf16(value, name) {
for (var i = 0; i < value.length; ++i) {
var c = value.charCodeAt(i);
if (c >= 0xD800 && c <= 0xDBFF) {
var next = value.charCodeAt(i + 1);
if (!(next >= 0xDC00 && next <= 0xDFFF))
throw invalid(name, value, "unpaired high surrogate");
++i;
} else if (c >= 0xDC00 && c <= 0xDFFF)
throw invalid(name, value, "unpaired low surrogate");
}
}
function parseBytes(value, name) {
if (typeof value !== "string")
throw invalid(name, value, "expected base64 string");
var s = value.replace(/-/g, "+").replace(/_/g, "/");
while (s.length % 4)
s += "=";
var buffer = util.newBuffer(util.base64.length(s));
util.base64.decode(s, buffer, 0);
return buffer;
}
function longFromString(str, unsigned) {
return util.Long ? util.Long.fromString(str, unsigned) : parseInt(str, 10);
}
function readScalar(type, value, name) {
switch (type) {
case "int32": case "sint32": case "sfixed32":
case "uint32": case "fixed32":
return Number(parseIntegerString(value, type, name));
case "int64": case "sint64": case "sfixed64":
return longFromString(parseIntegerString(value, type, name), false);
case "uint64": case "fixed64":
return longFromString(parseIntegerString(value, type, name), true);
case "float":
return parseFloat32Or64(value, true, name);
case "double":
return parseFloat32Or64(value, false, name);
case "bool":
if (typeof value !== "boolean")
throw invalid(name, value, "expected boolean");
return value;
case "string":
if (typeof value !== "string")
throw invalid(name, value, "expected string");
validateUtf16(value, name);
return value;
case "bytes":
return parseBytes(value, name);
default:
throw Error(name + ": unsupported scalar type " + type);
}
}
function readEnum(enm, value, name, options) {
if (typeof value === "string") {
var num = enm.values[value];
if (num !== undefined)
return num;
if (options.ignoreUnknownFields)
return SKIP;
throw invalid(name, value, "unknown enum value");
}
if (typeof value === "number") {
if ((value | 0) !== value)
throw invalid(name, value, "invalid enum number");
if (enm._features.enum_type === "CLOSED" && enm.valuesById[value] === undefined)
throw invalid(name, value, "unknown enum value");
return value;
}
if (value === null && enm.fullName === ".google.protobuf.NullValue")
return 0;
throw invalid(name, value, "expected enum string or number");
}
function readMapKey(field, key) {
switch (field.keyType) {
case "bool":
if (key !== "true" && key !== "false")
throw invalid(field.fullName, key, "invalid bool map key");
return key;
case "string":
validateUtf16(key, field.fullName);
return key;
case "int32": case "sint32": case "sfixed32":
case "uint32": case "fixed32":
case "int64": case "sint64": case "sfixed64":
case "uint64": case "fixed64":
return parseMapIntegerKey(key, field.keyType, field.fullName);
default:
throw Error(field.fullName + ": unsupported map key type " + field.keyType);
}
}
// --- reading messages ---
function readField(field, value, options, depth) {
if (field.map) {
if (value === null || typeof value !== "object" || Array.isArray(value))
throw invalid(field.fullName, value, "expected object for map");
var map = Object.create(null), k;
for (k in value)
if (hasOwn(value, k)) {
var mk = readMapKey(field, k),
mv = readSingular(field, value[k], options, depth);
if (mv !== SKIP) {
if (hasOwn(map, mk))
throw invalid(field.fullName, k, "duplicate map key");
map[mk] = mv;
}
}
return map;
}
if (field.repeated) {
if (!Array.isArray(value))
throw invalid(field.fullName, value, "expected array");
var arr = [], i = 0;
for (; i < value.length; ++i) {
if (value[i] === null && !isValueType(field.resolvedType) && !isNullValueType(field.resolvedType))
throw invalid(field.fullName, null, "null element");
var el = readSingular(field, value[i], options, depth);
if (el !== SKIP)
arr.push(el);
}
return arr;
}
return readSingular(field, value, options, depth);
}
function readSingular(field, value, options, depth) {
if (field.resolvedType instanceof Type)
return readMessage(field.resolvedType, value, options, depth + 1);
if (field.resolvedType instanceof Enum)
return readEnum(field.resolvedType, value, field.fullName, options);
return readScalar(field.type, value, field.fullName);
}
function isValueType(type) {
return type instanceof Type && type.fullName === ".google.protobuf.Value";
}
function isNullValueType(type) {
return type instanceof Enum && type.fullName === ".google.protobuf.NullValue";
}
function isImplicitDefault(field, value) {
if (field.hasPresence || field.repeated || field.map || field.resolvedType instanceof Type)
return false;
if (field.resolvedType instanceof Enum)
return value === 0;
switch (field.type) {
case "bool": return value === false;
case "string": return value === "";
case "bytes": return value == null || value.length === 0;
default: return longToNumber(value) === 0;
}
}
function readMessage(type, value, options, depth) {
if (depth > util.recursionLimit)
throw Error("max depth exceeded");
var wkt = WKT_FROM[type.fullName];
if (wkt)
return wkt(type, value, options, depth);
if (value === null || typeof value !== "object" || Array.isArray(value))
throw invalid(type.fullName, value, "expected object");
var index = fieldsByJsonName(type),
out = {},
seenFields = Object.create(null),
seenOneofs = Object.create(null),
key;
for (key in value) {
if (!hasOwn(value, key))
continue;
var field = index[key];
if (field === undefined) {
if (options.ignoreUnknownFields)
continue;
throw invalid(type.fullName, key, "unknown field");
}
if (seenFields[field.name])
throw invalid(type.fullName, key, "duplicate field");
seenFields[field.name] = true;
var fv = value[key], fieldValue;
if (fv === null) {
if (isValueType(field.resolvedType))
fieldValue = { nullValue: 0 };
else if (field.resolvedType instanceof Enum && field.resolvedType.fullName === ".google.protobuf.NullValue")
fieldValue = 0;
else
continue;
} else
fieldValue = readField(field, fv, options, depth);
if (fieldValue === SKIP)
continue;
if (field.partOf) {
if (seenOneofs[field.partOf.name])
throw Error(type.fullName + ": multiple values for oneof " + field.partOf.name);
seenOneofs[field.partOf.name] = true;
}
if (!isImplicitDefault(field, fieldValue))
out[field.name] = fieldValue;
}
return out;
}
// --- writing messages ---
function hasOwn(o, k) {
return o != null && Object.prototype.hasOwnProperty.call(o, k);
}
function setOwn(o, k, v) {
if (k === "__proto__")
util.makeProp(o, k);
o[k] = v;
}
function wktFieldName(type, name) {
var field = fieldsByJsonName(type)[name];
return field ? field.name : name;
}
function wktFieldValue(type, message, name) {
var field = fieldsByJsonName(type)[name];
if (!field)
return message && message[name];
if (hasOwn(message, field.name))
return message[field.name];
if (hasOwn(message, field.protoName))
return message[field.protoName];
if (hasOwn(message, field.jsonName))
return message[field.jsonName];
return undefined;
}
function writeScalar(type, value) {
switch (type) {
case "int64": case "sint64": case "sfixed64":
case "uint64": case "fixed64":
return value == null ? "0" : String(value);
case "float": case "double":
return typeof value === "number" && !isFinite(value) ? String(value) : value;
case "bytes":
return value == null ? "" : util.base64.encode(value, 0, value.length);
default:
return value;
}
}
function writeSingular(field, value, options, depth) {
if (field.resolvedType instanceof Type)
return toJsonValue(field.resolvedType, value, options, depth + 1);
if (field.resolvedType instanceof Enum) {
if (field.resolvedType.fullName === ".google.protobuf.NullValue")
return null;
var name = field.resolvedType.valuesById[value];
return name === undefined ? value : name;
}
return writeScalar(field.type, value);
}
function toJsonValue(type, message, options, depth) {
if (depth > util.recursionLimit)
throw Error("max depth exceeded");
var wkt = WKT_TO[type.fullName];
if (wkt)
return wkt(type, message, options, depth);
var out = {},
fields = type.fieldsArray,
i = 0;
for (; i < fields.length; ++i) {
var field = fields[i].resolve(),
value = message[field.name];
if (value == null)
continue;
var key = isExtension(field) ? extensionName(field) : field.jsonName;
if (field.map) {
var mk = Object.keys(value);
if (!mk.length)
continue;
var longKey = LONG_TYPE[field.keyType],
unsignedKey = field.keyType === "uint64" || field.keyType === "fixed64",
mo = {}, ki = 0;
for (; ki < mk.length; ++ki) {
var outKey = longKey ? util.longFromKey(mk[ki], unsignedKey).toString() : mk[ki];
setOwn(mo, outKey, writeSingular(field, value[mk[ki]], options, depth));
}
setOwn(out, key, mo);
} else if (field.repeated) {
if (!value.length)
continue;
var arr = new Array(value.length), j = 0;
for (; j < value.length; ++j)
arr[j] = writeSingular(field, value[j], options, depth);
setOwn(out, key, arr);
} else {
if (!hasOwn(message, field.name) || isImplicitDefault(field, value))
continue;
setOwn(out, key, writeSingular(field, value, options, depth));
}
}
return out;
}
// --- well-known types ---
function longToNumber(value) {
if (value == null) return 0;
if (typeof value === "number") return value;
if (typeof value.toNumber === "function") return value.toNumber();
return Number(value) || 0;
}
function nanosToString(nanos) {
var str = String(nanos < 0 ? -nanos : nanos);
while (str.length < 9) str = "0" + str;
while (str.length > 3 && str.slice(str.length - 3) === "000") str = str.slice(0, str.length - 3);
return str;
}
function fracToNanos(frac) {
while (frac.length < 9) frac += "0";
return parseInt(frac.slice(0, 9), 10);
}
function daysInMonth(year, month) {
switch (month) {
case 2:
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : 28;
case 4:
case 6:
case 9:
case 11:
return 30;
default:
return 31;
}
}
function camelToSnake(path) {
return path.replace(/[A-Z]/g, function ($0) { return "_" + $0.toLowerCase(); });
}
var WKT_FROM = {};
var WKT_TO = {};
WKT_FROM[".google.protobuf.Duration"] = function (type, value) {
if (typeof value !== "string")
throw invalid(type.fullName, value, "expected duration string");
var match = /^(-)?([0-9]+)(?:\.([0-9]{1,9}))?s$/.exec(value);
if (!match)
throw invalid(type.fullName, value, "invalid duration");
var sign = match[1] ? -1 : 1,
seconds = parseInt(match[2], 10) * sign || 0,
nanos = match[3] ? fracToNanos(match[3]) * sign || 0 : 0;
if (seconds > 315576000000 || seconds < -315576000000)
throw invalid(type.fullName, value, "duration out of range");
var message = {};
if (seconds !== 0)
message.seconds = seconds;
if (nanos !== 0)
message.nanos = nanos;
return message;
};
WKT_TO[".google.protobuf.Duration"] = function (type, message) {
var seconds = longToNumber(message.seconds),
nanos = message.nanos || 0;
if (seconds > 315576000000 || seconds < -315576000000)
throw Error("google.protobuf.Duration out of range");
if (nanos > 999999999 || nanos < -999999999 || seconds && nanos && seconds < 0 !== nanos < 0)
throw Error("google.protobuf.Duration nanos invalid");
var result = (seconds < 0 || nanos < 0 ? "-" : "") + Math.abs(seconds);
if (nanos)
result += "." + nanosToString(nanos);
return result + "s";
};
WKT_FROM[".google.protobuf.Timestamp"] = function (type, value) {
if (typeof value !== "string")
throw invalid(type.fullName, value, "expected timestamp string");
var match = /^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])T([01]\d|2[0-3]):([0-5]\d):([0-5]\d)(?:\.(\d{1,9}))?(Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/.exec(value);
if (!match)
throw invalid(type.fullName, value, "invalid timestamp");
var year = parseInt(match[1], 10),
month = parseInt(match[2], 10),
day = parseInt(match[3], 10);
if (day > daysInMonth(year, month))
throw invalid(type.fullName, value, "invalid timestamp date");
var millis = new Date(value).getTime();
if (isNaN(millis))
throw invalid(type.fullName, value, "invalid timestamp");
var seconds = Math.floor(millis / 1000),
nanos = match[7] ? fracToNanos(match[7]) : 0;
if (seconds < -62135596800 || seconds > 253402300799)
throw invalid(type.fullName, value, "timestamp out of range");
var message = {};
if (seconds !== 0)
message.seconds = seconds;
if (nanos !== 0)
message.nanos = nanos;
return message;
};
WKT_TO[".google.protobuf.Timestamp"] = function (type, message) {
var seconds = longToNumber(message.seconds),
nanos = message.nanos || 0;
if (seconds < -62135596800 || seconds > 253402300799)
throw Error("google.protobuf.Timestamp out of range");
if (nanos < 0 || nanos > 999999999)
throw Error("google.protobuf.Timestamp nanos out of range");
var iso = new Date(seconds * 1000).toISOString();
return nanos
? iso.replace(/\.\d+Z$/, "." + nanosToString(nanos) + "Z")
: iso.replace(/\.\d+Z$/, "Z");
};
WKT_FROM[".google.protobuf.FieldMask"] = function (type, value) {
if (typeof value !== "string")
throw invalid(type.fullName, value, "expected field mask string");
if (value.indexOf("_") !== -1)
throw invalid(type.fullName, value, "field mask path must be lowerCamelCase");
var paths = value.length ? value.split(",") : [],
i = 0;
for (; i < paths.length; ++i)
paths[i] = camelToSnake(paths[i]);
return { paths: paths };
};
WKT_TO[".google.protobuf.FieldMask"] = function (type, message) {
var paths = message.paths || [],
out = [],
i = 0;
for (; i < paths.length; ++i) {
var camel = util.jsonName(paths[i]);
if (camelToSnake(camel) !== paths[i])
throw Error("google.protobuf.FieldMask path does not round-trip: " + paths[i]);
out.push(camel);
}
return out.join(",");
};
["DoubleValue", "FloatValue", "Int64Value", "UInt64Value", "Int32Value",
"UInt32Value", "BoolValue", "StringValue", "BytesValue"].forEach(function (name) {
var fullName = ".google.protobuf." + name;
WKT_FROM[fullName] = function (type, value, options, depth) {
var field = type.fields.value.resolve(),
fieldValue = readSingular(field, value, options, depth),
message = {};
if (!isImplicitDefault(field, fieldValue))
message.value = fieldValue;
return message;
};
WKT_TO[fullName] = function (type, message, options, depth) {
var field = type.fields.value.resolve(),
value = wktFieldValue(type, message, "value");
return writeSingular(field, value === undefined ? field.defaultValue : value, options, depth);
};
});
function valueFromJson(json, depth) {
if (depth > util.recursionLimit)
throw Error("max depth exceeded");
if (json === null)
return { nullValue: 0 };
switch (typeof json) {
case "number":
if (!isFinite(json))
throw Error("google.protobuf.Value cannot hold a non-finite number");
return { numberValue: json };
case "string":
validateUtf16(json, "google.protobuf.Value.string_value");
return { stringValue: json };
case "boolean":
return { boolValue: json };
}
if (Array.isArray(json)) {
var values = new Array(json.length), i = 0;
for (; i < json.length; ++i)
values[i] = valueFromJson(json[i], depth + 1);
return { listValue: { values: values } };
}
return { structValue: { fields: structFieldsFromJson(json, depth + 1) } };
}
function structFieldsFromJson(json, depth) {
var fields = Object.create(null), k;
for (k in json)
if (hasOwn(json, k)) {
validateUtf16(k, "google.protobuf.Struct.fields");
fields[k] = valueFromJson(json[k], depth);
}
return fields;
}
WKT_FROM[".google.protobuf.Value"] = function (type, value, options, depth) {
return valueFromJson(value, depth);
};
WKT_FROM[".google.protobuf.Struct"] = function (type, value, options, depth) {
if (value === null || typeof value !== "object" || Array.isArray(value))
throw invalid(type.fullName, value, "google.protobuf.Struct must be an object");
return { fields: structFieldsFromJson(value, depth + 1) };
};
WKT_FROM[".google.protobuf.ListValue"] = function (type, value, options, depth) {
if (!Array.isArray(value))
throw invalid(type.fullName, value, "google.protobuf.ListValue must be an array");
var values = new Array(value.length), i = 0;
for (; i < value.length; ++i)
values[i] = valueFromJson(value[i], depth + 1);
return { values: values };
};
function valueToJson(message, options, depth) {
if (depth > util.recursionLimit)
throw Error("max depth exceeded");
if (message == null || hasOwn(message, "nullValue"))
return null;
if (hasOwn(message, "numberValue")) {
if (typeof message.numberValue === "number" && !isFinite(message.numberValue))
throw Error("google.protobuf.Value cannot hold a non-finite number");
return message.numberValue;
}
if (hasOwn(message, "stringValue")) return message.stringValue;
if (hasOwn(message, "boolValue")) return message.boolValue;
if (hasOwn(message, "structValue")) return structToJson(message.structValue, options, depth + 1);
if (hasOwn(message, "listValue")) return listToJson(message.listValue, options, depth + 1);
return null;
}
function structToJson(message, options, depth) {
var out = {}, fields = message && message.fields, k;
if (fields)
for (k in fields)
if (hasOwn(fields, k))
setOwn(out, k, valueToJson(fields[k], options, depth));
return out;
}
function listToJson(message, options, depth) {
var values = message && message.values;
if (!values) return [];
var arr = new Array(values.length), i = 0;
for (; i < values.length; ++i)
arr[i] = valueToJson(values[i], options, depth);
return arr;
}
WKT_TO[".google.protobuf.Value"] = function (type, message, options, depth) {
return valueToJson(message, options, depth);
};
WKT_TO[".google.protobuf.Struct"] = function (type, message, options, depth) {
return structToJson(message, options, depth);
};
WKT_TO[".google.protobuf.ListValue"] = function (type, message, options, depth) {
return listToJson(message, options, depth);
};
WKT_FROM[".google.protobuf.Any"] = function (type, value, options, depth) {
if (value === null || typeof value !== "object" || Array.isArray(value))
throw invalid(type.fullName, value, "google.protobuf.Any must be an object");
var typeUrl = value["@type"];
if (typeUrl === undefined)
return {};
if (typeof typeUrl !== "string")
throw Error("google.protobuf.Any @type must be a string");
var name = typeUrl.substring(typeUrl.lastIndexOf("/") + 1),
msgType = type.root.lookupType(name),
custom = WKT_FROM[msgType.fullName] !== undefined,
body;
if (custom)
body = value.value;
else {
body = {};
for (var k in value)
if (hasOwn(value, k) && k !== "@type")
setOwn(body, k, value[k]);
}
var inner = readMessage(msgType, body, options, depth + 1);
var url = typeUrl.charAt(0) === "." ? typeUrl.slice(1) : typeUrl,
out = {};
if (url.indexOf("/") === -1)
url = "/" + url;
out[wktFieldName(type, "type_url")] = url;
var bytes = msgType.encode(inner).finish();
if (bytes.length)
out[wktFieldName(type, "value")] = bytes;
return out;
};
WKT_TO[".google.protobuf.Any"] = function (type, message, options, depth) {
var typeUrl = wktFieldValue(type, message, "type_url");
if (!typeUrl)
return {};
var name = typeUrl.substring(typeUrl.lastIndexOf("/") + 1),
msgType = type.root.lookupType(name),
value = wktFieldValue(type, message, "value"),
decoded = msgType.decode(value || util.emptyArray),
body = toJsonValue(msgType, decoded, options, depth + 1),
result;
if (WKT_TO[msgType.fullName])
result = { "@type": typeUrl, "value": body };
else {
result = { "@type": typeUrl };
for (var k in body)
if (hasOwn(body, k))
setOwn(result, k, body[k]);
}
return result;
};
// --- duplicate keys ---
// JSON.parse keeps the last duplicate key, but ProtoJSON rejects duplicates.
function checkDuplicateKeys(str) {
var stack = [],
expectKey = false,
i = 0,
n = str.length;
while (i < n) {
var c = str.charAt(i);
if (c === "{") {
stack.push(Object.create(null));
expectKey = true;
++i;
} else if (c === "[") {
stack.push(null);
expectKey = false;
++i;
} else if (c === "}" || c === "]") {
stack.pop();
expectKey = false;
++i;
} else if (c === ":") {
expectKey = false;
++i;
} else if (c === ",") {
expectKey = stack.length > 0 && stack[stack.length - 1] !== null;
++i;
} else if (c === "\"") {
var start = i++;
while (i < n) {
var ch = str.charAt(i++);
if (ch === "\\") ++i;
else if (ch === "\"") break;
}
if (expectKey) {
var seen = stack[stack.length - 1],
name = JSON.parse(str.slice(start, i));
if (seen[name])
throw Error("duplicate key in JSON object: " + JSON.stringify(name));
seen[name] = true;
expectKey = false;
}
} else
++i;
}
}
// --- public API ---
/**
* ProtoJSON conversion options.
* @interface IProtoJsonOptions
* @property {boolean} [ignoreUnknownFields=false] Ignores unknown object members and unrecognized enum names while parsing.
*/
/**
* Parses a message from an already-parsed ProtoJSON value using the specified reflected type.
* @function fromJson
* @name fromJson
* @param {$protobuf.Type} type Reflected message type
* @param {*} json Already-parsed ProtoJSON value
* @param {IProtoJsonOptions} [options] Conversion options
* @returns {$protobuf.Message<{}>} Message instance
*/
protojson.fromJson = function fromJson(type, json, options) {
if (!(type instanceof Type))
throw TypeError("type must be a Type");
type.root.resolveAll();
return type.create(readMessage(type, json, options || {}, 0));
};
/**
* Parses a message from ProtoJSON text using the specified reflected type.
* @function fromJsonString
* @name fromJsonString
* @param {$protobuf.Type} type Reflected message type
* @param {string} json ProtoJSON text
* @param {IProtoJsonOptions} [options] Conversion options
* @returns {$protobuf.Message<{}>} Message instance
*/
protojson.fromJsonString = function fromJsonString(type, json, options) {
if (typeof json !== "string")
throw TypeError("json must be a string");
checkDuplicateKeys(json);
return protojson.fromJson(type, JSON.parse(json), options);
};
/**
* Formats a message as ProtoJSON using the specified reflected type.
* @function toJson
* @name toJson
* @param {$protobuf.Type} type Reflected message type
* @param {$protobuf.Message<{}>|Object.<string,*>} message Message instance or plain object
* @param {IProtoJsonOptions} [options] Conversion options
* @returns {*} ProtoJSON value (object, array, string, number, boolean or null)
*/
protojson.toJson = function toJson(type, message, options) {
if (!(type instanceof Type))
throw TypeError("type must be a Type");
type.root.resolveAll();
return toJsonValue(type, message, options || {}, 0);
};
/**
* Formats a message as ProtoJSON text using the specified reflected type.
* @function toJsonString
* @name toJsonString
* @param {$protobuf.Type} type Reflected message type
* @param {$protobuf.Message<{}>|Object.<string,*>} message Message instance or plain object
* @param {IProtoJsonOptions} [options] Conversion options
* @returns {string} ProtoJSON text
*/
protojson.toJsonString = function toJsonString(type, message, options) {
return JSON.stringify(protojson.toJson(type, message, options));
};
/**
* Installs reflected {@link Type} convenience methods.
* @function install
* @name install
* @returns {undefined}
*/
protojson.install = function install() {
/**
* Parses a message of this type from an already-parsed ProtoJSON value. Convenience for {@link protojson.fromJson}.
* @param {*} json Already-parsed ProtoJSON value
* @param {IProtoJsonOptions} [options] Conversion options
* @returns {Message<{}>} Message instance
*/
Type.prototype.fromJson = function fromJson(json, options) {
return protojson.fromJson(this, json, options);
};
/**
* Parses a message of this type from ProtoJSON text. Convenience for {@link protojson.fromJsonString}.
* @param {string} json ProtoJSON text
* @param {IProtoJsonOptions} [options] Conversion options
* @returns {Message<{}>} Message instance
*/
Type.prototype.fromJsonString = function fromJsonString(json, options) {
return protojson.fromJsonString(this, json, options);
};
/**
* Formats a message of this type as ProtoJSON. Convenience for {@link protojson.toJson}.
* @param {Message<{}>|Object.<string,*>} message Message instance or plain object
* @param {IProtoJsonOptions} [options] Conversion options
* @returns {*} ProtoJSON value
*/
Type.prototype.toJson = function toJson(message, options) {
return protojson.toJson(this, message, options);
};
/**
* Formats a message of this type as ProtoJSON text. Convenience for {@link protojson.toJsonString}.
* @param {Message<{}>|Object.<string,*>} message Message instance or plain object
* @param {IProtoJsonOptions} [options] Conversion options
* @returns {string} ProtoJSON text
*/
Type.prototype.toJsonString = function toJsonString(message, options) {
return protojson.toJsonString(this, message, options);
};
};
+19
View File
@@ -0,0 +1,19 @@
import * as $protobuf from "..";
import { ITextFormatOptions } from "./textformat.generated";
export * from "./textformat.generated";
declare module ".." {
namespace textformat {
/** Maximum recursion depth for formatting length-delimited unknown fields. */
let unknownRecursionLimit: number;
}
interface Type {
/** Installed by `textformat.install()`. Parses this type from protobuf text format. */
fromText(text: string): $protobuf.Message<{}>;
/** Installed by `textformat.install()`. Formats a message of this type as protobuf text format. */
toText(message: ($protobuf.Message<{}>|{ [k: string]: any }), options?: ITextFormatOptions): string;
}
}
+33
View File
@@ -0,0 +1,33 @@
// DO NOT EDIT! This is a generated file. Edit the source file instead and regenerate.
import * as $protobuf from "..";
/** Maximum recursion depth for formatting length-delimited unknown fields. */
export let unknownRecursionLimit: number;
/** Text format options. */
export interface ITextFormatOptions {
/** Also includes and formats unknown fields. */
unknowns?: boolean;
}
/**
* Parses a message from protobuf text format using the specified reflected type.
* @param type Reflected message type
* @param text Text format input
* @returns Message instance
*/
export function fromText(type: $protobuf.Type, text: string): $protobuf.Message<{}>;
/**
* Formats a message as protobuf text format using the specified reflected type.
* @param type Reflected message type
* @param message Message instance or plain object
* @param [options] Text format options
* @returns Text format output
*/
export function toText(type: $protobuf.Type, message: ($protobuf.Message<{}>|{ [k: string]: any }), options?: ITextFormatOptions): string;
/** Installs reflected {@link Type} convenience methods. */
export function install(): void;
+1276
View File
File diff suppressed because it is too large Load Diff