UNPKG

87.2 kBTypeScriptView Raw
1// DO NOT EDIT! This is a generated file. Edit the JSDoc in src/*.js instead and run 'npm run build:types'.
2
3export as namespace protobuf;
4
5/**
6 * Provides common type definitions.
7 * Can also be used to provide additional google types or your own custom types.
8 * @param name Short name as in `google/protobuf/[name].proto` or full file name
9 * @param json JSON definition within `google.protobuf` if a short name, otherwise the file's root definition
10 */
11export function common(name: string, json: { [k: string]: any }): void;
12
13export namespace common {
14
15 /** Properties of a google.protobuf.Any message. */
16 interface IAny {
17 typeUrl?: string;
18 bytes?: Uint8Array;
19 }
20
21 /** Properties of a google.protobuf.Duration message. */
22 interface IDuration {
23 seconds?: (number|Long);
24 nanos?: number;
25 }
26
27 /** Properties of a google.protobuf.Timestamp message. */
28 interface ITimestamp {
29 seconds?: (number|Long);
30 nanos?: number;
31 }
32
33 /** Properties of a google.protobuf.Empty message. */
34 interface IEmpty {
35 }
36
37 /** Properties of a google.protobuf.Struct message. */
38 interface IStruct {
39 fields?: { [k: string]: IValue };
40 }
41
42 /** Properties of a google.protobuf.Value message. */
43 interface IValue {
44 kind?: string;
45 nullValue?: 0;
46 numberValue?: number;
47 stringValue?: string;
48 boolValue?: boolean;
49 structValue?: IStruct;
50 listValue?: IListValue;
51 }
52
53 /** Properties of a google.protobuf.ListValue message. */
54 interface IListValue {
55 values?: IValue[];
56 }
57
58 /** Properties of a google.protobuf.DoubleValue message. */
59 interface IDoubleValue {
60 value?: number;
61 }
62
63 /** Properties of a google.protobuf.FloatValue message. */
64 interface IFloatValue {
65 value?: number;
66 }
67
68 /** Properties of a google.protobuf.Int64Value message. */
69 interface IInt64Value {
70 value?: (number|Long);
71 }
72
73 /** Properties of a google.protobuf.UInt64Value message. */
74 interface IUInt64Value {
75 value?: (number|Long);
76 }
77
78 /** Properties of a google.protobuf.Int32Value message. */
79 interface IInt32Value {
80 value?: number;
81 }
82
83 /** Properties of a google.protobuf.UInt32Value message. */
84 interface IUInt32Value {
85 value?: number;
86 }
87
88 /** Properties of a google.protobuf.BoolValue message. */
89 interface IBoolValue {
90 value?: boolean;
91 }
92
93 /** Properties of a google.protobuf.StringValue message. */
94 interface IStringValue {
95 value?: string;
96 }
97
98 /** Properties of a google.protobuf.BytesValue message. */
99 interface IBytesValue {
100 value?: Uint8Array;
101 }
102
103 /**
104 * Gets the root definition of the specified common proto file.
105 *
106 * Bundled definitions are:
107 * - google/protobuf/any.proto
108 * - google/protobuf/duration.proto
109 * - google/protobuf/empty.proto
110 * - google/protobuf/field_mask.proto
111 * - google/protobuf/struct.proto
112 * - google/protobuf/timestamp.proto
113 * - google/protobuf/wrappers.proto
114 *
115 * @param file Proto file name
116 * @returns Root definition or `null` if not defined
117 */
118 function get(file: string): (INamespace|null);
119}
120
121/** Runtime message from/to plain object converters. */
122export namespace converter {
123
124 /**
125 * Generates a plain object to runtime message converter specific to the specified message type.
126 * @param mtype Message type
127 * @returns Codegen instance
128 */
129 function fromObject(mtype: Type): Codegen;
130
131 /**
132 * Generates a runtime message to plain object converter specific to the specified message type.
133 * @param mtype Message type
134 * @returns Codegen instance
135 */
136 function toObject(mtype: Type): Codegen;
137}
138
139/**
140 * Generates a decoder specific to the specified message type.
141 * @param mtype Message type
142 * @returns Codegen instance
143 */
144export function decoder(mtype: Type): Codegen;
145
146/**
147 * Generates an encoder specific to the specified message type.
148 * @param mtype Message type
149 * @returns Codegen instance
150 */
151export function encoder(mtype: Type): Codegen;
152
153/** Reflected enum. */
154export class Enum extends ReflectionObject {
155
156 /**
157 * Constructs a new enum instance.
158 * @param name Unique name within its namespace
159 * @param [values] Enum values as an object, by name
160 * @param [options] Declared options
161 * @param [comment] The comment for this enum
162 * @param [comments] The value comments for this enum
163 * @param [valuesOptions] The value options for this enum
164 */
165 constructor(name: string, values?: { [k: string]: number }, options?: { [k: string]: any }, comment?: string, comments?: { [k: string]: string }, valuesOptions?: ({ [k: string]: { [k: string]: any } }|undefined));
166
167 /** Enum values by id. */
168 public valuesById: { [k: number]: string };
169
170 /** Enum values by name. */
171 public values: { [k: string]: number };
172
173 /** Enum comment text. */
174 public comment: (string|null);
175
176 /** Value comment texts, if any. */
177 public comments: { [k: string]: string };
178
179 /** Values options, if any */
180 public valuesOptions?: { [k: string]: { [k: string]: any } };
181
182 /** Reserved ranges, if any. */
183 public reserved: (number[]|string)[];
184
185 /**
186 * Constructs an enum from an enum descriptor.
187 * @param name Enum name
188 * @param json Enum descriptor
189 * @returns Created enum
190 * @throws {TypeError} If arguments are invalid
191 */
192 public static fromJSON(name: string, json: IEnum): Enum;
193
194 /**
195 * Converts this enum to an enum descriptor.
196 * @param [toJSONOptions] JSON conversion options
197 * @returns Enum descriptor
198 */
199 public toJSON(toJSONOptions?: IToJSONOptions): IEnum;
200
201 /**
202 * Adds a value to this enum.
203 * @param name Value name
204 * @param id Value id
205 * @param [comment] Comment, if any
206 * @param {Object.<string, *>|undefined} [options] Options, if any
207 * @returns `this`
208 * @throws {TypeError} If arguments are invalid
209 * @throws {Error} If there is already a value with this name or id
210 */
211 public add(name: string, id: number, comment?: string, options?: ({ [k: string]: any }|undefined)): Enum;
212
213 /**
214 * Removes a value from this enum
215 * @param name Value name
216 * @returns `this`
217 * @throws {TypeError} If arguments are invalid
218 * @throws {Error} If `name` is not a name of this enum
219 */
220 public remove(name: string): Enum;
221
222 /**
223 * Tests if the specified id is reserved.
224 * @param id Id to test
225 * @returns `true` if reserved, otherwise `false`
226 */
227 public isReservedId(id: number): boolean;
228
229 /**
230 * Tests if the specified name is reserved.
231 * @param name Name to test
232 * @returns `true` if reserved, otherwise `false`
233 */
234 public isReservedName(name: string): boolean;
235}
236
237/** Enum descriptor. */
238export interface IEnum {
239
240 /** Enum values */
241 values: { [k: string]: number };
242
243 /** Enum options */
244 options?: { [k: string]: any };
245}
246
247/** Reflected message field. */
248export class Field extends FieldBase {
249
250 /**
251 * Constructs a new message field instance. Note that {@link MapField|map fields} have their own class.
252 * @param name Unique name within its namespace
253 * @param id Unique id within its namespace
254 * @param type Value type
255 * @param [rule="optional"] Field rule
256 * @param [extend] Extended type if different from parent
257 * @param [options] Declared options
258 */
259 constructor(name: string, id: number, type: string, rule?: (string|{ [k: string]: any }), extend?: (string|{ [k: string]: any }), options?: { [k: string]: any });
260
261 /**
262 * Constructs a field from a field descriptor.
263 * @param name Field name
264 * @param json Field descriptor
265 * @returns Created field
266 * @throws {TypeError} If arguments are invalid
267 */
268 public static fromJSON(name: string, json: IField): Field;
269
270 /** Determines whether this field is packed. Only relevant when repeated and working with proto2. */
271 public readonly packed: boolean;
272
273 /**
274 * Field decorator (TypeScript).
275 * @param fieldId Field id
276 * @param fieldType Field type
277 * @param [fieldRule="optional"] Field rule
278 * @param [defaultValue] Default value
279 * @returns Decorator function
280 */
281 public static d<T extends number | number[] | Long | Long[] | string | string[] | boolean | boolean[] | Uint8Array | Uint8Array[] | Buffer | Buffer[]>(fieldId: number, fieldType: ("double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"string"|"bool"|"bytes"|object), fieldRule?: ("optional"|"required"|"repeated"), defaultValue?: T): FieldDecorator;
282
283 /**
284 * Field decorator (TypeScript).
285 * @param fieldId Field id
286 * @param fieldType Field type
287 * @param [fieldRule="optional"] Field rule
288 * @returns Decorator function
289 */
290 public static d<T extends Message<T>>(fieldId: number, fieldType: (Constructor<T>|string), fieldRule?: ("optional"|"required"|"repeated")): FieldDecorator;
291}
292
293/** Base class of all reflected message fields. This is not an actual class but here for the sake of having consistent type definitions. */
294export class FieldBase extends ReflectionObject {
295
296 /**
297 * Not an actual constructor. Use {@link Field} instead.
298 * @param name Unique name within its namespace
299 * @param id Unique id within its namespace
300 * @param type Value type
301 * @param [rule="optional"] Field rule
302 * @param [extend] Extended type if different from parent
303 * @param [options] Declared options
304 * @param [comment] Comment associated with this field
305 */
306 constructor(name: string, id: number, type: string, rule?: (string|{ [k: string]: any }), extend?: (string|{ [k: string]: any }), options?: { [k: string]: any }, comment?: string);
307
308 /** Field type. */
309 public type: string;
310
311 /** Unique field id. */
312 public id: number;
313
314 /** Extended type if different from parent. */
315 public extend?: string;
316
317 /** Whether this field is required. */
318 public required: boolean;
319
320 /** Whether this field is optional. */
321 public optional: boolean;
322
323 /** Whether this field is repeated. */
324 public repeated: boolean;
325
326 /** Whether this field is a map or not. */
327 public map: boolean;
328
329 /** Message this field belongs to. */
330 public message: (Type|null);
331
332 /** OneOf this field belongs to, if any, */
333 public partOf: (OneOf|null);
334
335 /** The field type's default value. */
336 public typeDefault: any;
337
338 /** The field's default value on prototypes. */
339 public defaultValue: any;
340
341 /** Whether this field's value should be treated as a long. */
342 public long: boolean;
343
344 /** Whether this field's value is a buffer. */
345 public bytes: boolean;
346
347 /** Resolved type if not a basic type. */
348 public resolvedType: (Type|Enum|null);
349
350 /** Sister-field within the extended type if a declaring extension field. */
351 public extensionField: (Field|null);
352
353 /** Sister-field within the declaring namespace if an extended field. */
354 public declaringField: (Field|null);
355
356 /** Comment for this field. */
357 public comment: (string|null);
358
359 /**
360 * Converts this field to a field descriptor.
361 * @param [toJSONOptions] JSON conversion options
362 * @returns Field descriptor
363 */
364 public toJSON(toJSONOptions?: IToJSONOptions): IField;
365
366 /**
367 * Resolves this field's type references.
368 * @returns `this`
369 * @throws {Error} If any reference cannot be resolved
370 */
371 public resolve(): Field;
372}
373
374/** Field descriptor. */
375export interface IField {
376
377 /** Field rule */
378 rule?: string;
379
380 /** Field type */
381 type: string;
382
383 /** Field id */
384 id: number;
385
386 /** Field options */
387 options?: { [k: string]: any };
388}
389
390/** Extension field descriptor. */
391export interface IExtensionField extends IField {
392
393 /** Extended type */
394 extend: string;
395}
396
397/**
398 * Decorator function as returned by {@link Field.d} and {@link MapField.d} (TypeScript).
399 * @param prototype Target prototype
400 * @param fieldName Field name
401 */
402type FieldDecorator = (prototype: object, fieldName: string) => void;
403
404/**
405 * A node-style callback as used by {@link load} and {@link Root#load}.
406 * @param error Error, if any, otherwise `null`
407 * @param [root] Root, if there hasn't been an error
408 */
409type LoadCallback = (error: (Error|null), root?: Root) => void;
410
411/**
412 * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.
413 * @param filename One or multiple files to load
414 * @param root Root namespace, defaults to create a new one if omitted.
415 * @param callback Callback function
416 * @see {@link Root#load}
417 */
418export function load(filename: (string|string[]), root: Root, callback: LoadCallback): void;
419
420/**
421 * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.
422 * @param filename One or multiple files to load
423 * @param callback Callback function
424 * @see {@link Root#load}
425 */
426export function load(filename: (string|string[]), callback: LoadCallback): void;
427
428/**
429 * Loads one or multiple .proto or preprocessed .json files into a common root namespace and returns a promise.
430 * @param filename One or multiple files to load
431 * @param [root] Root namespace, defaults to create a new one if omitted.
432 * @returns Promise
433 * @see {@link Root#load}
434 */
435export function load(filename: (string|string[]), root?: Root): Promise<Root>;
436
437/**
438 * Synchronously loads one or multiple .proto or preprocessed .json files into a common root namespace (node only).
439 * @param filename One or multiple files to load
440 * @param [root] Root namespace, defaults to create a new one if omitted.
441 * @returns Root namespace
442 * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid
443 * @see {@link Root#loadSync}
444 */
445export function loadSync(filename: (string|string[]), root?: Root): Root;
446
447/** Build type, one of `"full"`, `"light"` or `"minimal"`. */
448export const build: string;
449
450/** Reconfigures the library according to the environment. */
451export function configure(): void;
452
453/** Reflected map field. */
454export class MapField extends FieldBase {
455
456 /**
457 * Constructs a new map field instance.
458 * @param name Unique name within its namespace
459 * @param id Unique id within its namespace
460 * @param keyType Key type
461 * @param type Value type
462 * @param [options] Declared options
463 * @param [comment] Comment associated with this field
464 */
465 constructor(name: string, id: number, keyType: string, type: string, options?: { [k: string]: any }, comment?: string);
466
467 /** Key type. */
468 public keyType: string;
469
470 /** Resolved key type if not a basic type. */
471 public resolvedKeyType: (ReflectionObject|null);
472
473 /**
474 * Constructs a map field from a map field descriptor.
475 * @param name Field name
476 * @param json Map field descriptor
477 * @returns Created map field
478 * @throws {TypeError} If arguments are invalid
479 */
480 public static fromJSON(name: string, json: IMapField): MapField;
481
482 /**
483 * Converts this map field to a map field descriptor.
484 * @param [toJSONOptions] JSON conversion options
485 * @returns Map field descriptor
486 */
487 public toJSON(toJSONOptions?: IToJSONOptions): IMapField;
488
489 /**
490 * Map field decorator (TypeScript).
491 * @param fieldId Field id
492 * @param fieldKeyType Field key type
493 * @param fieldValueType Field value type
494 * @returns Decorator function
495 */
496 public static d<T extends { [key: string]: number | Long | string | boolean | Uint8Array | Buffer | number[] | Message<{}> }>(fieldId: number, fieldKeyType: ("int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"), fieldValueType: ("double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"|"bytes"|object|Constructor<{}>)): FieldDecorator;
497}
498
499/** Map field descriptor. */
500export interface IMapField extends IField {
501
502 /** Key type */
503 keyType: string;
504}
505
506/** Extension map field descriptor. */
507export interface IExtensionMapField extends IMapField {
508
509 /** Extended type */
510 extend: string;
511}
512
513/** Abstract runtime message. */
514export class Message<T extends object = object> {
515
516 /**
517 * Constructs a new message instance.
518 * @param [properties] Properties to set
519 */
520 constructor(properties?: Properties<T>);
521
522 /** Reference to the reflected type. */
523 public static readonly $type: Type;
524
525 /** Reference to the reflected type. */
526 public readonly $type: Type;
527
528 /**
529 * Creates a new message of this type using the specified properties.
530 * @param [properties] Properties to set
531 * @returns Message instance
532 */
533 public static create<T extends Message<T>>(this: Constructor<T>, properties?: { [k: string]: any }): Message<T>;
534
535 /**
536 * Encodes a message of this type.
537 * @param message Message to encode
538 * @param [writer] Writer to use
539 * @returns Writer
540 */
541 public static encode<T extends Message<T>>(this: Constructor<T>, message: (T|{ [k: string]: any }), writer?: Writer): Writer;
542
543 /**
544 * Encodes a message of this type preceeded by its length as a varint.
545 * @param message Message to encode
546 * @param [writer] Writer to use
547 * @returns Writer
548 */
549 public static encodeDelimited<T extends Message<T>>(this: Constructor<T>, message: (T|{ [k: string]: any }), writer?: Writer): Writer;
550
551 /**
552 * Decodes a message of this type.
553 * @param reader Reader or buffer to decode
554 * @returns Decoded message
555 */
556 public static decode<T extends Message<T>>(this: Constructor<T>, reader: (Reader|Uint8Array)): T;
557
558 /**
559 * Decodes a message of this type preceeded by its length as a varint.
560 * @param reader Reader or buffer to decode
561 * @returns Decoded message
562 */
563 public static decodeDelimited<T extends Message<T>>(this: Constructor<T>, reader: (Reader|Uint8Array)): T;
564
565 /**
566 * Verifies a message of this type.
567 * @param message Plain object to verify
568 * @returns `null` if valid, otherwise the reason why it is not
569 */
570 public static verify(message: { [k: string]: any }): (string|null);
571
572 /**
573 * Creates a new message of this type from a plain object. Also converts values to their respective internal types.
574 * @param object Plain object
575 * @returns Message instance
576 */
577 public static fromObject<T extends Message<T>>(this: Constructor<T>, object: { [k: string]: any }): T;
578
579 /**
580 * Creates a plain object from a message of this type. Also converts values to other types if specified.
581 * @param message Message instance
582 * @param [options] Conversion options
583 * @returns Plain object
584 */
585 public static toObject<T extends Message<T>>(this: Constructor<T>, message: T, options?: IConversionOptions): { [k: string]: any };
586
587 /**
588 * Converts this message to JSON.
589 * @returns JSON object
590 */
591 public toJSON(): { [k: string]: any };
592}
593
594/** Reflected service method. */
595export class Method extends ReflectionObject {
596
597 /**
598 * Constructs a new service method instance.
599 * @param name Method name
600 * @param type Method type, usually `"rpc"`
601 * @param requestType Request message type
602 * @param responseType Response message type
603 * @param [requestStream] Whether the request is streamed
604 * @param [responseStream] Whether the response is streamed
605 * @param [options] Declared options
606 * @param [comment] The comment for this method
607 * @param [parsedOptions] Declared options, properly parsed into an object
608 */
609 constructor(name: string, type: (string|undefined), requestType: string, responseType: string, requestStream?: (boolean|{ [k: string]: any }), responseStream?: (boolean|{ [k: string]: any }), options?: { [k: string]: any }, comment?: string, parsedOptions?: { [k: string]: any });
610
611 /** Method type. */
612 public type: string;
613
614 /** Request type. */
615 public requestType: string;
616
617 /** Whether requests are streamed or not. */
618 public requestStream?: boolean;
619
620 /** Response type. */
621 public responseType: string;
622
623 /** Whether responses are streamed or not. */
624 public responseStream?: boolean;
625
626 /** Resolved request type. */
627 public resolvedRequestType: (Type|null);
628
629 /** Resolved response type. */
630 public resolvedResponseType: (Type|null);
631
632 /** Comment for this method */
633 public comment: (string|null);
634
635 /** Options properly parsed into an object */
636 public parsedOptions: any;
637
638 /**
639 * Constructs a method from a method descriptor.
640 * @param name Method name
641 * @param json Method descriptor
642 * @returns Created method
643 * @throws {TypeError} If arguments are invalid
644 */
645 public static fromJSON(name: string, json: IMethod): Method;
646
647 /**
648 * Converts this method to a method descriptor.
649 * @param [toJSONOptions] JSON conversion options
650 * @returns Method descriptor
651 */
652 public toJSON(toJSONOptions?: IToJSONOptions): IMethod;
653}
654
655/** Method descriptor. */
656export interface IMethod {
657
658 /** Method type */
659 type?: string;
660
661 /** Request type */
662 requestType: string;
663
664 /** Response type */
665 responseType: string;
666
667 /** Whether requests are streamed */
668 requestStream?: boolean;
669
670 /** Whether responses are streamed */
671 responseStream?: boolean;
672
673 /** Method options */
674 options?: { [k: string]: any };
675
676 /** Method comments */
677 comment: string;
678
679 /** Method options properly parsed into an object */
680 parsedOptions?: { [k: string]: any };
681}
682
683/** Reflected namespace. */
684export class Namespace extends NamespaceBase {
685
686 /**
687 * Constructs a new namespace instance.
688 * @param name Namespace name
689 * @param [options] Declared options
690 */
691 constructor(name: string, options?: { [k: string]: any });
692
693 /**
694 * Constructs a namespace from JSON.
695 * @param name Namespace name
696 * @param json JSON object
697 * @returns Created namespace
698 * @throws {TypeError} If arguments are invalid
699 */
700 public static fromJSON(name: string, json: { [k: string]: any }): Namespace;
701
702 /**
703 * Converts an array of reflection objects to JSON.
704 * @param array Object array
705 * @param [toJSONOptions] JSON conversion options
706 * @returns JSON object or `undefined` when array is empty
707 */
708 public static arrayToJSON(array: ReflectionObject[], toJSONOptions?: IToJSONOptions): ({ [k: string]: any }|undefined);
709
710 /**
711 * Tests if the specified id is reserved.
712 * @param reserved Array of reserved ranges and names
713 * @param id Id to test
714 * @returns `true` if reserved, otherwise `false`
715 */
716 public static isReservedId(reserved: ((number[]|string)[]|undefined), id: number): boolean;
717
718 /**
719 * Tests if the specified name is reserved.
720 * @param reserved Array of reserved ranges and names
721 * @param name Name to test
722 * @returns `true` if reserved, otherwise `false`
723 */
724 public static isReservedName(reserved: ((number[]|string)[]|undefined), name: string): boolean;
725}
726
727/** Base class of all reflection objects containing nested objects. This is not an actual class but here for the sake of having consistent type definitions. */
728export abstract class NamespaceBase extends ReflectionObject {
729
730 /** Nested objects by name. */
731 public nested?: { [k: string]: ReflectionObject };
732
733 /** Nested objects of this namespace as an array for iteration. */
734 public readonly nestedArray: ReflectionObject[];
735
736 /**
737 * Converts this namespace to a namespace descriptor.
738 * @param [toJSONOptions] JSON conversion options
739 * @returns Namespace descriptor
740 */
741 public toJSON(toJSONOptions?: IToJSONOptions): INamespace;
742
743 /**
744 * Adds nested objects to this namespace from nested object descriptors.
745 * @param nestedJson Any nested object descriptors
746 * @returns `this`
747 */
748 public addJSON(nestedJson: { [k: string]: AnyNestedObject }): Namespace;
749
750 /**
751 * Gets the nested object of the specified name.
752 * @param name Nested object name
753 * @returns The reflection object or `null` if it doesn't exist
754 */
755 public get(name: string): (ReflectionObject|null);
756
757 /**
758 * Gets the values of the nested {@link Enum|enum} of the specified name.
759 * This methods differs from {@link Namespace#get|get} in that it returns an enum's values directly and throws instead of returning `null`.
760 * @param name Nested enum name
761 * @returns Enum values
762 * @throws {Error} If there is no such enum
763 */
764 public getEnum(name: string): { [k: string]: number };
765
766 /**
767 * Adds a nested object to this namespace.
768 * @param object Nested object to add
769 * @returns `this`
770 * @throws {TypeError} If arguments are invalid
771 * @throws {Error} If there is already a nested object with this name
772 */
773 public add(object: ReflectionObject): Namespace;
774
775 /**
776 * Removes a nested object from this namespace.
777 * @param object Nested object to remove
778 * @returns `this`
779 * @throws {TypeError} If arguments are invalid
780 * @throws {Error} If `object` is not a member of this namespace
781 */
782 public remove(object: ReflectionObject): Namespace;
783
784 /**
785 * Defines additial namespaces within this one if not yet existing.
786 * @param path Path to create
787 * @param [json] Nested types to create from JSON
788 * @returns Pointer to the last namespace created or `this` if path is empty
789 */
790 public define(path: (string|string[]), json?: any): Namespace;
791
792 /**
793 * Resolves this namespace's and all its nested objects' type references. Useful to validate a reflection tree, but comes at a cost.
794 * @returns `this`
795 */
796 public resolveAll(): Namespace;
797
798 /**
799 * Recursively looks up the reflection object matching the specified path in the scope of this namespace.
800 * @param path Path to look up
801 * @param filterTypes Filter types, any combination of the constructors of `protobuf.Type`, `protobuf.Enum`, `protobuf.Service` etc.
802 * @param [parentAlreadyChecked=false] If known, whether the parent has already been checked
803 * @returns Looked up object or `null` if none could be found
804 */
805 public lookup(path: (string|string[]), filterTypes: (any|any[]), parentAlreadyChecked?: boolean): (ReflectionObject|null);
806
807 /**
808 * Looks up the reflection object at the specified path, relative to this namespace.
809 * @param path Path to look up
810 * @param [parentAlreadyChecked=false] Whether the parent has already been checked
811 * @returns Looked up object or `null` if none could be found
812 */
813 public lookup(path: (string|string[]), parentAlreadyChecked?: boolean): (ReflectionObject|null);
814
815 /**
816 * Looks up the {@link Type|type} at the specified path, relative to this namespace.
817 * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.
818 * @param path Path to look up
819 * @returns Looked up type
820 * @throws {Error} If `path` does not point to a type
821 */
822 public lookupType(path: (string|string[])): Type;
823
824 /**
825 * Looks up the values of the {@link Enum|enum} at the specified path, relative to this namespace.
826 * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.
827 * @param path Path to look up
828 * @returns Looked up enum
829 * @throws {Error} If `path` does not point to an enum
830 */
831 public lookupEnum(path: (string|string[])): Enum;
832
833 /**
834 * Looks up the {@link Type|type} or {@link Enum|enum} at the specified path, relative to this namespace.
835 * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.
836 * @param path Path to look up
837 * @returns Looked up type or enum
838 * @throws {Error} If `path` does not point to a type or enum
839 */
840 public lookupTypeOrEnum(path: (string|string[])): Type;
841
842 /**
843 * Looks up the {@link Service|service} at the specified path, relative to this namespace.
844 * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.
845 * @param path Path to look up
846 * @returns Looked up service
847 * @throws {Error} If `path` does not point to a service
848 */
849 public lookupService(path: (string|string[])): Service;
850}
851
852/** Namespace descriptor. */
853export interface INamespace {
854
855 /** Namespace options */
856 options?: { [k: string]: any };
857
858 /** Nested object descriptors */
859 nested?: { [k: string]: AnyNestedObject };
860}
861
862/** Any extension field descriptor. */
863type AnyExtensionField = (IExtensionField|IExtensionMapField);
864
865/** Any nested object descriptor. */
866type AnyNestedObject = (IEnum|IType|IService|AnyExtensionField|INamespace|IOneOf);
867
868/** Base class of all reflection objects. */
869export abstract class ReflectionObject {
870
871 /** Options. */
872 public options?: { [k: string]: any };
873
874 /** Parsed Options. */
875 public parsedOptions?: { [k: string]: any[] };
876
877 /** Unique name within its namespace. */
878 public name: string;
879
880 /** Parent namespace. */
881 public parent: (Namespace|null);
882
883 /** Whether already resolved or not. */
884 public resolved: boolean;
885
886 /** Comment text, if any. */
887 public comment: (string|null);
888
889 /** Defining file name. */
890 public filename: (string|null);
891
892 /** Reference to the root namespace. */
893 public readonly root: Root;
894
895 /** Full name including leading dot. */
896 public readonly fullName: string;
897
898 /**
899 * Converts this reflection object to its descriptor representation.
900 * @returns Descriptor
901 */
902 public toJSON(): { [k: string]: any };
903
904 /**
905 * Called when this object is added to a parent.
906 * @param parent Parent added to
907 */
908 public onAdd(parent: ReflectionObject): void;
909
910 /**
911 * Called when this object is removed from a parent.
912 * @param parent Parent removed from
913 */
914 public onRemove(parent: ReflectionObject): void;
915
916 /**
917 * Resolves this objects type references.
918 * @returns `this`
919 */
920 public resolve(): ReflectionObject;
921
922 /**
923 * Gets an option value.
924 * @param name Option name
925 * @returns Option value or `undefined` if not set
926 */
927 public getOption(name: string): any;
928
929 /**
930 * Sets an option.
931 * @param name Option name
932 * @param value Option value
933 * @param [ifNotSet] Sets the option only if it isn't currently set
934 * @returns `this`
935 */
936 public setOption(name: string, value: any, ifNotSet?: boolean): ReflectionObject;
937
938 /**
939 * Sets a parsed option.
940 * @param name parsed Option name
941 * @param value Option value
942 * @param propName dot '.' delimited full path of property within the option to set. if undefined\empty, will add a new option with that value
943 * @returns `this`
944 */
945 public setParsedOption(name: string, value: any, propName: string): ReflectionObject;
946
947 /**
948 * Sets multiple options.
949 * @param options Options to set
950 * @param [ifNotSet] Sets an option only if it isn't currently set
951 * @returns `this`
952 */
953 public setOptions(options: { [k: string]: any }, ifNotSet?: boolean): ReflectionObject;
954
955 /**
956 * Converts this instance to its string representation.
957 * @returns Class name[, space, full name]
958 */
959 public toString(): string;
960}
961
962/** Reflected oneof. */
963export class OneOf extends ReflectionObject {
964
965 /**
966 * Constructs a new oneof instance.
967 * @param name Oneof name
968 * @param [fieldNames] Field names
969 * @param [options] Declared options
970 * @param [comment] Comment associated with this field
971 */
972 constructor(name: string, fieldNames?: (string[]|{ [k: string]: any }), options?: { [k: string]: any }, comment?: string);
973
974 /** Field names that belong to this oneof. */
975 public oneof: string[];
976
977 /** Fields that belong to this oneof as an array for iteration. */
978 public readonly fieldsArray: Field[];
979
980 /** Comment for this field. */
981 public comment: (string|null);
982
983 /**
984 * Constructs a oneof from a oneof descriptor.
985 * @param name Oneof name
986 * @param json Oneof descriptor
987 * @returns Created oneof
988 * @throws {TypeError} If arguments are invalid
989 */
990 public static fromJSON(name: string, json: IOneOf): OneOf;
991
992 /**
993 * Converts this oneof to a oneof descriptor.
994 * @param [toJSONOptions] JSON conversion options
995 * @returns Oneof descriptor
996 */
997 public toJSON(toJSONOptions?: IToJSONOptions): IOneOf;
998
999 /**
1000 * Adds a field to this oneof and removes it from its current parent, if any.
1001 * @param field Field to add
1002 * @returns `this`
1003 */
1004 public add(field: Field): OneOf;
1005
1006 /**
1007 * Removes a field from this oneof and puts it back to the oneof's parent.
1008 * @param field Field to remove
1009 * @returns `this`
1010 */
1011 public remove(field: Field): OneOf;
1012
1013 /**
1014 * OneOf decorator (TypeScript).
1015 * @param fieldNames Field names
1016 * @returns Decorator function
1017 */
1018 public static d<T extends string>(...fieldNames: string[]): OneOfDecorator;
1019}
1020
1021/** Oneof descriptor. */
1022export interface IOneOf {
1023
1024 /** Oneof field names */
1025 oneof: string[];
1026
1027 /** Oneof options */
1028 options?: { [k: string]: any };
1029}
1030
1031/**
1032 * Decorator function as returned by {@link OneOf.d} (TypeScript).
1033 * @param prototype Target prototype
1034 * @param oneofName OneOf name
1035 */
1036type OneOfDecorator = (prototype: object, oneofName: string) => void;
1037
1038/**
1039 * Parses the given .proto source and returns an object with the parsed contents.
1040 * @param source Source contents
1041 * @param [options] Parse options. Defaults to {@link parse.defaults} when omitted.
1042 * @returns Parser result
1043 */
1044export function parse(source: string, options?: IParseOptions): IParserResult;
1045
1046/** Result object returned from {@link parse}. */
1047export interface IParserResult {
1048
1049 /** Package name, if declared */
1050 package: (string|undefined);
1051
1052 /** Imports, if any */
1053 imports: (string[]|undefined);
1054
1055 /** Weak imports, if any */
1056 weakImports: (string[]|undefined);
1057
1058 /** Syntax, if specified (either `"proto2"` or `"proto3"`) */
1059 syntax: (string|undefined);
1060
1061 /** Populated root instance */
1062 root: Root;
1063}
1064
1065/** Options modifying the behavior of {@link parse}. */
1066export interface IParseOptions {
1067
1068 /** Keeps field casing instead of converting to camel case */
1069 keepCase?: boolean;
1070
1071 /** Recognize double-slash comments in addition to doc-block comments. */
1072 alternateCommentMode?: boolean;
1073
1074 /** Use trailing comment when both leading comment and trailing comment exist. */
1075 preferTrailingComment?: boolean;
1076}
1077
1078/** Options modifying the behavior of JSON serialization. */
1079export interface IToJSONOptions {
1080
1081 /** Serializes comments. */
1082 keepComments?: boolean;
1083}
1084
1085/**
1086 * Parses the given .proto source and returns an object with the parsed contents.
1087 * @param source Source contents
1088 * @param root Root to populate
1089 * @param [options] Parse options. Defaults to {@link parse.defaults} when omitted.
1090 * @returns Parser result
1091 */
1092export function parse(source: string, root: Root, options?: IParseOptions): IParserResult;
1093
1094/** Wire format reader using `Uint8Array` if available, otherwise `Array`. */
1095export class Reader {
1096
1097 /**
1098 * Constructs a new reader instance using the specified buffer.
1099 * @param buffer Buffer to read from
1100 */
1101 constructor(buffer: Uint8Array);
1102
1103 /** Read buffer. */
1104 public buf: Uint8Array;
1105
1106 /** Read buffer position. */
1107 public pos: number;
1108
1109 /** Read buffer length. */
1110 public len: number;
1111
1112 /**
1113 * Creates a new reader using the specified buffer.
1114 * @param buffer Buffer to read from
1115 * @returns A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader}
1116 * @throws {Error} If `buffer` is not a valid buffer
1117 */
1118 public static create(buffer: (Uint8Array|Buffer)): (Reader|BufferReader);
1119
1120 /**
1121 * Reads a varint as an unsigned 32 bit value.
1122 * @returns Value read
1123 */
1124 public uint32(): number;
1125
1126 /**
1127 * Reads a varint as a signed 32 bit value.
1128 * @returns Value read
1129 */
1130 public int32(): number;
1131
1132 /**
1133 * Reads a zig-zag encoded varint as a signed 32 bit value.
1134 * @returns Value read
1135 */
1136 public sint32(): number;
1137
1138 /**
1139 * Reads a varint as a signed 64 bit value.
1140 * @returns Value read
1141 */
1142 public int64(): Long;
1143
1144 /**
1145 * Reads a varint as an unsigned 64 bit value.
1146 * @returns Value read
1147 */
1148 public uint64(): Long;
1149
1150 /**
1151 * Reads a zig-zag encoded varint as a signed 64 bit value.
1152 * @returns Value read
1153 */
1154 public sint64(): Long;
1155
1156 /**
1157 * Reads a varint as a boolean.
1158 * @returns Value read
1159 */
1160 public bool(): boolean;
1161
1162 /**
1163 * Reads fixed 32 bits as an unsigned 32 bit integer.
1164 * @returns Value read
1165 */
1166 public fixed32(): number;
1167
1168 /**
1169 * Reads fixed 32 bits as a signed 32 bit integer.
1170 * @returns Value read
1171 */
1172 public sfixed32(): number;
1173
1174 /**
1175 * Reads fixed 64 bits.
1176 * @returns Value read
1177 */
1178 public fixed64(): Long;
1179
1180 /**
1181 * Reads zig-zag encoded fixed 64 bits.
1182 * @returns Value read
1183 */
1184 public sfixed64(): Long;
1185
1186 /**
1187 * Reads a float (32 bit) as a number.
1188 * @returns Value read
1189 */
1190 public float(): number;
1191
1192 /**
1193 * Reads a double (64 bit float) as a number.
1194 * @returns Value read
1195 */
1196 public double(): number;
1197
1198 /**
1199 * Reads a sequence of bytes preceeded by its length as a varint.
1200 * @returns Value read
1201 */
1202 public bytes(): Uint8Array;
1203
1204 /**
1205 * Reads a string preceeded by its byte length as a varint.
1206 * @returns Value read
1207 */
1208 public string(): string;
1209
1210 /**
1211 * Skips the specified number of bytes if specified, otherwise skips a varint.
1212 * @param [length] Length if known, otherwise a varint is assumed
1213 * @returns `this`
1214 */
1215 public skip(length?: number): Reader;
1216
1217 /**
1218 * Skips the next element of the specified wire type.
1219 * @param wireType Wire type received
1220 * @returns `this`
1221 */
1222 public skipType(wireType: number): Reader;
1223}
1224
1225/** Wire format reader using node buffers. */
1226export class BufferReader extends Reader {
1227
1228 /**
1229 * Constructs a new buffer reader instance.
1230 * @param buffer Buffer to read from
1231 */
1232 constructor(buffer: Buffer);
1233
1234 /**
1235 * Reads a sequence of bytes preceeded by its length as a varint.
1236 * @returns Value read
1237 */
1238 public bytes(): Buffer;
1239}
1240
1241/** Root namespace wrapping all types, enums, services, sub-namespaces etc. that belong together. */
1242export class Root extends NamespaceBase {
1243
1244 /**
1245 * Constructs a new root namespace instance.
1246 * @param [options] Top level options
1247 */
1248 constructor(options?: { [k: string]: any });
1249
1250 /** Deferred extension fields. */
1251 public deferred: Field[];
1252
1253 /** Resolved file names of loaded files. */
1254 public files: string[];
1255
1256 /**
1257 * Loads a namespace descriptor into a root namespace.
1258 * @param json Nameespace descriptor
1259 * @param [root] Root namespace, defaults to create a new one if omitted
1260 * @returns Root namespace
1261 */
1262 public static fromJSON(json: INamespace, root?: Root): Root;
1263
1264 /**
1265 * Resolves the path of an imported file, relative to the importing origin.
1266 * This method exists so you can override it with your own logic in case your imports are scattered over multiple directories.
1267 * @param origin The file name of the importing file
1268 * @param target The file name being imported
1269 * @returns Resolved path to `target` or `null` to skip the file
1270 */
1271 public resolvePath(origin: string, target: string): (string|null);
1272
1273 /**
1274 * Fetch content from file path or url
1275 * This method exists so you can override it with your own logic.
1276 * @param path File path or url
1277 * @param callback Callback function
1278 */
1279 public fetch(path: string, callback: FetchCallback): void;
1280
1281 /**
1282 * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.
1283 * @param filename Names of one or multiple files to load
1284 * @param options Parse options
1285 * @param callback Callback function
1286 */
1287 public load(filename: (string|string[]), options: IParseOptions, callback: LoadCallback): void;
1288
1289 /**
1290 * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.
1291 * @param filename Names of one or multiple files to load
1292 * @param callback Callback function
1293 */
1294 public load(filename: (string|string[]), callback: LoadCallback): void;
1295
1296 /**
1297 * Loads one or multiple .proto or preprocessed .json files into this root namespace and returns a promise.
1298 * @param filename Names of one or multiple files to load
1299 * @param [options] Parse options. Defaults to {@link parse.defaults} when omitted.
1300 * @returns Promise
1301 */
1302 public load(filename: (string|string[]), options?: IParseOptions): Promise<Root>;
1303
1304 /**
1305 * Synchronously loads one or multiple .proto or preprocessed .json files into this root namespace (node only).
1306 * @param filename Names of one or multiple files to load
1307 * @param [options] Parse options. Defaults to {@link parse.defaults} when omitted.
1308 * @returns Root namespace
1309 * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid
1310 */
1311 public loadSync(filename: (string|string[]), options?: IParseOptions): Root;
1312}
1313
1314/**
1315 * Named roots.
1316 * This is where pbjs stores generated structures (the option `-r, --root` specifies a name).
1317 * Can also be used manually to make roots available across modules.
1318 */
1319export let roots: { [k: string]: Root };
1320
1321/** Streaming RPC helpers. */
1322export namespace rpc {
1323
1324 /**
1325 * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}.
1326 *
1327 * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`.
1328 * @param error Error, if any
1329 * @param [response] Response message
1330 */
1331 type ServiceMethodCallback<TRes extends Message<TRes>> = (error: (Error|null), response?: TRes) => void;
1332
1333 /**
1334 * A service method part of a {@link rpc.Service} as created by {@link Service.create}.
1335 * @param request Request message or plain object
1336 * @param [callback] Node-style callback called with the error, if any, and the response message
1337 * @returns Promise if `callback` has been omitted, otherwise `undefined`
1338 */
1339 type ServiceMethod<TReq extends Message<TReq>, TRes extends Message<TRes>> = (request: (TReq|Properties<TReq>), callback?: rpc.ServiceMethodCallback<TRes>) => Promise<Message<TRes>>;
1340
1341 /** An RPC service as returned by {@link Service#create}. */
1342 class Service extends util.EventEmitter {
1343
1344 /**
1345 * Constructs a new RPC service instance.
1346 * @param rpcImpl RPC implementation
1347 * @param [requestDelimited=false] Whether requests are length-delimited
1348 * @param [responseDelimited=false] Whether responses are length-delimited
1349 */
1350 constructor(rpcImpl: RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean);
1351
1352 /** RPC implementation. Becomes `null` once the service is ended. */
1353 public rpcImpl: (RPCImpl|null);
1354
1355 /** Whether requests are length-delimited. */
1356 public requestDelimited: boolean;
1357
1358 /** Whether responses are length-delimited. */
1359 public responseDelimited: boolean;
1360
1361 /**
1362 * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}.
1363 * @param method Reflected or static method
1364 * @param requestCtor Request constructor
1365 * @param responseCtor Response constructor
1366 * @param request Request message or plain object
1367 * @param callback Service callback
1368 */
1369 public rpcCall<TReq extends Message<TReq>, TRes extends Message<TRes>>(method: (Method|rpc.ServiceMethod<TReq, TRes>), requestCtor: Constructor<TReq>, responseCtor: Constructor<TRes>, request: (TReq|Properties<TReq>), callback: rpc.ServiceMethodCallback<TRes>): void;
1370
1371 /**
1372 * Ends this service and emits the `end` event.
1373 * @param [endedByRPC=false] Whether the service has been ended by the RPC implementation.
1374 * @returns `this`
1375 */
1376 public end(endedByRPC?: boolean): rpc.Service;
1377 }
1378}
1379
1380/**
1381 * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets.
1382 * @param method Reflected or static method being called
1383 * @param requestData Request data
1384 * @param callback Callback function
1385 */
1386type RPCImpl = (method: (Method|rpc.ServiceMethod<Message<{}>, Message<{}>>), requestData: Uint8Array, callback: RPCImplCallback) => void;
1387
1388/**
1389 * Node-style callback as used by {@link RPCImpl}.
1390 * @param error Error, if any, otherwise `null`
1391 * @param [response] Response data or `null` to signal end of stream, if there hasn't been an error
1392 */
1393type RPCImplCallback = (error: (Error|null), response?: (Uint8Array|null)) => void;
1394
1395/** Reflected service. */
1396export class Service extends NamespaceBase {
1397
1398 /**
1399 * Constructs a new service instance.
1400 * @param name Service name
1401 * @param [options] Service options
1402 * @throws {TypeError} If arguments are invalid
1403 */
1404 constructor(name: string, options?: { [k: string]: any });
1405
1406 /** Service methods. */
1407 public methods: { [k: string]: Method };
1408
1409 /**
1410 * Constructs a service from a service descriptor.
1411 * @param name Service name
1412 * @param json Service descriptor
1413 * @returns Created service
1414 * @throws {TypeError} If arguments are invalid
1415 */
1416 public static fromJSON(name: string, json: IService): Service;
1417
1418 /**
1419 * Converts this service to a service descriptor.
1420 * @param [toJSONOptions] JSON conversion options
1421 * @returns Service descriptor
1422 */
1423 public toJSON(toJSONOptions?: IToJSONOptions): IService;
1424
1425 /** Methods of this service as an array for iteration. */
1426 public readonly methodsArray: Method[];
1427
1428 /**
1429 * Creates a runtime service using the specified rpc implementation.
1430 * @param rpcImpl RPC implementation
1431 * @param [requestDelimited=false] Whether requests are length-delimited
1432 * @param [responseDelimited=false] Whether responses are length-delimited
1433 * @returns RPC service. Useful where requests and/or responses are streamed.
1434 */
1435 public create(rpcImpl: RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): rpc.Service;
1436}
1437
1438/** Service descriptor. */
1439export interface IService extends INamespace {
1440
1441 /** Method descriptors */
1442 methods: { [k: string]: IMethod };
1443}
1444
1445/**
1446 * Gets the next token and advances.
1447 * @returns Next token or `null` on eof
1448 */
1449type TokenizerHandleNext = () => (string|null);
1450
1451/**
1452 * Peeks for the next token.
1453 * @returns Next token or `null` on eof
1454 */
1455type TokenizerHandlePeek = () => (string|null);
1456
1457/**
1458 * Pushes a token back to the stack.
1459 * @param token Token
1460 */
1461type TokenizerHandlePush = (token: string) => void;
1462
1463/**
1464 * Skips the next token.
1465 * @param expected Expected token
1466 * @param [optional=false] If optional
1467 * @returns Whether the token matched
1468 * @throws {Error} If the token didn't match and is not optional
1469 */
1470type TokenizerHandleSkip = (expected: string, optional?: boolean) => boolean;
1471
1472/**
1473 * Gets the comment on the previous line or, alternatively, the line comment on the specified line.
1474 * @param [line] Line number
1475 * @returns Comment text or `null` if none
1476 */
1477type TokenizerHandleCmnt = (line?: number) => (string|null);
1478
1479/** Handle object returned from {@link tokenize}. */
1480export interface ITokenizerHandle {
1481
1482 /** Gets the next token and advances (`null` on eof) */
1483 next: TokenizerHandleNext;
1484
1485 /** Peeks for the next token (`null` on eof) */
1486 peek: TokenizerHandlePeek;
1487
1488 /** Pushes a token back to the stack */
1489 push: TokenizerHandlePush;
1490
1491 /** Skips a token, returns its presence and advances or, if non-optional and not present, throws */
1492 skip: TokenizerHandleSkip;
1493
1494 /** Gets the comment on the previous line or the line comment on the specified line, if any */
1495 cmnt: TokenizerHandleCmnt;
1496
1497 /** Current line number */
1498 line: number;
1499}
1500
1501/**
1502 * Tokenizes the given .proto source and returns an object with useful utility functions.
1503 * @param source Source contents
1504 * @param alternateCommentMode Whether we should activate alternate comment parsing mode.
1505 * @returns Tokenizer handle
1506 */
1507export function tokenize(source: string, alternateCommentMode: boolean): ITokenizerHandle;
1508
1509export namespace tokenize {
1510
1511 /**
1512 * Unescapes a string.
1513 * @param str String to unescape
1514 * @returns Unescaped string
1515 */
1516 function unescape(str: string): string;
1517}
1518
1519/** Reflected message type. */
1520export class Type extends NamespaceBase {
1521
1522 /**
1523 * Constructs a new reflected message type instance.
1524 * @param name Message name
1525 * @param [options] Declared options
1526 */
1527 constructor(name: string, options?: { [k: string]: any });
1528
1529 /** Message fields. */
1530 public fields: { [k: string]: Field };
1531
1532 /** Oneofs declared within this namespace, if any. */
1533 public oneofs: { [k: string]: OneOf };
1534
1535 /** Extension ranges, if any. */
1536 public extensions: number[][];
1537
1538 /** Reserved ranges, if any. */
1539 public reserved: (number[]|string)[];
1540
1541 /** Message fields by id. */
1542 public readonly fieldsById: { [k: number]: Field };
1543
1544 /** Fields of this message as an array for iteration. */
1545 public readonly fieldsArray: Field[];
1546
1547 /** Oneofs of this message as an array for iteration. */
1548 public readonly oneofsArray: OneOf[];
1549
1550 /**
1551 * The registered constructor, if any registered, otherwise a generic constructor.
1552 * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor.
1553 */
1554 public ctor: Constructor<{}>;
1555
1556 /**
1557 * Generates a constructor function for the specified type.
1558 * @param mtype Message type
1559 * @returns Codegen instance
1560 */
1561 public static generateConstructor(mtype: Type): Codegen;
1562
1563 /**
1564 * Creates a message type from a message type descriptor.
1565 * @param name Message name
1566 * @param json Message type descriptor
1567 * @returns Created message type
1568 */
1569 public static fromJSON(name: string, json: IType): Type;
1570
1571 /**
1572 * Converts this message type to a message type descriptor.
1573 * @param [toJSONOptions] JSON conversion options
1574 * @returns Message type descriptor
1575 */
1576 public toJSON(toJSONOptions?: IToJSONOptions): IType;
1577
1578 /**
1579 * Adds a nested object to this type.
1580 * @param object Nested object to add
1581 * @returns `this`
1582 * @throws {TypeError} If arguments are invalid
1583 * @throws {Error} If there is already a nested object with this name or, if a field, when there is already a field with this id
1584 */
1585 public add(object: ReflectionObject): Type;
1586
1587 /**
1588 * Removes a nested object from this type.
1589 * @param object Nested object to remove
1590 * @returns `this`
1591 * @throws {TypeError} If arguments are invalid
1592 * @throws {Error} If `object` is not a member of this type
1593 */
1594 public remove(object: ReflectionObject): Type;
1595
1596 /**
1597 * Tests if the specified id is reserved.
1598 * @param id Id to test
1599 * @returns `true` if reserved, otherwise `false`
1600 */
1601 public isReservedId(id: number): boolean;
1602
1603 /**
1604 * Tests if the specified name is reserved.
1605 * @param name Name to test
1606 * @returns `true` if reserved, otherwise `false`
1607 */
1608 public isReservedName(name: string): boolean;
1609
1610 /**
1611 * Creates a new message of this type using the specified properties.
1612 * @param [properties] Properties to set
1613 * @returns Message instance
1614 */
1615 public create(properties?: { [k: string]: any }): Message<{}>;
1616
1617 /**
1618 * Sets up {@link Type#encode|encode}, {@link Type#decode|decode} and {@link Type#verify|verify}.
1619 * @returns `this`
1620 */
1621 public setup(): Type;
1622
1623 /**
1624 * Encodes a message of this type. Does not implicitly {@link Type#verify|verify} messages.
1625 * @param message Message instance or plain object
1626 * @param [writer] Writer to encode to
1627 * @returns writer
1628 */
1629 public encode(message: (Message<{}>|{ [k: string]: any }), writer?: Writer): Writer;
1630
1631 /**
1632 * Encodes a message of this type preceeded by its byte length as a varint. Does not implicitly {@link Type#verify|verify} messages.
1633 * @param message Message instance or plain object
1634 * @param [writer] Writer to encode to
1635 * @returns writer
1636 */
1637 public encodeDelimited(message: (Message<{}>|{ [k: string]: any }), writer?: Writer): Writer;
1638
1639 /**
1640 * Decodes a message of this type.
1641 * @param reader Reader or buffer to decode from
1642 * @param [length] Length of the message, if known beforehand
1643 * @returns Decoded message
1644 * @throws {Error} If the payload is not a reader or valid buffer
1645 * @throws {util.ProtocolError<{}>} If required fields are missing
1646 */
1647 public decode(reader: (Reader|Uint8Array), length?: number): Message<{}>;
1648
1649 /**
1650 * Decodes a message of this type preceeded by its byte length as a varint.
1651 * @param reader Reader or buffer to decode from
1652 * @returns Decoded message
1653 * @throws {Error} If the payload is not a reader or valid buffer
1654 * @throws {util.ProtocolError} If required fields are missing
1655 */
1656 public decodeDelimited(reader: (Reader|Uint8Array)): Message<{}>;
1657
1658 /**
1659 * Verifies that field values are valid and that required fields are present.
1660 * @param message Plain object to verify
1661 * @returns `null` if valid, otherwise the reason why it is not
1662 */
1663 public verify(message: { [k: string]: any }): (null|string);
1664
1665 /**
1666 * Creates a new message of this type from a plain object. Also converts values to their respective internal types.
1667 * @param object Plain object to convert
1668 * @returns Message instance
1669 */
1670 public fromObject(object: { [k: string]: any }): Message<{}>;
1671
1672 /**
1673 * Creates a plain object from a message of this type. Also converts values to other types if specified.
1674 * @param message Message instance
1675 * @param [options] Conversion options
1676 * @returns Plain object
1677 */
1678 public toObject(message: Message<{}>, options?: IConversionOptions): { [k: string]: any };
1679
1680 /**
1681 * Type decorator (TypeScript).
1682 * @param [typeName] Type name, defaults to the constructor's name
1683 * @returns Decorator function
1684 */
1685 public static d<T extends Message<T>>(typeName?: string): TypeDecorator<T>;
1686}
1687
1688/** Message type descriptor. */
1689export interface IType extends INamespace {
1690
1691 /** Oneof descriptors */
1692 oneofs?: { [k: string]: IOneOf };
1693
1694 /** Field descriptors */
1695 fields: { [k: string]: IField };
1696
1697 /** Extension ranges */
1698 extensions?: number[][];
1699
1700 /** Reserved ranges */
1701 reserved?: (number[]|string)[];
1702
1703 /** Whether a legacy group or not */
1704 group?: boolean;
1705}
1706
1707/** Conversion options as used by {@link Type#toObject} and {@link Message.toObject}. */
1708export interface IConversionOptions {
1709
1710 /**
1711 * Long conversion type.
1712 * Valid values are `String` and `Number` (the global types).
1713 * Defaults to copy the present value, which is a possibly unsafe number without and a {@link Long} with a long library.
1714 */
1715 longs?: Function;
1716
1717 /**
1718 * Enum value conversion type.
1719 * Only valid value is `String` (the global type).
1720 * Defaults to copy the present value, which is the numeric id.
1721 */
1722 enums?: Function;
1723
1724 /**
1725 * Bytes value conversion type.
1726 * Valid values are `Array` and (a base64 encoded) `String` (the global types).
1727 * Defaults to copy the present value, which usually is a Buffer under node and an Uint8Array in the browser.
1728 */
1729 bytes?: Function;
1730
1731 /** Also sets default values on the resulting object */
1732 defaults?: boolean;
1733
1734 /** Sets empty arrays for missing repeated fields even if `defaults=false` */
1735 arrays?: boolean;
1736
1737 /** Sets empty objects for missing map fields even if `defaults=false` */
1738 objects?: boolean;
1739
1740 /** Includes virtual oneof properties set to the present field's name, if any */
1741 oneofs?: boolean;
1742
1743 /** Performs additional JSON compatibility conversions, i.e. NaN and Infinity to strings */
1744 json?: boolean;
1745}
1746
1747/**
1748 * Decorator function as returned by {@link Type.d} (TypeScript).
1749 * @param target Target constructor
1750 */
1751type TypeDecorator<T extends Message<T>> = (target: Constructor<T>) => void;
1752
1753/** Common type constants. */
1754export namespace types {
1755
1756 /** Basic type wire types. */
1757 const basic: {
1758 "double": number,
1759 "float": number,
1760 "int32": number,
1761 "uint32": number,
1762 "sint32": number,
1763 "fixed32": number,
1764 "sfixed32": number,
1765 "int64": number,
1766 "uint64": number,
1767 "sint64": number,
1768 "fixed64": number,
1769 "sfixed64": number,
1770 "bool": number,
1771 "string": number,
1772 "bytes": number
1773 };
1774
1775 /** Basic type defaults. */
1776 const defaults: {
1777 "double": number,
1778 "float": number,
1779 "int32": number,
1780 "uint32": number,
1781 "sint32": number,
1782 "fixed32": number,
1783 "sfixed32": number,
1784 "int64": number,
1785 "uint64": number,
1786 "sint64": number,
1787 "fixed64": number,
1788 "sfixed64": number,
1789 "bool": boolean,
1790 "string": string,
1791 "bytes": number[],
1792 "message": null
1793 };
1794
1795 /** Basic long type wire types. */
1796 const long: {
1797 "int64": number,
1798 "uint64": number,
1799 "sint64": number,
1800 "fixed64": number,
1801 "sfixed64": number
1802 };
1803
1804 /** Allowed types for map keys with their associated wire type. */
1805 const mapKey: {
1806 "int32": number,
1807 "uint32": number,
1808 "sint32": number,
1809 "fixed32": number,
1810 "sfixed32": number,
1811 "int64": number,
1812 "uint64": number,
1813 "sint64": number,
1814 "fixed64": number,
1815 "sfixed64": number,
1816 "bool": number,
1817 "string": number
1818 };
1819
1820 /** Allowed types for packed repeated fields with their associated wire type. */
1821 const packed: {
1822 "double": number,
1823 "float": number,
1824 "int32": number,
1825 "uint32": number,
1826 "sint32": number,
1827 "fixed32": number,
1828 "sfixed32": number,
1829 "int64": number,
1830 "uint64": number,
1831 "sint64": number,
1832 "fixed64": number,
1833 "sfixed64": number,
1834 "bool": number
1835 };
1836}
1837
1838/** Constructor type. */
1839export interface Constructor<T> extends Function {
1840 new(...params: any[]): T; prototype: T;
1841}
1842
1843/** Properties type. */
1844type Properties<T> = { [P in keyof T]?: T[P] };
1845
1846/**
1847 * Any compatible Buffer instance.
1848 * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings.
1849 */
1850export interface Buffer extends Uint8Array {
1851}
1852
1853/**
1854 * Any compatible Long instance.
1855 * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js.
1856 */
1857export interface Long {
1858
1859 /** Low bits */
1860 low: number;
1861
1862 /** High bits */
1863 high: number;
1864
1865 /** Whether unsigned or not */
1866 unsigned: boolean;
1867}
1868
1869/**
1870 * A OneOf getter as returned by {@link util.oneOfGetter}.
1871 * @returns Set field name, if any
1872 */
1873type OneOfGetter = () => (string|undefined);
1874
1875/**
1876 * A OneOf setter as returned by {@link util.oneOfSetter}.
1877 * @param value Field name
1878 */
1879type OneOfSetter = (value: (string|undefined)) => void;
1880
1881/** Various utility functions. */
1882export namespace util {
1883
1884 /** Helper class for working with the low and high bits of a 64 bit value. */
1885 class LongBits {
1886
1887 /**
1888 * Constructs new long bits.
1889 * @param lo Low 32 bits, unsigned
1890 * @param hi High 32 bits, unsigned
1891 */
1892 constructor(lo: number, hi: number);
1893
1894 /** Low bits. */
1895 public lo: number;
1896
1897 /** High bits. */
1898 public hi: number;
1899
1900 /** Zero bits. */
1901 public static zero: util.LongBits;
1902
1903 /** Zero hash. */
1904 public static zeroHash: string;
1905
1906 /**
1907 * Constructs new long bits from the specified number.
1908 * @param value Value
1909 * @returns Instance
1910 */
1911 public static fromNumber(value: number): util.LongBits;
1912
1913 /**
1914 * Constructs new long bits from a number, long or string.
1915 * @param value Value
1916 * @returns Instance
1917 */
1918 public static from(value: (Long|number|string)): util.LongBits;
1919
1920 /**
1921 * Converts this long bits to a possibly unsafe JavaScript number.
1922 * @param [unsigned=false] Whether unsigned or not
1923 * @returns Possibly unsafe number
1924 */
1925 public toNumber(unsigned?: boolean): number;
1926
1927 /**
1928 * Converts this long bits to a long.
1929 * @param [unsigned=false] Whether unsigned or not
1930 * @returns Long
1931 */
1932 public toLong(unsigned?: boolean): Long;
1933
1934 /**
1935 * Constructs new long bits from the specified 8 characters long hash.
1936 * @param hash Hash
1937 * @returns Bits
1938 */
1939 public static fromHash(hash: string): util.LongBits;
1940
1941 /**
1942 * Converts this long bits to a 8 characters long hash.
1943 * @returns Hash
1944 */
1945 public toHash(): string;
1946
1947 /**
1948 * Zig-zag encodes this long bits.
1949 * @returns `this`
1950 */
1951 public zzEncode(): util.LongBits;
1952
1953 /**
1954 * Zig-zag decodes this long bits.
1955 * @returns `this`
1956 */
1957 public zzDecode(): util.LongBits;
1958
1959 /**
1960 * Calculates the length of this longbits when encoded as a varint.
1961 * @returns Length
1962 */
1963 public length(): number;
1964 }
1965
1966 /** Whether running within node or not. */
1967 let isNode: boolean;
1968
1969 /** Global object reference. */
1970 let global: object;
1971
1972 /** An immuable empty array. */
1973 const emptyArray: any[];
1974
1975 /** An immutable empty object. */
1976 const emptyObject: object;
1977
1978 /**
1979 * Tests if the specified value is an integer.
1980 * @param value Value to test
1981 * @returns `true` if the value is an integer
1982 */
1983 function isInteger(value: any): boolean;
1984
1985 /**
1986 * Tests if the specified value is a string.
1987 * @param value Value to test
1988 * @returns `true` if the value is a string
1989 */
1990 function isString(value: any): boolean;
1991
1992 /**
1993 * Tests if the specified value is a non-null object.
1994 * @param value Value to test
1995 * @returns `true` if the value is a non-null object
1996 */
1997 function isObject(value: any): boolean;
1998
1999 /**
2000 * Checks if a property on a message is considered to be present.
2001 * This is an alias of {@link util.isSet}.
2002 * @param obj Plain object or message instance
2003 * @param prop Property name
2004 * @returns `true` if considered to be present, otherwise `false`
2005 */
2006 function isset(obj: object, prop: string): boolean;
2007
2008 /**
2009 * Checks if a property on a message is considered to be present.
2010 * @param obj Plain object or message instance
2011 * @param prop Property name
2012 * @returns `true` if considered to be present, otherwise `false`
2013 */
2014 function isSet(obj: object, prop: string): boolean;
2015
2016 /** Node's Buffer class if available. */
2017 let Buffer: Constructor<Buffer>;
2018
2019 /**
2020 * Creates a new buffer of whatever type supported by the environment.
2021 * @param [sizeOrArray=0] Buffer size or number array
2022 * @returns Buffer
2023 */
2024 function newBuffer(sizeOrArray?: (number|number[])): (Uint8Array|Buffer);
2025
2026 /** Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`. */
2027 let Array: Constructor<Uint8Array>;
2028
2029 /** Long.js's Long class if available. */
2030 let Long: Constructor<Long>;
2031
2032 /** Regular expression used to verify 2 bit (`bool`) map keys. */
2033 const key2Re: RegExp;
2034
2035 /** Regular expression used to verify 32 bit (`int32` etc.) map keys. */
2036 const key32Re: RegExp;
2037
2038 /** Regular expression used to verify 64 bit (`int64` etc.) map keys. */
2039 const key64Re: RegExp;
2040
2041 /**
2042 * Converts a number or long to an 8 characters long hash string.
2043 * @param value Value to convert
2044 * @returns Hash
2045 */
2046 function longToHash(value: (Long|number)): string;
2047
2048 /**
2049 * Converts an 8 characters long hash string to a long or number.
2050 * @param hash Hash
2051 * @param [unsigned=false] Whether unsigned or not
2052 * @returns Original value
2053 */
2054 function longFromHash(hash: string, unsigned?: boolean): (Long|number);
2055
2056 /**
2057 * Merges the properties of the source object into the destination object.
2058 * @param dst Destination object
2059 * @param src Source object
2060 * @param [ifNotSet=false] Merges only if the key is not already set
2061 * @returns Destination object
2062 */
2063 function merge(dst: { [k: string]: any }, src: { [k: string]: any }, ifNotSet?: boolean): { [k: string]: any };
2064
2065 /**
2066 * Converts the first character of a string to lower case.
2067 * @param str String to convert
2068 * @returns Converted string
2069 */
2070 function lcFirst(str: string): string;
2071
2072 /**
2073 * Creates a custom error constructor.
2074 * @param name Error name
2075 * @returns Custom error constructor
2076 */
2077 function newError(name: string): Constructor<Error>;
2078
2079 /** Error subclass indicating a protocol specifc error. */
2080 class ProtocolError<T extends Message<T>> extends Error {
2081
2082 /**
2083 * Constructs a new protocol error.
2084 * @param message Error message
2085 * @param [properties] Additional properties
2086 */
2087 constructor(message: string, properties?: { [k: string]: any });
2088
2089 /** So far decoded message instance. */
2090 public instance: Message<T>;
2091 }
2092
2093 /**
2094 * Builds a getter for a oneof's present field name.
2095 * @param fieldNames Field names
2096 * @returns Unbound getter
2097 */
2098 function oneOfGetter(fieldNames: string[]): OneOfGetter;
2099
2100 /**
2101 * Builds a setter for a oneof's present field name.
2102 * @param fieldNames Field names
2103 * @returns Unbound setter
2104 */
2105 function oneOfSetter(fieldNames: string[]): OneOfSetter;
2106
2107 /**
2108 * Default conversion options used for {@link Message#toJSON} implementations.
2109 *
2110 * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely:
2111 *
2112 * - Longs become strings
2113 * - Enums become string keys
2114 * - Bytes become base64 encoded strings
2115 * - (Sub-)Messages become plain objects
2116 * - Maps become plain objects with all string keys
2117 * - Repeated fields become arrays
2118 * - NaN and Infinity for float and double fields become strings
2119 *
2120 * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json
2121 */
2122 let toJSONOptions: IConversionOptions;
2123
2124 /** Node's fs module if available. */
2125 let fs: { [k: string]: any };
2126
2127 /**
2128 * Converts an object's values to an array.
2129 * @param object Object to convert
2130 * @returns Converted array
2131 */
2132 function toArray(object: { [k: string]: any }): any[];
2133
2134 /**
2135 * Converts an array of keys immediately followed by their respective value to an object, omitting undefined values.
2136 * @param array Array to convert
2137 * @returns Converted object
2138 */
2139 function toObject(array: any[]): { [k: string]: any };
2140
2141 /**
2142 * Tests whether the specified name is a reserved word in JS.
2143 * @param name Name to test
2144 * @returns `true` if reserved, otherwise `false`
2145 */
2146 function isReserved(name: string): boolean;
2147
2148 /**
2149 * Returns a safe property accessor for the specified property name.
2150 * @param prop Property name
2151 * @returns Safe accessor
2152 */
2153 function safeProp(prop: string): string;
2154
2155 /**
2156 * Converts the first character of a string to upper case.
2157 * @param str String to convert
2158 * @returns Converted string
2159 */
2160 function ucFirst(str: string): string;
2161
2162 /**
2163 * Converts a string to camel case.
2164 * @param str String to convert
2165 * @returns Converted string
2166 */
2167 function camelCase(str: string): string;
2168
2169 /**
2170 * Compares reflected fields by id.
2171 * @param a First field
2172 * @param b Second field
2173 * @returns Comparison value
2174 */
2175 function compareFieldsById(a: Field, b: Field): number;
2176
2177 /**
2178 * Decorator helper for types (TypeScript).
2179 * @param ctor Constructor function
2180 * @param [typeName] Type name, defaults to the constructor's name
2181 * @returns Reflected type
2182 */
2183 function decorateType<T extends Message<T>>(ctor: Constructor<T>, typeName?: string): Type;
2184
2185 /**
2186 * Decorator helper for enums (TypeScript).
2187 * @param object Enum object
2188 * @returns Reflected enum
2189 */
2190 function decorateEnum(object: object): Enum;
2191
2192 /**
2193 * Sets the value of a property by property path. If a value already exists, it is turned to an array
2194 * @param dst Destination object
2195 * @param path dot '.' delimited path of the property to set
2196 * @param value the value to set
2197 * @returns Destination object
2198 */
2199 function setProperty(dst: { [k: string]: any }, path: string, value: object): { [k: string]: any };
2200
2201 /** Decorator root (TypeScript). */
2202 let decorateRoot: Root;
2203
2204 /**
2205 * Returns a promise from a node-style callback function.
2206 * @param fn Function to call
2207 * @param ctx Function context
2208 * @param params Function arguments
2209 * @returns Promisified function
2210 */
2211 function asPromise(fn: asPromiseCallback, ctx: any, ...params: any[]): Promise<any>;
2212
2213 /** A minimal base64 implementation for number arrays. */
2214 namespace base64 {
2215
2216 /**
2217 * Calculates the byte length of a base64 encoded string.
2218 * @param string Base64 encoded string
2219 * @returns Byte length
2220 */
2221 function length(string: string): number;
2222
2223 /**
2224 * Encodes a buffer to a base64 encoded string.
2225 * @param buffer Source buffer
2226 * @param start Source start
2227 * @param end Source end
2228 * @returns Base64 encoded string
2229 */
2230 function encode(buffer: Uint8Array, start: number, end: number): string;
2231
2232 /**
2233 * Decodes a base64 encoded string to a buffer.
2234 * @param string Source string
2235 * @param buffer Destination buffer
2236 * @param offset Destination offset
2237 * @returns Number of bytes written
2238 * @throws {Error} If encoding is invalid
2239 */
2240 function decode(string: string, buffer: Uint8Array, offset: number): number;
2241
2242 /**
2243 * Tests if the specified string appears to be base64 encoded.
2244 * @param string String to test
2245 * @returns `true` if probably base64 encoded, otherwise false
2246 */
2247 function test(string: string): boolean;
2248 }
2249
2250 /**
2251 * Begins generating a function.
2252 * @param functionParams Function parameter names
2253 * @param [functionName] Function name if not anonymous
2254 * @returns Appender that appends code to the function's body
2255 */
2256 function codegen(functionParams: string[], functionName?: string): Codegen;
2257
2258 namespace codegen {
2259
2260 /** When set to `true`, codegen will log generated code to console. Useful for debugging. */
2261 let verbose: boolean;
2262 }
2263
2264 /**
2265 * Begins generating a function.
2266 * @param [functionName] Function name if not anonymous
2267 * @returns Appender that appends code to the function's body
2268 */
2269 function codegen(functionName?: string): Codegen;
2270
2271 /** A minimal event emitter. */
2272 class EventEmitter {
2273
2274 /** Constructs a new event emitter instance. */
2275 constructor();
2276
2277 /**
2278 * Registers an event listener.
2279 * @param evt Event name
2280 * @param fn Listener
2281 * @param [ctx] Listener context
2282 * @returns `this`
2283 */
2284 public on(evt: string, fn: EventEmitterListener, ctx?: any): this;
2285
2286 /**
2287 * Removes an event listener or any matching listeners if arguments are omitted.
2288 * @param [evt] Event name. Removes all listeners if omitted.
2289 * @param [fn] Listener to remove. Removes all listeners of `evt` if omitted.
2290 * @returns `this`
2291 */
2292 public off(evt?: string, fn?: EventEmitterListener): this;
2293
2294 /**
2295 * Emits an event by calling its listeners with the specified arguments.
2296 * @param evt Event name
2297 * @param args Arguments
2298 * @returns `this`
2299 */
2300 public emit(evt: string, ...args: any[]): this;
2301 }
2302
2303 /** Reads / writes floats / doubles from / to buffers. */
2304 namespace float {
2305
2306 /**
2307 * Writes a 32 bit float to a buffer using little endian byte order.
2308 * @param val Value to write
2309 * @param buf Target buffer
2310 * @param pos Target buffer offset
2311 */
2312 function writeFloatLE(val: number, buf: Uint8Array, pos: number): void;
2313
2314 /**
2315 * Writes a 32 bit float to a buffer using big endian byte order.
2316 * @param val Value to write
2317 * @param buf Target buffer
2318 * @param pos Target buffer offset
2319 */
2320 function writeFloatBE(val: number, buf: Uint8Array, pos: number): void;
2321
2322 /**
2323 * Reads a 32 bit float from a buffer using little endian byte order.
2324 * @param buf Source buffer
2325 * @param pos Source buffer offset
2326 * @returns Value read
2327 */
2328 function readFloatLE(buf: Uint8Array, pos: number): number;
2329
2330 /**
2331 * Reads a 32 bit float from a buffer using big endian byte order.
2332 * @param buf Source buffer
2333 * @param pos Source buffer offset
2334 * @returns Value read
2335 */
2336 function readFloatBE(buf: Uint8Array, pos: number): number;
2337
2338 /**
2339 * Writes a 64 bit double to a buffer using little endian byte order.
2340 * @param val Value to write
2341 * @param buf Target buffer
2342 * @param pos Target buffer offset
2343 */
2344 function writeDoubleLE(val: number, buf: Uint8Array, pos: number): void;
2345
2346 /**
2347 * Writes a 64 bit double to a buffer using big endian byte order.
2348 * @param val Value to write
2349 * @param buf Target buffer
2350 * @param pos Target buffer offset
2351 */
2352 function writeDoubleBE(val: number, buf: Uint8Array, pos: number): void;
2353
2354 /**
2355 * Reads a 64 bit double from a buffer using little endian byte order.
2356 * @param buf Source buffer
2357 * @param pos Source buffer offset
2358 * @returns Value read
2359 */
2360 function readDoubleLE(buf: Uint8Array, pos: number): number;
2361
2362 /**
2363 * Reads a 64 bit double from a buffer using big endian byte order.
2364 * @param buf Source buffer
2365 * @param pos Source buffer offset
2366 * @returns Value read
2367 */
2368 function readDoubleBE(buf: Uint8Array, pos: number): number;
2369 }
2370
2371 /**
2372 * Fetches the contents of a file.
2373 * @param filename File path or url
2374 * @param options Fetch options
2375 * @param callback Callback function
2376 */
2377 function fetch(filename: string, options: IFetchOptions, callback: FetchCallback): void;
2378
2379 /**
2380 * Fetches the contents of a file.
2381 * @param path File path or url
2382 * @param callback Callback function
2383 */
2384 function fetch(path: string, callback: FetchCallback): void;
2385
2386 /**
2387 * Fetches the contents of a file.
2388 * @param path File path or url
2389 * @param [options] Fetch options
2390 * @returns Promise
2391 */
2392 function fetch(path: string, options?: IFetchOptions): Promise<(string|Uint8Array)>;
2393
2394 /**
2395 * Requires a module only if available.
2396 * @param moduleName Module to require
2397 * @returns Required module if available and not empty, otherwise `null`
2398 */
2399 function inquire(moduleName: string): object;
2400
2401 /** A minimal path module to resolve Unix, Windows and URL paths alike. */
2402 namespace path {
2403
2404 /**
2405 * Tests if the specified path is absolute.
2406 * @param path Path to test
2407 * @returns `true` if path is absolute
2408 */
2409 function isAbsolute(path: string): boolean;
2410
2411 /**
2412 * Normalizes the specified path.
2413 * @param path Path to normalize
2414 * @returns Normalized path
2415 */
2416 function normalize(path: string): string;
2417
2418 /**
2419 * Resolves the specified include path against the specified origin path.
2420 * @param originPath Path to the origin file
2421 * @param includePath Include path relative to origin path
2422 * @param [alreadyNormalized=false] `true` if both paths are already known to be normalized
2423 * @returns Path to the include file
2424 */
2425 function resolve(originPath: string, includePath: string, alreadyNormalized?: boolean): string;
2426 }
2427
2428 /**
2429 * A general purpose buffer pool.
2430 * @param alloc Allocator
2431 * @param slice Slicer
2432 * @param [size=8192] Slab size
2433 * @returns Pooled allocator
2434 */
2435 function pool(alloc: PoolAllocator, slice: PoolSlicer, size?: number): PoolAllocator;
2436
2437 /** A minimal UTF8 implementation for number arrays. */
2438 namespace utf8 {
2439
2440 /**
2441 * Calculates the UTF8 byte length of a string.
2442 * @param string String
2443 * @returns Byte length
2444 */
2445 function length(string: string): number;
2446
2447 /**
2448 * Reads UTF8 bytes as a string.
2449 * @param buffer Source buffer
2450 * @param start Source start
2451 * @param end Source end
2452 * @returns String read
2453 */
2454 function read(buffer: Uint8Array, start: number, end: number): string;
2455
2456 /**
2457 * Writes a string as UTF8 bytes.
2458 * @param string Source string
2459 * @param buffer Destination buffer
2460 * @param offset Destination offset
2461 * @returns Bytes written
2462 */
2463 function write(string: string, buffer: Uint8Array, offset: number): number;
2464 }
2465}
2466
2467/**
2468 * Generates a verifier specific to the specified message type.
2469 * @param mtype Message type
2470 * @returns Codegen instance
2471 */
2472export function verifier(mtype: Type): Codegen;
2473
2474/** Wrappers for common types. */
2475export const wrappers: { [k: string]: IWrapper };
2476
2477/**
2478 * From object converter part of an {@link IWrapper}.
2479 * @param object Plain object
2480 * @returns Message instance
2481 */
2482type WrapperFromObjectConverter = (this: Type, object: { [k: string]: any }) => Message<{}>;
2483
2484/**
2485 * To object converter part of an {@link IWrapper}.
2486 * @param message Message instance
2487 * @param [options] Conversion options
2488 * @returns Plain object
2489 */
2490type WrapperToObjectConverter = (this: Type, message: Message<{}>, options?: IConversionOptions) => { [k: string]: any };
2491
2492/** Common type wrapper part of {@link wrappers}. */
2493export interface IWrapper {
2494
2495 /** From object converter */
2496 fromObject?: WrapperFromObjectConverter;
2497
2498 /** To object converter */
2499 toObject?: WrapperToObjectConverter;
2500}
2501
2502/** Wire format writer using `Uint8Array` if available, otherwise `Array`. */
2503export class Writer {
2504
2505 /** Constructs a new writer instance. */
2506 constructor();
2507
2508 /** Current length. */
2509 public len: number;
2510
2511 /** Operations head. */
2512 public head: object;
2513
2514 /** Operations tail */
2515 public tail: object;
2516
2517 /** Linked forked states. */
2518 public states: (object|null);
2519
2520 /**
2521 * Creates a new writer.
2522 * @returns A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer}
2523 */
2524 public static create(): (BufferWriter|Writer);
2525
2526 /**
2527 * Allocates a buffer of the specified size.
2528 * @param size Buffer size
2529 * @returns Buffer
2530 */
2531 public static alloc(size: number): Uint8Array;
2532
2533 /**
2534 * Writes an unsigned 32 bit value as a varint.
2535 * @param value Value to write
2536 * @returns `this`
2537 */
2538 public uint32(value: number): Writer;
2539
2540 /**
2541 * Writes a signed 32 bit value as a varint.
2542 * @param value Value to write
2543 * @returns `this`
2544 */
2545 public int32(value: number): Writer;
2546
2547 /**
2548 * Writes a 32 bit value as a varint, zig-zag encoded.
2549 * @param value Value to write
2550 * @returns `this`
2551 */
2552 public sint32(value: number): Writer;
2553
2554 /**
2555 * Writes an unsigned 64 bit value as a varint.
2556 * @param value Value to write
2557 * @returns `this`
2558 * @throws {TypeError} If `value` is a string and no long library is present.
2559 */
2560 public uint64(value: (Long|number|string)): Writer;
2561
2562 /**
2563 * Writes a signed 64 bit value as a varint.
2564 * @param value Value to write
2565 * @returns `this`
2566 * @throws {TypeError} If `value` is a string and no long library is present.
2567 */
2568 public int64(value: (Long|number|string)): Writer;
2569
2570 /**
2571 * Writes a signed 64 bit value as a varint, zig-zag encoded.
2572 * @param value Value to write
2573 * @returns `this`
2574 * @throws {TypeError} If `value` is a string and no long library is present.
2575 */
2576 public sint64(value: (Long|number|string)): Writer;
2577
2578 /**
2579 * Writes a boolish value as a varint.
2580 * @param value Value to write
2581 * @returns `this`
2582 */
2583 public bool(value: boolean): Writer;
2584
2585 /**
2586 * Writes an unsigned 32 bit value as fixed 32 bits.
2587 * @param value Value to write
2588 * @returns `this`
2589 */
2590 public fixed32(value: number): Writer;
2591
2592 /**
2593 * Writes a signed 32 bit value as fixed 32 bits.
2594 * @param value Value to write
2595 * @returns `this`
2596 */
2597 public sfixed32(value: number): Writer;
2598
2599 /**
2600 * Writes an unsigned 64 bit value as fixed 64 bits.
2601 * @param value Value to write
2602 * @returns `this`
2603 * @throws {TypeError} If `value` is a string and no long library is present.
2604 */
2605 public fixed64(value: (Long|number|string)): Writer;
2606
2607 /**
2608 * Writes a signed 64 bit value as fixed 64 bits.
2609 * @param value Value to write
2610 * @returns `this`
2611 * @throws {TypeError} If `value` is a string and no long library is present.
2612 */
2613 public sfixed64(value: (Long|number|string)): Writer;
2614
2615 /**
2616 * Writes a float (32 bit).
2617 * @param value Value to write
2618 * @returns `this`
2619 */
2620 public float(value: number): Writer;
2621
2622 /**
2623 * Writes a double (64 bit float).
2624 * @param value Value to write
2625 * @returns `this`
2626 */
2627 public double(value: number): Writer;
2628
2629 /**
2630 * Writes a sequence of bytes.
2631 * @param value Buffer or base64 encoded string to write
2632 * @returns `this`
2633 */
2634 public bytes(value: (Uint8Array|string)): Writer;
2635
2636 /**
2637 * Writes a string.
2638 * @param value Value to write
2639 * @returns `this`
2640 */
2641 public string(value: string): Writer;
2642
2643 /**
2644 * Forks this writer's state by pushing it to a stack.
2645 * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.
2646 * @returns `this`
2647 */
2648 public fork(): Writer;
2649
2650 /**
2651 * Resets this instance to the last state.
2652 * @returns `this`
2653 */
2654 public reset(): Writer;
2655
2656 /**
2657 * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.
2658 * @returns `this`
2659 */
2660 public ldelim(): Writer;
2661
2662 /**
2663 * Finishes the write operation.
2664 * @returns Finished buffer
2665 */
2666 public finish(): Uint8Array;
2667}
2668
2669/** Wire format writer using node buffers. */
2670export class BufferWriter extends Writer {
2671
2672 /** Constructs a new buffer writer instance. */
2673 constructor();
2674
2675 /**
2676 * Allocates a buffer of the specified size.
2677 * @param size Buffer size
2678 * @returns Buffer
2679 */
2680 public static alloc(size: number): Buffer;
2681
2682 /**
2683 * Finishes the write operation.
2684 * @returns Finished buffer
2685 */
2686 public finish(): Buffer;
2687}
2688
2689/**
2690 * Callback as used by {@link util.asPromise}.
2691 * @param error Error, if any
2692 * @param params Additional arguments
2693 */
2694type asPromiseCallback = (error: (Error|null), ...params: any[]) => void;
2695
2696/**
2697 * Appends code to the function's body or finishes generation.
2698 * @param [formatStringOrScope] Format string or, to finish the function, an object of additional scope variables, if any
2699 * @param [formatParams] Format parameters
2700 * @returns Itself or the generated function if finished
2701 * @throws {Error} If format parameter counts do not match
2702 */
2703type Codegen = (formatStringOrScope?: (string|{ [k: string]: any }), ...formatParams: any[]) => (Codegen|Function);
2704
2705/**
2706 * Event listener as used by {@link util.EventEmitter}.
2707 * @param args Arguments
2708 */
2709type EventEmitterListener = (...args: any[]) => void;
2710
2711/**
2712 * Node-style callback as used by {@link util.fetch}.
2713 * @param error Error, if any, otherwise `null`
2714 * @param [contents] File contents, if there hasn't been an error
2715 */
2716type FetchCallback = (error: Error, contents?: string) => void;
2717
2718/** Options as used by {@link util.fetch}. */
2719export interface IFetchOptions {
2720
2721 /** Whether expecting a binary response */
2722 binary?: boolean;
2723
2724 /** If `true`, forces the use of XMLHttpRequest */
2725 xhr?: boolean;
2726}
2727
2728/**
2729 * An allocator as used by {@link util.pool}.
2730 * @param size Buffer size
2731 * @returns Buffer
2732 */
2733type PoolAllocator = (size: number) => Uint8Array;
2734
2735/**
2736 * A slicer as used by {@link util.pool}.
2737 * @param start Start offset
2738 * @param end End offset
2739 * @returns Buffer slice
2740 */
2741type PoolSlicer = (this: Uint8Array, start: number, end: number) => Uint8Array;