Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
34 changes: 33 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,38 @@ 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');
});

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',
});
});
});

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';
63 changes: 63 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,63 @@
import { UnscopedValidationError } from '../errors';

/**
* Utility class for parsing template strings with variables.
*/
export class TemplateStringParser {
/**
* 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 template the template string containing variables
* @param input the input string to parse
* @throws UnscopedValidationError if the input does not match the template
*/
public static parse(template: string, input: string): Record<string, string> {
const templateParts = 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 ${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 ${template}`);
}
inputIndex += part.length;
}
}

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

return result;
}

public static interpolate(template: string, variables: Record<string, string>): string {
return template.replace(/\${([^{}]+)}/g, (_, varName) => {
if (variables[varName] === undefined) {
throw new UnscopedValidationError(`Variable ${varName} not provided for template interpolation`);
}
return variables[varName];
});
}
}
106 changes: 106 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,106 @@
import { UnscopedValidationError } from '../../lib';
import { TemplateStringParser } from '../../lib/helpers-internal/strings';

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

it('interpolates template with variable at the start correctly', () => {
const result = TemplateStringParser.interpolate('${greeting}, world!', { 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 TemplateStringParser = Type.fromName(this, 'TemplateStringParser');

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