UNPKG

aws-cdk-lib

Version:

Version 2 of the AWS Cloud Development Kit library

3 lines (2 loc) 10.3 kB
"use strict";var _a;Object.defineProperty(exports,"__esModule",{value:!0}),exports.AssetStaging=void 0;const jsiiDeprecationWarnings=require("../../.warnings.jsii.js"),JSII_RTTI_SYMBOL_1=Symbol.for("jsii.rtti"),crypto=require("crypto"),path=require("path"),cxapi=require("../../cx-api"),constructs_1=require("constructs"),fs=require("fs-extra"),assets_1=require("./assets"),bundling_1=require("./bundling"),fs_1=require("./fs"),fingerprint_1=require("./fs/fingerprint"),names_1=require("./names"),asset_staging_1=require("./private/asset-staging"),cache_1=require("./private/cache"),stack_1=require("./stack"),stage_1=require("./stage"),ARCHIVE_EXTENSIONS=[".tar.gz",".zip",".jar",".tar",".tgz"],ASSET_SALT_CONTEXT_KEY="@aws-cdk/core:assetHashSalt";class AssetStaging extends constructs_1.Construct{constructor(scope,id,props){super(scope,id);try{jsiiDeprecationWarnings.aws_cdk_lib_AssetStagingProps(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,AssetStaging),error}const salt=this.node.tryGetContext(ASSET_SALT_CONTEXT_KEY);if(this.sourcePath=path.resolve(props.sourcePath),this.fingerprintOptions={...props,extraHash:props.extraHash||salt?`${props.extraHash??""}${salt??""}`:void 0},!fs.existsSync(this.sourcePath))throw new Error(`Cannot find asset at ${this.sourcePath}`);this.sourceStats=fs.statSync(this.sourcePath);const outdir=stage_1.Stage.of(this)?.assetOutdir;if(!outdir)throw new Error('unable to determine cloud assembly asset output directory. Assets must be defined indirectly within a "Stage" or an "App" scope');this.assetOutdir=outdir,this.customSourceFingerprint=props.assetHash,this.hashType=determineHashType(props.assetHashType,this.customSourceFingerprint);let stageThisAsset,skip=!1;if(props.bundling){skip=!stack_1.Stack.of(this).bundlingRequired;const bundling=props.bundling;stageThisAsset=()=>this.stageByBundling(bundling,skip)}else stageThisAsset=()=>this.stageByCopying();this.cacheKey=calculateCacheKey({outdir:this.assetOutdir,sourcePath:path.resolve(props.sourcePath),bundling:props.bundling,assetHashType:this.hashType,customFingerprint:this.customSourceFingerprint,extraHash:props.extraHash,exclude:props.exclude,ignoreMode:props.ignoreMode,skip});const staged=AssetStaging.assetCache.obtain(this.cacheKey,stageThisAsset);this.stagedPath=staged.stagedPath,this.absoluteStagedPath=staged.stagedPath,this.assetHash=staged.assetHash,this.packaging=staged.packaging,this.isArchive=staged.isArchive}static clearAssetHashCache(){this.assetCache.clear(),fingerprint_1.clearLargeFileFingerprintCache()}get sourceHash(){return this.assetHash}relativeStagedPath(stack){try{jsiiDeprecationWarnings.aws_cdk_lib_Stack(stack)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.relativeStagedPath),error}const asmManifestDir=stage_1.Stage.of(stack)?.outdir;return asmManifestDir?path.relative(this.assetOutdir,this.stagedPath).startsWith("..")||this.stagingDisabled?this.stagedPath:path.relative(asmManifestDir,this.stagedPath):this.stagedPath}stageByCopying(){const assetHash=this.calculateHash(this.hashType),stagedPath=this.stagingDisabled?this.sourcePath:path.resolve(this.assetOutdir,renderAssetFilename(assetHash,getExtension(this.sourcePath)));if(!this.sourceStats.isDirectory()&&!this.sourceStats.isFile())throw new Error(`Asset ${this.sourcePath} is expected to be either a directory or a regular file`);return this.stageAsset(this.sourcePath,stagedPath,"copy"),{assetHash,stagedPath,packaging:this.sourceStats.isDirectory()?assets_1.FileAssetPackaging.ZIP_DIRECTORY:assets_1.FileAssetPackaging.FILE,isArchive:this.sourceStats.isDirectory()||ARCHIVE_EXTENSIONS.includes(getExtension(this.sourcePath).toLowerCase())}}stageByBundling(bundling,skip){if(!this.sourceStats.isDirectory())throw new Error(`Asset ${this.sourcePath} is expected to be a directory when bundling`);if(skip){let hashType=this.hashType;return(hashType===assets_1.AssetHashType.OUTPUT||hashType===assets_1.AssetHashType.BUNDLE)&&(this.customSourceFingerprint=names_1.Names.uniqueId(this),hashType=assets_1.AssetHashType.CUSTOM),{assetHash:this.calculateHash(hashType,bundling),stagedPath:this.sourcePath,packaging:assets_1.FileAssetPackaging.ZIP_DIRECTORY,isArchive:!0}}let assetHash=this.hashType===assets_1.AssetHashType.SOURCE||this.hashType===assets_1.AssetHashType.CUSTOM?this.calculateHash(this.hashType,bundling):void 0;const bundleDir=this.determineBundleDir(this.assetOutdir,assetHash);this.bundle(bundling,bundleDir);const bundlingOutputType=bundling.outputType??bundling_1.BundlingOutput.AUTO_DISCOVER,bundledAsset=determineBundledAsset(bundleDir,bundlingOutputType);assetHash=assetHash??this.calculateHash(this.hashType,bundling,bundledAsset.path);const stagedPath=path.resolve(this.assetOutdir,renderAssetFilename(assetHash,bundledAsset.extension));return this.stageAsset(bundledAsset.path,stagedPath,"move"),bundledAsset.packaging===assets_1.FileAssetPackaging.FILE&&fs.closeSync(fs.openSync(bundledAsset.path,"w")),{assetHash,stagedPath,packaging:bundledAsset.packaging,isArchive:!0}}get stagingDisabled(){return!!this.node.tryGetContext(cxapi.DISABLE_ASSET_STAGING_CONTEXT)}stageAsset(sourcePath,targetPath,style){if(fs.existsSync(targetPath)){style==="move"&&sourcePath!==targetPath&&fs.removeSync(sourcePath);return}if(style=="move"){fs.renameSync(sourcePath,targetPath);return}if(this.sourceStats.isFile())fs.copyFileSync(sourcePath,targetPath);else if(this.sourceStats.isDirectory())fs.mkdirSync(targetPath),fs_1.FileSystem.copyDirectory(sourcePath,targetPath,this.fingerprintOptions);else throw new Error(`Unknown file type: ${sourcePath}`)}determineBundleDir(outdir,sourceHash){return sourceHash?path.resolve(outdir,renderAssetFilename(sourceHash)):path.resolve(outdir,`bundling-temp-${this.cacheKey}`)}bundle(options,bundleDir){if(fs.existsSync(bundleDir))return;fs.ensureDirSync(bundleDir),fs.chmodSync(bundleDir,511);let localBundling;try{if(process.stderr.write(`Bundling asset ${this.node.path}... `),localBundling=options.local?.tryBundle(bundleDir,options),!localBundling){const assetStagingOptions={sourcePath:this.sourcePath,bundleDir,...options};switch(options.bundlingFileAccess){case bundling_1.BundlingFileAccess.VOLUME_COPY:new asset_staging_1.AssetBundlingVolumeCopy(assetStagingOptions).run();break;case bundling_1.BundlingFileAccess.BIND_MOUNT:default:new asset_staging_1.AssetBundlingBindMount(assetStagingOptions).run();break}}}catch(err){const bundleErrorDir=bundleDir+"-error";throw fs.existsSync(bundleErrorDir)&&fs.removeSync(bundleErrorDir),fs.renameSync(bundleDir,bundleErrorDir),new Error(`Failed to bundle asset ${this.node.path}, bundle output is located at ${bundleErrorDir}: ${err}`)}if(fs_1.FileSystem.isEmpty(bundleDir)){const outputDir=localBundling?bundleDir:AssetStaging.BUNDLING_OUTPUT_DIR;throw new Error(`Bundling did not produce any output. Check that content is written to ${outputDir}.`)}}calculateHash(hashType,bundling,outputDir){if(hashType==assets_1.AssetHashType.CUSTOM||hashType==assets_1.AssetHashType.SOURCE&&bundling){const hash=crypto.createHash("sha256");return hash.update(this.customSourceFingerprint??fs_1.FileSystem.fingerprint(this.sourcePath,this.fingerprintOptions)),bundling&&hash.update(JSON.stringify(bundling)),hash.digest("hex")}switch(hashType){case assets_1.AssetHashType.SOURCE:return fs_1.FileSystem.fingerprint(this.sourcePath,this.fingerprintOptions);case assets_1.AssetHashType.BUNDLE:case assets_1.AssetHashType.OUTPUT:if(!outputDir)throw new Error(`Cannot use \`${hashType}\` hash type when \`bundling\` is not specified.`);return fs_1.FileSystem.fingerprint(outputDir,this.fingerprintOptions);default:throw new Error("Unknown asset hash type.")}}}exports.AssetStaging=AssetStaging,_a=JSII_RTTI_SYMBOL_1,AssetStaging[_a]={fqn:"aws-cdk-lib.AssetStaging",version:"2.70.0"},AssetStaging.BUNDLING_INPUT_DIR="/asset-input",AssetStaging.BUNDLING_OUTPUT_DIR="/asset-output",AssetStaging.assetCache=new cache_1.Cache;function renderAssetFilename(assetHash,extension=""){return`asset.${assetHash}${extension}`}function determineHashType(assetHashType,customSourceFingerprint){const hashType=customSourceFingerprint?assetHashType??assets_1.AssetHashType.CUSTOM:assetHashType??assets_1.AssetHashType.SOURCE;if(customSourceFingerprint&&hashType!==assets_1.AssetHashType.CUSTOM)throw new Error(`Cannot specify \`${assetHashType}\` for \`assetHashType\` when \`assetHash\` is specified. Use \`CUSTOM\` or leave \`undefined\`.`);if(hashType===assets_1.AssetHashType.CUSTOM&&!customSourceFingerprint)throw new Error("`assetHash` must be specified when `assetHashType` is set to `AssetHashType.CUSTOM`.");return hashType}function calculateCacheKey(props){return crypto.createHash("sha256").update(JSON.stringify(sortObject(props))).digest("hex")}function sortObject(object){if(typeof object!="object"||object instanceof Array)return object;const ret={};for(const key of Object.keys(object).sort())ret[key]=sortObject(object[key]);return ret}function singleArchiveFile(directory){if(!fs.existsSync(directory))throw new Error(`Directory ${directory} does not exist.`);if(!fs.statSync(directory).isDirectory())throw new Error(`${directory} is not a directory.`);const content=fs.readdirSync(directory);if(content.length===1){const file=path.join(directory,content[0]),extension=getExtension(content[0]).toLowerCase();if(fs.statSync(file).isFile()&&ARCHIVE_EXTENSIONS.includes(extension))return file}}function determineBundledAsset(bundleDir,outputType){const archiveFile=singleArchiveFile(bundleDir);switch(outputType===bundling_1.BundlingOutput.AUTO_DISCOVER&&(outputType=archiveFile?bundling_1.BundlingOutput.ARCHIVED:bundling_1.BundlingOutput.NOT_ARCHIVED),outputType){case bundling_1.BundlingOutput.NOT_ARCHIVED:return{path:bundleDir,packaging:assets_1.FileAssetPackaging.ZIP_DIRECTORY};case bundling_1.BundlingOutput.ARCHIVED:if(!archiveFile)throw new Error("Bundling output directory is expected to include only a single archive file when `output` is set to `ARCHIVED`");return{path:archiveFile,packaging:assets_1.FileAssetPackaging.FILE,extension:getExtension(archiveFile)}}}function getExtension(source){for(const ext of ARCHIVE_EXTENSIONS)if(source.toLowerCase().endsWith(ext))return ext;return path.extname(source)}