aws-cdk-lib
Version:
Version 2 of the AWS Cloud Development Kit library
2 lines (1 loc) • 39.7 kB
JavaScript
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,Table_1;Object.defineProperty(exports,"__esModule",{value:!0}),exports.Table=exports.TableBase=exports.ApproximateCreationDateTimePrecision=exports.InputFormat=exports.InputCompressionType=void 0;var jsiiDeprecationWarnings=()=>{var tmp=require("../../.warnings.jsii.js");return jsiiDeprecationWarnings=()=>tmp,tmp};const JSII_RTTI_SYMBOL_1=Symbol.for("jsii.rtti");var constructs_1=()=>{var tmp=require("constructs");return constructs_1=()=>tmp,tmp},dynamodb_canned_metrics_generated_1=()=>{var tmp=require("./dynamodb-canned-metrics.generated");return dynamodb_canned_metrics_generated_1=()=>tmp,tmp},dynamodb_generated_1=()=>{var tmp=require("./dynamodb.generated");return dynamodb_generated_1=()=>tmp,tmp},perms=()=>{var tmp=require("./perms");return perms=()=>tmp,tmp},replica_provider_1=()=>{var tmp=require("./replica-provider");return replica_provider_1=()=>tmp,tmp},scalable_table_attribute_1=()=>{var tmp=require("./scalable-table-attribute");return scalable_table_attribute_1=()=>tmp,tmp},shared_1=()=>{var tmp=require("./shared");return shared_1=()=>tmp,tmp},appscaling=()=>{var tmp=require("../../aws-applicationautoscaling");return appscaling=()=>tmp,tmp},cloudwatch=()=>{var tmp=require("../../aws-cloudwatch");return cloudwatch=()=>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},prop_injectable_1=()=>{var tmp=require("../../core/lib/prop-injectable");return prop_injectable_1=()=>tmp,tmp},cx_api_1=()=>{var tmp=require("../../cx-api");return cx_api_1=()=>tmp,tmp};const HASH_KEY_TYPE="HASH",RANGE_KEY_TYPE="RANGE",MAX_LOCAL_SECONDARY_INDEX_COUNT=5;var InputCompressionType;(function(InputCompressionType2){InputCompressionType2.GZIP="GZIP",InputCompressionType2.ZSTD="ZSTD",InputCompressionType2.NONE="NONE"})(InputCompressionType||(exports.InputCompressionType=InputCompressionType={}));class InputFormat{static dynamoDBJson(){return new class extends InputFormat{_render(){return{inputFormat:"DYNAMODB_JSON"}}}}static ion(){return new class extends InputFormat{_render(){return{inputFormat:"ION"}}}}static csv(options){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_dynamodb_CsvOptions(options)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.csv),error}if(options?.delimiter&&(!this.validCsvDelimiters.includes(options.delimiter)||options.delimiter.length!==1))throw new(errors_1()).UnscopedValidationError(["Delimiter must be a single character and one of the following:",`${this.readableValidCsvDelimiters.join(", ")},`,`got '${options.delimiter}'`].join(" "));return new class extends InputFormat{_render(){return{inputFormat:"CSV",inputFormatOptions:{csv:{delimiter:options?.delimiter,headerList:options?.headerList}}}}}}}exports.InputFormat=InputFormat,_a=JSII_RTTI_SYMBOL_1,InputFormat[_a]={fqn:"aws-cdk-lib.aws_dynamodb.InputFormat",version:"2.202.0"},InputFormat.validCsvDelimiters=[","," ",":",";","|"," "],InputFormat.readableValidCsvDelimiters=["comma (,)","tab (\\t)","colon (:)","semicolon (;)","pipe (|)","space ( )"];var ApproximateCreationDateTimePrecision;(function(ApproximateCreationDateTimePrecision2){ApproximateCreationDateTimePrecision2.MILLISECOND="MILLISECOND",ApproximateCreationDateTimePrecision2.MICROSECOND="MICROSECOND"})(ApproximateCreationDateTimePrecision||(exports.ApproximateCreationDateTimePrecision=ApproximateCreationDateTimePrecision={}));class TableBase extends core_1().Resource{constructor(){super(...arguments),this.regionalArns=new Array}grant(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.grant),error}return iam().Grant.addToPrincipalOrResource({grantee,actions,resourceArns:[this.tableArn,core_1().Lazy.string({produce:()=>this.hasIndex?`${this.tableArn}/index/*`:core_1().Aws.NO_VALUE}),...this.regionalArns,...this.regionalArns.map(arn=>core_1().Lazy.string({produce:()=>this.hasIndex?`${arn}/index/*`:core_1().Aws.NO_VALUE}))],resource:this})}grantStream(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.grantStream),error}if(!this.tableStreamArn)throw new(errors_1()).ValidationError(`DynamoDB Streams must be enabled on the table ${this.node.path}`,this);return iam().Grant.addToPrincipal({grantee,actions,resourceArns:[this.tableStreamArn],scope:this})}grantReadData(grantee){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_IGrantable(grantee)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.grantReadData),error}const tableActions=perms().READ_DATA_ACTIONS.concat(perms().DESCRIBE_TABLE);return this.combinedGrant(grantee,{keyActions:perms().KEY_READ_ACTIONS,tableActions})}grantTableListStreams(grantee){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_IGrantable(grantee)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.grantTableListStreams),error}if(!this.tableStreamArn)throw new(errors_1()).ValidationError(`DynamoDB Streams must be enabled on the table ${this.node.path}`,this);return iam().Grant.addToPrincipal({grantee,actions:["dynamodb:ListStreams"],resourceArns:["*"]})}grantStreamRead(grantee){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_IGrantable(grantee)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.grantStreamRead),error}return this.grantTableListStreams(grantee),this.combinedGrant(grantee,{keyActions:perms().KEY_READ_ACTIONS,streamActions:perms().READ_STREAM_DATA_ACTIONS})}grantWriteData(grantee){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_IGrantable(grantee)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.grantWriteData),error}const tableActions=perms().WRITE_DATA_ACTIONS.concat(perms().DESCRIBE_TABLE),keyActions=perms().KEY_READ_ACTIONS.concat(perms().KEY_WRITE_ACTIONS);return this.combinedGrant(grantee,{keyActions,tableActions})}grantReadWriteData(grantee){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_IGrantable(grantee)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.grantReadWriteData),error}const tableActions=perms().READ_DATA_ACTIONS.concat(perms().WRITE_DATA_ACTIONS).concat(perms().DESCRIBE_TABLE),keyActions=perms().KEY_READ_ACTIONS.concat(perms().KEY_WRITE_ACTIONS);return this.combinedGrant(grantee,{keyActions,tableActions})}grantFullAccess(grantee){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_IGrantable(grantee)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.grantFullAccess),error}const keyActions=perms().KEY_READ_ACTIONS.concat(perms().KEY_WRITE_ACTIONS);return this.combinedGrant(grantee,{keyActions,tableActions:["dynamodb:*"]})}addToResourcePolicy(statement){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_PolicyStatement(statement)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.addToResourcePolicy),error}return this.resourcePolicy=this.resourcePolicy??new(iam()).PolicyDocument({statements:[]}),this.resourcePolicy.addStatements(statement),{statementAdded:!0,policyDependable:this}}metric(metricName,props){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_cloudwatch_MetricOptions(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.metric),error}return new(cloudwatch()).Metric({namespace:"AWS/DynamoDB",metricName,dimensionsMap:{TableName:this.tableName},...props}).attachTo(this)}metricConsumedReadCapacityUnits(props){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_cloudwatch_MetricOptions(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.metricConsumedReadCapacityUnits),error}return this.cannedMetric(dynamodb_canned_metrics_generated_1().DynamoDBMetrics.consumedReadCapacityUnitsSum,props)}metricConsumedWriteCapacityUnits(props){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_cloudwatch_MetricOptions(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.metricConsumedWriteCapacityUnits),error}return this.cannedMetric(dynamodb_canned_metrics_generated_1().DynamoDBMetrics.consumedWriteCapacityUnitsSum,props)}metricSystemErrors(props){try{jsiiDeprecationWarnings().print("aws-cdk-lib.aws_dynamodb.TableBase#metricSystemErrors","use `metricSystemErrorsForOperations`."),jsiiDeprecationWarnings().aws_cdk_lib_aws_cloudwatch_MetricOptions(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.metricSystemErrors),error}if(!props?.dimensions?.Operation&&!props?.dimensionsMap?.Operation)throw new(errors_1()).ValidationError("'Operation' dimension must be passed for the 'SystemErrors' metric.",this);const dimensionsMap={TableName:this.tableName,...props?.dimensions??{},...props?.dimensionsMap??{}};return this.metric("SystemErrors",{statistic:"sum",...props,dimensionsMap})}metricUserErrors(props){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_cloudwatch_MetricOptions(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.metricUserErrors),error}if(props?.dimensions)throw new(errors_1()).ValidationError("'dimensions' is not supported for the 'UserErrors' metric",this);return this.metric("UserErrors",{statistic:"sum",...props,dimensionsMap:{}})}metricConditionalCheckFailedRequests(props){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_cloudwatch_MetricOptions(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.metricConditionalCheckFailedRequests),error}return this.metric("ConditionalCheckFailedRequests",{statistic:"sum",...props})}metricThrottledRequests(props){try{jsiiDeprecationWarnings().print("aws-cdk-lib.aws_dynamodb.TableBase#metricThrottledRequests","Do not use this function. It returns an invalid metric. Use `metricThrottledRequestsForOperation` instead."),jsiiDeprecationWarnings().aws_cdk_lib_aws_cloudwatch_MetricOptions(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.metricThrottledRequests),error}return this.metric("ThrottledRequests",{statistic:"sum",...props})}metricSuccessfulRequestLatency(props){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_cloudwatch_MetricOptions(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.metricSuccessfulRequestLatency),error}if(!props?.dimensions?.Operation&&!props?.dimensionsMap?.Operation)throw new(errors_1()).ValidationError("'Operation' dimension must be passed for the 'SuccessfulRequestLatency' metric.",this);const dimensionsMap={TableName:this.tableName,Operation:props.dimensionsMap?.Operation??props.dimensions?.Operation};return new(cloudwatch()).Metric({...dynamodb_canned_metrics_generated_1().DynamoDBMetrics.successfulRequestLatencyAverage(dimensionsMap),...props,dimensionsMap}).attachTo(this)}metricThrottledRequestsForOperation(operation,props){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_cloudwatch_MetricOptions(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.metricThrottledRequestsForOperation),error}return new(cloudwatch()).Metric({...dynamodb_canned_metrics_generated_1().DynamoDBMetrics.throttledRequestsSum({Operation:operation,TableName:this.tableName}),...props}).attachTo(this)}metricThrottledRequestsForOperations(props){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_dynamodb_OperationsMetricOptions(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.metricThrottledRequestsForOperations),error}return this.sumMetricsForOperations("ThrottledRequests","Sum of throttled requests across all operations",props)}metricSystemErrorsForOperations(props){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_dynamodb_SystemErrorsForOperationsMetricOptions(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.metricSystemErrorsForOperations),error}return this.sumMetricsForOperations("SystemErrors","Sum of errors across all operations",props)}sumMetricsForOperations(metricName,expressionLabel,props){if(props?.dimensions?.Operation)throw new(errors_1()).ValidationError("The Operation dimension is not supported. Use the 'operations' property.",this);const operations=props?.operations??Object.values(shared_1().Operation),values=this.createMetricsForOperations(metricName,operations,{statistic:"sum",...props});return new(cloudwatch()).MathExpression({expression:`${Object.keys(values).join(" + ")}`,usingMetrics:{...values},color:props?.color,label:expressionLabel,period:props?.period})}createMetricsForOperations(metricName,operations,props,metricNameMapper){const metrics={},mapper=metricNameMapper??(op=>op.toLowerCase());if(props?.dimensions?.Operation)throw new(errors_1()).ValidationError("Invalid properties. Operation dimension is not supported when calculating operational metrics",this);for(const operation of operations){const metric=this.metric(metricName,{...props,dimensionsMap:{TableName:this.tableName,Operation:operation,...props?.dimensions}}),operationMetricName=mapper(operation),firstChar=operationMetricName.charAt(0);if(firstChar===firstChar.toUpperCase())throw new(errors_1()).ValidationError(`Mapper generated an illegal operation metric name: ${operationMetricName}. Must start with a lowercase letter`,this);metrics[operationMetricName]=metric}return metrics}combinedGrant(grantee,opts){if(this.encryptionKey&&opts.keyActions&&this.encryptionKey.grant(grantee,...opts.keyActions),opts.tableActions){const resources=[this.tableArn,core_1().Lazy.string({produce:()=>this.hasIndex?`${this.tableArn}/index/*`:core_1().Aws.NO_VALUE}),...this.regionalArns,...this.regionalArns.map(arn=>core_1().Lazy.string({produce:()=>this.hasIndex?`${arn}/index/*`:core_1().Aws.NO_VALUE}))];return iam().Grant.addToPrincipalOrResource({grantee,actions:opts.tableActions,resourceArns:resources,resource:this})}if(opts.streamActions){if(!this.tableStreamArn)throw new(errors_1()).ValidationError(`DynamoDB Streams must be enabled on the table ${this.node.path}`,this);const resources=[this.tableStreamArn];return iam().Grant.addToPrincipalOrResource({grantee,actions:opts.streamActions,resourceArns:resources,resource:this})}throw new(errors_1()).ValidationError(`Unexpected 'action', ${opts.tableActions||opts.streamActions}`,this)}cannedMetric(fn,props){return new(cloudwatch()).Metric({...fn({TableName:this.tableName}),...props}).attachTo(this)}}exports.TableBase=TableBase,_b=JSII_RTTI_SYMBOL_1,TableBase[_b]={fqn:"aws-cdk-lib.aws_dynamodb.TableBase",version:"2.202.0"};let Table=Table_1=class Table2 extends TableBase{static grantListStreams(grantee){return iam().Grant.addToPrincipal({grantee,actions:["dynamodb:ListStreams"],resourceArns:["*"]})}static fromTableName(scope,id,tableName){return Table_1.fromTableAttributes(scope,id,{tableName})}static fromTableArn(scope,id,tableArn){return Table_1.fromTableAttributes(scope,id,{tableArn})}static fromTableAttributes(scope,id,attrs){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_dynamodb_TableAttributes(attrs)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.fromTableAttributes),error}class Import extends TableBase{constructor(_tableArn,tableName,tableStreamArn){super(scope,id),this.hasIndex=(attrs.grantIndexPermissions??!1)||(attrs.globalIndexes??[]).length>0||(attrs.localIndexes??[]).length>0,this.tableArn=_tableArn,this.tableName=tableName,this.tableStreamArn=tableStreamArn,this.encryptionKey=attrs.encryptionKey}}let name,arn;const stack=core_1().Stack.of(scope);if(attrs.tableName){if(attrs.tableArn)throw new(errors_1()).ValidationError("Only one of tableArn or tableName can be provided",scope);name=attrs.tableName,arn=stack.formatArn({service:"dynamodb",resource:"table",resourceName:attrs.tableName})}else{if(!attrs.tableArn)throw new(errors_1()).ValidationError("One of tableName or tableArn is required!",scope);arn=attrs.tableArn;const maybeTableName=stack.splitArn(attrs.tableArn,core_1().ArnFormat.SLASH_RESOURCE_NAME).resourceName;if(!maybeTableName)throw new(errors_1()).ValidationError("ARN for DynamoDB table must be in the form: ...",scope);name=maybeTableName}return new Import(arn,name,attrs.tableStreamArn)}constructor(scope,id,props){super(scope,id,{physicalName:props.tableName}),this.keySchema=new Array,this.attributeDefinitions=new Array,this.globalSecondaryIndexes=new Array,this.localSecondaryIndexes=new Array,this.secondaryIndexSchemas=new Map,this.nonKeyAttributes=new Set,this.tableScaling={},this.indexScaling=new Map,this.globalReplicaCustomResources=new Array;try{jsiiDeprecationWarnings().aws_cdk_lib_aws_dynamodb_TableProps(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,Table2),error}(0,metadata_resource_1().addConstructMetadata)(this,props);const{sseSpecification,encryptionKey}=this.parseEncryption(props),pointInTimeRecoverySpecification=this.validatePitr(props);let streamSpecification;if(props.replicationRegions){if(props.stream&&props.stream!==shared_1().StreamViewType.NEW_AND_OLD_IMAGES)throw new(errors_1()).ValidationError("`stream` must be set to `NEW_AND_OLD_IMAGES` when specifying `replicationRegions`",this);streamSpecification={streamViewType:shared_1().StreamViewType.NEW_AND_OLD_IMAGES},this.billingMode=props.billingMode??shared_1().BillingMode.PAY_PER_REQUEST}else this.billingMode=props.billingMode??shared_1().BillingMode.PROVISIONED,props.stream&&(streamSpecification={streamViewType:props.stream});this.validateProvisioning(props);const kinesisStreamSpecification=props.kinesisStream?{streamArn:props.kinesisStream.streamArn,...props.kinesisPrecisionTimestamp&&{approximateCreationDateTimePrecision:props.kinesisPrecisionTimestamp}}:void 0;this.table=new(dynamodb_generated_1()).CfnTable(this,"Resource",{tableName:this.physicalName,keySchema:this.keySchema,attributeDefinitions:this.attributeDefinitions,globalSecondaryIndexes:core_1().Lazy.any({produce:()=>this.globalSecondaryIndexes},{omitEmptyArray:!0}),localSecondaryIndexes:core_1().Lazy.any({produce:()=>this.localSecondaryIndexes},{omitEmptyArray:!0}),pointInTimeRecoverySpecification,billingMode:this.billingMode===shared_1().BillingMode.PAY_PER_REQUEST?this.billingMode:void 0,provisionedThroughput:this.billingMode===shared_1().BillingMode.PAY_PER_REQUEST?void 0:{readCapacityUnits:props.readCapacity||5,writeCapacityUnits:props.writeCapacity||5},...props.maxReadRequestUnits||props.maxWriteRequestUnits?{onDemandThroughput:this.billingMode===shared_1().BillingMode.PROVISIONED?void 0:{maxReadRequestUnits:props.maxReadRequestUnits||void 0,maxWriteRequestUnits:props.maxWriteRequestUnits||void 0}}:void 0,sseSpecification,streamSpecification,tableClass:props.tableClass,timeToLiveSpecification:props.timeToLiveAttribute?{attributeName:props.timeToLiveAttribute,enabled:!0}:void 0,contributorInsightsSpecification:props.contributorInsightsEnabled!==void 0?{enabled:props.contributorInsightsEnabled}:void 0,kinesisStreamSpecification,deletionProtectionEnabled:props.deletionProtection,importSourceSpecification:this.renderImportSourceSpecification(props.importSource),resourcePolicy:props.resourcePolicy?{policyDocument:props.resourcePolicy}:void 0,warmThroughput:props.warmThroughput??void 0}),this.table.applyRemovalPolicy(props.removalPolicy),this.encryptionKey=encryptionKey,this.tableArn=this.getResourceArnAttribute(this.table.attrArn,{service:"dynamodb",resource:"table",resourceName:this.physicalName}),this.tableName=this.getResourceNameAttribute(this.table.ref),props.tableName&&this.node.addMetadata("aws:cdk:hasPhysicalName",this.tableName),this.tableStreamArn=streamSpecification?this.table.attrStreamArn:void 0,this.scalingRole=this.makeScalingRole(),this.addKey(props.partitionKey,HASH_KEY_TYPE),this.tablePartitionKey=props.partitionKey,props.sortKey&&(this.addKey(props.sortKey,RANGE_KEY_TYPE),this.tableSortKey=props.sortKey),props.replicationRegions&&props.replicationRegions.length>0&&this.createReplicaTables(props.replicationRegions,props.replicationTimeout,props.waitForReplicationToFinish,props.replicaRemovalPolicy),this.node.addValidation({validate:()=>this.validateTable()})}addGlobalSecondaryIndex(props){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_dynamodb_GlobalSecondaryIndexProps(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.addGlobalSecondaryIndex),error}this.validateProvisioning(props),this.validateIndexName(props.indexName);const gsiKeySchema=this.buildIndexKeySchema(props.partitionKey,props.sortKey),gsiProjection=this.buildIndexProjection(props);this.globalSecondaryIndexes.push({contributorInsightsSpecification:props.contributorInsightsEnabled!==void 0?{enabled:props.contributorInsightsEnabled}:void 0,indexName:props.indexName,keySchema:gsiKeySchema,projection:gsiProjection,provisionedThroughput:this.billingMode===shared_1().BillingMode.PAY_PER_REQUEST?void 0:{readCapacityUnits:props.readCapacity||5,writeCapacityUnits:props.writeCapacity||5},...props.maxReadRequestUnits||props.maxWriteRequestUnits?{onDemandThroughput:this.billingMode===shared_1().BillingMode.PROVISIONED?void 0:{maxReadRequestUnits:props.maxReadRequestUnits||void 0,maxWriteRequestUnits:props.maxWriteRequestUnits||void 0}}:void 0,warmThroughput:props.warmThroughput??void 0}),this.secondaryIndexSchemas.set(props.indexName,{partitionKey:props.partitionKey,sortKey:props.sortKey}),this.indexScaling.set(props.indexName,{})}addLocalSecondaryIndex(props){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_dynamodb_LocalSecondaryIndexProps(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.addLocalSecondaryIndex),error}if(this.localSecondaryIndexes.length>=MAX_LOCAL_SECONDARY_INDEX_COUNT)throw new RangeError(`a maximum number of local secondary index per table is ${MAX_LOCAL_SECONDARY_INDEX_COUNT}`);this.validateIndexName(props.indexName);const lsiKeySchema=this.buildIndexKeySchema(this.tablePartitionKey,props.sortKey),lsiProjection=this.buildIndexProjection(props);this.localSecondaryIndexes.push({indexName:props.indexName,keySchema:lsiKeySchema,projection:lsiProjection}),this.secondaryIndexSchemas.set(props.indexName,{partitionKey:this.tablePartitionKey,sortKey:props.sortKey})}autoScaleReadCapacity(props){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_dynamodb_EnableScalingProps(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.autoScaleReadCapacity),error}if(this.tableScaling.scalableReadAttribute)throw new(errors_1()).ValidationError("Read AutoScaling already enabled for this table",this);if(this.billingMode===shared_1().BillingMode.PAY_PER_REQUEST)throw new(errors_1()).ValidationError("AutoScaling is not available for tables with PAY_PER_REQUEST billing mode",this);return this.tableScaling.scalableReadAttribute=new(scalable_table_attribute_1()).ScalableTableAttribute(this,"ReadScaling",{serviceNamespace:appscaling().ServiceNamespace.DYNAMODB,resourceId:`table/${this.tableName}`,dimension:"dynamodb:table:ReadCapacityUnits",role:this.scalingRole,...props})}autoScaleWriteCapacity(props){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_dynamodb_EnableScalingProps(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.autoScaleWriteCapacity),error}if(this.tableScaling.scalableWriteAttribute)throw new(errors_1()).ValidationError("Write AutoScaling already enabled for this table",this);if(this.billingMode===shared_1().BillingMode.PAY_PER_REQUEST)throw new(errors_1()).ValidationError("AutoScaling is not available for tables with PAY_PER_REQUEST billing mode",this);this.tableScaling.scalableWriteAttribute=new(scalable_table_attribute_1()).ScalableTableAttribute(this,"WriteScaling",{serviceNamespace:appscaling().ServiceNamespace.DYNAMODB,resourceId:`table/${this.tableName}`,dimension:"dynamodb:table:WriteCapacityUnits",role:this.scalingRole,...props});for(const globalReplicaCustomResource of this.globalReplicaCustomResources)globalReplicaCustomResource.node.addDependency(this.tableScaling.scalableWriteAttribute);return this.tableScaling.scalableWriteAttribute}autoScaleGlobalSecondaryIndexReadCapacity(indexName,props){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_dynamodb_EnableScalingProps(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.autoScaleGlobalSecondaryIndexReadCapacity),error}if(this.billingMode===shared_1().BillingMode.PAY_PER_REQUEST)throw new(errors_1()).ValidationError("AutoScaling is not available for tables with PAY_PER_REQUEST billing mode",this);const attributePair=this.indexScaling.get(indexName);if(!attributePair)throw new(errors_1()).ValidationError(`No global secondary index with name ${indexName}`,this);if(attributePair.scalableReadAttribute)throw new(errors_1()).ValidationError("Read AutoScaling already enabled for this index",this);return attributePair.scalableReadAttribute=new(scalable_table_attribute_1()).ScalableTableAttribute(this,`${indexName}ReadScaling`,{serviceNamespace:appscaling().ServiceNamespace.DYNAMODB,resourceId:`table/${this.tableName}/index/${indexName}`,dimension:"dynamodb:index:ReadCapacityUnits",role:this.scalingRole,...props})}autoScaleGlobalSecondaryIndexWriteCapacity(indexName,props){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_dynamodb_EnableScalingProps(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.autoScaleGlobalSecondaryIndexWriteCapacity),error}if(this.billingMode===shared_1().BillingMode.PAY_PER_REQUEST)throw new(errors_1()).ValidationError("AutoScaling is not available for tables with PAY_PER_REQUEST billing mode",this);const attributePair=this.indexScaling.get(indexName);if(!attributePair)throw new(errors_1()).ValidationError(`No global secondary index with name ${indexName}`,this);if(attributePair.scalableWriteAttribute)throw new(errors_1()).ValidationError("Write AutoScaling already enabled for this index",this);return attributePair.scalableWriteAttribute=new(scalable_table_attribute_1()).ScalableTableAttribute(this,`${indexName}WriteScaling`,{serviceNamespace:appscaling().ServiceNamespace.DYNAMODB,resourceId:`table/${this.tableName}/index/${indexName}`,dimension:"dynamodb:index:WriteCapacityUnits",role:this.scalingRole,...props})}schema(indexName){if(!indexName)return{partitionKey:this.tablePartitionKey,sortKey:this.tableSortKey};let schema=this.secondaryIndexSchemas.get(indexName);if(!schema)throw new(errors_1()).ValidationError(`Cannot find schema for index: ${indexName}. Use 'addGlobalSecondaryIndex' or 'addLocalSecondaryIndex' to add index`,this);return schema}validateTable(){const errors=new Array;if(this.tablePartitionKey||errors.push("a partition key must be specified"),this.localSecondaryIndexes.length>0&&!this.tableSortKey&&errors.push("a sort key of the table must be specified to add local secondary indexes"),this.globalReplicaCustomResources.length>0&&this.billingMode===shared_1().BillingMode.PROVISIONED){const writeAutoScaleAttribute=this.tableScaling.scalableWriteAttribute;writeAutoScaleAttribute?writeAutoScaleAttribute._scalingPolicyCreated||errors.push("A global Table that uses PROVISIONED as the billing mode needs auto-scaled write capacity with a policy. Call one of the scaleOn*() methods of the object returned from autoScaleWriteCapacity()"):errors.push("A global Table that uses PROVISIONED as the billing mode needs auto-scaled write capacity. Use the autoScaleWriteCapacity() method to enable it.")}return errors}validateProvisioning(props){if(this.billingMode===shared_1().BillingMode.PAY_PER_REQUEST&&(props.readCapacity!==void 0||props.writeCapacity!==void 0))throw new(errors_1()).ValidationError("you cannot provision read and write capacity for a table with PAY_PER_REQUEST billing mode",this)}validateIndexName(indexName){if(this.secondaryIndexSchemas.has(indexName))throw new(errors_1()).ValidationError(`a duplicate index name, ${indexName}, is not allowed`,this)}validateNonKeyAttributes(nonKeyAttributes){if(this.nonKeyAttributes.size+nonKeyAttributes.length>100)throw new RangeError("a maximum number of nonKeyAttributes across all of secondary indexes is 100");nonKeyAttributes.forEach(att=>this.nonKeyAttributes.add(att))}validatePitr(props){if(props.pointInTimeRecoverySpecification!==void 0&&props.pointInTimeRecovery!==void 0)throw new(errors_1()).ValidationError("`pointInTimeRecoverySpecification` and `pointInTimeRecovery` are set. Use `pointInTimeRecoverySpecification` only.",this);const recoveryPeriodInDays=props.pointInTimeRecoverySpecification?.recoveryPeriodInDays;if(!props.pointInTimeRecoverySpecification?.pointInTimeRecoveryEnabled&&recoveryPeriodInDays)throw new(errors_1()).ValidationError("Cannot set `recoveryPeriodInDays` while `pointInTimeRecoveryEnabled` is set to false.",this);if(recoveryPeriodInDays!==void 0&&(recoveryPeriodInDays<1||recoveryPeriodInDays>35))throw new(errors_1()).ValidationError("`recoveryPeriodInDays` must be a value between `1` and `35`.",this);return props.pointInTimeRecoverySpecification??(props.pointInTimeRecovery!==void 0?{pointInTimeRecoveryEnabled:props.pointInTimeRecovery}:void 0)}buildIndexKeySchema(partitionKey,sortKey){this.registerAttribute(partitionKey);const indexKeySchema=[{attributeName:partitionKey.name,keyType:HASH_KEY_TYPE}];return sortKey&&(this.registerAttribute(sortKey),indexKeySchema.push({attributeName:sortKey.name,keyType:RANGE_KEY_TYPE})),indexKeySchema}buildIndexProjection(props){if(props.projectionType===shared_1().ProjectionType.INCLUDE&&!props.nonKeyAttributes)throw new(errors_1()).ValidationError(`non-key attributes should be specified when using ${shared_1().ProjectionType.INCLUDE} projection type`,this);if(props.projectionType!==shared_1().ProjectionType.INCLUDE&&props.nonKeyAttributes)throw new(errors_1()).ValidationError(`non-key attributes should not be specified when not using ${shared_1().ProjectionType.INCLUDE} projection type`,this);return props.nonKeyAttributes&&this.validateNonKeyAttributes(props.nonKeyAttributes),{projectionType:props.projectionType??shared_1().ProjectionType.ALL,nonKeyAttributes:props.nonKeyAttributes??void 0}}findKey(keyType){return this.keySchema.find(prop=>prop.keyType===keyType)}addKey(attribute,keyType){const existingProp=this.findKey(keyType);if(existingProp)throw new(errors_1()).ValidationError(`Unable to set ${attribute.name} as a ${keyType} key, because ${existingProp.attributeName} is a ${keyType} key`,this);return this.registerAttribute(attribute),this.keySchema.push({attributeName:attribute.name,keyType}),this}registerAttribute(attribute){const{name,type}=attribute,existingDef=this.attributeDefinitions.find(def=>def.attributeName===name);if(existingDef&&existingDef.attributeType!==type)throw new(errors_1()).ValidationError(`Unable to specify ${name} as ${type} because it was already defined as ${existingDef.attributeType}`,this);existingDef||this.attributeDefinitions.push({attributeName:name,attributeType:type})}makeScalingRole(){return iam().Role.fromRoleArn(this,"ScalingRole",core_1().Stack.of(this).formatArn({service:"iam",region:"",resource:"role/aws-service-role/dynamodb.application-autoscaling.amazonaws.com",resourceName:"AWSServiceRoleForApplicationAutoScaling_DynamoDBTable"}))}createReplicaTables(regions,timeout,waitForReplicationToFinish,replicaRemovalPolicy){const stack=core_1().Stack.of(this);if(!core_1().Token.isUnresolved(stack.region)&®ions.includes(stack.region))throw new(errors_1()).ValidationError("`replicationRegions` cannot include the region where this stack is deployed.",this);const provider=replica_provider_1().ReplicaProvider.getOrCreate(this,{tableName:this.tableName,regions,timeout}),onEventHandlerPolicy=new SourceTableAttachedPolicy(this,provider.onEventHandler.role),isCompleteHandlerPolicy=new SourceTableAttachedPolicy(this,provider.isCompleteHandler.role);this.grant(onEventHandlerPolicy,"dynamodb:*"),this.grant(isCompleteHandlerPolicy,"dynamodb:DescribeTable");let previousRegion,previousRegionCondition;const skipReplicaDeletion=core_1().FeatureFlags.of(this).isEnabled(cx_api_1().DYNAMODB_TABLE_RETAIN_TABLE_REPLICA)?core_1().Lazy.any({produce:()=>replicaRemovalPolicy?replicaRemovalPolicy==core_1().RemovalPolicy.RETAIN:this.node.defaultChild.cfnOptions.deletionPolicy===core_1().CfnDeletionPolicy.RETAIN}):!1;for(const region of new Set(regions)){const currentRegion=new(core_1()).CustomResource(this,`Replica${region}`,{serviceToken:provider.provider.serviceToken,resourceType:"Custom::DynamoDBReplica",properties:{TableName:this.tableName,Region:region,...skipReplicaDeletion&&{SkipReplicaDeletion:skipReplicaDeletion},SkipReplicationCompletedWait:waitForReplicationToFinish==null?void 0:(!waitForReplicationToFinish).toString()}});currentRegion.node.addDependency(onEventHandlerPolicy.policy,isCompleteHandlerPolicy.policy),this.globalReplicaCustomResources.push(currentRegion);let createReplica;if(core_1().Token.isUnresolved(stack.region)){createReplica=new(core_1()).CfnCondition(this,`StackRegionNotEquals${region}`,{expression:core_1().Fn.conditionNot(core_1().Fn.conditionEquals(region,core_1().Aws.REGION))});const cfnCustomResource=currentRegion.node.defaultChild;cfnCustomResource.cfnOptions.condition=createReplica}if(this.regionalArns.push(stack.formatArn({region,service:"dynamodb",resource:"table",resourceName:this.tableName})),previousRegion)if(previousRegionCondition){const previousRegionCfnResource=previousRegion.node.defaultChild;currentRegion.node.defaultChild.addMetadata("DynamoDbReplicationDependency",core_1().Fn.conditionIf(previousRegionCondition.logicalId,previousRegionCfnResource.ref,core_1().Aws.NO_VALUE))}else currentRegion.node.addDependency(previousRegion);previousRegion=currentRegion,previousRegionCondition=createReplica}onEventHandlerPolicy.grantPrincipal.addToPrincipalPolicy(new(iam()).PolicyStatement({actions:["dynamodb:*"],resources:this.regionalArns}))}get hasIndex(){return this.globalSecondaryIndexes.length+this.localSecondaryIndexes.length>0}parseEncryption(props){let encryptionType=props.encryption;if(encryptionType!=null&&props.serverSideEncryption!=null)throw new(errors_1()).ValidationError("Only one of encryption and serverSideEncryption can be specified, but both were provided",this);if(props.serverSideEncryption&&props.encryptionKey)throw new(errors_1()).ValidationError("encryptionKey cannot be specified when serverSideEncryption is specified. Use encryption instead",this);if(encryptionType===void 0&&(encryptionType=props.encryptionKey!=null?shared_1().TableEncryption.CUSTOMER_MANAGED:props.serverSideEncryption?shared_1().TableEncryption.AWS_MANAGED:void 0),encryptionType!==shared_1().TableEncryption.CUSTOMER_MANAGED&&props.encryptionKey)throw new(errors_1()).ValidationError(`encryptionKey cannot be specified unless encryption is set to TableEncryption.CUSTOMER_MANAGED (it was set to ${encryptionType})`,this);if(encryptionType===shared_1().TableEncryption.CUSTOMER_MANAGED&&props.replicationRegions)throw new(errors_1()).ValidationError("TableEncryption.CUSTOMER_MANAGED is not supported by DynamoDB Global Tables (where replicationRegions was set)",this);switch(encryptionType){case shared_1().TableEncryption.CUSTOMER_MANAGED:const encryptionKey=props.encryptionKey??new(kms()).Key(this,"Key",{description:`Customer-managed key auto-created for encrypting DynamoDB table at ${this.node.path}`,enableKeyRotation:!0});return{sseSpecification:{sseEnabled:!0,kmsMasterKeyId:encryptionKey.keyArn,sseType:"KMS"},encryptionKey};case shared_1().TableEncryption.AWS_MANAGED:return{sseSpecification:{sseEnabled:!0}};case shared_1().TableEncryption.DEFAULT:return{sseSpecification:{sseEnabled:!1}};case void 0:return{sseSpecification:void 0};default:throw new(errors_1()).ValidationError(`Unexpected 'encryptionType': ${encryptionType}`,this)}}renderImportSourceSpecification(importSource){if(importSource)return{...importSource.inputFormat._render(),inputCompressionType:importSource.compressionType,s3BucketSource:{s3Bucket:importSource.bucket.bucketName,s3BucketOwner:importSource.bucketOwner,s3KeyPrefix:importSource.keyPrefix}}}};exports.Table=Table,_c=JSII_RTTI_SYMBOL_1,Table[_c]={fqn:"aws-cdk-lib.aws_dynamodb.Table",version:"2.202.0"},Table.PROPERTY_INJECTION_ID="aws-cdk-lib.aws-dynamodb.Table",__decorate([(0,metadata_resource_1().MethodMetadata)()],Table.prototype,"addGlobalSecondaryIndex",null),__decorate([(0,metadata_resource_1().MethodMetadata)()],Table.prototype,"addLocalSecondaryIndex",null),__decorate([(0,metadata_resource_1().MethodMetadata)()],Table.prototype,"autoScaleReadCapacity",null),__decorate([(0,metadata_resource_1().MethodMetadata)()],Table.prototype,"autoScaleWriteCapacity",null),__decorate([(0,metadata_resource_1().MethodMetadata)()],Table.prototype,"autoScaleGlobalSecondaryIndexReadCapacity",null),__decorate([(0,metadata_resource_1().MethodMetadata)()],Table.prototype,"autoScaleGlobalSecondaryIndexWriteCapacity",null),__decorate([(0,metadata_resource_1().MethodMetadata)()],Table.prototype,"schema",null),exports.Table=Table=Table_1=__decorate([prop_injectable_1().propertyInjectable],Table);class SourceTableAttachedPolicy extends constructs_1().Construct{constructor(sourceTable,role){super(sourceTable,`SourceTableAttachedManagedPolicy-${core_1().Names.nodeUniqueId(role.node)}`);const policy=new(iam()).ManagedPolicy(this,"Resource",{description:`DynamoDB replication managed policy for table ${sourceTable.tableName}`,roles:[role]});this.policy=policy,this.grantPrincipal=new SourceTableAttachedPrincipal(role,policy)}}class SourceTableAttachedPrincipal extends iam().PrincipalBase{constructor(role,policy){super(),this.role=role,this.policy=policy}get policyFragment(){return this.role.policyFragment}addToPrincipalPolicy(statement){return this.policy.addStatements(statement),{policyDependable:this.policy,statementAdded:!0}}dedupeString(){}}
;