Skip to content

Commit

Permalink
fix(rosetta): gets confused by type unions (#3156)
Browse files Browse the repository at this point in the history
Rosetta gets confused by type unions when it's trying to derive
the type of a struct.

This bites CDK as we're generating examples for L1s, and they all have
unions with `IResolvable` in all their properties.

If we can match a struct, let's do so.



---

By submitting this pull request, I confirm that my contribution is made under the terms of the [Apache 2.0 license].

[Apache 2.0 license]: https://www.apache.org/licenses/LICENSE-2.0
  • Loading branch information
rix0rrr committed Nov 11, 2021
1 parent 768ba07 commit ca04dad
Show file tree
Hide file tree
Showing 5 changed files with 59 additions and 4 deletions.
16 changes: 12 additions & 4 deletions packages/jsii-rosetta/lib/jsii/jsii-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,10 @@ export function determineJsiiType(typeChecker: ts.TypeChecker, type: ts.Type): J
}

if (type.isUnion() || type.isIntersection()) {
return { kind: 'error', message: 'Type unions or intersections are not supported in examples' };
return {
kind: 'error',
message: `Type unions or intersections are not supported in examples, got: ${typeChecker.typeToString(type)}`,
};
}
return { kind: 'unknown' };
}
Expand Down Expand Up @@ -94,10 +97,15 @@ export function analyzeObjectLiteral(
return isDeclaredCall ? { kind: 'map' } : { kind: 'unknown' };
}

const structType = analyzeStructType(type);
if (structType) {
return { kind: structType, type };
// If the type is a union between a struct and something else, return the first possible struct
const structCandidates = type.isUnion() ? type.types : [type];
for (const candidate of structCandidates) {
const structType = analyzeStructType(candidate);
if (structType) {
return { kind: structType, type: candidate };
}
}

return { kind: 'map' };
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
Takes(new MyProps {
Struct = new SomeStruct {
Enabled = false,
Option = "option"
}
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
takes(MyProps.builder()
.struct(SomeStruct.builder()
.enabled(false)
.option("option")
.build())
.build());
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
takes(
struct=SomeStruct(
enabled=False,
option="option"
)
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/// !hide
/// fake-from-jsii
interface IResolvable {
resolve(): any;
}

/// fake-from-jsii
interface SomeStruct {
readonly enabled: boolean | IResolvable;
readonly option?: string | IResolvable;
}

/// fake-from-jsii
interface MyProps {
readonly struct?: IResolvable | SomeStruct;
}

function takes(props: MyProps) {
}
/// !show

takes({
struct: {
enabled: false,
option: 'option',
},
});


0 comments on commit ca04dad

Please sign in to comment.