-
Notifications
You must be signed in to change notification settings - Fork 40
/
generate_nodejs.go
1698 lines (1484 loc) · 53.1 KB
/
generate_nodejs.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
// Copyright 2016-2018, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Pulling out some of the repeated strings tokens into constants would harm readability, so we just ignore the
// goconst linter's warning.
//
// nolint: goconst
package tfgen
import (
"encoding/json"
"fmt"
"os"
"path"
"path/filepath"
"reflect"
"sort"
"strconv"
"strings"
"github.com/gedex/inflector"
"github.com/golang/glog"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/sdk/go/common/diag"
"github.com/pulumi/pulumi/sdk/go/common/tokens"
"github.com/pulumi/pulumi/sdk/go/common/tools"
"github.com/pulumi/pulumi/sdk/go/common/util/cmdutil"
"github.com/pulumi/pulumi/sdk/go/common/util/contract"
"github.com/pulumi/pulumi-terraform-bridge/pkg/tfbridge"
)
// newNodeJSGenerator returns a language generator that understands how to produce Type/JavaScript packages.
func newNodeJSGenerator(pkg, version string, info tfbridge.ProviderInfo, overlaysDir, outDir string) langGenerator {
return &nodeJSGenerator{
pkg: pkg,
version: version,
info: info,
overlaysDir: overlaysDir,
outDir: outDir,
}
}
type nodeJSGenerator struct {
pkg string
version string
info tfbridge.ProviderInfo
overlaysDir string
outDir string
}
// nestedTypes is hold nested type information.
// The inputs and outputs maps are maps from a type name to type declaration.
// inputOverlays contains a set of custom types that need to be imported for the nested input types.
type nestedTypes struct {
inputs map[string]string
inputOverlays map[string]bool
outputs map[string]string
}
func newNestedTypes() *nestedTypes {
return &nestedTypes{
inputs: make(map[string]string),
inputOverlays: make(map[string]bool),
outputs: make(map[string]string),
}
}
// commentChars returns the comment characters to use for single-line comments.
func (g *nodeJSGenerator) commentChars() string {
return "//"
}
// moduleDir returns the directory for the given module.
func (g *nodeJSGenerator) moduleDir(mod *module) string {
dir := g.outDir
if mod.name != "" {
dir = filepath.Join(dir, mod.name)
}
return dir
}
// relativeRootDir returns the relative path to the root directory for the given module.
func (g *nodeJSGenerator) relativeRootDir(mod *module) string {
p, err := filepath.Rel(g.moduleDir(mod), g.outDir)
contract.IgnoreError(err)
return p
}
// openWriter opens a writer for the given module and file name, emitting the standard header automatically.
func (g *nodeJSGenerator) openWriter(mod *module, name string, needsSDK, needsInput, needsOutput, needsUtilities bool) (
*tools.GenWriter, string, error) {
dir := g.moduleDir(mod)
file := filepath.Join(dir, name)
w, err := tools.NewGenWriter(tfgen, file)
if err != nil {
return nil, "", err
}
// Emit a standard warning header ("do not edit", etc).
w.EmitHeaderWarning(g.commentChars())
// If needed, emit the standard Pulumi SDK import statement.
if needsSDK {
g.emitSDKImport(mod, w, needsInput, needsOutput, needsUtilities)
}
return w, file, nil
}
func (g *nodeJSGenerator) emitSDKImport(mod *module, w *tools.GenWriter, needsInput, needsOutput, needsUtilities bool) {
w.Writefmtln("import * as pulumi from \"@pulumi/pulumi\";")
if needsInput {
w.Writefmtln("import * as inputs from \"%s/types/input\";", g.relativeRootDir(mod))
}
if needsOutput {
w.Writefmtln("import * as outputs from \"%s/types/output\";", g.relativeRootDir(mod))
}
if needsUtilities {
w.Writefmtln("import * as utilities from \"%s/utilities\";", g.relativeRootDir(mod))
}
w.Writefmtln("")
}
// typeName returns a type name for a given resource type.
func (g *nodeJSGenerator) typeName(r *resourceType) string {
return r.name
}
// emitPackage emits an entire package pack into the configured output directory with the configured settings.
func (g *nodeJSGenerator) emitPackage(pack *pkg) error {
// Return an error if the provider has its own `types` module, which is reserved for now.
// If we do run into a provider that has such a module, we'll have to make some changes to allow it.
if _, ok := pack.modules["types"]; ok {
return errors.New("This provider has a `types` module which is reserved for input/output types")
}
// Create a map of modules to *nestedTypes.
nestedMap := make(map[string]*nestedTypes)
// Generate the individual modules and their contents.
files, submodules, err := g.emitModules(pack.modules, nestedMap)
if err != nil {
return err
}
// Generate a top-level index file that re-exports any child modules and a top-level utils file.
index := pack.modules.ensureModule("")
if pack.provider != nil {
index.members = append(index.members, pack.provider)
}
// Generate initial top-level module without `types` submodule.
_, _, nested, err := g.emitModule(index, submodules)
if err != nil {
return err
}
if nested != nil {
nestedMap[""] = nested
}
// Emit input/output files in the `types` module.
typesInputFile, err := g.emitNestedTypes(nestedMap, true /*input*/)
if err != nil {
return err
}
if typesInputFile != "" {
files = append(files, typesInputFile)
}
typesOutputFile, err := g.emitNestedTypes(nestedMap, false /*input*/)
if err != nil {
return err
}
if typesOutputFile != "" {
files = append(files, typesOutputFile)
}
hasInputs := typesInputFile != ""
hasOutputs := typesOutputFile != ""
typesIndex, err := g.emitTypesModule(hasInputs, hasOutputs)
if err != nil {
return err
}
if typesIndex != "" {
files = append(files, typesIndex)
submodules["types"] = typesIndex
}
// Regenerate the top-level index again, this time including the `types` submodule, if present.
indexFiles, _, _, err := g.emitModule(index, submodules)
if err != nil {
return err
}
files = append(files, indexFiles...)
// Finally emit the package metadata (NPM, TypeScript, and so on).
sort.Strings(files)
return g.emitPackageMetadata(pack, files)
}
// emitTypesModule emits the `types` module.
func (g *nodeJSGenerator) emitTypesModule(hasInputs, hasOutputs bool) (string, error) {
if !hasInputs && !hasOutputs {
return "", nil
}
typesMod := newModule("types")
dir := g.moduleDir(typesMod)
submodules := make(map[string]string)
if hasInputs {
submodules["input"] = path.Join(dir, "input.ts")
}
if hasOutputs {
submodules["output"] = path.Join(dir, "output.ts")
}
typesIndexFile, err := g.emitIndex(typesMod, nil, submodules)
if err != nil {
return "", err
}
return typesIndexFile, nil
}
// emitNestedTypes emits the nested types in the map of modules to nestedTypes in either a `types/input.ts` or
// `types/output.ts` based on the value of `input`.
func (g *nodeJSGenerator) emitNestedTypes(nestedMap map[string]*nestedTypes, input bool) (string, error) {
// Ensure we have nested types.
if nestedMap == nil {
return "", nil
}
any := false
for _, nested := range nestedMap {
typeMap := nested.outputs
if input {
typeMap = nested.inputs
}
if len(typeMap) > 0 {
any = true
break
}
}
if !any {
return "", nil
}
name := "output"
if input {
name = "input"
}
typesMod := newModule("types")
// Ensure the types directory exists.
dir := g.moduleDir(typesMod)
if err := tools.EnsureDir(dir); err != nil {
return "", errors.Wrapf(err, "creating module directory")
}
// Open the file for writing.
needsSDK := true
needsInput := input
needsOutput := !input
needsUtilities := false
w, file, err := g.openWriter(typesMod, name+".ts", needsSDK, needsInput, needsOutput, needsUtilities)
if err != nil {
return "", err
}
defer contract.IgnoreClose(w)
var mods []string
for mod := range nestedMap {
mods = append(mods, mod)
}
sort.Strings(mods)
// Gather custom type imports (overlays).
imports := make(importMap)
if input {
for _, mod := range mods {
nested := nestedMap[mod]
relmod := fmt.Sprintf("../%s", mod)
for typeName := range nested.inputOverlays {
importName := getCustomImportTypeName(typeName)
// Now just mark the member in the resulting map.
if imports[relmod] == nil {
imports[relmod] = make(map[string]bool)
}
imports[relmod][importName] = true
}
}
}
// Emit custom type imports.
if err := g.emitImportMap(w, imports); err != nil {
return "", err
}
// Emit the modules as namespaces.
// Types in the "" module are top-level and aren't outputted within a namespace.
for i, mod := range mods {
nested := nestedMap[mod]
typeMap := nested.outputs
if input {
typeMap = nested.inputs
}
if i > 0 {
w.Writefmtln("")
}
indent := ""
if mod != "" {
indent = " "
w.Writefmtln("export namespace %s {", mod)
}
// Emit the types.
var types []string
for typ := range typeMap {
types = append(types, typ)
}
sort.Strings(types)
for j, typ := range types {
declaration := typeMap[typ]
if j > 0 {
w.Writefmtln("")
}
declarationLines := strings.Split(declaration, "\n")
for k, line := range declarationLines {
if k == 0 {
w.Writefmtln("%sexport interface %s %s", indent, typ, line)
} else {
w.Writefmtln("%s%s", indent, line)
}
}
}
if mod != "" {
w.Writefmtln("}")
}
}
return file, nil
}
// emitModules emits all modules in the given module map. It returns a full list of files, a map of module to its
// associated index, and any error that occurred, if any.
func (g *nodeJSGenerator) emitModules(mmap moduleMap, nestedMap map[string]*nestedTypes) ([]string, map[string]string,
error) {
var allFiles []string
moduleMap := make(map[string]string)
for _, mod := range mmap.values() {
if mod.name == "" {
continue // skip the root module, it is handled specially.
}
files, index, nested, err := g.emitModule(mod, nil)
if err != nil {
return nil, nil, err
}
allFiles = append(allFiles, files...)
moduleMap[mod.name] = index
if nested != nil {
nestedMap[mod.name] = nested
}
}
return allFiles, moduleMap, nil
}
// emitModule emits a module. This module ends up having many possible ES6 sub-modules which are then re-exported
// at the top level. This is to make it convenient for overlays to import files within the same module without
// causing problematic cycles. For example, imagine a module m with many members; the result is:
//
// m/
// README.md
// index.ts
// member1.ts
// member<etc>.ts
// memberN.ts
//
// The one special case is the configuration module, which yields a vars.ts file containing all exported variables.
//
// Note that the special module "" represents the top-most package module and won't be placed in a sub-directory.
//
// The return values are the full list of files generated, the index file, and any error that occurred, respectively.
func (g *nodeJSGenerator) emitModule(mod *module, submods map[string]string) ([]string, string, *nestedTypes, error) {
glog.V(3).Infof("emitModule(%s)", mod.name)
// Ensure that the target module directory exists.
dir := g.moduleDir(mod)
if err := tools.EnsureDir(dir); err != nil {
return nil, "", nil, errors.Wrapf(err, "creating module directory")
}
// Ensure that the target module directory contains a README.md file.
if err := g.ensureReadme(dir); err != nil {
return nil, "", nil, errors.Wrapf(err, "creating module README file")
}
// Create the data structure to hold nested type information for the module.
nested := newNestedTypes()
// Now, enumerate each module member, in the order presented to us, and do the right thing.
var files []string
for _, member := range mod.members {
file, err := g.emitModuleMember(mod, member, nested)
if err != nil {
return nil, "", nil, errors.Wrapf(err, "emitting module %s member %s", mod.name, member.Name())
} else if file != "" {
files = append(files, file)
}
}
// If this is a config module, we need to emit the configuration variables.
if mod.config() {
file, err := g.emitConfigVariables(mod)
if err != nil {
return nil, "", nil, errors.Wrapf(err, "emitting config module variables")
}
files = append(files, file)
}
// Generate an index file for this module.
index, err := g.emitIndex(mod, files, submods)
if err != nil {
return nil, "", nil, errors.Wrapf(err, "emitting module %s index", mod.name)
}
files = append(files, index)
// Lastly, if this is the root module, we need to emit a file containing utility functions consumed by other
// modules.
if mod.root() {
utils, err := g.emitUtilities(mod)
if err != nil {
return nil, "", nil, errors.Wrapf(err, "emitting utility file for root module")
}
files = append(files, utils)
}
if len(nested.inputs) == 0 && len(nested.outputs) == 0 {
nested = nil
}
return files, index, nested, nil
}
// ensureReadme writes out a stock README.md file, provided one doesn't already exist.
func (g *nodeJSGenerator) ensureReadme(dir string) error {
rf := filepath.Join(dir, "README.md")
_, err := os.Stat(rf)
if err == nil {
return nil // file already exists, exit right away.
} else if !os.IsNotExist(err) {
return err // legitimate error, propagate it.
}
// If we got here, the README.md doesn't already exist -- write out a stock one.
w, err := tools.NewGenWriter(tfgen, rf)
if err != nil {
return err
}
defer contract.IgnoreClose(w)
downstreamLicense := g.info.GetTFProviderLicense()
licenseTypeURL := getLicenseTypeURL(downstreamLicense)
w.Writefmtln(standardDocReadme, g.pkg, g.info.Name, g.info.GetGitHubOrg(), downstreamLicense, licenseTypeURL)
return nil
}
// emitIndex emits an index module, optionally re-exporting other members or submodules.
func (g *nodeJSGenerator) emitIndex(mod *module, exports []string, submods map[string]string) (string, error) {
// Open the index.ts file for this module, and ready it for writing.
w, index, err := g.openWriter(mod, "index.ts", false, false, false, false)
if err != nil {
return "", err
}
defer contract.IgnoreClose(w)
// Export anything flatly that is a direct export rather than sub-module.
if len(exports) > 0 {
w.Writefmtln("// Export members:")
var exps []string
exps = append(exps, exports...)
sort.Strings(exps)
for _, exp := range exps {
rel, err := g.relModule(mod, exp)
if err != nil {
return "", err
}
w.Writefmtln("export * from \"%s\";", rel)
}
}
// Finally, if there are submodules, export them.
if len(submods) > 0 {
if len(exports) > 0 {
w.Writefmtln("")
}
w.Writefmtln("// Export sub-modules:")
var subs []string
for sub := range submods {
subs = append(subs, sub)
}
sort.Strings(subs)
for _, sub := range subs {
rel, err := g.relModule(mod, submods[sub])
if err != nil {
return "", err
}
w.Writefmtln("import * as %s from \"%s\";", sub, rel)
}
w.Writefmt("export {")
for i, sub := range subs {
if i > 0 {
w.Writefmt(", ")
}
w.Writefmt(sub)
}
w.Writefmtln("};")
}
return index, nil
}
// emitUtilities emits a utilities file for submodules to consume.
func (g *nodeJSGenerator) emitUtilities(mod *module) (string, error) {
contract.Require(mod.root(), "mod.root()")
// Open the utilities.ts file for this module and ready it for writing.
w, utilities, err := g.openWriter(mod, "utilities.ts", false, false, false, false)
if err != nil {
return "", err
}
defer contract.IgnoreClose(w)
// TODO: use w.WriteString
w.Writefmt(tsUtilitiesFile)
return utilities, nil
}
// emitModuleMember emits the given member, and returns the module file that it was emitted into (if any).
func (g *nodeJSGenerator) emitModuleMember(mod *module, member moduleMember, nested *nestedTypes) (string, error) {
glog.V(3).Infof("emitModuleMember(%s, %s)", mod, member.Name())
switch t := member.(type) {
case *resourceType:
return g.emitResourceType(mod, t, nested)
case *resourceFunc:
return g.emitResourceFunc(mod, t, nested)
case *variable:
contract.Assertf(mod.config(),
"only expected top-level variables in config module (%s is not one)", mod.name)
// skip the variable, we will process it later.
return "", nil
case *overlayFile:
return g.emitOverlay(mod, t)
default:
contract.Failf("unexpected member type: %v", reflect.TypeOf(member))
return "", nil
}
}
// emitConfigVariables emits all config vaiables in the given module, returning the resulting file.
func (g *nodeJSGenerator) emitConfigVariables(mod *module) (string, error) {
// Create a vars.ts file into which all configuration variables will go.
w, config, err := g.openWriter(mod, "vars.ts", true, false, false, true)
if err != nil {
return "", err
}
defer contract.IgnoreClose(w)
// Ensure we import any custom schemas referenced by the variables.
var infos []*tfbridge.SchemaInfo
for _, member := range mod.members {
if v, ok := member.(*variable); ok {
infos = append(infos, v.info)
}
}
if err = g.emitCustomImports(w, mod, infos); err != nil {
return "", err
}
// Create a config bag for the variables to pull from.
w.Writefmtln("let __config = new pulumi.Config(\"%v\");", g.pkg)
w.Writefmtln("")
// Emit an entry for all config variables.
for _, member := range mod.members {
if v, ok := member.(*variable); ok {
g.emitConfigVariable(w, v)
}
}
return config, nil
}
func (g *nodeJSGenerator) emitConfigVariable(w *tools.GenWriter, v *variable) {
getfunc := "get"
if v.schema.Type != schema.TypeString {
// Only try to parse a JSON object if the config isn't a straight string.
getfunc = fmt.Sprintf("getObject<%s>",
tsType("", "", v, nil, nil, false /*noflags*/, !v.out /*wrapInput*/, false /*isInputType*/))
}
var anycast string
if v.info != nil && v.info.Type != "" {
// If there's a custom type, we need to inject a cast to silence the compiler.
anycast = "<any>"
}
if v.doc != "" && v.doc != elidedDocComment {
g.emitDocComment(w, v.doc, v.docURL, "", "")
} else if v.rawdoc != "" {
g.emitRawDocComment(w, v.rawdoc, "", "")
}
configFetch := fmt.Sprintf("__config.%s(\"%s\")", getfunc, v.name)
if defaultValue := tsDefaultValue(v); defaultValue != "undefined" {
configFetch += " || " + defaultValue
}
w.Writefmtln("export let %s: %s | undefined = %s%s;", v.name,
tsType("", "", v, nil, nil, false /*noflags*/, !v.out /*wrapInput*/, false /*isInputType*/),
anycast, configFetch)
}
// sanitizeForDocComment ensures that no `*/` sequence appears in the string, to avoid
// accidentally closing the comment block.
func sanitizeForDocComment(str string) string {
return strings.Replace(str, "*/", "*/", -1)
}
func (g *nodeJSGenerator) emitDocComment(w *tools.GenWriter, comment, docURL, deprecationMessage, prefix string) {
if comment == elidedDocComment && docURL == "" {
return
}
w.Writefmtln("%v/**", prefix)
if comment != elidedDocComment {
lines := strings.Split(comment, "\n")
for i, docLine := range lines {
docLine = sanitizeForDocComment(docLine)
// Break if we get to the last line and it's empty
if i == len(lines)-1 && strings.TrimSpace(docLine) == "" {
break
}
// Print the line of documentation
w.Writefmtln("%v * %s", prefix, docLine)
}
if docURL != "" {
w.Writefmtln("%v *", prefix)
}
}
if docURL != "" {
w.Writefmtln("%v * > This content is derived from %s.", prefix, docURL)
}
if deprecationMessage != "" {
w.Writefmtln("%v * ", prefix)
w.Writefmtln("%v * @deprecated %s", prefix, deprecationMessage)
}
w.Writefmtln("%v */", prefix)
}
func (g *nodeJSGenerator) emitRawDocComment(w *tools.GenWriter, comment, deprecationMessage, prefix string) {
if comment != "" {
curr := 0
w.Writefmtln("%v/**", prefix)
w.Writefmt("%v * ", prefix)
for _, word := range strings.Fields(comment) {
word = sanitizeForDocComment(word)
if curr > 0 {
if curr+len(word)+1 > (maxWidth - len(prefix)) {
curr = 0
w.Writefmt("\n%v * ", prefix)
} else {
w.Writefmt(" ")
curr++
}
}
w.Writefmt(word)
curr += len(word)
}
w.Writefmtln("")
if deprecationMessage != "" {
w.Writefmtln("%v * ", prefix)
w.Writefmtln("%v * @deprecated %s", prefix, deprecationMessage)
}
w.Writefmtln("%v */", prefix)
}
}
func (g *nodeJSGenerator) emitPlainOldType(w *tools.GenWriter, pot *propertyType, module, prefix string,
nestedTypeDeclarations map[string]string, nestedInputOverlays map[string]bool, wrapInput,
isInputType bool) {
if pot.doc != "" {
g.emitDocComment(w, pot.doc, "", "", "")
}
w.Writefmtln("export interface %s {", pot.name)
for _, prop := range pot.properties {
if prop.doc != "" && prop.doc != elidedDocComment {
g.emitDocComment(w, prop.doc, prop.docURL, prop.deprecationMessage(), " ")
} else if prop.rawdoc != "" {
g.emitRawDocComment(w, prop.rawdoc, prop.deprecationMessage(), " ")
}
w.Writefmtln(" readonly %s%s: %s;", prop.name, tsFlags(prop), tsType(module, prefix, prop,
nestedTypeDeclarations, nestedInputOverlays, false /*noflags*/, wrapInput, isInputType))
}
w.Writefmtln("}")
}
//nolint:lll
func (g *nodeJSGenerator) emitResourceType(mod *module, res *resourceType, nested *nestedTypes) (string, error) {
// Create a resource module file into which all of this resource's types will go.
name := res.name
filename := lowerFirst(name)
// We need to check if the resource is called index or utilities. If so then we will have problems
// based on the fact that we need to generate an index.ts based on the package contents
// Therefore, we are going to append _ into the name to allow us to continue
if filename == "index" || filename == "utilities" {
filename = fmt.Sprintf("%s_", filename)
}
needsSDK := true
needsInput := len(nested.inputs) > 0
needsOutput := len(nested.outputs) > 0
needsUtilities := true
w, file, err := g.openWriter(mod, filename+".ts", needsSDK, needsInput, needsOutput, needsUtilities)
if err != nil {
return "", err
}
defer contract.IgnoreClose(w)
// Ensure that we've emitted any custom imports pertaining to any of the field types.
var fldinfos []*tfbridge.SchemaInfo
for _, fldinfo := range res.info.Fields {
fldinfos = append(fldinfos, fldinfo)
}
if err = g.emitCustomImports(w, mod, fldinfos); err != nil {
return "", err
}
// Write the TypeDoc/JSDoc for the resource class
if res.doc != "" {
g.emitDocComment(w, res.doc, res.docURL, "", "")
}
baseType := "CustomResource"
if res.IsProvider() {
baseType = "ProviderResource"
}
if !res.IsProvider() && res.info.DeprecationMessage != "" {
w.Writefmtln("/** @deprecated %s */", res.info.DeprecationMessage)
}
// Begin defining the class.
w.Writefmtln("export class %s extends pulumi.%s {", name, baseType)
// Emit a static factory to read instances of this resource unless this is a provider resource.
stateType := res.statet.name
if !res.IsProvider() {
w.Writefmtln(" /**")
w.Writefmtln(" * Get an existing %s resource's state with the given name, ID, and optional extra", name)
w.Writefmtln(" * properties used to qualify the lookup.")
w.Writefmtln(" *")
w.Writefmtln(" * @param name The _unique_ name of the resulting resource.")
w.Writefmtln(" * @param id The _unique_ provider ID of the resource to lookup.")
w.Writefmtln(" * @param state Any extra arguments used during the lookup.")
w.Writefmtln(" */")
w.Writefmtln(" public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: %s, opts?: pulumi.CustomResourceOptions): %s {", stateType, name)
if res.info.DeprecationMessage != "" {
w.Writefmtln(" pulumi.log.warn(\"%s is deprecated: %s\")", name, res.info.DeprecationMessage)
}
w.Writefmtln(" return new %s(name, <any>state, { ...opts, id: id });", name)
w.Writefmtln(" }")
w.Writefmtln("")
}
w.Writefmtln(" /** @internal */")
w.Writefmtln(" public static readonly __pulumiType = '%s';", res.info.Tok)
w.Writefmtln("")
w.Writefmtln(" /**")
w.Writefmtln(" * Returns true if the given object is an instance of %s. This is designed to work even", name)
w.Writefmtln(" * when multiple copies of the Pulumi SDK have been loaded into the same process.")
w.Writefmtln(" */")
w.Writefmtln(" public static isInstance(obj: any): obj is %s {", name)
w.Writefmtln(" if (obj === undefined || obj === null) {")
w.Writefmtln(" return false;")
w.Writefmtln(" }")
w.Writefmtln(" return obj['__pulumiType'] === %s.__pulumiType;", name)
w.Writefmtln(" }")
w.Writefmtln("")
// Emit all properties (using their output types).
// TODO[pulumi/pulumi#397]: represent sensitive types using a Secret<T> type.
ins := make(map[string]bool)
for _, prop := range res.inprops {
ins[prop.name] = true
}
for _, prop := range res.outprops {
if prop.doc != "" && prop.doc != elidedDocComment {
g.emitDocComment(w, prop.doc, prop.docURL, "", " ")
} else if prop.rawdoc != "" {
g.emitRawDocComment(w, prop.rawdoc, "", " ")
}
// Make a little comment in the code so it's easy to pick out output properties.
var outcomment string
if !ins[prop.name] {
outcomment = "/*out*/ "
}
w.Writefmtln(" public %sreadonly %s!: pulumi.Output<%s>;",
outcomment, prop.name, tsType(mod.name, name, prop, nested.outputs, nil,
true /*noflags*/, !prop.out /*wrapInput*/, false /*isInputType*/))
}
w.Writefmtln("")
// Now create a constructor that chains supercalls and stores into properties.
w.Writefmtln(" /**")
w.Writefmtln(" * Create a %s resource with the given unique name, arguments, and options.", name)
w.Writefmtln(" *")
w.Writefmtln(" * @param name The _unique_ name of the resource.")
w.Writefmtln(" * @param args The arguments to use to populate this resource's properties.")
w.Writefmtln(" * @param opts A bag of options that control this resource's behavior.")
w.Writefmtln(" */")
// Write out callable constructor: We only emit a single public constructor, even though we use a private signature
// as well as part of the implementation of `.get`. This is complicated slightly by the fact that, if there is no
// args type, we will emit a constructor lacking that parameter.
var argsFlags string
if len(res.reqprops) == 0 {
// If the number of required input properties was zero, we can make the args object optional.
argsFlags = "?"
}
argsType := res.argst.name
trailingBrace := ""
if res.IsProvider() {
trailingBrace = " {"
}
optionsType := "CustomResourceOptions"
if res.IsProvider() {
optionsType = "ResourceOptions"
}
if res.info.DeprecationMessage != "" {
w.Writefmtln(" /** @deprecated %s */", res.info.DeprecationMessage)
}
w.Writefmtln(" constructor(name: string, args%s: %s, opts?: pulumi.%s)%s", argsFlags, argsType,
optionsType, trailingBrace)
if !res.IsProvider() {
if res.info.DeprecationMessage != "" {
w.Writefmtln(" /** @deprecated %s */", res.info.DeprecationMessage)
}
// Now write out a general purpose constructor implementation that can handle the public signautre as well as the
// signature to support construction via `.get`. And then emit the body preamble which will pluck out the
// conditional state into sensible variables using dynamic type tests.
w.Writefmtln(" constructor(name: string, argsOrState?: %s | %s, opts?: pulumi.CustomResourceOptions) {",
argsType, stateType)
if res.info.DeprecationMessage != "" {
w.Writefmtln(" pulumi.log.warn(\"%s is deprecated: %s\")", name, res.info.DeprecationMessage)
}
w.Writefmtln(" let inputs: pulumi.Inputs = {};")
// The lookup case:
w.Writefmtln(" if (opts && opts.id) {")
w.Writefmtln(" const state = argsOrState as %[1]s | undefined;", stateType)
for _, prop := range res.outprops {
w.Writefmtln(` inputs["%[1]s"] = state ? state.%[1]s : undefined;`, prop.name)
}
// The creation case (with args):
w.Writefmtln(" } else {")
w.Writefmtln(" const args = argsOrState as %s | undefined;", argsType)
} else {
w.Writefmtln(" let inputs: pulumi.Inputs = {};")
w.Writefmtln(" {")
}
for _, prop := range res.inprops {
// Here we are checking to see if there is a defaultFunc specified in the
// Terraform configuration but that isn't in the Pulumi configuration
if res.IsProvider() && prop.schema != nil && prop.schema.DefaultFunc != nil {
if prop.info == nil {
cmdutil.Diag().Warningf(
diag.Message("", "property %s has a DefaultFunc that isn't projected"), prop.name)
}
// There is a chance that we do have a SchemaInfo but we may not have EnvVars or a Default Value set
if prop.info != nil && len(prop.info.Default.EnvVars) == 0 && prop.info.Default.Value == nil {
cmdutil.Diag().Warningf(
diag.Message("", "property %s has a DefaultFunc that isn't projected"), prop.name)
}
}
if !prop.optional() {
w.Writefmtln(" if (!args || args.%s === undefined) {", prop.name)
w.Writefmtln(" throw new Error(\"Missing required property '%s'\");", prop.name)
w.Writefmtln(" }")
}
}
for _, prop := range res.inprops {
arg := fmt.Sprintf("args ? args.%[1]s : undefined", prop.name)
if defaultValue := tsDefaultValue(prop); defaultValue != "undefined" {
arg = fmt.Sprintf("(%s) || %s", arg, defaultValue)
}
// provider properties must be marshaled as JSON strings.
if res.IsProvider() && prop.schema != nil && prop.schema.Type != schema.TypeString {
arg = fmt.Sprintf("pulumi.output(%s).apply(JSON.stringify)", arg)
}
w.Writefmtln(` inputs["%s"] = %s;`, prop.name, arg)
}
for _, prop := range res.outprops {
if !ins[prop.name] {
w.Writefmtln(` inputs["%s"] = undefined /*out*/;`, prop.name)
}
}
w.Writefmtln(" }")
// If the caller didn't request a specific version, supply one using the version of this library.
w.Writefmtln(" if (!opts) {")
w.Writefmtln(" opts = {}")
w.Writefmtln(" }")
w.Writefmtln("")
w.Writefmtln(" if (!opts.version) {")
w.Writefmtln(" opts.version = utilities.getVersion();")
w.Writefmtln(" }")
// Now invoke the super constructor with the type, name, and a property map.
if len(res.info.Aliases) > 0 {
w.Writefmt(` const aliasOpts = { aliases: [`)
for i, alias := range res.info.Aliases {
if i > 0 {
w.Writefmt(", ")
}
g.writeAlias(w, alias)
}
w.Writefmtln(`] };`)
w.Writefmtln(` opts = opts ? pulumi.mergeOptions(opts, aliasOpts) : aliasOpts;`)
}
w.Writefmtln(` super(%s.__pulumiType, name, inputs, opts);`, name)
// Finish the class.
w.Writefmtln(" }")
w.Writefmtln("}")
// Emit the state type for get methods.
if !res.IsProvider() {
w.Writefmtln("")
g.emitPlainOldType(w, res.statet, mod.name, name, nested.inputs, nested.inputOverlays,
true /*wrapInput*/, true /*isInputType*/)
}
// Emit the argument type for construction.
w.Writefmtln("")
g.emitPlainOldType(w, res.argst, mod.name, name, nested.inputs, nested.inputOverlays,
true /*wrapInput*/, true /*isInputType*/)
// If we generated any nested types, regenerate the type to add the proper imports at the top.
// This approach isn't great. Ideally, we'd precompute the nested types so we wouldn't have to regenerate.
if (!needsInput && len(nested.inputs) > 0) || (!needsOutput && len(nested.outputs) > 0) {
contract.IgnoreClose(w)
return g.emitResourceType(mod, res, nested)
}
return file, nil
}