use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Write;
use crucible_codegen_infra::{Plan, Property};
use crucible_ir::{
Diagnostics, ShapeId,
ir::{Constraints, Service, Shape, SimpleKind, TimestampFormat},
};
use serde_json::{Value, json};
pub fn emit(service: &Service, plan: &Plan, diagnostics: &mut Diagnostics) -> String {
let mut output = String::from(
"// Generated by crucible. Do not edit.\nimport { CfnResource, IResolvable } from 'aws-cdk-lib';\nimport { Construct } from 'constructs';\nimport { toWire, validate } from './validation';\n\n",
);
let mut reachable = BTreeSet::new();
let mut names = BTreeMap::new();
if !plan.resources.iter().any(|resource| resource.cdk.is_some()) {
diagnostics.push(&service.id, "provisioning bindings select no CDK resources");
}
for resource in &plan.resources {
let Some(cdk) = &resource.cdk else {
continue;
};
let class = cdk
.class_name
.clone()
.unwrap_or_else(|| format!("Cfn{}", resource.name));
register(&class, &resource.id, &mut names, diagnostics);
if !cdk.resource_type.starts_with("Custom::")
|| cdk.resource_type.len() > 60
|| cdk.resource_type.len() == 8
|| !cdk.resource_type[8.min(cdk.resource_type.len())..]
.chars()
.all(|c| c.is_ascii_alphanumeric() || "_@-".contains(c))
{
diagnostics.push(
&resource.id,
"CDK resource_type must be a Custom:: resource name of at most 60 characters",
);
}
register(
&format!("{class}Props"),
&resource.id,
&mut names,
diagnostics,
);
for property in resource.properties.values().chain(cdk.context.values()) {
visit(service, &property.target, &mut reachable, diagnostics);
}
for (name, attribute) in &resource.attributes {
if !matches!(service.shape(&attribute.target), Some(Shape::Simple(s)) if matches!(s.kind, SimpleKind::String | SimpleKind::Timestamp))
&& !matches!(service.shape(&attribute.target), Some(Shape::Enum(_)))
&& prelude_kind(&attribute.target) != Some("string")
{
diagnostics.push(&resource.id, format!("CDK attribute `{name}` must target a string; other attribute representations are not supported"));
}
}
}
for id in &reachable {
if let Some(Shape::Structure(shape)) = service.shape(id) {
let name = format!("{}Property", service.name_of(id));
register(&name, id, &mut names, diagnostics);
docs(&mut output, shape.docs.as_deref(), "", Some("@struct"));
writeln!(output, "export interface {name} {{").unwrap();
let mut member_names = BTreeSet::new();
for member in &shape.members {
let member_name = &public_name(&member.name);
check_member(member_name, id, diagnostics);
if !member_names.insert(member_name.clone()) {
diagnostics.push(
id,
format!("CDK member `{}` collides at `{member_name}`", member.name),
);
}
docs(&mut output, member.docs.as_deref(), " ", None);
writeln!(
output,
" readonly {member_name}{}: {};",
if member.optional_on_server() { "?" } else { "" },
member_type(service, member, &mut BTreeSet::new())
)
.unwrap();
}
output.push_str("}\n\n");
}
}
let mut schemas = BTreeMap::new();
for id in &reachable {
schemas.insert(id.to_string(), shape_schema(service, id));
}
writeln!(
output,
"const schemas = {};\n",
crucible_codegen_common::source_json(&serde_json::to_string(&schemas).unwrap())
)
.unwrap();
for resource in &plan.resources {
let Some(cdk) = &resource.cdk else {
continue;
};
let class = cdk
.class_name
.clone()
.unwrap_or_else(|| format!("Cfn{}", resource.name));
let properties: BTreeMap<_, _> = resource
.properties
.iter()
.chain(cdk.context.iter())
.collect();
let mut property_names = BTreeSet::from(["serviceToken".to_owned()]);
writeln!(output, "/** @struct */\nexport interface {class}Props {{\n /** ARN of the provider implementing this resource contract. */\n readonly serviceToken: string;").unwrap();
for (name, property) in &properties {
let public = public_name(name);
check_member(&public, &resource.id, diagnostics);
if !property_names.insert(public.clone()) || *name == "ServiceToken" {
diagnostics.push(
&resource.id,
format!("CDK property `{name}` collides with another property or ServiceToken"),
);
}
docs(
&mut output,
property.docs.as_deref(),
" ",
if property.immutable {
Some("Changing this value requires provider-defined replacement.")
} else {
None
},
);
writeln!(
output,
" readonly {public}{}: {};",
if property.required { "" } else { "?" },
property
.timestamp_format
.map(timestamp_type)
.map(str::to_owned)
.unwrap_or_else(|| type_of(service, &property.target, &mut BTreeSet::new()))
)
.unwrap();
}
writeln!(output, "}}\n\nexport class {class} extends CfnResource {{").unwrap();
writeln!(
output,
" public static readonly CFN_RESOURCE_TYPE_NAME: string = {};",
quote(&cdk.resource_type)
)
.unwrap();
let mut attributes = BTreeSet::new();
for name in resource.attributes.keys() {
let attr = format!("attr{}", upper_first(&public_name(name)));
check_member(&attr, &resource.id, diagnostics);
if !attributes.insert(attr.clone()) {
diagnostics.push(&resource.id, format!("CDK attributes collide at `{attr}`"));
}
if upper_first(&attr) == class {
diagnostics.push(
&resource.id,
format!("CDK attribute `{attr}` collides with its enclosing class in .NET"),
);
}
writeln!(output, " public readonly {attr}: string;").unwrap();
}
writeln!(output, "\n public constructor(scope: Construct, id: string, props: {class}Props) {{\n super(scope, id, {{\n type: {},\n properties: {{\n ServiceToken: props.serviceToken,", quote(&cdk.resource_type)).unwrap();
for (name, property) in &properties {
writeln!(
output,
" {}: toWire(props.{}, {}, schemas),",
quote(name),
public_name(name),
quote(&property.target.to_string())
)
.unwrap();
}
output.push_str(" },\n });\n validate(props.serviceToken, { kind: 'string' }, schemas, 'serviceToken', true);\n");
for (name, property) in &properties {
writeln!(
output,
" validate(props.{}, {}, schemas, {}, {});",
public_name(name),
crucible_codegen_common::source_json(
&property_schema(service, property).to_string()
),
quote(&public_name(name)),
property.required
)
.unwrap();
}
for name in resource.attributes.keys() {
writeln!(
output,
" this.attr{} = this.getAttString({});",
upper_first(&public_name(name)),
quote(name)
)
.unwrap();
}
output.push_str(" }\n\n /** A deployment-time string attribute returned by the provider. */\n public getAttString(attributeName: string): string {\n return this.getAtt(attributeName).toString();\n }\n}\n\n");
}
if output.matches("IResolvable").count() == 1 {
output = output.replace("CfnResource, IResolvable", "CfnResource");
}
output.truncate(output.trim_end().len());
output.push('\n');
output
}
fn public_name(name: &str) -> String {
let mut parts = name.split('_').filter(|part| !part.is_empty());
let mut result = String::new();
if let Some(first) = parts.next() {
let mut chars = first.chars();
if let Some(c) = chars.next() {
result.extend(c.to_lowercase());
result.extend(chars);
}
}
for part in parts {
let part = if part.chars().all(|c| !c.is_lowercase()) {
part.to_lowercase()
} else {
part.to_owned()
};
result.push_str(&upper_first(&part));
}
result
}
fn upper_first(name: &str) -> String {
let mut chars = name.chars();
match chars.next() {
Some(first) => first.to_uppercase().chain(chars).collect(),
None => String::new(),
}
}
fn identifier(name: &str) -> bool {
!name.is_empty()
&& name
.chars()
.enumerate()
.all(|(i, c)| c.is_ascii_alphabetic() || c == '_' || (i > 0 && c.is_ascii_digit()))
}
fn check_member(name: &str, id: &ShapeId, diagnostics: &mut Diagnostics) {
if !identifier(name) || ["constructor", "prototype", "__proto__"].contains(&name) {
diagnostics.push(id, format!("`{name}` is not a supported CDK member name"));
}
}
fn register(
name: &str,
id: &ShapeId,
names: &mut BTreeMap<String, ShapeId>,
diagnostics: &mut Diagnostics,
) {
if !identifier(name)
|| !name.starts_with(char::is_uppercase)
|| ["CfnResource", "IResolvable", "Construct"].contains(&name)
{
diagnostics.push(id, format!("`{name}` is not a supported CDK type name"));
}
if names.insert(name.into(), id.clone()).is_some() {
diagnostics.push(id, format!("duplicate CDK type name `{name}`"));
}
}
fn docs(output: &mut String, text: Option<&str>, indent: &str, extra: Option<&str>) {
if text.is_none() && extra.is_none() {
return;
}
writeln!(output, "{indent}/**").unwrap();
let text = crucible_codegen_common::docs::comment_text(text.unwrap_or_default());
for line in text.lines() {
writeln!(
output,
"{indent} * {}",
line.replace("*/", "* /").replace('@', "@")
)
.unwrap();
}
if let Some(extra) = extra {
writeln!(output, "{indent} * {extra}").unwrap();
}
writeln!(output, "{indent} */").unwrap();
}
fn quote(value: &str) -> String {
crucible_codegen_common::quoted(value)
}
fn visit(
service: &Service,
id: &ShapeId,
seen: &mut BTreeSet<ShapeId>,
diagnostics: &mut Diagnostics,
) {
if !seen.insert(id.clone()) {
return;
}
if collection_cycle(service, id, &mut BTreeSet::new()) {
diagnostics.push(
id,
"recursive collection aliases are not supported by the CDK jsii type system",
);
}
match service.shape(id) {
None if prelude_kind(id).is_some() => {},
Some(Shape::Simple(simple)) if matches!(simple.kind, SimpleKind::Document | SimpleKind::Blob) => diagnostics.push(id, "CDK properties do not yet support document or blob targets; use an explicit string representation in the provisioning model"),
Some(Shape::Simple(_)) | Some(Shape::Enum(_)) => {},
Some(Shape::Structure(s)) => for member in &s.members { visit(service, &member.target, seen, diagnostics); },
Some(Shape::List(s)) => { if s.sparse { diagnostics.push(id,"CDK sparse lists are not supported"); } visit(service, &s.member.target, seen, diagnostics); },
Some(Shape::Map(s)) => { if s.sparse { diagnostics.push(id,"CDK sparse maps are not supported"); } visit(service, &s.key.target, seen, diagnostics); visit(service, &s.value.target, seen, diagnostics); },
_ => diagnostics.push(id, "unsupported CDK property target (union, unit or missing shape)"),
}
}
fn collection_cycle(service: &Service, id: &ShapeId, chain: &mut BTreeSet<ShapeId>) -> bool {
let next = match service.shape(id) {
Some(Shape::List(list)) => &list.member.target,
Some(Shape::Map(map)) => &map.value.target,
_ => return false,
};
if !chain.insert(id.clone()) {
return true;
}
collection_cycle(service, next, chain)
}
fn type_of(service: &Service, id: &ShapeId, chain: &mut BTreeSet<ShapeId>) -> String {
if !chain.insert(id.clone()) {
return "IResolvable".into();
}
let result = match service.shape(id) {
None if prelude_kind(id).is_some() => match prelude_kind(id).unwrap() {
"boolean" => "boolean | IResolvable",
kind => kind,
}
.into(),
Some(Shape::Simple(s)) => match s.kind {
SimpleKind::String => "string",
SimpleKind::Boolean => "boolean | IResolvable",
SimpleKind::Timestamp => {
timestamp_type(s.timestamp_format.unwrap_or(TimestampFormat::DateTime))
}
_ => "number",
}
.into(),
Some(Shape::Enum(_)) => "string".into(),
Some(Shape::Structure(_)) => format!("{}Property | IResolvable", service.name_of(id)),
Some(Shape::List(s)) => format!(
"Array<{}> | IResolvable",
member_type(service, &s.member, chain)
),
Some(Shape::Map(s)) => format!(
"{{ [key: string]: {} }} | IResolvable",
member_type(service, &s.value, chain)
),
_ => "IResolvable".into(),
};
chain.remove(id);
result
}
fn constraints(value: &Constraints) -> Value {
json!({"minLength":value.length.as_ref().and_then(|b| b.min), "maxLength":value.length.as_ref().and_then(|b| b.max), "min":value.range.as_ref().and_then(|b| b.min.as_ref()), "max":value.range.as_ref().and_then(|b| b.max.as_ref()), "pattern":value.pattern, "unique":value.unique_items})
}
fn integer_range(service: &Service, id: &ShapeId) -> Option<[i64; 2]> {
let kind = match service.shape(id) {
Some(Shape::Simple(s)) => s.kind,
None if id.is_prelude() && id.name() == "Integer" => SimpleKind::Integer,
_ => return None,
};
match kind {
SimpleKind::Byte => Some([i8::MIN.into(), i8::MAX.into()]),
SimpleKind::Short => Some([i16::MIN.into(), i16::MAX.into()]),
SimpleKind::Integer => Some([i32::MIN.into(), i32::MAX.into()]),
_ => None,
}
}
fn property_schema(service: &Service, property: &Property) -> Value {
json!({"target": property.target.to_string(), "constraints":constraints(&property.constraints), "enumValues":property.enum_values, "integer":property.integer, "intRange":integer_range(service, &property.target), "timestamp":property.timestamp_format.map(timestamp_name)})
}
fn shape_schema(service: &Service, id: &ShapeId) -> Value {
match service.shape(id) {
None if prelude_kind(id).is_some() => {
json!({"kind":prelude_kind(id),"integer":matches!(id.name(),"Integer"|"Long"),"intRange":integer_range(service, id)})
}
Some(Shape::Simple(s)) => {
json!({"kind": match s.kind { SimpleKind::String => "string", SimpleKind::Boolean => "boolean", SimpleKind::Timestamp => "timestamp", _ => "number" }, "timestamp":if s.kind == SimpleKind::Timestamp {Some(timestamp_name(s.timestamp_format.unwrap_or(TimestampFormat::DateTime)))} else {None}, "integer":matches!(s.kind,SimpleKind::Byte|SimpleKind::Short|SimpleKind::Integer|SimpleKind::Long), "intRange":integer_range(service, id), "constraints":constraints(&s.constraints)})
}
Some(Shape::Enum(s)) => {
json!({"kind":"string", "enumValues":s.values.iter().map(|v| &v.value).collect::<Vec<_>>()})
}
Some(Shape::Structure(s)) => {
json!({"kind":"object", "members":s.members.iter().map(|m| (public_name(&m.name),member_schema(service,m))).collect::<BTreeMap<_,_>>()})
}
Some(Shape::List(s)) => {
json!({"kind":"array", "element":member_schema(service,&s.member), "constraints":constraints(&s.constraints)})
}
Some(Shape::Map(s)) => {
json!({"kind":"map", "key":member_schema(service,&s.key), "element":member_schema(service,&s.value), "constraints":constraints(&s.constraints)})
}
_ => json!({}),
}
}
fn timestamp_type(format: TimestampFormat) -> &'static str {
if format == TimestampFormat::EpochSeconds {
"number"
} else {
"string"
}
}
fn timestamp_name(format: TimestampFormat) -> &'static str {
match format {
TimestampFormat::EpochSeconds => "epoch-seconds",
TimestampFormat::DateTime => "date-time",
TimestampFormat::HttpDate => "http-date",
}
}
fn member_type(
service: &Service,
member: &crucible_ir::ir::Member,
chain: &mut BTreeSet<ShapeId>,
) -> String {
if matches!(service.shape(&member.target),Some(Shape::Simple(s)) if s.kind == SimpleKind::Timestamp)
{
timestamp_type(service.timestamp_format(member)).into()
} else {
type_of(service, &member.target, chain)
}
}
fn member_schema(service: &Service, member: &crucible_ir::ir::Member) -> Value {
json!({"wire":member.name, "target":member.target.to_string(), "required":!member.optional_on_server(), "constraints":constraints(&member.constraints), "timestamp":if matches!(service.shape(&member.target),Some(Shape::Simple(s)) if s.kind == SimpleKind::Timestamp) {Some(timestamp_name(service.timestamp_format(member)))} else {None}})
}
fn prelude_kind(id: &ShapeId) -> Option<&'static str> {
if !id.is_prelude() {
return None;
}
match id.name() {
"String" => Some("string"),
"Boolean" => Some("boolean"),
"Integer" | "Long" | "Double" => Some("number"),
_ => None,
}
}