aws-cdk-lib
Version:
Version 2 of the AWS Cloud Development Kit library
1 lines • 53.7 kB
JavaScript
"use strict";var __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},__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};Object.defineProperty(exports,"__esModule",{value:!0}),exports.ObjectLockRetention=exports.ObjectLockMode=exports.ReplaceKey=exports.BucketAccessControl=exports.EventType=exports.BucketEncryption=exports.Bucket=exports.TransitionDefaultMinimumObjectSize=exports.ReplicationTimeValue=exports.TargetObjectKeyFormat=exports.PartitionDateSource=exports.ObjectOwnership=exports.InventoryObjectVersion=exports.InventoryFrequency=exports.InventoryFormat=exports.RedirectProtocol=exports.HttpMethods=exports.BlockPublicAccess=exports.BucketBase=void 0;var jsiiDeprecationWarnings=()=>{var tmp=require("../../.warnings.jsii.js");return jsiiDeprecationWarnings=()=>tmp,tmp};const JSII_RTTI_SYMBOL_1=Symbol.for("jsii.rtti");var os_1=()=>{var tmp=require("os");return os_1=()=>tmp,tmp},bucket_grants_1=()=>{var tmp=require("./bucket-grants");return bucket_grants_1=()=>tmp,tmp},bucket_policy_1=()=>{var tmp=require("./bucket-policy");return bucket_policy_1=()=>tmp,tmp},notifications_resource_1=()=>{var tmp=require("./notifications-resource");return notifications_resource_1=()=>tmp,tmp},perms=()=>{var tmp=require("./perms");return perms=()=>tmp,tmp},s3_generated_1=()=>{var tmp=require("./s3.generated");return s3_generated_1=()=>tmp,tmp},util_1=()=>{var tmp=require("./util");return util_1=()=>tmp,tmp},events=()=>{var tmp=require("../../aws-events");return events=()=>tmp,tmp},iam=()=>{var tmp=require("../../aws-iam");return iam=()=>tmp,tmp},kms=()=>{var tmp=require("../../aws-kms");return kms=()=>tmp,tmp},core_1=()=>{var tmp=require("../../core");return core_1=()=>tmp,tmp},errors_1=()=>{var tmp=require("../../core/lib/errors");return errors_1=()=>tmp,tmp},metadata_resource_1=()=>{var tmp=require("../../core/lib/metadata-resource");return metadata_resource_1=()=>tmp,tmp},cfn_reference_1=()=>{var tmp=require("../../core/lib/private/cfn-reference");return cfn_reference_1=()=>tmp,tmp},prop_injectable_1=()=>{var tmp=require("../../core/lib/prop-injectable");return prop_injectable_1=()=>tmp,tmp},auto_delete_objects_provider_generated_1=()=>{var tmp=require("../../custom-resource-handlers/dist/aws-s3/auto-delete-objects-provider.generated");return auto_delete_objects_provider_generated_1=()=>tmp,tmp},cxapi=()=>{var tmp=require("../../cx-api");return cxapi=()=>tmp,tmp},regionInformation=()=>{var tmp=require("../../region-info");return regionInformation=()=>tmp,tmp};const AUTO_DELETE_OBJECTS_RESOURCE_TYPE="Custom::S3AutoDeleteObjects",AUTO_DELETE_OBJECTS_TAG="aws-cdk:auto-delete-objects";class BucketBase extends core_1().Resource{static[JSII_RTTI_SYMBOL_1]={fqn:"aws-cdk-lib.aws_s3.BucketBase",version:"2.233.0"};notifications;notificationsHandlerRole;notificationsSkipDestinationValidation;objectOwnership;grants=bucket_grants_1().BucketGrants.fromBucket(this);constructor(scope,id,props={}){super(scope,id,props);try{jsiiDeprecationWarnings().aws_cdk_lib_ResourceProps(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,BucketBase),error}this.node.addValidation({validate:()=>this.policy?.document.validateForResourcePolicy()??[]})}grantOnKey(grantee,...actions){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_IGrantable(grantee)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.grantOnKey),error}return{grant:this.encryptionKey?.grant(grantee,...actions)}}onCloudTrailEvent(id,options={}){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_s3_OnCloudTrailBucketEventOptions(options)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.onCloudTrailEvent),error}const rule=new(events()).Rule(this,id,options);return rule.addTarget(options.target),rule.addEventPattern({source:["aws.s3"],detailType:["AWS API Call via CloudTrail"],detail:{resources:{ARN:options.paths?.map(p=>this.arnForObjects(p))??[this.bucketArn]}}}),rule}onCloudTrailPutObject(id,options={}){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_s3_OnCloudTrailBucketEventOptions(options)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.onCloudTrailPutObject),error}const rule=this.onCloudTrailEvent(id,options);return rule.addEventPattern({detail:{eventName:["PutObject"]}}),rule}onCloudTrailWriteObject(id,options={}){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_s3_OnCloudTrailBucketEventOptions(options)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.onCloudTrailWriteObject),error}const rule=this.onCloudTrailEvent(id,options);return rule.addEventPattern({detail:{eventName:["CompleteMultipartUpload","CopyObject","PutObject"],requestParameters:{bucketName:[this.bucketName],key:options.paths}}}),rule}addToResourcePolicy(permission){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_PolicyStatement(permission)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.addToResourcePolicy),error}return!this.policy&&this.autoCreatePolicy&&(this.policy=new(bucket_policy_1()).BucketPolicy(this,"Policy",{bucket:this})),this.policy?(this.policy.document.addStatements(permission),{statementAdded:!0,policyDependable:this.policy}):{statementAdded:!1}}urlForObject(key){const stack=core_1().Stack.of(this),prefix=`https://s3.${this.env.region}.${stack.urlSuffix}/`;return typeof key!="string"?this.urlJoin(prefix,this.bucketName):this.urlJoin(prefix,this.bucketName,key)}transferAccelerationUrlForObject(key,options){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_s3_TransferAccelerationUrlOptions(options)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.transferAccelerationUrlForObject),error}const dualStack=options?.dualStack?".dualstack":"",prefix=`https://${this.bucketName}.s3-accelerate${dualStack}.amazonaws.com/`;return typeof key!="string"?this.urlJoin(prefix):this.urlJoin(prefix,key)}virtualHostedUrlForObject(key,options){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_s3_VirtualHostedStyleUrlOptions(options)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.virtualHostedUrlForObject),error}const prefix=`https://${options?.regional??!0?this.bucketRegionalDomainName:this.bucketDomainName}`;return typeof key!="string"?prefix:this.urlJoin(prefix,key)}s3UrlForObject(key){const prefix="s3://";return typeof key!="string"?this.urlJoin(prefix,this.bucketName):this.urlJoin(prefix,this.bucketName,key)}arnForObjects(keyPattern){return`${this.bucketArn}/${keyPattern}`}grantRead(identity,objectsKeyPattern="*"){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_IGrantable(identity)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.grantRead),error}return this.grants.read(identity,objectsKeyPattern)}grantWrite(identity,objectsKeyPattern="*",allowedActionPatterns=[]){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_IGrantable(identity)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.grantWrite),error}return this.grants.write(identity,objectsKeyPattern,allowedActionPatterns)}grantPut(identity,objectsKeyPattern="*"){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_IGrantable(identity)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.grantPut),error}return this.grants.put(identity,objectsKeyPattern)}grantPutAcl(identity,objectsKeyPattern="*"){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_IGrantable(identity)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.grantPutAcl),error}return this.grants.putAcl(identity,objectsKeyPattern)}grantDelete(identity,objectsKeyPattern="*"){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_IGrantable(identity)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.grantDelete),error}return this.grants.delete(identity,objectsKeyPattern)}grantReadWrite(identity,objectsKeyPattern="*"){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_IGrantable(identity)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.grantReadWrite),error}return this.grants.readWrite(identity,objectsKeyPattern)}grantReplicationPermission(identity,props){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_IGrantable(identity),jsiiDeprecationWarnings().aws_cdk_lib_aws_s3_GrantReplicationPermissionProps(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.grantReplicationPermission),error}return this.grants.replicationPermission(identity,props)}grantPublicAccess(keyPrefix="*",...allowedActions){return this.grants.publicAccess(keyPrefix,...allowedActions)}addEventNotification(event,dest,...filters){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_s3_EventType(event),jsiiDeprecationWarnings().aws_cdk_lib_aws_s3_IBucketNotificationDestination(dest),jsiiDeprecationWarnings().aws_cdk_lib_aws_s3_NotificationKeyFilter(filters)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.addEventNotification),error}this.withNotifications(notifications=>notifications.addNotification(event,dest,...filters))}withNotifications(cb){this.notifications||(this.notifications=new(notifications_resource_1()).BucketNotifications(this,"Notifications",{bucket:this,handlerRole:this.notificationsHandlerRole,skipDestinationValidation:this.notificationsSkipDestinationValidation??!1})),cb(this.notifications)}addObjectCreatedNotification(dest,...filters){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_s3_IBucketNotificationDestination(dest),jsiiDeprecationWarnings().aws_cdk_lib_aws_s3_NotificationKeyFilter(filters)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.addObjectCreatedNotification),error}return this.addEventNotification(EventType.OBJECT_CREATED,dest,...filters)}addObjectRemovedNotification(dest,...filters){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_s3_IBucketNotificationDestination(dest),jsiiDeprecationWarnings().aws_cdk_lib_aws_s3_NotificationKeyFilter(filters)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.addObjectRemovedNotification),error}return this.addEventNotification(EventType.OBJECT_REMOVED,dest,...filters)}enableEventBridgeNotification(){this.withNotifications(notifications=>notifications.enableEventBridgeNotification())}addReplicationPolicy(roleArn,accessControlTransition,account){const results=[];if(results.push(this.addToResourcePolicy(new(iam()).PolicyStatement({actions:["s3:GetBucketVersioning","s3:PutBucketVersioning"],resources:[this.bucketArn],principals:[new(iam()).ArnPrincipal(roleArn)]})).statementAdded),results.push(this.addToResourcePolicy(new(iam()).PolicyStatement({actions:["s3:ReplicateObject","s3:ReplicateDelete"],resources:[this.arnForObjects("*")],principals:[new(iam()).ArnPrincipal(roleArn)]})).statementAdded),accessControlTransition){if(!account)throw new(errors_1()).ValidationError("account must be specified to override ownership access control transition",this);results.push(this.addToResourcePolicy(new(iam()).PolicyStatement({actions:["s3:ObjectOwnerOverrideToBucketOwner"],resources:[this.arnForObjects("*")],principals:[new(iam()).AccountPrincipal(account)]})).statementAdded)}results.includes(!1)&&core_1().Annotations.of(this).addInfo(`Cross-account S3 replication for a referenced destination bucket is set up. In the destination bucket's bucket policy, please grant access permissions from ${this.stack.resolve(roleArn)}.`)}urlJoin(...components){return components.reduce((result,component)=>(result.endsWith("/")&&(result=result.slice(0,-1)),component.startsWith("/")&&(component=component.slice(1)),`${result}/${component}`))}get bucketRef(){return{bucketArn:this.bucketArn,bucketName:this.bucketName}}}exports.BucketBase=BucketBase;class BlockPublicAccess{static[JSII_RTTI_SYMBOL_1]={fqn:"aws-cdk-lib.aws_s3.BlockPublicAccess",version:"2.233.0"};static BLOCK_ALL=new BlockPublicAccess({blockPublicAcls:!0,blockPublicPolicy:!0,ignorePublicAcls:!0,restrictPublicBuckets:!0});static BLOCK_ACLS=new BlockPublicAccess({blockPublicAcls:!0,ignorePublicAcls:!0});static BLOCK_ACLS_ONLY=new BlockPublicAccess({blockPublicAcls:!0,blockPublicPolicy:!1,ignorePublicAcls:!0,restrictPublicBuckets:!1});blockPublicAcls;blockPublicPolicy;ignorePublicAcls;restrictPublicBuckets;constructor(options){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_s3_BlockPublicAccessOptions(options)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,BlockPublicAccess),error}this.blockPublicAcls=options.blockPublicAcls,this.blockPublicPolicy=options.blockPublicPolicy,this.ignorePublicAcls=options.ignorePublicAcls,this.restrictPublicBuckets=options.restrictPublicBuckets}}exports.BlockPublicAccess=BlockPublicAccess;var HttpMethods;(function(HttpMethods2){HttpMethods2.GET="GET",HttpMethods2.PUT="PUT",HttpMethods2.HEAD="HEAD",HttpMethods2.POST="POST",HttpMethods2.DELETE="DELETE"})(HttpMethods||(exports.HttpMethods=HttpMethods={}));var RedirectProtocol;(function(RedirectProtocol2){RedirectProtocol2.HTTP="http",RedirectProtocol2.HTTPS="https"})(RedirectProtocol||(exports.RedirectProtocol=RedirectProtocol={}));var InventoryFormat;(function(InventoryFormat2){InventoryFormat2.CSV="CSV",InventoryFormat2.PARQUET="Parquet",InventoryFormat2.ORC="ORC"})(InventoryFormat||(exports.InventoryFormat=InventoryFormat={}));var InventoryFrequency;(function(InventoryFrequency2){InventoryFrequency2.DAILY="Daily",InventoryFrequency2.WEEKLY="Weekly"})(InventoryFrequency||(exports.InventoryFrequency=InventoryFrequency={}));var InventoryObjectVersion;(function(InventoryObjectVersion2){InventoryObjectVersion2.ALL="All",InventoryObjectVersion2.CURRENT="Current"})(InventoryObjectVersion||(exports.InventoryObjectVersion=InventoryObjectVersion={}));var ObjectOwnership;(function(ObjectOwnership2){ObjectOwnership2.BUCKET_OWNER_ENFORCED="BucketOwnerEnforced",ObjectOwnership2.BUCKET_OWNER_PREFERRED="BucketOwnerPreferred",ObjectOwnership2.OBJECT_WRITER="ObjectWriter"})(ObjectOwnership||(exports.ObjectOwnership=ObjectOwnership={}));var PartitionDateSource;(function(PartitionDateSource2){PartitionDateSource2.EVENT_TIME="EventTime",PartitionDateSource2.DELIVERY_TIME="DeliveryTime"})(PartitionDateSource||(exports.PartitionDateSource=PartitionDateSource={}));class TargetObjectKeyFormat{static[JSII_RTTI_SYMBOL_1]={fqn:"aws-cdk-lib.aws_s3.TargetObjectKeyFormat",version:"2.233.0"};static partitionedPrefix(dateSource){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_s3_PartitionDateSource(dateSource)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.partitionedPrefix),error}return new class extends TargetObjectKeyFormat{_render(){return{partitionedPrefix:{partitionDateSource:dateSource}}}}}static simplePrefix(){return new class extends TargetObjectKeyFormat{_render(){return{simplePrefix:{}}}}}}exports.TargetObjectKeyFormat=TargetObjectKeyFormat;class ReplicationTimeValue{minutes;static[JSII_RTTI_SYMBOL_1]={fqn:"aws-cdk-lib.aws_s3.ReplicationTimeValue",version:"2.233.0"};static FIFTEEN_MINUTES=new ReplicationTimeValue(15);constructor(minutes){this.minutes=minutes}}exports.ReplicationTimeValue=ReplicationTimeValue;var TransitionDefaultMinimumObjectSize;(function(TransitionDefaultMinimumObjectSize2){TransitionDefaultMinimumObjectSize2.ALL_STORAGE_CLASSES_128_K="all_storage_classes_128K",TransitionDefaultMinimumObjectSize2.VARIES_BY_STORAGE_CLASS="varies_by_storage_class"})(TransitionDefaultMinimumObjectSize||(exports.TransitionDefaultMinimumObjectSize=TransitionDefaultMinimumObjectSize={}));let Bucket=(()=>{let _classDecorators=[prop_injectable_1().propertyInjectable],_classDescriptor,_classExtraInitializers=[],_classThis,_classSuper=BucketBase,_instanceExtraInitializers=[],_addLifecycleRule_decorators,_addMetric_decorators,_addCorsRule_decorators,_addInventory_decorators;var Bucket2=class extends _classSuper{static{_classThis=this}static{const _metadata=typeof Symbol=="function"&&Symbol.metadata?Object.create(_classSuper[Symbol.metadata]??null):void 0;_addLifecycleRule_decorators=[(0,metadata_resource_1().MethodMetadata)()],_addMetric_decorators=[(0,metadata_resource_1().MethodMetadata)()],_addCorsRule_decorators=[(0,metadata_resource_1().MethodMetadata)()],_addInventory_decorators=[(0,metadata_resource_1().MethodMetadata)()],__esDecorate(this,null,_addLifecycleRule_decorators,{kind:"method",name:"addLifecycleRule",static:!1,private:!1,access:{has:obj=>"addLifecycleRule"in obj,get:obj=>obj.addLifecycleRule},metadata:_metadata},null,_instanceExtraInitializers),__esDecorate(this,null,_addMetric_decorators,{kind:"method",name:"addMetric",static:!1,private:!1,access:{has:obj=>"addMetric"in obj,get:obj=>obj.addMetric},metadata:_metadata},null,_instanceExtraInitializers),__esDecorate(this,null,_addCorsRule_decorators,{kind:"method",name:"addCorsRule",static:!1,private:!1,access:{has:obj=>"addCorsRule"in obj,get:obj=>obj.addCorsRule},metadata:_metadata},null,_instanceExtraInitializers),__esDecorate(this,null,_addInventory_decorators,{kind:"method",name:"addInventory",static:!1,private:!1,access:{has:obj=>"addInventory"in obj,get:obj=>obj.addInventory},metadata:_metadata},null,_instanceExtraInitializers),__esDecorate(null,_classDescriptor={value:_classThis},_classDecorators,{kind:"class",name:_classThis.name,metadata:_metadata},null,_classExtraInitializers),Bucket2=_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.Bucket",version:"2.233.0"};static PROPERTY_INJECTION_ID="aws-cdk-lib.aws-s3.Bucket";static fromBucketArn(scope,id,bucketArn){return Bucket2.fromBucketAttributes(scope,id,{bucketArn})}static fromBucketName(scope,id,bucketName){return Bucket2.fromBucketAttributes(scope,id,{bucketName})}static fromBucketAttributes(scope,id,attrs){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_s3_BucketAttributes(attrs)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.fromBucketAttributes),error}const stack=core_1().Stack.of(scope),region=attrs.region??stack.region,regionInfo=regionInformation().RegionInfo.get(region),urlSuffix=regionInfo.domainSuffix??stack.urlSuffix,bucketName=(0,util_1().parseBucketName)(scope,attrs);if(!bucketName)throw new(errors_1()).ValidationError("Bucket name is required",scope);Bucket2.validateBucketName(bucketName,!0);const oldEndpoint=`s3-website-${region}.${urlSuffix}`,newEndpoint=`s3-website.${region}.${urlSuffix}`;let staticDomainEndpoint=regionInfo.s3StaticWebsiteEndpoint??core_1().Lazy.string({produce:()=>stack.regionalFact(regionInformation().FactName.S3_STATIC_WEBSITE_ENDPOINT,newEndpoint)});attrs.bucketWebsiteNewUrlFormat!==void 0&&(staticDomainEndpoint=attrs.bucketWebsiteNewUrlFormat?newEndpoint:oldEndpoint);const websiteDomain=`${bucketName}.${staticDomainEndpoint}`;class Import extends BucketBase{bucketName=bucketName;bucketArn=(0,util_1().parseBucketArn)(scope,attrs);bucketDomainName=attrs.bucketDomainName||`${bucketName}.s3.${urlSuffix}`;bucketWebsiteUrl=attrs.bucketWebsiteUrl||`http://${websiteDomain}`;bucketWebsiteDomainName=attrs.bucketWebsiteUrl?core_1().Fn.select(2,core_1().Fn.split("/",attrs.bucketWebsiteUrl)):websiteDomain;bucketRegionalDomainName=attrs.bucketRegionalDomainName||`${bucketName}.s3.${region}.${urlSuffix}`;bucketDualStackDomainName=attrs.bucketDualStackDomainName||`${bucketName}.s3.dualstack.${region}.${urlSuffix}`;bucketWebsiteNewUrlFormat=attrs.bucketWebsiteNewUrlFormat??!1;encryptionKey=attrs.encryptionKey;isWebsite=attrs.isWebsite??!1;policy=void 0;replicationRoleArn=void 0;autoCreatePolicy=!1;disallowPublicAccess=!1;notificationsHandlerRole=attrs.notificationsHandlerRole;export(){return attrs}}return new Import(scope,id,{account:attrs.account,region:attrs.region})}static fromCfnBucket(cfnBucket){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_s3_CfnBucket(cfnBucket)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.fromCfnBucket),error}const id="@FromCfnBucket",existing=cfnBucket.node.tryFindChild(id);if(existing)return existing;let encryptionKey;if(cfnBucket.bucketEncryption){const serverSideEncryptionConfiguration=cfnBucket.bucketEncryption.serverSideEncryptionConfiguration;if(Array.isArray(serverSideEncryptionConfiguration)&&serverSideEncryptionConfiguration.length===1){const serverSideEncryptionByDefault=serverSideEncryptionConfiguration[0].serverSideEncryptionByDefault;if(serverSideEncryptionByDefault&&core_1().Token.isUnresolved(serverSideEncryptionByDefault.kmsMasterKeyId)){const kmsIResolvable=core_1().Tokenization.reverse(serverSideEncryptionByDefault.kmsMasterKeyId);if(kmsIResolvable instanceof cfn_reference_1().CfnReference){const cfnElement=kmsIResolvable.target;cfnElement instanceof kms().CfnKey&&(encryptionKey=kms().Key.fromCfnKey(cfnElement))}}}}return new class extends BucketBase{bucketArn=cfnBucket.attrArn;bucketName=cfnBucket.ref;bucketDomainName=cfnBucket.attrDomainName;bucketDualStackDomainName=cfnBucket.attrDualStackDomainName;bucketRegionalDomainName=cfnBucket.attrRegionalDomainName;bucketWebsiteUrl=cfnBucket.attrWebsiteUrl;bucketWebsiteDomainName=core_1().Fn.select(2,core_1().Fn.split("/",cfnBucket.attrWebsiteUrl));encryptionKey=encryptionKey;isWebsite=cfnBucket.websiteConfiguration!==void 0;policy=void 0;replicationRoleArn=void 0;autoCreatePolicy=!0;disallowPublicAccess=cfnBucket.publicAccessBlockConfiguration&&cfnBucket.publicAccessBlockConfiguration.blockPublicPolicy;constructor(){super(cfnBucket,id),this.node.defaultChild=cfnBucket}}}static validateBucketName(physicalName,allowLegacyBucketNaming=!1){const bucketName=physicalName;if(!bucketName||core_1().Token.isUnresolved(bucketName))return;const errors=[];(bucketName.length<3||bucketName.length>63)&&errors.push("Bucket name must be at least 3 and no more than 63 characters");const illegalCharsetRegEx=allowLegacyBucketNaming?/[^A-Za-z0-9._-]/:/[^a-z0-9.-]/,allowedEdgeCharsetRegEx=allowLegacyBucketNaming?/[A-Za-z0-9]/:/[a-z0-9]/,illegalCharMatch=bucketName.match(illegalCharsetRegEx);illegalCharMatch&&errors.push(allowLegacyBucketNaming?"Bucket name must only contain uppercase or lowercase characters and the symbols, period (.), underscore (_), and dash (-)":`Bucket name must only contain lowercase characters and the symbols, period (.) and dash (-) (offset: ${illegalCharMatch.index})`),allowedEdgeCharsetRegEx.test(bucketName.charAt(0))||errors.push(allowLegacyBucketNaming?"Bucket name must start with an uppercase, lowercase character or number":"Bucket name must start with a lowercase character or number (offset: 0)"),allowedEdgeCharsetRegEx.test(bucketName.charAt(bucketName.length-1))||errors.push(allowLegacyBucketNaming?"Bucket name must end with an uppercase, lowercase character or number":`Bucket name must end with a lowercase character or number (offset: ${bucketName.length-1})`);const consecSymbolMatch=bucketName.match(/\.-|-\.|\.\./);if(consecSymbolMatch&&errors.push(`Bucket name must not have dash next to period, or period next to dash, or consecutive periods (offset: ${consecSymbolMatch.index})`),/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(bucketName)&&errors.push("Bucket name must not resemble an IP address"),errors.length>0)throw new(errors_1()).UnscopedValidationError(`Invalid S3 bucket name (value: ${bucketName})${os_1().EOL}${errors.join(os_1().EOL)}`)}bucketArn=__runInitializers(this,_instanceExtraInitializers);bucketName;bucketDomainName;bucketWebsiteUrl;bucketWebsiteDomainName;bucketDualStackDomainName;bucketRegionalDomainName;encryptionKey;isWebsite;policy;replicationRoleArn;autoCreatePolicy=!0;disallowPublicAccess;accessControl;lifecycleRules=[];transitionDefaultMinimumObjectSize;eventBridgeEnabled;metrics=[];cors=[];inventories=[];_resource;constructor(scope,id,props={}){super(scope,id,{physicalName:props.bucketName});try{jsiiDeprecationWarnings().aws_cdk_lib_aws_s3_BucketProps(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,Bucket2),error}(0,metadata_resource_1().addConstructMetadata)(this,props),this.notificationsHandlerRole=props.notificationsHandlerRole,this.notificationsSkipDestinationValidation=props.notificationsSkipDestinationValidation;const{bucketEncryption,encryptionKey}=this.parseEncryption(props);this.encryptionKey=encryptionKey,Bucket2.validateBucketName(this.physicalName);let publicAccessBlockConfig=props.blockPublicAccess;props.blockPublicAccess&&core_1().FeatureFlags.of(this).isEnabled(cxapi().S3_PUBLIC_ACCESS_BLOCKED_BY_DEFAULT)&&(publicAccessBlockConfig=this.setDefaultPublicAccessBlockConfig(props.blockPublicAccess));const websiteConfiguration=this.renderWebsiteConfiguration(props);this.isWebsite=websiteConfiguration!==void 0;const objectLockConfiguration=this.parseObjectLockConfig(props),replicationConfiguration=this.renderReplicationConfiguration(props);this.replicationRoleArn=replicationConfiguration?.role,this.objectOwnership=props.objectOwnership,this.transitionDefaultMinimumObjectSize=props.transitionDefaultMinimumObjectSize;const resource=new(s3_generated_1()).CfnBucket(this,"Resource",{bucketName:this.physicalName,bucketEncryption,versioningConfiguration:props.versioned?{status:"Enabled"}:void 0,lifecycleConfiguration:core_1().Lazy.any({produce:()=>this.parseLifecycleConfiguration()}),websiteConfiguration,publicAccessBlockConfiguration:publicAccessBlockConfig,metricsConfigurations:core_1().Lazy.any({produce:()=>this.parseMetricConfiguration()}),corsConfiguration:core_1().Lazy.any({produce:()=>this.parseCorsConfiguration()}),accessControl:core_1().Lazy.string({produce:()=>this.accessControl}),loggingConfiguration:this.parseServerAccessLogs(props),inventoryConfigurations:core_1().Lazy.any({produce:()=>this.parseInventoryConfiguration()}),ownershipControls:core_1().Lazy.any({produce:()=>this.parseOwnershipControls()}),accelerateConfiguration:props.transferAcceleration?{accelerationStatus:"Enabled"}:void 0,intelligentTieringConfigurations:this.parseTieringConfig(props),objectLockEnabled:objectLockConfiguration?!0:props.objectLockEnabled,objectLockConfiguration,replicationConfiguration});if(this._resource=resource,resource.applyRemovalPolicy(props.removalPolicy),this.eventBridgeEnabled=props.eventBridgeEnabled,this.bucketName=this.getResourceNameAttribute(resource.ref),this.bucketArn=this.getResourceArnAttribute(resource.attrArn,{region:"",account:"",service:"s3",resource:this.physicalName}),this.bucketDomainName=resource.attrDomainName,this.bucketWebsiteUrl=resource.attrWebsiteUrl,this.bucketWebsiteDomainName=core_1().Fn.select(2,core_1().Fn.split("/",this.bucketWebsiteUrl)),this.bucketDualStackDomainName=resource.attrDualStackDomainName,this.bucketRegionalDomainName=resource.attrRegionalDomainName,this.disallowPublicAccess=props.blockPublicAccess&&props.blockPublicAccess.blockPublicPolicy,this.accessControl=props.accessControl,props.enforceSSL)this.enforceSSLStatement(),this.minimumTLSVersionStatement(props.minimumTLSVersion);else if(props.minimumTLSVersion)throw new(errors_1()).ValidationError("'enforceSSL' must be enabled for 'minimumTLSVersion' to be applied",this);props.serverAccessLogsBucket instanceof Bucket2?props.serverAccessLogsBucket.allowLogDelivery(this,props.serverAccessLogsPrefix):!props.serverAccessLogsBucket&&props.serverAccessLogsPrefix?this.allowLogDelivery(this,props.serverAccessLogsPrefix):props.serverAccessLogsBucket&&core_1().Annotations.of(this).addWarningV2("@aws-cdk/aws-s3:accessLogsPolicyNotAdded",`Unable to add necessary logging permissions to imported target bucket: ${props.serverAccessLogsBucket}`);for(const inventory of props.inventories??[])this.addInventory(inventory);if((props.metrics||[]).forEach(this.addMetric.bind(this)),(props.cors||[]).forEach(this.addCorsRule.bind(this)),(props.lifecycleRules||[]).forEach(this.addLifecycleRule.bind(this)),props.publicReadAccess){if(props.blockPublicAccess===void 0)throw new(errors_1()).ValidationError("Cannot use 'publicReadAccess' property on a bucket without allowing bucket-level public access through 'blockPublicAccess' property.",this);this.grantPublicAccess()}if(props.autoDeleteObjects){if(props.removalPolicy!==core_1().RemovalPolicy.DESTROY)throw new(errors_1()).ValidationError("Cannot use 'autoDeleteObjects' property on a bucket without setting removal policy to 'DESTROY'.",this);this.enableAutoDeleteObjects()}this.eventBridgeEnabled&&this.enableEventBridgeNotification()}addLifecycleRule(rule){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_s3_LifecycleRule(rule)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.addLifecycleRule),error}this.lifecycleRules.push(rule)}addMetric(metric){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_s3_BucketMetrics(metric)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.addMetric),error}this.metrics.push(metric)}addCorsRule(rule){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_s3_CorsRule(rule)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.addCorsRule),error}this.cors.push(rule)}addInventory(inventory){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_s3_Inventory(inventory)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.addInventory),error}this.inventories.push(inventory)}enforceSSLStatement(){const statement=new(iam()).PolicyStatement({actions:["s3:*"],conditions:{Bool:{"aws:SecureTransport":"false"}},effect:iam().Effect.DENY,resources:[this.bucketArn,this.arnForObjects("*")],principals:[new(iam()).AnyPrincipal]});this.addToResourcePolicy(statement)}minimumTLSVersionStatement(minimumTLSVersion){if(!minimumTLSVersion)return;const statement=new(iam()).PolicyStatement({actions:["s3:*"],conditions:{NumericLessThan:{"s3:TlsVersion":minimumTLSVersion}},effect:iam().Effect.DENY,resources:[this.bucketArn,this.arnForObjects("*")],principals:[new(iam()).AnyPrincipal]});this.addToResourcePolicy(statement)}parseEncryption(props){let encryptionType=props.encryption;if(encryptionType===void 0&&(encryptionType=props.encryptionKey?BucketEncryption.KMS:BucketEncryption.UNENCRYPTED),encryptionType!==BucketEncryption.DSSE&&encryptionType!==BucketEncryption.KMS&&props.encryptionKey)throw new(errors_1()).ValidationError(`encryptionKey is specified, so 'encryption' must be set to KMS or DSSE (value: ${encryptionType})`,this);if(props.bucketKeyEnabled&&encryptionType===BucketEncryption.UNENCRYPTED)throw new(errors_1()).ValidationError(`bucketKeyEnabled is specified, so 'encryption' must be set to KMS, DSSE or S3 (value: ${encryptionType})`,this);if(encryptionType===BucketEncryption.UNENCRYPTED)return{bucketEncryption:void 0,encryptionKey:void 0};if(encryptionType===BucketEncryption.KMS){const encryptionKey=props.encryptionKey||new(kms()).Key(this,"Key",{description:`Created by ${this.node.path}`,enableKeyRotation:!0}),bucketEncryption={serverSideEncryptionConfiguration:[{bucketKeyEnabled:props.bucketKeyEnabled,serverSideEncryptionByDefault:{sseAlgorithm:"aws:kms",kmsMasterKeyId:encryptionKey.keyArn}}]};return{encryptionKey,bucketEncryption}}if(encryptionType===BucketEncryption.S3_MANAGED)return{bucketEncryption:{serverSideEncryptionConfiguration:[{bucketKeyEnabled:props.bucketKeyEnabled,serverSideEncryptionByDefault:{sseAlgorithm:"AES256"}}]}};if(encryptionType===BucketEncryption.KMS_MANAGED)return{bucketEncryption:{serverSideEncryptionConfiguration:[{bucketKeyEnabled:props.bucketKeyEnabled,serverSideEncryptionByDefault:{sseAlgorithm:"aws:kms"}}]}};if(encryptionType===BucketEncryption.DSSE){const encryptionKey=props.encryptionKey||new(kms()).Key(this,"Key",{description:`Created by ${this.node.path}`}),bucketEncryption={serverSideEncryptionConfiguration:[{bucketKeyEnabled:props.bucketKeyEnabled,serverSideEncryptionByDefault:{sseAlgorithm:"aws:kms:dsse",kmsMasterKeyId:encryptionKey.keyArn}}]};return{encryptionKey,bucketEncryption}}if(encryptionType===BucketEncryption.DSSE_MANAGED)return{bucketEncryption:{serverSideEncryptionConfiguration:[{bucketKeyEnabled:props.bucketKeyEnabled,serverSideEncryptionByDefault:{sseAlgorithm:"aws:kms:dsse"}}]}};throw new(errors_1()).ValidationError(`Unexpected 'encryptionType': ${encryptionType}`,this)}parseLifecycleConfiguration(){if(!this.lifecycleRules||this.lifecycleRules.length===0)return;const self=this;return{rules:this.lifecycleRules.map(parseLifecycleRule),transitionDefaultMinimumObjectSize:this.transitionDefaultMinimumObjectSize};function parseLifecycleRule(rule){const enabled=rule.enabled??!0;if(rule.expiredObjectDeleteMarker&&(rule.expiration||rule.expirationDate||self.parseTagFilters(rule.tagFilters)))throw new(errors_1()).ValidationError("ExpiredObjectDeleteMarker cannot be specified with expiration, ExpirationDate, or TagFilters.",self);if(rule.abortIncompleteMultipartUploadAfter===void 0&&rule.expiration===void 0&&rule.expirationDate===void 0&&rule.expiredObjectDeleteMarker===void 0&&rule.noncurrentVersionExpiration===void 0&&rule.noncurrentVersionsToRetain===void 0&&rule.noncurrentVersionTransitions===void 0&&rule.transitions===void 0)throw new(errors_1()).ValidationError("All rules for `lifecycleRules` must have at least one of the following properties: `abortIncompleteMultipartUploadAfter`, `expiration`, `expirationDate`, `expiredObjectDeleteMarker`, `noncurrentVersionExpiration`, `noncurrentVersionsToRetain`, `noncurrentVersionTransitions`, or `transitions`",self);if(rule.transitions)for(const transition of rule.transitions){const hasTransitionDate=transition.transitionDate!==void 0,hasTransitionAfter=transition.transitionAfter!==void 0;if(!hasTransitionDate&&!hasTransitionAfter)throw new(errors_1()).ValidationError("Exactly one of transitionDate or transitionAfter must be specified in lifecycle rule transition",self);if(hasTransitionDate&&hasTransitionAfter)throw new(errors_1()).ValidationError("Exactly one of transitionDate or transitionAfter must be specified in lifecycle rule transition",self)}return{abortIncompleteMultipartUpload:rule.abortIncompleteMultipartUploadAfter!==void 0?{daysAfterInitiation:rule.abortIncompleteMultipartUploadAfter.toDays()}:void 0,expirationDate:rule.expirationDate,expirationInDays:rule.expiration?.toDays(),id:rule.id,noncurrentVersionExpiration:rule.noncurrentVersionExpiration&&{noncurrentDays:rule.noncurrentVersionExpiration.toDays(),newerNoncurrentVersions:rule.noncurrentVersionsToRetain},noncurrentVersionTransitions:mapOrUndefined(rule.noncurrentVersionTransitions,t=>({storageClass:t.storageClass.value,transitionInDays:t.transitionAfter.toDays(),newerNoncurrentVersions:t.noncurrentVersionsToRetain})),prefix:rule.prefix,status:enabled?"Enabled":"Disabled",transitions:mapOrUndefined(rule.transitions,t=>({storageClass:t.storageClass.value,transitionDate:t.transitionDate,transitionInDays:t.transitionAfter&&t.transitionAfter.toDays()})),expiredObjectDeleteMarker:rule.expiredObjectDeleteMarker,tagFilters:self.parseTagFilters(rule.tagFilters),objectSizeLessThan:rule.objectSizeLessThan,objectSizeGreaterThan:rule.objectSizeGreaterThan}}}parseServerAccessLogs(props){if(!(!props.serverAccessLogsBucket&&!props.serverAccessLogsPrefix)){if(!props.serverAccessLogsBucket&&props.encryption&&[BucketEncryption.KMS_MANAGED,BucketEncryption.DSSE_MANAGED].includes(props.encryption))throw new(errors_1()).ValidationError("Default bucket encryption with KMS managed or DSSE managed key is not supported for Server Access Logging target buckets",this);return props.serverAccessLogsBucket?.encryptionKey&&props.serverAccessLogsBucket.encryptionKey.grantEncryptDecrypt(new(iam()).ServicePrincipal("logging.s3.amazonaws.com")),{destinationBucketName:props.serverAccessLogsBucket?.bucketName,logFilePrefix:props.serverAccessLogsPrefix,targetObjectKeyFormat:props.targetObjectKeyFormat?._render()}}}parseMetricConfiguration(){if(!this.metrics||this.metrics.length===0)return;const self=this;return this.metrics.map(parseMetric);function parseMetric(metric){return{id:metric.id,prefix:metric.prefix,tagFilters:self.parseTagFilters(metric.tagFilters)}}}parseCorsConfiguration(){if(!this.cors||this.cors.length===0)return;return{corsRules:this.cors.map(parseCors)};function parseCors(rule){return{id:rule.id,maxAge:rule.maxAge,allowedHeaders:rule.allowedHeaders,allowedMethods:rule.allowedMethods,allowedOrigins:rule.allowedOrigins,exposedHeaders:rule.exposedHeaders}}}parseTagFilters(tagFilters){if(!(!tagFilters||tagFilters.length===0))return Object.keys(tagFilters).map(tag=>({key:tag,value:tagFilters[tag]}))}parseOwnershipControls(){const aclsThatDoNotRequireObjectOwnership=[BucketAccessControl.PRIVATE,BucketAccessControl.BUCKET_OWNER_READ,BucketAccessControl.BUCKET_OWNER_FULL_CONTROL],accessControlRequiresObjectOwnership=this.accessControl&&!aclsThatDoNotRequireObjectOwnership.includes(this.accessControl);if(!(!this.objectOwnership&&!accessControlRequiresObjectOwnership)){if(accessControlRequiresObjectOwnership&&this.objectOwnership===ObjectOwnership.BUCKET_OWNER_ENFORCED)throw new(errors_1()).ValidationError(`objectOwnership must be set to "${ObjectOwnership.OBJECT_WRITER}" when accessControl is "${this.accessControl}"`,this);return{rules:[{objectOwnership:this.objectOwnership??ObjectOwnership.OBJECT_WRITER}]}}}parseTieringConfig({intelligentTieringConfigurations}){if(intelligentTieringConfigurations)return intelligentTieringConfigurations.map(config=>{const tierings=[];return config.archiveAccessTierTime&&tierings.push({accessTier:"ARCHIVE_ACCESS",days:config.archiveAccessTierTime.toDays({integral:!0})}),config.deepArchiveAccessTierTime&&tierings.push({accessTier:"DEEP_ARCHIVE_ACCESS",days:config.deepArchiveAccessTierTime.toDays({integral:!0})}),{id:config.name,prefix:config.prefix,status:"Enabled",tagFilters:config.tags,tierings}})}parseObjectLockConfig(props){const{objectLockEnabled,objectLockDefaultRetention}=props;if(objectLockDefaultRetention){if(objectLockEnabled===!1&&objectLockDefaultRetention)throw new(errors_1()).ValidationError("Object Lock must be enabled to configure default retention settings",this);return{objectLockEnabled:"Enabled",rule:{defaultRetention:{days:objectLockDefaultRetention.duration.toDays(),mode:objectLockDefaultRetention.mode}}}}}renderWebsiteConfiguration(props){if(!props.websiteErrorDocument&&!props.websiteIndexDocument&&!props.websiteRedirect&&!props.websiteRoutingRules)return;if(props.websiteErrorDocument&&!props.websiteIndexDocument)throw new(errors_1()).ValidationError('"websiteIndexDocument" is required if "websiteErrorDocument" is set',this);if(props.websiteRedirect&&(props.websiteErrorDocument||props.websiteIndexDocument||props.websiteRoutingRules))throw new(errors_1()).ValidationError('"websiteIndexDocument", "websiteErrorDocument" and, "websiteRoutingRules" cannot be set if "websiteRedirect" is used',this);const routingRules=props.websiteRoutingRules?props.websiteRoutingRules.map(rule=>{if(rule.condition&&rule.condition.httpErrorCodeReturnedEquals==null&&rule.condition.keyPrefixEquals==null)throw new(errors_1()).ValidationError("The condition property cannot be an empty object",this);return{redirectRule:{hostName:rule.hostName,httpRedirectCode:rule.httpRedirectCode,protocol:rule.protocol,replaceKeyWith:rule.replaceKey&&rule.replaceKey.withKey,replaceKeyPrefixWith:rule.replaceKey&&rule.replaceKey.prefixWithKey},routingRuleCondition:rule.condition}}):void 0;return{indexDocument:props.websiteIndexDocument,errorDocument:props.websiteErrorDocument,redirectAllRequestsTo:props.websiteRedirect,routingRules}}renderReplicationConfiguration(props){const replicationRulesIsEmpty=!props.replicationRules||props.replicationRules.length===0;if(replicationRulesIsEmpty&&props.replicationRole)throw new(errors_1()).ValidationError("cannot specify replicationRole when replicationRules is empty",this);if(replicationRulesIsEmpty)return;if(!props.versioned)throw new(errors_1()).ValidationError("Replication rules require versioning to be enabled on the bucket",this);if(props.replicationRules.length>1&&props.replicationRules.some(rule=>rule.priority===void 0))throw new(errors_1()).ValidationError("'priority' must be specified for all replication rules when there are multiple rules",this);props.replicationRules.forEach(rule=>{if(rule.replicationTimeControl&&!rule.metrics)throw new(errors_1()).ValidationError("'replicationTimeControlMetrics' must be enabled when 'replicationTimeControl' is enabled.",this);if(rule.deleteMarkerReplication&&rule.filter?.tags)throw new(errors_1()).ValidationError("tag filter cannot be specified when 'deleteMarkerReplication' is enabled.",this)});let replicationRole;return props.replicationRole?replicationRole=props.replicationRole:(replicationRole=new(iam()).Role(this,"ReplicationRole",{assumedBy:new(iam()).ServicePrincipal("s3.amazonaws.com"),roleName:core_1().FeatureFlags.of(this).isEnabled(cxapi().SET_UNIQUE_REPLICATION_ROLE_NAME)?core_1().PhysicalName.GENERATE_IF_NEEDED:"CDKReplicationRole"}),this.grantReplicationPermission(replicationRole,{sourceDecryptionKey:props.encryptionKey,destinations:props.replicationRules.map(rule=>({encryptionKey:rule.kmsKey,bucket:rule.destination}))})),{role:replicationRole.roleArn,rules:props.replicationRules.map(rule=>{const sourceSelectionCriteria=rule.replicaModifications!==void 0||rule.sseKmsEncryptedObjects!==void 0?{replicaModifications:rule.replicaModifications!==void 0?{status:rule.replicaModifications?"Enabled":"Disabled"}:void 0,sseKmsEncryptedObjects:rule.sseKmsEncryptedObjects!==void 0?{status:rule.sseKmsEncryptedObjects?"Enabled":"Disabled"}:void 0}:void 0,isAndFilter=rule.filter?.tags&&rule.filter.tags.length>0,prefix=rule.filter?.prefix??"",filter=isAndFilter?{and:{prefix,tagFilters:rule.filter?.tags}}:{prefix},sourceAccount=core_1().Stack.of(this).account,destinationAccount=rule.destination.env.account,isCrossAccount=sourceAccount!==destinationAccount;if(isCrossAccount)core_1().Annotations.of(this).addInfo("For Cross-account S3 replication, ensure to set up permissions on destination bucket using method addReplicationPolicy() ");else if(rule.accessControlTransition)throw new(errors_1()).ValidationError("accessControlTranslation is only supported for cross-account replication",this);return{id:rule.id,priority:rule.priority,status:"Enabled",destination:{bucket:rule.destination.bucketArn,account:isCrossAccount?destinationAccount:void 0,storageClass:rule.storageClass?.toString(),accessControlTranslation:rule.accessControlTransition?{owner:"Destination"}:void 0,encryptionConfiguration:rule.kmsKey?{replicaKmsKeyId:rule.kmsKey.keyArn}:void 0,replicationTime:rule.replicationTimeControl!==void 0?{status:"Enabled",time:{minutes:rule.replicationTimeControl.minutes}}:void 0,metrics:rule.metrics!==void 0?{status:"Enabled",eventThreshold:{minutes:rule.metrics.minutes}}:void 0},filter,deleteMarkerReplication:{status:rule.deleteMarkerReplication?"Enabled":"Disabled"},sourceSelectionCriteria}})}}allowLogDelivery(from,prefix){if(core_1().FeatureFlags.of(this).isEnabled(cxapi().S3_SERVER_ACCESS_LOGS_USE_BUCKET_POLICY)){let conditions;from instanceof Bucket2&&core_1().Stack.of(this)===core_1().Stack.of(from)&&(conditions={ArnLike:{"aws:SourceArn":from.bucketArn},StringEquals:{"aws:SourceAccount":from.env.account}}),this.addToResourcePolicy(new(iam()).PolicyStatement({effect:iam().Effect.ALLOW,principals:[new(iam()).ServicePrincipal("logging.s3.amazonaws.com")],actions:["s3:PutObject"],resources:[this.arnForObjects(prefix?`${prefix}*`:"*")],conditions}))}else{if(this.accessControl&&this.accessControl!==BucketAccessControl.LOG_DELIVERY_WRITE)throw new(errors_1()).ValidationError("Cannot enable log delivery to this bucket because the bucket's ACL has been set and can't be changed",this);this.accessControl=BucketAccessControl.LOG_DELIVERY_WRITE}}parseInventoryConfiguration(){if(!this.inventories||this.inventories.length===0)return;const inventoryIdValidationRegex=/[^\w\.\-]/g;return this.inventories.map((inventory,index)=>{const format=inventory.format??InventoryFormat.CSV,frequency=inventory.frequency??InventoryFrequency.WEEKLY;if(inventory.inventoryId!==void 0&&(inventory.inventoryId.length>64||inventoryIdValidationRegex.test(inventory.inventoryId)))throw new(errors_1()).ValidationError(`inventoryId should not exceed 64 characters and should not contain special characters except . and -, got ${inventory.inventoryId}`,this);const id=inventory.inventoryId??`${this.node.id}Inventory${index}`.replace(inventoryIdValidationRegex,"").slice(-64);return inventory.destination.bucket instanceof Bucket2&&inventory.destination.bucket.addToResourcePolicy(new(iam()).PolicyStatement({effect:iam().Effect.ALLOW,actions:["s3:PutObject"],resources:[inventory.destination.bucket.bucketArn,inventory.destination.bucket.arnForObjects(`${inventory.destination.prefix??""}*`)],principals:[new(iam()).ServicePrincipal("s3.amazonaws.com")],conditions:{ArnLike:{"aws:SourceArn":this.bucketArn}}})),{id,destination:{bucketArn:inventory.destination.bucket.bucketArn,bucketAccountId:inventory.destination.bucketOwner,prefix:inventory.destination.prefix,format},enabled:inventory.enabled??!0,includedObjectVersions:inventory.includeObjectVersions??InventoryObjectVersion.ALL,scheduleFrequency:frequency,optionalFields:inventory.optionalFields,prefix:inventory.objectsPrefix}})}enableAutoDeleteObjects(){const provider=auto_delete_objects_provider_generated_1().AutoDeleteObjectsProvider.getOrCreateProvider(this,AUTO_DELETE_OBJECTS_RESOURCE_TYPE,{useCfnResponseWrapper:!1,description:`Lambda function for auto-deleting objects in ${this.bucketName} S3 bucket.`});this.addToResourcePolicy(new(iam()).PolicyStatement({actions:[...perms().BUCKET_PUT_POLICY_ACTIONS,...perms().BUCKET_READ_METADATA_ACTIONS,...perms().BUCKET_DELETE_ACTIONS],resources:[this.bucketArn,this.arnForObjects("*")],principals:[new(iam()).ArnPrincipal(provider.roleArn)]}));const customResource=new(core_1()).CustomResource(this,"AutoDeleteObjectsCustomResource",{resourceType:AUTO_DELETE_OBJECTS_RESOURCE_TYPE,serviceToken:provider.serviceToken,properties:{BucketName:this.bucketName}});this.policy&&customResource.node.addDependency(this.policy),core_1().Tags.of(this._resource).add(AUTO_DELETE_OBJECTS_TAG,"true")}setDefaultPublicAccessBlockConfig(blockPublicAccessOptions){return{blockPublicAcls:blockPublicAccessOptions.blockPublicAcls??!0,blockPublicPolicy:blockPublicAccessOptions.blockPublicPolicy??!0,ignorePublicAcls:blockPublicAccessOptions.ignorePublicAcls??!0,restrictPublicBuckets:blockPublicAccessOptions.restrictPublicBuckets??!0}}static{__runInitializers(_classThis,_classExtraInitializers)}};return Bucket2=_classThis})();exports.Bucket=Bucket;var BucketEncryption;(function(BucketEncryption2){BucketEncryption2.UNENCRYPTED="UNENCRYPTED",BucketEncryption2.KMS_MANAGED="KMS_MANAGED",BucketEncryption2.S3_MANAGED="S3_MANAGED",BucketEncryption2.KMS="KMS",BucketEncryption2.DSSE_MANAGED="DSSE_MANAGED",BucketEncryption2.DSSE="DSSE"})(BucketEncryption||(exports.BucketEncryption=BucketEncryption={}));var EventType;(function(EventType2){EventType2.OBJECT_CREATED="s3:ObjectCreated:*",EventType2.OBJECT_CREATED_PUT="s3:ObjectCreated:Put",EventType2.OBJECT_CREATED_POST="s3:ObjectCreated:Post",EventType2.OBJECT_CREATED_COPY="s3:ObjectCreated:Copy",EventType2.OBJECT_CREATED_COMPLETE_MULTIPART_UPLOAD="s3:ObjectCreated:CompleteMultipartUpload",EventType2.OBJECT_REMOVED="s3:ObjectRemoved:*",EventType2.OBJECT_REMOVED_DELETE="s3:ObjectRemoved:Delete",EventType2.OBJECT_REMOVE