Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/@aws-cdk/custom-resource-handlers/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@
"@types/jest": "^29.5.14",
"aws-sdk-client-mock": "4.1.0",
"aws-sdk-client-mock-jest": "4.1.0",
"@cdklabs/typewriter": "^0.0.5",
"@cdklabs/typewriter": "^0.0.6",
"jest": "^29.7.0",
"sinon": "^9.2.4",
"nock": "^13.5.6",
Expand Down
46 changes: 45 additions & 1 deletion packages/aws-cdk-lib/aws-dynamodb/test/dynamodb.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import * as iam from '../../aws-iam';
import * as kinesis from '../../aws-kinesis';
import * as kms from '../../aws-kms';
import * as s3 from '../../aws-s3';
import { App, Aws, CfnDeletionPolicy, Duration, PhysicalName, RemovalPolicy, Resource, Stack, Tags } from '../../core';
import { App, ArnFormat, Aws, CfnDeletionPolicy, Duration, PhysicalName, RemovalPolicy, Resource, Stack, Tags } from '../../core';
import * as cr from '../../custom-resources';
import * as cxapi from '../../cx-api';
import {
Expand Down Expand Up @@ -397,6 +397,50 @@ describe('default properties', () => {
});
});

describe('L1 static factory methods', () => {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Choosing one representative to test that the generated methods actually return the right thing.

test('fromTableArn', () => {
const stack = new Stack();
const table = CfnTable.fromTableArn(stack, 'MyBucket', 'arn:aws:dynamodb:eu-west-1:123456789012:table/MyTable');
expect(table.tableRef.tableName).toEqual('MyTable');
expect(table.tableRef.tableArn).toEqual('arn:aws:dynamodb:eu-west-1:123456789012:table/MyTable');

const env = stack.resolve((table as unknown as Resource).env);
expect(env).toEqual({
region: 'eu-west-1',
account: '123456789012',
});
});

test('fromTableName', () => {
const app = new App();
const stack = new Stack(app, 'MyStack', {
env: { account: '23432424', region: 'us-east-1' },
});

const table = CfnTable.fromTableName(stack, 'Table', 'MyTable');
const arnComponents = stack.splitArn(table.tableRef.tableArn, ArnFormat.SLASH_RESOURCE_NAME);

expect(table.tableRef.tableName).toEqual('MyTable');
expect(arnComponents).toMatchObject({
account: '23432424',
region: 'us-east-1',
resource: 'table',
resourceName: 'MyTable',
service: 'dynamodb',
});

expect(stack.resolve(arnComponents.partition)).toEqual({
Ref: 'AWS::Partition',
});

const env = stack.resolve((table as unknown as Resource).env);
expect(env).toEqual({
region: 'us-east-1',
account: '23432424',
});
});
});

