Skip to content

Commit

Permalink
fix: cannot have multiple assets in the same scope (#1016)
Browse files Browse the repository at this point in the history
Fixes #993
  • Loading branch information
mrgrain authored Dec 24, 2023
1 parent 8337d8e commit 6777ba2
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 2 deletions.
17 changes: 15 additions & 2 deletions src/source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,25 @@ import {
ISource,
SourceConfig,
} from 'aws-cdk-lib/aws-s3-deployment';
import { Construct } from 'constructs';
import { Construct, IConstruct } from 'constructs';
import { TypeScriptAsset, TypeScriptAssetProps } from './asset';
import { EntryPoints } from './bundler';
import { TypeScriptCodeProps } from './code';
import { BuildOptions } from './esbuild-types';

const assetIds = new WeakMap<IConstruct, number>();
const assetId = (scope: IConstruct, name: string) => {
const nextId = (assetIds.get(scope) ?? 0) + 1;
assetIds.set(scope, nextId);

// Only one asset per scope, skip the id
if (nextId === 1) {
return name;
}

return `${name}${nextId}`;
};

export interface TypeScriptSourceProps extends TypeScriptCodeProps {};

export class TypeScriptSource implements ISource {
Expand Down Expand Up @@ -66,7 +79,7 @@ export class TypeScriptSource implements ISource {
if (!this.asset) {
this.asset = new TypeScriptAsset(
scope,
this.constructor.name,
assetId(scope, this.constructor.name),
this.props,
);
} else if (Stack.of(this.asset) !== Stack.of(scope)) {
Expand Down
32 changes: 32 additions & 0 deletions test/source.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,4 +176,36 @@ describe('source', () => {
expect(source.props.buildOptions.platform).toBe('browser');
});
});

describe('with multiple sources in the same scope', () => {
it('does not throw', () => {
const stack = new Stack();

const sourceOne = new TypeScriptSource('fixtures/handlers/ts-handler.ts', {
buildOptions: {
absWorkingDir: resolve(__dirname),
},
});
const sourceTwo = new TypeScriptSource('fixtures/handlers/ts-handler.ts', {
buildOptions: {
absWorkingDir: resolve(__dirname),
},
});

const destinationBucket = new Bucket(stack, 'WebsiteBucket', {
autoDeleteObjects: true,
publicReadAccess: true,
removalPolicy: RemovalPolicy.DESTROY,
websiteIndexDocument: 'index.html',
});

new BucketDeployment(stack, 'MultipleAssets', {
destinationBucket,
sources: [
sourceOne,
sourceTwo,
],
});
});
});
});

0 comments on commit 6777ba2

Please sign in to comment.