/
typescript.go
1495 lines (1287 loc) · 42.9 KB
/
typescript.go
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
package clientgen
import (
"bufio"
"bytes"
"fmt"
"reflect"
"sort"
"strings"
"unicode"
"github.com/cockroachdb/errors"
"encr.dev/internal/clientgen/clientgentypes"
"encr.dev/internal/version"
"encr.dev/parser/encoding"
"encr.dev/pkg/idents"
meta "encr.dev/proto/encore/parser/meta/v1"
schema "encr.dev/proto/encore/parser/schema/v1"
)
/* The TypeScript generator generates code that looks like this:
export namespace task {
export interface AddParams {
description: string
}
export class ServiceClient {
public Add(params: task_AddParams): Promise<task_AddResponse> {
// ...
}
}
}
*/
// tsGenVersion allows us to introduce breaking changes in the generated code but behind a switch
// meaning that people with client code reliant on the old behaviour can continue to generate the
// old code.
type tsGenVersion int
const (
// TsInitial is the originally released typescript generator
TsInitial tsGenVersion = iota
// TsExperimental can be used to lock experimental or uncompleted features in the generated code
// It should always be the last item in the enum
TsExperimental
)
const typescriptGenLatestVersion = TsExperimental - 1
type typescript struct {
*bytes.Buffer
md *meta.Data
appSlug string
typs *typeRegistry
currDecl *schema.Decl
generatorVersion tsGenVersion
seenJSON bool // true if a JSON type was seen
seenHeaderResponse bool // true if we've seen a header used in a response object
hasAuth bool // true if we've seen an authentication handler
authIsComplexType bool // true if the auth type is a complex type
}
func (ts *typescript) Version() int {
return int(ts.generatorVersion)
}
func (ts *typescript) Generate(p clientgentypes.GenerateParams) (err error) {
defer ts.handleBailout(&err)
ts.Buffer = p.Buf
ts.md = p.Meta
ts.appSlug = p.AppSlug
ts.typs = getNamedTypes(p.Meta, p.Services)
if ts.md.AuthHandler != nil {
ts.hasAuth = true
ts.authIsComplexType = ts.md.AuthHandler.Params.GetBuiltin() != schema.Builtin_STRING
}
ts.WriteString("// " + doNotEditHeader() + "\n\n")
ts.WriteString("// Disable eslint, jshint, and jslint for this file.\n")
ts.WriteString("/* eslint-disable */\n")
ts.WriteString("/* jshint ignore:start */\n")
ts.WriteString("/*jslint-disable*/\n")
nss := ts.typs.Namespaces()
seenNs := make(map[string]bool)
ts.writeClient(p.Services)
for _, svc := range p.Meta.Svcs {
if err := ts.writeService(svc, p.Services); err != nil {
return err
}
seenNs[svc.Name] = true
}
for _, ns := range nss {
if !seenNs[ns] {
ts.writeNamespace(ns)
}
}
ts.writeExtraTypes()
if err := ts.writeBaseClient(p.AppSlug); err != nil {
return err
}
ts.writeCustomErrorType()
return nil
}
func (ts *typescript) writeService(svc *meta.Service, p clientgentypes.ServiceSet) error {
// Determine if we have anything worth exposing.
// Either a public RPC or a named type.
isIncluded := hasPublicRPC(svc) && p.Has(svc.Name)
decls := ts.typs.Decls(svc.Name)
if !isIncluded && len(decls) == 0 {
return nil
}
ns := svc.Name
fmt.Fprintf(ts, "export namespace %s {\n", ts.typeName(ns))
sort.Slice(decls, func(i, j int) bool {
return decls[i].Name < decls[j].Name
})
for i, d := range decls {
if i > 0 {
ts.WriteString("\n")
}
ts.writeDeclDef(ns, d)
}
if !isIncluded {
ts.WriteString("}\n\n")
return nil
}
ts.WriteString("\n")
numIndent := 1
indent := func() {
ts.WriteString(strings.Repeat(" ", numIndent))
}
indent()
fmt.Fprint(ts, "export class ServiceClient {\n")
numIndent++
// Constructor
indent()
ts.WriteString("private baseClient: BaseClient\n\n")
indent()
ts.WriteString("constructor(baseClient: BaseClient) {\n")
numIndent++
indent()
ts.WriteString("this.baseClient = baseClient\n")
numIndent--
indent()
ts.WriteString("}\n")
// RPCs
for _, rpc := range svc.Rpcs {
if rpc.AccessType == meta.RPC_PRIVATE {
continue
}
ts.WriteByte('\n')
// Doc string
if rpc.Doc != nil && *rpc.Doc != "" {
scanner := bufio.NewScanner(strings.NewReader(*rpc.Doc))
indent()
ts.WriteString("/**\n")
for scanner.Scan() {
indent()
ts.WriteString(" * ")
ts.WriteString(scanner.Text())
ts.WriteByte('\n')
}
indent()
ts.WriteString(" */\n")
}
// Signature
indent()
fmt.Fprintf(ts, "public async %s(", ts.memberName(rpc.Name))
if rpc.Proto == meta.RPC_RAW {
ts.WriteString("method: ")
for i, method := range rpc.HttpMethods {
if i > 0 {
ts.WriteString(" | ")
}
if method == "*" {
ts.WriteString("string")
} else {
ts.WriteString("\"" + method + "\"")
}
}
ts.WriteString(", ")
}
nParams := 0
var rpcPath strings.Builder
for _, s := range rpc.Path.Segments {
rpcPath.WriteByte('/')
if s.Type != meta.PathSegment_LITERAL {
if nParams > 0 {
ts.WriteString(", ")
}
ts.WriteString(ts.nonReservedId(s.Value))
ts.WriteString(": ")
switch s.ValueType {
case meta.PathSegment_STRING, meta.PathSegment_UUID:
ts.WriteString("string")
case meta.PathSegment_BOOL:
ts.WriteString("boolean")
case meta.PathSegment_INT8, meta.PathSegment_INT16, meta.PathSegment_INT32, meta.PathSegment_INT64, meta.PathSegment_INT,
meta.PathSegment_UINT8, meta.PathSegment_UINT16, meta.PathSegment_UINT32, meta.PathSegment_UINT64, meta.PathSegment_UINT:
ts.WriteString("number")
default:
panic(fmt.Sprintf("unhandled PathSegment type %s", s.ValueType))
}
if s.Type == meta.PathSegment_WILDCARD || s.Type == meta.PathSegment_FALLBACK {
ts.WriteString("[]")
rpcPath.WriteString("${" + ts.nonReservedId(s.Value) + ".map(encodeURIComponent).join(\"/\")}")
} else {
rpcPath.WriteString("${encodeURIComponent(" + ts.nonReservedId(s.Value) + ")}")
}
nParams++
} else {
rpcPath.WriteString(s.Value)
}
}
// Avoid a name collision.
payloadName := "params"
if rpc.RequestSchema != nil {
if nParams > 0 {
ts.WriteString(", ")
}
ts.WriteString(payloadName + ": ")
ts.writeTyp(ns, rpc.RequestSchema, 0)
} else if rpc.Proto == meta.RPC_RAW {
if nParams > 0 {
ts.WriteString(", ")
}
ts.WriteString("body?: BodyInit, options?: CallParameters")
}
ts.WriteString("): Promise<")
if rpc.ResponseSchema != nil {
ts.writeTyp(ns, rpc.ResponseSchema, 0)
} else if rpc.Proto == meta.RPC_RAW {
ts.WriteString("Response")
} else {
ts.WriteString("void")
}
ts.WriteString("> {\n")
err := ts.rpcCallSite(ns, ts.newIdentWriter(numIndent+1), rpc, rpcPath.String())
if err != nil {
return errors.Wrapf(err, "unable to write RPC call site for %s.%s", rpc.ServiceName, rpc.Name)
}
indent()
ts.WriteString("}\n")
}
numIndent--
indent()
ts.WriteString("}\n}\n\n")
return nil
}
func (ts *typescript) rpcCallSite(ns string, w *indentWriter, rpc *meta.RPC, rpcPath string) error {
// Work out how we're going to encode and call this RPC
rpcEncoding, err := encoding.DescribeRPC(ts.md, rpc, &encoding.Options{SrcNameTag: "json"})
if err != nil {
return errors.Wrapf(err, "rpc %s", rpc.Name)
}
// Raw end points just pass through the request
// and need no further code generation
if rpc.Proto == meta.RPC_RAW {
w.WriteStringf(
"return this.baseClient.callAPI(method, `%s`, body, options)\n",
rpcPath,
)
return nil
}
// Work out how we encode the Request Schema
headers := ""
query := ""
body := ""
if rpc.RequestSchema != nil {
reqEnc := rpcEncoding.DefaultRequestEncoding
if len(reqEnc.HeaderParameters) > 0 || len(reqEnc.QueryParameters) > 0 {
w.WriteString("// Convert our params into the objects we need for the request\n")
}
// Generate the headers
if len(reqEnc.HeaderParameters) > 0 {
headers = "headers"
dict := make(map[string]string)
for _, field := range reqEnc.HeaderParameters {
ref := ts.Dot("params", field.SrcName)
dict[field.WireFormat] = ts.convertBuiltinToString(field.Type.GetBuiltin(), ref, field.Optional)
}
w.WriteString("const headers = makeRecord<string, string>(")
ts.Values(w, dict)
w.WriteString(")\n\n")
}
// Generate the query string
if len(reqEnc.QueryParameters) > 0 {
query = "query"
dict := make(map[string]string)
for _, field := range reqEnc.QueryParameters {
if list := field.Type.GetList(); list != nil {
dot := ts.Dot("params", field.SrcName)
if field.Optional || ts.isRecursive(field.Type) {
dot += "?"
}
dict[field.WireFormat] = dot +
".map((v) => " + ts.convertBuiltinToString(list.Elem.GetBuiltin(), "v", field.Optional) + ")"
} else {
dict[field.WireFormat] = ts.convertBuiltinToString(
field.Type.GetBuiltin(),
ts.Dot("params", field.SrcName),
field.Optional,
)
}
}
w.WriteString("const query = makeRecord<string, string | string[]>(")
ts.Values(w, dict)
w.WriteString(")\n\n")
}
// Generate the body
if len(reqEnc.BodyParameters) > 0 {
if len(reqEnc.HeaderParameters) == 0 && len(reqEnc.QueryParameters) == 0 {
// In the simple case we can just encode the params as the body directly
body = "JSON.stringify(params)"
} else {
// Else we need a new struct called "body"
body = "JSON.stringify(body)"
dict := make(map[string]string)
for _, field := range reqEnc.BodyParameters {
dict[field.WireFormat] = ts.Dot("params", field.SrcName)
}
w.WriteString("// Construct the body with only the fields which we want encoded within the body (excluding query string or header fields)\nconst body: Record<string, any> = ")
ts.Values(w, dict)
w.WriteString("\n\n")
}
}
}
// Build the call to callAPI
callAPI := fmt.Sprintf(
"this.baseClient.callAPI(\"%s\", `%s`",
rpcEncoding.DefaultMethod,
rpcPath,
)
if body != "" || headers != "" || query != "" {
if body == "" {
callAPI += ", undefined"
} else {
callAPI += ", " + body
}
if headers != "" || query != "" {
callAPI += ", {" + headers
if headers != "" && query != "" {
callAPI += ", "
}
if query != "" {
callAPI += query
}
callAPI += "}"
}
}
callAPI += ")"
// If there's no response schema, we can just return the call to the API directly
if rpc.ResponseSchema == nil {
w.WriteStringf("await %s\n", callAPI)
return nil
}
w.WriteStringf("// Now make the actual call to the API\nconst resp = await %s\n", callAPI)
respEnc := rpcEncoding.ResponseEncoding
// If we don't need to do anything with the body, we can just return the response
if len(respEnc.HeaderParameters) == 0 {
w.WriteString("return await resp.json() as ")
ts.writeTyp(ns, rpc.ResponseSchema, 0)
w.WriteString("\n")
return nil
}
// Otherwise, we need to add the header fields to the response
w.WriteString("\n//Populate the return object from the JSON body and received headers\nconst rtn = await resp.json() as ")
ts.writeTyp(ns, rpc.ResponseSchema, 0)
w.WriteString("\n")
for _, headerField := range respEnc.HeaderParameters {
ts.seenHeaderResponse = true
fieldValue := fmt.Sprintf("mustBeSet(\"Header `%s`\", resp.headers.get(\"%s\"))", headerField.WireFormat, headerField.WireFormat)
w.WriteStringf("%s = %s\n", ts.Dot("rtn", headerField.SrcName), ts.convertStringToBuiltin(headerField.Type.GetBuiltin(), fieldValue))
}
w.WriteString("return rtn\n")
return nil
}
// nonReservedId returns the given ID, unless we have it a reserved within the client function _or_ it's a reserved Typescript keyword
func (ts *typescript) nonReservedId(id string) string {
switch id {
// our reserved keywords (or ID's we use within the generated client functions)
case "params", "headers", "query", "body", "resp", "rtn":
return "_" + id
// Typescript & Javascript keywords
case "abstract", "any", "arguments", "as", "async", "await", "boolean", "break", "byte", "case", "catch", "char",
"class", "const", "constructor", "continue", "debugger", "declare", "default", "delete", "do", "double", "else",
"enum", "eval", "export", "extends", "false", "final", "finally", "float", "for", "from", "function", "get",
"goto", "if", "implements", "import", "in", "instanceof", "interface", "let", "long", "module", "namespace",
"native", "new", "null", "number", "of", "package", "private", "protected", "public", "require", "return",
"set", "short", "static", "string", "super", "switch", "symbol", "synchronized", "this", "throw", "throws",
"transient", "true", "try", "type", "typeof", "var", "void", "volatile", "while", "with", "yield":
return "_" + id
default:
return id
}
}
func (ts *typescript) writeNamespace(ns string) {
decls := ts.typs.Decls(ns)
if len(decls) == 0 {
return
}
fmt.Fprintf(ts, "export namespace %s {\n", ts.typeName(ns))
sort.Slice(decls, func(i, j int) bool {
return decls[i].Name < decls[j].Name
})
for i, d := range decls {
if i > 0 {
ts.WriteString("\n")
}
ts.writeDeclDef(ns, d)
}
ts.WriteString("}\n\n")
}
func (ts *typescript) writeDeclDef(ns string, decl *schema.Decl) {
if decl.Doc != "" {
scanner := bufio.NewScanner(strings.NewReader(decl.Doc))
ts.WriteString(" /**\n")
for scanner.Scan() {
ts.WriteString(" * ")
ts.WriteString(scanner.Text())
ts.WriteByte('\n')
}
ts.WriteString(" */\n")
}
var typeParams strings.Builder
if len(decl.TypeParams) > 0 {
typeParams.WriteRune('<')
for i, typeParam := range decl.TypeParams {
if i > 0 {
typeParams.WriteString(", ")
}
typeParams.WriteString(typeParam.Name)
}
typeParams.WriteRune('>')
}
// If it's a struct type, expose it as an interface;
// other types should be type aliases.
if st := decl.Type.GetStruct(); st != nil {
fmt.Fprintf(ts, " export interface %s%s ", ts.typeName(decl.Name), typeParams.String())
} else {
fmt.Fprintf(ts, " export type %s%s = ", ts.typeName(decl.Name), typeParams.String())
}
ts.currDecl = decl
ts.writeTyp(ns, decl.Type, 1)
ts.WriteString("\n")
}
func (ts *typescript) writeClient(set clientgentypes.ServiceSet) {
w := ts.newIdentWriter(0)
w.WriteString(`
/**
* BaseURL is the base URL for calling the Encore application's API.
*/
export type BaseURL = string
export const Local: BaseURL = "http://localhost:4000"
/**
* Environment returns a BaseURL for calling the cloud environment with the given name.
*/
export function Environment(name: string): BaseURL {
return ` + "`https://${name}-" + ts.appSlug + ".encr.app`" + `
}
/**
* PreviewEnv returns a BaseURL for calling the preview environment with the given PR number.
*/
export function PreviewEnv(pr: number | string): BaseURL {
return Environment(` + "`pr${pr}`" + `)
}
/**
* Client is an API client for the ` + ts.appSlug + ` Encore application.
*/
export default class Client {
`)
{
w := w.Indent()
for _, svc := range ts.md.Svcs {
if hasPublicRPC(svc) && set.Has(svc.Name) {
w.WriteStringf("public readonly %s: %s.ServiceClient\n", ts.memberName(svc.Name), ts.typeName(svc.Name))
}
}
w.WriteString("\n")
// Only include the deprecated constructor if bearer token authentication is being used
if ts.hasAuth && !ts.authIsComplexType {
w.WriteString(`
/**
* @deprecated This constructor is deprecated, and you should move to using BaseURL with an Options object
*/
constructor(target: string, token?: string)
`)
}
w.WriteString(`
/**
* Creates a Client for calling the public and authenticated APIs of your Encore application.
*
* @param target The target which the client should be configured to use. See Local and Environment for options.
* @param options Options for the client
*/
constructor(target: BaseURL, options?: ClientOptions)`)
if ts.hasAuth && !ts.authIsComplexType {
w.WriteString("\nconstructor(target: string | BaseURL = \"prod\", options?: string | ClientOptions) {\n")
{
w := w.Indent()
w.WriteString(`
// Convert the old constructor parameters to a BaseURL object and a ClientOptions object
if (!target.startsWith("http://") && !target.startsWith("https://")) {
target = Environment(target)
}
if (typeof options === "string") {
options = { auth: options }
}
`)
}
} else {
w.WriteString(" {\n")
}
{
w := w.Indent()
w.WriteString("const base = new BaseClient(target, options ?? {})\n")
for _, svc := range ts.md.Svcs {
if hasPublicRPC(svc) && set.Has(svc.Name) {
w.WriteStringf("this.%s = new %s.ServiceClient(base)\n", ts.memberName(svc.Name), ts.typeName(svc.Name))
}
}
}
w.WriteString("}\n")
}
w.WriteString("}\n")
w.WriteString(`
/**
* ClientOptions allows you to override any default behaviour within the generated Encore client.
*/
export interface ClientOptions {
/**
* By default the client will use the inbuilt fetch function for making the API requests.
* however you can override it with your own implementation here if you want to run custom
* code on each API request made or response received.
*/
fetcher?: Fetcher
/** Default RequestInit to be used for the client */
requestInit?: Omit<RequestInit, "headers"> & { headers?: Record<string, string> }
`)
if ts.hasAuth {
if !ts.authIsComplexType {
w.WriteString(`
/**
* Allows you to set the auth token to be used for each request
* either by passing in a static token string or by passing in a function
* which returns the auth token.
*
* These tokens will be sent as bearer tokens in the Authorization header.
*/
`)
} else {
w.WriteString(`
/**
* Allows you to set the authentication data to be used for each
* request either by passing in a static object or by passing in
* a function which returns a new object for each request.
*/
`)
}
w.WriteString(" auth?: ")
ts.writeTyp("", ts.md.AuthHandler.Params, 2)
w.WriteString(" | AuthDataGenerator\n")
}
w.WriteString(`}
`)
}
func (ts *typescript) writeBaseClient(appSlug string) error {
userAgent := fmt.Sprintf("%s-Generated-TS-Client (Encore/%s)", appSlug, version.Version)
ts.WriteString(`
// CallParameters is the type of the parameters to a method call, but require headers to be a Record type
type CallParameters = Omit<RequestInit, "method" | "body" | "headers"> & {
/** Headers to be sent with the request */
headers?: Record<string, string>
/** Query parameters to be sent with the request */
query?: Record<string, string | string[]>
}
`)
if ts.hasAuth {
ts.WriteString(`
// AuthDataGenerator is a function that returns a new instance of the authentication data required by this API
export type AuthDataGenerator = () =>
| `)
ts.writeTyp("", ts.md.AuthHandler.Params, 0)
ts.WriteString(`
| Promise<`)
ts.writeTyp("", ts.md.AuthHandler.Params, 0)
ts.WriteString(` | undefined>
| undefined;`)
}
ts.WriteString(`
// A fetcher is the prototype for the inbuilt Fetch function
export type Fetcher = typeof fetch;
const boundFetch = fetch.bind(this);
class BaseClient {
readonly baseURL: string
readonly fetcher: Fetcher
readonly headers: Record<string, string>
readonly requestInit: Omit<RequestInit, "headers"> & { headers?: Record<string, string> }`)
if ts.hasAuth {
ts.WriteString("\n readonly authGenerator?: AuthDataGenerator")
}
ts.WriteString(`
constructor(baseURL: string, options: ClientOptions) {
this.baseURL = baseURL
this.headers = {
"Content-Type": "application/json",
}
// Add User-Agent header if the script is running in the server
// because browsers do not allow setting User-Agent headers to requests
if (typeof window === "undefined") {
this.headers["User-Agent"] = "` + userAgent + `";
}
this.requestInit = options.requestInit ?? {};
// Setup what fetch function we'll be using in the base client
if (options.fetcher !== undefined) {
this.fetcher = options.fetcher
} else {
this.fetcher = boundFetch
}`)
if ts.hasAuth {
ts.WriteString(`
// Setup an authentication data generator using the auth data token option
if (options.auth !== undefined) {
const auth = options.auth
if (typeof auth === "function") {
this.authGenerator = auth
} else {
this.authGenerator = () => auth
}
}
`)
}
ts.WriteString(`
}
// callAPI is used by each generated API method to actually make the request
public async callAPI(method: string, path: string, body?: BodyInit, params?: CallParameters): Promise<Response> {
let { query, headers, ...rest } = params ?? {}
const init = {
...this.requestInit,
...rest,
method,
body: body ?? null,
}
// Merge our headers with any predefined headers
init.headers = {...this.headers, ...init.headers, ...headers}
`)
w := ts.newIdentWriter(2)
if ts.hasAuth {
w.WriteString(`
// If authorization data generator is present, call it and add the returned data to the request
let authData: `)
ts.writeTyp("", ts.md.AuthHandler.Params, 2)
w.WriteString(" | undefined\n")
w.WriteString(`if (this.authGenerator) {
const mayBePromise = this.authGenerator()
if (mayBePromise instanceof Promise) {
authData = await mayBePromise
} else {
authData = mayBePromise
}
}
// If we now have authentication data, add it to the request
if (authData) {
`)
{
w := w.Indent()
if ts.authIsComplexType {
authData, err := encoding.DescribeAuth(ts.md, ts.md.AuthHandler.Params, &encoding.Options{SrcNameTag: "json"})
if err != nil {
return errors.Wrap(err, "unable to describe auth data")
}
// Write all the query string fields in
for i, field := range authData.QueryParameters {
// We need to ensure that the query field is not undefined
if i == 0 {
w.WriteString("query = query ?? {}\n")
}
w.WriteString("query[\"")
w.WriteString(field.WireFormat)
w.WriteString("\"] = ")
if list := field.Type.GetList(); list != nil {
dot := ts.Dot("authData", field.SrcName)
if field.Optional || ts.isRecursive(field.Type) {
dot += "?"
}
w.WriteString(dot +
".map((v) => " + ts.convertBuiltinToString(list.Elem.GetBuiltin(), "v", field.Optional) + ")",
)
} else {
w.WriteString(ts.convertBuiltinToString(field.Type.GetBuiltin(), ts.Dot("authData", field.SrcName), field.Optional))
}
w.WriteString("\n")
}
// Write all the headers
for _, field := range authData.HeaderParameters {
w.WriteString("init.headers[\"")
w.WriteString(field.WireFormat)
w.WriteString("\"] = ")
w.WriteString(ts.convertBuiltinToString(field.Type.GetBuiltin(), ts.Dot("authData", field.SrcName), field.Optional))
w.WriteString("\n")
}
} else {
w.WriteString("init.headers[\"Authorization\"] = \"Bearer \" + authData\n")
}
}
w.WriteString("}\n")
}
ts.WriteString(`
// Make the actual request
const queryString = query ? '?' + encodeQuery(query) : ''
const response = await this.fetcher(this.baseURL+path+queryString, init)
// handle any error responses
if (!response.ok) {
// try and get the error message from the response body
let body: APIErrorResponse = { code: ErrCode.Unknown, message: ` + "`request failed: status ${response.status}`" + ` }
// if we can get the structured error we should, otherwise give a best effort
try {
const text = await response.text()
try {
const jsonBody = JSON.parse(text)
if (isAPIErrorResponse(jsonBody)) {
body = jsonBody
} else {
body.message += ": " + JSON.stringify(jsonBody)
}
} catch {
body.message += ": " + text
}
} catch (e) {
// otherwise we just append the text to the error message
body.message += ": " + String(e)
}
throw new APIError(response.status, body)
}
return response
}
}`)
return nil
}
func (ts *typescript) writeExtraTypes() {
if ts.seenJSON {
ts.WriteString(`// JSONValue represents an arbitrary JSON value.
export type JSONValue = string | number | boolean | null | JSONValue[] | {[key: string]: JSONValue}
`)
}
ts.WriteString(`
function encodeQuery(parts: Record<string, string | string[]>): string {
const pairs: string[] = []
for (const key in parts) {
const val = (Array.isArray(parts[key]) ? parts[key] : [parts[key]]) as string[]
for (const v of val) {
pairs.push(` + "`" + `${key}=${encodeURIComponent(v)}` + "`" + `)
}
}
return pairs.join("&")
}
// makeRecord takes a record and strips any undefined values from it,
// and returns the same record with a narrower type.
// @ts-ignore - TS ignore because makeRecord is not always used
function makeRecord<K extends string | number | symbol, V>(record: Record<K, V | undefined>): Record<K, V> {
for (const key in record) {
if (record[key] === undefined) {
delete record[key]
}
}
return record as Record<K, V>
}
`)
if ts.seenHeaderResponse {
ts.WriteString(`
// mustBeSet will throw an APIError with the Data Loss code if value is null or undefined
function mustBeSet<A>(field: string, value: A | null | undefined): A {
if (value === null || value === undefined) {
throw new APIError(
500,
{
code: ErrCode.DataLoss,
message: ` + "`${field} was unexpectedly ${value}`" + `, // ${value} will create the string "null" or "undefined"
},
)
}
return value
}
`)
}
}
func (ts *typescript) writeDecl(ns string, decl *schema.Decl) {
if decl.Loc.PkgName != ns {
ts.WriteString(ts.typeName(decl.Loc.PkgName) + ".")
}
ts.WriteString(ts.typeName(decl.Name))
}
func (ts *typescript) builtinType(typ schema.Builtin) string {
switch typ {
case schema.Builtin_ANY:
return "any"
case schema.Builtin_BOOL:
return "boolean"
case schema.Builtin_INT, schema.Builtin_INT8, schema.Builtin_INT16, schema.Builtin_INT32, schema.Builtin_INT64,
schema.Builtin_UINT, schema.Builtin_UINT8, schema.Builtin_UINT16, schema.Builtin_UINT32, schema.Builtin_UINT64,
schema.Builtin_FLOAT32, schema.Builtin_FLOAT64:
return "number"
case schema.Builtin_STRING:
return "string"
case schema.Builtin_BYTES:
return "string" // TODO
case schema.Builtin_TIME:
return "string" // TODO
case schema.Builtin_JSON:
ts.seenJSON = true
return "JSONValue"
case schema.Builtin_UUID:
return "string"
case schema.Builtin_USER_ID:
return "string"
default:
ts.errorf("unknown builtin type %v", typ)
return "any"
}
}
func (ts *typescript) convertBuiltinToString(typ schema.Builtin, val string, isOptional bool) string {
var code string
switch typ {
case schema.Builtin_STRING:
return val
case schema.Builtin_JSON:
code = fmt.Sprintf("JSON.stringify(%s)", val)
default:
code = fmt.Sprintf("String(%s)", val)
}
if isOptional {
code = fmt.Sprintf("%s === undefined ? undefined : %s", val, code)
}
return code
}
func (ts *typescript) convertStringToBuiltin(typ schema.Builtin, val string) string {
switch typ {
case schema.Builtin_ANY:
return val
case schema.Builtin_BOOL:
return fmt.Sprintf("%s.toLowerCase() === \"true\"", val)
case schema.Builtin_INT, schema.Builtin_INT8, schema.Builtin_INT16, schema.Builtin_INT32, schema.Builtin_INT64,
schema.Builtin_UINT, schema.Builtin_UINT8, schema.Builtin_UINT16, schema.Builtin_UINT32, schema.Builtin_UINT64:
return fmt.Sprintf("parseInt(%s, 10)", val)
case schema.Builtin_FLOAT32, schema.Builtin_FLOAT64:
return fmt.Sprintf("Number(%s)", val)
case schema.Builtin_STRING:
return val
case schema.Builtin_BYTES:
return val
case schema.Builtin_TIME:
return val
case schema.Builtin_JSON:
ts.seenJSON = true
return fmt.Sprintf("JSON.parse(%s)", val)
case schema.Builtin_UUID:
return val
case schema.Builtin_USER_ID:
return val
default:
ts.errorf("unknown builtin type %v", typ)
return "any"
}
}
func (ts *typescript) writeTyp(ns string, typ *schema.Type, numIndents int) {
switch typ := typ.Typ.(type) {
case *schema.Type_Named: