forked from stephenh/ts-proto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
2590 lines (2343 loc) · 93.4 KB
/
main.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { code, Code, conditionalOutput, def, imp, joinCode } from "ts-poet";
import { ConditionalOutput } from "ts-poet/build/ConditionalOutput";
import {
DescriptorProto,
FieldDescriptorProto,
FieldDescriptorProto_Label,
FieldDescriptorProto_Type,
FieldOptions_JSType,
FileDescriptorProto,
} from "ts-proto-descriptors";
import { camelToSnake, capitalize, maybeSnakeToCamel } from "./case";
import { Context } from "./context";
import { generateEnum } from "./enums";
import { generateDecodeTransform, generateEncodeTransform } from "./generate-async-iterable";
import { generateGenericServiceDefinition } from "./generate-generic-service-definition";
import { generateGrpcJsService } from "./generate-grpc-js";
import {
addGrpcWebMisc,
generateGrpcClientImpl,
generateGrpcMethodDesc,
generateGrpcServiceDesc,
} from "./generate-grpc-web";
import {
generateNestjsGrpcServiceMethodsDecorator,
generateNestjsServiceClient,
generateNestjsServiceController,
} from "./generate-nestjs";
import { generateNiceGrpcService } from "./generate-nice-grpc";
import {
generateDataLoaderOptionsType,
generateDataLoadersType,
generateRpcType,
generateService,
generateServiceClientImpl,
} from "./generate-services";
import {
generateUnwrapDeep,
generateUnwrapShallow,
generateWrapDeep,
generateWrapShallow,
isWrapperType,
} from "./generate-struct-wrappers";
import {
addTypeToMessages,
DateOption,
EnvOption,
JsonTimestampOption,
LongOption,
OneofOption,
Options,
ServiceOption,
} from "./options";
import { generateSchema } from "./schema";
import SourceInfo, { Fields } from "./sourceInfo";
import {
basicLongWireType,
basicTypeName,
basicWireType,
defaultValue,
detectMapType,
getEnumMethod,
getFieldOptionsJsType,
isAnyValueType,
isBytes,
isBytesValueType,
isEnum,
isFieldMaskType,
isFieldMaskTypeName,
isJsTypeFieldOption,
isListValueType,
isLong,
isLongValueType,
isMapType,
isMessage,
isObjectId,
isOptionalProperty,
isPrimitive,
isRepeated,
isScalar,
isStructType,
isTimestamp,
isValueType,
isWholeNumber,
isWithinOneOf,
isWithinOneOfThatShouldBeUnion,
notDefaultCheck,
packedType,
shouldGenerateJSMapType,
toReaderCall,
toTypeName,
valueTypeName,
} from "./types";
import {
assertInstanceOf,
FormattedMethodDescriptor,
getFieldJsonName,
getFieldName,
getPropertyAccessor,
impFile,
impProto,
maybeAddComment,
nullOrUndefined,
maybePrefixPackage,
safeAccessor,
withOrMaybeCheckIsNull,
withAndMaybeCheckIsNotNull,
withOrMaybeCheckIsNotNull,
withAndMaybeCheckIsNull,
} from "./utils";
import { visit, visitServices } from "./visit";
export function generateFile(ctx: Context, fileDesc: FileDescriptorProto): [string, Code] {
const { options, utils } = ctx;
if (options.useOptionals === false) {
console.warn(
"ts-proto: Passing useOptionals as a boolean option is deprecated and will be removed in a future version. Please pass the string 'none' instead of false.",
);
options.useOptionals = "none";
} else if (options.useOptionals === true) {
console.warn(
"ts-proto: Passing useOptionals as a boolean option is deprecated and will be removed in a future version. Please pass the string 'messages' instead of true.",
);
options.useOptionals = "messages";
}
// Google's protofiles are organized like Java, where package == the folder the file
// is in, and file == a specific service within the package. I.e. you can have multiple
// company/foo.proto and company/bar.proto files, where package would be 'company'.
//
// We'll match that structure by setting up the module path as:
//
// company/foo.proto --> company/foo.ts
// company/bar.proto --> company/bar.ts
//
// We'll also assume that the fileDesc.name is already the `company/foo.proto` path, with
// the package already implicitly in it, so we won't re-append/strip/etc. it out/back in.
const suffix = `${options.fileSuffix}.ts`;
const moduleName = fileDesc.name.replace(".proto", suffix);
const chunks: Code[] = [];
// Indicate this file's source protobuf package for reflective use with google.protobuf.Any
if (options.exportCommonSymbols) {
chunks.push(code`export const protobufPackage = '${fileDesc.package}';`);
}
// Syntax, unlike most fields, is not repeated and thus does not use an index
const sourceInfo = SourceInfo.fromDescriptor(fileDesc);
const headerComment = sourceInfo.lookup(Fields.file.syntax, undefined);
maybeAddComment(options, headerComment, chunks, fileDesc.options?.deprecated);
// Apply formatting to methods here, so they propagate globally
for (let svc of fileDesc.service) {
for (let i = 0; i < svc.method.length; i++) {
svc.method[i] = new FormattedMethodDescriptor(svc.method[i], options);
}
}
// first make all the type declarations
visit(
fileDesc,
sourceInfo,
(fullName, message, sInfo, fullProtoTypeName) => {
chunks.push(
generateInterfaceDeclaration(ctx, fullName, message, sInfo, maybePrefixPackage(fileDesc, fullProtoTypeName)),
);
},
options,
(fullName, enumDesc, sInfo) => {
chunks.push(generateEnum(ctx, fullName, enumDesc, sInfo));
},
);
// If nestJs=true export [package]_PACKAGE_NAME and [service]_SERVICE_NAME const
if (options.nestJs) {
if (options.exportCommonSymbols) {
const prefix = camelToSnake(fileDesc.package.replace(/\./g, "_"));
chunks.push(code`export const ${prefix}_PACKAGE_NAME = '${fileDesc.package}';`);
}
if (
options.useDate === DateOption.DATE &&
fileDesc.messageType.find((message) =>
message.field.find((field) => field.typeName === ".google.protobuf.Timestamp"),
)
) {
chunks.push(makeProtobufTimestampWrapper());
}
}
// We add `nestJs` here because enough though it doesn't use our encode/decode methods
// for most/vanilla messages, we do generate static wrap/unwrap methods for the special
// Struct/Value/wrapper types and use the `wrappers[...]` to have NestJS know about them.
if (
options.outputEncodeMethods ||
options.outputJsonMethods ||
options.outputTypeAnnotations ||
options.outputTypeRegistry ||
options.nestJs
) {
// then add the encoder/decoder/base instance
visit(
fileDesc,
sourceInfo,
(fullName, message, _sInfo, fullProtoTypeName) => {
const fullTypeName = maybePrefixPackage(fileDesc, fullProtoTypeName);
const outputWrapAndUnwrap = isWrapperType(fullTypeName);
// Only decode, fromPartial, and wrap use the createBase method
if (
(options.outputEncodeMethods && options.outputEncodeMethods !== "encode-no-creation") ||
options.outputPartialMethods ||
outputWrapAndUnwrap
) {
chunks.push(generateBaseInstanceFactory(ctx, fullName, message, fullTypeName));
}
const staticMembers: Code[] = [];
if (options.outputTypeAnnotations || options.outputTypeRegistry) {
staticMembers.push(code`$type: '${fullTypeName}' as const`);
}
if (options.outputExtensions) {
for (const extension of message.extension) {
const { name, type, extensionInfo } = generateExtension(ctx, message, extension);
staticMembers.push(code`${name}: <${ctx.utils.Extension}<${type}>> ${extensionInfo}`);
}
}
if (options.outputEncodeMethods) {
if (
options.outputEncodeMethods === true ||
options.outputEncodeMethods === "encode-only" ||
options.outputEncodeMethods === "encode-no-creation"
) {
staticMembers.push(generateEncode(ctx, fullName, message));
if (options.outputExtensions && options.unknownFields && message.extensionRange.length) {
staticMembers.push(generateSetExtension(ctx, fullName));
}
}
if (options.outputEncodeMethods === true || options.outputEncodeMethods === "decode-only") {
staticMembers.push(generateDecode(ctx, fullName, message));
if (options.outputExtensions && options.unknownFields && message.extensionRange.length) {
staticMembers.push(generateGetExtension(ctx, fullName));
}
}
}
if (options.useAsyncIterable) {
staticMembers.push(generateEncodeTransform(ctx.utils, fullName));
staticMembers.push(generateDecodeTransform(ctx.utils, fullName));
}
if (options.outputJsonMethods) {
if (options.outputJsonMethods === true || options.outputJsonMethods === "from-only") {
staticMembers.push(generateFromJson(ctx, fullName, fullTypeName, message));
}
if (options.outputJsonMethods === true || options.outputJsonMethods === "to-only") {
staticMembers.push(generateToJson(ctx, fullName, fullTypeName, message));
}
}
if (options.outputPartialMethods) {
staticMembers.push(generateFromPartial(ctx, fullName, message));
}
const structFieldNames = {
nullValue: maybeSnakeToCamel("null_value", ctx.options),
numberValue: maybeSnakeToCamel("number_value", ctx.options),
stringValue: maybeSnakeToCamel("string_value", ctx.options),
boolValue: maybeSnakeToCamel("bool_value", ctx.options),
structValue: maybeSnakeToCamel("struct_value", ctx.options),
listValue: maybeSnakeToCamel("list_value", ctx.options),
};
if (options.nestJs) {
staticMembers.push(...generateWrapDeep(ctx, fullTypeName, structFieldNames));
staticMembers.push(...generateUnwrapDeep(ctx, fullTypeName, structFieldNames));
} else {
staticMembers.push(...generateWrapShallow(ctx, fullTypeName, structFieldNames));
staticMembers.push(...generateUnwrapShallow(ctx, fullTypeName, structFieldNames));
}
if (staticMembers.length > 0) {
chunks.push(code`
export const ${def(fullName)} = {
${joinCode(staticMembers, { on: ",\n\n" })}
};
`);
}
if (options.outputTypeRegistry) {
const messageTypeRegistry = impFile(options, "messageTypeRegistry@./typeRegistry");
chunks.push(code`
${messageTypeRegistry}.set(${fullName}.$type, ${fullName});
`);
}
},
options,
);
}
if (options.outputExtensions) {
for (const extension of fileDesc.extension) {
const { name, type, extensionInfo } = generateExtension(ctx, undefined, extension);
chunks.push(code`export const ${name}: ${ctx.utils.Extension}<${type}> = ${extensionInfo};`);
}
}
if (options.nestJs) {
if (fileDesc.messageType.find((message) => message.field.find(isStructType))) {
chunks.push(makeProtobufStructWrapper(options));
}
}
let hasServerStreamingMethods = false;
let hasStreamingMethods = false;
visitServices(fileDesc, sourceInfo, (serviceDesc, sInfo) => {
if (options.nestJs) {
// NestJS is sufficiently different that we special case the client/server interfaces
// generate nestjs grpc client interface
chunks.push(generateNestjsServiceClient(ctx, fileDesc, sInfo, serviceDesc));
// and the service controller interface
chunks.push(generateNestjsServiceController(ctx, fileDesc, sInfo, serviceDesc));
// generate nestjs grpc service controller decorator
chunks.push(generateNestjsGrpcServiceMethodsDecorator(ctx, serviceDesc));
let serviceConstName = `${camelToSnake(serviceDesc.name)}_NAME`;
if (!serviceDesc.name.toLowerCase().endsWith("service")) {
serviceConstName = `${camelToSnake(serviceDesc.name)}_SERVICE_NAME`;
}
chunks.push(code`export const ${serviceConstName} = "${serviceDesc.name}";`);
}
const uniqueServices = [...new Set(options.outputServices)].sort();
uniqueServices.forEach((outputService) => {
if (outputService === ServiceOption.GRPC) {
chunks.push(generateGrpcJsService(ctx, fileDesc, sInfo, serviceDesc));
} else if (outputService === ServiceOption.NICE_GRPC) {
chunks.push(generateNiceGrpcService(ctx, fileDesc, sInfo, serviceDesc));
} else if (outputService === ServiceOption.GENERIC) {
chunks.push(generateGenericServiceDefinition(ctx, fileDesc, sInfo, serviceDesc));
} else if (outputService === ServiceOption.DEFAULT) {
// This service could be Twirp or grpc-web or JSON (maybe). So far all of their
// interfaces are fairly similar so we share the same service interface.
chunks.push(generateService(ctx, fileDesc, sInfo, serviceDesc));
if (options.outputClientImpl === true) {
chunks.push(generateServiceClientImpl(ctx, fileDesc, serviceDesc));
} else if (options.outputClientImpl === "grpc-web") {
chunks.push(generateGrpcClientImpl(ctx, fileDesc, serviceDesc));
chunks.push(generateGrpcServiceDesc(fileDesc, serviceDesc));
serviceDesc.method.forEach((method) => {
if (!method.clientStreaming) {
chunks.push(generateGrpcMethodDesc(ctx, serviceDesc, method));
}
if (method.serverStreaming) {
hasServerStreamingMethods = true;
}
});
}
}
});
serviceDesc.method.forEach((methodDesc, _index) => {
if (methodDesc.serverStreaming || methodDesc.clientStreaming) {
hasStreamingMethods = true;
}
});
});
if (
options.outputServices.includes(ServiceOption.DEFAULT) &&
options.outputClientImpl &&
fileDesc.service.length > 0
) {
if (options.outputClientImpl === true) {
chunks.push(generateRpcType(ctx, hasStreamingMethods));
} else if (options.outputClientImpl === "grpc-web") {
chunks.push(addGrpcWebMisc(ctx, hasServerStreamingMethods));
}
}
if (options.context) {
chunks.push(generateDataLoaderOptionsType());
chunks.push(generateDataLoadersType());
}
if (options.outputSchema) {
chunks.push(...generateSchema(ctx, fileDesc, sourceInfo));
}
// https://www.typescriptlang.org/docs/handbook/2/modules.html:
// > In TypeScript, just as in ECMAScript 2015, any file containing a top-level import or export is considered a module.
// > Conversely, a file without any top-level import or export declarations is treated as a script whose contents are available in the global scope (and therefore to modules as well).
//
// Thus, to mark an empty file a module, we need to add `export {}` to it.
if (options.esModuleInterop && chunks.length === 0) {
chunks.push(code`export {};`);
}
chunks.push(
...Object.values(utils).map((v) => {
if (v instanceof ConditionalOutput) {
return code`${v.ifUsed}`;
} else {
return code``;
}
}),
);
// Finally, reset method definitions to their original state (unformatted)
// This is mainly so that the `meta-typings` tests pass
for (let svc of fileDesc.service) {
for (let i = 0; i < svc.method.length; i++) {
const methodInfo = svc.method[i];
assertInstanceOf(methodInfo, FormattedMethodDescriptor);
svc.method[i] = methodInfo.getSource();
}
}
return [moduleName, joinCode(chunks, { on: "\n\n" })];
}
export type Utils = ReturnType<typeof makeDeepPartial> &
ReturnType<typeof makeObjectIdMethods> &
ReturnType<typeof makeTimestampMethods> &
ReturnType<typeof makeByteUtils> &
ReturnType<typeof makeLongUtils> &
ReturnType<typeof makeComparisonUtils> &
ReturnType<typeof makeNiceGrpcServerStreamingMethodResult> &
ReturnType<typeof makeGrpcWebErrorClass> &
ReturnType<typeof makeExtensionClass> &
ReturnType<typeof makeAssertionUtils>;
/** These are runtime utility methods used by the generated code. */
export function makeUtils(options: Options): Utils {
const bytes = makeByteUtils(options);
const longs = makeLongUtils(options, bytes);
return {
...bytes,
...makeDeepPartial(options, longs),
...makeObjectIdMethods(),
...makeTimestampMethods(options, longs, bytes),
...longs,
...makeComparisonUtils(),
...makeNiceGrpcServerStreamingMethodResult(options),
...makeGrpcWebErrorClass(bytes),
...makeExtensionClass(options),
...makeAssertionUtils(bytes),
};
}
function makeProtobufTimestampWrapper() {
const wrappers = imp("wrappers@protobufjs");
return code`
${wrappers}['.google.protobuf.Timestamp'] = {
fromObject(value: Date) {
return {
seconds: value.getTime() / 1000,
nanos: (value.getTime() % 1000) * 1e6,
};
},
toObject(message: { seconds: number; nanos: number }) {
return new Date(message.seconds * 1000 + message.nanos / 1e6);
},
} as any;`;
}
function makeProtobufStructWrapper(options: Options) {
const wrappers = imp("wrappers@protobufjs");
const Struct = impProto(options, "google/protobuf/struct", "Struct");
return code`
${wrappers}['.google.protobuf.Struct'] = {
fromObject: ${Struct}.wrap,
toObject: ${Struct}.unwrap,
} as any;`;
}
function makeLongUtils(options: Options, bytes: ReturnType<typeof makeByteUtils>) {
// Regardless of which `forceLong` config option we're using, we always use
// the `long` library to either represent or at least sanity-check 64-bit values
const util = impFile(options, `util@protobufjs/minimal`);
const configure = impFile(options, `configure@protobufjs/minimal`);
const LongImp = imp("Long=long");
// Instead of exposing `LongImp` directly, let callers think that they are getting the
// `imp(Long)` but really it is that + our long initialization snippet. This means the
// initialization code will only be emitted in files that actually use the Long import.
const Long = conditionalOutput(
"Long",
code`
if (${util}.Long !== ${LongImp}) {
${util}.Long = ${LongImp} as any;
${configure}();
}
`,
);
// TODO This is unused?
const numberToLong = conditionalOutput(
"numberToLong",
code`
function numberToLong(number: number) {
return ${Long}.fromNumber(number);
}
`,
);
const longToString = conditionalOutput(
"longToString",
code`
function longToString(long: ${Long}) {
return long.toString();
}
`,
);
const longToBigint = conditionalOutput(
"longToBigint",
code`
function longToBigint(long: ${Long}) {
return BigInt(long.toString());
}
`,
);
const longToNumber = conditionalOutput(
"longToNumber",
code`
function longToNumber(long: ${Long}): number {
if (long.gt(${bytes.globalThis}.Number.MAX_SAFE_INTEGER)) {
throw new ${bytes.globalThis}.Error("Value is larger than Number.MAX_SAFE_INTEGER")
}
return long.toNumber();
}
`,
);
return { numberToLong, longToNumber, longToString, longToBigint, Long };
}
function makeByteUtils(options: Options) {
const globalThisPolyfill = conditionalOutput(
"gt",
code`
declare const self: any | undefined;
declare const window: any | undefined;
declare const global: any | undefined;
const gt: any = (() => {
if (typeof globalThis !== "undefined") return globalThis;
if (typeof self !== "undefined") return self;
if (typeof window !== "undefined") return window;
if (typeof global !== "undefined") return global;
throw "Unable to locate global object";
})();
`,
);
const globalThis = options.globalThisPolyfill ? globalThisPolyfill : conditionalOutput("globalThis", code``);
function getBytesFromBase64Snippet() {
const bytesFromBase64NodeSnippet = code`
return Uint8Array.from(${globalThis}.Buffer.from(b64, 'base64'));
`;
const bytesFromBase64BrowserSnippet = code`
const bin = ${globalThis}.atob(b64);
const arr = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; ++i) {
arr[i] = bin.charCodeAt(i);
}
return arr;
`;
switch (options.env) {
case EnvOption.NODE:
return bytesFromBase64NodeSnippet;
case EnvOption.BROWSER:
return bytesFromBase64BrowserSnippet;
default:
return code`
if ((${globalThis} as any).Buffer) {
${bytesFromBase64NodeSnippet}
} else {
${bytesFromBase64BrowserSnippet}
}
`;
}
}
const bytesFromBase64 = conditionalOutput(
"bytesFromBase64",
code`
function bytesFromBase64(b64: string): Uint8Array {
${getBytesFromBase64Snippet()}
}
`,
);
function getBase64FromBytesSnippet() {
const base64FromBytesNodeSnippet = code`
return ${globalThis}.Buffer.from(arr).toString('base64');
`;
const base64FromBytesBrowserSnippet = code`
const bin: string[] = [];
arr.forEach((byte) => {
bin.push(${globalThis}.String.fromCharCode(byte));
});
return ${globalThis}.btoa(bin.join(''));
`;
switch (options.env) {
case EnvOption.NODE:
return base64FromBytesNodeSnippet;
case EnvOption.BROWSER:
return base64FromBytesBrowserSnippet;
default:
return code`
if ((${globalThis} as any).Buffer) {
${base64FromBytesNodeSnippet}
} else {
${base64FromBytesBrowserSnippet}
}
`;
}
}
const base64FromBytes = conditionalOutput(
"base64FromBytes",
code`
function base64FromBytes(arr: Uint8Array): string {
${getBase64FromBytesSnippet()}
}
`,
);
return { globalThis, bytesFromBase64, base64FromBytes };
}
function makeDeepPartial(options: Options, longs: ReturnType<typeof makeLongUtils>) {
let oneofCase = "";
if (options.oneof === OneofOption.UNIONS) {
oneofCase = `
: T extends { ${maybeReadonly(options)}$case: string }
? { [K in keyof Omit<T, '$case'>]?: DeepPartial<T[K]> } & { ${maybeReadonly(options)}$case: T['$case'] }
`;
}
const maybeExport = options.exportCommonSymbols ? "export" : "";
// Allow passing longs as numbers or strings, nad we'll convert them
const maybeLong =
options.forceLong === LongOption.LONG ? code` : T extends ${longs.Long} ? string | number | Long ` : "";
const Builtin = conditionalOutput(
"Builtin",
code`type Builtin = Date | Function | Uint8Array | string | number | boolean |${
options.forceLong === LongOption.BIGINT ? " bigint |" : ""
} undefined;`,
);
// Based on https://github.com/sindresorhus/type-fest/pull/259
const maybeExcludeType = addTypeToMessages(options) ? `| '$type'` : "";
const Exact = conditionalOutput(
"Exact",
code`
type KeysOfUnion<T> = T extends T ? keyof T : never;
${maybeExport} type Exact<P, I extends P> = P extends ${Builtin}
? P
: P &
{ [K in keyof P]: Exact<P[K], I[K]> } & { [K in Exclude<keyof I, KeysOfUnion<P> ${maybeExcludeType}>]: never };
`,
);
// Based on the type from ts-essentials
const keys = addTypeToMessages(options) ? code`Exclude<keyof T, '$type'>` : code`keyof T`;
const DeepPartial = conditionalOutput(
"DeepPartial",
code`
${maybeExport} type DeepPartial<T> = T extends ${Builtin}
? T
${maybeLong}
: T extends globalThis.Array<infer U>
? globalThis.Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>${oneofCase}
: T extends {}
? { [K in ${keys}]?: DeepPartial<T[K]> }
: Partial<T>;
`,
);
return { Builtin, DeepPartial, Exact };
}
function makeObjectIdMethods() {
const mongodb = imp("mongodb*mongodb");
const fromProtoObjectId = conditionalOutput(
"fromProtoObjectId",
code`
function fromProtoObjectId(oid: ObjectId): ${mongodb}.ObjectId {
return new ${mongodb}.ObjectId(oid.value);
}
`,
);
const fromJsonObjectId = conditionalOutput(
"fromJsonObjectId",
code`
function fromJsonObjectId(o: any): ${mongodb}.ObjectId {
if (o instanceof ${mongodb}.ObjectId) {
return o;
} else if (typeof o === "string") {
return new ${mongodb}.ObjectId(o);
} else {
return ${fromProtoObjectId}(ObjectId.fromJSON(o));
}
}
`,
);
const toProtoObjectId = conditionalOutput(
"toProtoObjectId",
code`
function toProtoObjectId(oid: ${mongodb}.ObjectId): ObjectId {
const value = oid.toString();
return { value };
}
`,
);
return { fromJsonObjectId, fromProtoObjectId, toProtoObjectId };
}
function makeTimestampMethods(
options: Options,
longs: ReturnType<typeof makeLongUtils>,
bytes: ReturnType<typeof makeByteUtils>,
) {
const Timestamp = impProto(options, "google/protobuf/timestamp", "Timestamp");
const NanoDate = imp("NanoDate=nano-date");
let seconds: string | Code = "Math.trunc(date.getTime() / 1_000)";
let toNumberCode: string | Code = "t.seconds";
const makeToNumberCode = (methodCall: string) =>
`t.seconds${options.useOptionals === "all" ? "?" : ""}.${methodCall}`;
if (options.forceLong === LongOption.LONG) {
toNumberCode = makeToNumberCode("toNumber()");
seconds = code`${longs.numberToLong}(${seconds})`;
} else if (options.forceLong === LongOption.BIGINT) {
toNumberCode = code`${bytes.globalThis}.Number(${makeToNumberCode("toString()")})`;
seconds = code`BigInt(${seconds})`;
} else if (options.forceLong === LongOption.STRING) {
toNumberCode = code`${bytes.globalThis}.Number(t.seconds)`;
seconds = code`${seconds}.toString()`;
}
const maybeTypeField = addTypeToMessages(options) ? `$type: 'google.protobuf.Timestamp',` : "";
const toTimestamp = conditionalOutput(
"toTimestamp",
options.useDate === DateOption.STRING
? code`
function toTimestamp(dateStr: string): ${Timestamp} {
const date = new ${bytes.globalThis}.Date(dateStr);
const seconds = ${seconds};
const nanos = (date.getTime() % 1_000) * 1_000_000;
return { ${maybeTypeField} seconds, nanos };
}
`
: options.useDate === DateOption.STRING_NANO
? code`
function toTimestamp(dateStr: string): ${Timestamp} {
const nanoDate = new ${NanoDate}(dateStr);
const date = {
getTime: (): number => nanoDate.valueOf(),
} as const;
const seconds = ${seconds};
let nanos = nanoDate.getMilliseconds() * 1_000_000;
nanos += nanoDate.getMicroseconds() * 1_000;
nanos += nanoDate.getNanoseconds();
return { ${maybeTypeField} seconds, nanos };
}
`
: code`
function toTimestamp(date: Date): ${Timestamp} {
const seconds = ${seconds};
const nanos = (date.getTime() % 1_000) * 1_000_000;
return { ${maybeTypeField} seconds, nanos };
}
`,
);
const fromTimestamp = conditionalOutput(
"fromTimestamp",
options.useDate === DateOption.STRING
? code`
function fromTimestamp(t: ${Timestamp}): string {
let millis = (${toNumberCode} || 0) * 1_000;
millis += (t.nanos || 0) / 1_000_000;
return new ${bytes.globalThis}.Date(millis).toISOString();
}
`
: options.useDate === DateOption.STRING_NANO
? code`
function fromTimestamp(t: ${Timestamp}): string {
const seconds = ${toNumberCode} || 0;
const nanos = (t.nanos || 0) % 1_000;
const micros = Math.trunc(((t.nanos || 0) % 1_000_000) / 1_000)
let millis = seconds * 1_000;
millis += Math.trunc((t.nanos || 0) / 1_000_000);
const nanoDate = new ${NanoDate}(millis);
nanoDate.setMicroseconds(micros);
nanoDate.setNanoseconds(nanos);
return nanoDate.toISOStringFull();
}
`
: code`
function fromTimestamp(t: ${Timestamp}): Date {
let millis = (${toNumberCode} || 0) * 1_000;
millis += (t.nanos || 0) / 1_000_000;
return new ${bytes.globalThis}.Date(millis);
}
`,
);
const fromJsonTimestamp = conditionalOutput(
"fromJsonTimestamp",
options.useDate === DateOption.DATE
? code`
function fromJsonTimestamp(o: any): Date {
if (o instanceof ${bytes.globalThis}.Date) {
return o;
} else if (typeof o === "string") {
return new ${bytes.globalThis}.Date(o);
} else {
return ${fromTimestamp}(Timestamp.fromJSON(o));
}
}
`
: code`
function fromJsonTimestamp(o: any): Timestamp {
if (o instanceof ${bytes.globalThis}.Date) {
return ${toTimestamp}(o);
} else if (typeof o === "string") {
return ${toTimestamp}(new ${bytes.globalThis}.Date(o));
} else {
return Timestamp.fromJSON(o);
}
}
`,
);
return { toTimestamp, fromTimestamp, fromJsonTimestamp };
}
function makeComparisonUtils() {
const isObject = conditionalOutput(
"isObject",
code`
function isObject(value: any): boolean {
return typeof value === 'object' && value !== null;
}`,
);
const isSet = conditionalOutput(
"isSet",
code`
function isSet(value: any): boolean {
return value !== null && value !== undefined;
}`,
);
return { isObject, isSet };
}
function makeNiceGrpcServerStreamingMethodResult(options: Options) {
const NiceGrpcServerStreamingMethodResult = conditionalOutput(
"ServerStreamingMethodResult",
options.outputIndex
? code`
type ServerStreamingMethodResult<Response> = {
[Symbol.asyncIterator](): AsyncIterator<Response, void>;
};
`
: code`
export type ServerStreamingMethodResult<Response> = {
[Symbol.asyncIterator](): AsyncIterator<Response, void>;
};
`,
);
return { NiceGrpcServerStreamingMethodResult };
}
function makeGrpcWebErrorClass(bytes: ReturnType<typeof makeByteUtils>) {
const GrpcWebError = conditionalOutput(
"GrpcWebError",
code`
export class GrpcWebError extends ${bytes.globalThis}.Error {
constructor(message: string, public code: grpc.Code, public metadata: grpc.Metadata) {
super(message);
}
}
`,
);
return { GrpcWebError };
}
function makeExtensionClass(options: Options) {
const Reader = impFile(options, "Reader@protobufjs/minimal");
const Writer = impFile(options, "Writer@protobufjs/minimal");
const Extension = conditionalOutput(
"Extension",
code`
export interface Extension <T> {
number: number;
tag: number;
singularTag?: number;
encode?: (message: T) => Uint8Array[];
decode?: (tag: number, input: Uint8Array[]) => T;
repeated: boolean;
packed: boolean;
}
`,
);
return { Extension };
}
function makeAssertionUtils(bytes: ReturnType<typeof makeByteUtils>) {
const fail = conditionalOutput(
"fail",
code`
function fail(message?: string): never {
throw new ${bytes.globalThis}.Error(message ?? "Failed");
}
`,
);
return { fail };
}
// Create the interface with properties
function generateInterfaceDeclaration(
ctx: Context,
fullName: string,
messageDesc: DescriptorProto,
sourceInfo: SourceInfo,
fullTypeName: string,
): Code {
const { options, currentFile } = ctx;
const chunks: Code[] = [];
maybeAddComment(options, sourceInfo, chunks, messageDesc.options?.deprecated);
// interface name should be defined to avoid import collisions
chunks.push(code`export interface ${def(fullName)} {`);
if (addTypeToMessages(options)) {
chunks.push(code`$type${options.outputTypeAnnotations === "optional" ? "?" : ""}: '${fullTypeName}',`);
}
// When oneof=unions, we generate a single property with an ADT per `oneof` clause.
const processedOneofs = new Set<number>();
messageDesc.field.forEach((fieldDesc, index) => {
if (isWithinOneOfThatShouldBeUnion(options, fieldDesc)) {
const { oneofIndex } = fieldDesc;
if (!processedOneofs.has(oneofIndex)) {
processedOneofs.add(oneofIndex);
chunks.push(generateOneofProperty(ctx, messageDesc, oneofIndex, sourceInfo));
}
return;
}
const info = sourceInfo.lookup(Fields.message.field, index);
maybeAddComment(options, info, chunks, fieldDesc.options?.deprecated);
const fieldKey = safeAccessor(getFieldName(fieldDesc, options));
const isOptional = isOptionalProperty(fieldDesc, messageDesc.options, options, currentFile.isProto3Syntax);
const type = toTypeName(ctx, messageDesc, fieldDesc, isOptional);
chunks.push(code`${maybeReadonly(options)}${fieldKey}${isOptional ? "?" : ""}: ${type}, `);
});
if (ctx.options.unknownFields) {
chunks.push(code`_unknownFields?: {[key: number]: Uint8Array[]} | undefined,`);
}
chunks.push(code`}`);
return joinCode(chunks, { on: "\n" });
}
function generateOneofProperty(
ctx: Context,