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

(cherry picked from commit 6777ba2)
  • Loading branch information
mrgrain committed Dec 24, 2023
1 parent 0da8800 commit 6b556bf
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,11 +4,24 @@ import {
ISource,
SourceConfig,
} from 'aws-cdk-lib/aws-s3-deployment';
import { Construct } from 'constructs';
import { Construct, IConstruct } from 'constructs';
import { AssetBaseProps, AssetProps, JavaScriptAsset, TypeScriptAsset } from './asset';
import { EntryPoints } from './bundler';
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 JavaScriptSourceProps extends AssetBaseProps{};
export interface TypeScriptSourceProps extends AssetBaseProps{};

Expand Down Expand Up @@ -75,7 +88,7 @@ abstract class Source<
if (!this.asset) {
this.asset = new this.assetClass(
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 @@ -178,4 +178,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 6b556bf

Please sign in to comment.