testDeprecated('when specifying every property', () => {
const stack = new Stack();
const stream = new kinesis.Stream(stack, 'MyStream');
Expand Down
1 change: 1 addition & 0 deletions packages/aws-cdk-lib/core/lib/helpers-internal/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ export { md5hash } from '../private/md5';
export * from './customize-roles';
export * from './string-specializer';
export * from './validate-all-props';
export * from './strings';
export { constructInfoFromConstruct, constructInfoFromStack } from '../private/runtime-info';
71 changes: 71 additions & 0 deletions packages/aws-cdk-lib/core/lib/helpers-internal/strings.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { UnscopedValidationError } from '../errors';

/**
* A string with variables in the form `${name}`.
*/
export class TemplateString {
constructor(private readonly template: string) {
}

/**
* Parses a template string with variables in the form of `${var}` and extracts the values from the input string.
* Returns a record mapping variable names to their corresponding values.
* @param input the input string to parse
* @throws UnscopedValidationError if the input does not match the template
*/
public parse(input: string): Record<string, string> {
const templateParts = this.template.split(/(\$\{[^{}]+})/);
const result: Record<string, string> = {};

let inputIndex = 0;

for (let i = 0; i < templateParts.length; i++) {
const part = templateParts[i];
if (part.startsWith('${') && part.endsWith('}')) {
const varName = part.slice(2, -1);
const nextLiteral = templateParts[i + 1] || '';

let value = '';
if (nextLiteral) {
const endIndex = input.indexOf(nextLiteral, inputIndex);
if (endIndex === -1) {
throw new UnscopedValidationError(`Input ${input} does not match template ${this.template}`);
}
value = input.slice(inputIndex, endIndex);
inputIndex = endIndex;
} else {
value = input.slice(inputIndex);
inputIndex = input.length;
}

result[varName] = value;
} else {
if (input.slice(inputIndex, inputIndex + part.length) !== part) {
throw new UnscopedValidationError(`Input ${input} does not match template ${this.template}`);
}
inputIndex += part.length;
}
}

if (inputIndex !== input.length) {
throw new UnscopedValidationError(`Input ${input} does not match template ${this.template}`);
}

return result;
}

/**
* Returns the template interpolated with the attributes of an object passed as input.
* Attributes that don't match any variable in the template are ignored, but all template
* variables must be replaced.
* @param variables an object where keys are the variable names, and values are the values to be replaced.
*/
public interpolate(variables: Record<string, string>): string {
return this.template.replace(/\${([^{}]+)}/g, (_, varName) => {
if (variables[varName] === undefined) {
throw new UnscopedValidationError(`Variable ${varName} not provided for template interpolation`);
}
return variables[varName];
});
}
}
117 changes: 117 additions & 0 deletions packages/aws-cdk-lib/core/test/helpers-internal/strings.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import { UnscopedValidationError } from '../../lib';
import { TemplateString } from '../../lib/helpers-internal';

describe('new TemplateString', () => {
describe('parse', () => {
it('parses template with single variable correctly', () => {
const result = new TemplateString('Hello, ${name}!').parse('Hello, John!');
expect(result).toEqual({ name: 'John' });
});

it('parses template with multiple variables correctly', () => {
const result = new TemplateString('My name is ${firstName} ${lastName}.').parse('My name is Jane Doe.');
expect(result).toEqual({ firstName: 'Jane', lastName: 'Doe' });
});

it('throws error when input does not match template', () => {
expect(() => {
new TemplateString('Hello, ${name}!').parse('Hi, John!');
}).toThrow(UnscopedValidationError);
});

it('parses template with no variables correctly', () => {
const result = new TemplateString('Hello, world!').parse('Hello, world!');
expect(result).toEqual({});
});

it('parses template with trailing variable correctly', () => {
const result = new TemplateString('Path: ${path}').parse('Path: /home/user');
expect(result).toEqual({ path: '/home/user' });
});

it('throws error when input has extra characters', () => {
expect(() => {
new TemplateString('Hello, ${name}!').parse('Hello, John!!');
}).toThrow(UnscopedValidationError);
});

it('parses template with adjacent variables correctly', () => {
const result = new TemplateString('${greeting}, ${name}!').parse('Hi, John!');
expect(result).toEqual({ greeting: 'Hi', name: 'John' });
});

it('throws error when input is shorter than template', () => {
expect(() => {
new TemplateString('Hello, ${name}!').parse('Hello, ');
}).toThrow(UnscopedValidationError);
});

it('parses template with empty variable value correctly', () => {
const result = new TemplateString('Hello, ${name}!').parse('Hello, !');
expect(result).toEqual({ name: '' });
});

it('parses template with variable at the start correctly', () => {
const result = new TemplateString('${greeting}, world!').parse('Hi, world!');
expect(result).toEqual({ greeting: 'Hi' });
});

it('parses complex template correctly', () => {
const result = new TemplateString('arn:${Partition}:dynamodb:${Region}:${Account}:table/${TableName}')
.parse('arn:aws:dynamodb:us-east-1:12345:table/MyTable');
expect(result).toEqual({
Partition: 'aws',
Region: 'us-east-1',
Account: '12345',
TableName: 'MyTable',
});
});
});

describe('interpolate', () => {
it('interpolates template with single variable correctly', () => {
const result = new TemplateString('Hello, ${name}!').interpolate({ name: 'John' });
expect(result).toBe('Hello, John!');
});

it('interpolates template with multiple variables correctly', () => {
const result = new TemplateString('My name is ${firstName} ${lastName}.').interpolate({
firstName: 'Jane',
lastName: 'Doe',
});
expect(result).toBe('My name is Jane Doe.');
});

it('throws error when variable is missing in interpolation', () => {
expect(() => {
new TemplateString('Hello, ${name}!').interpolate({});
}).toThrow(UnscopedValidationError);
});

it('interpolates template with no variables correctly', () => {
const result = new TemplateString('Hello, world!').interpolate({});
expect(result).toBe('Hello, world!');
});

it('throws error when template contains undefined variable', () => {
expect(() => {
new TemplateString('Hello, ${name}!').interpolate({ greeting: 'Hi' });
}).toThrow(UnscopedValidationError);
});

it('interpolates template with adjacent variables correctly', () => {
const result = new TemplateString('${greeting}, ${name}!').interpolate({ greeting: 'Hi', name: 'John' });
expect(result).toBe('Hi, John!');
});

it('interpolates template with empty variable value correctly', () => {
const result = new TemplateString('Hello, ${name}!').interpolate({ name: '' });
expect(result).toBe('Hello, !');
});

it('interpolates template with variable at the start correctly', () => {
const result = new TemplateString('${greeting}, world!').interpolate({ greeting: 'Hi' });
expect(result).toBe('Hi, world!');
});
});
});
2 changes: 2 additions & 0 deletions tools/@aws-cdk/spec2cdk/lib/cdk/cdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export class CdkCore extends ExternalModule {
public readonly ITaggable = Type.fromName(this, 'ITaggable');
public readonly ITaggableV2 = Type.fromName(this, 'ITaggableV2');
public readonly IResolvable = Type.fromName(this, 'IResolvable');
public readonly Stack = Type.fromName(this, 'Stack');

public readonly objectToCloudFormation = makeCallableExpr(this, 'objectToCloudFormation');
public readonly stringToCloudFormation = makeCallableExpr(this, 'stringToCloudFormation');
Expand Down Expand Up @@ -93,6 +94,7 @@ export class CdkInternalHelpers extends ExternalModule {
public readonly FromCloudFormationResult = $T(Type.fromName(this, 'FromCloudFormationResult'));
public readonly FromCloudFormation = $T(Type.fromName(this, 'FromCloudFormation'));
public readonly FromCloudFormationPropertyObject = Type.fromName(this, 'FromCloudFormationPropertyObject');
public readonly TemplateString = Type.fromName(this, 'TemplateString');

constructor(parent: CdkCore) {
super(`${parent.fqn}/core/lib/helpers-internal`);
Expand Down
Loading
Loading