@cdktn/provider-generator 0.26.0-pre.20 → 0.26.0-pre.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/build/get/generator/models/scope.js +2 -14
  2. package/jest.config.js +0 -1
  3. package/package.json +5 -5
  4. package/package.sh +0 -0
  5. package/src/__tests__/edge-provider-schema/builder.ts +0 -201
  6. package/src/__tests__/edge-provider-schema/cli.ts +0 -51
  7. package/src/__tests__/edge-provider-schema/index.ts +0 -284
  8. package/src/__tests__/edge-provider-schema.test.ts +0 -24
  9. package/src/__tests__/erasable-syntax.test.ts +0 -81
  10. package/src/__tests__/provider.test.ts +0 -208
  11. package/src/get/__tests__/constructs-maker.test.ts +0 -242
  12. package/src/get/__tests__/generator/complex-computed-types.test.ts +0 -28
  13. package/src/get/__tests__/generator/deep-nested-attributes.test.ts +0 -56
  14. package/src/get/__tests__/generator/description-escaping.test.ts +0 -84
  15. package/src/get/__tests__/generator/empty-provider-resources.test.ts +0 -26
  16. package/src/get/__tests__/generator/ephemeral-resources.test.ts +0 -46
  17. package/src/get/__tests__/generator/export-sharding.test.ts +0 -169
  18. package/src/get/__tests__/generator/import-style.test.ts +0 -129
  19. package/src/get/__tests__/generator/module-docs-registry.test.ts +0 -89
  20. package/src/get/__tests__/generator/module-generator.test.ts +0 -528
  21. package/src/get/__tests__/generator/nested-types.test.ts +0 -54
  22. package/src/get/__tests__/generator/provider-functions-name-collision.test.ts +0 -84
  23. package/src/get/__tests__/generator/provider-functions.test.ts +0 -262
  24. package/src/get/__tests__/generator/provider-source-matching.test.ts +0 -84
  25. package/src/get/__tests__/generator/provider.test.ts +0 -59
  26. package/src/get/__tests__/generator/resource-types.test.ts +0 -118
  27. package/src/get/__tests__/generator/skipped-attributes.test.ts +0 -72
  28. package/src/get/__tests__/generator/supported-stored-classes.test.ts +0 -147
  29. package/src/get/__tests__/generator/types.test.ts +0 -686
  30. package/src/get/__tests__/generator/versions-file.test.ts +0 -77
  31. package/src/get/__tests__/generator/write-only.test.ts +0 -71
  32. package/src/get/__tests__/registry-class-invalidation.test.ts +0 -123
  33. package/src/get/__tests__/target-versions.test.ts +0 -249
  34. package/src/get/__tests__/util.ts +0 -80
  35. package/src/get/constructs-maker.ts +0 -991
  36. package/src/get/generator/custom-defaults.ts +0 -494
  37. package/src/get/generator/emitter/attributes-emitter.ts +0 -316
  38. package/src/get/generator/emitter/index.ts +0 -6
  39. package/src/get/generator/emitter/provider-functions-emitter.ts +0 -117
  40. package/src/get/generator/emitter/resource-emitter.ts +0 -330
  41. package/src/get/generator/emitter/struct-emitter.ts +0 -683
  42. package/src/get/generator/loop-detection.ts +0 -81
  43. package/src/get/generator/models/attribute-model.ts +0 -273
  44. package/src/get/generator/models/attribute-type-model.ts +0 -559
  45. package/src/get/generator/models/index.ts +0 -8
  46. package/src/get/generator/models/provider-function-model.ts +0 -872
  47. package/src/get/generator/models/resource-model.ts +0 -206
  48. package/src/get/generator/models/scope.ts +0 -54
  49. package/src/get/generator/models/struct.ts +0 -124
  50. package/src/get/generator/models/supported-stored-classes.ts +0 -88
  51. package/src/get/generator/module-generator.ts +0 -236
  52. package/src/get/generator/provider-generator.ts +0 -451
  53. package/src/get/generator/resource-parser.ts +0 -782
  54. package/src/get/generator/sanitized-comments.ts +0 -49
  55. package/src/get/generator/skipped-attributes.ts +0 -27
  56. package/src/index.ts +0 -40
  57. package/src/util.ts +0 -26
