UNPKG

aws-cdk-lib

Version:

Version 2 of the AWS Cloud Development Kit library

1 lines 51 kB
"use strict";var __decorate=exports&&exports.__decorate||function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r},_a,_b,_c,_d,_e,_f,_g;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_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},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{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()??[]})}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.grant(identity,perms().BUCKET_READ_ACTIONS,perms().KEY_READ_ACTIONS,this.bucketArn,this.arnForObjects(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}const grantedWriteActions=allowedActionPatterns.length>0?allowedActionPatterns:this.writeActions;return this.grant(identity,grantedWriteActions,perms().KEY_WRITE_ACTIONS,this.bucketArn,this.arnForObjects(objectsKeyPattern))}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.grant(identity,this.putActions,perms().KEY_WRITE_ACTIONS,this.arnForObjects(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.grant(identity,perms().BUCKET_PUT_ACL_ACTIONS,[],this.arnForObjects(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.grant(identity,perms().BUCKET_DELETE_ACTIONS,[],this.arnForObjects(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}const bucketActions=perms().BUCKET_READ_ACTIONS.concat(this.writeActions),keyActions=[...new Set([...perms().KEY_READ_ACTIONS,...perms().KEY_WRITE_ACTIONS])];return this.grant(identity,bucketActions,keyActions,this.bucketArn,this.arnForObjects(objectsKeyPattern))}grantPublicAccess(keyPrefix="*",...allowedActions){if(this.disallowPublicAccess)throw new(errors_1()).ValidationError("Cannot grant public access when 'blockPublicPolicy' is enabled",this);return allowedActions=allowedActions.length>0?allowedActions:["s3:GetObject"],iam().Grant.addToPrincipalOrResource({actions:allowedActions,resourceArns:[this.arnForObjects(keyPrefix)],grantee:new(iam()).AnyPrincipal,resource:this})}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)}.`)}get writeActions(){return[...perms().BUCKET_DELETE_ACTIONS,...this.putActions]}get putActions(){return core_1().FeatureFlags.of(this).isEnabled(cxapi().S3_GRANT_WRITE_WITHOUT_ACL)?perms().BUCKET_PUT_ACTIONS:perms().LEGACY_BUCKET_PUT_ACTIONS}urlJoin(...components){return components.reduce((result,component)=>(result.endsWith("/")&&(result=result.slice(0,-1)),component.startsWith("/")&&(component=component.slice(1)),`${result}/${component}`))}grant(grantee,bucketActions,keyActions,resourceArn,...otherResourceArns){const resources=[resourceArn,...otherResourceArns],ret=iam().Grant.addToPrincipalOrResource({grantee,actions:bucketActions,resourceArns:resources,resource:this});return this.encryptionKey&&keyActions&&keyActions.length!==0&&this.encryptionKey.grant(grantee,...keyActions),ret}}exports.BucketBase=BucketBase,_a=JSII_RTTI_SYMBOL_1,BucketBase[_a]={fqn:"aws-cdk-lib.aws_s3.BucketBase",version:"2.185.0"};class BlockPublicAccess{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,_b=JSII_RTTI_SYMBOL_1,BlockPublicAccess[_b]={fqn:"aws-cdk-lib.aws_s3.BlockPublicAccess",version:"2.185.0"},BlockPublicAccess.BLOCK_ALL=new BlockPublicAccess({blockPublicAcls:!0,blockPublicPolicy:!0,ignorePublicAcls:!0,restrictPublicBuckets:!0}),BlockPublicAccess.BLOCK_ACLS=new BlockPublicAccess({blockPublicAcls:!0,ignorePublicAcls:!0});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 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,_c=JSII_RTTI_SYMBOL_1,TargetObjectKeyFormat[_c]={fqn:"aws-cdk-lib.aws_s3.TargetObjectKeyFormat",version:"2.185.0"};class ReplicationTimeValue{constructor(minutes){this.minutes=minutes}}exports.ReplicationTimeValue=ReplicationTimeValue,_d=JSII_RTTI_SYMBOL_1,ReplicationTimeValue[_d]={fqn:"aws-cdk-lib.aws_s3.ReplicationTimeValue",version:"2.185.0"},ReplicationTimeValue.FIFTEEN_MINUTES=new ReplicationTimeValue(15);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={}));class Bucket extends BucketBase{static fromBucketArn(scope,id,bucketArn){return Bucket.fromBucketAttributes(scope,id,{bucketArn})}static fromBucketName(scope,id,bucketName){return Bucket.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);Bucket.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{constructor(){super(...arguments),this.bucketName=bucketName,this.bucketArn=(0,util_1().parseBucketArn)(scope,attrs),this.bucketDomainName=attrs.bucketDomainName||`${bucketName}.s3.${urlSuffix}`,this.bucketWebsiteUrl=attrs.bucketWebsiteUrl||`http://${websiteDomain}`,this.bucketWebsiteDomainName=attrs.bucketWebsiteUrl?core_1().Fn.select(2,core_1().Fn.split("/",attrs.bucketWebsiteUrl)):websiteDomain,this.bucketRegionalDomainName=attrs.bucketRegionalDomainName||`${bucketName}.s3.${region}.${urlSuffix}`,this.bucketDualStackDomainName=attrs.bucketDualStackDomainName||`${bucketName}.s3.dualstack.${region}.${urlSuffix}`,this.bucketWebsiteNewUrlFormat=attrs.bucketWebsiteNewUrlFormat??!1,this.encryptionKey=attrs.encryptionKey,this.isWebsite=attrs.isWebsite??!1,this.policy=void 0,this.replicationRoleArn=void 0,this.autoCreatePolicy=!1,this.disallowPublicAccess=!1,this.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{constructor(){super(cfnBucket,id),this.bucketArn=cfnBucket.attrArn,this.bucketName=cfnBucket.ref,this.bucketDomainName=cfnBucket.attrDomainName,this.bucketDualStackDomainName=cfnBucket.attrDualStackDomainName,this.bucketRegionalDomainName=cfnBucket.attrRegionalDomainName,this.bucketWebsiteUrl=cfnBucket.attrWebsiteUrl,this.bucketWebsiteDomainName=core_1().Fn.select(2,core_1().Fn.split("/",cfnBucket.attrWebsiteUrl)),this.encryptionKey=encryptionKey,this.isWebsite=cfnBucket.websiteConfiguration!==void 0,this.policy=void 0,this.replicationRoleArn=void 0,this.autoCreatePolicy=!0,this.disallowPublicAccess=cfnBucket.publicAccessBlockConfiguration&&cfnBucket.publicAccessBlockConfiguration.blockPublicPolicy,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)}`)}constructor(scope,id,props={}){super(scope,id,{physicalName:props.bucketName}),this.autoCreatePolicy=!0,this.lifecycleRules=[],this.metrics=[],this.cors=[],this.inventories=[];try{jsiiDeprecationWarnings().aws_cdk_lib_aws_s3_BucketProps(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,Bucket),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,Bucket.validateBucketName(this.physicalName);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:props.blockPublicAccess,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 Bucket?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){if(!props.replicationRules||props.replicationRules.length===0)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)});const destinationBuckets=props.replicationRules.map(rule=>rule.destination),kmsKeys=props.replicationRules.map(rule=>rule.kmsKey).filter(kmsKey=>kmsKey!==void 0),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"});return replicationRole.addToPrincipalPolicy(new(iam()).PolicyStatement({actions:["s3:GetReplicationConfiguration","s3:ListBucket"],resources:[core_1().Lazy.string({produce:()=>this.bucketArn})],effect:iam().Effect.ALLOW})),replicationRole.addToPrincipalPolicy(new(iam()).PolicyStatement({actions:["s3:GetObjectVersionForReplication","s3:GetObjectVersionAcl","s3:GetObjectVersionTagging"],resources:[core_1().Lazy.string({produce:()=>this.arnForObjects("*")})],effect:iam().Effect.ALLOW})),destinationBuckets.length>0&&replicationRole.addToPrincipalPolicy(new(iam()).PolicyStatement({actions:["s3:ReplicateObject","s3:ReplicateDelete","s3:ReplicateTags","s3:ObjectOwnerOverrideToBucketOwner"],resources:destinationBuckets.map(bucket=>bucket.arnForObjects("*")),effect:iam().Effect.ALLOW})),kmsKeys.forEach(kmsKey=>{kmsKey.grantEncrypt(replicationRole)}),this.encryptionKey?.grantDecrypt(replicationRole),{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 Bucket&&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 Bucket&&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")}}exports.Bucket=Bucket,_e=JSII_RTTI_SYMBOL_1,Bucket[_e]={fqn:"aws-cdk-lib.aws_s3.Bucket",version:"2.185.0"},__decorate([(0,metadata_resource_1().MethodMetadata)()],Bucket.prototype,"addLifecycleRule",null),__decorate([(0,metadata_resource_1().MethodMetadata)()],Bucket.prototype,"addMetric",null),__decorate([(0,metadata_resource_1().MethodMetadata)()],Bucket.prototype,"addCorsRule",null),__decorate([(0,metadata_resource_1().MethodMetadata)()],Bucket.prototype,"addInventory",null);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_REMOVED_DELETE_MARKER_CREATED="s3:ObjectRemoved:DeleteMarkerCreated",EventType2.OBJECT_RESTORE_POST="s3:ObjectRestore:Post",EventType2.OBJECT_RESTORE_COMPLETED="s3:ObjectRestore:Completed",EventType2.OBJECT_RESTORE_DELETE="s3:ObjectRestore:Delete",EventType2.REDUCED_REDUNDANCY_LOST_OBJECT="s3:ReducedRedundancyLostObject",EventType2.REPLICATION_OPERATION_FAILED_REPLICATION="s3:Replication:OperationFailedReplication",EventType2.REPLICATION_OPERATION_MISSED_THRESHOLD="s3:Replication:OperationMissedThreshold",EventType2.REPLICATION_OPERATION_REPLICATED_AFTER_THRESHOLD="s3:Replication:OperationReplicatedAfterThreshold",EventType2.REPLICATION_OPERATION_NOT_TRACKED="s3:Replication:OperationNotTracked",EventType2.LIFECYCLE_EXPIRATION="s3:LifecycleExpiration:*",EventType2.LIFECYCLE_EXPIRATION_DELETE="s3:LifecycleExpiration:Delete",EventType2.LIFECYCLE_EXPIRATION_DELETE_MARKER_CREATED="s3:LifecycleExpiration:DeleteMarkerCreated",EventType2.LIFECYCLE_TRANSITION="s3:LifecycleTransition",EventType2.INTELLIGENT_TIERING="s3:IntelligentTiering",EventType2.OBJECT_TAGGING="s3:ObjectTagging:*",EventType2.OBJECT_TAGGING_PUT="s3:ObjectTagging:Put",EventType2.OBJECT_TAGGING_DELETE="s3:ObjectTagging:Delete",EventType2.OBJECT_ACL_PUT="s3:ObjectAcl:Put",EventType2.OBJECT_RESTORE="s3:ObjectRestore:*",EventType2.REPLICATION="s3:Replication:*"})(EventType||(exports.EventType=EventType={}));var BucketAccessControl;(function(BucketAccessControl2){BucketAccessControl2.PRIVATE="Private",BucketAccessControl2.PUBLIC_READ="PublicRead",BucketAccessControl2.PUBLIC_READ_WRITE="PublicReadWrite",BucketAccessControl2.AUTHENTICATED_READ="AuthenticatedRead",BucketAccessControl2.LOG_DELIVERY_WRITE="LogDeliveryWrite",BucketAccessControl2.BUCKET_OWNER_READ="BucketOwnerRead",BucketAccessControl2.BUCKET_OWNER_FULL_CONTROL="BucketOwnerFullControl",BucketAccessControl2.AWS_EXEC_READ="AwsExecRead"})(BucketAccessControl||(exports.BucketAccessControl=BucketAccessControl={}));class ReplaceKey{static with(keyReplacement){return new this(keyReplacement)}static prefixWith(keyReplacement){return new this(void 0,keyReplacement)}constructor(withKey,prefixWithKey){this.withKey=withKey,this.prefixWithKey=prefixWithKey}}exports.ReplaceKey=ReplaceKey,_f=JSII_RTTI_SYMBOL_1,ReplaceKey[_f]={fqn:"aws-cdk-lib.aws_s3.ReplaceKey",version:"2.185.0"};var ObjectLockMode;(function(ObjectLockMode2){ObjectLockMode2.GOVERNANCE="GOVERNANCE",ObjectLockMode2.COMPLIANCE="COMPLIANCE"})(ObjectLockMode||(exports.ObjectLockMode=ObjectLockMode={}));class ObjectLockRetention{static governance(duration){try{jsiiDeprecationWarnings().aws_cdk_lib_Duration(duration)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.governan