aws-cdk-lib
Version:
Version 2 of the AWS Cloud Development Kit library
2 lines (1 loc) • 17.1 kB
JavaScript
;var __esDecorate=exports&&exports.__esDecorate||function(ctor,descriptorIn,decorators,contextIn,initializers,extraInitializers){function accept(f){if(f!==void 0&&typeof f!="function")throw new TypeError("Function expected");return f}for(var kind=contextIn.kind,key=kind==="getter"?"get":kind==="setter"?"set":"value",target=!descriptorIn&&ctor?contextIn.static?ctor:ctor.prototype:null,descriptor=descriptorIn||(target?Object.getOwnPropertyDescriptor(target,contextIn.name):{}),_,done=!1,i=decorators.length-1;i>=0;i--){var context={};for(var p in contextIn)context[p]=p==="access"?{}:contextIn[p];for(var p in contextIn.access)context.access[p]=contextIn.access[p];context.addInitializer=function(f){if(done)throw new TypeError("Cannot add initializers after decoration has completed");extraInitializers.push(accept(f||null))};var result=(0,decorators[i])(kind==="accessor"?{get:descriptor.get,set:descriptor.set}:descriptor[key],context);if(kind==="accessor"){if(result===void 0)continue;if(result===null||typeof result!="object")throw new TypeError("Object expected");(_=accept(result.get))&&(descriptor.get=_),(_=accept(result.set))&&(descriptor.set=_),(_=accept(result.init))&&initializers.unshift(_)}else(_=accept(result))&&(kind==="field"?initializers.unshift(_):descriptor[key]=_)}target&&Object.defineProperty(target,contextIn.name,descriptor),done=!0},__runInitializers=exports&&exports.__runInitializers||function(thisArg,initializers,value){for(var useValue=arguments.length>2,i=0;i<initializers.length;i++)value=useValue?initializers[i].call(thisArg,value):initializers[i].call(thisArg);return useValue?value:void 0};Object.defineProperty(exports,"__esModule",{value:!0}),exports.Expires=exports.StorageClass=exports.ServerSideEncryption=exports.CacheControl=exports.DeployTimeSubstitutedFile=exports.BucketDeployment=void 0;var jsiiDeprecationWarnings=()=>{var tmp=require("../../.warnings.jsii.js");return jsiiDeprecationWarnings=()=>tmp,tmp};const JSII_RTTI_SYMBOL_1=Symbol.for("jsii.rtti");var fs=()=>{var tmp=require("fs");return fs=()=>tmp,tmp},case_1=()=>{var tmp=require("case");return case_1=()=>tmp,tmp},constructs_1=()=>{var tmp=require("constructs");return constructs_1=()=>tmp,tmp},source_1=()=>{var tmp=require("./source");return source_1=()=>tmp,tmp},efs=()=>{var tmp=require("../../aws-efs");return efs=()=>tmp,tmp},iam=()=>{var tmp=require("../../aws-iam");return iam=()=>tmp,tmp},lambda=()=>{var tmp=require("../../aws-lambda");return lambda=()=>tmp,tmp},s3=()=>{var tmp=require("../../aws-s3");return s3=()=>tmp,tmp},cdk=()=>{var tmp=require("../../core");return cdk=()=>tmp,tmp},errors_1=()=>{var tmp=require("../../core/lib/errors");return errors_1=()=>tmp,tmp},prop_injectable_1=()=>{var tmp=require("../../core/lib/prop-injectable");return prop_injectable_1=()=>tmp,tmp},bucket_deployment_provider_generated_1=()=>{var tmp=require("../../custom-resource-handlers/dist/aws-s3-deployment/bucket-deployment-provider.generated");return bucket_deployment_provider_generated_1=()=>tmp,tmp},lambda_layer_awscli_1=()=>{var tmp=require("../../lambda-layer-awscli");return lambda_layer_awscli_1=()=>tmp,tmp};const CUSTOM_RESOURCE_OWNER_TAG="aws-cdk:cr-owned";let BucketDeployment=(()=>{let _classDecorators=[prop_injectable_1().propertyInjectable],_classDescriptor,_classExtraInitializers=[],_classThis,_classSuper=constructs_1().Construct;var BucketDeployment2=class extends _classSuper{static{_classThis=this}static{const _metadata=typeof Symbol=="function"&&Symbol.metadata?Object.create(_classSuper[Symbol.metadata]??null):void 0;__esDecorate(null,_classDescriptor={value:_classThis},_classDecorators,{kind:"class",name:_classThis.name,metadata:_metadata},null,_classExtraInitializers),BucketDeployment2=_classThis=_classDescriptor.value,_metadata&&Object.defineProperty(_classThis,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:_metadata})}static[JSII_RTTI_SYMBOL_1]={fqn:"aws-cdk-lib.aws_s3_deployment.BucketDeployment",version:"2.233.0"};static PROPERTY_INJECTION_ID="aws-cdk-lib.aws-s3-deployment.BucketDeployment";cr;_deployedBucket;requestDestinationArn=!1;destinationBucket;sources;handlerRole;constructor(scope,id,props){super(scope,id);try{jsiiDeprecationWarnings().aws_cdk_lib_aws_s3_deployment_BucketDeploymentProps(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,BucketDeployment2),error}if(props.distributionPaths){if(!props.distribution)throw new(errors_1()).ValidationError("Distribution must be specified if distribution paths are specified",this);if(!cdk().Token.isUnresolved(props.distributionPaths)&&!props.distributionPaths.every(distributionPath=>cdk().Token.isUnresolved(distributionPath)||distributionPath.startsWith("/")))throw new(errors_1()).ValidationError('Distribution paths must start with "/"',this)}if(props.useEfs&&!props.vpc)throw new(errors_1()).ValidationError("Vpc must be specified if useEfs is set",this);this.destinationBucket=props.destinationBucket;const accessPointPath="/lambda";let accessPoint;if(props.useEfs&&props.vpc){const accessMode="0777",fileSystem=this.getOrCreateEfsFileSystem(scope,{vpc:props.vpc,removalPolicy:cdk().RemovalPolicy.DESTROY});accessPoint=fileSystem.addAccessPoint("AccessPoint",{path:accessPointPath,createAcl:{ownerUid:"1001",ownerGid:"1001",permissions:accessMode},posixUser:{uid:"1001",gid:"1001"}}),accessPoint.node.addDependency(fileSystem.mountTargetsAvailable)}props.vpc&&this.node.addDependency(props.vpc);const mountPath=`/mnt${accessPointPath}`,handler=new(bucket_deployment_provider_generated_1()).BucketDeploymentSingletonFunction(this,"CustomResourceHandler",{uuid:this.renderSingletonUuid(props.memoryLimit,props.ephemeralStorageSize,props.vpc,props.securityGroups),layers:[new(lambda_layer_awscli_1()).AwsCliLayer(this,"AwsCliLayer")],environment:{...props.useEfs?{MOUNT_PATH:mountPath}:void 0,AWS_CA_BUNDLE:"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"},lambdaPurpose:"Custom::CDKBucketDeployment",timeout:cdk().Duration.minutes(15),role:props.role,memorySize:props.memoryLimit,ephemeralStorageSize:props.ephemeralStorageSize,vpc:props.vpc,vpcSubnets:props.vpcSubnets,securityGroups:props.securityGroups&&props.securityGroups.length>0?props.securityGroups:void 0,filesystem:accessPoint?lambda().FileSystem.fromEfsAccessPoint(accessPoint,mountPath):void 0,...props.logRetention?{logRetention:props.logRetention}:{},logGroup:props.logGroup}),handlerRole=handler.role;if(!handlerRole)throw new(errors_1()).ValidationError("lambda.SingletonFunction should have created a Role",this);this.handlerRole=handlerRole,this.sources=props.sources.map(source=>source.bind(this,{handlerRole:this.handlerRole})),this.destinationBucket.grantReadWrite(handler),props.accessControl&&this.destinationBucket.grantPutAcl(handler),props.distribution&&handler.addToRolePolicy(new(iam()).PolicyStatement({effect:iam().Effect.ALLOW,actions:["cloudfront:GetInvalidation","cloudfront:CreateInvalidation"],resources:["*"]}));const _this=this;this.node.addValidation({validate(){return _this.sources.some(source=>source.markers)&&props.extract==!1?["Some sources are incompatible with extract=false; sources with deploy-time values (such as 'snsTopic.topicArn') must be extracted."]:[]}});const crUniqueId=`CustomResource${this.renderUniqueId(props.memoryLimit,props.ephemeralStorageSize,props.vpc)}`;this.cr=new(cdk()).CustomResource(this,crUniqueId,{serviceToken:handler.functionArn,resourceType:"Custom::CDKBucketDeployment",properties:{SourceBucketNames:cdk().Lazy.uncachedList({produce:()=>this.sources.map(source=>source.bucket.bucketName)}),SourceObjectKeys:cdk().Lazy.uncachedList({produce:()=>this.sources.map(source=>source.zipObjectKey)}),SourceMarkers:cdk().Lazy.uncachedAny({produce:()=>this.sources.reduce((acc,source)=>(source.markers?acc.push(source.markers):this.sources.length>1&&acc.push({}),acc),[])},{omitEmptyArray:!0}),SourceMarkersConfig:cdk().Lazy.uncachedAny({produce:()=>this.sources.reduce((acc,source)=>(source.markersConfig?acc.push(source.markersConfig):this.sources.length>1&&acc.push({}),acc),[])},{omitEmptyArray:!0}),DestinationBucketName:this.destinationBucket.bucketName,DestinationBucketKeyPrefix:props.destinationKeyPrefix,WaitForDistributionInvalidation:props.waitForDistributionInvalidation??!0,RetainOnDelete:props.retainOnDelete,Extract:props.extract,Prune:props.prune??!0,Exclude:props.exclude,Include:props.include,UserMetadata:props.metadata?mapUserMetadata(props.metadata):void 0,SystemMetadata:mapSystemMetadata(props),DistributionId:props.distribution?.distributionRef.distributionId,DistributionPaths:props.distributionPaths,SignContent:props.signContent,OutputObjectKeys:props.outputObjectKeys??!0,DestinationBucketArn:cdk().Lazy.string({produce:()=>this.requestDestinationArn?this.destinationBucket.bucketArn:void 0})}});let prefix=props.destinationKeyPrefix?`:${props.destinationKeyPrefix}`:"";prefix+=`:${this.cr.node.addr.slice(-8)}`;const tagKey=CUSTOM_RESOURCE_OWNER_TAG+prefix;if(!cdk().Token.isUnresolved(tagKey)&&tagKey.length>128)throw new(errors_1()).ValidationError('The BucketDeployment construct requires that the "destinationKeyPrefix" be <=104 characters.',this);cdk().Tags.of(this.destinationBucket).add(tagKey,"true")}get deployedBucket(){return this.requestDestinationArn=!0,this._deployedBucket=this._deployedBucket??s3().Bucket.fromBucketAttributes(this,"DestinationBucket",{bucketArn:cdk().Token.asString(this.cr.getAtt("DestinationBucketArn")),region:this.destinationBucket.env.region,account:this.destinationBucket.env.account,isWebsite:this.destinationBucket.isWebsite}),this._deployedBucket}get objectKeys(){return cdk().Token.asList(this.cr.getAtt("SourceObjectKeys"))}addSource(source){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_s3_deployment_ISource(source)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.addSource),error}const config=source.bind(this,{handlerRole:this.handlerRole});this.sources.some(c=>sourceConfigEqual(cdk().Stack.of(this),c,config))||this.sources.push(config)}renderUniqueId(memoryLimit,ephemeralStorageSize,vpc,securityGroups){let uuid="";if(memoryLimit){if(cdk().Token.isUnresolved(memoryLimit))throw new(errors_1()).ValidationError("Can't use tokens when specifying 'memoryLimit' since we use it to identify the singleton custom resource handler.",this);uuid+=`-${memoryLimit.toString()}MiB`}if(ephemeralStorageSize){if(ephemeralStorageSize.isUnresolved())throw new(errors_1()).ValidationError("Can't use tokens when specifying 'ephemeralStorageSize' since we use it to identify the singleton custom resource handler.",this);uuid+=`-${ephemeralStorageSize.toMebibytes().toString()}MiB`}if(vpc&&(uuid+=`-${vpc.node.addr}`),securityGroups&&securityGroups.length>0){const sortedSecurityGroupIds=securityGroups.map(sg=>sg.node.addr).sort().join("-");uuid+=`-${sortedSecurityGroupIds}`}return uuid}renderSingletonUuid(memoryLimit,ephemeralStorageSize,vpc,securityGroups){let uuid="8693BB64-9689-44B6-9AAF-B0CC9EB8756C";return uuid+=this.renderUniqueId(memoryLimit,ephemeralStorageSize,vpc,securityGroups),uuid}getOrCreateEfsFileSystem(scope,fileSystemProps){const stack=cdk().Stack.of(scope),uuid=`BucketDeploymentEFS-VPC-${fileSystemProps.vpc.node.addr}`;return stack.node.tryFindChild(uuid)??new(efs()).FileSystem(scope,uuid,fileSystemProps)}static{__runInitializers(_classThis,_classExtraInitializers)}};return BucketDeployment2=_classThis})();exports.BucketDeployment=BucketDeployment;class DeployTimeSubstitutedFile extends BucketDeployment{static[JSII_RTTI_SYMBOL_1]={fqn:"aws-cdk-lib.aws_s3_deployment.DeployTimeSubstitutedFile",version:"2.233.0"};objectKey;constructor(scope,id,props){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_s3_deployment_DeployTimeSubstitutedFileProps(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,DeployTimeSubstitutedFile),error}if(!fs().existsSync(props.source))throw new(errors_1()).ValidationError(`No file found at 'source' path ${props.source}`,scope);let fileData=fs().readFileSync(props.source,"utf-8");fileData=fileData.replace(/{{\s*(\w+)\s*}}/g,function(match,expr){return props.substitutions[expr]??match});const objectKey=props.destinationKey??cdk().FileSystem.fingerprint(props.source),fileSource=source_1().Source.data(objectKey,fileData),fullBucketDeploymentProps={prune:!1,extract:!0,...props,sources:[fileSource],role:props.role};super(scope,id,fullBucketDeploymentProps),this.objectKey=objectKey}get bucket(){return this.deployedBucket}}exports.DeployTimeSubstitutedFile=DeployTimeSubstitutedFile;function mapUserMetadata(metadata){const mapKey=key=>key.toLowerCase();return Object.keys(metadata).reduce((o,key)=>({...o,[mapKey(key)]:metadata[key]}),{})}function mapSystemMetadata(metadata){const res={};return metadata.cacheControl&&(res["cache-control"]=metadata.cacheControl.map(c=>c.value).join(", ")),metadata.expires&&(res.expires=metadata.expires.date.toUTCString()),metadata.contentDisposition&&(res["content-disposition"]=metadata.contentDisposition),metadata.contentEncoding&&(res["content-encoding"]=metadata.contentEncoding),metadata.contentLanguage&&(res["content-language"]=metadata.contentLanguage),metadata.contentType&&(res["content-type"]=metadata.contentType),metadata.serverSideEncryption&&(res.sse=metadata.serverSideEncryption),metadata.storageClass&&(res["storage-class"]=metadata.storageClass),metadata.websiteRedirectLocation&&(res["website-redirect"]=metadata.websiteRedirectLocation),metadata.serverSideEncryptionAwsKmsKeyId&&(res["sse-kms-key-id"]=metadata.serverSideEncryptionAwsKmsKeyId),metadata.serverSideEncryptionCustomerAlgorithm&&(res["sse-c-copy-source"]=metadata.serverSideEncryptionCustomerAlgorithm),metadata.accessControl&&(res.acl=(0,case_1().kebab)(metadata.accessControl.toString())),Object.keys(res).length===0?void 0:res}class CacheControl{value;static[JSII_RTTI_SYMBOL_1]={fqn:"aws-cdk-lib.aws_s3_deployment.CacheControl",version:"2.233.0"};static mustRevalidate(){return new CacheControl("must-revalidate")}static noCache(){return new CacheControl("no-cache")}static noTransform(){return new CacheControl("no-transform")}static noStore(){return new CacheControl("no-store")}static mustUnderstand(){return new CacheControl("must-understand")}static setPublic(){return new CacheControl("public")}static setPrivate(){return new CacheControl("private")}static immutable(){return new CacheControl("immutable")}static proxyRevalidate(){return new CacheControl("proxy-revalidate")}static maxAge(t){try{jsiiDeprecationWarnings().aws_cdk_lib_Duration(t)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.maxAge),error}return new CacheControl(`max-age=${t.toSeconds()}`)}static sMaxAge(t){try{jsiiDeprecationWarnings().aws_cdk_lib_Duration(t)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.sMaxAge),error}return new CacheControl(`s-maxage=${t.toSeconds()}`)}static staleWhileRevalidate(t){try{jsiiDeprecationWarnings().aws_cdk_lib_Duration(t)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.staleWhileRevalidate),error}return new CacheControl(`stale-while-revalidate=${t.toSeconds()}`)}static staleIfError(t){try{jsiiDeprecationWarnings().aws_cdk_lib_Duration(t)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.staleIfError),error}return new CacheControl(`stale-if-error=${t.toSeconds()}`)}static fromString(s){return new CacheControl(s)}constructor(value){this.value=value}}exports.CacheControl=CacheControl;var ServerSideEncryption;(function(ServerSideEncryption2){ServerSideEncryption2.AES_256="AES256",ServerSideEncryption2.AWS_KMS="aws:kms",ServerSideEncryption2.AWS_KMS_DSSE="aws:kms:dsse"})(ServerSideEncryption||(exports.ServerSideEncryption=ServerSideEncryption={}));var StorageClass;(function(StorageClass2){StorageClass2.STANDARD="STANDARD",StorageClass2.REDUCED_REDUNDANCY="REDUCED_REDUNDANCY",StorageClass2.STANDARD_IA="STANDARD_IA",StorageClass2.ONEZONE_IA="ONEZONE_IA",StorageClass2.INTELLIGENT_TIERING="INTELLIGENT_TIERING",StorageClass2.GLACIER="GLACIER",StorageClass2.DEEP_ARCHIVE="DEEP_ARCHIVE"})(StorageClass||(exports.StorageClass=StorageClass={}));class Expires{value;static[JSII_RTTI_SYMBOL_1]={fqn:"aws-cdk-lib.aws_s3_deployment.Expires",version:"2.233.0"};static atDate(d){return new Expires(d.toUTCString())}static atTimestamp(t){return Expires.atDate(new Date(t))}static after(t){return Expires.atDate(new Date(Date.now()+t.toMilliseconds()))}static fromString(s){return new Expires(s)}constructor(value){this.value=value}}exports.Expires=Expires;function sourceConfigEqual(stack,a,b){const resolveName=config=>JSON.stringify(stack.resolve(config.bucket.bucketName));return resolveName(a)===resolveName(b)&&a.zipObjectKey===b.zipObjectKey&&a.markers===void 0&&b.markers===void 0}