@@ -1,206 +0,0 @@
1
- // Copyright (c) HashiCorp, Inc
2
- // SPDX-License-Identifier: MPL-2.0
3
- import { toSnakeCase } from "codemaker";
4
- import path from "path";
5
- import { FQPN, parseFQPN, ProviderName } from "@cdktn/provider-schema";
6
- import { AttributeModel } from "./attribute-model";
7
- import { Struct, ConfigStruct } from "./struct";
8
- import {
9
- Schema,
10
- TerraformTargetVersions,
11
- registryForTargetVersions,
12
- } from "@cdktn/commons";
13
- import { ProviderFunctionsModel } from "./provider-function-model";
14
-
15
- // Limit is 1200 to prevent stack size error.
16
- // Could increase now that calculation is more accurate;
17
- // however, probably better to have smaller
18
- export const STRUCT_SHARDING_THRESHOLD = 400;
19
-
20
- interface ResourceModelOptions {
21
- terraformType: string;
22
- className: string;
23
- baseName: string;
24
- fileName: string;
25
- filePath: string;
26
- attributes: AttributeModel[];
27
- structs: Struct[];
28
- fqpn: FQPN;
29
- schema: Schema;
30
- terraformSchemaType: string;
31
- configStructName: string;
32
- targetVersions?: TerraformTargetVersions;
33
- }
34
-
35
- type DefinitionPath = string;
36
- export class ResourceModel {
37
- public className: string;
38
- public filePath: string;
39
- public terraformType: string;
40
- public baseName: string;
41
- public provider: ProviderName;
42
- public fqpn: FQPN;
43
- private readonly targetVersions?: TerraformTargetVersions;
44
- public providerVersionConstraint?: string;
45
- public providerVersion?: string;
46
- public terraformProviderSource?: string;
47
- /*
48
- * usually same as provider, but can be overridden if user picks a different name
49
- * to be able to use two providers with the same name
50
- */
51
- public terraformProviderName: string;
52
- /*
53
- * Only set (by provider-generator.ts) when isProvider is true and the
54
- * provider schema declares provider-defined functions - drives whether
55
- * ResourceEmitter emits the memoized `functions` getter and its
56
- * cross-directory import of the sibling provider-functions/index.ts file.
57
- */
58
- public providerFunctionsModel?: ProviderFunctionsModel;
59
- public fileName: string;
60
- public attributes: AttributeModel[];
61
- public schema: Schema;
62
- private _structs: Struct[];
63
- private dependencies: string[];
64
- private terraformSchemaType: string;
65
- private configStructName: string;
66
- public readonly structsRequireSharding: boolean;
67
- public recursiveAttributePaths: { [usagePath: string]: DefinitionPath } = {};
68
-
69
- constructor(options: ResourceModelOptions) {
70
- this.className = options.className;
71
- this.filePath = options.filePath;
72
- this.terraformType = options.terraformType;
73
- this.baseName = options.baseName;
74
- this.attributes = options.attributes;
75
- this.schema = options.schema;
76
- this.fqpn = options.fqpn;
77
- this.targetVersions = options.targetVersions;
78
- this.provider = parseFQPN(options.fqpn).name;
79
- this.terraformProviderName = this.provider;
80
- this.fileName = options.fileName;
81
- this._structs = options.structs;
82
- this.terraformSchemaType = options.terraformSchemaType;
83
- this.configStructName = options.configStructName;
84
- this.dependencies = [
85
- `import { Construct } from 'constructs';`,
86
- `import * as cdktn from 'cdktn';`,
87
- ];
88
-
89
- this.structsRequireSharding =
90
- this._structs.reduce((partialSum, s) => partialSum + s.exportCount, 0) >
91
- STRUCT_SHARDING_THRESHOLD;
92
- }
93
-
94
- public get structs(): Struct[] {
95
- return [this.configStruct, ...this._structs];
96
- }
97
-
98
- public get configStruct() {
99
- return new ConfigStruct(
100
- this.configStructName,
101
- this.attributes,
102
- this.isEphemeralResource ? "TerraformEphemeralMetaArguments" : undefined,
103
- );
104
- }
105
-
106
- public get synthesizableAttributes(): AttributeModel[] {
107
- return this.configStruct.assignableAttributes;
108
- }
109
-
110
- public get importStatements(): string[] {
111
- return this.dependencies;
112
- }
113
-
114
- public get schemaAsJson(): string {
115
- return this.escapeSchema(JSON.stringify(this.schema, undefined, 2));
116
- }
117
-
118
- /** Registry that linkToDocs points at, for use in the surrounding prose. */
119
- public get docsRegistryName(): string {
120
- return registryForTargetVersions(this.targetVersions).displayName;
121
- }
122
-
123
- public get linkToDocs(): string {
124
- // Keyed off the project's declared targets, not the FQPN hostname: that
125
- // hostname reflects whichever CLI fetched the schema, which would make the
126
- // generated link differ between a terraform and a tofu `cdktn get`.
127
- const registry = registryForTargetVersions(this.targetVersions);
128
- const { namespace, name } = parseFQPN(this.fqpn);
129
- const version = this.providerVersion || "latest";
130
- const kind = this.isProvider
131
- ? "provider"
132
- : this.isDataSource
133
- ? "data-source"
134
- : this.isEphemeralResource
135
- ? "ephemeral-resource"
136
- : "resource";
137
- return registry.docsUrl(
138
- namespace,
139
- name,
140
- version,
141
- kind,
142
- this.terraformDocName,
143
- );
144
- }
145
-
146
- public get isProvider(): boolean {
147
- return this.terraformSchemaType === "provider";
148
- }
149
-
150
- public get isDataSource(): boolean {
151
- return this.terraformSchemaType === "data_source";
152
- }
153
-
154
- public get isEphemeralResource(): boolean {
155
- return this.terraformSchemaType === "ephemeral_resource";
156
- }
157
-
158
- public get parentClassName(): string {
159
- return this.isProvider
160
- ? "TerraformProvider"
161
- : this.isDataSource
162
- ? "TerraformDataSource"
163
- : this.isEphemeralResource
164
- ? "TerraformEphemeralResource"
165
- : "TerraformResource";
166
- }
167
-
168
- public get terraformResourceType(): string {
169
- return this.isProvider
170
- ? this.terraformProviderName
171
- : this.isDataSource
172
- ? this.terraformType.replace(/^data_/, "")
173
- : this.isEphemeralResource
174
- ? this.terraformType.replace(/^ephemeral_/, "")
175
- : this.terraformType;
176
- }
177
-
178
- public get terraformDocName(): string {
179
- return toSnakeCase(
180
- this.terraformResourceType.replace(
181
- new RegExp(`^${this.provider}_`, "i"),
182
- "",
183
- ),
184
- );
185
- }
186
-
187
- public get referencedTypes(): string[] {
188
- return this.configStruct.referencedTypes;
189
- }
190
-
191
- public get structsFolderName(): string {
192
- return `${path.basename(this.fileName, ".ts")}-structs`;
193
- }
194
-
195
- public get structsFolderPath(): string {
196
- return path.join(this.namespaceFolderPath, this.structsFolderName);
197
- }
198
-
199
- public get namespaceFolderPath(): string {
200
- return this.filePath.split("/").slice(0, -1).join("/");
201
- }
202
-
203
- private escapeSchema(schema: string): string {
204
- return schema.replace(/(\*\/)/gi, `*\\/`);
205
- }
206
- }
@@ -1,54 +0,0 @@
1
- // Copyright (c) HashiCorp, Inc
2
- // SPDX-License-Identifier: MPL-2.0
3
- export interface ScopeProps {
4
- readonly name: string;
5
- readonly isProvider: boolean;
6
- readonly isComputed?: boolean;
7
- readonly isOptional?: boolean;
8
- readonly isRequired?: boolean;
9
- readonly inBlockType?: boolean;
10
- readonly isNestedType?: boolean;
11
- readonly parent?: Scope;
12
- }
13
-
14
- export class Scope {
15
- public readonly name: string;
16
- public readonly provider?: string;
17
- public readonly parent?: Scope;
18
- public readonly isProvider: boolean;
19
- public isComputed: boolean;
20
- public isOptional: boolean;
21
- public isRequired: boolean;
22
- public inBlockType: boolean;
23
- public isNestedType: boolean;
24
-
25
- constructor(props: ScopeProps) {
26
- this.name = props.name;
27
- this.parent = props.parent;
28
- this.isProvider = props.isProvider;
29
- this.isComputed = props.isComputed ?? false;
30
- this.isOptional = props.isOptional ?? true;
31
- this.isRequired = props.isRequired ?? false;
32
- this.inBlockType = props.inBlockType ?? false;
33
- this.isNestedType = props.isNestedType ?? false;
34
- }
35
-
36
- public fullName(attributeName: string) {
37
- return `${this.baseName}.${attributeName}`;
38
- }
39
-
40
- public get baseName() {
41
- // eslint-disable-next-line @typescript-eslint/no-this-alias
42
- let scope: Scope | undefined = this;
43
- let name = "";
44
- while (scope) {
45
- if (name === "") {
46
- name = scope.name;
47
- } else {
48
- name = `${scope.name}.${name}`;
49
- }
50
- scope = scope.parent;
51
- }
52
- return name;
53
- }
54
- }
@@ -1,124 +0,0 @@
1
- // Copyright (c) HashiCorp, Inc
2
- // SPDX-License-Identifier: MPL-2.0
3
- import { AttributeModel } from "./attribute-model";
4
- import { downcaseFirst } from "../../../util";
5
- export class Struct {
6
- constructor(
7
- public readonly name: string,
8
- public readonly attributes: AttributeModel[],
9
- public readonly isClass = false,
10
- public readonly isAnonymous = false,
11
- public isSingleItem = false,
12
- public readonly nestingMode: string = "",
13
- ) {}
14
-
15
- public get assignableAttributes(): AttributeModel[] {
16
- return this.attributes.filter((attribute) => attribute.isAssignable);
17
- }
18
-
19
- public get optionalAttributes(): AttributeModel[] {
20
- return this.attributes.filter((attribute) => attribute.optional);
21
- }
22
-
23
- public get allOptional(): boolean {
24
- return (
25
- this.attributes.filter(
26
- (attribute) => !attribute.optional && !attribute.computed,
27
- ).length == 0
28
- );
29
- }
30
-
31
- public get attributeType() {
32
- return `${this.name}${this.allOptional ? " = {}" : ""}`;
33
- }
34
-
35
- public get assignable() {
36
- return !this.isClass || this.assignableAttributes.length > 0;
37
- }
38
-
39
- public get extends(): string {
40
- return "";
41
- }
42
-
43
- public get mapperName(): string {
44
- return `${downcaseFirst(this.name)}ToTerraform`;
45
- }
46
-
47
- public get hclMapperName(): string {
48
- return `${downcaseFirst(this.name)}ToHclTerraform`;
49
- }
50
-
51
- public get outputReferenceName(): string {
52
- return `${this.name}OutputReference`;
53
- }
54
-
55
- public get listName(): string {
56
- return `${this.name}List`;
57
- }
58
-
59
- public get mapName(): string {
60
- return `${this.name}Map`;
61
- }
62
-
63
- public get mapListName(): string {
64
- return `${this.name}MapList`;
65
- }
66
-
67
- public get listMapName(): string {
68
- return `${this.name}ListMap`;
69
- }
70
-
71
- public get listListName(): string {
72
- return `${this.name}ListList`;
73
- }
74
-
75
- public get isProvider(): boolean {
76
- return this.attributes.some((att) => att.isProvider);
77
- }
78
-
79
- public get referencedTypes(): string[] {
80
- const types: string[] = [];
81
-
82
- this.attributes.forEach((att) => {
83
- const attReferences = att.getReferencedTypes(false); // This may be a config struct, but still need the references in this context
84
- if (attReferences) {
85
- types.push(...attReferences);
86
- }
87
- });
88
-
89
- return types;
90
- }
91
-
92
- public get exportCount(): number {
93
- let count = 1; // self
94
- count += 1; // toTerraform function
95
-
96
- if (
97
- this.nestingMode === "list" ||
98
- this.nestingMode === "set" ||
99
- this.nestingMode === "map"
100
- ) {
101
- count += 1; // output reference
102
-
103
- if (!this.isSingleItem) {
104
- count += 1; // complex collection
105
- }
106
- }
107
-
108
- return count;
109
- }
110
- }
111
-
112
- export class ConfigStruct extends Struct {
113
- constructor(
114
- name: string,
115
- attributes: AttributeModel[],
116
- private readonly extendsClass: string = "TerraformMetaArguments",
117
- ) {
118
- super(name, attributes);
119
- }
120
-
121
- public get extends(): string {
122
- return ` extends cdktn.${this.extendsClass}`;
123
- }
124
- }
@@ -1,88 +0,0 @@
1
- // Copyright (c) HashiCorp, Inc
2
- // SPDX-License-Identifier: MPL-2.0
3
- import { uppercaseFirst } from "../../../util";
4
-
5
- // The core cdktn package (packages/cdktn/src/complex-computed-list.ts) only hand-writes
6
- // this fixed set of wrapper classes for computed, non-complex collection attributes.
7
- // Arbitrarily deep nestings of list/set/map (e.g. map(map(list(string)))) compose a
8
- // storedClassType (e.g. "stringListMapMap") that has no corresponding class. Rather than
9
- // falling back straight to a plain, untyped getter, resolveStoredClassName below first
10
- // looks for the nearest typed "Any"-wrapper that still exists in this set, collapsing the
11
- // unsupported inner shape into an untyped boundary while preserving typed navigation for
12
- // the outer layers (see https://github.com/open-constructs/cdk-terrain/issues/11).
13
- const SUPPORTED_STORED_CLASSES = new Set([
14
- "StringMap",
15
- "NumberMap",
16
- "BooleanMap",
17
- "AnyMap",
18
- "StringMapMap",
19
- "NumberMapMap",
20
- "BooleanMapMap",
21
- "AnyMapMap",
22
- "BooleanList",
23
- "StringListList",
24
- "NumberListList",
25
- "BooleanListList",
26
- "AnyListList",
27
- "StringMapList",
28
- "NumberMapList",
29
- "BooleanMapList",
30
- "AnyMapList",
31
- "StringListMap",
32
- "NumberListMap",
33
- "BooleanListMap",
34
- "AnyListMap",
35
- ]);
36
-
37
- // Resolves the composed stored class name to use for a collection attribute (list/set/map)
38
- // whose element is itself a non-complex collection (or simple type).
39
- //
40
- // `ownStoredClassType` is this type's own composed storedClassType (e.g. "stringListMapMap"
41
- // for map(map(list(string)))) and `elementTypeModelType` is the element's typeModelType
42
- // ("list" | "set" | "map" | "simple" | ...).
43
- //
44
- // Resolution order:
45
- // 1. The own composed name (e.g. "StringListMapMap") - used as-is when it refers to a
46
- // class that is hand-written in the core package (not collapsed).
47
- // 2. Otherwise, the nearest typed "Any"-wrapper that still encodes the outer two layers
48
- // (this type's own layer and its element's layer), e.g. "AnyMapMap" - collapsing the
49
- // unsupported inner shape into an untyped boundary while preserving typed navigation
50
- // for the outer layers.
51
- // 3. Otherwise (defensively; every depth should resolve via 1 or 2), undefined - the
52
- // caller must fall back to a plain, untyped getter.
53
- export function resolveStoredClassName(
54
- ownStoredClassType: string,
55
- elementTypeModelType: string,
56
- ): { name: string; collapsed: boolean } | undefined {
57
- const candidate1 = uppercaseFirst(ownStoredClassType);
58
- if (SUPPORTED_STORED_CLASSES.has(candidate1)) {
59
- return { name: candidate1, collapsed: false };
60
- }
61
-
62
- let ownLayer: "List" | "Map" | undefined;
63
- if (ownStoredClassType.endsWith("List")) {
64
- ownLayer = "List";
65
- } else if (ownStoredClassType.endsWith("Map")) {
66
- ownLayer = "Map";
67
- }
68
- if (!ownLayer) {
69
- return undefined;
70
- }
71
-
72
- let innerLayer: "List" | "Map" | undefined;
73
- if (elementTypeModelType === "list" || elementTypeModelType === "set") {
74
- innerLayer = "List";
75
- } else if (elementTypeModelType === "map") {
76
- innerLayer = "Map";
77
- }
78
- if (!innerLayer) {
79
- return undefined;
80
- }
81
-
82
- const candidate2 = `Any${innerLayer}${ownLayer}`;
83
- if (SUPPORTED_STORED_CLASSES.has(candidate2)) {
84
- return { name: candidate2, collapsed: true };
85
- }
86
-
87
- return undefined;
88
- }
@@ -1,236 +0,0 @@
1
- // Copyright (c) HashiCorp, Inc
2
- // SPDX-License-Identifier: MPL-2.0
3
- import { CodeMaker, toCamelCase } from "codemaker";
4
- import { AttributeModel } from "./models";
5
- import { sanitizedComment } from "./sanitized-comments";
6
- import {
7
- ConstructsMakerModuleTarget,
8
- TerraformTargetVersions,
9
- registryForTargetVersions,
10
- } from "@cdktn/commons";
11
-
12
- export class ModuleGenerator {
13
- constructor(
14
- private readonly code: CodeMaker,
15
- private readonly targets: ConstructsMakerModuleTarget[],
16
- private readonly targetVersions?: TerraformTargetVersions,
17
- ) {
18
- this.code.indentation = 2;
19
-
20
- for (const target of this.targets) {
21
- this.emitSubmodule(target);
22
- }
23
- }
24
-
25
- private emitSubmodule(target: ConstructsMakerModuleTarget) {
26
- const spec = target.spec;
27
-
28
- if (!spec) {
29
- throw new Error(`missing spec for ${target.fqn}`);
30
- }
31
-
32
- this.code.openFile(target.fileName);
33
-
34
- this.code.line(`// generated by cdktn get`);
35
- this.code.line(`// ${target.source}`);
36
-
37
- this.code.line(
38
- `import { TerraformModule, type TerraformModuleUserConfig } from 'cdktn';`,
39
- );
40
- this.code.line(`import { Construct } from 'constructs';`);
41
-
42
- const baseName = this.code.toPascalCase(target.name.replace(/[-/.]/g, "_"));
43
- const configType = `${baseName}Config`;
44
-
45
- this.code.openBlock(
46
- `export interface ${configType} extends TerraformModuleUserConfig`,
47
- );
48
- for (const input of spec.inputs) {
49
- const optional = input.required && input.default === undefined ? "" : "?";
50
-
51
- const comment = sanitizedComment(this.code);
52
- if (input.description) {
53
- comment.line(input.description);
54
- }
55
- if (input.default) {
56
- comment.line(input.default);
57
- }
58
- if (input.type.includes("map(")) {
59
- comment.line(
60
- `The property type contains a map, they have special handling, please see {@link cdk.tf/module-map-inputs the docs}`,
61
- );
62
- }
63
- comment.end();
64
-
65
- this.code.line(
66
- `readonly ${AttributeModel.escapeName(
67
- toCamelCase(input.name),
68
- )}${optional}: ${parseType(input.type)};`,
69
- );
70
- }
71
- this.code.closeBlock();
72
-
73
- // Add a link to the Terraform Registry if it is sourced from there
74
- // https://developer.hashicorp.com/terraform/language/modules/sources
75
- // Registry modules are referred to as <NAMESPACE>/<NAME>/<PROVIDER>
76
- // Other sources contain dots, e.g.
77
- // app.terraform.io/example-corp/k8s-cluster/azurerm (private registries)
78
- // github.com/hashicorp/example (Github)
79
- // git@github.com:hashicorp/example.git
80
- // bitbucket.org/hashicorp/terraform-consul-aws (Bitbucket)
81
- // ... and more
82
- // ../module and ./module (local paths)
83
- const isNonRegistryModule = target.source.includes(".");
84
- // Keyed off the project's declared targets rather than a fixed registry, so
85
- // the link matches the product the project builds for.
86
- const registry = registryForTargetVersions(this.targetVersions);
87
- // Registries only have pages for a direct child of `modules/`, e.g.
88
- // terraform-aws-modules/vpc/aws//modules/vpc-endpoints; any other `//` path
89
- // links to the module itself.
90
- const [moduleSource, subPath] = target.source.split("//", 2);
91
- const submodule = subPath?.match(/^modules\/([^/]+)$/)?.[1];
92
- const docsUrl = registry.moduleDocsUrl(
93
- moduleSource,
94
- target.version,
95
- submodule,
96
- );
97
-
98
- const comment = sanitizedComment(this.code);
99
- comment.line(`Defines an ${baseName} based on a Terraform module`);
100
- comment.line(``);
101
- comment.line(
102
- isNonRegistryModule
103
- ? `Source at ${target.source}`
104
- : `Docs at ${registry.displayName}: {@link ${docsUrl} ${target.source}}`,
105
- );
106
- comment.end();
107
- this.code.openBlock(`export class ${baseName} extends TerraformModule`);
108
-
109
- this.code.line(`private readonly inputs: { [name: string]: any } = { };`);
110
-
111
- const allOptional = spec.inputs.find((x) => x.required) ? "" : " = {}";
112
-
113
- this.code.open(
114
- `public constructor(scope: Construct, id: string, config: ${configType}${allOptional}) {`,
115
- );
116
- this.code.open(`super(scope, id, {`);
117
- this.code.line("...config,");
118
- this.code.line(`source: '${target.source}',`);
119
- if (target.version) {
120
- this.code.line(`version: '${target.version}',`);
121
- }
122
- this.code.close(`});`);
123
-
124
- for (const input of spec.inputs) {
125
- const inputName = AttributeModel.escapeName(toCamelCase(input.name));
126
- this.code.line(`this.${inputName} = config.${inputName};`);
127
- }
128
-
129
- this.code.close(`}`); // ctor
130
-
131
- for (const input of spec.inputs) {
132
- const inputName = AttributeModel.escapeName(toCamelCase(input.name));
133
- const inputType =
134
- parseType(input.type) +
135
- (input.required && input.default === undefined ? "" : " | undefined");
136
- this.code.openBlock(`public get ${inputName}(): ${inputType}`);
137
- this.code.line(`return this.inputs['${input.name}'] as ${inputType};`);
138
- this.code.closeBlock();
139
-
140
- this.code.openBlock(`public set ${inputName}(value: ${inputType})`);
141
- this.code.line(`this.inputs['${input.name}'] = value;`);
142
- this.code.closeBlock();
143
- }
144
-
145
- for (const output of spec.outputs) {
146
- const outputName = toCamelCase(output.name);
147
- this.code.openBlock(`public get ${outputName}Output()`);
148
- this.code.line(`return this.getString('${output.name}');`);
149
- this.code.closeBlock();
150
- }
151
-
152
- this.code.openBlock(`protected synthesizeAttributes()`);
153
- this.code.line(`return this.inputs;`);
154
- this.code.closeBlock();
155
-
156
- this.code.openBlock(
157
- `protected synthesizeHclAttributes(): { [name: string]: any }`,
158
- );
159
- this.code.line(`return Object.fromEntries(`);
160
- this.code.line(` Object.entries(this.inputs)`);
161
- this.code.line(` .filter(([, val]) => val !== undefined)`);
162
- this.code.line(` .map(([key, val]) => {`);
163
- this.code.line(` return [`);
164
- this.code.line(` key,`);
165
- this.code.line(` {`);
166
- this.code.line(` value: val,`);
167
- this.code.line(` type: "any",`);
168
- this.code.line(` },`);
169
- this.code.line(` ];`);
170
- this.code.line(` })`);
171
- this.code.line(`);`);
172
- this.code.closeBlock();
173
-
174
- this.code.closeBlock(); // class
175
- this.code.closeFile(target.fileName);
176
- }
177
- }
178
-
179
- function parseType(type: string) {
180
- if (type === "string") {
181
- return "string";
182
- }
183
- if (type === "number") {
184
- return "number";
185
- }
186
- if (type === "bool") {
187
- return "boolean";
188
- }
189
- if (type === "list") {
190
- return "string[]";
191
- }
192
- if (type === "map") {
193
- return "{ [key: string]: string }";
194
- }
195
- if (type === "tuple") {
196
- return "string[]";
197
- }
198
- if (type === "any") {
199
- return "any";
200
- }
201
-
202
- const complexType = parseComplexType(type);
203
- if (complexType) {
204
- return complexType;
205
- }
206
-
207
- throw new Error(`unknown type ${type}`);
208
- }
209
-
210
- function parseComplexType(type: string): string | undefined {
211
- const complex = /^(object|list|map|set|tuple)\(([\s\S]+)\)/;
212
- const match = complex.exec(type);
213
- if (!match) {
214
- return undefined;
215
- }
216
-
217
- const [, kind, innerType] = match;
218
-
219
- if (kind === "object") {
220
- return `any`;
221
- }
222
-
223
- if (kind === "list" || kind === "set") {
224
- return `${parseType(innerType)}[]`;
225
- }
226
-
227
- if (kind === "tuple") {
228
- return `any[]`;
229
- }
230
-
231
- if (kind === "map") {
232
- return `{ [key: string]: ${parseType(innerType)} }`;
233
- }
234
-
235
- throw new Error(`unexpected kind ${kind}`);
236
- }