@aws-cdk/toolkit-lib 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/build-info.json +2 -2
  2. package/lib/actions/bootstrap/index.js +69 -5
  3. package/lib/actions/diff/index.d.ts +8 -0
  4. package/lib/actions/diff/index.js +1 -1
  5. package/lib/actions/diff/private/helpers.d.ts +16 -0
  6. package/lib/actions/diff/private/helpers.js +31 -6
  7. package/lib/actions/index.d.ts +1 -0
  8. package/lib/actions/index.js +2 -1
  9. package/lib/actions/refactor/index.d.ts +15 -0
  10. package/lib/actions/refactor/index.js +3 -0
  11. package/lib/api/cloud-assembly/cached-source.d.ts +36 -0
  12. package/lib/api/cloud-assembly/cached-source.js +52 -0
  13. package/lib/api/cloud-assembly/index.d.ts +1 -0
  14. package/lib/api/cloud-assembly/index.js +2 -1
  15. package/lib/api/cloud-assembly/private/borrowed-assembly.d.ts +14 -0
  16. package/lib/api/cloud-assembly/private/borrowed-assembly.js +22 -0
  17. package/lib/api/cloud-assembly/private/context-aware-source.d.ts +18 -5
  18. package/lib/api/cloud-assembly/private/context-aware-source.js +25 -8
  19. package/lib/api/cloud-assembly/private/index.d.ts +0 -2
  20. package/lib/api/cloud-assembly/private/index.js +1 -3
  21. package/lib/api/cloud-assembly/private/prepare-source.d.ts +37 -8
  22. package/lib/api/cloud-assembly/private/prepare-source.js +76 -17
  23. package/lib/api/cloud-assembly/private/readable-assembly.d.ts +26 -0
  24. package/lib/api/cloud-assembly/private/readable-assembly.js +34 -0
  25. package/lib/api/cloud-assembly/private/source-builder.d.ts +27 -0
  26. package/lib/api/cloud-assembly/private/source-builder.js +139 -30
  27. package/lib/api/cloud-assembly/private/stack-assembly.d.ts +9 -4
  28. package/lib/api/cloud-assembly/private/stack-assembly.js +21 -3
  29. package/lib/api/cloud-assembly/source-builder.d.ts +6 -0
  30. package/lib/api/cloud-assembly/source-builder.js +1 -1
  31. package/lib/api/cloud-assembly/types.d.ts +32 -1
  32. package/lib/api/cloud-assembly/types.js +1 -1
  33. package/lib/api/shared-private.js +373 -20
  34. package/lib/api/shared-private.js.map +4 -4
  35. package/lib/api/shared-public.d.ts +82 -61
  36. package/lib/index_bg.wasm +0 -0
  37. package/lib/toolkit/private/index.d.ts +4 -0
  38. package/lib/toolkit/private/index.js +7 -2
  39. package/lib/toolkit/toolkit.d.ts +15 -2
  40. package/lib/toolkit/toolkit.js +326 -162
  41. package/package.json +11 -11
  42. package/lib/api/cloud-assembly/private/cached-source.d.ts +0 -15
  43. package/lib/api/cloud-assembly/private/cached-source.js +0 -25
  44. package/lib/api/cloud-assembly/private/identity-source.d.ts +0 -10
  45. package/lib/api/cloud-assembly/private/identity-source.js +0 -17
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["shared-private.ts", "../../../tmp-toolkit-helpers/src/api/io/private/span.ts", "../../../tmp-toolkit-helpers/src/util/archive.ts", "../../../tmp-toolkit-helpers/src/util/format-error.ts", "../../../tmp-toolkit-helpers/src/util/arrays.ts", "../../../tmp-toolkit-helpers/src/util/bytes.ts", "../../../tmp-toolkit-helpers/src/util/cloudformation.ts", "../../../tmp-toolkit-helpers/src/util/content-hash.ts", "../../../tmp-toolkit-helpers/src/util/directories.ts", "../../../tmp-toolkit-helpers/src/api/toolkit-error.ts", "../../../tmp-toolkit-helpers/src/util/json.ts", "../../../tmp-toolkit-helpers/src/util/types.ts", "../../../tmp-toolkit-helpers/src/util/objects.ts", "../../../tmp-toolkit-helpers/src/util/parallel.ts", "../../../tmp-toolkit-helpers/src/util/serialize.ts", "../../../tmp-toolkit-helpers/src/util/yaml-cfn.ts", "../../../tmp-toolkit-helpers/src/util/string-manipulation.ts", "../../../tmp-toolkit-helpers/src/util/version-range.ts", "../../../tmp-toolkit-helpers/src/api/io/private/io-helper.ts", "../../../tmp-toolkit-helpers/src/api/io/private/level-priority.ts", "../../../tmp-toolkit-helpers/src/api/io/private/message-maker.ts", "../../../tmp-toolkit-helpers/src/api/io/private/messages.ts", "../../../tmp-toolkit-helpers/src/api/io/private/io-default-messages.ts", "../../../tmp-toolkit-helpers/src/private/activity-printer/base.ts", "../../../tmp-toolkit-helpers/src/private/activity-printer/history.ts", "../../../tmp-toolkit-helpers/src/private/activity-printer/current.ts", "../../../tmp-toolkit-helpers/src/private/activity-printer/display.ts", "../../../tmp-toolkit-helpers/src/api/aws-auth/proxy-agent.ts", "../../../tmp-toolkit-helpers/src/api/aws-auth/sdk.ts", "../../../tmp-toolkit-helpers/src/api/aws-auth/account-cache.ts", "../../../tmp-toolkit-helpers/src/api/aws-auth/cached.ts", "../../../tmp-toolkit-helpers/src/api/aws-auth/tracing.ts", "../../../tmp-toolkit-helpers/src/api/aws-auth/user-agent.ts", "../../../tmp-toolkit-helpers/src/api/aws-auth/util.ts", "../../../tmp-toolkit-helpers/src/api/aws-auth/sdk-provider.ts", "../../../tmp-toolkit-helpers/src/api/aws-auth/awscli-compatible.ts", "../../../tmp-toolkit-helpers/src/api/aws-auth/provider-caching.ts", "../../../tmp-toolkit-helpers/src/api/aws-auth/credential-plugins.ts", "../../../tmp-toolkit-helpers/src/api/plugin/plugin.ts", "../../../tmp-toolkit-helpers/src/api/plugin/context-provider-plugin.ts", "../../../tmp-toolkit-helpers/src/api/plugin/mode.ts", "../../../tmp-toolkit-helpers/src/api/aws-auth/sdk-logger.ts", "../../../tmp-toolkit-helpers/src/api/bootstrap/bootstrap-environment.ts", "../../../tmp-toolkit-helpers/src/api/bootstrap/deploy-bootstrap.ts", "../../../tmp-toolkit-helpers/src/api/bootstrap/bootstrap-props.ts", "../../../tmp-toolkit-helpers/src/api/deployments/deployments.ts", "../../../tmp-toolkit-helpers/src/api/deployments/asset-manifest-builder.ts", "../../../tmp-toolkit-helpers/src/api/deployments/asset-publishing.ts", "../../../tmp-toolkit-helpers/src/api/deployments/cfn-api.ts", "../../../tmp-toolkit-helpers/src/api/resource-metadata/resource-metadata.ts", "../../../tmp-toolkit-helpers/src/api/cloudformation/evaluate-cloudformation-template.ts", "../../../tmp-toolkit-helpers/src/api/cloudformation/template-body-parameter.ts", "../../../tmp-toolkit-helpers/src/api/cloudformation/nested-stack-helpers.ts", "../../../tmp-toolkit-helpers/src/api/stack-events/stack-activity-monitor.ts", "../../../tmp-toolkit-helpers/src/api/stack-events/stack-event-poller.ts", "../../../tmp-toolkit-helpers/src/api/stack-events/stack-progress-monitor.ts", "../../../tmp-toolkit-helpers/src/api/stack-events/stack-status.ts", "../../../tmp-toolkit-helpers/src/api/cloudformation/stack-helpers.ts", "../../../tmp-toolkit-helpers/src/api/deployments/checks.ts", "../../../tmp-toolkit-helpers/src/api/deployments/deploy-stack.ts", "../../../tmp-toolkit-helpers/src/api/deployments/assets.ts", "../../../tmp-toolkit-helpers/src/api/hotswap/common.ts", "../../../tmp-toolkit-helpers/src/api/hotswap/hotswap-deployments.ts", "../../../tmp-toolkit-helpers/src/api/deployments/deployment-result.ts", "../../../tmp-toolkit-helpers/src/api/hotswap/appsync-mapping-templates.ts", "../../../tmp-toolkit-helpers/src/api/hotswap/code-build-projects.ts", "../../../tmp-toolkit-helpers/src/api/hotswap/ecs-services.ts", "../../../tmp-toolkit-helpers/src/api/hotswap/lambda-functions.ts", "../../../tmp-toolkit-helpers/src/api/hotswap/s3-bucket-deployments.ts", "../../../tmp-toolkit-helpers/src/api/hotswap/stepfunctions-state-machines.ts", "../../../tmp-toolkit-helpers/src/api/notices.ts", "../../../tmp-toolkit-helpers/src/api/tree.ts", "../../../tmp-toolkit-helpers/src/api/toolkit-info.ts", "../../../tmp-toolkit-helpers/src/api/environment/environment-resources.ts", "../../../tmp-toolkit-helpers/src/api/environment/placeholders.ts", "../../../tmp-toolkit-helpers/src/api/environment/environment-access.ts", "../../../tmp-toolkit-helpers/src/api/bootstrap/legacy-template.ts", "../../../tmp-toolkit-helpers/src/api/cloud-assembly/environment.ts", "../../../tmp-toolkit-helpers/src/api/cloud-assembly/stack-assembly.ts", "../../../tmp-toolkit-helpers/src/api/cloud-assembly/stack-collection.ts", "../../../tmp-toolkit-helpers/src/api/cloud-assembly/stack-selector.ts", "../../../tmp-toolkit-helpers/src/api/settings.ts", "../../../tmp-toolkit-helpers/src/api/context.ts", "../../../tmp-toolkit-helpers/src/api/diff/diff-formatter.ts", "../../../tmp-toolkit-helpers/src/api/require-approval.ts", "../../../tmp-toolkit-helpers/src/api/garbage-collection/garbage-collector.ts", "../../../tmp-toolkit-helpers/src/api/garbage-collection/progress-printer.ts", "../../../tmp-toolkit-helpers/src/api/garbage-collection/stack-refresh.ts", "../../../tmp-toolkit-helpers/src/api/logs-monitor/logs-monitor.ts", "../../../tmp-toolkit-helpers/src/api/logs-monitor/find-cloudwatch-logs.ts", "../../../tmp-toolkit-helpers/src/api/resource-import/importer.ts", "../../../tmp-toolkit-helpers/src/api/resource-import/migrator.ts", "../../../tmp-toolkit-helpers/src/api/rwlock.ts", "../../../tmp-toolkit-helpers/src/api/work-graph/work-graph-types.ts", "../../../tmp-toolkit-helpers/src/api/work-graph/work-graph.ts", "../../../tmp-toolkit-helpers/src/api/work-graph/work-graph-builder.ts", "../../../tmp-toolkit-helpers/src/api/tags.ts", "../../../tmp-toolkit-helpers/src/context-providers/index.ts", "../../../tmp-toolkit-helpers/src/context-providers/ami.ts", "../../../tmp-toolkit-helpers/src/context-providers/availability-zones.ts", "../../../tmp-toolkit-helpers/src/context-providers/cc-api-provider.ts", "../../../tmp-toolkit-helpers/src/context-providers/endpoint-service-availability-zones.ts", "../../../tmp-toolkit-helpers/src/context-providers/hosted-zones.ts", "../../../tmp-toolkit-helpers/src/context-providers/keys.ts", "../../../tmp-toolkit-helpers/src/context-providers/load-balancers.ts", "../../../tmp-toolkit-helpers/src/context-providers/security-groups.ts", "../../../tmp-toolkit-helpers/src/context-providers/ssm-parameters.ts", "../../../tmp-toolkit-helpers/src/context-providers/vpcs.ts"],
4
- "sourcesContent": ["/* eslint-disable import/no-restricted-paths */\n\nexport * from '../../../tmp-toolkit-helpers/src/api/io/private';\nexport * from '../../../tmp-toolkit-helpers/src/private';\nexport * from '../../../tmp-toolkit-helpers/src/api';\nexport * as cfnApi from '../../../tmp-toolkit-helpers/src/api/deployments/cfn-api';\n\n// Context Providers\nexport * as contextproviders from '../../../tmp-toolkit-helpers/src/context-providers';\n", "import * as util from 'node:util';\nimport * as uuid from 'uuid';\nimport type { ActionLessMessage, IoHelper } from './io-helper';\nimport type { IoMessageMaker } from './message-maker';\nimport type { Duration } from '../../../payloads/types';\nimport { formatTime } from '../../../util';\n\nexport interface SpanEnd {\n readonly duration: number;\n}\n\n/**\n * Describes a specific span\n *\n * A span definition is a pair of `IoMessageMaker`s to create a start and end message of the span respectively.\n * It also has a display name, that is used for auto-generated message text when they are not provided.\n */\nexport interface SpanDefinition<S extends object, E extends SpanEnd> {\n readonly name: string;\n readonly start: IoMessageMaker<S>;\n readonly end: IoMessageMaker<E>;\n}\n\n/**\n * Used in conditional types to check if a type (e.g. after omitting fields) is an empty object\n * This is needed because counter-intuitive neither `object` nor `{}` represent that.\n */\ntype EmptyObject = {\n [index: string | number | symbol]: never;\n}\n\n/**\n * Helper type to force a parameter to be not present of the computed type is an empty object\n */\ntype VoidWhenEmpty<T> = T extends EmptyObject ? void : T\n\n/**\n * Helper type to force a parameter to be an empty object if the computed type is an empty object\n * This is weird, but some computed types (e.g. using `Omit`) don't end up enforcing this.\n */\ntype ForceEmpty<T> = T extends EmptyObject ? EmptyObject : T\n\n/**\n * Make some properties optional\n */\ntype Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>;\n\n/**\n * Ending the span returns the observed duration\n */\ninterface ElapsedTime {\n readonly asMs: number;\n readonly asSec: number;\n}\n\n/**\n * A message span that can be ended and read times from\n */\nexport interface IMessageSpan<E extends SpanEnd> {\n /**\n * Get the time elapsed since the start\n */\n elapsedTime(): Promise<ElapsedTime>;\n /**\n * Sends a simple, generic message with the current timing\n * For more complex intermediate messages, get the `elapsedTime` and use `notify`\n */\n timing(maker: IoMessageMaker<Duration>, message?: string): Promise<ElapsedTime>;\n /**\n * Sends an arbitrary intermediate message as part of the span\n */\n notify(message: ActionLessMessage<unknown>): Promise<void>;\n /**\n * End the span with a payload\n */\n end(payload: VoidWhenEmpty<Omit<E, keyof SpanEnd>>): Promise<ElapsedTime>;\n /**\n * End the span with a payload, overwriting\n */\n end(payload: VoidWhenEmpty<Optional<E, keyof SpanEnd>>): Promise<ElapsedTime>;\n /**\n * End the span with a message and payload\n */\n end(message: string, payload: ForceEmpty<Optional<E, keyof SpanEnd>>): Promise<ElapsedTime>;\n}\n\n/**\n * Helper class to make spans around blocks of work\n *\n * Blocks are enclosed by a start and end message.\n * All messages of the span share a unique id.\n * The end message contains the time passed between start and end.\n */\nexport class SpanMaker<S extends object, E extends SpanEnd> {\n private readonly definition: SpanDefinition<S, E>;\n private readonly ioHelper: IoHelper;\n\n public constructor(ioHelper: IoHelper, definition: SpanDefinition<S, E>) {\n this.definition = definition;\n this.ioHelper = ioHelper;\n }\n\n /**\n * Starts the span and initially notifies the IoHost\n * @returns a message span\n */\n public async begin(payload: VoidWhenEmpty<S>): Promise<IMessageSpan<E>>;\n public async begin(message: string, payload: S): Promise<IMessageSpan<E>>;\n public async begin(a: any, b?: S): Promise<IMessageSpan<E>> {\n const spanId = uuid.v4();\n const startTime = new Date().getTime();\n\n const notify = (msg: ActionLessMessage<unknown>): Promise<void> => {\n return this.ioHelper.notify(withSpanId(spanId, msg));\n };\n\n const startInput = parseArgs<S>(a, b);\n const startMsg = startInput.message ?? `Starting ${this.definition.name} ...`;\n const startPayload = startInput.payload;\n\n await notify(this.definition.start.msg(\n startMsg,\n startPayload,\n ));\n\n const timingMsgTemplate = '\\n\u2728 %s time: %ds\\n';\n const time = () => {\n const elapsedTime = new Date().getTime() - startTime;\n return {\n asMs: elapsedTime,\n asSec: formatTime(elapsedTime),\n };\n };\n\n return {\n elapsedTime: async (): Promise<ElapsedTime> => {\n return time();\n },\n\n notify: async(msg: ActionLessMessage<unknown>): Promise<void> => {\n await notify(msg);\n },\n\n timing: async(maker: IoMessageMaker<Duration>, message?: string): Promise<ElapsedTime> => {\n const duration = time();\n const timingMsg = message ? message : util.format(timingMsgTemplate, this.definition.name, duration.asSec);\n await notify(maker.msg(timingMsg, {\n duration: duration.asMs,\n }));\n return duration;\n },\n\n end: async (x: any, y?: ForceEmpty<Optional<E, keyof SpanEnd>>): Promise<ElapsedTime> => {\n const duration = time();\n\n const endInput = parseArgs<ForceEmpty<Optional<E, keyof SpanEnd>>>(x, y);\n const endMsg = endInput.message ?? util.format(timingMsgTemplate, this.definition.name, duration.asSec);\n const endPayload = endInput.payload;\n\n await notify(this.definition.end.msg(\n endMsg, {\n duration: duration.asMs,\n ...endPayload,\n } as E));\n\n return duration;\n },\n };\n }\n}\n\nfunction parseArgs<S extends object>(first: any, second?: S): { message: string | undefined; payload: S } {\n const firstIsMessage = typeof first === 'string';\n\n // When the first argument is a string or we have a second argument, then the first arg is the message\n const message = (firstIsMessage || second) ? first : undefined;\n\n // When the first argument is a string or we have a second argument,\n // then the second arg is the payload, otherwise the first arg is the payload\n const payload = (firstIsMessage || second) ? second : first;\n\n return {\n message,\n payload,\n };\n}\n\nfunction withSpanId(span: string, message: ActionLessMessage<unknown>): ActionLessMessage<unknown> {\n return {\n ...message,\n span,\n };\n}\n", "import { error } from 'console';\nimport { createWriteStream, promises as fs } from 'fs';\nimport * as path from 'path';\nimport * as glob from 'glob';\nimport { formatErrorMessage } from './format-error';\n\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nconst archiver = require('archiver');\n\n// Adapted from cdk-assets\nexport async function zipDirectory(directory: string, outputFile: string): Promise<void> {\n // We write to a temporary file and rename at the last moment. This is so that if we are\n // interrupted during this process, we don't leave a half-finished file in the target location.\n const temporaryOutputFile = `${outputFile}.${randomString()}._tmp`;\n await writeZipFile(directory, temporaryOutputFile);\n await moveIntoPlace(temporaryOutputFile, outputFile);\n}\n\nfunction writeZipFile(directory: string, outputFile: string): Promise<void> {\n return new Promise(async (ok, fail) => {\n // The below options are needed to support following symlinks when building zip files:\n // - nodir: This will prevent symlinks themselves from being copied into the zip.\n // - follow: This will follow symlinks and copy the files within.\n const globOptions = {\n dot: true,\n nodir: true,\n follow: true,\n cwd: directory,\n };\n const files = glob.sync('**', globOptions); // The output here is already sorted\n\n const output = createWriteStream(outputFile);\n\n const archive = archiver('zip');\n archive.on('warning', fail);\n archive.on('error', fail);\n\n // archive has been finalized and the output file descriptor has closed, resolve promise\n // this has to be done before calling `finalize` since the events may fire immediately after.\n // see https://www.npmjs.com/package/archiver\n output.once('close', ok);\n\n archive.pipe(output);\n\n // Append files serially to ensure file order\n for (const file of files) {\n const fullPath = path.resolve(directory, file);\n // Exactly 2 promises\n // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism\n const [data, stat] = await Promise.all([fs.readFile(fullPath), fs.stat(fullPath)]);\n archive.append(data, {\n name: file,\n mode: stat.mode,\n });\n }\n\n await archive.finalize();\n });\n}\n\n/**\n * Rename the file to the target location, taking into account:\n *\n * - That we may see EPERM on Windows while an Antivirus scanner still has the\n * file open, so retry a couple of times.\n * - This same function may be called in parallel and be interrupted at any point.\n */\nasync function moveIntoPlace(source: string, target: string) {\n let delay = 100;\n let attempts = 5;\n while (true) {\n try {\n // 'rename' is guaranteed to overwrite an existing target, as long as it is a file (not a directory)\n await fs.rename(source, target);\n return;\n } catch (e: any) {\n if (e.code !== 'EPERM' || attempts-- <= 0) {\n throw e;\n }\n error(formatErrorMessage(e));\n await sleep(Math.floor(Math.random() * delay));\n delay *= 2;\n }\n }\n}\n\nfunction sleep(ms: number) {\n return new Promise(ok => setTimeout(ok, ms));\n}\n\nfunction randomString() {\n return Math.random().toString(36).replace(/[^a-z0-9]+/g, '');\n}\n", "/**\n * Takes in an error and returns a correctly formatted string of its error message.\n * If it is an AggregateError, it will return a string with all the inner errors\n * formatted and separated by a newline.\n *\n * @param error The error to format\n * @returns A string with the error message(s) of the error\n */\nexport function formatErrorMessage(error: any): string {\n if (error && Array.isArray(error.errors)) {\n const innerMessages = error.errors\n .map((innerError: { message: any; toString: () => any }) => (innerError?.message || innerError?.toString()))\n .join('\\n');\n return `AggregateError: ${innerMessages}`;\n }\n\n // Fallback for regular Error or other types\n return error?.message || error?.toString() || 'Unknown error';\n}\n", "/**\n * Map a function over an array and concatenate the results\n */\nexport function flatMap<T, U>(xs: T[], fn: ((x: T, i: number) => U[])): U[] {\n return flatten(xs.map(fn));\n}\n\n/**\n * Flatten a list of lists into a list of elements\n */\nexport function flatten<T>(xs: T[][]): T[] {\n return Array.prototype.concat.apply([], xs);\n}\n\n/**\n * Partition a collection by removing and returning all elements that match a predicate\n *\n * Note: the input collection is modified in-place!\n */\nexport function partition<T>(collection: T[], pred: (x: T) => boolean): T[] {\n const ret: T[] = [];\n let i = 0;\n while (i < collection.length) {\n if (pred(collection[i])) {\n ret.push(collection.splice(i, 1)[0]);\n } else {\n i++;\n }\n }\n return ret;\n}\n", "/**\n * Format bytes as a human readable string\n *\n * @param bytes Number of bytes to format\n * @param decimals Number of decimal places to show (default 2)\n * @returns Formatted string with appropriate unit suffix\n */\nexport function formatBytes(bytes: number, decimals: number = 2): string {\n decimals = decimals < 0 ? 0 : decimals;\n\n if (bytes === 0) {\n return '0 Bytes';\n }\n\n const k = 1024;\n const sizes = ['Bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];\n\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n\n return `${parseFloat((bytes / Math.pow(k, i)).toFixed(decimals))} ${sizes[i]}`;\n}\n", "/**\n * Validate SNS topic arn\n */\nexport function validateSnsTopicArn(arn: string): boolean {\n return /^arn:aws:sns:[a-z0-9\\-]+:[0-9]+:[a-z0-9\\-\\_]+$/i.test(arn);\n}\n\n/**\n * Does a Stack Event have an error message based on the status.\n */\nexport function stackEventHasErrorMessage(status: string): boolean {\n return status.endsWith('_FAILED') || status === 'ROLLBACK_IN_PROGRESS' || status === 'UPDATE_ROLLBACK_IN_PROGRESS';\n}\n\n/**\n * Calculate the maximal length of all resource types for a given template.\n *\n * @param template the stack template to analyze\n * @param startWidth the initial width to start with. Defaults to the length of 'AWS::CloudFormation::Stack'.\n * @returns the determined width\n */\nexport function maxResourceTypeLength(template: any, startWidth = 'AWS::CloudFormation::Stack'.length): number {\n const resources = (template && template.Resources) || {};\n let maxWidth = startWidth;\n for (const id of Object.keys(resources)) {\n const type = resources[id].Type || '';\n if (type.length > maxWidth) {\n maxWidth = type.length;\n }\n }\n return maxWidth;\n}\n", "import * as crypto from 'crypto';\n\nexport function contentHash(data: string | Buffer | DataView) {\n return crypto.createHash('sha256').update(data).digest('hex');\n}\n\n/**\n * A stably sorted hash of an arbitrary JS object\n */\nexport function contentHashAny(value: unknown) {\n const ret = crypto.createHash('sha256');\n recurse(value);\n return ret.digest('hex');\n\n function recurse(x: unknown) {\n if (typeof x === 'string') {\n ret.update(x);\n return;\n }\n\n if (Array.isArray(x)) {\n ret.update('[');\n for (const e of x) {\n recurse(e);\n ret.update('||');\n }\n ret.update(']');\n return;\n }\n\n if (x && typeof x === 'object') {\n ret.update('{');\n for (const key of Object.keys(x).sort()) {\n ret.update(key);\n ret.update(':');\n recurse((x as any)[key]);\n }\n ret.update('}');\n return;\n }\n\n ret.update(`${x}${typeof x}`); // typeof to make sure hash('123') !== hash(123)\n }\n}\n", "import * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\nimport { ToolkitError } from '../api/toolkit-error';\n\n/**\n * Return a location that will be used as the CDK home directory.\n * Currently the only thing that is placed here is the cache.\n *\n * First try to use the users home directory (i.e. /home/someuser/),\n * but if that directory does not exist for some reason create a tmp directory.\n *\n * Typically it wouldn't make sense to create a one time use tmp directory for\n * the purpose of creating a cache, but since this only applies to users that do\n * not have a home directory (some CI systems?) this should be fine.\n */\nexport function cdkHomeDir() {\n const tmpDir = fs.realpathSync(os.tmpdir());\n let home;\n try {\n let userInfoHome: string | undefined = os.userInfo().homedir;\n // Node returns this if the user doesn't have a home directory\n /* c8 ignore start */ // will not happen in normal setups\n if (userInfoHome == '/var/empty') {\n userInfoHome = undefined;\n }\n /* c8 ignore stop */\n home = path.join((userInfoHome ?? os.homedir()).trim(), '.cdk');\n } catch {\n }\n return process.env.CDK_HOME\n ? path.resolve(process.env.CDK_HOME)\n : home || fs.mkdtempSync(path.join(tmpDir, '.cdk')).trim();\n}\n\nexport function cdkCacheDir() {\n return path.join(cdkHomeDir(), 'cache');\n}\n\n/**\n * From the start location, find the directory that contains the bundled package's package.json\n *\n * You must assume the caller of this function will be bundled and the package root dir\n * is not going to be the same as the package the caller currently lives in.\n */\nexport function bundledPackageRootDir(start: string): string;\nexport function bundledPackageRootDir(start: string, fail: true): string;\nexport function bundledPackageRootDir(start: string, fail: false): string | undefined;\nexport function bundledPackageRootDir(start: string, fail?: boolean) {\n function _rootDir(dirname: string): string | undefined {\n const manifestPath = path.join(dirname, 'package.json');\n if (fs.existsSync(manifestPath)) {\n return dirname;\n }\n if (path.dirname(dirname) === dirname) {\n if (fail ?? true) {\n throw new ToolkitError('Unable to find package manifest');\n }\n return undefined;\n }\n return _rootDir(path.dirname(dirname));\n }\n\n return _rootDir(start);\n}\n", "import type * as cxapi from '@aws-cdk/cx-api';\n\nconst TOOLKIT_ERROR_SYMBOL = Symbol.for('@aws-cdk/toolkit-lib.ToolkitError');\nconst AUTHENTICATION_ERROR_SYMBOL = Symbol.for('@aws-cdk/toolkit-lib.AuthenticationError');\nconst ASSEMBLY_ERROR_SYMBOL = Symbol.for('@aws-cdk/toolkit-lib.AssemblyError');\nconst CONTEXT_PROVIDER_ERROR_SYMBOL = Symbol.for('@aws-cdk/toolkit-lib.ContextProviderError');\n\n/**\n * Represents a general toolkit error in the AWS CDK Toolkit.\n */\nexport class ToolkitError extends Error {\n /**\n * Determines if a given error is an instance of ToolkitError.\n */\n public static isToolkitError(x: any): x is ToolkitError {\n return x !== null && typeof(x) === 'object' && TOOLKIT_ERROR_SYMBOL in x;\n }\n\n /**\n * Determines if a given error is an instance of AuthenticationError.\n */\n public static isAuthenticationError(x: any): x is AuthenticationError {\n return this.isToolkitError(x) && AUTHENTICATION_ERROR_SYMBOL in x;\n }\n\n /**\n * Determines if a given error is an instance of AssemblyError.\n */\n public static isAssemblyError(x: any): x is AssemblyError {\n return this.isToolkitError(x) && ASSEMBLY_ERROR_SYMBOL in x;\n }\n\n /**\n * Determines if a given error is an instance of AssemblyError.\n */\n public static isContextProviderError(x: any): x is ContextProviderError {\n return this.isToolkitError(x) && CONTEXT_PROVIDER_ERROR_SYMBOL in x;\n }\n\n /**\n * An AssemblyError with an original error as cause\n */\n public static withCause(message: string, error: unknown): ToolkitError {\n return new ToolkitError(message, 'toolkit', error);\n }\n\n /**\n * The type of the error, defaults to \"toolkit\".\n */\n public readonly type: string;\n\n /**\n * Denotes the source of the error as the toolkit.\n */\n public readonly source: 'toolkit' | 'user';\n\n /**\n * The specific original cause of the error, if available\n */\n public readonly cause?: unknown;\n\n constructor(message: string, type: string = 'toolkit', cause?: unknown) {\n super(message);\n Object.setPrototypeOf(this, ToolkitError.prototype);\n Object.defineProperty(this, TOOLKIT_ERROR_SYMBOL, { value: true });\n this.name = new.target.name;\n this.type = type;\n this.source = 'toolkit';\n this.cause = cause;\n }\n}\n\n/**\n * Represents an authentication-specific error in the AWS CDK Toolkit.\n */\nexport class AuthenticationError extends ToolkitError {\n /**\n * Denotes the source of the error as user.\n */\n public readonly source = 'user';\n\n constructor(message: string) {\n super(message, 'authentication');\n Object.setPrototypeOf(this, AuthenticationError.prototype);\n Object.defineProperty(this, AUTHENTICATION_ERROR_SYMBOL, { value: true });\n }\n}\n\n/**\n * Represents an error causes by cloud assembly synthesis\n *\n * This includes errors thrown during app execution, as well as failing annotations.\n */\nexport class AssemblyError extends ToolkitError {\n /**\n * An AssemblyError with an original error as cause\n */\n public static withCause(message: string, error: unknown): AssemblyError {\n return new AssemblyError(message, undefined, error);\n }\n\n /**\n * An AssemblyError with a list of stacks as cause\n */\n public static withStacks(message: string, stacks?: cxapi.CloudFormationStackArtifact[]): AssemblyError {\n return new AssemblyError(message, stacks);\n }\n\n /**\n * Denotes the source of the error as user.\n */\n public readonly source = 'user';\n\n /**\n * The stacks that caused the error, if available\n *\n * The `messages` property of each `cxapi.CloudFormationStackArtifact` will contain the respective errors.\n * Absence indicates synthesis didn't fully complete.\n */\n public readonly stacks?: cxapi.CloudFormationStackArtifact[];\n\n private constructor(message: string, stacks?: cxapi.CloudFormationStackArtifact[], cause?: unknown) {\n super(message, 'assembly', cause);\n Object.setPrototypeOf(this, AssemblyError.prototype);\n Object.defineProperty(this, ASSEMBLY_ERROR_SYMBOL, { value: true });\n this.stacks = stacks;\n }\n}\n\n/**\n * Represents an error originating from a Context Provider\n */\nexport class ContextProviderError extends ToolkitError {\n /**\n * Denotes the source of the error as user.\n */\n public readonly source = 'user';\n\n constructor(message: string) {\n super(message, 'context-provider');\n Object.setPrototypeOf(this, ContextProviderError.prototype);\n Object.defineProperty(this, CONTEXT_PROVIDER_ERROR_SYMBOL, { value: true });\n }\n}\n", "/**\n * This gets the values of the jsonObject at the paths specified in propertiesToReturn.\n *\n * For example, jsonObject = {\n * key1: 'abc',\n * key2: {\n * foo: 'qwerty',\n * bar: 'data',\n * }\n * }\n *\n * propertiesToReturn = ['key1', 'key2.foo'];\n *\n * The returned object is:\n *\n * ```\n * {\n * key1: 'abc',\n * 'key2.foo': 'qwerty',\n * Identifier: identifier\n * }\n * ```\n */\nexport function getResultObj(jsonObject: any, identifier: string, propertiesToReturn: string[]): {[key: string]: any} {\n const propsObj = {};\n propertiesToReturn.forEach((propName) => {\n Object.assign(propsObj, { [propName]: findJsonValue(jsonObject, propName) });\n });\n Object.assign(propsObj, { ['Identifier']: identifier });\n return propsObj;\n}\n\n/**\n * This finds the value of the jsonObject at the path. Path is delimited by '.'.\n *\n * For example, jsonObject = {\n * key1: 'abc',\n * key2: {\n * foo: 'qwerty',\n * bar: 'data',\n * }\n * }\n *\n * If path is 'key1', then it will return 'abc'.\n * If path is 'key2.foo', then it will return 'qwerty'.\n * If path is 'key2', then it will return the object:\n * {\n * foo: 'qwerty',\n * bar: 'data',\n * }\n *\n * If the path is not found, an Error will be thrown stating which token is missing.\n */\nexport function findJsonValue(jsonObject: any, path: string): any {\n const paths = path.split('.');\n let obj = jsonObject;\n paths.forEach(p => {\n obj = obj[p];\n if (obj === undefined) {\n throw new TypeError(`Cannot read field ${path}. ${p} is not found.`);\n }\n });\n return obj;\n}\n", "/**\n * Type of a map mapping strings to some arbitrary type\n *\n * Name is not ideal, but:\n *\n * - Cannot call it Object, that already means something.\n * - Cannot call it Dict or Dictionary, since in other languages\n * those also allow specifying the key type.\n */\nexport type Obj<T> = {[key: string]: T};\n\n/**\n * Return whether the given value is an object\n *\n * Even though arrays technically are objects, we usually want to treat them differently,\n * so we return false in those cases.\n */\nexport function isObject(x: any): x is Obj<any> {\n return x !== null && typeof x === 'object' && !isArray(x);\n}\n\n/**\n * Return whether the given value is an array\n */\nexport const isArray = Array.isArray;\n\n/**\n * Return the value of the first argument if it's not undefined, otherwise the default\n */\nexport function ifDefined<T>(x: T | undefined, def: T): T {\n return typeof x !== 'undefined' ? x : def;\n}\n", "import type { Obj } from './types';\nimport { isArray, isObject } from './types';\nimport { ToolkitError } from '../api/toolkit-error';\n\n/**\n * Return a new object by adding missing keys into another object\n */\nexport function applyDefaults(hash: any, defaults: any) {\n const result: any = { };\n\n Object.keys(hash).forEach(k => result[k] = hash[k]);\n\n Object.keys(defaults)\n .filter(k => !(k in result))\n .forEach(k => result[k] = defaults[k]);\n\n return result;\n}\n\n/**\n * Return whether the given parameter is an empty object or empty list.\n */\nexport function isEmpty(x: any) {\n if (x == null) {\n return false;\n }\n if (isArray(x)) {\n return x.length === 0;\n }\n return Object.keys(x).length === 0;\n}\n\n/**\n * Deep clone a tree of objects, lists or scalars\n *\n * Does not support cycles.\n */\nexport function deepClone(x: any): any {\n if (typeof x === 'undefined') {\n return undefined;\n }\n if (x === null) {\n return null;\n }\n if (isArray(x)) {\n return x.map(deepClone);\n }\n if (isObject(x)) {\n return makeObject(mapObject(x, (k, v) => [k, deepClone(v)] as [string, any]));\n }\n return x;\n}\n\n/**\n * Map over an object, treating it as a dictionary\n */\nexport function mapObject<T, U>(x: Obj<T>, fn: (key: string, value: T) => U): U[] {\n const ret: U[] = [];\n Object.keys(x).forEach(key => {\n ret.push(fn(key, x[key]));\n });\n return ret;\n}\n\n/**\n * Construct an object from a list of (k, v) pairs\n */\nexport function makeObject<T>(pairs: Array<[string, T]>): Obj<T> {\n const ret: Obj<T> = {};\n for (const pair of pairs) {\n ret[pair[0]] = pair[1];\n }\n return ret;\n}\n\n/**\n * Deep get a value from a tree of nested objects\n *\n * Returns undefined if any part of the path was unset or\n * not an object.\n */\nexport function deepGet(x: any, path: string[]): any {\n path = path.slice();\n\n while (path.length > 0 && isObject(x)) {\n const key = path.shift()!;\n x = x[key];\n }\n return path.length === 0 ? x : undefined;\n}\n\n/**\n * Deep set a value in a tree of nested objects\n *\n * Throws an error if any part of the path is not an object.\n */\nexport function deepSet(x: any, path: string[], value: any) {\n path = path.slice();\n\n if (path.length === 0) {\n throw new ToolkitError('Path may not be empty');\n }\n\n while (path.length > 1 && isObject(x)) {\n const key = path.shift()!;\n\n if (isPrototypePollutingKey(key)) {\n continue;\n }\n\n if (!(key in x)) {\n x[key] = {};\n }\n x = x[key];\n }\n\n if (!isObject(x)) {\n throw new ToolkitError(`Expected an object, got '${x}'`);\n }\n\n const finalKey = path[0];\n\n if (isPrototypePollutingKey(finalKey)) {\n return;\n }\n\n if (value !== undefined) {\n x[finalKey] = value;\n } else {\n delete x[finalKey];\n }\n}\n\n/**\n * Helper to detect prototype polluting keys\n *\n * A key matching this, MUST NOT be used in an assignment.\n * Use this to check user-input.\n */\nfunction isPrototypePollutingKey(key: string) {\n return key === '__proto__' || key === 'constructor' || key === 'prototype';\n}\n\n/**\n * Recursively merge objects together\n *\n * The leftmost object is mutated and returned. Arrays are not merged\n * but overwritten just like scalars.\n *\n * If an object is merged into a non-object, the non-object is lost.\n */\nexport function deepMerge(...objects: Array<Obj<any> | undefined>) {\n function mergeOne(target: Obj<any>, source: Obj<any>) {\n for (const key of Object.keys(source)) {\n if (isPrototypePollutingKey(key)) {\n continue;\n }\n\n const value = source[key];\n\n if (isObject(value)) {\n if (!isObject(target[key])) {\n target[key] = {};\n } // Overwrite on purpose\n mergeOne(target[key], value);\n } else if (typeof value !== 'undefined') {\n target[key] = value;\n }\n }\n }\n\n const others = objects.filter(x => x != null) as Array<Obj<any>>;\n\n if (others.length === 0) {\n return {};\n }\n const into = others.splice(0, 1)[0];\n\n others.forEach(other => mergeOne(into, other));\n return into;\n}\n\n/**\n * Splits the given object into two, such that:\n *\n * 1. The size of the first object (after stringified in UTF-8) is less than or equal to the provided size limit.\n * 2. Merging the two objects results in the original one.\n */\nexport function splitBySize(data: any, maxSizeBytes: number): [any, any] {\n if (maxSizeBytes < 2) {\n // It's impossible to fit anything in the first object\n return [undefined, data];\n }\n const entries = Object.entries(data);\n return recurse(0, 0);\n\n function recurse(index: number, runningTotalSize: number): [any, any] {\n if (index >= entries.length) {\n // Everything fits in the first object\n return [data, undefined];\n }\n\n const size = runningTotalSize + entrySize(entries[index]);\n return (size > maxSizeBytes) ? cutAt(index) : recurse(index + 1, size);\n }\n\n function entrySize(entry: [string, unknown]) {\n return Buffer.byteLength(JSON.stringify(Object.fromEntries([entry])));\n }\n\n function cutAt(index: number): [any, any] {\n return [\n Object.fromEntries(entries.slice(0, index)),\n Object.fromEntries(entries.slice(index)),\n ];\n }\n}\n\ntype Exclude = { [key: string]: Exclude | true };\n\n/**\n * This function transforms all keys (recursively) in the provided `val` object.\n *\n * @param val The object whose keys need to be transformed.\n * @param transform The function that will be applied to each key.\n * @param exclude The keys that will not be transformed and copied to output directly\n * @returns A new object with the same values as `val`, but with all keys transformed according to `transform`.\n */\nexport function transformObjectKeys(val: any, transform: (str: string) => string, exclude: Exclude = {}): any {\n if (val == null || typeof val !== 'object') {\n return val;\n }\n if (Array.isArray(val)) {\n // For arrays we just pass parent's exclude object directly\n // since it makes no sense to specify different exclude options for each array element\n return val.map((input: any) => transformObjectKeys(input, transform, exclude));\n }\n const ret: { [k: string]: any } = {};\n for (const [k, v] of Object.entries(val)) {\n const childExclude = exclude[k];\n if (childExclude === true) {\n // we don't transform this object if the key is specified in exclude\n ret[transform(k)] = v;\n } else {\n ret[transform(k)] = transformObjectKeys(v, transform, childExclude);\n }\n }\n return ret;\n}\n", "/**\n * Run a number of promise generators with max parallelism\n *\n * Order is not maintained between the input and output.\n */\nexport async function parallelPromises<A>(n: number, promises: Array<() => Promise<A>>): Promise<Array<A>> {\n const ret = new Array<A>();\n let count = 0;\n let error: Error | undefined;\n const queue = [...promises];\n\n return new Promise((ok, ko) => {\n tick();\n\n function tick() {\n if (count === 0 && error) {\n ko(error);\n return;\n }\n if (count === 0 && queue.length === 0) {\n ok(ret);\n return;\n }\n\n while (count < n && queue.length > 0 && !error) {\n const next = queue.shift();\n if (next !== undefined) {\n start(next);\n }\n }\n }\n\n function start(fn: () => Promise<A>) {\n count += 1;\n fn()\n .then((result) => {\n ret.push(result);\n })\n .catch((e) => {\n error = e;\n })\n .finally(() => {\n count -= 1;\n tick();\n });\n }\n });\n}\n", "import * as fs from 'fs/promises';\nimport { formatBytes } from './bytes';\nimport * as yaml_cfn from './yaml-cfn';\n\n/**\n * Stringify to YAML\n */\nexport function toYAML(obj: any): string {\n return yaml_cfn.serialize(obj);\n}\n\n/**\n * Parse either YAML or JSON\n */\nexport function deserializeStructure(str: string): any {\n return yaml_cfn.deserialize(str);\n}\n\n/**\n * Serialize to either YAML or JSON\n */\nexport function serializeStructure(object: any, json: boolean) {\n if (json) {\n return JSON.stringify(object, undefined, 2);\n } else {\n return toYAML(object);\n }\n}\n\n/**\n * Load a YAML or JSON file from disk\n */\nexport async function loadStructuredFile(fileName: string) {\n const contents = await fs.readFile(fileName, { encoding: 'utf-8' });\n return deserializeStructure(contents);\n}\n\n/**\n * Remove any template elements that we don't want to show users.\n */\nexport function obscureTemplate(template: any = {}) {\n if (template.Rules) {\n // see https://github.com/aws/aws-cdk/issues/17942\n if (template.Rules.CheckBootstrapVersion) {\n if (Object.keys(template.Rules).length > 1) {\n delete template.Rules.CheckBootstrapVersion;\n } else {\n delete template.Rules;\n }\n }\n }\n\n return template;\n}\n\n/**\n * Detects a buffer that has been converted to a JSON-like object\n * In Node, `Buffer`s have `toJSON()` method that converts the buffer\n * into a JS object that can be JSON stringified.\n * Unfortunately this conversion happens before the replacer is called,\n * so normal means of detecting a `Buffer` objet don't work anymore.\n * @see https://github.com/nodejs/node-v0.x-archive/issues/5110\n */\nfunction isJsonBuffer(value: any): value is {\n type: 'Buffer';\n data: number[];\n} {\n return typeof value === 'object'\n && 'type' in value\n && value.type === 'Buffer'\n && 'data' in value\n && Array.isArray(value.data);\n}\n\n/**\n * A JSON.stringify() replacer that converts Buffers into a string with information\n * Use this if you plan to print out JSON stringified objects that may contain a Buffer.\n * Without this, large buffers (think: Megabytes) will completely fill up the output\n * and even crash the system.\n */\nexport function replacerBufferWithInfo(_key: any, value: any): any {\n if (isJsonBuffer(value)) {\n return `<Buffer: ${formatBytes(value.data.length)}>`;\n }\n return value;\n}\n", "import * as yaml from 'yaml';\nimport type * as yaml_cst from 'yaml/parse-cst';\nimport * as yaml_types from 'yaml/types';\n\n/**\n * Serializes the given data structure into valid YAML.\n *\n * @param obj the data structure to serialize\n * @returns a string containing the YAML representation of {@param obj}\n */\nexport function serialize(obj: any): string {\n const oldFold = yaml_types.strOptions.fold.lineWidth;\n try {\n yaml_types.strOptions.fold.lineWidth = 0;\n return yaml.stringify(obj, { schema: 'yaml-1.1' });\n } finally {\n yaml_types.strOptions.fold.lineWidth = oldFold;\n }\n}\n\n/**\n * Deserialize the YAML into the appropriate data structure.\n *\n * @param str the string containing YAML\n * @returns the data structure the YAML represents\n * (most often in case of CloudFormation, an object)\n */\nexport function deserialize(str: string): any {\n return parseYamlStrWithCfnTags(str);\n}\n\nfunction makeTagForCfnIntrinsic(intrinsicName: string, addFnPrefix: boolean): yaml_types.Schema.CustomTag {\n return {\n identify(value: any) {\n return typeof value === 'string';\n },\n tag: `!${intrinsicName}`,\n resolve: (_doc: yaml.Document, cstNode: yaml_cst.CST.Node) => {\n const ret: any = {};\n ret[addFnPrefix ? `Fn::${intrinsicName}` : intrinsicName] =\n // the +1 is to account for the ! the short form begins with\n parseYamlStrWithCfnTags(cstNode.toString().substring(intrinsicName.length + 1));\n return ret;\n },\n };\n}\n\nconst shortForms: yaml_types.Schema.CustomTag[] = [\n 'Base64', 'Cidr', 'FindInMap', 'GetAZs', 'ImportValue', 'Join', 'Sub',\n 'Select', 'Split', 'Transform', 'And', 'Equals', 'If', 'Not', 'Or', 'GetAtt',\n].map(name => makeTagForCfnIntrinsic(name, true)).concat(\n makeTagForCfnIntrinsic('Ref', false),\n makeTagForCfnIntrinsic('Condition', false),\n);\n\nfunction parseYamlStrWithCfnTags(text: string): any {\n return yaml.parse(text, {\n customTags: shortForms,\n schema: 'core',\n });\n}\n", "/**\n * Pad 's' on the left with 'char' until it is n characters wide\n */\nexport function padLeft(n: number, x: string, char: string = ' '): string {\n return char.repeat(Math.max(0, n - x.length)) + x;\n}\n\n/**\n * Pad 's' on the right with 'char' until it is n characters wide\n */\nexport function padRight(n: number, x: string, char: string = ' '): string {\n return x + char.repeat(Math.max(0, n - x.length));\n}\n\n/**\n * Formats time in milliseconds (which we get from 'Date.getTime()')\n * to a human-readable time; returns time in seconds rounded to 2\n * decimal places.\n */\nexport function formatTime(num: number): number {\n return roundPercentage(millisecondsToSeconds(num));\n}\n\n/**\n * Rounds a decimal number to two decimal points.\n * The function is useful for fractions that need to be outputted as percentages.\n */\nfunction roundPercentage(num: number): number {\n return Math.round(100 * num) / 100;\n}\n\n/**\n * Given a time in milliseconds, return an equivalent amount in seconds.\n */\nfunction millisecondsToSeconds(num: number): number {\n return num / 1000;\n}\n\n/**\n * This function lower cases the first character of the string provided.\n */\nexport function lowerCaseFirstCharacter(str: string): string {\n return str.length > 0 ? `${str[0].toLowerCase()}${str.slice(1)}` : str;\n}\n", "import * as semver from 'semver';\nimport { ToolkitError } from '../api/toolkit-error';\n\n// bracket - https://docs.oracle.com/middleware/1212/core/MAVEN/maven_version.htm#MAVEN401\n// pep - https://www.python.org/dev/peps/pep-0440/#version-specifiers\nexport type RangeType = 'bracket' | 'pep'\n\nexport function rangeFromSemver(ver: string, targetType: RangeType) {\n const re = ver.match(/^([^\\d]*)([\\d.]*)$/);\n if (!re || !semver.valid(re[2])) {\n throw new ToolkitError('not a semver or unsupported range syntax');\n }\n const prefixPart = re[1];\n const verPart = re[2];\n\n switch (targetType) {\n case 'bracket':\n switch (prefixPart) {\n case '':\n // if there's no prefix and the remaining is a valid semver, there's no range specified\n return ver;\n case '^':\n return `[${verPart},${semver.major(verPart)+1}.0.0)`;\n default:\n throw new ToolkitError(`unsupported range syntax - ${prefixPart}`);\n }\n case 'pep':\n switch (prefixPart) {\n case '':\n // if there's no prefix and the remaining is a valid semver, there's no range specified\n return `==${ver}`;\n case '^':\n return `>=${verPart},<${semver.major(verPart)+1}.0.0`;\n default:\n throw new ToolkitError(`unsupported range syntax - ${prefixPart}`);\n }\n }\n}\n", "import type { IIoHost } from '../io-host';\nimport type { IoMessage, IoRequest } from '../io-message';\nimport type { ToolkitAction } from '../toolkit-action';\nimport type { SpanEnd, SpanDefinition } from './span';\nimport { SpanMaker } from './span';\n\nexport type ActionLessMessage<T> = Omit<IoMessage<T>, 'action'>;\nexport type ActionLessRequest<T, U> = Omit<IoRequest<T, U>, 'action'>;\n\n/**\n * A class containing helper tools to interact with IoHost\n */\nexport class IoHelper implements IIoHost {\n public static fromIoHost(ioHost: IIoHost, action: ToolkitAction) {\n return new IoHelper(ioHost, action);\n }\n\n private readonly ioHost: IIoHost;\n private readonly action: ToolkitAction;\n\n private constructor(ioHost: IIoHost, action: ToolkitAction) {\n this.ioHost = ioHost;\n this.action = action;\n }\n\n /**\n * Forward a message to the IoHost, while injection the current action\n */\n public notify(msg: ActionLessMessage<unknown>): Promise<void> {\n return this.ioHost.notify({\n ...msg,\n action: this.action,\n });\n }\n\n /**\n * Forward a request to the IoHost, while injection the current action\n */\n public requestResponse<T, U>(msg: ActionLessRequest<T, U>): Promise<U> {\n return this.ioHost.requestResponse({\n ...msg,\n action: this.action,\n });\n }\n\n /**\n * Create a new marker from a given registry entry\n */\n public span<S extends object, E extends SpanEnd>(definition: SpanDefinition<S, E>) {\n return new SpanMaker(this, definition);\n }\n}\n\n/**\n * Wraps an IoHost and creates an IoHelper from it\n */\nexport function asIoHelper(ioHost: IIoHost, action: ToolkitAction): IoHelper {\n return IoHelper.fromIoHost(ioHost, action);\n}\n", "import type { IoMessageLevel } from '../';\n\n/**\n * Keep this list ordered from most to least verbose.\n * Every level \"includes\" all of the levels below it.\n * This is used to compare levels of messages to determine what should be logged.\n */\nconst levels = [\n 'trace',\n 'debug',\n 'info',\n 'warn',\n 'result',\n 'error',\n] as const;\n\n// compare levels helper\n// helper to convert the array into a map with numbers\nconst orderedLevels: Record<typeof levels[number], number> = Object.fromEntries(Object.entries(levels).map(a => a.reverse()));\nfunction compareFn(a: IoMessageLevel, b: IoMessageLevel): number {\n return orderedLevels[a] - orderedLevels[b];\n}\n\n/**\n * Determines if a message is relevant for the given log level.\n *\n * @param msg The message to compare.\n * @param level The level to compare against.\n * @returns true if the message is relevant for the given level.\n */\nexport function isMessageRelevantForLevel(msg: { level: IoMessageLevel}, level: IoMessageLevel): boolean {\n return compareFn(msg.level, level) >= 0;\n}\n\n", "import type { IoMessage, IoMessageCode, IoMessageLevel } from '../io-message';\nimport type { ActionLessMessage, ActionLessRequest } from './io-helper';\n\n/**\n * Information for each IO Message Code.\n */\ninterface CodeInfo {\n /**\n * The message code.\n */\n readonly code: IoMessageCode;\n\n /**\n * A brief description of the meaning of this IO Message.\n */\n readonly description: string;\n\n /**\n * The name of the payload interface, if applicable.\n * Some Io Messages include a payload, with a specific interface. The name of\n * the interface is specified here so that it can be linked with the message\n * when documentation is generated.\n *\n * The interface _must_ be exposed directly from toolkit-lib, so that it will\n * have a documentation page generated (that can be linked to).\n */\n readonly interface?: string;\n}\n\n/**\n * Information for each IO Message\n */\ninterface MessageInfo extends CodeInfo {\n /**\n * The message level\n */\n readonly level: IoMessageLevel;\n}\n\n/**\n * An interface that can produce messages for a specific code.\n */\nexport interface IoMessageMaker<T> extends MessageInfo {\n /**\n * Create a message for this code, with or without payload.\n */\n msg: [T] extends [AbsentData] ? (message: string) => ActionLessMessage<AbsentData> : (message: string, data: T) => ActionLessMessage<T>;\n\n /**\n * Returns whether the given `IoMessage` instance matches the current message definition\n */\n is(x: IoMessage<unknown>): x is IoMessage<T>;\n}\n\n/**\n * Produce an IoMessageMaker for the provided level and code info.\n */\nfunction message<T = AbsentData>(level: IoMessageLevel, details: CodeInfo): IoMessageMaker<T> {\n const maker = (text: string, data: T) => ({\n time: new Date(),\n level,\n code: details.code,\n message: text,\n data,\n } as ActionLessMessage<T>);\n\n return {\n ...details,\n level,\n msg: maker as any,\n is: (m): m is IoMessage<T> => m.code === details.code,\n };\n}\n\n/**\n * A type that is impossible for a user to replicate\n * This is used to ensure that results always have a proper type generic declared.\n */\ndeclare const privateKey: unique symbol;\nexport type ImpossibleType = {\n readonly [privateKey]: typeof privateKey;\n};\n\n// Create `IoMessageMaker`s for a given level and type check that calls with payload are using the correct interface\ntype CodeInfoMaybeInterface<T> = [T] extends [AbsentData] ? Omit<CodeInfo, 'interface'> : Required<CodeInfo>;\n\n/**\n * The type we use to represent an absent data field\n *\n * This is here to make it easy to change between `undefined`, `void`\n * and `never`.\n *\n * Not a lot of difference between `undefined` and `void`, but `void`\n * reads better.\n */\ntype AbsentData = void;\n\nexport const trace = <T = AbsentData>(details: CodeInfoMaybeInterface<T>) => message<T>('trace', details);\nexport const debug = <T = AbsentData>(details: CodeInfoMaybeInterface<T>) => message<T>('debug', details);\nexport const info = <T = AbsentData>(details: CodeInfoMaybeInterface<T>) => message<T>('info', details);\nexport const warn = <T = AbsentData>(details: CodeInfoMaybeInterface<T>) => message<T>('warn', details);\nexport const error = <T = AbsentData>(details: CodeInfoMaybeInterface<T>) => message<T>('error', details);\nexport const result = <T extends object = ImpossibleType>(details: Required<CodeInfo>) => message<T>('result', details);\n\ninterface RequestInfo<U> extends CodeInfo {\n readonly defaultResponse: U;\n}\n\n/**\n * An interface that can produce requests for a specific code.\n */\nexport interface IoRequestMaker<T, U> extends MessageInfo {\n /**\n * Create a message for this code, with or without payload.\n */\n req: [T] extends [AbsentData] ? (message: string) => ActionLessMessage<AbsentData> : (message: string, data: T) => ActionLessRequest<T, U>;\n}\n\n/**\n * Produce an IoRequestMaker for the provided level and request info.\n */\nfunction request<T = AbsentData, U = ImpossibleType>(level: IoMessageLevel, details: RequestInfo<U>): IoRequestMaker<T, U> {\n const maker = (text: string, data: T) => ({\n time: new Date(),\n level,\n code: details.code,\n message: text,\n data,\n defaultResponse: details.defaultResponse,\n } as ActionLessRequest<T, U>);\n\n return {\n ...details,\n level,\n req: maker as any,\n };\n}\n\n/**\n * A request that is a simple yes/no question, with the expectation that 'yes' is the default.\n */\nexport const confirm = <T extends object = ImpossibleType>(details: Required<Omit<RequestInfo<boolean>, 'defaultResponse'>>) => request<T, boolean>('info', {\n ...details,\n defaultResponse: true,\n});\n", "import type * as cxapi from '@aws-cdk/cx-api';\nimport * as make from './message-maker';\nimport type { SpanDefinition } from './span';\nimport type { DiffResult } from '../../../payloads';\nimport type { BootstrapEnvironmentProgress } from '../../../payloads/bootstrap-environment-progress';\nimport type { MissingContext, UpdatedContext } from '../../../payloads/context';\nimport type { BuildAsset, DeployConfirmationRequest, PublishAsset, StackDeployProgress, SuccessfulDeployStackResult } from '../../../payloads/deploy';\nimport type { StackDestroy, StackDestroyProgress } from '../../../payloads/destroy';\nimport type { HotswapDeploymentDetails, HotswapDeploymentAttempt, HotswappableChange, HotswapResult } from '../../../payloads/hotswap';\nimport type { StackDetailsPayload } from '../../../payloads/list';\nimport type { CloudWatchLogEvent, CloudWatchLogMonitorControlEvent } from '../../../payloads/logs-monitor';\nimport type { StackRollbackProgress } from '../../../payloads/rollback';\nimport type { SdkTrace } from '../../../payloads/sdk-trace';\nimport type { StackActivity, StackMonitoringControlEvent } from '../../../payloads/stack-activity';\nimport type { StackSelectionDetails } from '../../../payloads/synth';\nimport type { AssemblyData, ConfirmationRequest, ContextProviderMessageSource, Duration, ErrorPayload, StackAndAssemblyData } from '../../../payloads/types';\nimport type { FileWatchEvent, WatchSettings } from '../../../payloads/watch';\n\n/**\n * We have a rough system by which we assign message codes:\n * - First digit groups messages by action, e.g. synth or deploy\n * - X000-X009 are reserved for timings\n * - X900-X999 are reserved for results\n */\nexport const IO = {\n // Defaults (0000)\n DEFAULT_TOOLKIT_INFO: make.info({\n code: 'CDK_TOOLKIT_I0000',\n description: 'Default info messages emitted from the Toolkit',\n }),\n DEFAULT_TOOLKIT_DEBUG: make.debug({\n code: 'CDK_TOOLKIT_I0000',\n description: 'Default debug messages emitted from the Toolkit',\n }),\n DEFAULT_TOOLKIT_WARN: make.warn({\n code: 'CDK_TOOLKIT_W0000',\n description: 'Default warning messages emitted from the Toolkit',\n }),\n DEFAULT_TOOLKIT_ERROR: make.error({\n code: 'CDK_TOOLKIT_E0000',\n description: 'Default error messages emitted from the Toolkit',\n }),\n DEFAULT_TOOLKIT_TRACE: make.trace({\n code: 'CDK_TOOLKIT_I0000',\n description: 'Default trace messages emitted from the Toolkit',\n }),\n\n // warnings & errors\n CDK_TOOLKIT_W0100: make.warn({\n code: 'CDK_TOOLKIT_W0100',\n description: 'Credential plugin warnings',\n }),\n\n // 1: Synth (1xxx)\n CDK_TOOLKIT_I1000: make.info<Duration>({\n code: 'CDK_TOOLKIT_I1000',\n description: 'Provides synthesis times.',\n interface: 'Duration',\n }),\n CDK_TOOLKIT_I1001: make.trace<StackSelectionDetails>({\n code: 'CDK_TOOLKIT_I1001',\n description: 'Cloud Assembly synthesis is starting',\n interface: 'StackSelectionDetails',\n }),\n CDK_TOOLKIT_I1901: make.result<StackAndAssemblyData>({\n code: 'CDK_TOOLKIT_I1901',\n description: 'Provides stack data',\n interface: 'StackAndAssemblyData',\n }),\n CDK_TOOLKIT_I1902: make.result<AssemblyData>({\n code: 'CDK_TOOLKIT_I1902',\n description: 'Successfully deployed stacks',\n interface: 'AssemblyData',\n }),\n\n // 2: List (2xxx)\n CDK_TOOLKIT_I2901: make.result<StackDetailsPayload>({\n code: 'CDK_TOOLKIT_I2901',\n description: 'Provides details on the selected stacks and their dependencies',\n interface: 'StackDetailsPayload',\n }),\n\n // 3: Import & Migrate\n CDK_TOOLKIT_E3900: make.error<ErrorPayload>({\n code: 'CDK_TOOLKIT_E3900',\n description: 'Resource import failed',\n interface: 'ErrorPayload',\n }),\n\n // 4: Diff (4xxx)\n CDK_TOOLKIT_I4000: make.trace<StackSelectionDetails>({\n code: 'CDK_TOOLKIT_I4000',\n description: 'Diff stacks is starting',\n interface: 'StackSelectionDetails',\n }),\n CDK_TOOLKIT_I4001: make.info<DiffResult>({\n code: 'CDK_TOOLKIT_I4001',\n description: 'Output of the diff command',\n interface: 'DiffResult',\n }),\n\n // 5: Deploy & Watch (5xxx)\n CDK_TOOLKIT_I5000: make.info<Duration>({\n code: 'CDK_TOOLKIT_I5000',\n description: 'Provides deployment times',\n interface: 'Duration',\n }),\n CDK_TOOLKIT_I5001: make.info<Duration>({\n code: 'CDK_TOOLKIT_I5001',\n description: 'Provides total time in deploy action, including synth and rollback',\n interface: 'Duration',\n }),\n CDK_TOOLKIT_I5002: make.info<Duration>({\n code: 'CDK_TOOLKIT_I5002',\n description: 'Provides time for resource migration',\n interface: 'Duration',\n }),\n CDK_TOOLKIT_W5021: make.warn({\n code: 'CDK_TOOLKIT_W5021',\n description: 'Empty non-existent stack, deployment is skipped',\n }),\n CDK_TOOLKIT_W5022: make.warn({\n code: 'CDK_TOOLKIT_W5022',\n description: 'Empty existing stack, stack will be destroyed',\n }),\n CDK_TOOLKIT_I5031: make.info({\n code: 'CDK_TOOLKIT_I5031',\n description: 'Informs about any log groups that are traced as part of the deployment',\n }),\n CDK_TOOLKIT_I5032: make.debug<CloudWatchLogMonitorControlEvent>({\n code: 'CDK_TOOLKIT_I5032',\n description: 'Start monitoring log groups',\n interface: 'CloudWatchLogMonitorControlEvent',\n }),\n CDK_TOOLKIT_I5033: make.info<CloudWatchLogEvent>({\n code: 'CDK_TOOLKIT_I5033',\n description: 'A log event received from Cloud Watch',\n interface: 'CloudWatchLogEvent',\n }),\n CDK_TOOLKIT_I5034: make.debug<CloudWatchLogMonitorControlEvent>({\n code: 'CDK_TOOLKIT_I5034',\n description: 'Stop monitoring log groups',\n interface: 'CloudWatchLogMonitorControlEvent',\n }),\n CDK_TOOLKIT_E5035: make.error<ErrorPayload>({\n code: 'CDK_TOOLKIT_E5035',\n description: 'A log monitoring error',\n interface: 'ErrorPayload',\n }),\n CDK_TOOLKIT_I5050: make.confirm<ConfirmationRequest>({\n code: 'CDK_TOOLKIT_I5050',\n description: 'Confirm rollback during deployment',\n interface: 'ConfirmationRequest',\n }),\n CDK_TOOLKIT_I5060: make.confirm<DeployConfirmationRequest>({\n code: 'CDK_TOOLKIT_I5060',\n description: 'Confirm deploy security sensitive changes',\n interface: 'DeployConfirmationRequest',\n }),\n CDK_TOOLKIT_I5100: make.info<StackDeployProgress>({\n code: 'CDK_TOOLKIT_I5100',\n description: 'Stack deploy progress',\n interface: 'StackDeployProgress',\n }),\n\n // Assets (52xx)\n CDK_TOOLKIT_I5210: make.trace<BuildAsset>({\n code: 'CDK_TOOLKIT_I5210',\n description: 'Started building a specific asset',\n interface: 'BuildAsset',\n }),\n CDK_TOOLKIT_I5211: make.trace<Duration>({\n code: 'CDK_TOOLKIT_I5211',\n description: 'Building the asset has completed',\n interface: 'Duration',\n }),\n CDK_TOOLKIT_I5220: make.trace<PublishAsset>({\n code: 'CDK_TOOLKIT_I5220',\n description: 'Started publishing a specific asset',\n interface: 'PublishAsset',\n }),\n CDK_TOOLKIT_I5221: make.trace<Duration>({\n code: 'CDK_TOOLKIT_I5221',\n description: 'Publishing the asset has completed',\n interface: 'Duration',\n }),\n\n // Watch (53xx)\n CDK_TOOLKIT_I5310: make.debug<WatchSettings>({\n code: 'CDK_TOOLKIT_I5310',\n description: 'The computed settings used for file watching',\n interface: 'WatchSettings',\n }),\n CDK_TOOLKIT_I5311: make.info<FileWatchEvent>({\n code: 'CDK_TOOLKIT_I5311',\n description: 'File watching started',\n interface: 'FileWatchEvent',\n }),\n CDK_TOOLKIT_I5312: make.info<FileWatchEvent>({\n code: 'CDK_TOOLKIT_I5312',\n description: 'File event detected, starting deployment',\n interface: 'FileWatchEvent',\n }),\n CDK_TOOLKIT_I5313: make.info<FileWatchEvent>({\n code: 'CDK_TOOLKIT_I5313',\n description: 'File event detected during active deployment, changes are queued',\n interface: 'FileWatchEvent',\n }),\n CDK_TOOLKIT_I5314: make.info({\n code: 'CDK_TOOLKIT_I5314',\n description: 'Initial watch deployment started',\n }),\n CDK_TOOLKIT_I5315: make.info({\n code: 'CDK_TOOLKIT_I5315',\n description: 'Queued watch deployment started',\n }),\n\n // Hotswap (54xx)\n CDK_TOOLKIT_I5400: make.trace<HotswapDeploymentAttempt>({\n code: 'CDK_TOOLKIT_I5400',\n description: 'Attempting a hotswap deployment',\n interface: 'HotswapDeploymentAttempt',\n }),\n CDK_TOOLKIT_I5401: make.trace<HotswapDeploymentDetails>({\n code: 'CDK_TOOLKIT_I5401',\n description: 'Computed details for the hotswap deployment',\n interface: 'HotswapDeploymentDetails',\n }),\n CDK_TOOLKIT_I5402: make.info<HotswappableChange>({\n code: 'CDK_TOOLKIT_I5402',\n description: 'A hotswappable change is processed as part of a hotswap deployment',\n interface: 'HotswappableChange',\n }),\n CDK_TOOLKIT_I5403: make.info<HotswappableChange>({\n code: 'CDK_TOOLKIT_I5403',\n description: 'The hotswappable change has completed processing',\n interface: 'HotswappableChange',\n }),\n CDK_TOOLKIT_I5410: make.info<HotswapResult>({\n code: 'CDK_TOOLKIT_I5410',\n description: 'Hotswap deployment has ended, a full deployment might still follow if needed',\n interface: 'HotswapResult',\n }),\n\n // Stack Monitor (55xx)\n CDK_TOOLKIT_I5501: make.info<StackMonitoringControlEvent>({\n code: 'CDK_TOOLKIT_I5501',\n description: 'Stack Monitoring: Start monitoring of a single stack',\n interface: 'StackMonitoringControlEvent',\n }),\n CDK_TOOLKIT_I5502: make.info<StackActivity>({\n code: 'CDK_TOOLKIT_I5502',\n description: 'Stack Monitoring: Activity event for a single stack',\n interface: 'StackActivity',\n }),\n CDK_TOOLKIT_I5503: make.info<StackMonitoringControlEvent>({\n code: 'CDK_TOOLKIT_I5503',\n description: 'Stack Monitoring: Finished monitoring of a single stack',\n interface: 'StackMonitoringControlEvent',\n }),\n\n // Success (59xx)\n CDK_TOOLKIT_I5900: make.result<SuccessfulDeployStackResult>({\n code: 'CDK_TOOLKIT_I5900',\n description: 'Deployment results on success',\n interface: 'SuccessfulDeployStackResult',\n }),\n CDK_TOOLKIT_I5901: make.info({\n code: 'CDK_TOOLKIT_I5901',\n description: 'Generic deployment success messages',\n }),\n CDK_TOOLKIT_W5400: make.warn({\n code: 'CDK_TOOLKIT_W5400',\n description: 'Hotswap disclosure message',\n }),\n\n CDK_TOOLKIT_E5001: make.error({\n code: 'CDK_TOOLKIT_E5001',\n description: 'No stacks found',\n }),\n CDK_TOOLKIT_E5500: make.error<ErrorPayload>({\n code: 'CDK_TOOLKIT_E5500',\n description: 'Stack Monitoring error',\n interface: 'ErrorPayload',\n }),\n\n // 6: Rollback (6xxx)\n CDK_TOOLKIT_I6000: make.info<Duration>({\n code: 'CDK_TOOLKIT_I6000',\n description: 'Provides rollback times',\n interface: 'Duration',\n }),\n CDK_TOOLKIT_I6100: make.info<StackRollbackProgress>({\n code: 'CDK_TOOLKIT_I6100',\n description: 'Stack rollback progress',\n interface: 'StackRollbackProgress',\n }),\n\n CDK_TOOLKIT_E6001: make.error({\n code: 'CDK_TOOLKIT_E6001',\n description: 'No stacks found',\n }),\n CDK_TOOLKIT_E6900: make.error<ErrorPayload>({\n code: 'CDK_TOOLKIT_E6900',\n description: 'Rollback failed',\n interface: 'ErrorPayload',\n }),\n\n // 7: Destroy (7xxx)\n CDK_TOOLKIT_I7000: make.info<Duration>({\n code: 'CDK_TOOLKIT_I7000',\n description: 'Provides destroy times',\n interface: 'Duration',\n }),\n CDK_TOOLKIT_I7001: make.trace<Duration>({\n code: 'CDK_TOOLKIT_I7001',\n description: 'Provides destroy time for a single stack',\n interface: 'Duration',\n }),\n CDK_TOOLKIT_I7010: make.confirm<ConfirmationRequest>({\n code: 'CDK_TOOLKIT_I7010',\n description: 'Confirm destroy stacks',\n interface: 'ConfirmationRequest',\n }),\n CDK_TOOLKIT_I7100: make.info<StackDestroyProgress>({\n code: 'CDK_TOOLKIT_I7100',\n description: 'Stack destroy progress',\n interface: 'StackDestroyProgress',\n }),\n CDK_TOOLKIT_I7101: make.trace<StackDestroy>({\n code: 'CDK_TOOLKIT_I7101',\n description: 'Start stack destroying',\n interface: 'StackDestroy',\n }),\n\n CDK_TOOLKIT_I7900: make.result<cxapi.CloudFormationStackArtifact>({\n code: 'CDK_TOOLKIT_I7900',\n description: 'Stack deletion succeeded',\n interface: 'cxapi.CloudFormationStackArtifact',\n }),\n\n CDK_TOOLKIT_E7010: make.error({\n code: 'CDK_TOOLKIT_E7010',\n description: 'Action was aborted due to negative confirmation of request',\n }),\n CDK_TOOLKIT_E7900: make.error<ErrorPayload>({\n code: 'CDK_TOOLKIT_E7900',\n description: 'Stack deletion failed',\n interface: 'ErrorPayload',\n }),\n\n // 9: Bootstrap (9xxx)\n CDK_TOOLKIT_I9000: make.info<Duration>({\n code: 'CDK_TOOLKIT_I9000',\n description: 'Provides bootstrap times',\n interface: 'Duration',\n }),\n CDK_TOOLKIT_I9100: make.info<BootstrapEnvironmentProgress>({\n code: 'CDK_TOOLKIT_I9100',\n description: 'Bootstrap progress',\n interface: 'BootstrapEnvironmentProgress',\n }),\n\n CDK_TOOLKIT_I9900: make.result<{ environment: cxapi.Environment }>({\n code: 'CDK_TOOLKIT_I9900',\n description: 'Bootstrap results on success',\n interface: 'cxapi.Environment',\n }),\n CDK_TOOLKIT_E9900: make.error<ErrorPayload>({\n code: 'CDK_TOOLKIT_E9900',\n description: 'Bootstrap failed',\n interface: 'ErrorPayload',\n }),\n\n // Notices\n CDK_TOOLKIT_I0100: make.info({\n code: 'CDK_TOOLKIT_I0100',\n description: 'Notices decoration (the header or footer of a list of notices)',\n }),\n CDK_TOOLKIT_W0101: make.warn({\n code: 'CDK_TOOLKIT_W0101',\n description: 'A notice that is marked as a warning',\n }),\n CDK_TOOLKIT_E0101: make.error({\n code: 'CDK_TOOLKIT_E0101',\n description: 'A notice that is marked as an error',\n }),\n CDK_TOOLKIT_I0101: make.info({\n code: 'CDK_TOOLKIT_I0101',\n description: 'A notice that is marked as informational',\n }),\n\n // Assembly codes\n DEFAULT_ASSEMBLY_TRACE: make.trace({\n code: 'CDK_ASSEMBLY_I0000',\n description: 'Default trace messages emitted from Cloud Assembly operations',\n }),\n DEFAULT_ASSEMBLY_DEBUG: make.debug({\n code: 'CDK_ASSEMBLY_I0000',\n description: 'Default debug messages emitted from Cloud Assembly operations',\n }),\n DEFAULT_ASSEMBLY_INFO: make.info({\n code: 'CDK_ASSEMBLY_I0000',\n description: 'Default info messages emitted from Cloud Assembly operations',\n }),\n DEFAULT_ASSEMBLY_WARN: make.warn({\n code: 'CDK_ASSEMBLY_W0000',\n description: 'Default warning messages emitted from Cloud Assembly operations',\n }),\n\n CDK_ASSEMBLY_I0010: make.debug({\n code: 'CDK_ASSEMBLY_I0010',\n description: 'Generic environment preparation debug messages',\n }),\n CDK_ASSEMBLY_W0010: make.warn({\n code: 'CDK_ASSEMBLY_W0010',\n description: 'Emitted if the found framework version does not support context overflow',\n }),\n CDK_ASSEMBLY_I0042: make.debug<UpdatedContext>({\n code: 'CDK_ASSEMBLY_I0042',\n description: 'Writing updated context',\n interface: 'UpdatedContext',\n }),\n CDK_ASSEMBLY_I0240: make.debug<MissingContext>({\n code: 'CDK_ASSEMBLY_I0240',\n description: 'Context lookup was stopped as no further progress was made. ',\n interface: 'MissingContext',\n }),\n CDK_ASSEMBLY_I0241: make.debug<MissingContext>({\n code: 'CDK_ASSEMBLY_I0241',\n description: 'Fetching missing context. This is an iterative message that may appear multiple times with different missing keys.',\n interface: 'MissingContext',\n }),\n CDK_ASSEMBLY_I1000: make.debug({\n code: 'CDK_ASSEMBLY_I1000',\n description: 'Cloud assembly output starts',\n }),\n CDK_ASSEMBLY_I1001: make.info({\n code: 'CDK_ASSEMBLY_I1001',\n description: 'Output lines emitted by the cloud assembly to stdout',\n }),\n CDK_ASSEMBLY_E1002: make.error({\n code: 'CDK_ASSEMBLY_E1002',\n description: 'Output lines emitted by the cloud assembly to stderr',\n }),\n CDK_ASSEMBLY_I1003: make.info({\n code: 'CDK_ASSEMBLY_I1003',\n description: 'Cloud assembly output finished',\n }),\n CDK_ASSEMBLY_E1111: make.error<ErrorPayload>({\n code: 'CDK_ASSEMBLY_E1111',\n description: 'Incompatible CDK CLI version. Upgrade needed.',\n interface: 'ErrorPayload',\n }),\n\n CDK_ASSEMBLY_I0150: make.debug<never>({\n code: 'CDK_ASSEMBLY_I0150',\n description: 'Indicates the use of a pre-synthesized cloud assembly directory',\n }),\n\n CDK_ASSEMBLY_I0300: make.info<ContextProviderMessageSource>({\n code: 'CDK_ASSEMBLY_I0300',\n description: 'An info message emitted by a Context Provider',\n interface: 'ContextProviderMessageSource',\n }),\n CDK_ASSEMBLY_I0301: make.debug<ContextProviderMessageSource>({\n code: 'CDK_ASSEMBLY_I0301',\n description: 'A debug message emitted by a Context Provider',\n interface: 'ContextProviderMessageSource',\n }),\n\n // Assembly Annotations\n CDK_ASSEMBLY_I9999: make.info<cxapi.SynthesisMessage>({\n code: 'CDK_ASSEMBLY_I9999',\n description: 'Annotations emitted by the cloud assembly',\n interface: 'cxapi.SynthesisMessage',\n }),\n CDK_ASSEMBLY_W9999: make.warn<cxapi.SynthesisMessage>({\n code: 'CDK_ASSEMBLY_W9999',\n description: 'Warnings emitted by the cloud assembly',\n interface: 'cxapi.SynthesisMessage',\n }),\n CDK_ASSEMBLY_E9999: make.error<cxapi.SynthesisMessage>({\n code: 'CDK_ASSEMBLY_E9999',\n description: 'Errors emitted by the cloud assembly',\n interface: 'cxapi.SynthesisMessage',\n }),\n\n // SDK codes\n DEFAULT_SDK_TRACE: make.trace({\n code: 'CDK_SDK_I0000',\n description: 'An SDK trace message.',\n }),\n DEFAULT_SDK_DEBUG: make.debug({\n code: 'CDK_SDK_I0000',\n description: 'An SDK debug message.',\n }),\n DEFAULT_SDK_WARN: make.warn({\n code: 'CDK_SDK_W0000',\n description: 'An SDK warning message.',\n }),\n CDK_SDK_I0100: make.trace<SdkTrace>({\n code: 'CDK_SDK_I0100',\n description: 'An SDK trace. SDK traces are emitted as traces to the IoHost, but contain the original SDK logging level.',\n interface: 'SdkTrace',\n }),\n};\n\n//////////////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Payload type of the end message must extend Duration\n */\nexport const SPAN = {\n SYNTH_ASSEMBLY: {\n name: 'Synthesis',\n start: IO.CDK_TOOLKIT_I1001,\n end: IO.CDK_TOOLKIT_I1000,\n },\n DEPLOY_STACK: {\n name: 'Deployment',\n start: IO.CDK_TOOLKIT_I5100,\n end: IO.CDK_TOOLKIT_I5001,\n },\n ROLLBACK_STACK: {\n name: 'Rollback',\n start: IO.CDK_TOOLKIT_I6100,\n end: IO.CDK_TOOLKIT_I6000,\n },\n DIFF_STACK: {\n name: 'Diff',\n start: IO.CDK_TOOLKIT_I4000,\n end: IO.CDK_TOOLKIT_I4001,\n },\n DESTROY_STACK: {\n name: 'Destroy',\n start: IO.CDK_TOOLKIT_I7100,\n end: IO.CDK_TOOLKIT_I7001,\n },\n DESTROY_ACTION: {\n name: 'Destroy',\n start: IO.CDK_TOOLKIT_I7101,\n end: IO.CDK_TOOLKIT_I7000,\n },\n BOOTSTRAP_SINGLE: {\n name: 'Bootstrap',\n start: IO.CDK_TOOLKIT_I9100,\n end: IO.CDK_TOOLKIT_I9000,\n },\n BUILD_ASSET: {\n name: 'Build Asset',\n start: IO.CDK_TOOLKIT_I5210,\n end: IO.CDK_TOOLKIT_I5211,\n },\n PUBLISH_ASSET: {\n name: 'Publish Asset',\n start: IO.CDK_TOOLKIT_I5220,\n end: IO.CDK_TOOLKIT_I5221,\n },\n HOTSWAP: {\n name: 'hotswap-deployment',\n start: IO.CDK_TOOLKIT_I5400,\n end: IO.CDK_TOOLKIT_I5410,\n },\n} satisfies Record<string, SpanDefinition<any, any>>;\n", "import * as util from 'util';\nimport type { ActionLessMessage, ActionLessRequest, IoHelper } from './io-helper';\nimport type { IoMessageMaker } from './message-maker';\nimport { IO } from './messages';\n\n/**\n * Helper class to emit standard log messages to an IoHost\n *\n * It wraps an `IoHelper`, and adds convenience methods to emit default messages\n * for the various log levels.\n */\nexport class IoDefaultMessages {\n constructor(private readonly ioHelper: IoHelper) {\n }\n\n public notify(msg: ActionLessMessage<unknown>): Promise<void> {\n return this.ioHelper.notify(msg);\n }\n\n public requestResponse<T, U>(msg: ActionLessRequest<T, U>): Promise<U> {\n return this.ioHelper.requestResponse(msg);\n }\n\n public error(input: string, ...args: unknown[]) {\n this.emitMessage(IO.DEFAULT_TOOLKIT_ERROR, input, ...args);\n }\n\n public warn(input: string, ...args: unknown[]) {\n this.emitMessage(IO.DEFAULT_TOOLKIT_WARN, input, ...args);\n }\n\n public warning(input: string, ...args: unknown[]) {\n this.emitMessage(IO.DEFAULT_TOOLKIT_WARN, input, ...args);\n }\n\n public info(input: string, ...args: unknown[]) {\n this.emitMessage(IO.DEFAULT_TOOLKIT_INFO, input, ...args);\n }\n\n public debug(input: string, ...args: unknown[]) {\n this.emitMessage(IO.DEFAULT_TOOLKIT_DEBUG, input, ...args);\n }\n\n public trace(input: string, ...args: unknown[]) {\n this.emitMessage(IO.DEFAULT_TOOLKIT_TRACE, input, ...args);\n }\n\n public result(input: string, ...args: unknown[]) {\n const message = args.length > 0 ? util.format(input, ...args) : input;\n // This is just the default \"info\" message but with a level of \"result\"\n void this.ioHelper.notify({\n time: new Date(),\n code: IO.DEFAULT_TOOLKIT_INFO.code,\n level: 'result',\n message,\n data: undefined,\n });\n }\n\n private emitMessage(maker: IoMessageMaker<void>, input: string, ...args: unknown[]) {\n // Format message if args are provided\n const message = args.length > 0 ? util.format(input, ...args) : input;\n void this.ioHelper.notify(maker.msg(message));\n }\n}\n", "import type { CloudFormationStackArtifact } from '@aws-cdk/cx-api';\nimport type { IoMessage } from '../../api/io';\nimport { IO } from '../../api/io/private';\nimport { type StackActivity, type StackProgress } from '../../payloads';\nimport { maxResourceTypeLength, stackEventHasErrorMessage } from '../../util';\n\nexport interface IActivityPrinter {\n notify(msg: IoMessage<unknown>): void;\n}\n\nexport interface ActivityPrinterProps {\n /**\n * Stream to write to\n */\n readonly stream: NodeJS.WriteStream;\n}\n\nexport abstract class ActivityPrinterBase implements IActivityPrinter {\n protected static readonly TIMESTAMP_WIDTH = 12;\n protected static readonly STATUS_WIDTH = 20;\n\n /**\n * Stream to write to\n */\n protected readonly stream: NodeJS.WriteStream;\n\n /**\n * The with of the \"resource type\" column.\n */\n protected resourceTypeColumnWidth: number = maxResourceTypeLength({});\n\n /**\n * A list of resource IDs which are currently being processed\n */\n protected resourcesInProgress: Record<string, StackActivity> = {};\n\n protected stackProgress?: StackProgress;\n\n protected rollingBack = false;\n\n protected readonly failures = new Array<StackActivity>();\n\n protected hookFailureMap = new Map<string, Map<string, string>>();\n\n constructor(protected readonly props: ActivityPrinterProps) {\n this.stream = props.stream;\n }\n\n protected abstract print(): void;\n\n /**\n * Receive a stack activity message\n */\n public notify(msg: IoMessage<unknown>): void {\n switch (true) {\n case IO.CDK_TOOLKIT_I5501.is(msg):\n this.start(msg.data);\n break;\n case IO.CDK_TOOLKIT_I5502.is(msg):\n this.activity(msg.data);\n break;\n case IO.CDK_TOOLKIT_I5503.is(msg):\n this.stop();\n break;\n default:\n // ignore all other messages\n break;\n }\n }\n\n public start({ stack }: { stack: CloudFormationStackArtifact}) {\n this.resourceTypeColumnWidth = maxResourceTypeLength(stack.template);\n }\n\n public activity(activity: StackActivity) {\n // process the activity and then call print\n this.addActivity(activity);\n this.print();\n }\n\n public stop() {\n // final print after the stack is done\n this.print();\n }\n\n protected addActivity(activity: StackActivity) {\n const status = activity.event.ResourceStatus;\n const hookStatus = activity.event.HookStatus;\n const hookType = activity.event.HookType;\n if (!status || !activity.event.LogicalResourceId) {\n return;\n }\n\n this.stackProgress = activity.progress;\n\n if (status === 'ROLLBACK_IN_PROGRESS' || status === 'UPDATE_ROLLBACK_IN_PROGRESS') {\n // Only triggered on the stack once we've started doing a rollback\n this.rollingBack = true;\n }\n\n if (status.endsWith('_IN_PROGRESS')) {\n this.resourcesInProgress[activity.event.LogicalResourceId] = activity;\n }\n\n if (stackEventHasErrorMessage(status)) {\n const isCancelled = (activity.event.ResourceStatusReason ?? '').indexOf('cancelled') > -1;\n\n // Cancelled is not an interesting failure reason\n if (!isCancelled) {\n this.failures.push(activity);\n }\n }\n\n if (status.endsWith('_COMPLETE') || status.endsWith('_FAILED')) {\n delete this.resourcesInProgress[activity.event.LogicalResourceId];\n }\n\n if (\n hookStatus !== undefined &&\n hookStatus.endsWith('_COMPLETE_FAILED') &&\n activity.event.LogicalResourceId !== undefined &&\n hookType !== undefined\n ) {\n if (this.hookFailureMap.has(activity.event.LogicalResourceId)) {\n this.hookFailureMap.get(activity.event.LogicalResourceId)?.set(hookType, activity.event.HookStatusReason ?? '');\n } else {\n this.hookFailureMap.set(activity.event.LogicalResourceId, new Map<string, string>());\n this.hookFailureMap.get(activity.event.LogicalResourceId)?.set(hookType, activity.event.HookStatusReason ?? '');\n }\n }\n }\n\n protected failureReason(activity: StackActivity) {\n const resourceStatusReason = activity.event.ResourceStatusReason ?? '';\n const logicalResourceId = activity.event.LogicalResourceId ?? '';\n const hookFailureReasonMap = this.hookFailureMap.get(logicalResourceId);\n\n if (hookFailureReasonMap !== undefined) {\n for (const hookType of hookFailureReasonMap.keys()) {\n if (resourceStatusReason.includes(hookType)) {\n return resourceStatusReason + ' : ' + hookFailureReasonMap.get(hookType);\n }\n }\n }\n return resourceStatusReason;\n }\n\n /**\n * Is the activity a meta activity for the stack itself.\n */\n protected isActivityForTheStack(activity: StackActivity) {\n return activity.event.PhysicalResourceId === activity.event.StackId;\n }\n}\n", "import * as util from 'util';\nimport * as chalk from 'chalk';\nimport type { ActivityPrinterProps } from './base';\nimport { ActivityPrinterBase } from './base';\nimport type { StackActivity } from '../../payloads';\nimport { padRight } from '../../util';\n\n/**\n * Activity Printer which shows a full log of all CloudFormation events\n *\n * When there hasn't been activity for a while, it will print the resources\n * that are currently in progress, to show what's holding up the deployment.\n */\nexport class HistoryActivityPrinter extends ActivityPrinterBase {\n /**\n * Last time we printed something to the console.\n *\n * Used to measure timeout for progress reporting.\n */\n private lastPrintTime = Date.now();\n\n private lastPrinted?: StackActivity;\n\n /**\n * Number of ms of change absence before we tell the user about the resources that are currently in progress.\n */\n private readonly inProgressDelay = 30_000;\n\n private readonly printable = new Array<StackActivity>();\n\n constructor(props: ActivityPrinterProps) {\n super(props);\n }\n\n public activity(activity: StackActivity) {\n this.printable.push(activity);\n super.activity(activity);\n }\n\n public stop() {\n super.stop();\n\n // Print failures at the end\n if (this.failures.length > 0) {\n this.stream.write('\\nFailed resources:\\n');\n for (const failure of this.failures) {\n // Root stack failures are not interesting\n if (this.isActivityForTheStack(failure)) {\n continue;\n }\n\n this.printOne(failure, false);\n }\n }\n }\n\n protected print() {\n for (const activity of this.printable) {\n this.printOne(activity);\n this.lastPrinted = activity;\n }\n this.printable.splice(0, this.printable.length);\n this.printInProgress(this.lastPrinted?.progress.formatted);\n }\n\n private printOne(activity: StackActivity, progress?: boolean) {\n const event = activity.event;\n const color = colorFromStatusResult(event.ResourceStatus);\n let reasonColor = chalk.cyan;\n\n let stackTrace = '';\n const metadata = activity.metadata;\n\n if (event.ResourceStatus && event.ResourceStatus.indexOf('FAILED') !== -1) {\n if (progress == undefined || progress) {\n event.ResourceStatusReason = event.ResourceStatusReason ? this.failureReason(activity) : '';\n }\n if (metadata) {\n stackTrace = metadata.entry.trace ? `\\n\\t${metadata.entry.trace.join('\\n\\t\\\\_ ')}` : '';\n }\n reasonColor = chalk.red;\n }\n\n const resourceName = metadata ? metadata.constructPath : event.LogicalResourceId || '';\n const logicalId = resourceName !== event.LogicalResourceId ? `(${event.LogicalResourceId}) ` : '';\n\n this.stream.write(\n util.format(\n '%s | %s%s | %s | %s | %s %s%s%s\\n',\n event.StackName,\n progress !== false ? `${activity.progress.formatted} | ` : '',\n new Date(event.Timestamp!).toLocaleTimeString(),\n color(padRight(HistoryActivityPrinter.STATUS_WIDTH, (event.ResourceStatus || '').slice(0, HistoryActivityPrinter.STATUS_WIDTH))), // pad left and trim\n padRight(this.resourceTypeColumnWidth, event.ResourceType || ''),\n color(chalk.bold(resourceName)),\n logicalId,\n reasonColor(chalk.bold(event.ResourceStatusReason ? event.ResourceStatusReason : '')),\n reasonColor(stackTrace),\n ),\n );\n\n this.lastPrintTime = Date.now();\n }\n\n /**\n * If some resources are taking a while to create, notify the user about what's currently in progress\n */\n private printInProgress(progress?: string) {\n if (!progress || Date.now() < this.lastPrintTime + this.inProgressDelay) {\n return;\n }\n\n if (Object.keys(this.resourcesInProgress).length > 0) {\n this.stream.write(\n util.format(\n '%s Currently in progress: %s\\n',\n progress,\n chalk.bold(Object.keys(this.resourcesInProgress).join(', ')),\n ),\n );\n }\n\n // We cheat a bit here. To prevent printInProgress() from repeatedly triggering,\n // we set the timestamp into the future. It will be reset whenever a regular print\n // occurs, after which we can be triggered again.\n this.lastPrintTime = +Infinity;\n }\n}\n\nfunction colorFromStatusResult(status?: string) {\n if (!status) {\n return chalk.reset;\n }\n\n if (status.indexOf('FAILED') !== -1) {\n return chalk.red;\n }\n if (status.indexOf('ROLLBACK') !== -1) {\n return chalk.yellow;\n }\n if (status.indexOf('COMPLETE') !== -1) {\n return chalk.green;\n }\n\n return chalk.reset;\n}\n", "import * as util from 'util';\nimport * as chalk from 'chalk';\nimport type { ActivityPrinterProps } from './base';\nimport { ActivityPrinterBase } from './base';\nimport { RewritableBlock } from './display';\nimport type { StackActivity } from '../../payloads';\nimport { padLeft, padRight, stackEventHasErrorMessage } from '../../util';\n\n/**\n * Activity Printer which shows the resources currently being updated\n *\n * It will continuously re-update the terminal and show only the resources\n * that are currently being updated, in addition to a progress bar which\n * shows how far along the deployment is.\n *\n * Resources that have failed will always be shown, and will be recapitulated\n * along with their stack trace when the monitoring ends.\n *\n * Resources that failed deployment because they have been cancelled are\n * not included.\n */\nexport class CurrentActivityPrinter extends ActivityPrinterBase {\n /**\n * Continuously write to the same output block.\n */\n private block: RewritableBlock;\n\n constructor(props: ActivityPrinterProps) {\n super(props);\n this.block = new RewritableBlock(this.stream);\n }\n\n protected print(): void {\n const lines = [];\n\n // Add a progress bar at the top\n const progressWidth = Math.max(\n Math.min((this.block.width ?? 80) - PROGRESSBAR_EXTRA_SPACE - 1, MAX_PROGRESSBAR_WIDTH),\n MIN_PROGRESSBAR_WIDTH,\n );\n const prog = this.progressBar(progressWidth);\n if (prog) {\n lines.push(' ' + prog, '');\n }\n\n // Normally we'd only print \"resources in progress\", but it's also useful\n // to keep an eye on the failures and know about the specific errors asquickly\n // as possible (while the stack is still rolling back), so add those in.\n const toPrint: StackActivity[] = [...this.failures, ...Object.values(this.resourcesInProgress)];\n toPrint.sort((a, b) => a.event.Timestamp!.getTime() - b.event.Timestamp!.getTime());\n\n lines.push(\n ...toPrint.map((res) => {\n const color = colorFromStatusActivity(res.event.ResourceStatus);\n const resourceName = res.metadata?.constructPath ?? res.event.LogicalResourceId ?? '';\n\n return util.format(\n '%s | %s | %s | %s%s',\n padLeft(CurrentActivityPrinter.TIMESTAMP_WIDTH, new Date(res.event.Timestamp!).toLocaleTimeString()),\n color(padRight(CurrentActivityPrinter.STATUS_WIDTH, (res.event.ResourceStatus || '').slice(0, CurrentActivityPrinter.STATUS_WIDTH))),\n padRight(this.resourceTypeColumnWidth, res.event.ResourceType || ''),\n color(chalk.bold(shorten(40, resourceName))),\n this.failureReasonOnNextLine(res),\n );\n }),\n );\n\n this.block.displayLines(lines);\n }\n\n public stop() {\n super.stop();\n\n // Print failures at the end\n const lines = new Array<string>();\n for (const failure of this.failures) {\n // Root stack failures are not interesting\n if (this.isActivityForTheStack(failure)) {\n continue;\n }\n\n lines.push(\n util.format(\n chalk.red('%s | %s | %s | %s%s') + '\\n',\n padLeft(CurrentActivityPrinter.TIMESTAMP_WIDTH, new Date(failure.event.Timestamp!).toLocaleTimeString()),\n padRight(CurrentActivityPrinter.STATUS_WIDTH, (failure.event.ResourceStatus || '').slice(0, CurrentActivityPrinter.STATUS_WIDTH)),\n padRight(this.resourceTypeColumnWidth, failure.event.ResourceType || ''),\n shorten(40, failure.event.LogicalResourceId ?? ''),\n this.failureReasonOnNextLine(failure),\n ),\n );\n\n const trace = failure.metadata?.entry?.trace;\n if (trace) {\n lines.push(chalk.red(`\\t${trace.join('\\n\\t\\\\_ ')}\\n`));\n }\n }\n\n // Display in the same block space, otherwise we're going to have silly empty lines.\n this.block.displayLines(lines);\n this.block.removeEmptyLines();\n }\n\n private progressBar(width: number) {\n if (!this.stackProgress || !this.stackProgress.total) {\n return '';\n }\n const fraction = Math.min(this.stackProgress.completed / this.stackProgress.total, 1);\n const innerWidth = Math.max(1, width - 2);\n const chars = innerWidth * fraction;\n const remainder = chars - Math.floor(chars);\n\n const fullChars = FULL_BLOCK.repeat(Math.floor(chars));\n const partialChar = PARTIAL_BLOCK[Math.floor(remainder * PARTIAL_BLOCK.length)];\n const filler = '\u00B7'.repeat(innerWidth - Math.floor(chars) - (partialChar ? 1 : 0));\n\n const color = this.rollingBack ? chalk.yellow : chalk.green;\n\n return '[' + color(fullChars + partialChar) + filler + `] (${this.stackProgress.completed}/${this.stackProgress.total})`;\n }\n\n private failureReasonOnNextLine(activity: StackActivity) {\n return stackEventHasErrorMessage(activity.event.ResourceStatus ?? '')\n ? `\\n${' '.repeat(CurrentActivityPrinter.TIMESTAMP_WIDTH + CurrentActivityPrinter.STATUS_WIDTH + 6)}${chalk.red(this.failureReason(activity) ?? '')}`\n : '';\n }\n}\n\nconst FULL_BLOCK = '\u2588';\nconst PARTIAL_BLOCK = ['', '\u258F', '\u258E', '\u258D', '\u258C', '\u258B', '\u258A', '\u2589'];\nconst MAX_PROGRESSBAR_WIDTH = 60;\nconst MIN_PROGRESSBAR_WIDTH = 10;\nconst PROGRESSBAR_EXTRA_SPACE =\n 2 /* leading spaces */ + 2 /* brackets */ + 4 /* progress number decoration */ + 6; /* 2 progress numbers up to 999 */\n\nfunction colorFromStatusActivity(status?: string) {\n if (!status) {\n return chalk.reset;\n }\n\n if (status.endsWith('_FAILED')) {\n return chalk.red;\n }\n\n if (status.startsWith('CREATE_') || status.startsWith('UPDATE_') || status.startsWith('IMPORT_')) {\n return chalk.green;\n }\n // For stacks, it may also be 'UPDDATE_ROLLBACK_IN_PROGRESS'\n if (status.indexOf('ROLLBACK_') !== -1) {\n return chalk.yellow;\n }\n if (status.startsWith('DELETE_')) {\n return chalk.yellow;\n }\n\n return chalk.reset;\n}\n\nfunction shorten(maxWidth: number, p: string) {\n if (p.length <= maxWidth) {\n return p;\n }\n const half = Math.floor((maxWidth - 3) / 2);\n return p.slice(0, half) + '...' + p.slice(-half);\n}\n\n", "// namespace object imports won't work in the bundle for function exports\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nconst wrapAnsi = require('wrap-ansi');\n\n/**\n * A class representing rewritable display lines\n */\nexport class RewritableBlock {\n private lastHeight = 0;\n private trailingEmptyLines = 0;\n\n constructor(private readonly stream: NodeJS.WriteStream) {\n }\n\n public get width() {\n // Might get changed if the user resizes the terminal\n return this.stream.columns;\n }\n\n public get height() {\n // Might get changed if the user resizes the terminal\n return this.stream.rows;\n }\n\n public displayLines(lines: string[]) {\n lines = terminalWrap(this.width, expandNewlines(lines));\n lines = lines.slice(0, getMaxBlockHeight(this.height, this.lastHeight, lines));\n\n this.stream.write(cursorUp(this.lastHeight));\n for (const line of lines) {\n this.stream.write(cll() + line + '\\n');\n }\n\n this.trailingEmptyLines = Math.max(0, this.lastHeight - lines.length);\n\n // Clear remainder of unwritten lines\n for (let i = 0; i < this.trailingEmptyLines; i++) {\n this.stream.write(cll() + '\\n');\n }\n\n // The block can only ever get bigger\n this.lastHeight = Math.max(this.lastHeight, lines.length);\n }\n\n public removeEmptyLines() {\n this.stream.write(cursorUp(this.trailingEmptyLines));\n }\n}\n\nconst ESC = '\\u001b';\n\n/*\n * Move cursor up `n` lines. Default is 1\n */\nfunction cursorUp(n: number) {\n n = typeof n === 'number' ? n : 1;\n return n > 0 ? ESC + '[' + n + 'A' : '';\n}\n\n/**\n * Clear to end of line\n */\nfunction cll() {\n return ESC + '[K';\n}\n\nfunction terminalWrap(width: number | undefined, lines: string[]) {\n if (width === undefined) {\n return lines;\n }\n\n return lines.flatMap(line => wrapAnsi(line, width - 1, {\n hard: true,\n trim: true,\n wordWrap: false,\n }).split('\\n'));\n}\n\n/**\n * Make sure there are no hidden newlines in the gin strings\n */\nfunction expandNewlines(lines: string[]): string[] {\n return lines.flatMap(line => line.split('\\n'));\n}\n\nfunction getMaxBlockHeight(windowHeight: number | undefined, lastHeight: number, lines: string[]): number {\n if (windowHeight === undefined) {\n return Math.max(lines.length, lastHeight);\n }\n return lines.length < windowHeight ? lines.length : windowHeight - 1;\n}\n", "import * as fs from 'fs-extra';\nimport { ProxyAgent } from 'proxy-agent';\nimport type { SdkHttpOptions } from './sdk-provider';\nimport { IO, type IoHelper } from '../io/private';\n\nexport class ProxyAgentProvider {\n private readonly ioHelper: IoHelper;\n\n public constructor(ioHelper: IoHelper) {\n this.ioHelper = ioHelper;\n }\n\n public async create(options: SdkHttpOptions) {\n // Force it to use the proxy provided through the command line.\n // Otherwise, let the ProxyAgent auto-detect the proxy using environment variables.\n const getProxyForUrl = options.proxyAddress != null\n ? () => Promise.resolve(options.proxyAddress!)\n : undefined;\n\n return new ProxyAgent({\n ca: await this.tryGetCACert(options.caBundlePath),\n getProxyForUrl,\n });\n }\n\n private async tryGetCACert(bundlePath?: string) {\n const path = bundlePath || this.caBundlePathFromEnvironment();\n if (path) {\n await this.ioHelper.notify(IO.DEFAULT_SDK_DEBUG.msg(`Using CA bundle path: ${path}`));\n try {\n if (!fs.pathExistsSync(path)) {\n return undefined;\n }\n return fs.readFileSync(path, { encoding: 'utf-8' });\n } catch (e: any) {\n await this.ioHelper.notify(IO.DEFAULT_SDK_DEBUG.msg(String(e)));\n return undefined;\n }\n }\n return undefined;\n }\n\n /**\n * Find and return a CA certificate bundle path to be passed into the SDK.\n */\n private caBundlePathFromEnvironment(): string | undefined {\n if (process.env.aws_ca_bundle) {\n return process.env.aws_ca_bundle;\n }\n if (process.env.AWS_CA_BUNDLE) {\n return process.env.AWS_CA_BUNDLE;\n }\n return undefined;\n }\n}\n\n", "import type {\n FunctionConfiguration,\n GetSchemaCreationStatusCommandInput,\n GetSchemaCreationStatusCommandOutput,\n ListFunctionsCommandInput,\n StartSchemaCreationCommandInput,\n StartSchemaCreationCommandOutput,\n UpdateApiKeyCommandInput,\n UpdateApiKeyCommandOutput,\n UpdateFunctionCommandInput,\n UpdateFunctionCommandOutput,\n UpdateResolverCommandInput,\n UpdateResolverCommandOutput,\n} from '@aws-sdk/client-appsync';\nimport {\n AppSyncClient,\n GetSchemaCreationStatusCommand,\n paginateListFunctions,\n StartSchemaCreationCommand,\n UpdateApiKeyCommand,\n UpdateFunctionCommand,\n UpdateResolverCommand,\n} from '@aws-sdk/client-appsync';\nimport type {\n GetResourceCommandInput,\n GetResourceCommandOutput,\n ListResourcesCommandInput,\n ListResourcesCommandOutput,\n} from '@aws-sdk/client-cloudcontrol';\nimport {\n CloudControlClient,\n GetResourceCommand,\n ListResourcesCommand,\n} from '@aws-sdk/client-cloudcontrol';\nimport type {\n ContinueUpdateRollbackCommandInput,\n ContinueUpdateRollbackCommandOutput,\n DescribeStackEventsCommandOutput,\n DescribeStackResourcesCommandInput,\n DescribeStackResourcesCommandOutput,\n ListStacksCommandInput,\n ListStacksCommandOutput,\n RollbackStackCommandInput,\n RollbackStackCommandOutput,\n StackResourceSummary,\n CreateChangeSetCommandInput,\n CreateChangeSetCommandOutput,\n CreateGeneratedTemplateCommandInput,\n CreateGeneratedTemplateCommandOutput,\n CreateStackCommandInput,\n CreateStackCommandOutput,\n DeleteChangeSetCommandInput,\n DeleteChangeSetCommandOutput,\n DeleteGeneratedTemplateCommandInput,\n DeleteGeneratedTemplateCommandOutput,\n DeleteStackCommandInput,\n DeleteStackCommandOutput,\n DescribeChangeSetCommandInput,\n DescribeChangeSetCommandOutput,\n DescribeGeneratedTemplateCommandInput,\n DescribeGeneratedTemplateCommandOutput,\n DescribeResourceScanCommandInput,\n DescribeResourceScanCommandOutput,\n DescribeStackEventsCommandInput,\n DescribeStacksCommandInput,\n DescribeStacksCommandOutput,\n ExecuteChangeSetCommandInput,\n ExecuteChangeSetCommandOutput,\n GetGeneratedTemplateCommandInput,\n GetGeneratedTemplateCommandOutput,\n GetTemplateCommandInput,\n GetTemplateCommandOutput,\n GetTemplateSummaryCommandInput,\n GetTemplateSummaryCommandOutput,\n ListExportsCommandInput,\n ListExportsCommandOutput,\n ListResourceScanRelatedResourcesCommandInput,\n ListResourceScanRelatedResourcesCommandOutput,\n ListResourceScanResourcesCommandInput,\n ListResourceScanResourcesCommandOutput,\n ListResourceScansCommandInput,\n ListResourceScansCommandOutput,\n ListStackResourcesCommandInput,\n StartResourceScanCommandInput,\n StartResourceScanCommandOutput,\n UpdateStackCommandInput,\n UpdateStackCommandOutput,\n UpdateTerminationProtectionCommandInput,\n UpdateTerminationProtectionCommandOutput,\n} from '@aws-sdk/client-cloudformation';\nimport {\n CloudFormationClient,\n ContinueUpdateRollbackCommand,\n CreateChangeSetCommand,\n CreateGeneratedTemplateCommand,\n CreateStackCommand,\n DeleteChangeSetCommand,\n DeleteGeneratedTemplateCommand,\n DeleteStackCommand,\n DescribeChangeSetCommand,\n DescribeGeneratedTemplateCommand,\n DescribeResourceScanCommand,\n DescribeStackEventsCommand,\n DescribeStackResourcesCommand,\n DescribeStacksCommand,\n ExecuteChangeSetCommand,\n GetGeneratedTemplateCommand,\n GetTemplateCommand,\n GetTemplateSummaryCommand,\n ListExportsCommand,\n ListResourceScanRelatedResourcesCommand,\n ListResourceScanResourcesCommand,\n ListResourceScansCommand,\n ListStacksCommand,\n paginateListStackResources,\n RollbackStackCommand,\n StartResourceScanCommand,\n UpdateStackCommand,\n UpdateTerminationProtectionCommand,\n} from '@aws-sdk/client-cloudformation';\nimport type {\n FilterLogEventsCommandInput,\n FilterLogEventsCommandOutput,\n DescribeLogGroupsCommandInput,\n DescribeLogGroupsCommandOutput,\n} from '@aws-sdk/client-cloudwatch-logs';\nimport {\n CloudWatchLogsClient,\n DescribeLogGroupsCommand,\n FilterLogEventsCommand,\n} from '@aws-sdk/client-cloudwatch-logs';\nimport {\n CodeBuildClient,\n UpdateProjectCommand,\n type UpdateProjectCommandInput,\n type UpdateProjectCommandOutput,\n} from '@aws-sdk/client-codebuild';\nimport {\n DescribeAvailabilityZonesCommand,\n type DescribeAvailabilityZonesCommandInput,\n type DescribeAvailabilityZonesCommandOutput,\n DescribeImagesCommand,\n type DescribeImagesCommandInput,\n type DescribeImagesCommandOutput,\n DescribeInstancesCommand,\n type DescribeInstancesCommandInput,\n type DescribeInstancesCommandOutput,\n DescribeRouteTablesCommand,\n type DescribeRouteTablesCommandInput,\n type DescribeRouteTablesCommandOutput,\n DescribeSecurityGroupsCommand,\n type DescribeSecurityGroupsCommandInput,\n type DescribeSecurityGroupsCommandOutput,\n DescribeSubnetsCommand,\n type DescribeSubnetsCommandInput,\n type DescribeSubnetsCommandOutput,\n DescribeVpcEndpointServicesCommand,\n type DescribeVpcEndpointServicesCommandInput,\n type DescribeVpcEndpointServicesCommandOutput,\n DescribeVpcsCommand,\n type DescribeVpcsCommandInput,\n type DescribeVpcsCommandOutput,\n DescribeVpnGatewaysCommand,\n type DescribeVpnGatewaysCommandInput,\n type DescribeVpnGatewaysCommandOutput,\n EC2Client,\n} from '@aws-sdk/client-ec2';\nimport type {\n BatchDeleteImageCommandInput,\n BatchDeleteImageCommandOutput,\n ListImagesCommandInput,\n ListImagesCommandOutput,\n PutImageCommandInput,\n PutImageCommandOutput,\n BatchGetImageCommandInput,\n BatchGetImageCommandOutput,\n CreateRepositoryCommandInput,\n CreateRepositoryCommandOutput,\n DescribeImagesCommandInput as ECRDescribeImagesCommandInput,\n DescribeImagesCommandOutput as ECRDescribeImagesCommandOutput,\n DescribeRepositoriesCommandInput,\n DescribeRepositoriesCommandOutput,\n GetAuthorizationTokenCommandInput,\n GetAuthorizationTokenCommandOutput,\n PutImageScanningConfigurationCommandInput,\n PutImageScanningConfigurationCommandOutput,\n} from '@aws-sdk/client-ecr';\nimport {\n BatchDeleteImageCommand,\n CreateRepositoryCommand,\n DescribeImagesCommand as ECRDescribeImagesCommand,\n DescribeRepositoriesCommand,\n ECRClient,\n GetAuthorizationTokenCommand,\n ListImagesCommand,\n PutImageCommand,\n PutImageScanningConfigurationCommand,\n BatchGetImageCommand,\n} from '@aws-sdk/client-ecr';\nimport type {\n DescribeServicesCommandInput,\n RegisterTaskDefinitionCommandInput,\n ListClustersCommandInput,\n ListClustersCommandOutput,\n RegisterTaskDefinitionCommandOutput,\n UpdateServiceCommandInput,\n UpdateServiceCommandOutput,\n} from '@aws-sdk/client-ecs';\nimport {\n ECSClient,\n ListClustersCommand,\n RegisterTaskDefinitionCommand,\n UpdateServiceCommand,\n waitUntilServicesStable,\n} from '@aws-sdk/client-ecs';\nimport type {\n Listener,\n LoadBalancer,\n DescribeListenersCommandInput,\n DescribeListenersCommandOutput,\n DescribeLoadBalancersCommandInput,\n DescribeLoadBalancersCommandOutput,\n DescribeTagsCommandInput,\n DescribeTagsCommandOutput,\n} from '@aws-sdk/client-elastic-load-balancing-v2';\nimport {\n DescribeListenersCommand,\n DescribeLoadBalancersCommand,\n DescribeTagsCommand,\n ElasticLoadBalancingV2Client,\n paginateDescribeListeners,\n paginateDescribeLoadBalancers,\n} from '@aws-sdk/client-elastic-load-balancing-v2';\nimport {\n CreatePolicyCommand,\n type CreatePolicyCommandInput,\n type CreatePolicyCommandOutput,\n GetPolicyCommand,\n type GetPolicyCommandInput,\n type GetPolicyCommandOutput,\n GetRoleCommand,\n type GetRoleCommandInput,\n type GetRoleCommandOutput,\n IAMClient,\n} from '@aws-sdk/client-iam';\nimport {\n DescribeKeyCommand,\n type DescribeKeyCommandInput,\n type DescribeKeyCommandOutput,\n KMSClient,\n ListAliasesCommand,\n type ListAliasesCommandInput,\n type ListAliasesCommandOutput,\n} from '@aws-sdk/client-kms';\nimport {\n InvokeCommand,\n type InvokeCommandInput,\n type InvokeCommandOutput,\n LambdaClient,\n PublishVersionCommand,\n type PublishVersionCommandInput,\n type PublishVersionCommandOutput,\n UpdateAliasCommand,\n type UpdateAliasCommandInput,\n type UpdateAliasCommandOutput,\n UpdateFunctionCodeCommand,\n type UpdateFunctionCodeCommandInput,\n type UpdateFunctionCodeCommandOutput,\n UpdateFunctionConfigurationCommand,\n type UpdateFunctionConfigurationCommandInput,\n type UpdateFunctionConfigurationCommandOutput,\n waitUntilFunctionUpdatedV2,\n} from '@aws-sdk/client-lambda';\nimport {\n GetHostedZoneCommand,\n type GetHostedZoneCommandInput,\n type GetHostedZoneCommandOutput,\n ListHostedZonesByNameCommand,\n type ListHostedZonesByNameCommandInput,\n type ListHostedZonesByNameCommandOutput,\n ListHostedZonesCommand,\n type ListHostedZonesCommandInput,\n type ListHostedZonesCommandOutput,\n Route53Client,\n} from '@aws-sdk/client-route-53';\nimport type {\n DeleteObjectsCommandInput,\n DeleteObjectsCommandOutput,\n DeleteObjectTaggingCommandInput,\n DeleteObjectTaggingCommandOutput,\n GetObjectTaggingCommandInput,\n GetObjectTaggingCommandOutput,\n PutObjectTaggingCommandInput,\n PutObjectTaggingCommandOutput,\n CompleteMultipartUploadCommandOutput,\n GetBucketEncryptionCommandInput,\n GetBucketEncryptionCommandOutput,\n GetBucketLocationCommandInput,\n GetBucketLocationCommandOutput,\n GetObjectCommandInput,\n GetObjectCommandOutput,\n ListObjectsV2CommandInput,\n ListObjectsV2CommandOutput,\n PutObjectCommandInput,\n} from '@aws-sdk/client-s3';\nimport {\n DeleteObjectsCommand,\n DeleteObjectTaggingCommand,\n GetBucketEncryptionCommand,\n GetBucketLocationCommand,\n GetObjectCommand,\n GetObjectTaggingCommand,\n ListObjectsV2Command,\n PutObjectTaggingCommand,\n S3Client,\n} from '@aws-sdk/client-s3';\nimport {\n GetSecretValueCommand,\n type GetSecretValueCommandInput,\n type GetSecretValueCommandOutput,\n SecretsManagerClient,\n} from '@aws-sdk/client-secrets-manager';\nimport type {\n UpdateStateMachineCommandInput,\n UpdateStateMachineCommandOutput,\n} from '@aws-sdk/client-sfn';\nimport {\n SFNClient,\n UpdateStateMachineCommand,\n} from '@aws-sdk/client-sfn';\nimport {\n GetParameterCommand,\n type GetParameterCommandInput,\n type GetParameterCommandOutput,\n SSMClient,\n} from '@aws-sdk/client-ssm';\nimport { GetCallerIdentityCommand, STSClient } from '@aws-sdk/client-sts';\nimport { Upload } from '@aws-sdk/lib-storage';\nimport { getEndpointFromInstructions } from '@smithy/middleware-endpoint';\nimport type { NodeHttpHandlerOptions } from '@smithy/node-http-handler';\nimport type { AwsCredentialIdentityProvider, Logger } from '@smithy/types';\nimport { ConfiguredRetryStrategy } from '@smithy/util-retry';\nimport type { WaiterResult } from '@smithy/util-waiter';\nimport { AccountAccessKeyCache } from './account-cache';\nimport { cachedAsync } from './cached';\nimport type { Account } from './sdk-provider';\nimport { traceMemberMethods } from './tracing';\nimport { defaultCliUserAgent } from './user-agent';\nimport { formatErrorMessage } from '../../util';\nimport { IO, type IoHelper } from '../io/private';\nimport { AuthenticationError } from '../toolkit-error';\n\nexport interface S3ClientOptions {\n /**\n * If APIs are used that require MD5 checksums.\n *\n * Some S3 APIs in SDKv2 have a bug that always requires them to use a MD5 checksum.\n * These APIs are not going to be supported in a FIPS environment.\n */\n needsMd5Checksums?: boolean;\n}\n\n/**\n * Additional SDK configuration options\n */\nexport interface SdkOptions {\n /**\n * Additional descriptive strings that indicate where the \"AssumeRole\" credentials are coming from\n *\n * Will be printed in an error message to help users diagnose auth problems.\n */\n readonly assumeRoleCredentialsSourceDescription?: string;\n}\n\n// TODO: still some cleanup here. Make the pagination functions do all the work here instead of in individual packages.\n// Also add async/await. Does that actually matter in this context? Find out and update accordingly.\n\n// Also add notes to the PR about why you imported everything individually and used 'type' so reviewers don't have to ask.\n\nexport interface ConfigurationOptions {\n region: string;\n credentials: AwsCredentialIdentityProvider;\n requestHandler: NodeHttpHandlerOptions;\n retryStrategy: ConfiguredRetryStrategy;\n customUserAgent: string;\n logger?: Logger;\n s3DisableBodySigning?: boolean;\n computeChecksums?: boolean;\n}\n\nexport interface IAppSyncClient {\n getSchemaCreationStatus(input: GetSchemaCreationStatusCommandInput): Promise<GetSchemaCreationStatusCommandOutput>;\n startSchemaCreation(input: StartSchemaCreationCommandInput): Promise<StartSchemaCreationCommandOutput>;\n updateApiKey(input: UpdateApiKeyCommandInput): Promise<UpdateApiKeyCommandOutput>;\n updateFunction(input: UpdateFunctionCommandInput): Promise<UpdateFunctionCommandOutput>;\n updateResolver(input: UpdateResolverCommandInput): Promise<UpdateResolverCommandOutput>;\n // Pagination functions\n listFunctions(input: ListFunctionsCommandInput): Promise<FunctionConfiguration[]>;\n}\n\nexport interface ICloudControlClient{\n listResources(input: ListResourcesCommandInput): Promise<ListResourcesCommandOutput>;\n getResource(input: GetResourceCommandInput): Promise<GetResourceCommandOutput>;\n}\n\nexport interface ICloudFormationClient {\n continueUpdateRollback(input: ContinueUpdateRollbackCommandInput): Promise<ContinueUpdateRollbackCommandOutput>;\n createChangeSet(input: CreateChangeSetCommandInput): Promise<CreateChangeSetCommandOutput>;\n createGeneratedTemplate(input: CreateGeneratedTemplateCommandInput): Promise<CreateGeneratedTemplateCommandOutput>;\n createStack(input: CreateStackCommandInput): Promise<CreateStackCommandOutput>;\n deleteChangeSet(input: DeleteChangeSetCommandInput): Promise<DeleteChangeSetCommandOutput>;\n deleteGeneratedTemplate(input: DeleteGeneratedTemplateCommandInput): Promise<DeleteGeneratedTemplateCommandOutput>;\n deleteStack(input: DeleteStackCommandInput): Promise<DeleteStackCommandOutput>;\n describeChangeSet(input: DescribeChangeSetCommandInput): Promise<DescribeChangeSetCommandOutput>;\n describeGeneratedTemplate(\n input: DescribeGeneratedTemplateCommandInput,\n ): Promise<DescribeGeneratedTemplateCommandOutput>;\n describeResourceScan(input: DescribeResourceScanCommandInput): Promise<DescribeResourceScanCommandOutput>;\n describeStacks(input: DescribeStacksCommandInput): Promise<DescribeStacksCommandOutput>;\n describeStackResources(input: DescribeStackResourcesCommandInput): Promise<DescribeStackResourcesCommandOutput>;\n executeChangeSet(input: ExecuteChangeSetCommandInput): Promise<ExecuteChangeSetCommandOutput>;\n getGeneratedTemplate(input: GetGeneratedTemplateCommandInput): Promise<GetGeneratedTemplateCommandOutput>;\n getTemplate(input: GetTemplateCommandInput): Promise<GetTemplateCommandOutput>;\n getTemplateSummary(input: GetTemplateSummaryCommandInput): Promise<GetTemplateSummaryCommandOutput>;\n listExports(input: ListExportsCommandInput): Promise<ListExportsCommandOutput>;\n listResourceScanRelatedResources(\n input: ListResourceScanRelatedResourcesCommandInput,\n ): Promise<ListResourceScanRelatedResourcesCommandOutput>;\n listResourceScanResources(\n input: ListResourceScanResourcesCommandInput,\n ): Promise<ListResourceScanResourcesCommandOutput>;\n listResourceScans(input?: ListResourceScansCommandInput): Promise<ListResourceScansCommandOutput>;\n listStacks(input: ListStacksCommandInput): Promise<ListStacksCommandOutput>;\n rollbackStack(input: RollbackStackCommandInput): Promise<RollbackStackCommandOutput>;\n startResourceScan(input: StartResourceScanCommandInput): Promise<StartResourceScanCommandOutput>;\n updateStack(input: UpdateStackCommandInput): Promise<UpdateStackCommandOutput>;\n updateTerminationProtection(\n input: UpdateTerminationProtectionCommandInput,\n ): Promise<UpdateTerminationProtectionCommandOutput>;\n // Pagination functions\n describeStackEvents(input: DescribeStackEventsCommandInput): Promise<DescribeStackEventsCommandOutput>;\n listStackResources(input: ListStackResourcesCommandInput): Promise<StackResourceSummary[]>;\n}\n\nexport interface ICloudWatchLogsClient {\n describeLogGroups(input: DescribeLogGroupsCommandInput): Promise<DescribeLogGroupsCommandOutput>;\n filterLogEvents(input: FilterLogEventsCommandInput): Promise<FilterLogEventsCommandOutput>;\n}\n\nexport interface ICodeBuildClient {\n updateProject(input: UpdateProjectCommandInput): Promise<UpdateProjectCommandOutput>;\n}\nexport interface IEC2Client {\n describeAvailabilityZones(\n input: DescribeAvailabilityZonesCommandInput,\n ): Promise<DescribeAvailabilityZonesCommandOutput>;\n describeImages(input: DescribeImagesCommandInput): Promise<DescribeImagesCommandOutput>;\n describeInstances(input: DescribeInstancesCommandInput): Promise<DescribeInstancesCommandOutput>;\n describeRouteTables(input: DescribeRouteTablesCommandInput): Promise<DescribeRouteTablesCommandOutput>;\n describeSecurityGroups(input: DescribeSecurityGroupsCommandInput): Promise<DescribeSecurityGroupsCommandOutput>;\n describeSubnets(input: DescribeSubnetsCommandInput): Promise<DescribeSubnetsCommandOutput>;\n describeVpcEndpointServices(\n input: DescribeVpcEndpointServicesCommandInput,\n ): Promise<DescribeVpcEndpointServicesCommandOutput>;\n describeVpcs(input: DescribeVpcsCommandInput): Promise<DescribeVpcsCommandOutput>;\n describeVpnGateways(input: DescribeVpnGatewaysCommandInput): Promise<DescribeVpnGatewaysCommandOutput>;\n}\n\nexport interface IECRClient {\n batchDeleteImage(input: BatchDeleteImageCommandInput): Promise<BatchDeleteImageCommandOutput>;\n batchGetImage(input: BatchGetImageCommandInput): Promise<BatchGetImageCommandOutput>;\n createRepository(input: CreateRepositoryCommandInput): Promise<CreateRepositoryCommandOutput>;\n describeImages(input: ECRDescribeImagesCommandInput): Promise<ECRDescribeImagesCommandOutput>;\n describeRepositories(input: DescribeRepositoriesCommandInput): Promise<DescribeRepositoriesCommandOutput>;\n getAuthorizationToken(input: GetAuthorizationTokenCommandInput): Promise<GetAuthorizationTokenCommandOutput>;\n listImages(input: ListImagesCommandInput): Promise<ListImagesCommandOutput>;\n putImage(input: PutImageCommandInput): Promise<PutImageCommandOutput>;\n putImageScanningConfiguration(\n input: PutImageScanningConfigurationCommandInput,\n ): Promise<PutImageScanningConfigurationCommandOutput>;\n}\n\nexport interface IECSClient {\n listClusters(input: ListClustersCommandInput): Promise<ListClustersCommandOutput>;\n registerTaskDefinition(input: RegisterTaskDefinitionCommandInput): Promise<RegisterTaskDefinitionCommandOutput>;\n updateService(input: UpdateServiceCommandInput): Promise<UpdateServiceCommandOutput>;\n // Waiters\n waitUntilServicesStable(input: DescribeServicesCommandInput): Promise<WaiterResult>;\n}\n\nexport interface IElasticLoadBalancingV2Client {\n describeListeners(input: DescribeListenersCommandInput): Promise<DescribeListenersCommandOutput>;\n describeLoadBalancers(input: DescribeLoadBalancersCommandInput): Promise<DescribeLoadBalancersCommandOutput>;\n describeTags(input: DescribeTagsCommandInput): Promise<DescribeTagsCommandOutput>;\n // Pagination\n paginateDescribeListeners(input: DescribeListenersCommandInput): Promise<Listener[]>;\n paginateDescribeLoadBalancers(input: DescribeLoadBalancersCommandInput): Promise<LoadBalancer[]>;\n}\n\nexport interface IIAMClient {\n createPolicy(input: CreatePolicyCommandInput): Promise<CreatePolicyCommandOutput>;\n getPolicy(input: GetPolicyCommandInput): Promise<GetPolicyCommandOutput>;\n getRole(input: GetRoleCommandInput): Promise<GetRoleCommandOutput>;\n}\n\nexport interface IKMSClient {\n describeKey(input: DescribeKeyCommandInput): Promise<DescribeKeyCommandOutput>;\n listAliases(input: ListAliasesCommandInput): Promise<ListAliasesCommandOutput>;\n}\n\nexport interface ILambdaClient {\n invokeCommand(input: InvokeCommandInput): Promise<InvokeCommandOutput>;\n publishVersion(input: PublishVersionCommandInput): Promise<PublishVersionCommandOutput>;\n updateAlias(input: UpdateAliasCommandInput): Promise<UpdateAliasCommandOutput>;\n updateFunctionCode(input: UpdateFunctionCodeCommandInput): Promise<UpdateFunctionCodeCommandOutput>;\n updateFunctionConfiguration(\n input: UpdateFunctionConfigurationCommandInput,\n ): Promise<UpdateFunctionConfigurationCommandOutput>;\n // Waiters\n waitUntilFunctionUpdated(delaySeconds: number, input: UpdateFunctionConfigurationCommandInput): Promise<WaiterResult>;\n}\n\nexport interface IRoute53Client {\n getHostedZone(input: GetHostedZoneCommandInput): Promise<GetHostedZoneCommandOutput>;\n listHostedZones(input: ListHostedZonesCommandInput): Promise<ListHostedZonesCommandOutput>;\n listHostedZonesByName(input: ListHostedZonesByNameCommandInput): Promise<ListHostedZonesByNameCommandOutput>;\n}\n\nexport interface IS3Client {\n deleteObjects(input: DeleteObjectsCommandInput): Promise<DeleteObjectsCommandOutput>;\n deleteObjectTagging(input: DeleteObjectTaggingCommandInput): Promise<DeleteObjectTaggingCommandOutput>;\n getBucketEncryption(input: GetBucketEncryptionCommandInput): Promise<GetBucketEncryptionCommandOutput>;\n getBucketLocation(input: GetBucketLocationCommandInput): Promise<GetBucketLocationCommandOutput>;\n getObject(input: GetObjectCommandInput): Promise<GetObjectCommandOutput>;\n getObjectTagging(input: GetObjectTaggingCommandInput): Promise<GetObjectTaggingCommandOutput>;\n listObjectsV2(input: ListObjectsV2CommandInput): Promise<ListObjectsV2CommandOutput>;\n putObjectTagging(input: PutObjectTaggingCommandInput): Promise<PutObjectTaggingCommandOutput>;\n upload(input: PutObjectCommandInput): Promise<CompleteMultipartUploadCommandOutput>;\n}\n\nexport interface ISecretsManagerClient {\n getSecretValue(input: GetSecretValueCommandInput): Promise<GetSecretValueCommandOutput>;\n}\n\nexport interface ISSMClient {\n getParameter(input: GetParameterCommandInput): Promise<GetParameterCommandOutput>;\n}\n\nexport interface IStepFunctionsClient {\n updateStateMachine(input: UpdateStateMachineCommandInput): Promise<UpdateStateMachineCommandOutput>;\n}\n\n/**\n * Base functionality of SDK without credential fetching\n */\n@traceMemberMethods\nexport class SDK {\n public readonly currentRegion: string;\n\n public readonly config: ConfigurationOptions;\n\n protected readonly logger?: Logger;\n\n private readonly accountCache;\n\n /**\n * STS is used to check credential validity, don't do too many retries.\n */\n private readonly stsRetryStrategy = new ConfiguredRetryStrategy(3, (attempt) => 100 * (2 ** attempt));\n\n /**\n * Whether we have proof that the credentials have not expired\n *\n * We need to do some manual plumbing around this because the JS SDKv2 treats `ExpiredToken`\n * as retriable and we have hefty retries on CFN calls making the CLI hang for a good 15 minutes\n * if the credentials have expired.\n */\n private _credentialsValidated = false;\n\n /**\n * A function to create debug messages\n */\n private readonly debug: (msg: string) => Promise<void>;\n\n constructor(\n private readonly credProvider: AwsCredentialIdentityProvider,\n region: string,\n requestHandler: NodeHttpHandlerOptions,\n ioHelper: IoHelper,\n logger?: Logger,\n ) {\n const debugFn = async (msg: string) => ioHelper.notify(IO.DEFAULT_SDK_DEBUG.msg(msg));\n this.accountCache = new AccountAccessKeyCache(AccountAccessKeyCache.DEFAULT_PATH, debugFn);\n this.debug = debugFn;\n this.config = {\n region,\n credentials: credProvider,\n requestHandler,\n retryStrategy: new ConfiguredRetryStrategy(7, (attempt) => 300 * (2 ** attempt)),\n customUserAgent: defaultCliUserAgent(),\n logger,\n };\n this.logger = logger;\n this.currentRegion = region;\n }\n\n public appendCustomUserAgent(userAgentData?: string): void {\n if (!userAgentData) {\n return;\n }\n\n const currentCustomUserAgent = this.config.customUserAgent;\n this.config.customUserAgent = currentCustomUserAgent ? `${currentCustomUserAgent} ${userAgentData}` : userAgentData;\n }\n\n public removeCustomUserAgent(userAgentData: string): void {\n this.config.customUserAgent = this.config.customUserAgent?.replace(userAgentData, '');\n }\n\n public appsync(): IAppSyncClient {\n const client = new AppSyncClient(this.config);\n return {\n getSchemaCreationStatus: (\n input: GetSchemaCreationStatusCommandInput,\n ): Promise<GetSchemaCreationStatusCommandOutput> => client.send(new GetSchemaCreationStatusCommand(input)),\n startSchemaCreation: (input: StartSchemaCreationCommandInput): Promise<StartSchemaCreationCommandOutput> =>\n client.send(new StartSchemaCreationCommand(input)),\n updateApiKey: (input: UpdateApiKeyCommandInput): Promise<UpdateApiKeyCommandOutput> =>\n client.send(new UpdateApiKeyCommand(input)),\n updateFunction: (input: UpdateFunctionCommandInput): Promise<UpdateFunctionCommandOutput> =>\n client.send(new UpdateFunctionCommand(input)),\n updateResolver: (input: UpdateResolverCommandInput): Promise<UpdateResolverCommandOutput> =>\n client.send(new UpdateResolverCommand(input)),\n\n // Pagination Functions\n listFunctions: async (input: ListFunctionsCommandInput): Promise<FunctionConfiguration[]> => {\n const functions = Array<FunctionConfiguration>();\n const paginator = paginateListFunctions({ client }, input);\n for await (const page of paginator) {\n functions.push(...(page.functions || []));\n }\n return functions;\n },\n };\n }\n\n public cloudControl(): ICloudControlClient {\n const client = new CloudControlClient(this.config);\n return {\n listResources: (input: ListResourcesCommandInput): Promise<ListResourcesCommandOutput> =>\n client.send(new ListResourcesCommand(input)),\n getResource: (input: GetResourceCommandInput): Promise<GetResourceCommandOutput> =>\n client.send(new GetResourceCommand(input)),\n };\n }\n\n public cloudFormation(): ICloudFormationClient {\n const client = new CloudFormationClient({\n ...this.config,\n retryStrategy: new ConfiguredRetryStrategy(11, (attempt: number) => 1000 * (2 ** attempt)),\n });\n return {\n continueUpdateRollback: async (\n input: ContinueUpdateRollbackCommandInput,\n ): Promise<ContinueUpdateRollbackCommandOutput> => client.send(new ContinueUpdateRollbackCommand(input)),\n createChangeSet: (input: CreateChangeSetCommandInput): Promise<CreateChangeSetCommandOutput> =>\n client.send(new CreateChangeSetCommand(input)),\n createGeneratedTemplate: (\n input: CreateGeneratedTemplateCommandInput,\n ): Promise<CreateGeneratedTemplateCommandOutput> => client.send(new CreateGeneratedTemplateCommand(input)),\n createStack: (input: CreateStackCommandInput): Promise<CreateStackCommandOutput> =>\n client.send(new CreateStackCommand(input)),\n deleteChangeSet: (input: DeleteChangeSetCommandInput): Promise<DeleteChangeSetCommandOutput> =>\n client.send(new DeleteChangeSetCommand(input)),\n deleteGeneratedTemplate: (\n input: DeleteGeneratedTemplateCommandInput,\n ): Promise<DeleteGeneratedTemplateCommandOutput> => client.send(new DeleteGeneratedTemplateCommand(input)),\n deleteStack: (input: DeleteStackCommandInput): Promise<DeleteStackCommandOutput> =>\n client.send(new DeleteStackCommand(input)),\n describeChangeSet: (input: DescribeChangeSetCommandInput): Promise<DescribeChangeSetCommandOutput> =>\n client.send(new DescribeChangeSetCommand(input)),\n describeGeneratedTemplate: (\n input: DescribeGeneratedTemplateCommandInput,\n ): Promise<DescribeGeneratedTemplateCommandOutput> => client.send(new DescribeGeneratedTemplateCommand(input)),\n describeResourceScan: (input: DescribeResourceScanCommandInput): Promise<DescribeResourceScanCommandOutput> =>\n client.send(new DescribeResourceScanCommand(input)),\n describeStacks: (input: DescribeStacksCommandInput): Promise<DescribeStacksCommandOutput> =>\n client.send(new DescribeStacksCommand(input)),\n describeStackResources: (input: DescribeStackResourcesCommandInput): Promise<DescribeStackResourcesCommandOutput> =>\n client.send(new DescribeStackResourcesCommand(input)),\n executeChangeSet: (input: ExecuteChangeSetCommandInput): Promise<ExecuteChangeSetCommandOutput> =>\n client.send(new ExecuteChangeSetCommand(input)),\n getGeneratedTemplate: (input: GetGeneratedTemplateCommandInput): Promise<GetGeneratedTemplateCommandOutput> =>\n client.send(new GetGeneratedTemplateCommand(input)),\n getTemplate: (input: GetTemplateCommandInput): Promise<GetTemplateCommandOutput> =>\n client.send(new GetTemplateCommand(input)),\n getTemplateSummary: (input: GetTemplateSummaryCommandInput): Promise<GetTemplateSummaryCommandOutput> =>\n client.send(new GetTemplateSummaryCommand(input)),\n listExports: (input: ListExportsCommandInput): Promise<ListExportsCommandOutput> =>\n client.send(new ListExportsCommand(input)),\n listResourceScanRelatedResources: (\n input: ListResourceScanRelatedResourcesCommandInput,\n ): Promise<ListResourceScanRelatedResourcesCommandOutput> =>\n client.send(new ListResourceScanRelatedResourcesCommand(input)),\n listResourceScanResources: (\n input: ListResourceScanResourcesCommandInput,\n ): Promise<ListResourceScanResourcesCommandOutput> => client.send(new ListResourceScanResourcesCommand(input)),\n listResourceScans: (input: ListResourceScansCommandInput): Promise<ListResourceScansCommandOutput> =>\n client.send(new ListResourceScansCommand(input)),\n listStacks: (input: ListStacksCommandInput): Promise<ListStacksCommandOutput> =>\n client.send(new ListStacksCommand(input)),\n rollbackStack: (input: RollbackStackCommandInput): Promise<RollbackStackCommandOutput> =>\n client.send(new RollbackStackCommand(input)),\n startResourceScan: (input: StartResourceScanCommandInput): Promise<StartResourceScanCommandOutput> =>\n client.send(new StartResourceScanCommand(input)),\n updateStack: (input: UpdateStackCommandInput): Promise<UpdateStackCommandOutput> =>\n client.send(new UpdateStackCommand(input)),\n updateTerminationProtection: (\n input: UpdateTerminationProtectionCommandInput,\n ): Promise<UpdateTerminationProtectionCommandOutput> =>\n client.send(new UpdateTerminationProtectionCommand(input)),\n describeStackEvents: (input: DescribeStackEventsCommandInput): Promise<DescribeStackEventsCommandOutput> => {\n return client.send(new DescribeStackEventsCommand(input));\n },\n listStackResources: async (input: ListStackResourcesCommandInput): Promise<StackResourceSummary[]> => {\n const stackResources = Array<StackResourceSummary>();\n const paginator = paginateListStackResources({ client }, input);\n for await (const page of paginator) {\n stackResources.push(...(page?.StackResourceSummaries || []));\n }\n return stackResources;\n },\n };\n }\n\n public cloudWatchLogs(): ICloudWatchLogsClient {\n const client = new CloudWatchLogsClient(this.config);\n return {\n describeLogGroups: (input: DescribeLogGroupsCommandInput): Promise<DescribeLogGroupsCommandOutput> =>\n client.send(new DescribeLogGroupsCommand(input)),\n filterLogEvents: (input: FilterLogEventsCommandInput): Promise<FilterLogEventsCommandOutput> =>\n client.send(new FilterLogEventsCommand(input)),\n };\n }\n\n public codeBuild(): ICodeBuildClient {\n const client = new CodeBuildClient(this.config);\n return {\n updateProject: (input: UpdateProjectCommandInput): Promise<UpdateProjectCommandOutput> =>\n client.send(new UpdateProjectCommand(input)),\n };\n }\n\n public ec2(): IEC2Client {\n const client = new EC2Client(this.config);\n return {\n describeAvailabilityZones: (\n input: DescribeAvailabilityZonesCommandInput,\n ): Promise<DescribeAvailabilityZonesCommandOutput> => client.send(new DescribeAvailabilityZonesCommand(input)),\n describeImages: (input: DescribeImagesCommandInput): Promise<DescribeImagesCommandOutput> =>\n client.send(new DescribeImagesCommand(input)),\n describeInstances: (input: DescribeInstancesCommandInput): Promise<DescribeInstancesCommandOutput> =>\n client.send(new DescribeInstancesCommand(input)),\n describeRouteTables: (input: DescribeRouteTablesCommandInput): Promise<DescribeRouteTablesCommandOutput> =>\n client.send(new DescribeRouteTablesCommand(input)),\n describeSecurityGroups: (\n input: DescribeSecurityGroupsCommandInput,\n ): Promise<DescribeSecurityGroupsCommandOutput> => client.send(new DescribeSecurityGroupsCommand(input)),\n describeSubnets: (input: DescribeSubnetsCommandInput): Promise<DescribeSubnetsCommandOutput> =>\n client.send(new DescribeSubnetsCommand(input)),\n describeVpcEndpointServices: (\n input: DescribeVpcEndpointServicesCommandInput,\n ): Promise<DescribeVpcEndpointServicesCommandOutput> =>\n client.send(new DescribeVpcEndpointServicesCommand(input)),\n describeVpcs: (input: DescribeVpcsCommandInput): Promise<DescribeVpcsCommandOutput> =>\n client.send(new DescribeVpcsCommand(input)),\n describeVpnGateways: (input: DescribeVpnGatewaysCommandInput): Promise<DescribeVpnGatewaysCommandOutput> =>\n client.send(new DescribeVpnGatewaysCommand(input)),\n };\n }\n\n public ecr(): IECRClient {\n const client = new ECRClient(this.config);\n return {\n batchDeleteImage: (input: BatchDeleteImageCommandInput): Promise<BatchDeleteImageCommandOutput> =>\n client.send(new BatchDeleteImageCommand(input)),\n batchGetImage: (input: BatchGetImageCommandInput): Promise<BatchGetImageCommandOutput> =>\n client.send(new BatchGetImageCommand(input)),\n createRepository: (input: CreateRepositoryCommandInput): Promise<CreateRepositoryCommandOutput> =>\n client.send(new CreateRepositoryCommand(input)),\n describeImages: (input: ECRDescribeImagesCommandInput): Promise<ECRDescribeImagesCommandOutput> =>\n client.send(new ECRDescribeImagesCommand(input)),\n describeRepositories: (input: DescribeRepositoriesCommandInput): Promise<DescribeRepositoriesCommandOutput> =>\n client.send(new DescribeRepositoriesCommand(input)),\n getAuthorizationToken: (input: GetAuthorizationTokenCommandInput): Promise<GetAuthorizationTokenCommandOutput> =>\n client.send(new GetAuthorizationTokenCommand(input)),\n listImages: (input: ListImagesCommandInput): Promise<ListImagesCommandOutput> =>\n client.send(new ListImagesCommand(input)),\n putImage: (input: PutImageCommandInput): Promise<PutImageCommandOutput> =>\n client.send(new PutImageCommand(input)),\n putImageScanningConfiguration: (\n input: PutImageScanningConfigurationCommandInput,\n ): Promise<PutImageScanningConfigurationCommandOutput> =>\n client.send(new PutImageScanningConfigurationCommand(input)),\n };\n }\n\n public ecs(): IECSClient {\n const client = new ECSClient(this.config);\n return {\n listClusters: (input: ListClustersCommandInput): Promise<ListClustersCommandOutput> =>\n client.send(new ListClustersCommand(input)),\n registerTaskDefinition: (\n input: RegisterTaskDefinitionCommandInput,\n ): Promise<RegisterTaskDefinitionCommandOutput> => client.send(new RegisterTaskDefinitionCommand(input)),\n updateService: (input: UpdateServiceCommandInput): Promise<UpdateServiceCommandOutput> =>\n client.send(new UpdateServiceCommand(input)),\n // Waiters\n waitUntilServicesStable: (input: DescribeServicesCommandInput): Promise<WaiterResult> => {\n return waitUntilServicesStable(\n {\n client,\n maxWaitTime: 600,\n minDelay: 6,\n maxDelay: 6,\n },\n input,\n );\n },\n };\n }\n\n public elbv2(): IElasticLoadBalancingV2Client {\n const client = new ElasticLoadBalancingV2Client(this.config);\n return {\n describeListeners: (input: DescribeListenersCommandInput): Promise<DescribeListenersCommandOutput> =>\n client.send(new DescribeListenersCommand(input)),\n describeLoadBalancers: (input: DescribeLoadBalancersCommandInput): Promise<DescribeLoadBalancersCommandOutput> =>\n client.send(new DescribeLoadBalancersCommand(input)),\n describeTags: (input: DescribeTagsCommandInput): Promise<DescribeTagsCommandOutput> =>\n client.send(new DescribeTagsCommand(input)),\n // Pagination Functions\n paginateDescribeListeners: async (input: DescribeListenersCommandInput): Promise<Listener[]> => {\n const listeners = Array<Listener>();\n const paginator = paginateDescribeListeners({ client }, input);\n for await (const page of paginator) {\n listeners.push(...(page?.Listeners || []));\n }\n return listeners;\n },\n paginateDescribeLoadBalancers: async (input: DescribeLoadBalancersCommandInput): Promise<LoadBalancer[]> => {\n const loadBalancers = Array<LoadBalancer>();\n const paginator = paginateDescribeLoadBalancers({ client }, input);\n for await (const page of paginator) {\n loadBalancers.push(...(page?.LoadBalancers || []));\n }\n return loadBalancers;\n },\n };\n }\n\n public iam(): IIAMClient {\n const client = new IAMClient(this.config);\n return {\n createPolicy: (input: CreatePolicyCommandInput): Promise<CreatePolicyCommandOutput> =>\n client.send(new CreatePolicyCommand(input)),\n getPolicy: (input: GetPolicyCommandInput): Promise<GetPolicyCommandOutput> =>\n client.send(new GetPolicyCommand(input)),\n getRole: (input: GetRoleCommandInput): Promise<GetRoleCommandOutput> => client.send(new GetRoleCommand(input)),\n };\n }\n\n public kms(): IKMSClient {\n const client = new KMSClient(this.config);\n return {\n describeKey: (input: DescribeKeyCommandInput): Promise<DescribeKeyCommandOutput> =>\n client.send(new DescribeKeyCommand(input)),\n listAliases: (input: ListAliasesCommandInput): Promise<ListAliasesCommandOutput> =>\n client.send(new ListAliasesCommand(input)),\n };\n }\n\n public lambda(): ILambdaClient {\n const client = new LambdaClient(this.config);\n return {\n invokeCommand: (input: InvokeCommandInput): Promise<InvokeCommandOutput> => client.send(new InvokeCommand(input)),\n publishVersion: (input: PublishVersionCommandInput): Promise<PublishVersionCommandOutput> =>\n client.send(new PublishVersionCommand(input)),\n updateAlias: (input: UpdateAliasCommandInput): Promise<UpdateAliasCommandOutput> =>\n client.send(new UpdateAliasCommand(input)),\n updateFunctionCode: (input: UpdateFunctionCodeCommandInput): Promise<UpdateFunctionCodeCommandOutput> =>\n client.send(new UpdateFunctionCodeCommand(input)),\n updateFunctionConfiguration: (\n input: UpdateFunctionConfigurationCommandInput,\n ): Promise<UpdateFunctionConfigurationCommandOutput> =>\n client.send(new UpdateFunctionConfigurationCommand(input)),\n // Waiters\n waitUntilFunctionUpdated: (\n delaySeconds: number,\n input: UpdateFunctionConfigurationCommandInput,\n ): Promise<WaiterResult> => {\n return waitUntilFunctionUpdatedV2(\n {\n client,\n maxDelay: delaySeconds,\n minDelay: delaySeconds,\n maxWaitTime: delaySeconds * 60,\n },\n input,\n );\n },\n };\n }\n\n public route53(): IRoute53Client {\n const client = new Route53Client(this.config);\n return {\n getHostedZone: (input: GetHostedZoneCommandInput): Promise<GetHostedZoneCommandOutput> =>\n client.send(new GetHostedZoneCommand(input)),\n listHostedZones: (input: ListHostedZonesCommandInput): Promise<ListHostedZonesCommandOutput> =>\n client.send(new ListHostedZonesCommand(input)),\n listHostedZonesByName: (input: ListHostedZonesByNameCommandInput): Promise<ListHostedZonesByNameCommandOutput> =>\n client.send(new ListHostedZonesByNameCommand(input)),\n };\n }\n\n public s3(): IS3Client {\n const client = new S3Client(this.config);\n return {\n deleteObjects: (input: DeleteObjectsCommandInput): Promise<DeleteObjectsCommandOutput> =>\n client.send(new DeleteObjectsCommand({\n ...input,\n ChecksumAlgorithm: 'SHA256',\n })),\n deleteObjectTagging: (input: DeleteObjectTaggingCommandInput): Promise<DeleteObjectTaggingCommandOutput> =>\n client.send(new DeleteObjectTaggingCommand(input)),\n getBucketEncryption: (input: GetBucketEncryptionCommandInput): Promise<GetBucketEncryptionCommandOutput> =>\n client.send(new GetBucketEncryptionCommand(input)),\n getBucketLocation: (input: GetBucketLocationCommandInput): Promise<GetBucketLocationCommandOutput> =>\n client.send(new GetBucketLocationCommand(input)),\n getObject: (input: GetObjectCommandInput): Promise<GetObjectCommandOutput> =>\n client.send(new GetObjectCommand(input)),\n getObjectTagging: (input: GetObjectTaggingCommandInput): Promise<GetObjectTaggingCommandOutput> =>\n client.send(new GetObjectTaggingCommand(input)),\n listObjectsV2: (input: ListObjectsV2CommandInput): Promise<ListObjectsV2CommandOutput> =>\n client.send(new ListObjectsV2Command(input)),\n putObjectTagging: (input: PutObjectTaggingCommandInput): Promise<PutObjectTaggingCommandOutput> =>\n client.send(new PutObjectTaggingCommand({\n ...input,\n ChecksumAlgorithm: 'SHA256',\n })),\n upload: (input: PutObjectCommandInput): Promise<CompleteMultipartUploadCommandOutput> => {\n try {\n const upload = new Upload({\n client,\n params: { ...input, ChecksumAlgorithm: 'SHA256' },\n });\n\n return upload.done();\n } catch (e: any) {\n throw new AuthenticationError(`Upload failed: ${formatErrorMessage(e)}`);\n }\n },\n };\n }\n\n public secretsManager(): ISecretsManagerClient {\n const client = new SecretsManagerClient(this.config);\n return {\n getSecretValue: (input: GetSecretValueCommandInput): Promise<GetSecretValueCommandOutput> =>\n client.send(new GetSecretValueCommand(input)),\n };\n }\n\n public ssm(): ISSMClient {\n const client = new SSMClient(this.config);\n return {\n getParameter: (input: GetParameterCommandInput): Promise<GetParameterCommandOutput> =>\n client.send(new GetParameterCommand(input)),\n };\n }\n\n public stepFunctions(): IStepFunctionsClient {\n const client = new SFNClient(this.config);\n return {\n updateStateMachine: (input: UpdateStateMachineCommandInput): Promise<UpdateStateMachineCommandOutput> =>\n client.send(new UpdateStateMachineCommand(input)),\n };\n }\n\n /**\n * The AWS SDK v3 requires a client config and a command in order to get an endpoint for\n * any given service.\n */\n public async getUrlSuffix(region: string): Promise<string> {\n const cfn = new CloudFormationClient({ region });\n const endpoint = await getEndpointFromInstructions({}, DescribeStackResourcesCommand, { ...cfn.config });\n return endpoint.url.hostname.split(`${region}.`).pop()!;\n }\n\n public async currentAccount(): Promise<Account> {\n return cachedAsync(this, CURRENT_ACCOUNT_KEY, async () => {\n const creds = await this.credProvider();\n return this.accountCache.fetch(creds.accessKeyId, async () => {\n // if we don't have one, resolve from STS and store in cache.\n await this.debug('Looking up default account ID from STS');\n const client = new STSClient({\n ...this.config,\n retryStrategy: this.stsRetryStrategy,\n });\n const command = new GetCallerIdentityCommand({});\n const result = await client.send(command);\n const accountId = result.Account;\n const partition = result.Arn!.split(':')[1];\n if (!accountId) {\n throw new AuthenticationError(\"STS didn't return an account ID\");\n }\n await this.debug(`Default account ID: ${accountId}`);\n\n // Save another STS call later if this one already succeeded\n this._credentialsValidated = true;\n return { accountId, partition };\n });\n });\n }\n\n /**\n * Make sure the the current credentials are not expired\n */\n public async validateCredentials() {\n if (this._credentialsValidated) {\n return;\n }\n\n const client = new STSClient({ ...this.config, retryStrategy: this.stsRetryStrategy });\n await client.send(new GetCallerIdentityCommand({}));\n this._credentialsValidated = true;\n }\n}\n\nconst CURRENT_ACCOUNT_KEY = Symbol('current_account_key');\n", "import * as path from 'path';\nimport * as fs from 'fs-extra';\nimport type { Account } from './sdk-provider';\nimport { cdkCacheDir } from '../../util';\n\n/**\n * Disk cache which maps access key IDs to account IDs.\n * Usage:\n * cache.get(accessKey) => accountId | undefined\n * cache.put(accessKey, accountId)\n */\nexport class AccountAccessKeyCache {\n /**\n * Max number of entries in the cache, after which the cache will be reset.\n */\n public static readonly MAX_ENTRIES = 1000;\n\n /**\n * The default path used for the accounts access key cache\n */\n public static get DEFAULT_PATH(): string {\n // needs to be a getter because cdkCacheDir can be set via env variable and might change\n return path.join(cdkCacheDir(), 'accounts_partitions.json');\n }\n\n private readonly cacheFile: string;\n\n private readonly debug: (msg: string) => Promise<void>;\n\n /**\n * @param filePath Path to the cache file\n */\n constructor(filePath: string = AccountAccessKeyCache.DEFAULT_PATH, debugFn: (msg: string) => Promise<void>) {\n this.cacheFile = filePath;\n this.debug = debugFn;\n }\n\n /**\n * Tries to fetch the account ID from cache. If it's not in the cache, invokes\n * the resolver function which should retrieve the account ID and return it.\n * Then, it will be stored into disk cache returned.\n *\n * Example:\n *\n * const accountId = cache.fetch(accessKey, async () => {\n * return await fetchAccountIdFromSomewhere(accessKey);\n * });\n */\n public async fetch<A extends Account>(accessKeyId: string, resolver: () => Promise<A>) {\n // try to get account ID based on this access key ID from disk.\n const cached = await this.get(accessKeyId);\n if (cached) {\n await this.debug(`Retrieved account ID ${cached.accountId} from disk cache`);\n return cached;\n }\n\n // if it's not in the cache, resolve and put in cache.\n const account = await resolver();\n if (account) {\n await this.put(accessKeyId, account);\n }\n\n return account;\n }\n\n /** Get the account ID from an access key or undefined if not in cache */\n public async get(accessKeyId: string): Promise<Account | undefined> {\n const map = await this.loadMap();\n return map[accessKeyId];\n }\n\n /** Put a mapping between access key and account ID */\n public async put(accessKeyId: string, account: Account) {\n let map = await this.loadMap();\n\n // nuke cache if it's too big.\n if (Object.keys(map).length >= AccountAccessKeyCache.MAX_ENTRIES) {\n map = {};\n }\n\n map[accessKeyId] = account;\n await this.saveMap(map);\n }\n\n private async loadMap(): Promise<{ [accessKeyId: string]: Account }> {\n try {\n return await fs.readJson(this.cacheFile);\n } catch (e: any) {\n // File doesn't exist or is not readable. This is a cache,\n // pretend we successfully loaded an empty map.\n if (e.code === 'ENOENT' || e.code === 'EACCES') {\n return {};\n }\n // File is not JSON, could be corrupted because of concurrent writes.\n // Again, an empty cache is fine.\n if (e instanceof SyntaxError) {\n return {};\n }\n throw e;\n }\n }\n\n private async saveMap(map: { [accessKeyId: string]: Account }) {\n try {\n await fs.ensureFile(this.cacheFile);\n await fs.writeJson(this.cacheFile, map, { spaces: 2 });\n } catch (e: any) {\n // File doesn't exist or file/dir isn't writable. This is a cache,\n // if we can't write it then too bad.\n if (e.code === 'ENOENT' || e.code === 'EACCES' || e.code === 'EROFS') {\n return;\n }\n throw e;\n }\n }\n}\n", "/**\n * Cache the result of a function on an object\n *\n * We could have used @decorators to make this nicer but we don't use them anywhere yet,\n * so let's keep it simple and readable.\n */\nexport function cached<A extends object, B>(obj: A, sym: symbol, fn: () => B): B {\n if (!(sym in obj)) {\n (obj as any)[sym] = fn();\n }\n return (obj as any)[sym];\n}\n\n/**\n * Like 'cached', but async\n */\nexport async function cachedAsync<A extends object, B>(obj: A, sym: symbol, fn: () => Promise<B>): Promise<B> {\n if (!(sym in obj)) {\n (obj as any)[sym] = await fn();\n }\n return (obj as any)[sym];\n}\n", "import type { Logger } from '@smithy/types';\n\nlet ENABLED = false;\nlet INDENT = 0;\n\nexport function setSdkTracing(enabled: boolean) {\n ENABLED = enabled;\n}\n\n/**\n * Method decorator to trace a single static or member method, any time it's called\n */\nexport function callTrace(fn: string, className?: string, logger?: Logger) {\n if (!ENABLED || !logger) {\n return;\n }\n\n logger.info(`[trace] ${' '.repeat(INDENT)}${className || '(anonymous)'}#${fn}()`);\n}\n\n/**\n * Method decorator to trace a single member method any time it's called\n */\nfunction traceCall(receiver: object, _propertyKey: string, descriptor: PropertyDescriptor, parentClassName?: string) {\n const fn = descriptor.value;\n const className = typeof receiver === 'function' ? receiver.name : parentClassName;\n\n descriptor.value = function (...args: any[]) {\n const logger = (this as any).logger;\n if (!ENABLED || typeof logger?.info !== 'function') {\n return fn.apply(this, args);\n }\n\n logger.info.apply(logger, [`[trace] ${' '.repeat(INDENT)}${className || this.constructor.name || '(anonymous)'}#${fn.name}()`]);\n INDENT += 2;\n\n const ret = fn.apply(this, args);\n if (ret instanceof Promise) {\n return ret.finally(() => {\n INDENT -= 2;\n });\n } else {\n INDENT -= 2;\n return ret;\n }\n };\n return descriptor;\n}\n\n/**\n * Class decorator, enable tracing for all member methods on this class\n * @deprecated this doesn't work well with localized logging instances, don't use\n */\nexport function traceMemberMethods(constructor: Function) {\n // Instance members\n for (const [name, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(constructor.prototype))) {\n if (typeof descriptor.value !== 'function') {\n continue;\n }\n const newDescriptor = traceCall(constructor.prototype, name, descriptor, constructor.name) ?? descriptor;\n Object.defineProperty(constructor.prototype, name, newDescriptor);\n }\n}\n", "import * as path from 'path';\nimport { readIfPossible } from './util';\nimport { bundledPackageRootDir } from '../../util';\n/**\n * Find the package.json from the main toolkit.\n *\n * If we can't read it for some reason, try to do something reasonable anyway.\n * Fall back to argv[1], or a standard string if that is undefined for some reason.\n */\nexport function defaultCliUserAgent() {\n const root = bundledPackageRootDir(__dirname, false);\n const pkg = JSON.parse((root ? readIfPossible(path.join(root, 'package.json')) : undefined) ?? '{}');\n const name = pkg.name ?? path.basename(process.argv[1] ?? 'cdk-cli');\n const version = pkg.version ?? '<unknown>';\n return `${name}/${version}`;\n}\n", "import * as fs from 'fs-extra';\n\n/**\n * Read a file if it exists, or return undefined\n *\n * Not async because it is used in the constructor\n */\nexport function readIfPossible(filename: string): string | undefined {\n try {\n if (!fs.pathExistsSync(filename)) {\n return undefined;\n }\n return fs.readFileSync(filename, { encoding: 'utf-8' });\n } catch (e: any) {\n return undefined;\n }\n}\n", "import * as os from 'os';\nimport type { ContextLookupRoleOptions } from '@aws-cdk/cloud-assembly-schema';\nimport type { Environment } from '@aws-cdk/cx-api';\nimport { EnvironmentUtils, UNKNOWN_ACCOUNT, UNKNOWN_REGION } from '@aws-cdk/cx-api';\nimport type { AssumeRoleCommandInput } from '@aws-sdk/client-sts';\nimport { fromTemporaryCredentials } from '@aws-sdk/credential-providers';\nimport type { NodeHttpHandlerOptions } from '@smithy/node-http-handler';\nimport type { AwsCredentialIdentityProvider, Logger } from '@smithy/types';\nimport { AwsCliCompatible } from './awscli-compatible';\nimport { cached } from './cached';\nimport { CredentialPlugins } from './credential-plugins';\nimport { makeCachingProvider } from './provider-caching';\nimport { SDK } from './sdk';\nimport { callTrace, traceMemberMethods } from './tracing';\nimport { formatErrorMessage } from '../../util';\nimport { IO, type IoHelper } from '../io/private';\nimport { Mode, PluginHost } from '../plugin';\nimport { AuthenticationError } from '../toolkit-error';\n\nexport type AssumeRoleAdditionalOptions = Partial<Omit<AssumeRoleCommandInput, 'ExternalId' | 'RoleArn'>>;\n\n/**\n * Options for the default SDK provider\n */\nexport interface SdkProviderOptions {\n /**\n * IoHelper for messaging\n */\n readonly ioHelper: IoHelper;\n\n /**\n * Profile to read from ~/.aws\n *\n * @default - No profile\n */\n readonly profile?: string;\n\n /**\n * HTTP options for SDK\n */\n readonly httpOptions?: SdkHttpOptions;\n\n /**\n * The logger for sdk calls.\n */\n readonly logger?: Logger;\n}\n\n/**\n * Options for individual SDKs\n */\nexport interface SdkHttpOptions {\n /**\n * Proxy address to use\n *\n * @default No proxy\n */\n readonly proxyAddress?: string;\n\n /**\n * A path to a certificate bundle that contains a cert to be trusted.\n *\n * @default No certificate bundle\n */\n readonly caBundlePath?: string;\n}\n\nconst CACHED_ACCOUNT = Symbol('cached_account');\n\n/**\n * SDK configuration for a given environment\n * 'forEnvironment' will attempt to assume a role and if it\n * is not successful, then it will either:\n * 1. Check to see if the default credentials (local credentials the CLI was executed with)\n * are for the given environment. If they are then return those.\n * 2. If the default credentials are not for the given environment then\n * throw an error\n *\n * 'didAssumeRole' allows callers to whether they are receiving the assume role\n * credentials or the default credentials.\n */\nexport interface SdkForEnvironment {\n /**\n * The SDK for the given environment\n */\n readonly sdk: SDK;\n\n /**\n * Whether or not the assume role was successful.\n * If the assume role was not successful (false)\n * then that means that the 'sdk' returned contains\n * the default credentials (not the assume role credentials)\n */\n readonly didAssumeRole: boolean;\n}\n\n/**\n * Creates instances of the AWS SDK appropriate for a given account/region.\n *\n * Behavior is as follows:\n *\n * - First, a set of \"base\" credentials are established\n * - If a target environment is given and the default (\"current\") SDK credentials are for\n * that account, return those; otherwise\n * - If a target environment is given, scan all credential provider plugins\n * for credentials, and return those if found; otherwise\n * - Return default (\"current\") SDK credentials, noting that they might be wrong.\n *\n * - Second, a role may optionally need to be assumed. Use the base credentials\n * established in the previous process to assume that role.\n * - If assuming the role fails and the base credentials are for the correct\n * account, return those. This is a fallback for people who are trying to interact\n * with a Default Synthesized stack and already have right credentials setup.\n *\n * Typical cases we see in the wild:\n * - Credential plugin setup that, although not recommended, works for them\n * - Seeded terminal with `ReadOnly` credentials in order to do `cdk diff`--the `ReadOnly`\n * role doesn't have `sts:AssumeRole` and will fail for no real good reason.\n */\n@traceMemberMethods\nexport class SdkProvider {\n /**\n * Create a new SdkProvider which gets its defaults in a way that behaves like the AWS CLI does\n *\n * The AWS SDK for JS behaves slightly differently from the AWS CLI in a number of ways; see the\n * class `AwsCliCompatible` for the details.\n */\n public static async withAwsCliCompatibleDefaults(options: SdkProviderOptions) {\n const builder = new AwsCliCompatible(options.ioHelper);\n callTrace(SdkProvider.withAwsCliCompatibleDefaults.name, SdkProvider.constructor.name, options.logger);\n const credentialProvider = await builder.credentialChainBuilder({\n profile: options.profile,\n httpOptions: options.httpOptions,\n logger: options.logger,\n });\n\n const region = await builder.region(options.profile);\n const requestHandler = await builder.requestHandlerBuilder(options.httpOptions);\n return new SdkProvider(credentialProvider, region, requestHandler, options.ioHelper, options.logger);\n }\n\n private readonly plugins;\n\n public constructor(\n private readonly defaultCredentialProvider: AwsCredentialIdentityProvider,\n /**\n * Default region\n */\n public readonly defaultRegion: string,\n private readonly requestHandler: NodeHttpHandlerOptions = {},\n private readonly ioHelper: IoHelper,\n private readonly logger?: Logger,\n ) {\n this.plugins = new CredentialPlugins(PluginHost.instance, ioHelper);\n }\n\n /**\n * Return an SDK which can do operations in the given environment\n *\n * The `environment` parameter is resolved first (see `resolveEnvironment()`).\n */\n public async forEnvironment(\n environment: Environment,\n mode: Mode,\n options?: CredentialsOptions,\n quiet = false,\n ): Promise<SdkForEnvironment> {\n const env = await this.resolveEnvironment(environment);\n\n const baseCreds = await this.obtainBaseCredentials(env.account, mode);\n\n // At this point, we need at least SOME credentials\n if (baseCreds.source === 'none') {\n throw new AuthenticationError(fmtObtainCredentialsError(env.account, baseCreds));\n }\n\n // Simple case is if we don't need to \"assumeRole\" here. If so, we must now have credentials for the right\n // account.\n if (options?.assumeRoleArn === undefined) {\n if (baseCreds.source === 'incorrectDefault') {\n throw new AuthenticationError(fmtObtainCredentialsError(env.account, baseCreds));\n }\n\n // Our current credentials must be valid and not expired. Confirm that before we get into doing\n // actual CloudFormation calls, which might take a long time to hang.\n const sdk = new SDK(baseCreds.credentials, env.region, this.requestHandler, this.ioHelper, this.logger);\n await sdk.validateCredentials();\n return { sdk, didAssumeRole: false };\n }\n\n try {\n // We will proceed to AssumeRole using whatever we've been given.\n const sdk = await this.withAssumedRole(\n baseCreds,\n options.assumeRoleArn,\n options.assumeRoleExternalId,\n options.assumeRoleAdditionalOptions,\n env.region,\n );\n\n return { sdk, didAssumeRole: true };\n } catch (err: any) {\n if (err.name === 'ExpiredToken') {\n throw err;\n }\n\n // AssumeRole failed. Proceed and warn *if and only if* the baseCredentials were already for the right account\n // or returned from a plugin. This is to cover some current setups for people using plugins or preferring to\n // feed the CLI credentials which are sufficient by themselves. Prefer to assume the correct role if we can,\n // but if we can't then let's just try with available credentials anyway.\n if (baseCreds.source === 'correctDefault' || baseCreds.source === 'plugin') {\n await this.ioHelper.notify(IO.DEFAULT_SDK_DEBUG.msg(err.message));\n\n const maker = quiet ? IO.DEFAULT_SDK_DEBUG : IO.DEFAULT_SDK_WARN;\n await this.ioHelper.notify(maker.msg(\n `${fmtObtainedCredentials(baseCreds)} could not be used to assume '${options.assumeRoleArn}', but are for the right account. Proceeding anyway.`,\n ));\n return {\n sdk: new SDK(baseCreds.credentials, env.region, this.requestHandler, this.ioHelper, this.logger),\n didAssumeRole: false,\n };\n }\n\n throw err;\n }\n }\n\n /**\n * Return the partition that base credentials are for\n *\n * Returns `undefined` if there are no base credentials.\n */\n public async baseCredentialsPartition(environment: Environment, mode: Mode): Promise<string | undefined> {\n const env = await this.resolveEnvironment(environment);\n const baseCreds = await this.obtainBaseCredentials(env.account, mode);\n if (baseCreds.source === 'none') {\n return undefined;\n }\n return (await new SDK(baseCreds.credentials, env.region, this.requestHandler, this.ioHelper, this.logger).currentAccount()).partition;\n }\n\n /**\n * Resolve the environment for a stack\n *\n * Replaces the magic values `UNKNOWN_REGION` and `UNKNOWN_ACCOUNT`\n * with the defaults for the current SDK configuration (`~/.aws/config` or\n * otherwise).\n *\n * It is an error if `UNKNOWN_ACCOUNT` is used but the user hasn't configured\n * any SDK credentials.\n */\n public async resolveEnvironment(env: Environment): Promise<Environment> {\n const region = env.region !== UNKNOWN_REGION ? env.region : this.defaultRegion;\n const account = env.account !== UNKNOWN_ACCOUNT ? env.account : (await this.defaultAccount())?.accountId;\n\n if (!account) {\n throw new AuthenticationError(\n 'Unable to resolve AWS account to use. It must be either configured when you define your CDK Stack, or through the environment',\n );\n }\n\n return {\n region,\n account,\n name: EnvironmentUtils.format(account, region),\n };\n }\n\n /**\n * The account we'd auth into if we used default credentials.\n *\n * Default credentials are the set of ambiently configured credentials using\n * one of the environment variables, or ~/.aws/credentials, or the *one*\n * profile that was passed into the CLI.\n *\n * Might return undefined if there are no default/ambient credentials\n * available (in which case the user should better hope they have\n * credential plugins configured).\n *\n * Uses a cache to avoid STS calls if we don't need 'em.\n */\n public async defaultAccount(): Promise<Account | undefined> {\n return cached(this, CACHED_ACCOUNT, async () => {\n try {\n return await new SDK(this.defaultCredentialProvider, this.defaultRegion, this.requestHandler, this.ioHelper, this.logger).currentAccount();\n } catch (e: any) {\n // Treat 'ExpiredToken' specially. This is a common situation that people may find themselves in, and\n // they are complaining about if we fail 'cdk synth' on them. We loudly complain in order to show that\n // the current situation is probably undesirable, but we don't fail.\n if (e.name === 'ExpiredToken') {\n await this.ioHelper.notify(IO.DEFAULT_SDK_WARN.msg(\n 'There are expired AWS credentials in your environment. The CDK app will synth without current account information.',\n ));\n return undefined;\n }\n\n await this.ioHelper.notify(IO.DEFAULT_SDK_DEBUG.msg(`Unable to determine the default AWS account (${e.name}): ${formatErrorMessage(e)}`));\n return undefined;\n }\n });\n }\n\n /**\n * Get credentials for the given account ID in the given mode\n *\n * 1. Use the default credentials if the destination account matches the\n * current credentials' account.\n * 2. Otherwise try all credential plugins.\n * 3. Fail if neither of these yield any credentials.\n * 4. Return a failure if any of them returned credentials\n */\n private async obtainBaseCredentials(accountId: string, mode: Mode): Promise<ObtainBaseCredentialsResult> {\n // First try 'current' credentials\n const defaultAccountId = (await this.defaultAccount())?.accountId;\n if (defaultAccountId === accountId) {\n return {\n source: 'correctDefault',\n credentials: await this.defaultCredentialProvider,\n };\n }\n\n // Then try the plugins\n const pluginCreds = await this.plugins.fetchCredentialsFor(accountId, mode);\n if (pluginCreds) {\n return { source: 'plugin', ...pluginCreds };\n }\n\n // Fall back to default credentials with a note that they're not the right ones yet\n if (defaultAccountId !== undefined) {\n return {\n source: 'incorrectDefault',\n accountId: defaultAccountId,\n credentials: await this.defaultCredentialProvider,\n unusedPlugins: this.plugins.availablePluginNames,\n };\n }\n\n // Apparently we didn't find any at all\n return {\n source: 'none',\n unusedPlugins: this.plugins.availablePluginNames,\n };\n }\n\n /**\n * Return an SDK which uses assumed role credentials\n *\n * The base credentials used to retrieve the assumed role credentials will be the\n * same credentials returned by obtainCredentials if an environment and mode is passed,\n * otherwise it will be the current credentials.\n */\n private async withAssumedRole(\n mainCredentials: Exclude<ObtainBaseCredentialsResult, { source: 'none' }>,\n roleArn: string,\n externalId?: string,\n additionalOptions?: AssumeRoleAdditionalOptions,\n region?: string,\n ): Promise<SDK> {\n await this.ioHelper.notify(IO.DEFAULT_SDK_DEBUG.msg(`Assuming role '${roleArn}'.`));\n\n region = region ?? this.defaultRegion;\n\n const sourceDescription = fmtObtainedCredentials(mainCredentials);\n\n try {\n const credentials = await makeCachingProvider(fromTemporaryCredentials({\n masterCredentials: mainCredentials.credentials,\n params: {\n RoleArn: roleArn,\n ExternalId: externalId,\n RoleSessionName: `aws-cdk-${safeUsername()}`,\n ...additionalOptions,\n TransitiveTagKeys: additionalOptions?.Tags ? additionalOptions.Tags.map((t) => t.Key!) : undefined,\n },\n clientConfig: {\n region,\n requestHandler: this.requestHandler,\n customUserAgent: 'aws-cdk',\n logger: this.logger,\n },\n logger: this.logger,\n }));\n\n // Call the provider at least once here, to catch an error if it occurs\n await credentials();\n\n return new SDK(credentials, region, this.requestHandler, this.ioHelper, this.logger);\n } catch (err: any) {\n if (err.name === 'ExpiredToken') {\n throw err;\n }\n\n await this.ioHelper.notify(IO.DEFAULT_SDK_DEBUG.msg(`Assuming role failed: ${err.message}`));\n throw new AuthenticationError(\n [\n 'Could not assume role in target account',\n ...(sourceDescription ? [`using ${sourceDescription}`] : []),\n err.message,\n \". Please make sure that this role exists in the account. If it doesn't exist, (re)-bootstrap the environment \" +\n \"with the right '--trust', using the latest version of the CDK CLI.\",\n ].join(' '),\n );\n }\n }\n}\n\n/**\n * An AWS account\n *\n * An AWS account always exists in only one partition. Usually we don't care about\n * the partition, but when we need to form ARNs we do.\n */\nexport interface Account {\n /**\n * The account number\n */\n readonly accountId: string;\n\n /**\n * The partition ('aws' or 'aws-cn' or otherwise)\n */\n readonly partition: string;\n}\n\n/**\n * Return the username with characters invalid for a RoleSessionName removed\n *\n * @see https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html#API_AssumeRole_RequestParameters\n */\nfunction safeUsername() {\n try {\n return os.userInfo().username.replace(/[^\\w+=,.@-]/g, '@');\n } catch {\n return 'noname';\n }\n}\n\n/**\n * Options for obtaining credentials for an environment\n */\nexport interface CredentialsOptions {\n /**\n * The ARN of the role that needs to be assumed, if any\n */\n readonly assumeRoleArn?: string;\n\n /**\n * External ID required to assume the given role.\n */\n readonly assumeRoleExternalId?: string;\n\n /**\n * Session tags required to assume the given role.\n */\n readonly assumeRoleAdditionalOptions?: AssumeRoleAdditionalOptions;\n}\n\n/**\n * Result of obtaining base credentials\n */\ntype ObtainBaseCredentialsResult =\n | { source: 'correctDefault'; credentials: AwsCredentialIdentityProvider }\n | { source: 'plugin'; pluginName: string; credentials: AwsCredentialIdentityProvider }\n | {\n source: 'incorrectDefault';\n credentials: AwsCredentialIdentityProvider;\n accountId: string;\n unusedPlugins: string[];\n }\n | { source: 'none'; unusedPlugins: string[] };\n\n/**\n * Isolating the code that translates calculation errors into human error messages\n *\n * We cover the following cases:\n *\n * - No credentials are available at all\n * - Default credentials are for the wrong account\n */\nfunction fmtObtainCredentialsError(\n targetAccountId: string,\n obtainResult: ObtainBaseCredentialsResult & {\n source: 'none' | 'incorrectDefault';\n },\n): string {\n const msg = [`Need to perform AWS calls for account ${targetAccountId}`];\n switch (obtainResult.source) {\n case 'incorrectDefault':\n msg.push(`but the current credentials are for ${obtainResult.accountId}`);\n break;\n case 'none':\n msg.push('but no credentials have been configured');\n }\n if (obtainResult.unusedPlugins.length > 0) {\n msg.push(`and none of these plugins found any: ${obtainResult.unusedPlugins.join(', ')}`);\n }\n return msg.join(', ');\n}\n\n/**\n * Format a message indicating where we got base credentials for the assume role\n *\n * We cover the following cases:\n *\n * - Default credentials for the right account\n * - Default credentials for the wrong account\n * - Credentials returned from a plugin\n */\nfunction fmtObtainedCredentials(obtainResult: Exclude<ObtainBaseCredentialsResult, { source: 'none' }>): string {\n switch (obtainResult.source) {\n case 'correctDefault':\n return 'current credentials';\n case 'plugin':\n return `credentials returned by plugin '${obtainResult.pluginName}'`;\n case 'incorrectDefault':\n const msg = [];\n msg.push(`current credentials (which are for account ${obtainResult.accountId}`);\n\n if (obtainResult.unusedPlugins.length > 0) {\n msg.push(`, and none of the following plugins provided credentials: ${obtainResult.unusedPlugins.join(', ')}`);\n }\n msg.push(')');\n\n return msg.join('');\n }\n}\n\n/**\n * Instantiate an SDK for context providers. This function ensures that all\n * lookup assume role options are used when context providers perform lookups.\n */\nexport async function initContextProviderSdk(aws: SdkProvider, options: ContextLookupRoleOptions): Promise<SDK> {\n const account = options.account;\n const region = options.region;\n\n const creds: CredentialsOptions = {\n assumeRoleArn: options.lookupRoleArn,\n assumeRoleExternalId: options.lookupRoleExternalId,\n assumeRoleAdditionalOptions: options.assumeRoleAdditionalOptions,\n };\n\n return (await aws.forEnvironment(EnvironmentUtils.make(account, region), Mode.ForReading, creds)).sdk;\n}\n", "import { format } from 'node:util';\nimport { createCredentialChain, fromEnv, fromIni, fromNodeProviderChain } from '@aws-sdk/credential-providers';\nimport { MetadataService } from '@aws-sdk/ec2-metadata-service';\nimport type { NodeHttpHandlerOptions } from '@smithy/node-http-handler';\nimport { loadSharedConfigFiles } from '@smithy/shared-ini-file-loader';\nimport type { AwsCredentialIdentityProvider, Logger } from '@smithy/types';\nimport * as promptly from 'promptly';\nimport { makeCachingProvider } from './provider-caching';\nimport { ProxyAgentProvider } from './proxy-agent';\nimport type { SdkHttpOptions } from './sdk-provider';\nimport { IO, type IoHelper } from '../io/private';\nimport { AuthenticationError } from '../toolkit-error';\n\nconst DEFAULT_CONNECTION_TIMEOUT = 10000;\nconst DEFAULT_TIMEOUT = 300000;\n\n/**\n * Behaviors to match AWS CLI\n *\n * See these links:\n *\n * https://docs.aws.amazon.com/cli/latest/topic/config-vars.html\n * https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-envvars.html\n */\nexport class AwsCliCompatible {\n private readonly ioHelper: IoHelper;\n\n public constructor(ioHelper: IoHelper) {\n this.ioHelper = ioHelper;\n }\n\n /**\n * Build an AWS CLI-compatible credential chain provider\n *\n * The credential chain returned by this function is always caching.\n */\n public async credentialChainBuilder(\n options: CredentialChainOptions = {},\n ): Promise<AwsCredentialIdentityProvider> {\n const clientConfig = {\n requestHandler: await this.requestHandlerBuilder(options.httpOptions),\n customUserAgent: 'aws-cdk',\n logger: options.logger,\n };\n\n // Super hacky solution to https://github.com/aws/aws-cdk/issues/32510, proposed by the SDK team.\n //\n // Summary of the problem: we were reading the region from the config file and passing it to\n // the credential providers. However, in the case of SSO, this makes the credential provider\n // use that region to do the SSO flow, which is incorrect. The region that should be used for\n // that is the one set in the sso_session section of the config file.\n //\n // The idea here: the \"clientConfig\" is for configuring the inner auth client directly,\n // and has the highest priority, whereas \"parentClientConfig\" is the upper data client\n // and has lower priority than the sso_region but still higher priority than STS global region.\n const parentClientConfig = {\n region: await this.region(options.profile),\n };\n /**\n * The previous implementation matched AWS CLI behavior:\n *\n * If a profile is explicitly set using `--profile`,\n * we use that to the exclusion of everything else.\n *\n * Note: this does not apply to AWS_PROFILE,\n * environment credentials still take precedence over AWS_PROFILE\n */\n if (options.profile) {\n return makeCachingProvider(fromIni({\n profile: options.profile,\n ignoreCache: true,\n mfaCodeProvider: this.tokenCodeFn.bind(this),\n clientConfig,\n parentClientConfig,\n logger: options.logger,\n }));\n }\n\n const envProfile = process.env.AWS_PROFILE || process.env.AWS_DEFAULT_PROFILE;\n\n /**\n * Env AWS - EnvironmentCredentials with string AWS\n * Env Amazon - EnvironmentCredentials with string AMAZON\n * Profile Credentials - PatchedSharedIniFileCredentials with implicit profile, credentials file, http options, and token fn\n * SSO with implicit profile only\n * SharedIniFileCredentials with implicit profile and preferStaticCredentials true (profile with source_profile)\n * Shared Credential file that points to Environment Credentials with AWS prefix\n * Shared Credential file that points to EC2 Metadata\n * Shared Credential file that points to ECS Credentials\n * SSO Credentials - SsoCredentials with implicit profile and http options\n * ProcessCredentials with implicit profile\n * ECS Credentials - ECSCredentials with no input OR Web Identity - TokenFileWebIdentityCredentials with no input OR EC2 Metadata - EC2MetadataCredentials with no input\n *\n * These translate to:\n * fromEnv()\n * fromSSO()/fromIni()\n * fromProcess()\n * fromContainerMetadata()\n * fromTokenFile()\n * fromInstanceMetadata()\n *\n * The NodeProviderChain is already cached.\n */\n const nodeProviderChain = fromNodeProviderChain({\n profile: envProfile,\n clientConfig,\n parentClientConfig,\n logger: options.logger,\n mfaCodeProvider: this.tokenCodeFn.bind(this),\n ignoreCache: true,\n });\n\n return shouldPrioritizeEnv()\n ? createCredentialChain(fromEnv(), nodeProviderChain).expireAfter(60 * 60_000)\n : nodeProviderChain;\n }\n\n public async requestHandlerBuilder(options: SdkHttpOptions = {}): Promise<NodeHttpHandlerOptions> {\n const agent = await new ProxyAgentProvider(this.ioHelper).create(options);\n\n return {\n connectionTimeout: DEFAULT_CONNECTION_TIMEOUT,\n requestTimeout: DEFAULT_TIMEOUT,\n httpsAgent: agent,\n httpAgent: agent,\n };\n }\n\n /**\n * Attempts to get the region from a number of sources and falls back to us-east-1 if no region can be found,\n * as is done in the AWS CLI.\n *\n * The order of priority is the following:\n *\n * 1. Environment variables specifying region, with both an AWS prefix and AMAZON prefix\n * to maintain backwards compatibility, and without `DEFAULT` in the name because\n * Lambda and CodeBuild set the $AWS_REGION variable.\n * 2. Regions listed in the Shared Ini Files - First checking for the profile provided\n * and then checking for the default profile.\n * 3. IMDS instance identity region from the Metadata Service.\n * 4. us-east-1\n */\n public async region(maybeProfile?: string): Promise<string> {\n const defaultRegion = 'us-east-1';\n const profile = maybeProfile || process.env.AWS_PROFILE || process.env.AWS_DEFAULT_PROFILE || 'default';\n\n const region =\n process.env.AWS_REGION ||\n process.env.AMAZON_REGION ||\n process.env.AWS_DEFAULT_REGION ||\n process.env.AMAZON_DEFAULT_REGION ||\n (await this.getRegionFromIni(profile)) ||\n (await this.regionFromMetadataService());\n\n if (!region) {\n const usedProfile = !profile ? '' : ` (profile: \"${profile}\")`;\n await this.ioHelper.notify(IO.DEFAULT_SDK_DEBUG.msg(\n `Unable to determine AWS region from environment or AWS configuration${usedProfile}, defaulting to '${defaultRegion}'`,\n ));\n return defaultRegion;\n }\n\n return region;\n }\n\n /**\n * The MetadataService class will attempt to fetch the instance identity document from\n * IMDSv2 first, and then will attempt v1 as a fallback.\n *\n * If this fails, we will use us-east-1 as the region so no error should be thrown.\n * @returns The region for the instance identity\n */\n private async regionFromMetadataService() {\n await this.ioHelper.notify(IO.DEFAULT_SDK_DEBUG.msg('Looking up AWS region in the EC2 Instance Metadata Service (IMDS).'));\n try {\n const metadataService = new MetadataService({\n httpOptions: {\n timeout: 1000,\n },\n });\n\n await metadataService.fetchMetadataToken();\n const document = await metadataService.request('/latest/dynamic/instance-identity/document', {});\n return JSON.parse(document).region;\n } catch (e) {\n await this.ioHelper.notify(IO.DEFAULT_SDK_DEBUG.msg(`Unable to retrieve AWS region from IMDS: ${e}`));\n }\n }\n\n /**\n * Looks up the region of the provided profile. If no region is present,\n * it will attempt to lookup the default region.\n * @param profile The profile to use to lookup the region\n * @returns The region for the profile or default profile, if present. Otherwise returns undefined.\n */\n private async getRegionFromIni(profile: string): Promise<string | undefined> {\n const sharedFiles = await loadSharedConfigFiles({ ignoreCache: true });\n\n // Priority:\n //\n // credentials come before config because aws-cli v1 behaves like that.\n //\n // 1. profile-region-in-credentials\n // 2. profile-region-in-config\n // 3. default-region-in-credentials\n // 4. default-region-in-config\n\n return this.getRegionFromIniFile(profile, sharedFiles.credentialsFile)\n ?? this.getRegionFromIniFile(profile, sharedFiles.configFile)\n ?? this.getRegionFromIniFile('default', sharedFiles.credentialsFile)\n ?? this.getRegionFromIniFile('default', sharedFiles.configFile);\n }\n\n private getRegionFromIniFile(profile: string, data?: any) {\n return data?.[profile]?.region;\n }\n\n /**\n * Ask user for MFA token for given serial\n *\n * Result is send to callback function for SDK to authorize the request\n */\n private async tokenCodeFn(serialArn: string): Promise<string> {\n const debugFn = (msg: string, ...args: any[]) => this.ioHelper.notify(IO.DEFAULT_SDK_DEBUG.msg(format(msg, ...args)));\n await debugFn('Require MFA token for serial ARN', serialArn);\n try {\n const token: string = await promptly.prompt(`MFA token for ${serialArn}: `, {\n trim: true,\n default: '',\n });\n await debugFn('Successfully got MFA token from user');\n return token;\n } catch (err: any) {\n await debugFn('Failed to get MFA token', err);\n const e = new AuthenticationError(`Error fetching MFA token: ${err.message ?? err}`);\n e.name = 'SharedIniFileCredentialsProviderFailure';\n throw e;\n }\n }\n}\n\n/**\n * We used to support both AWS and AMAZON prefixes for these environment variables.\n *\n * Adding this for backward compatibility.\n */\nfunction shouldPrioritizeEnv() {\n const id = process.env.AWS_ACCESS_KEY_ID || process.env.AMAZON_ACCESS_KEY_ID;\n const key = process.env.AWS_SECRET_ACCESS_KEY || process.env.AMAZON_SECRET_ACCESS_KEY;\n\n if (!!id && !!key) {\n process.env.AWS_ACCESS_KEY_ID = id;\n process.env.AWS_SECRET_ACCESS_KEY = key;\n\n const sessionToken = process.env.AWS_SESSION_TOKEN ?? process.env.AMAZON_SESSION_TOKEN;\n if (sessionToken) {\n process.env.AWS_SESSION_TOKEN = sessionToken;\n }\n\n return true;\n }\n\n return false;\n}\n\nexport interface CredentialChainOptions {\n readonly profile?: string;\n readonly httpOptions?: SdkHttpOptions;\n readonly logger?: Logger;\n}\n", "import { memoize } from '@smithy/property-provider';\nimport type { AwsCredentialIdentity, AwsCredentialIdentityProvider } from '@smithy/types';\n\n/**\n * Wrap a credential provider in a cache\n *\n * Some credential providers in the SDKv3 are cached (the default Node\n * chain, specifically) but most others are not.\n *\n * Since we want to avoid duplicate calls to `AssumeRole`, or duplicate\n * MFA prompts or what have you, we are going to liberally wrap providers\n * in caches which will return the cached value until it expires.\n */\nexport function makeCachingProvider(provider: AwsCredentialIdentityProvider): AwsCredentialIdentityProvider {\n return memoize(\n provider,\n credentialsAboutToExpire,\n (token) => !!token.expiration,\n );\n}\n\nexport function credentialsAboutToExpire(token: AwsCredentialIdentity) {\n const expiryMarginSecs = 5;\n // token.expiration is sometimes null\n return !!token.expiration && token.expiration.getTime() - Date.now() < expiryMarginSecs * 1000;\n}\n", "import { inspect } from 'util';\nimport type { CredentialProviderSource, ForReading, ForWriting, PluginProviderResult, SDKv2CompatibleCredentials, SDKv3CompatibleCredentialProvider, SDKv3CompatibleCredentials } from '@aws-cdk/cli-plugin-contract';\nimport type { AwsCredentialIdentity, AwsCredentialIdentityProvider } from '@smithy/types';\nimport { credentialsAboutToExpire, makeCachingProvider } from './provider-caching';\nimport { formatErrorMessage } from '../../util';\nimport { IO, type IoHelper } from '../io/private';\nimport type { Mode } from '../plugin/mode';\nimport type { PluginHost } from '../plugin/plugin';\nimport { AuthenticationError } from '../toolkit-error';\n\n/**\n * Cache for credential providers.\n *\n * Given an account and an operating mode (read or write) will return an\n * appropriate credential provider for credentials for the given account. The\n * credential provider will be cached so that multiple AWS clients for the same\n * environment will not make multiple network calls to obtain credentials.\n *\n * Will use default credentials if they are for the right account; otherwise,\n * all loaded credential provider plugins will be tried to obtain credentials\n * for the given account.\n */\nexport class CredentialPlugins {\n private readonly cache: { [key: string]: PluginCredentialsFetchResult | undefined } = {};\n private readonly host: PluginHost;\n private readonly ioHelper: IoHelper;\n\n constructor(host: PluginHost, ioHelper: IoHelper) {\n this.host = host;\n this.ioHelper = ioHelper;\n }\n\n public async fetchCredentialsFor(awsAccountId: string, mode: Mode): Promise<PluginCredentialsFetchResult | undefined> {\n const key = `${awsAccountId}-${mode}`;\n if (!(key in this.cache)) {\n this.cache[key] = await this.lookupCredentials(awsAccountId, mode);\n }\n return this.cache[key];\n }\n\n public get availablePluginNames(): string[] {\n return this.host.credentialProviderSources.map((s) => s.name);\n }\n\n private async lookupCredentials(awsAccountId: string, mode: Mode): Promise<PluginCredentialsFetchResult | undefined> {\n const triedSources: CredentialProviderSource[] = [];\n // Otherwise, inspect the various credential sources we have\n for (const source of this.host.credentialProviderSources) {\n let available: boolean;\n try {\n available = await source.isAvailable();\n } catch (e: any) {\n // This shouldn't happen, but let's guard against it anyway\n await this.ioHelper.notify(IO.CDK_TOOLKIT_W0100.msg(`Uncaught exception in ${source.name}: ${formatErrorMessage(e)}`));\n available = false;\n }\n\n if (!available) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Credentials source ${source.name} is not available, ignoring it.`));\n continue;\n }\n triedSources.push(source);\n let canProvide: boolean;\n try {\n canProvide = await source.canProvideCredentials(awsAccountId);\n } catch (e: any) {\n // This shouldn't happen, but let's guard against it anyway\n await this.ioHelper.notify(IO.CDK_TOOLKIT_W0100.msg(`Uncaught exception in ${source.name}: ${formatErrorMessage(e)}`));\n canProvide = false;\n }\n if (!canProvide) {\n continue;\n }\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Using ${source.name} credentials for account ${awsAccountId}`));\n\n return {\n credentials: await v3ProviderFromPlugin(() => source.getProvider(awsAccountId, mode as ForReading | ForWriting, {\n supportsV3Providers: true,\n })),\n pluginName: source.name,\n };\n }\n return undefined;\n }\n}\n\n/**\n * Result from trying to fetch credentials from the Plugin host\n */\nexport interface PluginCredentialsFetchResult {\n /**\n * SDK-v3 compatible credential provider\n */\n readonly credentials: AwsCredentialIdentityProvider;\n\n /**\n * Name of plugin that successfully provided credentials\n */\n readonly pluginName: string;\n}\n\n/**\n * Take a function that calls the plugin, and turn it into an SDKv3-compatible credential provider.\n *\n * What we will do is the following:\n *\n * - Query the plugin and see what kind of result it gives us.\n * - If the result is self-refreshing or doesn't need refreshing, we turn it into an SDKv3 provider\n * and return it directly.\n * * If the underlying return value is a provider, we will make it a caching provider\n * (because we can't know if it will cache by itself or not).\n * * If the underlying return value is a static credential, caching isn't relevant.\n * * If the underlying return value is V2 credentials, those have caching built-in.\n * - If the result is a static credential that expires, we will wrap it in an SDKv3 provider\n * that will query the plugin again when the credential expires.\n */\nasync function v3ProviderFromPlugin(producer: () => Promise<PluginProviderResult>): Promise<AwsCredentialIdentityProvider> {\n const initial = await producer();\n\n if (isV3Provider(initial)) {\n // Already a provider, make caching\n return makeCachingProvider(initial);\n } else if (isV3Credentials(initial) && initial.expiration === undefined) {\n // Static credentials that don't need refreshing nor caching\n return () => Promise.resolve(initial);\n } else if (isV3Credentials(initial) && initial.expiration !== undefined) {\n // Static credentials that do need refreshing and caching\n return refreshFromPluginProvider(initial, producer);\n } else if (isV2Credentials(initial)) {\n // V2 credentials that refresh and cache themselves\n return v3ProviderFromV2Credentials(initial);\n } else {\n throw new AuthenticationError(`Plugin returned a value that doesn't resemble AWS credentials: ${inspect(initial)}`);\n }\n}\n\n/**\n * Converts a V2 credential into a V3-compatible provider\n */\nfunction v3ProviderFromV2Credentials(x: SDKv2CompatibleCredentials): AwsCredentialIdentityProvider {\n return async () => {\n // Get will fetch or refresh as necessary\n await x.getPromise();\n\n return {\n accessKeyId: x.accessKeyId,\n secretAccessKey: x.secretAccessKey,\n sessionToken: x.sessionToken,\n expiration: x.expireTime ?? undefined,\n };\n };\n}\n\nfunction refreshFromPluginProvider(current: AwsCredentialIdentity, producer: () => Promise<PluginProviderResult>): AwsCredentialIdentityProvider {\n return async () => {\n if (credentialsAboutToExpire(current)) {\n const newCreds = await producer();\n if (!isV3Credentials(newCreds)) {\n throw new AuthenticationError(`Plugin initially returned static V3 credentials but now returned something else: ${inspect(newCreds)}`);\n }\n current = newCreds;\n }\n return current;\n };\n}\n\nfunction isV3Provider(x: PluginProviderResult): x is SDKv3CompatibleCredentialProvider {\n return typeof x === 'function';\n}\n\nfunction isV2Credentials(x: PluginProviderResult): x is SDKv2CompatibleCredentials {\n return !!(x && typeof x === 'object' && (x as SDKv2CompatibleCredentials).getPromise);\n}\n\nfunction isV3Credentials(x: PluginProviderResult): x is SDKv3CompatibleCredentials {\n return !!(x && typeof x === 'object' && x.accessKeyId && !isV2Credentials(x));\n}\n", "import { inspect } from 'util';\nimport type { CredentialProviderSource, IPluginHost, Plugin } from '@aws-cdk/cli-plugin-contract';\nimport { type ContextProviderPlugin, isContextProviderPlugin } from './context-provider-plugin';\nimport { ToolkitError } from '../toolkit-error';\n\nexport let TESTING = false;\n\nexport function markTesting() {\n TESTING = true;\n}\n\n/**\n * A utility to manage plug-ins.\n *\n */\nexport class PluginHost implements IPluginHost {\n public static instance = new PluginHost();\n\n /**\n * Access the currently registered CredentialProviderSources. New sources can\n * be registered using the +registerCredentialProviderSource+ method.\n */\n public readonly credentialProviderSources = new Array<CredentialProviderSource>();\n\n public readonly contextProviderPlugins: Record<string, ContextProviderPlugin> = {};\n\n constructor() {\n if (!TESTING && PluginHost.instance && PluginHost.instance !== this) {\n throw new ToolkitError('New instances of PluginHost must not be built. Use PluginHost.instance instead!');\n }\n }\n\n /**\n * Loads a plug-in into this PluginHost.\n *\n * @param moduleSpec the specification (path or name) of the plug-in module to be loaded.\n */\n public load(moduleSpec: string) {\n try {\n /* eslint-disable @typescript-eslint/no-require-imports */\n const plugin = require(moduleSpec);\n /* eslint-enable */\n if (!isPlugin(plugin)) {\n throw new ToolkitError(`Module ${moduleSpec} is not a valid plug-in, or has an unsupported version.`);\n }\n if (plugin.init) {\n plugin.init(this);\n }\n } catch (e: any) {\n throw ToolkitError.withCause(`Unable to load plug-in '${moduleSpec}'`, e);\n }\n\n function isPlugin(x: any): x is Plugin {\n return x != null && x.version === '1';\n }\n }\n\n /**\n * Allows plug-ins to register new CredentialProviderSources.\n *\n * @param source a new CredentialProviderSource to register.\n */\n public registerCredentialProviderSource(source: CredentialProviderSource) {\n // Forward to the right credentials-related plugin host\n this.credentialProviderSources.push(source);\n }\n\n /**\n * (EXPERIMENTAL) Allow plugins to register context providers\n *\n * Context providers are objects with the following method:\n *\n * ```ts\n * getValue(args: {[key: string]: any}): Promise<any>;\n * ```\n *\n * Currently, they cannot reuse the CDK's authentication mechanisms, so they\n * must be prepared to either not make AWS calls or use their own source of\n * AWS credentials.\n *\n * This feature is experimental, and only intended to be used internally at Amazon\n * as a trial.\n *\n * After registering with 'my-plugin-name', the provider must be addressed as follows:\n *\n * ```ts\n * const value = ContextProvider.getValue(this, {\n * providerName: 'plugin',\n * props: {\n * pluginName: 'my-plugin-name',\n * myParameter1: 'xyz',\n * },\n * includeEnvironment: true | false,\n * dummyValue: 'what-to-return-on-the-first-pass',\n * })\n * ```\n *\n * @experimental\n */\n public registerContextProviderAlpha(pluginProviderName: string, provider: ContextProviderPlugin) {\n if (!isContextProviderPlugin(provider)) {\n throw new ToolkitError(`Object you gave me does not look like a ContextProviderPlugin: ${inspect(provider)}`);\n }\n this.contextProviderPlugins[pluginProviderName] = provider;\n }\n}\n", "export interface ContextProviderPlugin {\n getValue(args: {[key: string]: any}): Promise<any>;\n}\n\nexport function isContextProviderPlugin(x: unknown): x is ContextProviderPlugin {\n return typeof x === 'object' && !!x && !!(x as any).getValue;\n}\n", "import type { ForReading as PluginForReading, ForWriting as PluginForWriting } from '@aws-cdk/cli-plugin-contract';\n\nexport enum Mode {\n ForReading = 0 satisfies PluginForReading,\n ForWriting = 1 satisfies PluginForWriting,\n}\n", "import { inspect, format } from 'util';\nimport type { Logger } from '@smithy/types';\nimport { replacerBufferWithInfo } from '../../util';\nimport type { IoHelper } from '../io/private';\nimport { IO } from '../io/private';\n\nexport class SdkToCliLogger implements Logger {\n private readonly ioHelper: IoHelper;\n\n public constructor(ioHelper: IoHelper) {\n this.ioHelper = ioHelper;\n }\n\n private notify(level: 'info' | 'warn' | 'error', ...content: any[]) {\n void this.ioHelper.notify(IO.CDK_SDK_I0100.msg(format('[SDK %s] %s', level, formatSdkLoggerContent(content)), {\n sdkLevel: level,\n content,\n }));\n }\n\n public trace(..._content: any[]) {\n // This is too much detail for our logs\n // this.notify('trace', ...content);\n }\n\n public debug(..._content: any[]) {\n // This is too much detail for our logs\n // this.notify('debug', ...content);\n }\n\n /**\n * Info is called mostly (exclusively?) for successful API calls\n *\n * Payload:\n *\n * (Note the input contains entire CFN templates, for example)\n *\n * ```\n * {\n * clientName: 'S3Client',\n * commandName: 'GetBucketLocationCommand',\n * input: {\n * Bucket: '.....',\n * ExpectedBucketOwner: undefined\n * },\n * output: { LocationConstraint: 'eu-central-1' },\n * metadata: {\n * httpStatusCode: 200,\n * requestId: '....',\n * extendedRequestId: '...',\n * cfId: undefined,\n * attempts: 1,\n * totalRetryDelay: 0\n * }\n * }\n * ```\n */\n public info(...content: any[]) {\n this.notify('info', ...content);\n }\n\n public warn(...content: any[]) {\n this.notify('warn', ...content);\n }\n\n /**\n * Error is called mostly (exclusively?) for failing API calls\n *\n * Payload (input would be the entire API call arguments).\n *\n * ```\n * {\n * clientName: 'STSClient',\n * commandName: 'GetCallerIdentityCommand',\n * input: {},\n * error: AggregateError [ECONNREFUSED]:\n * at internalConnectMultiple (node:net:1121:18)\n * at afterConnectMultiple (node:net:1688:7) {\n * code: 'ECONNREFUSED',\n * '$metadata': { attempts: 3, totalRetryDelay: 600 },\n * [errors]: [ [Error], [Error] ]\n * },\n * metadata: { attempts: 3, totalRetryDelay: 600 }\n * }\n * ```\n */\n public error(...content: any[]) {\n this.notify('error', ...content);\n }\n}\n\n/**\n * This can be anything.\n *\n * For debug, it seems to be mostly strings.\n * For info, it seems to be objects.\n *\n * Stringify and join without separator.\n */\nexport function formatSdkLoggerContent(content: any[]) {\n if (content.length === 1) {\n const apiFmt = formatApiCall(content[0]);\n if (apiFmt) {\n return apiFmt;\n }\n }\n return content.map((x) => typeof x === 'string' ? x : inspect(x)).join('');\n}\n\nfunction formatApiCall(content: any): string | undefined {\n if (!isSdkApiCallSuccess(content) && !isSdkApiCallError(content)) {\n return undefined;\n }\n\n const service = content.clientName.replace(/Client$/, '');\n const api = content.commandName.replace(/Command$/, '');\n\n const parts = [];\n if ((content.metadata?.attempts ?? 0) > 1) {\n parts.push(`[${content.metadata?.attempts} attempts, ${content.metadata?.totalRetryDelay}ms retry]`);\n }\n\n parts.push(`${service}.${api}(${JSON.stringify(content.input, replacerBufferWithInfo)})`);\n\n if (isSdkApiCallSuccess(content)) {\n parts.push('-> OK');\n } else {\n parts.push(`-> ${content.error}`);\n }\n\n return parts.join(' ');\n}\n\ninterface SdkApiCallBase {\n clientName: string;\n commandName: string;\n input: Record<string, unknown>;\n metadata?: {\n httpStatusCode?: number;\n requestId?: string;\n extendedRequestId?: string;\n cfId?: string;\n attempts?: number;\n totalRetryDelay?: number;\n };\n}\n\ntype SdkApiCallSuccess = SdkApiCallBase & { output: Record<string, unknown> };\ntype SdkApiCallError = SdkApiCallBase & { error: Error };\n\nfunction isSdkApiCallSuccess(x: any): x is SdkApiCallSuccess {\n return x && typeof x === 'object' && x.commandName && x.output;\n}\n\nfunction isSdkApiCallError(x: any): x is SdkApiCallError {\n return x && typeof x === 'object' && x.commandName && x.error;\n}\n", "import * as path from 'path';\nimport type * as cxapi from '@aws-cdk/cx-api';\nimport type { BootstrapEnvironmentOptions, BootstrappingParameters } from './bootstrap-props';\nimport { BootstrapStack, bootstrapVersionFromTemplate } from './deploy-bootstrap';\nimport { legacyBootstrapTemplate } from './legacy-template';\nimport { bundledPackageRootDir, loadStructuredFile, serializeStructure } from '../../util';\nimport type { SDK, SdkProvider } from '../aws-auth';\nimport type { SuccessfulDeployStackResult } from '../deployments';\nimport { IO, type IoHelper } from '../io/private';\nimport { Mode } from '../plugin';\nimport { ToolkitError } from '../toolkit-error';\nimport { DEFAULT_TOOLKIT_STACK_NAME } from '../toolkit-info';\n\nexport type BootstrapSource = { source: 'legacy' } | { source: 'default' } | { source: 'custom'; templateFile: string };\n\nexport class Bootstrapper {\n private readonly ioHelper: IoHelper;\n\n constructor(\n private readonly source: BootstrapSource = { source: 'default' },\n ioHelper: IoHelper,\n ) {\n this.ioHelper = ioHelper;\n }\n\n public bootstrapEnvironment(\n environment: cxapi.Environment,\n sdkProvider: SdkProvider,\n options: BootstrapEnvironmentOptions = {},\n ): Promise<SuccessfulDeployStackResult> {\n switch (this.source.source) {\n case 'legacy':\n return this.legacyBootstrap(environment, sdkProvider, options);\n case 'default':\n return this.modernBootstrap(environment, sdkProvider, options);\n case 'custom':\n return this.customBootstrap(environment, sdkProvider, options);\n }\n }\n\n public async showTemplate(json: boolean) {\n const template = await this.loadTemplate();\n process.stdout.write(`${serializeStructure(template, json)}\\n`);\n }\n\n /**\n * Deploy legacy bootstrap stack\n *\n */\n private async legacyBootstrap(\n environment: cxapi.Environment,\n sdkProvider: SdkProvider,\n options: BootstrapEnvironmentOptions = {},\n ): Promise<SuccessfulDeployStackResult> {\n const params = options.parameters ?? {};\n\n if (params.trustedAccounts?.length) {\n throw new ToolkitError('--trust can only be passed for the modern bootstrap experience.');\n }\n if (params.cloudFormationExecutionPolicies?.length) {\n throw new ToolkitError('--cloudformation-execution-policies can only be passed for the modern bootstrap experience.');\n }\n if (params.createCustomerMasterKey !== undefined) {\n throw new ToolkitError('--bootstrap-customer-key can only be passed for the modern bootstrap experience.');\n }\n if (params.qualifier) {\n throw new ToolkitError('--qualifier can only be passed for the modern bootstrap experience.');\n }\n\n const toolkitStackName = options.toolkitStackName ?? DEFAULT_TOOLKIT_STACK_NAME;\n const current = await BootstrapStack.lookup(sdkProvider, environment, toolkitStackName, this.ioHelper);\n return current.update(\n await this.loadTemplate(params),\n {},\n {\n ...options,\n terminationProtection: options.terminationProtection ?? current.terminationProtection,\n },\n );\n }\n\n /**\n * Deploy CI/CD-ready bootstrap stack from template\n *\n */\n private async modernBootstrap(\n environment: cxapi.Environment,\n sdkProvider: SdkProvider,\n options: BootstrapEnvironmentOptions = {},\n ): Promise<SuccessfulDeployStackResult> {\n const params = options.parameters ?? {};\n\n const bootstrapTemplate = await this.loadTemplate();\n\n const toolkitStackName = options.toolkitStackName ?? DEFAULT_TOOLKIT_STACK_NAME;\n const current = await BootstrapStack.lookup(sdkProvider, environment, toolkitStackName, this.ioHelper);\n const partition = await current.partition();\n\n if (params.createCustomerMasterKey !== undefined && params.kmsKeyId) {\n throw new ToolkitError(\n \"You cannot pass '--bootstrap-kms-key-id' and '--bootstrap-customer-key' together. Specify one or the other\",\n );\n }\n\n // If people re-bootstrap, existing parameter values are reused so that people don't accidentally change the configuration\n // on their bootstrap stack (this happens automatically in deployStack). However, to do proper validation on the\n // combined arguments (such that if --trust has been given, --cloudformation-execution-policies is necessary as well)\n // we need to take this parameter reuse into account.\n //\n // Ideally we'd do this inside the template, but the `Rules` section of CFN\n // templates doesn't seem to be able to express the conditions that we need\n // (can't use Fn::Join or reference Conditions) so we do it here instead.\n const allTrusted = new Set([\n ...params.trustedAccounts ?? [],\n ...params.trustedAccountsForLookup ?? [],\n ]);\n const invalid = intersection(allTrusted, new Set(params.untrustedAccounts));\n if (invalid.size > 0) {\n throw new ToolkitError(`Accounts cannot be both trusted and untrusted. Found: ${[...invalid].join(',')}`);\n }\n\n const removeUntrusted = (accounts: string[]) =>\n accounts.filter(acc => !params.untrustedAccounts?.map(String).includes(String(acc)));\n\n const trustedAccounts = removeUntrusted(params.trustedAccounts ?? splitCfnArray(current.parameters.TrustedAccounts));\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(\n `Trusted accounts for deployment: ${trustedAccounts.length > 0 ? trustedAccounts.join(', ') : '(none)'}`,\n ));\n\n const trustedAccountsForLookup = removeUntrusted(\n params.trustedAccountsForLookup ?? splitCfnArray(current.parameters.TrustedAccountsForLookup),\n );\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(\n `Trusted accounts for lookup: ${trustedAccountsForLookup.length > 0 ? trustedAccountsForLookup.join(', ') : '(none)'}`,\n ));\n\n const cloudFormationExecutionPolicies =\n params.cloudFormationExecutionPolicies ?? splitCfnArray(current.parameters.CloudFormationExecutionPolicies);\n if (trustedAccounts.length === 0 && cloudFormationExecutionPolicies.length === 0) {\n // For self-trust it's okay to default to AdministratorAccess, and it improves the usability of bootstrapping a lot.\n //\n // We don't actually make the implicitly policy a physical parameter. The template will infer it instead,\n // we simply do the UI advertising that behavior here.\n //\n // If we DID make it an explicit parameter, we wouldn't be able to tell the difference between whether\n // we inferred it or whether the user told us, and the sequence:\n //\n // $ cdk bootstrap\n // $ cdk bootstrap --trust 1234\n //\n // Would leave AdministratorAccess policies with a trust relationship, without the user explicitly\n // approving the trust policy.\n const implicitPolicy = `arn:${partition}:iam::aws:policy/AdministratorAccess`;\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_WARN.msg(\n `Using default execution policy of '${implicitPolicy}'. Pass '--cloudformation-execution-policies' to customize.`,\n ));\n } else if (cloudFormationExecutionPolicies.length === 0) {\n throw new ToolkitError(\n `Please pass \\'--cloudformation-execution-policies\\' when using \\'--trust\\' to specify deployment permissions. Try a managed policy of the form \\'arn:${partition}:iam::aws:policy/<PolicyName>\\'.`,\n );\n } else {\n // Remind people what the current settings are\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(`Execution policies: ${cloudFormationExecutionPolicies.join(', ')}`));\n }\n\n // * If an ARN is given, that ARN. Otherwise:\n // * '-' if customerKey = false\n // * '' if customerKey = true\n // * if customerKey is also not given\n // * undefined if we already had a value in place (reusing what we had)\n // * '-' if this is the first time we're deploying this stack (or upgrading from old to new bootstrap)\n const currentKmsKeyId = current.parameters.FileAssetsBucketKmsKeyId;\n const kmsKeyId =\n params.kmsKeyId ??\n (params.createCustomerMasterKey === true\n ? CREATE_NEW_KEY\n : params.createCustomerMasterKey === false || currentKmsKeyId === undefined\n ? USE_AWS_MANAGED_KEY\n : undefined);\n\n /* A permissions boundary can be provided via:\n * - the flag indicating the example one should be used\n * - the name indicating the custom permissions boundary to be used\n * Re-bootstrapping will NOT be blocked by either tightening or relaxing the permissions' boundary.\n */\n\n // InputPermissionsBoundary is an `any` type and if it is not defined it\n // appears as an empty string ''. We need to force it to evaluate an empty string\n // as undefined\n const currentPermissionsBoundary: string | undefined = current.parameters.InputPermissionsBoundary || undefined;\n const inputPolicyName = params.examplePermissionsBoundary\n ? CDK_BOOTSTRAP_PERMISSIONS_BOUNDARY\n : params.customPermissionsBoundary;\n let policyName: string | undefined;\n if (inputPolicyName) {\n // If the example policy is not already in place, it must be created.\n const sdk = (await sdkProvider.forEnvironment(environment, Mode.ForWriting)).sdk;\n policyName = await this.getPolicyName(environment, sdk, inputPolicyName, partition, params);\n }\n if (currentPermissionsBoundary !== policyName) {\n if (!currentPermissionsBoundary) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_WARN.msg(\n `Adding new permissions boundary ${policyName}`,\n ));\n } else if (!policyName) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_WARN.msg(\n `Removing existing permissions boundary ${currentPermissionsBoundary}`,\n ));\n } else {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_WARN.msg(\n `Changing permissions boundary from ${currentPermissionsBoundary} to ${policyName}`,\n ));\n }\n }\n\n return current.update(\n bootstrapTemplate,\n {\n FileAssetsBucketName: params.bucketName,\n FileAssetsBucketKmsKeyId: kmsKeyId,\n // Empty array becomes empty string\n TrustedAccounts: trustedAccounts.join(','),\n TrustedAccountsForLookup: trustedAccountsForLookup.join(','),\n CloudFormationExecutionPolicies: cloudFormationExecutionPolicies.join(','),\n Qualifier: params.qualifier,\n PublicAccessBlockConfiguration:\n params.publicAccessBlockConfiguration || params.publicAccessBlockConfiguration === undefined\n ? 'true'\n : 'false',\n InputPermissionsBoundary: policyName,\n },\n {\n ...options,\n terminationProtection: options.terminationProtection ?? current.terminationProtection,\n },\n );\n }\n\n private async getPolicyName(\n environment: cxapi.Environment,\n sdk: SDK,\n permissionsBoundary: string,\n partition: string,\n params: BootstrappingParameters,\n ): Promise<string> {\n if (permissionsBoundary !== CDK_BOOTSTRAP_PERMISSIONS_BOUNDARY) {\n this.validatePolicyName(permissionsBoundary);\n return Promise.resolve(permissionsBoundary);\n }\n // if no Qualifier is supplied, resort to the default one\n const arn = await this.getExamplePermissionsBoundary(\n params.qualifier ?? 'hnb659fds',\n partition,\n environment.account,\n sdk,\n );\n const policyName = arn.split('/').pop();\n if (!policyName) {\n throw new ToolkitError('Could not retrieve the example permission boundary!');\n }\n return Promise.resolve(policyName);\n }\n\n private async getExamplePermissionsBoundary(\n qualifier: string,\n partition: string,\n account: string,\n sdk: SDK,\n ): Promise<string> {\n const iam = sdk.iam();\n\n let policyName = `cdk-${qualifier}-permissions-boundary`;\n const arn = `arn:${partition}:iam::${account}:policy/${policyName}`;\n\n try {\n let getPolicyResp = await iam.getPolicy({ PolicyArn: arn });\n if (getPolicyResp.Policy) {\n return arn;\n }\n } catch (e: any) {\n // https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetPolicy.html#API_GetPolicy_Errors\n if (e.name === 'NoSuchEntity') {\n // noop, proceed with creating the policy\n } else {\n throw e;\n }\n }\n\n const policyDoc = {\n Version: '2012-10-17',\n Statement: [\n {\n Action: ['*'],\n Resource: '*',\n Effect: 'Allow',\n Sid: 'ExplicitAllowAll',\n },\n {\n Condition: {\n StringEquals: {\n 'iam:PermissionsBoundary': `arn:${partition}:iam::${account}:policy/cdk-${qualifier}-permissions-boundary`,\n },\n },\n Action: [\n 'iam:CreateUser',\n 'iam:CreateRole',\n 'iam:PutRolePermissionsBoundary',\n 'iam:PutUserPermissionsBoundary',\n ],\n Resource: '*',\n Effect: 'Allow',\n Sid: 'DenyAccessIfRequiredPermBoundaryIsNotBeingApplied',\n },\n {\n Action: [\n 'iam:CreatePolicyVersion',\n 'iam:DeletePolicy',\n 'iam:DeletePolicyVersion',\n 'iam:SetDefaultPolicyVersion',\n ],\n Resource: `arn:${partition}:iam::${account}:policy/cdk-${qualifier}-permissions-boundary`,\n Effect: 'Deny',\n Sid: 'DenyPermBoundaryIAMPolicyAlteration',\n },\n {\n Action: ['iam:DeleteUserPermissionsBoundary', 'iam:DeleteRolePermissionsBoundary'],\n Resource: '*',\n Effect: 'Deny',\n Sid: 'DenyRemovalOfPermBoundaryFromAnyUserOrRole',\n },\n ],\n };\n const request = {\n PolicyName: policyName,\n PolicyDocument: JSON.stringify(policyDoc),\n };\n const createPolicyResponse = await iam.createPolicy(request);\n if (createPolicyResponse.Policy?.Arn) {\n return createPolicyResponse.Policy.Arn;\n } else {\n throw new ToolkitError(`Could not retrieve the example permission boundary ${arn}!`);\n }\n }\n\n private validatePolicyName(permissionsBoundary: string) {\n // https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreatePolicy.html\n // Added support for policy names with a path\n // See https://github.com/aws/aws-cdk/issues/26320\n const regexp: RegExp = /[\\w+\\/=,.@-]+/;\n const matches = regexp.exec(permissionsBoundary);\n if (!(matches && matches.length === 1 && matches[0] === permissionsBoundary)) {\n throw new ToolkitError(`The permissions boundary name ${permissionsBoundary} does not match the IAM conventions.`);\n }\n }\n\n private async customBootstrap(\n environment: cxapi.Environment,\n sdkProvider: SdkProvider,\n options: BootstrapEnvironmentOptions = {},\n ): Promise<SuccessfulDeployStackResult> {\n // Look at the template, decide whether it's most likely a legacy or modern bootstrap\n // template, and use the right bootstrapper for that.\n const version = bootstrapVersionFromTemplate(await this.loadTemplate());\n if (version === 0) {\n return this.legacyBootstrap(environment, sdkProvider, options);\n } else {\n return this.modernBootstrap(environment, sdkProvider, options);\n }\n }\n\n private async loadTemplate(params: BootstrappingParameters = {}): Promise<any> {\n switch (this.source.source) {\n case 'custom':\n return loadStructuredFile(this.source.templateFile);\n case 'default':\n return loadStructuredFile(path.join(bundledPackageRootDir(__dirname), 'lib', 'api', 'bootstrap', 'bootstrap-template.yaml'));\n case 'legacy':\n return legacyBootstrapTemplate(params);\n }\n }\n}\n\n/**\n * Magic parameter value that will cause the bootstrap-template.yml to NOT create a CMK but use the default key\n */\nconst USE_AWS_MANAGED_KEY = 'AWS_MANAGED_KEY';\n\n/**\n * Magic parameter value that will cause the bootstrap-template.yml to create a CMK\n */\nconst CREATE_NEW_KEY = '';\n/**\n * Parameter value indicating the use of the default, CDK provided permissions boundary for bootstrap-template.yml\n */\nconst CDK_BOOTSTRAP_PERMISSIONS_BOUNDARY = 'CDK_BOOTSTRAP_PERMISSIONS_BOUNDARY';\n\n/**\n * Split an array-like CloudFormation parameter on ,\n *\n * An empty string is the empty array (instead of `['']`).\n */\nfunction splitCfnArray(xs: string | undefined): string[] {\n if (xs === '' || xs === undefined) {\n return [];\n }\n return xs.split(',');\n}\n\nfunction intersection<A>(xs: Set<A>, ys: Set<A>): Set<A> {\n return new Set<A>(Array.from(xs).filter(x => ys.has(x)));\n}\n", "import * as os from 'os';\nimport * as path from 'path';\nimport { ArtifactType } from '@aws-cdk/cloud-assembly-schema';\nimport type { Environment } from '@aws-cdk/cx-api';\nimport { CloudAssemblyBuilder, EnvironmentUtils } from '@aws-cdk/cx-api';\nimport * as fs from 'fs-extra';\nimport type { BootstrapEnvironmentOptions } from './bootstrap-props';\nimport {\n BOOTSTRAP_VARIANT_PARAMETER,\n BOOTSTRAP_VERSION_OUTPUT,\n BOOTSTRAP_VERSION_RESOURCE,\n DEFAULT_BOOTSTRAP_VARIANT,\n} from './bootstrap-props';\nimport type { SDK, SdkProvider } from '../aws-auth';\nimport type { SuccessfulDeployStackResult } from '../deployments';\nimport { assertIsSuccessfulDeployStackResult } from '../deployments';\nimport { deployStack } from '../deployments/deploy-stack';\nimport { NoBootstrapStackEnvironmentResources } from '../environment';\nimport { IO, type IoHelper } from '../io/private';\nimport { Mode } from '../plugin';\nimport { DEFAULT_TOOLKIT_STACK_NAME, ToolkitInfo } from '../toolkit-info';\n\n/**\n * A class to hold state around stack bootstrapping\n *\n * This class exists so we can break bootstrapping into 2 phases:\n *\n * ```ts\n * const current = BootstrapStack.lookup(...);\n * // ...\n * current.update(newTemplate, ...);\n * ```\n *\n * And do something in between the two phases (such as look at the\n * current bootstrap stack and doing something intelligent).\n */\nexport class BootstrapStack {\n public static async lookup(sdkProvider: SdkProvider, environment: Environment, toolkitStackName: string, ioHelper: IoHelper) {\n toolkitStackName = toolkitStackName ?? DEFAULT_TOOLKIT_STACK_NAME;\n\n const resolvedEnvironment = await sdkProvider.resolveEnvironment(environment);\n const sdk = (await sdkProvider.forEnvironment(resolvedEnvironment, Mode.ForWriting)).sdk;\n\n const currentToolkitInfo = await ToolkitInfo.lookup(resolvedEnvironment, sdk, ioHelper, toolkitStackName);\n\n return new BootstrapStack(sdkProvider, sdk, resolvedEnvironment, toolkitStackName, currentToolkitInfo, ioHelper);\n }\n\n protected constructor(\n private readonly sdkProvider: SdkProvider,\n private readonly sdk: SDK,\n private readonly resolvedEnvironment: Environment,\n private readonly toolkitStackName: string,\n private readonly currentToolkitInfo: ToolkitInfo,\n private readonly ioHelper: IoHelper,\n ) {\n }\n\n public get parameters(): Record<string, string> {\n return this.currentToolkitInfo.found ? this.currentToolkitInfo.bootstrapStack.parameters : {};\n }\n\n public get terminationProtection() {\n return this.currentToolkitInfo.found ? this.currentToolkitInfo.bootstrapStack.terminationProtection : undefined;\n }\n\n public async partition(): Promise<string> {\n return (await this.sdk.currentAccount()).partition;\n }\n\n /**\n * Perform the actual deployment of a bootstrap stack, given a template and some parameters\n */\n public async update(\n template: any,\n parameters: Record<string, string | undefined>,\n options: Omit<BootstrapEnvironmentOptions, 'parameters'>,\n ): Promise<SuccessfulDeployStackResult> {\n if (this.currentToolkitInfo.found && !options.forceDeployment) {\n // Safety checks\n const abortResponse = {\n type: 'did-deploy-stack',\n noOp: true,\n outputs: {},\n stackArn: this.currentToolkitInfo.bootstrapStack.stackId,\n } satisfies SuccessfulDeployStackResult;\n\n // Validate that the bootstrap stack we're trying to replace is from the same variant as the one we're trying to deploy\n const currentVariant = this.currentToolkitInfo.variant;\n const newVariant = bootstrapVariantFromTemplate(template);\n if (currentVariant !== newVariant) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_WARN.msg(\n `Bootstrap stack already exists, containing '${currentVariant}'. Not overwriting it with a template containing '${newVariant}' (use --force if you intend to overwrite)`,\n ));\n return abortResponse;\n }\n\n // Validate that we're not downgrading the bootstrap stack\n const newVersion = bootstrapVersionFromTemplate(template);\n const currentVersion = this.currentToolkitInfo.version;\n if (newVersion < currentVersion) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_WARN.msg(\n `Bootstrap stack already at version ${currentVersion}. Not downgrading it to version ${newVersion} (use --force if you intend to downgrade)`,\n ));\n if (newVersion === 0) {\n // A downgrade with 0 as target version means we probably have a new-style bootstrap in the account,\n // and an old-style bootstrap as current target, which means the user probably forgot to put this flag in.\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_WARN.msg(\n \"(Did you set the '@aws-cdk/core:newStyleStackSynthesis' feature flag in cdk.json?)\",\n ));\n }\n return abortResponse;\n }\n }\n\n const outdir = await fs.mkdtemp(path.join(os.tmpdir(), 'cdk-bootstrap'));\n const builder = new CloudAssemblyBuilder(outdir);\n const templateFile = `${this.toolkitStackName}.template.json`;\n await fs.writeJson(path.join(builder.outdir, templateFile), template, {\n spaces: 2,\n });\n\n builder.addArtifact(this.toolkitStackName, {\n type: ArtifactType.AWS_CLOUDFORMATION_STACK,\n environment: EnvironmentUtils.format(this.resolvedEnvironment.account, this.resolvedEnvironment.region),\n properties: {\n templateFile,\n terminationProtection: options.terminationProtection ?? false,\n },\n });\n\n const assembly = builder.buildAssembly();\n\n const ret = await deployStack({\n stack: assembly.getStackByName(this.toolkitStackName),\n resolvedEnvironment: this.resolvedEnvironment,\n sdk: this.sdk,\n sdkProvider: this.sdkProvider,\n forceDeployment: options.forceDeployment,\n roleArn: options.roleArn,\n tags: options.tags,\n deploymentMethod: { method: 'change-set', execute: options.execute },\n parameters,\n usePreviousParameters: options.usePreviousParameters ?? true,\n // Obviously we can't need a bootstrap stack to deploy a bootstrap stack\n envResources: new NoBootstrapStackEnvironmentResources(this.resolvedEnvironment, this.sdk, this.ioHelper),\n }, this.ioHelper);\n\n assertIsSuccessfulDeployStackResult(ret);\n\n return ret;\n }\n}\n\nexport function bootstrapVersionFromTemplate(template: any): number {\n const versionSources = [\n template.Outputs?.[BOOTSTRAP_VERSION_OUTPUT]?.Value,\n template.Resources?.[BOOTSTRAP_VERSION_RESOURCE]?.Properties?.Value,\n ];\n\n for (const vs of versionSources) {\n if (typeof vs === 'number') {\n return vs;\n }\n if (typeof vs === 'string' && !isNaN(parseInt(vs, 10))) {\n return parseInt(vs, 10);\n }\n }\n return 0;\n}\n\nexport function bootstrapVariantFromTemplate(template: any): string {\n return template.Parameters?.[BOOTSTRAP_VARIANT_PARAMETER]?.Default ?? DEFAULT_BOOTSTRAP_VARIANT;\n}\n", "import type { BootstrapSource } from './bootstrap-environment';\nimport type { StringWithoutPlaceholders } from '../environment';\nimport type { Tag } from '../tags';\n\nexport const BUCKET_NAME_OUTPUT = 'BucketName';\nexport const REPOSITORY_NAME_OUTPUT = 'ImageRepositoryName';\nexport const BUCKET_DOMAIN_NAME_OUTPUT = 'BucketDomainName';\nexport const BOOTSTRAP_VERSION_OUTPUT = 'BootstrapVersion';\nexport const BOOTSTRAP_VERSION_RESOURCE = 'CdkBootstrapVersion';\nexport const BOOTSTRAP_VARIANT_PARAMETER = 'BootstrapVariant';\n\n/**\n * The assumed vendor of a template in case it is not set\n */\nexport const DEFAULT_BOOTSTRAP_VARIANT = 'AWS CDK: Default Resources';\n\n/**\n * Options for the bootstrapEnvironment operation(s)\n */\nexport interface BootstrapEnvironmentOptions {\n readonly toolkitStackName?: string;\n readonly roleArn?: StringWithoutPlaceholders;\n readonly parameters?: BootstrappingParameters;\n readonly forceDeployment?: boolean;\n\n /**\n * The source of the bootstrap stack\n *\n * @default - modern v2-style bootstrapping\n */\n readonly source?: BootstrapSource;\n\n /**\n * Whether to execute the changeset or only create it and leave it in review.\n * @default true\n */\n readonly execute?: boolean;\n\n /**\n * Tags for cdktoolkit stack.\n *\n * @default - None.\n */\n readonly tags?: Tag[];\n\n /**\n * Whether the stacks created by the bootstrap process should be protected from termination.\n * @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-protect-stacks.html\n * @default true\n */\n readonly terminationProtection?: boolean;\n\n /**\n * Use previous values for unspecified parameters\n *\n * If not set, all parameters must be specified for every deployment.\n *\n * @default true\n */\n usePreviousParameters?: boolean;\n}\n\n/**\n * Parameters for the bootstrapping template\n */\nexport interface BootstrappingParameters {\n /**\n * The name to be given to the CDK Bootstrap bucket.\n *\n * @default - a name is generated by CloudFormation.\n */\n readonly bucketName?: string;\n\n /**\n * The ID of an existing KMS key to be used for encrypting items in the bucket.\n *\n * @default - use the default KMS key or create a custom one\n */\n readonly kmsKeyId?: string;\n\n /**\n * Whether or not to create a new customer master key (CMK)\n *\n * Only applies to modern bootstrapping. Legacy bootstrapping will never create\n * a CMK, only use the default S3 key.\n *\n * @default false\n */\n readonly createCustomerMasterKey?: boolean;\n\n /**\n * The list of AWS account IDs that are trusted to deploy into the environment being bootstrapped.\n *\n * @default - only the bootstrapped account can deploy into this environment\n */\n readonly trustedAccounts?: string[];\n\n /**\n * The list of AWS account IDs that are trusted to look up values in the environment being bootstrapped.\n *\n * @default - only the bootstrapped account can look up values in this environment\n */\n readonly trustedAccountsForLookup?: string[];\n\n /**\n * The list of AWS account IDs that should not be trusted by the bootstrapped environment.\n * If these accounts are already trusted, they will be removed on bootstrapping.\n *\n * @default - no account will be untrusted.\n */\n readonly untrustedAccounts?: string[];\n\n /**\n * The ARNs of the IAM managed policies that should be attached to the role performing CloudFormation deployments.\n * In most cases, this will be the AdministratorAccess policy.\n * At least one policy is required if `trustedAccounts` were passed.\n *\n * @default - the role will have no policies attached\n */\n readonly cloudFormationExecutionPolicies?: string[];\n\n /**\n * Identifier to distinguish multiple bootstrapped environments\n *\n * @default - Default qualifier\n */\n readonly qualifier?: string;\n\n /**\n * Whether or not to enable S3 Staging Bucket Public Access Block Configuration\n *\n * @default true\n */\n readonly publicAccessBlockConfiguration?: boolean;\n\n /**\n * Flag for using the default permissions boundary for bootstrapping\n *\n * @default - No value, optional argument\n */\n readonly examplePermissionsBoundary?: boolean;\n\n /**\n * Name for the customer's custom permissions boundary for bootstrapping\n *\n * @default - No value, optional argument\n */\n readonly customPermissionsBoundary?: string;\n}\n", "import { randomUUID } from 'crypto';\nimport type * as cxapi from '@aws-cdk/cx-api';\nimport * as cdk_assets from 'cdk-assets';\nimport * as chalk from 'chalk';\nimport { AssetManifestBuilder } from './asset-manifest-builder';\nimport {\n BasePublishProgressListener,\n PublishingAws,\n} from './asset-publishing';\nimport {\n stabilizeStack,\n uploadStackTemplateAssets,\n} from './cfn-api';\nimport { determineAllowCrossAccountAssetPublishing } from './checks';\n\nimport { deployStack, destroyStack } from './deploy-stack';\nimport type { DeploymentMethod } from './deployment-method';\nimport type { DeployStackResult } from './deployment-result';\nimport { formatErrorMessage } from '../../util';\nimport type { SdkProvider } from '../aws-auth';\nimport type {\n Template,\n RootTemplateWithNestedStacks,\n} from '../cloudformation';\nimport {\n CloudFormationStack,\n loadCurrentTemplate,\n loadCurrentTemplateWithNestedStacks,\n makeBodyParameter,\n} from '../cloudformation';\nimport { type EnvironmentResources, EnvironmentAccess } from '../environment';\nimport type { HotswapMode, HotswapPropertyOverrides } from '../hotswap/common';\nimport { IO, type IoHelper } from '../io/private';\nimport type { ResourceIdentifierSummaries, ResourcesToImport } from '../resource-import';\nimport { StackActivityMonitor, StackEventPoller, RollbackChoice } from '../stack-events';\nimport type { Tag } from '../tags';\nimport { ToolkitError } from '../toolkit-error';\nimport { DEFAULT_TOOLKIT_STACK_NAME } from '../toolkit-info';\n\nconst BOOTSTRAP_STACK_VERSION_FOR_ROLLBACK = 23;\n\nexport interface DeployStackOptions {\n /**\n * Stack to deploy\n */\n readonly stack: cxapi.CloudFormationStackArtifact;\n\n /**\n * Execution role for the deployment (pass through to CloudFormation)\n *\n * @default - Current role\n */\n readonly roleArn?: string;\n\n /**\n * Topic ARNs to send a message when deployment finishes (pass through to CloudFormation)\n *\n * @default - No notifications\n */\n readonly notificationArns?: string[];\n\n /**\n * Override name under which stack will be deployed\n *\n * @default - Use artifact default\n */\n readonly deployName?: string;\n\n /**\n * Name of the toolkit stack, if not the default name\n *\n * @default 'CDKToolkit'\n */\n readonly toolkitStackName?: string;\n\n /**\n * List of asset IDs which should NOT be built or uploaded\n *\n * @default - Build all assets\n */\n readonly reuseAssets?: string[];\n\n /**\n * Stack tags (pass through to CloudFormation)\n */\n readonly tags?: Tag[];\n\n /**\n * Stage the change set but don't execute it\n *\n * @default - true\n * @deprecated Use 'deploymentMethod' instead\n */\n readonly execute?: boolean;\n\n /**\n * Optional name to use for the CloudFormation change set.\n * If not provided, a name will be generated automatically.\n *\n * @deprecated Use 'deploymentMethod' instead\n */\n readonly changeSetName?: string;\n\n /**\n * Select the deployment method (direct or using a change set)\n *\n * @default - Change set with default options\n */\n readonly deploymentMethod?: DeploymentMethod;\n\n /**\n * Force deployment, even if the deployed template is identical to the one we are about to deploy.\n * @default false deployment will be skipped if the template is identical\n */\n readonly forceDeployment?: boolean;\n\n /**\n * Extra parameters for CloudFormation\n * @default - no additional parameters will be passed to the template\n */\n readonly parameters?: { [name: string]: string | undefined };\n\n /**\n * Use previous values for unspecified parameters\n *\n * If not set, all parameters must be specified for every deployment.\n *\n * @default true\n */\n readonly usePreviousParameters?: boolean;\n\n /**\n * Rollback failed deployments\n *\n * @default true\n */\n readonly rollback?: boolean;\n\n /*\n * Whether to perform a 'hotswap' deployment.\n * A 'hotswap' deployment will attempt to short-circuit CloudFormation\n * and update the affected resources like Lambda functions directly.\n *\n * @default - `HotswapMode.FULL_DEPLOYMENT` for regular deployments, `HotswapMode.HOTSWAP_ONLY` for 'watch' deployments\n */\n readonly hotswap?: HotswapMode;\n\n /**\n * Properties that configure hotswap behavior\n */\n readonly hotswapPropertyOverrides?: HotswapPropertyOverrides;\n\n /**\n * The extra string to append to the User-Agent header when performing AWS SDK calls.\n *\n * @default - nothing extra is appended to the User-Agent header\n */\n readonly extraUserAgent?: string;\n\n /**\n * List of existing resources to be IMPORTED into the stack, instead of being CREATED\n */\n readonly resourcesToImport?: ResourcesToImport;\n\n /**\n * If present, use this given template instead of the stored one\n *\n * @default - Use the stored template\n */\n readonly overrideTemplate?: any;\n\n /**\n * Whether to build/publish assets in parallel\n *\n * @default true To remain backward compatible.\n */\n readonly assetParallelism?: boolean;\n\n /**\n * Whether to deploy if the app contains no stacks.\n *\n * @deprecated this option seems to be unsed inside deployments\n * @default false\n */\n readonly ignoreNoStacks?: boolean;\n}\n\nexport interface RollbackStackOptions {\n /**\n * Stack to roll back\n */\n readonly stack: cxapi.CloudFormationStackArtifact;\n\n /**\n * Execution role for the deployment (pass through to CloudFormation)\n *\n * @default - Current role\n */\n readonly roleArn?: string;\n\n /**\n * Name of the toolkit stack, if not the default name\n *\n * @default 'CDKToolkit'\n */\n readonly toolkitStackName?: string;\n\n /**\n * Whether to automatically orphan all failed resources during the rollback\n *\n * This will force a rollback that otherwise would have failed.\n *\n * @default false\n */\n readonly orphanFailedResources?: boolean;\n\n /**\n * Orphan the resources with the given logical IDs\n *\n * @default - No orphaning\n */\n readonly orphanLogicalIds?: string[];\n\n /**\n * Whether to validate the version of the bootstrap stack permissions\n *\n * @default true\n */\n readonly validateBootstrapStackVersion?: boolean;\n}\n\nexport type RollbackStackResult = { readonly stackArn: string } & (\n | { readonly notInRollbackableState: true }\n | { readonly success: true; notInRollbackableState?: undefined }\n);\n\ninterface AssetOptions {\n /**\n * Stack with assets to build.\n */\n readonly stack: cxapi.CloudFormationStackArtifact;\n\n /**\n * Execution role for the building.\n *\n * @default - Current role\n */\n readonly roleArn?: string;\n}\n\nexport interface BuildStackAssetsOptions extends AssetOptions {\n /**\n * Stack name this asset is for\n */\n readonly stackName?: string;\n}\n\ninterface PublishStackAssetsOptions extends AssetOptions {\n /**\n * Stack name this asset is for\n */\n readonly stackName?: string;\n\n /**\n * Always publish, even if it already exists\n *\n * @default false\n */\n readonly forcePublish?: boolean;\n}\n\nexport interface DestroyStackOptions {\n stack: cxapi.CloudFormationStackArtifact;\n deployName?: string;\n roleArn?: string;\n}\n\nexport interface StackExistsOptions {\n stack: cxapi.CloudFormationStackArtifact;\n deployName?: string;\n tryLookupRole?: boolean;\n}\n\nexport interface DeploymentsProps {\n readonly sdkProvider: SdkProvider;\n readonly toolkitStackName?: string;\n readonly ioHelper: IoHelper;\n}\n\n/**\n * Scope for a single set of deployments from a set of Cloud Assembly Artifacts\n *\n * Manages lookup of SDKs, Bootstrap stacks, etc.\n */\nexport class Deployments {\n public readonly envs: EnvironmentAccess;\n\n /**\n * SDK provider for asset publishing (do not use for anything else).\n *\n * This SDK provider is only allowed to be used for that purpose, nothing else.\n *\n * It's not a different object, but the field name should imply that this\n * object should not be used directly, except to pass to asset handling routines.\n */\n private readonly assetSdkProvider: SdkProvider;\n\n /**\n * SDK provider for passing to deployStack\n *\n * This SDK provider is only allowed to be used for that purpose, nothing else.\n *\n * It's not a different object, but the field name should imply that this\n * object should not be used directly, except to pass to `deployStack`.\n */\n private readonly deployStackSdkProvider: SdkProvider;\n\n private readonly publisherCache = new Map<cdk_assets.AssetManifest, cdk_assets.AssetPublishing>();\n\n private _allowCrossAccountAssetPublishing: boolean | undefined;\n\n private readonly ioHelper: IoHelper;\n\n constructor(private readonly props: DeploymentsProps) {\n this.assetSdkProvider = props.sdkProvider;\n this.deployStackSdkProvider = props.sdkProvider;\n this.ioHelper = props.ioHelper;\n this.envs = new EnvironmentAccess(\n props.sdkProvider,\n props.toolkitStackName ?? DEFAULT_TOOLKIT_STACK_NAME,\n this.ioHelper,\n );\n }\n\n /**\n * Resolves the environment for a stack.\n */\n public async resolveEnvironment(stack: cxapi.CloudFormationStackArtifact): Promise<cxapi.Environment> {\n return this.envs.resolveStackEnvironment(stack);\n }\n\n public async readCurrentTemplateWithNestedStacks(\n rootStackArtifact: cxapi.CloudFormationStackArtifact,\n retrieveProcessedTemplate: boolean = false,\n ): Promise<RootTemplateWithNestedStacks> {\n const env = await this.envs.accessStackForLookupBestEffort(rootStackArtifact);\n return loadCurrentTemplateWithNestedStacks(rootStackArtifact, env.sdk, retrieveProcessedTemplate);\n }\n\n public async readCurrentTemplate(stackArtifact: cxapi.CloudFormationStackArtifact): Promise<Template> {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Reading existing template for stack ${stackArtifact.displayName}.`));\n const env = await this.envs.accessStackForLookupBestEffort(stackArtifact);\n return loadCurrentTemplate(stackArtifact, env.sdk);\n }\n\n public async resourceIdentifierSummaries(\n stackArtifact: cxapi.CloudFormationStackArtifact,\n ): Promise<ResourceIdentifierSummaries> {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Retrieving template summary for stack ${stackArtifact.displayName}.`));\n // Currently, needs to use `deploy-role` since it may need to read templates in the staging\n // bucket which have been encrypted with a KMS key (and lookup-role may not read encrypted things)\n const env = await this.envs.accessStackForReadOnlyStackOperations(stackArtifact);\n const cfn = env.sdk.cloudFormation();\n\n await uploadStackTemplateAssets(stackArtifact, this);\n\n // Upload the template, if necessary, before passing it to CFN\n const builder = new AssetManifestBuilder();\n const cfnParam = await makeBodyParameter(\n this.ioHelper,\n stackArtifact,\n env.resolvedEnvironment,\n builder,\n env.resources,\n );\n\n // If the `makeBodyParameter` before this added assets, make sure to publish them before\n // calling the API.\n const addedAssets = builder.toManifest(stackArtifact.assembly.directory);\n for (const entry of addedAssets.entries) {\n await this.buildSingleAsset('no-version-validation', addedAssets, entry, {\n stack: stackArtifact,\n });\n await this.publishSingleAsset(addedAssets, entry, {\n stack: stackArtifact,\n });\n }\n\n const response = await cfn.getTemplateSummary(cfnParam);\n if (!response.ResourceIdentifierSummaries) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg('GetTemplateSummary API call did not return \"ResourceIdentifierSummaries\"'));\n }\n return response.ResourceIdentifierSummaries ?? [];\n }\n\n public async deployStack(options: DeployStackOptions): Promise<DeployStackResult> {\n let deploymentMethod = options.deploymentMethod;\n if (options.changeSetName || options.execute !== undefined) {\n if (deploymentMethod) {\n throw new ToolkitError(\n \"You cannot supply both 'deploymentMethod' and 'changeSetName/execute'. Supply one or the other.\",\n );\n }\n deploymentMethod = {\n method: 'change-set',\n changeSetName: options.changeSetName,\n execute: options.execute,\n };\n }\n\n const env = await this.envs.accessStackForMutableStackOperations(options.stack);\n\n // Do a verification of the bootstrap stack version\n await this.validateBootstrapStackVersion(\n options.stack.stackName,\n options.stack.requiresBootstrapStackVersion,\n options.stack.bootstrapStackVersionSsmParameter,\n env.resources);\n\n const executionRoleArn = await env.replacePlaceholders(options.roleArn ?? options.stack.cloudFormationExecutionRoleArn);\n\n return deployStack({\n stack: options.stack,\n resolvedEnvironment: env.resolvedEnvironment,\n deployName: options.deployName,\n notificationArns: options.notificationArns,\n sdk: env.sdk,\n sdkProvider: this.deployStackSdkProvider,\n roleArn: executionRoleArn,\n reuseAssets: options.reuseAssets,\n envResources: env.resources,\n tags: options.tags,\n deploymentMethod,\n forceDeployment: options.forceDeployment,\n parameters: options.parameters,\n usePreviousParameters: options.usePreviousParameters,\n rollback: options.rollback,\n hotswap: options.hotswap,\n hotswapPropertyOverrides: options.hotswapPropertyOverrides,\n extraUserAgent: options.extraUserAgent,\n resourcesToImport: options.resourcesToImport,\n overrideTemplate: options.overrideTemplate,\n assetParallelism: options.assetParallelism,\n }, this.ioHelper);\n }\n\n public async rollbackStack(options: RollbackStackOptions): Promise<RollbackStackResult> {\n let resourcesToSkip: string[] = options.orphanLogicalIds ?? [];\n if (options.orphanFailedResources && resourcesToSkip.length > 0) {\n throw new ToolkitError('Cannot combine --force with --orphan');\n }\n\n const env = await this.envs.accessStackForMutableStackOperations(options.stack);\n\n if (options.validateBootstrapStackVersion ?? true) {\n // Do a verification of the bootstrap stack version\n await this.validateBootstrapStackVersion(\n options.stack.stackName,\n BOOTSTRAP_STACK_VERSION_FOR_ROLLBACK,\n options.stack.bootstrapStackVersionSsmParameter,\n env.resources);\n }\n\n const cfn = env.sdk.cloudFormation();\n const deployName = options.stack.stackName;\n\n // We loop in case of `--force` and the stack ends up in `CONTINUE_UPDATE_ROLLBACK`.\n let maxLoops = 10;\n while (maxLoops--) {\n const cloudFormationStack = await CloudFormationStack.lookup(cfn, deployName);\n const stackArn = cloudFormationStack.stackId;\n\n const executionRoleArn = await env.replacePlaceholders(options.roleArn ?? options.stack.cloudFormationExecutionRoleArn);\n\n switch (cloudFormationStack.stackStatus.rollbackChoice) {\n case RollbackChoice.NONE:\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_WARN.msg(`Stack ${deployName} does not need a rollback: ${cloudFormationStack.stackStatus}`));\n return { stackArn: cloudFormationStack.stackId, notInRollbackableState: true };\n\n case RollbackChoice.START_ROLLBACK:\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Initiating rollback of stack ${deployName}`));\n await cfn.rollbackStack({\n StackName: deployName,\n RoleARN: executionRoleArn,\n ClientRequestToken: randomUUID(),\n // Enabling this is just the better overall default, the only reason it isn't the upstream default is backwards compatibility\n RetainExceptOnCreate: true,\n });\n break;\n\n case RollbackChoice.CONTINUE_UPDATE_ROLLBACK:\n if (options.orphanFailedResources) {\n // Find the failed resources from the deployment and automatically skip them\n // (Using deployment log because we definitely have `DescribeStackEvents` permissions, and we might not have\n // `DescribeStackResources` permissions).\n const poller = new StackEventPoller(cfn, {\n stackName: deployName,\n stackStatuses: ['ROLLBACK_IN_PROGRESS', 'UPDATE_ROLLBACK_IN_PROGRESS'],\n });\n await poller.poll();\n resourcesToSkip = poller.resourceErrors\n .filter((r) => !r.isStackEvent && r.parentStackLogicalIds.length === 0)\n .map((r) => r.event.LogicalResourceId ?? '');\n }\n\n const skipDescription = resourcesToSkip.length > 0 ? ` (orphaning: ${resourcesToSkip.join(', ')})` : '';\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_WARN.msg(`Continuing rollback of stack ${deployName}${skipDescription}`));\n await cfn.continueUpdateRollback({\n StackName: deployName,\n ClientRequestToken: randomUUID(),\n RoleARN: executionRoleArn,\n ResourcesToSkip: resourcesToSkip,\n });\n break;\n\n case RollbackChoice.ROLLBACK_FAILED:\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_WARN.msg(\n `Stack ${deployName} failed creation and rollback. This state cannot be rolled back. You can recreate this stack by running 'cdk deploy'.`,\n ));\n return { stackArn, notInRollbackableState: true };\n\n default:\n throw new ToolkitError(`Unexpected rollback choice: ${cloudFormationStack.stackStatus.rollbackChoice}`);\n }\n\n const monitor = new StackActivityMonitor({\n cfn,\n stack: options.stack,\n stackName: deployName,\n ioHelper: this.ioHelper,\n });\n await monitor.start();\n\n let stackErrorMessage: string | undefined = undefined;\n let finalStackState = cloudFormationStack;\n try {\n const successStack = await stabilizeStack(cfn, this.ioHelper, deployName);\n\n // This shouldn't really happen, but catch it anyway. You never know.\n if (!successStack) {\n throw new ToolkitError('Stack deploy failed (the stack disappeared while we were rolling it back)');\n }\n finalStackState = successStack;\n\n const errors = monitor.errors.join(', ');\n if (errors) {\n stackErrorMessage = errors;\n }\n } catch (e: any) {\n stackErrorMessage = suffixWithErrors(formatErrorMessage(e), monitor.errors);\n } finally {\n await monitor.stop();\n }\n\n if (finalStackState.stackStatus.isRollbackSuccess || !stackErrorMessage) {\n return { stackArn, success: true };\n }\n\n // Either we need to ignore some resources to continue the rollback, or something went wrong\n if (finalStackState.stackStatus.rollbackChoice === RollbackChoice.CONTINUE_UPDATE_ROLLBACK && options.orphanFailedResources) {\n // Do another loop-de-loop\n continue;\n }\n\n throw new ToolkitError(\n `${stackErrorMessage} (fix problem and retry, or orphan these resources using --orphan or --force)`,\n );\n }\n throw new ToolkitError(\n \"Rollback did not finish after a large number of iterations; stopping because it looks like we're not making progress anymore. You can retry if rollback was progressing as expected.\",\n );\n }\n\n public async destroyStack(options: DestroyStackOptions) {\n const env = await this.envs.accessStackForMutableStackOperations(options.stack);\n const executionRoleArn = await env.replacePlaceholders(options.roleArn ?? options.stack.cloudFormationExecutionRoleArn);\n\n return destroyStack({\n sdk: env.sdk,\n roleArn: executionRoleArn,\n stack: options.stack,\n deployName: options.deployName,\n }, this.ioHelper);\n }\n\n public async stackExists(options: StackExistsOptions): Promise<boolean> {\n let env;\n if (options.tryLookupRole) {\n env = await this.envs.accessStackForLookupBestEffort(options.stack);\n } else {\n env = await this.envs.accessStackForReadOnlyStackOperations(options.stack);\n }\n const stack = await CloudFormationStack.lookup(env.sdk.cloudFormation(), options.deployName ?? options.stack.stackName);\n return stack.exists;\n }\n\n /**\n * Build a single asset from an asset manifest\n *\n * If an assert manifest artifact is given, the bootstrap stack version\n * will be validated according to the constraints in that manifest artifact.\n * If that is not necessary, `'no-version-validation'` can be passed.\n */\n // eslint-disable-next-line max-len\n public async buildSingleAsset(\n assetArtifact: cxapi.AssetManifestArtifact | 'no-version-validation',\n assetManifest: cdk_assets.AssetManifest,\n asset: cdk_assets.IManifestEntry,\n options: BuildStackAssetsOptions,\n ) {\n if (assetArtifact !== 'no-version-validation') {\n const env = await this.envs.accessStackForReadOnlyStackOperations(options.stack);\n await this.validateBootstrapStackVersion(\n options.stack.stackName,\n assetArtifact.requiresBootstrapStackVersion,\n assetArtifact.bootstrapStackVersionSsmParameter,\n env.resources);\n }\n\n const resolvedEnvironment = await this.envs.resolveStackEnvironment(options.stack);\n\n const publisher = this.cachedPublisher(assetManifest, resolvedEnvironment, options.stackName);\n await publisher.buildEntry(asset);\n if (publisher.hasFailures) {\n throw new ToolkitError(`Failed to build asset ${asset.displayName(false)}`);\n }\n }\n\n /**\n * Publish a single asset from an asset manifest\n */\n public async publishSingleAsset(\n assetManifest: cdk_assets.AssetManifest,\n asset: cdk_assets.IManifestEntry,\n options: PublishStackAssetsOptions,\n ) {\n const stackEnv = await this.envs.resolveStackEnvironment(options.stack);\n\n // No need to validate anymore, we already did that during build\n const publisher = this.cachedPublisher(assetManifest, stackEnv, options.stackName);\n await publisher.publishEntry(asset, {\n allowCrossAccount: await this.allowCrossAccountAssetPublishingForEnv(options.stack),\n force: options.forcePublish,\n });\n if (publisher.hasFailures) {\n throw new ToolkitError(`Failed to publish asset ${asset.displayName(true)}`);\n }\n }\n\n private async allowCrossAccountAssetPublishingForEnv(stack: cxapi.CloudFormationStackArtifact): Promise<boolean> {\n if (this._allowCrossAccountAssetPublishing === undefined) {\n const env = await this.envs.accessStackForReadOnlyStackOperations(stack);\n this._allowCrossAccountAssetPublishing = await determineAllowCrossAccountAssetPublishing(env.sdk, this.ioHelper, this.props.toolkitStackName);\n }\n return this._allowCrossAccountAssetPublishing;\n }\n\n /**\n * Return whether a single asset has been published already\n */\n public async isSingleAssetPublished(\n assetManifest: cdk_assets.AssetManifest,\n asset: cdk_assets.IManifestEntry,\n options: PublishStackAssetsOptions,\n ) {\n const stackEnv = await this.envs.resolveStackEnvironment(options.stack);\n const publisher = this.cachedPublisher(assetManifest, stackEnv, options.stackName);\n return publisher.isEntryPublished(asset);\n }\n\n /**\n * Validate that the bootstrap stack has the right version for this stack\n *\n * Call into envResources.validateVersion, but prepend the stack name in case of failure.\n */\n private async validateBootstrapStackVersion(\n stackName: string,\n requiresBootstrapStackVersion: number | undefined,\n bootstrapStackVersionSsmParameter: string | undefined,\n envResources: EnvironmentResources,\n ) {\n try {\n await envResources.validateVersion(requiresBootstrapStackVersion, bootstrapStackVersionSsmParameter);\n } catch (e: any) {\n throw new ToolkitError(`${stackName}: ${formatErrorMessage(e)}`);\n }\n }\n\n private cachedPublisher(assetManifest: cdk_assets.AssetManifest, env: cxapi.Environment, stackName?: string) {\n const existing = this.publisherCache.get(assetManifest);\n if (existing) {\n return existing;\n }\n const prefix = stackName ? `${chalk.bold(stackName)}: ` : '';\n const publisher = new cdk_assets.AssetPublishing(assetManifest, {\n // The AssetPublishing class takes care of role assuming etc, so it's okay to\n // give it a direct `SdkProvider`.\n aws: new PublishingAws(this.assetSdkProvider, env),\n progressListener: new ParallelSafeAssetProgress(prefix, this.ioHelper),\n });\n this.publisherCache.set(assetManifest, publisher);\n return publisher;\n }\n}\n\n/**\n * Asset progress that doesn't do anything with percentages (currently)\n */\nclass ParallelSafeAssetProgress extends BasePublishProgressListener {\n private readonly prefix: string;\n\n constructor(prefix: string, ioHelper: IoHelper) {\n super(ioHelper);\n this.prefix = prefix;\n }\n\n protected getMessage(type: cdk_assets.EventType, event: cdk_assets.IPublishProgress): string {\n return `${this.prefix}${type}: ${event.message}`;\n }\n}\n\nfunction suffixWithErrors(msg: string, errors?: string[]) {\n return errors && errors.length > 0 ? `${msg}: ${errors.join(', ')}` : msg;\n}\n", "import * as cxschema from '@aws-cdk/cloud-assembly-schema';\nimport { AssetManifest } from 'cdk-assets';\n\nexport class AssetManifestBuilder {\n private readonly manifest: cxschema.AssetManifest = {\n version: cxschema.Manifest.version(),\n files: {},\n dockerImages: {},\n };\n\n public addFileAsset(id: string, source: cxschema.FileSource, destination: cxschema.FileDestination) {\n this.manifest.files![id] = {\n source,\n destinations: {\n current: destination,\n },\n };\n }\n\n public addDockerImageAsset(id: string, source: cxschema.DockerImageSource, destination: cxschema.DockerImageDestination) {\n this.manifest.dockerImages![id] = {\n source,\n destinations: {\n current: destination,\n },\n };\n }\n\n public toManifest(directory: string): AssetManifest {\n return new AssetManifest(directory, this.manifest);\n }\n}\n", "import { type Environment, UNKNOWN_ACCOUNT, UNKNOWN_REGION } from '@aws-cdk/cx-api';\nimport type {\n ClientOptions,\n EventType,\n Account,\n AssetManifest,\n IAws,\n IECRClient,\n IPublishProgress,\n IPublishProgressListener,\n IS3Client,\n ISecretsManagerClient,\n} from 'cdk-assets';\nimport {\n AssetPublishing,\n} from 'cdk-assets';\nimport type { SDK } from '..';\nimport type { SdkProvider } from '../aws-auth';\nimport type { IoMessageMaker, IoHelper } from '../io/private';\nimport { IO } from '../io/private';\nimport { Mode } from '../plugin';\nimport { ToolkitError } from '../toolkit-error';\n\ninterface PublishAssetsOptions {\n /**\n * Whether to build/publish assets in parallel\n *\n * @default true To remain backward compatible.\n */\n readonly parallel?: boolean;\n\n /**\n * Whether cdk-assets is allowed to do cross account publishing.\n */\n readonly allowCrossAccount: boolean;\n}\n\n/**\n * Use cdk-assets to publish all assets in the given manifest.\n *\n * @deprecated used in legacy deployments only, should be migrated at some point\n */\nexport async function publishAssets(\n manifest: AssetManifest,\n sdk: SdkProvider,\n targetEnv: Environment,\n options: PublishAssetsOptions,\n ioHelper: IoHelper,\n) {\n // This shouldn't really happen (it's a programming error), but we don't have\n // the types here to guide us. Do an runtime validation to be super super sure.\n if (\n targetEnv.account === undefined ||\n targetEnv.account === UNKNOWN_ACCOUNT ||\n targetEnv.region === undefined ||\n targetEnv.account === UNKNOWN_REGION\n ) {\n throw new ToolkitError(`Asset publishing requires resolved account and region, got ${JSON.stringify(targetEnv)}`);\n }\n\n const publisher = new AssetPublishing(manifest, {\n aws: new PublishingAws(sdk, targetEnv),\n progressListener: new PublishingProgressListener(ioHelper),\n throwOnError: false,\n publishInParallel: options.parallel ?? true,\n buildAssets: true,\n publishAssets: true,\n quiet: false,\n });\n await publisher.publish({ allowCrossAccount: options.allowCrossAccount });\n if (publisher.hasFailures) {\n throw new ToolkitError('Failed to publish one or more assets. See the error messages above for more information.');\n }\n}\n\nexport class PublishingAws implements IAws {\n private sdkCache: Map<String, SDK> = new Map();\n\n constructor(\n /**\n * The base SDK to work with\n */\n private readonly aws: SdkProvider,\n\n /**\n * Environment where the stack we're deploying is going\n */\n private readonly targetEnv: Environment,\n ) {\n }\n\n public async discoverPartition(): Promise<string> {\n return (await this.aws.baseCredentialsPartition(this.targetEnv, Mode.ForWriting)) ?? 'aws';\n }\n\n public async discoverDefaultRegion(): Promise<string> {\n return this.targetEnv.region;\n }\n\n public async discoverCurrentAccount(): Promise<Account> {\n const account = await this.aws.defaultAccount();\n return (\n account ?? {\n accountId: '<unknown account>',\n partition: 'aws',\n }\n );\n }\n\n public async discoverTargetAccount(options: ClientOptions): Promise<Account> {\n return (await this.sdk(options)).currentAccount();\n }\n\n public async s3Client(options: ClientOptions): Promise<IS3Client> {\n return (await this.sdk(options)).s3();\n }\n\n public async ecrClient(options: ClientOptions): Promise<IECRClient> {\n return (await this.sdk(options)).ecr();\n }\n\n public async secretsManagerClient(options: ClientOptions): Promise<ISecretsManagerClient> {\n return (await this.sdk(options)).secretsManager();\n }\n\n /**\n * Get an SDK appropriate for the given client options\n */\n private async sdk(options: ClientOptions): Promise<SDK> {\n const env = {\n ...this.targetEnv,\n region: options.region ?? this.targetEnv.region, // Default: same region as the stack\n };\n\n const cacheKeyMap: any = {\n env, // region, name, account\n assumeRuleArn: options.assumeRoleArn,\n assumeRoleExternalId: options.assumeRoleExternalId,\n quiet: options.quiet,\n };\n\n if (options.assumeRoleAdditionalOptions) {\n cacheKeyMap.assumeRoleAdditionalOptions = options.assumeRoleAdditionalOptions;\n }\n\n const cacheKey = JSON.stringify(cacheKeyMap);\n\n const maybeSdk = this.sdkCache.get(cacheKey);\n if (maybeSdk) {\n return maybeSdk;\n }\n\n const sdk = (\n await this.aws.forEnvironment(\n env,\n Mode.ForWriting,\n {\n assumeRoleArn: options.assumeRoleArn,\n assumeRoleExternalId: options.assumeRoleExternalId,\n assumeRoleAdditionalOptions: options.assumeRoleAdditionalOptions,\n },\n options.quiet,\n )\n ).sdk;\n this.sdkCache.set(cacheKey, sdk);\n\n return sdk;\n }\n}\n\nconst EVENT_TO_MSG_MAKER: Record<EventType, IoMessageMaker<any> | false> = {\n build: IO.DEFAULT_TOOLKIT_DEBUG,\n cached: IO.DEFAULT_TOOLKIT_DEBUG,\n check: IO.DEFAULT_TOOLKIT_DEBUG,\n debug: IO.DEFAULT_TOOLKIT_DEBUG,\n fail: IO.DEFAULT_TOOLKIT_ERROR,\n found: IO.DEFAULT_TOOLKIT_DEBUG,\n start: IO.DEFAULT_TOOLKIT_INFO,\n success: IO.DEFAULT_TOOLKIT_INFO,\n upload: IO.DEFAULT_TOOLKIT_DEBUG,\n shell_open: IO.DEFAULT_TOOLKIT_DEBUG,\n shell_stderr: false,\n shell_stdout: false,\n shell_close: false,\n};\n\nexport abstract class BasePublishProgressListener implements IPublishProgressListener {\n protected readonly ioHelper: IoHelper;\n\n constructor(ioHelper: IoHelper) {\n this.ioHelper = ioHelper;\n }\n\n protected abstract getMessage(type: EventType, event: IPublishProgress): string;\n\n public onPublishEvent(type: EventType, event: IPublishProgress): void {\n const maker = EVENT_TO_MSG_MAKER[type];\n if (maker) {\n void this.ioHelper.notify(maker.msg(this.getMessage(type, event)));\n }\n }\n}\n\nclass PublishingProgressListener extends BasePublishProgressListener {\n protected getMessage(type: EventType, event: IPublishProgress): string {\n return `[${event.percentComplete}%] ${type}: ${event.message}`;\n }\n}\n", "import { format } from 'util';\nimport * as cxapi from '@aws-cdk/cx-api';\nimport { SSMPARAM_NO_INVALIDATE } from '@aws-cdk/cx-api';\nimport type {\n DescribeChangeSetCommandOutput,\n Parameter,\n ResourceToImport,\n Tag,\n} from '@aws-sdk/client-cloudformation';\nimport {\n ChangeSetStatus,\n} from '@aws-sdk/client-cloudformation';\nimport type { FileManifestEntry } from 'cdk-assets';\nimport { AssetManifest } from 'cdk-assets';\nimport { AssetManifestBuilder } from './asset-manifest-builder';\nimport type { Deployments } from './deployments';\nimport type { ICloudFormationClient, SdkProvider } from '../aws-auth';\nimport type { Template, TemplateBodyParameter, TemplateParameter } from '../cloudformation';\nimport { CloudFormationStack, makeBodyParameter } from '../cloudformation';\nimport { IO, type IoHelper } from '../io/private';\nimport type { ResourcesToImport } from '../resource-import';\nimport { ToolkitError } from '../toolkit-error';\n\n/**\n * Describe a changeset in CloudFormation, regardless of its current state.\n *\n * @param cfn a CloudFormation client\n * @param stackName the name of the Stack the ChangeSet belongs to\n * @param changeSetName the name of the ChangeSet\n * @param fetchAll if true, fetches all pages of the change set description.\n *\n * @returns CloudFormation information about the ChangeSet\n */\nasync function describeChangeSet(\n cfn: ICloudFormationClient,\n stackName: string,\n changeSetName: string,\n { fetchAll }: { fetchAll: boolean },\n): Promise<DescribeChangeSetCommandOutput> {\n const response = await cfn.describeChangeSet({\n StackName: stackName,\n ChangeSetName: changeSetName,\n });\n\n // If fetchAll is true, traverse all pages from the change set description.\n while (fetchAll && response.NextToken != null) {\n const nextPage = await cfn.describeChangeSet({\n StackName: stackName,\n ChangeSetName: response.ChangeSetId ?? changeSetName,\n NextToken: response.NextToken,\n });\n\n // Consolidate the changes\n if (nextPage.Changes != null) {\n response.Changes = response.Changes != null ? response.Changes.concat(nextPage.Changes) : nextPage.Changes;\n }\n\n // Forward the new NextToken\n response.NextToken = nextPage.NextToken;\n }\n\n return response;\n}\n\n/**\n * Waits for a function to return non-+undefined+ before returning.\n *\n * @param valueProvider a function that will return a value that is not +undefined+ once the wait should be over\n * @param timeout the time to wait between two calls to +valueProvider+\n *\n * @returns the value that was returned by +valueProvider+\n */\nasync function waitFor<T>(\n valueProvider: () => Promise<T | null | undefined>,\n timeout: number = 5000,\n): Promise<T | undefined> {\n while (true) {\n const result = await valueProvider();\n if (result === null) {\n return undefined;\n } else if (result !== undefined) {\n return result;\n }\n await new Promise((cb) => setTimeout(cb, timeout));\n }\n}\n\n/**\n * Waits for a ChangeSet to be available for triggering a StackUpdate.\n *\n * Will return a changeset that is either ready to be executed or has no changes.\n * Will throw in other cases.\n *\n * @param cfn a CloudFormation client\n * @param stackName the name of the Stack that the ChangeSet belongs to\n * @param changeSetName the name of the ChangeSet\n * @param fetchAll if true, fetches all pages of the ChangeSet before returning.\n *\n * @returns the CloudFormation description of the ChangeSet\n */\nexport async function waitForChangeSet(\n cfn: ICloudFormationClient,\n ioHelper: IoHelper,\n stackName: string,\n changeSetName: string,\n { fetchAll }: { fetchAll: boolean },\n): Promise<DescribeChangeSetCommandOutput> {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(format('Waiting for changeset %s on stack %s to finish creating...', changeSetName, stackName)));\n const ret = await waitFor(async () => {\n const description = await describeChangeSet(cfn, stackName, changeSetName, {\n fetchAll,\n });\n // The following doesn't use a switch because tsc will not allow fall-through, UNLESS it is allows\n // EVERYWHERE that uses this library directly or indirectly, which is undesirable.\n if (description.Status === 'CREATE_PENDING' || description.Status === 'CREATE_IN_PROGRESS') {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(format('Changeset %s on stack %s is still creating', changeSetName, stackName)));\n return undefined;\n }\n\n if (description.Status === ChangeSetStatus.CREATE_COMPLETE || changeSetHasNoChanges(description)) {\n return description;\n }\n\n // eslint-disable-next-line max-len\n throw new ToolkitError(\n `Failed to create ChangeSet ${changeSetName} on ${stackName}: ${description.Status || 'NO_STATUS'}, ${description.StatusReason || 'no reason provided'}`,\n );\n });\n\n if (!ret) {\n throw new ToolkitError('Change set took too long to be created; aborting');\n }\n\n return ret;\n}\n\nexport type PrepareChangeSetOptions = {\n stack: cxapi.CloudFormationStackArtifact;\n deployments: Deployments;\n uuid: string;\n willExecute: boolean;\n sdkProvider: SdkProvider;\n parameters: { [name: string]: string | undefined };\n resourcesToImport?: ResourcesToImport;\n}\n\nexport type CreateChangeSetOptions = {\n cfn: ICloudFormationClient;\n changeSetName: string;\n willExecute: boolean;\n exists: boolean;\n uuid: string;\n stack: cxapi.CloudFormationStackArtifact;\n bodyParameter: TemplateBodyParameter;\n parameters: { [name: string]: string | undefined };\n resourcesToImport?: ResourceToImport[];\n role?: string;\n};\n\n/**\n * Create a changeset for a diff operation\n */\nexport async function createDiffChangeSet(\n ioHelper: IoHelper,\n options: PrepareChangeSetOptions,\n): Promise<DescribeChangeSetCommandOutput | undefined> {\n // `options.stack` has been modified to include any nested stack templates directly inline with its own template, under a special `NestedTemplate` property.\n // Thus the parent template's Resources section contains the nested template's CDK metadata check, which uses Fn::Equals.\n // This causes CreateChangeSet to fail with `Template Error: Fn::Equals cannot be partially collapsed`.\n for (const resource of Object.values(options.stack.template.Resources ?? {})) {\n if ((resource as any).Type === 'AWS::CloudFormation::Stack') {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg('This stack contains one or more nested stacks, falling back to template-only diff...'));\n\n return undefined;\n }\n }\n\n return uploadBodyParameterAndCreateChangeSet(ioHelper, options);\n}\n\n/**\n * Returns all file entries from an AssetManifestArtifact that look like templates.\n *\n * This is used in the `uploadBodyParameterAndCreateChangeSet` function to find\n * all template asset files to build and publish.\n *\n * Returns a tuple of [AssetManifest, FileManifestEntry[]]\n */\nfunction templatesFromAssetManifestArtifact(\n artifact: cxapi.AssetManifestArtifact,\n): [AssetManifest, FileManifestEntry[]] {\n const assets: FileManifestEntry[] = [];\n const fileName = artifact.file;\n const assetManifest = AssetManifest.fromFile(fileName);\n\n assetManifest.entries.forEach((entry) => {\n if (entry.type === 'file') {\n const source = (entry as FileManifestEntry).source;\n if (source.path && source.path.endsWith('.template.json')) {\n assets.push(entry as FileManifestEntry);\n }\n }\n });\n return [assetManifest, assets];\n}\n\nasync function uploadBodyParameterAndCreateChangeSet(\n ioHelper: IoHelper,\n options: PrepareChangeSetOptions,\n): Promise<DescribeChangeSetCommandOutput | undefined> {\n try {\n await uploadStackTemplateAssets(options.stack, options.deployments);\n const env = await options.deployments.envs.accessStackForMutableStackOperations(options.stack);\n\n const bodyParameter = await makeBodyParameter(\n ioHelper,\n options.stack,\n env.resolvedEnvironment,\n new AssetManifestBuilder(),\n env.resources,\n );\n const cfn = env.sdk.cloudFormation();\n const exists = (await CloudFormationStack.lookup(cfn, options.stack.stackName, false)).exists;\n\n const executionRoleArn = await env.replacePlaceholders(options.stack.cloudFormationExecutionRoleArn);\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(\n 'Hold on while we create a read-only change set to get a diff with accurate replacement information (use --no-change-set to use a less accurate but faster template-only diff)\\n',\n ));\n\n return await createChangeSet(ioHelper, {\n cfn,\n changeSetName: 'cdk-diff-change-set',\n stack: options.stack,\n exists,\n uuid: options.uuid,\n willExecute: options.willExecute,\n bodyParameter,\n parameters: options.parameters,\n resourcesToImport: options.resourcesToImport,\n role: executionRoleArn,\n });\n } catch (e: any) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(String(e)));\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(\n 'Could not create a change set, will base the diff on template differences (run again with -v to see the reason)\\n',\n ));\n\n return undefined;\n }\n}\n\n/**\n * Uploads the assets that look like templates for this CloudFormation stack\n *\n * This is necessary for any CloudFormation call that needs the template, it may need\n * to be uploaded to an S3 bucket first. We have to follow the instructions in the\n * asset manifest, because technically that is the only place that knows about\n * bucket and assumed roles and such.\n */\nexport async function uploadStackTemplateAssets(stack: cxapi.CloudFormationStackArtifact, deployments: Deployments) {\n for (const artifact of stack.dependencies) {\n // Skip artifact if it is not an Asset Manifest Artifact\n if (!cxapi.AssetManifestArtifact.isAssetManifestArtifact(artifact)) {\n continue;\n }\n\n const [assetManifest, file_entries] = templatesFromAssetManifestArtifact(artifact);\n for (const entry of file_entries) {\n await deployments.buildSingleAsset(artifact, assetManifest, entry, {\n stack,\n });\n await deployments.publishSingleAsset(assetManifest, entry, {\n stack,\n });\n }\n }\n}\n\nexport async function createChangeSet(\n ioHelper: IoHelper,\n options: CreateChangeSetOptions,\n): Promise<DescribeChangeSetCommandOutput> {\n await cleanupOldChangeset(options.cfn, ioHelper, options.changeSetName, options.stack.stackName);\n\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Attempting to create ChangeSet with name ${options.changeSetName} for stack ${options.stack.stackName}`));\n\n const templateParams = TemplateParameters.fromTemplate(options.stack.template);\n const stackParams = templateParams.supplyAll(options.parameters);\n\n const changeSet = await options.cfn.createChangeSet({\n StackName: options.stack.stackName,\n ChangeSetName: options.changeSetName,\n ChangeSetType: options.resourcesToImport ? 'IMPORT' : options.exists ? 'UPDATE' : 'CREATE',\n Description: `CDK Changeset for diff ${options.uuid}`,\n ClientToken: `diff${options.uuid}`,\n TemplateURL: options.bodyParameter.TemplateURL,\n TemplateBody: options.bodyParameter.TemplateBody,\n Parameters: stackParams.apiParameters,\n ResourcesToImport: options.resourcesToImport,\n RoleARN: options.role,\n Tags: toCfnTags(options.stack.tags),\n Capabilities: ['CAPABILITY_IAM', 'CAPABILITY_NAMED_IAM', 'CAPABILITY_AUTO_EXPAND'],\n });\n\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(format('Initiated creation of changeset: %s; waiting for it to finish creating...', changeSet.Id)));\n // Fetching all pages if we'll execute, so we can have the correct change count when monitoring.\n const createdChangeSet = await waitForChangeSet(options.cfn, ioHelper, options.stack.stackName, options.changeSetName, {\n fetchAll: options.willExecute,\n });\n await cleanupOldChangeset(options.cfn, ioHelper, options.changeSetName, options.stack.stackName);\n\n return createdChangeSet;\n}\n\nfunction toCfnTags(tags: { [id: string]: string }): Tag[] {\n return Object.entries(tags).map(([k, v]) => ({\n Key: k,\n Value: v,\n }));\n}\n\nasync function cleanupOldChangeset(\n cfn: ICloudFormationClient,\n ioHelper: IoHelper,\n changeSetName: string,\n stackName: string,\n) {\n // Delete any existing change sets generated by CDK since change set names must be unique.\n // The delete request is successful as long as the stack exists (even if the change set does not exist).\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Removing existing change set with name ${changeSetName} if it exists`));\n await cfn.deleteChangeSet({\n StackName: stackName,\n ChangeSetName: changeSetName,\n });\n}\n\n/**\n * Return true if the given change set has no changes\n *\n * This must be determined from the status, not the 'Changes' array on the\n * object; the latter can be empty because no resources were changed, but if\n * there are changes to Outputs, the change set can still be executed.\n */\nexport function changeSetHasNoChanges(description: DescribeChangeSetCommandOutput) {\n const noChangeErrorPrefixes = [\n // Error message for a regular template\n \"The submitted information didn't contain changes.\",\n // Error message when a Transform is involved (see #10650)\n 'No updates are to be performed.',\n ];\n\n return (\n description.Status === 'FAILED' && noChangeErrorPrefixes.some((p) => (description.StatusReason ?? '').startsWith(p))\n );\n}\n\n/**\n * Waits for a CloudFormation stack to stabilize in a complete/available state\n * after a delete operation is issued.\n *\n * Fails if the stack is in a FAILED state. Will not fail if the stack was\n * already deleted.\n *\n * @param cfn a CloudFormation client\n * @param stackName the name of the stack to wait for after a delete\n *\n * @returns the CloudFormation description of the stabilized stack after the delete attempt\n */\nexport async function waitForStackDelete(\n cfn: ICloudFormationClient,\n ioHelper: IoHelper,\n stackName: string,\n): Promise<CloudFormationStack | undefined> {\n const stack = await stabilizeStack(cfn, ioHelper, stackName);\n if (!stack) {\n return undefined;\n }\n\n const status = stack.stackStatus;\n if (status.isFailure) {\n throw new ToolkitError(\n `The stack named ${stackName} is in a failed state. You may need to delete it from the AWS console : ${status}`,\n );\n } else if (status.isDeleted) {\n return undefined;\n }\n return stack;\n}\n\n/**\n * Waits for a CloudFormation stack to stabilize in a complete/available state\n * after an update/create operation is issued.\n *\n * Fails if the stack is in a FAILED state, ROLLBACK state, or DELETED state.\n *\n * @param cfn a CloudFormation client\n * @param stackName the name of the stack to wait for after an update\n *\n * @returns the CloudFormation description of the stabilized stack after the update attempt\n */\nexport async function waitForStackDeploy(\n cfn: ICloudFormationClient,\n ioHelper: IoHelper,\n stackName: string,\n): Promise<CloudFormationStack | undefined> {\n const stack = await stabilizeStack(cfn, ioHelper, stackName);\n if (!stack) {\n return undefined;\n }\n\n const status = stack.stackStatus;\n\n if (status.isCreationFailure) {\n throw new ToolkitError(\n `The stack named ${stackName} failed creation, it may need to be manually deleted from the AWS console: ${status}`,\n );\n } else if (!status.isDeploySuccess) {\n throw new ToolkitError(`The stack named ${stackName} failed to deploy: ${status}`);\n }\n\n return stack;\n}\n\n/**\n * Wait for a stack to become stable (no longer _IN_PROGRESS), returning it\n */\nexport async function stabilizeStack(\n cfn: ICloudFormationClient,\n ioHelper: IoHelper,\n stackName: string,\n) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(format('Waiting for stack %s to finish creating or updating...', stackName)));\n return waitFor(async () => {\n const stack = await CloudFormationStack.lookup(cfn, stackName);\n if (!stack.exists) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(format('Stack %s does not exist', stackName)));\n return null;\n }\n const status = stack.stackStatus;\n if (status.isInProgress) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(format('Stack %s has an ongoing operation in progress and is not stable (%s)', stackName, status)));\n return undefined;\n } else if (status.isReviewInProgress) {\n // This may happen if a stack creation operation is interrupted before the ChangeSet execution starts. Recovering\n // from this would requiring manual intervention (deleting or executing the pending ChangeSet), and failing to do\n // so will result in an endless wait here (the ChangeSet wont delete or execute itself). Instead of blocking\n // \"forever\" we proceed as if the stack was existing and stable. If there is a concurrent operation that just\n // hasn't finished proceeding just yet, either this operation or the concurrent one may fail due to the other one\n // having made progress. Which is fine. I guess.\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(format('Stack %s is in REVIEW_IN_PROGRESS state. Considering this is a stable status (%s)', stackName, status)));\n }\n\n return stack;\n });\n}\n\n/**\n * The set of (formal) parameters that have been declared in a template\n */\nexport class TemplateParameters {\n public static fromTemplate(template: Template) {\n return new TemplateParameters(template.Parameters || {});\n }\n\n constructor(private readonly params: Record<string, TemplateParameter>) {\n }\n\n /**\n * Calculate stack parameters to pass from the given desired parameter values\n *\n * Will throw if parameters without a Default value or a Previous value are not\n * supplied.\n */\n public supplyAll(updates: Record<string, string | undefined>): ParameterValues {\n return new ParameterValues(this.params, updates);\n }\n\n /**\n * From the template, the given desired values and the current values, calculate the changes to the stack parameters\n *\n * Will take into account parameters already set on the template (will emit\n * 'UsePreviousValue: true' for those unless the value is changed), and will\n * throw if parameters without a Default value or a Previous value are not\n * supplied.\n */\n public updateExisting(\n updates: Record<string, string | undefined>,\n previousValues: Record<string, string>,\n ): ParameterValues {\n return new ParameterValues(this.params, updates, previousValues);\n }\n}\n\n/**\n * The set of parameters we're going to pass to a Stack\n */\nexport class ParameterValues {\n public readonly values: Record<string, string> = {};\n public readonly apiParameters: Parameter[] = [];\n\n constructor(\n private readonly formalParams: Record<string, TemplateParameter>,\n updates: Record<string, string | undefined>,\n previousValues: Record<string, string> = {},\n ) {\n const missingRequired = new Array<string>();\n\n for (const [key, formalParam] of Object.entries(this.formalParams)) {\n // Check updates first, then use the previous value (if available), then use\n // the default (if available).\n //\n // If we don't find a parameter value using any of these methods, then that's an error.\n const updatedValue = updates[key];\n if (updatedValue !== undefined) {\n this.values[key] = updatedValue;\n this.apiParameters.push({\n ParameterKey: key,\n ParameterValue: updates[key],\n });\n continue;\n }\n\n if (key in previousValues) {\n this.values[key] = previousValues[key];\n this.apiParameters.push({ ParameterKey: key, UsePreviousValue: true });\n continue;\n }\n\n if (formalParam.Default !== undefined) {\n this.values[key] = formalParam.Default;\n continue;\n }\n\n // Oh no\n missingRequired.push(key);\n }\n\n if (missingRequired.length > 0) {\n throw new ToolkitError(`The following CloudFormation Parameters are missing a value: ${missingRequired.join(', ')}`);\n }\n\n // Just append all supplied overrides that aren't really expected (this\n // will fail CFN but maybe people made typos that they want to be notified\n // of)\n const unknownParam = ([key, _]: [string, any]) => this.formalParams[key] === undefined;\n const hasValue = ([_, value]: [string, any]) => !!value;\n for (const [key, value] of Object.entries(updates).filter(unknownParam).filter(hasValue)) {\n this.values[key] = value!;\n this.apiParameters.push({ ParameterKey: key, ParameterValue: value });\n }\n }\n\n /**\n * Whether this set of parameter updates will change the actual stack values\n */\n public hasChanges(currentValues: Record<string, string>): ParameterChanges {\n // If any of the parameters are SSM parameters, deploying must always happen\n // because we can't predict what the values will be. We will allow some\n // parameters to opt out of this check by having a magic string in their description.\n if (\n Object.values(this.formalParams).some(\n (p) => p.Type.startsWith('AWS::SSM::Parameter::') && !p.Description?.includes(SSMPARAM_NO_INVALIDATE),\n )\n ) {\n return 'ssm';\n }\n\n // Otherwise we're dirty if:\n // - any of the existing values are removed, or changed\n if (Object.entries(currentValues).some(([key, value]) => !(key in this.values) || value !== this.values[key])) {\n return true;\n }\n\n // - any of the values we're setting are new\n if (Object.keys(this.values).some((key) => !(key in currentValues))) {\n return true;\n }\n\n return false;\n }\n}\n\nexport type ParameterChanges = boolean | 'ssm';\n", "import { ArtifactMetadataEntryType, type MetadataEntry } from '@aws-cdk/cloud-assembly-schema';\nimport type { CloudFormationStackArtifact } from '@aws-cdk/cx-api';\n\n/**\n * Metadata entry for a resource within a CloudFormation stack\n */\nexport interface ResourceMetadata {\n /**\n * The resource's metadata as declared in the cloud assembly\n */\n readonly entry: MetadataEntry;\n /**\n * The construct path of the resource\n */\n readonly constructPath: string;\n}\n\n/**\n * Attempts to read metadata for resources from a CloudFormation stack artifact\n *\n * @param stack The CloudFormation stack to read from\n * @param logicalId The logical ID of the resource to read\n *\n * @returns The resource metadata, or undefined if the resource was not found\n */\nexport function resourceMetadata(stack: CloudFormationStackArtifact, logicalId: string): ResourceMetadata | undefined {\n const metadata = stack.manifest?.metadata;\n if (!metadata) {\n return undefined;\n }\n\n for (const path of Object.keys(metadata)) {\n const entry = metadata[path]\n .filter((e) => e.type === ArtifactMetadataEntryType.LOGICAL_ID)\n .find((e) => e.data === logicalId);\n if (entry) {\n return {\n entry,\n constructPath: simplifyConstructPath(path, stack.stackName),\n };\n }\n }\n return undefined;\n}\n\nfunction simplifyConstructPath(path: string, stackName: string) {\n path = path.replace(/\\/Resource$/, '');\n path = path.replace(/^\\//, ''); // remove \"/\" prefix\n\n // remove \"<stack-name>/\" prefix\n if (stackName) {\n if (path.startsWith(stackName + '/')) {\n path = path.slice(stackName.length + 1);\n }\n }\n return path;\n}\n", "import type { CloudFormationStackArtifact } from '@aws-cdk/cx-api';\nimport type { Export, ListExportsCommandOutput, StackResourceSummary } from '@aws-sdk/client-cloudformation';\nimport type { SDK } from '../aws-auth';\nimport { ToolkitError } from '../toolkit-error';\nimport type { NestedStackTemplates } from './nested-stack-helpers';\nimport type { Template } from './stack-helpers';\nimport type { ResourceMetadata } from '../resource-metadata';\nimport { resourceMetadata } from '../resource-metadata';\n\nexport interface ListStackResources {\n listStackResources(): Promise<StackResourceSummary[]>;\n}\n\nexport class LazyListStackResources implements ListStackResources {\n private stackResources: Promise<StackResourceSummary[]> | undefined;\n\n constructor(\n private readonly sdk: SDK,\n private readonly stackName: string,\n ) {\n }\n\n public async listStackResources(): Promise<StackResourceSummary[]> {\n if (this.stackResources === undefined) {\n this.stackResources = this.sdk.cloudFormation().listStackResources({\n StackName: this.stackName,\n });\n }\n return this.stackResources;\n }\n}\n\nexport interface LookupExport {\n lookupExport(name: string): Promise<Export | undefined>;\n}\n\nexport class LookupExportError extends Error {\n}\n\nexport class LazyLookupExport implements LookupExport {\n private cachedExports: { [name: string]: Export } = {};\n\n constructor(private readonly sdk: SDK) {\n }\n\n async lookupExport(name: string): Promise<Export | undefined> {\n if (this.cachedExports[name]) {\n return this.cachedExports[name];\n }\n\n for await (const cfnExport of this.listExports()) {\n if (!cfnExport.Name) {\n continue; // ignore any result that omits a name\n }\n this.cachedExports[cfnExport.Name] = cfnExport;\n\n if (cfnExport.Name === name) {\n return cfnExport;\n }\n }\n\n return undefined; // export not found\n }\n\n // TODO: Paginate\n private async *listExports() {\n let nextToken: string | undefined = undefined;\n while (true) {\n const response: ListExportsCommandOutput = await this.sdk.cloudFormation().listExports({ NextToken: nextToken });\n for (const cfnExport of response.Exports ?? []) {\n yield cfnExport;\n }\n\n if (!response.NextToken) {\n return;\n }\n nextToken = response.NextToken;\n }\n }\n}\n\nexport class CfnEvaluationException extends Error {\n}\n\nexport interface ResourceDefinition {\n readonly LogicalId: string;\n readonly Type: string;\n readonly Properties: { [p: string]: any };\n}\n\nexport interface EvaluateCloudFormationTemplateProps {\n readonly stackArtifact: CloudFormationStackArtifact;\n readonly stackName?: string;\n readonly template?: Template;\n readonly parameters: { [parameterName: string]: string };\n readonly account: string;\n readonly region: string;\n readonly partition: string;\n readonly sdk: SDK;\n readonly nestedStacks?: {\n [nestedStackLogicalId: string]: NestedStackTemplates;\n };\n}\n\nexport class EvaluateCloudFormationTemplate {\n public readonly stackArtifact: CloudFormationStackArtifact;\n private readonly stackName: string;\n private readonly template: Template;\n private readonly context: { [k: string]: any };\n private readonly account: string;\n private readonly region: string;\n private readonly partition: string;\n private readonly sdk: SDK;\n private readonly nestedStacks: {\n [nestedStackLogicalId: string]: NestedStackTemplates;\n };\n private readonly stackResources: ListStackResources;\n private readonly lookupExport: LookupExport;\n\n private cachedUrlSuffix: string | undefined;\n\n constructor(props: EvaluateCloudFormationTemplateProps) {\n this.stackArtifact = props.stackArtifact;\n this.stackName = props.stackName ?? props.stackArtifact.stackName;\n this.template = props.template ?? props.stackArtifact.template;\n this.context = {\n 'AWS::AccountId': props.account,\n 'AWS::Region': props.region,\n 'AWS::Partition': props.partition,\n ...props.parameters,\n };\n this.account = props.account;\n this.region = props.region;\n this.partition = props.partition;\n this.sdk = props.sdk;\n\n // We need names of nested stack so we can evaluate cross stack references\n this.nestedStacks = props.nestedStacks ?? {};\n\n // The current resources of the Stack.\n // We need them to figure out the physical name of a resource in case it wasn't specified by the user.\n // We fetch it lazily, to save a service call, in case all hotswapped resources have their physical names set.\n this.stackResources = new LazyListStackResources(this.sdk, this.stackName);\n\n // CloudFormation Exports lookup to be able to resolve Fn::ImportValue intrinsics in template\n this.lookupExport = new LazyLookupExport(this.sdk);\n }\n\n // clones current EvaluateCloudFormationTemplate object, but updates the stack name\n public async createNestedEvaluateCloudFormationTemplate(\n stackName: string,\n nestedTemplate: Template,\n nestedStackParameters: { [parameterName: string]: any },\n ) {\n const evaluatedParams = await this.evaluateCfnExpression(nestedStackParameters);\n return new EvaluateCloudFormationTemplate({\n stackArtifact: this.stackArtifact,\n stackName,\n template: nestedTemplate,\n parameters: evaluatedParams,\n account: this.account,\n region: this.region,\n partition: this.partition,\n sdk: this.sdk,\n nestedStacks: this.nestedStacks,\n });\n }\n\n public async establishResourcePhysicalName(\n logicalId: string,\n physicalNameInCfnTemplate: any,\n ): Promise<string | undefined> {\n if (physicalNameInCfnTemplate != null) {\n try {\n return await this.evaluateCfnExpression(physicalNameInCfnTemplate);\n } catch (e) {\n // If we can't evaluate the resource's name CloudFormation expression,\n // just look it up in the currently deployed Stack\n if (!(e instanceof CfnEvaluationException)) {\n throw e;\n }\n }\n }\n return this.findPhysicalNameFor(logicalId);\n }\n\n public async findPhysicalNameFor(logicalId: string): Promise<string | undefined> {\n const stackResources = await this.stackResources.listStackResources();\n return stackResources.find((sr) => sr.LogicalResourceId === logicalId)?.PhysicalResourceId;\n }\n\n public async findLogicalIdForPhysicalName(physicalName: string): Promise<string | undefined> {\n const stackResources = await this.stackResources.listStackResources();\n return stackResources.find((sr) => sr.PhysicalResourceId === physicalName)?.LogicalResourceId;\n }\n\n public findReferencesTo(logicalId: string): Array<ResourceDefinition> {\n const ret = new Array<ResourceDefinition>();\n for (const [resourceLogicalId, resourceDef] of Object.entries(this.template?.Resources ?? {})) {\n if (logicalId !== resourceLogicalId && this.references(logicalId, resourceDef)) {\n ret.push({\n ...(resourceDef as any),\n LogicalId: resourceLogicalId,\n });\n }\n }\n return ret;\n }\n\n public async evaluateCfnExpression(cfnExpression: any): Promise<any> {\n const self = this;\n /**\n * Evaluates CloudFormation intrinsic functions\n *\n * Note that supported intrinsic functions are documented in README.md -- please update\n * list of supported functions when adding new evaluations\n *\n * See: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference.html\n */\n class CfnIntrinsics {\n public evaluateIntrinsic(intrinsic: Intrinsic): any {\n const intrinsicFunc = (this as any)[intrinsic.name];\n if (!intrinsicFunc) {\n throw new CfnEvaluationException(`CloudFormation function ${intrinsic.name} is not supported`);\n }\n\n const argsAsArray = Array.isArray(intrinsic.args) ? intrinsic.args : [intrinsic.args];\n\n return intrinsicFunc.apply(this, argsAsArray);\n }\n\n async 'Fn::Join'(separator: string, args: any[]): Promise<string> {\n const evaluatedArgs = await self.evaluateCfnExpression(args);\n return evaluatedArgs.join(separator);\n }\n\n async 'Fn::Split'(separator: string, args: any): Promise<string> {\n const evaluatedArgs = await self.evaluateCfnExpression(args);\n return evaluatedArgs.split(separator);\n }\n\n async 'Fn::Select'(index: number, args: any[]): Promise<string> {\n const evaluatedArgs = await self.evaluateCfnExpression(args);\n return evaluatedArgs[index];\n }\n\n async Ref(logicalId: string): Promise<string> {\n const refTarget = await self.findRefTarget(logicalId);\n if (refTarget) {\n return refTarget;\n } else {\n throw new CfnEvaluationException(`Parameter or resource '${logicalId}' could not be found for evaluation`);\n }\n }\n\n async 'Fn::GetAtt'(logicalId: string, attributeName: string): Promise<string> {\n // ToDo handle the 'logicalId.attributeName' form of Fn::GetAtt\n const attrValue = await self.findGetAttTarget(logicalId, attributeName);\n if (attrValue) {\n return attrValue;\n } else {\n throw new CfnEvaluationException(\n `Attribute '${attributeName}' of resource '${logicalId}' could not be found for evaluation`,\n );\n }\n }\n\n async 'Fn::Sub'(template: string, explicitPlaceholders?: { [variable: string]: string }): Promise<string> {\n const placeholders = explicitPlaceholders ? await self.evaluateCfnExpression(explicitPlaceholders) : {};\n\n return asyncGlobalReplace(template, /\\${([^}]*)}/g, (key) => {\n if (key in placeholders) {\n return placeholders[key];\n } else {\n const splitKey = key.split('.');\n return splitKey.length === 1 ? this.Ref(key) : this['Fn::GetAtt'](splitKey[0], splitKey.slice(1).join('.'));\n }\n });\n }\n\n async 'Fn::ImportValue'(name: string): Promise<string> {\n const exported = await self.lookupExport.lookupExport(name);\n if (!exported) {\n throw new CfnEvaluationException(`Export '${name}' could not be found for evaluation`);\n }\n if (!exported.Value) {\n throw new CfnEvaluationException(`Export '${name}' exists without a value`);\n }\n return exported.Value;\n }\n }\n\n if (cfnExpression == null) {\n return cfnExpression;\n }\n\n if (Array.isArray(cfnExpression)) {\n // Small arrays in practice\n // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism\n return Promise.all(cfnExpression.map((expr) => this.evaluateCfnExpression(expr)));\n }\n\n if (typeof cfnExpression === 'object') {\n const intrinsic = this.parseIntrinsic(cfnExpression);\n if (intrinsic) {\n return new CfnIntrinsics().evaluateIntrinsic(intrinsic);\n } else {\n const ret: { [key: string]: any } = {};\n for (const [key, val] of Object.entries(cfnExpression)) {\n ret[key] = await this.evaluateCfnExpression(val);\n }\n return ret;\n }\n }\n\n return cfnExpression;\n }\n\n public getResourceProperty(logicalId: string, propertyName: string): any {\n return this.template.Resources?.[logicalId]?.Properties?.[propertyName];\n }\n\n public metadataFor(logicalId: string): ResourceMetadata | undefined {\n return resourceMetadata(this.stackArtifact, logicalId);\n }\n\n private references(logicalId: string, templateElement: any): boolean {\n if (typeof templateElement === 'string') {\n return logicalId === templateElement;\n }\n\n if (templateElement == null) {\n return false;\n }\n\n if (Array.isArray(templateElement)) {\n return templateElement.some((el) => this.references(logicalId, el));\n }\n\n if (typeof templateElement === 'object') {\n return Object.values(templateElement).some((el) => this.references(logicalId, el));\n }\n\n return false;\n }\n\n private parseIntrinsic(x: any): Intrinsic | undefined {\n const keys = Object.keys(x);\n if (keys.length === 1 && (keys[0].startsWith('Fn::') || keys[0] === 'Ref')) {\n return {\n name: keys[0],\n args: x[keys[0]],\n };\n }\n return undefined;\n }\n\n private async findRefTarget(logicalId: string): Promise<string | undefined> {\n // first, check to see if the Ref is a Parameter who's value we have\n if (logicalId === 'AWS::URLSuffix') {\n if (!this.cachedUrlSuffix) {\n this.cachedUrlSuffix = await this.sdk.getUrlSuffix(this.region);\n }\n\n return this.cachedUrlSuffix;\n }\n\n // Try finding the ref in the passed in parameters\n const parameterTarget = this.context[logicalId];\n if (parameterTarget) {\n return parameterTarget;\n }\n\n // If not in the passed in parameters, see if there is a default value in the template parameter that was not passed in\n const defaultParameterValue = this.template.Parameters?.[logicalId]?.Default;\n if (defaultParameterValue) {\n return defaultParameterValue;\n }\n\n // if it's not a Parameter, we need to search in the current Stack resources\n return this.findGetAttTarget(logicalId);\n }\n\n private async findGetAttTarget(logicalId: string, attribute?: string): Promise<string | undefined> {\n // Handle case where the attribute is referencing a stack output (used in nested stacks to share parameters)\n // See https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/quickref-cloudformation.html#w2ab1c17c23c19b5\n if (logicalId === 'Outputs' && attribute) {\n return this.evaluateCfnExpression(this.template.Outputs[attribute]?.Value);\n }\n\n const stackResources = await this.stackResources.listStackResources();\n const foundResource = stackResources.find((sr) => sr.LogicalResourceId === logicalId);\n if (!foundResource) {\n return undefined;\n }\n\n if (foundResource.ResourceType == 'AWS::CloudFormation::Stack' && attribute?.startsWith('Outputs.')) {\n const dependantStack = this.findNestedStack(logicalId, this.nestedStacks);\n if (!dependantStack || !dependantStack.physicalName) {\n // this is a newly created nested stack and cannot be hotswapped\n return undefined;\n }\n const evaluateCfnTemplate = await this.createNestedEvaluateCloudFormationTemplate(\n dependantStack.physicalName,\n dependantStack.generatedTemplate,\n dependantStack.generatedTemplate.Parameters!,\n );\n\n // Split Outputs.<refName> into 'Outputs' and '<refName>' and recursively call evaluate\n return evaluateCfnTemplate.evaluateCfnExpression({\n 'Fn::GetAtt': attribute.split(/\\.(.*)/s),\n });\n }\n // now, we need to format the appropriate identifier depending on the resource type,\n // and the requested attribute name\n return this.formatResourceAttribute(foundResource, attribute);\n }\n\n private findNestedStack(\n logicalId: string,\n nestedStacks: {\n [nestedStackLogicalId: string]: NestedStackTemplates;\n },\n ): NestedStackTemplates | undefined {\n for (const nestedStackLogicalId of Object.keys(nestedStacks)) {\n if (nestedStackLogicalId === logicalId) {\n return nestedStacks[nestedStackLogicalId];\n }\n const checkInNestedChildStacks = this.findNestedStack(\n logicalId,\n nestedStacks[nestedStackLogicalId].nestedStackTemplates,\n );\n if (checkInNestedChildStacks) return checkInNestedChildStacks;\n }\n return undefined;\n }\n\n private formatResourceAttribute(resource: StackResourceSummary, attribute: string | undefined): string | undefined {\n const physicalId = resource.PhysicalResourceId;\n\n // no attribute means Ref expression, for which we use the physical ID directly\n if (!attribute) {\n return physicalId;\n }\n\n const resourceTypeFormats = RESOURCE_TYPE_ATTRIBUTES_FORMATS[resource.ResourceType!];\n if (!resourceTypeFormats) {\n throw new CfnEvaluationException(\n `We don't support attributes of the '${resource.ResourceType}' resource. This is a CDK limitation. ` +\n 'Please report it at https://github.com/aws/aws-cdk/issues/new/choose',\n );\n }\n const attributeFmtFunc = resourceTypeFormats[attribute];\n if (!attributeFmtFunc) {\n throw new CfnEvaluationException(\n `We don't support the '${attribute}' attribute of the '${resource.ResourceType}' resource. This is a CDK limitation. ` +\n 'Please report it at https://github.com/aws/aws-cdk/issues/new/choose',\n );\n }\n const service = this.getServiceOfResource(resource);\n const resourceTypeArnPart = this.getResourceTypeArnPartOfResource(resource);\n return attributeFmtFunc({\n partition: this.partition,\n service,\n region: this.region,\n account: this.account,\n resourceType: resourceTypeArnPart,\n resourceName: physicalId!,\n });\n }\n\n private getServiceOfResource(resource: StackResourceSummary): string {\n return resource.ResourceType!.split('::')[1].toLowerCase();\n }\n\n private getResourceTypeArnPartOfResource(resource: StackResourceSummary): string {\n const resourceType = resource.ResourceType!;\n const specialCaseResourceType = RESOURCE_TYPE_SPECIAL_NAMES[resourceType]?.resourceType;\n return specialCaseResourceType\n ? specialCaseResourceType\n : // this is the default case\n resourceType.split('::')[2].toLowerCase();\n }\n}\n\ninterface ArnParts {\n readonly partition: string;\n readonly service: string;\n readonly region: string;\n readonly account: string;\n readonly resourceType: string;\n readonly resourceName: string;\n}\n\n/**\n * Usually, we deduce the names of the service and the resource type used to format the ARN from the CloudFormation resource type.\n * For a CFN type like AWS::Service::ResourceType, the second segment becomes the service name, and the third the resource type\n * (after converting both of them to lowercase).\n * However, some resource types break this simple convention, and we need to special-case them.\n * This map is for storing those cases.\n */\nconst RESOURCE_TYPE_SPECIAL_NAMES: {\n [type: string]: { resourceType: string };\n} = {\n 'AWS::Events::EventBus': {\n resourceType: 'event-bus',\n },\n};\n\nconst RESOURCE_TYPE_ATTRIBUTES_FORMATS: {\n [type: string]: { [attribute: string]: (parts: ArnParts) => string };\n} = {\n 'AWS::IAM::Role': { Arn: iamArnFmt },\n 'AWS::IAM::User': { Arn: iamArnFmt },\n 'AWS::IAM::Group': { Arn: iamArnFmt },\n 'AWS::S3::Bucket': { Arn: s3ArnFmt },\n 'AWS::Lambda::Function': { Arn: stdColonResourceArnFmt },\n 'AWS::Events::EventBus': {\n Arn: stdSlashResourceArnFmt,\n // the name attribute of the EventBus is the same as the Ref\n Name: (parts) => parts.resourceName,\n },\n 'AWS::DynamoDB::Table': { Arn: stdSlashResourceArnFmt },\n 'AWS::AppSync::GraphQLApi': { ApiId: appsyncGraphQlApiApiIdFmt },\n 'AWS::AppSync::FunctionConfiguration': {\n FunctionId: appsyncGraphQlFunctionIDFmt,\n },\n 'AWS::AppSync::DataSource': { Name: appsyncGraphQlDataSourceNameFmt },\n 'AWS::KMS::Key': { Arn: stdSlashResourceArnFmt },\n};\n\nfunction iamArnFmt(parts: ArnParts): string {\n // we skip region for IAM resources\n return `arn:${parts.partition}:${parts.service}::${parts.account}:${parts.resourceType}/${parts.resourceName}`;\n}\n\nfunction s3ArnFmt(parts: ArnParts): string {\n // we skip account, region and resourceType for S3 resources\n return `arn:${parts.partition}:${parts.service}:::${parts.resourceName}`;\n}\n\nfunction stdColonResourceArnFmt(parts: ArnParts): string {\n // this is a standard format for ARNs like: arn:aws:service:region:account:resourceType:resourceName\n return `arn:${parts.partition}:${parts.service}:${parts.region}:${parts.account}:${parts.resourceType}:${parts.resourceName}`;\n}\n\nfunction stdSlashResourceArnFmt(parts: ArnParts): string {\n // this is a standard format for ARNs like: arn:aws:service:region:account:resourceType/resourceName\n return `arn:${parts.partition}:${parts.service}:${parts.region}:${parts.account}:${parts.resourceType}/${parts.resourceName}`;\n}\n\nfunction appsyncGraphQlApiApiIdFmt(parts: ArnParts): string {\n // arn:aws:appsync:us-east-1:111111111111:apis/<apiId>\n return parts.resourceName.split('/')[1];\n}\n\nfunction appsyncGraphQlFunctionIDFmt(parts: ArnParts): string {\n // arn:aws:appsync:us-east-1:111111111111:apis/<apiId>/functions/<functionId>\n return parts.resourceName.split('/')[3];\n}\n\nfunction appsyncGraphQlDataSourceNameFmt(parts: ArnParts): string {\n // arn:aws:appsync:us-east-1:111111111111:apis/<apiId>/datasources/<name>\n return parts.resourceName.split('/')[3];\n}\n\ninterface Intrinsic {\n readonly name: string;\n readonly args: any;\n}\n\nasync function asyncGlobalReplace(str: string, regex: RegExp, cb: (x: string) => Promise<string>): Promise<string> {\n if (!regex.global) {\n throw new ToolkitError('Regex must be created with /g flag');\n }\n\n const ret = new Array<string>();\n let start = 0;\n while (true) {\n const match = regex.exec(str);\n if (!match) {\n break;\n }\n\n ret.push(str.substring(start, match.index));\n ret.push(await cb(match[1]));\n\n start = regex.lastIndex;\n }\n ret.push(str.slice(start));\n\n return ret.join('');\n}\n", "import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport * as util from 'node:util';\nimport { type CloudFormationStackArtifact, type Environment, EnvironmentPlaceholders } from '@aws-cdk/cx-api';\nimport { HeadObjectCommand, S3Client } from '@aws-sdk/client-s3';\nimport { getEndpointFromInstructions } from '@smithy/middleware-endpoint';\nimport * as chalk from 'chalk';\nimport { contentHash, toYAML } from '../../util';\nimport type { AssetManifestBuilder } from '../deployments';\nimport type { EnvironmentResources } from '../environment';\nimport { IO, type IoHelper } from '../io/private';\nimport { ToolkitError } from '../toolkit-error';\n\nexport type TemplateBodyParameter = {\n TemplateBody?: string;\n TemplateURL?: string;\n};\n\nconst LARGE_TEMPLATE_SIZE_KB = 50;\n\n/**\n * Prepares the body parameter for +CreateChangeSet+.\n *\n * If the template is small enough to be inlined into the API call, just return\n * it immediately.\n *\n * Otherwise, add it to the asset manifest to get uploaded to the staging\n * bucket and return its coordinates. If there is no staging bucket, an error\n * is thrown.\n *\n * @param stack the synthesized stack that provides the CloudFormation template\n * @param toolkitInfo information about the toolkit stack\n */\nexport async function makeBodyParameter(\n ioHelper: IoHelper,\n stack: CloudFormationStackArtifact,\n resolvedEnvironment: Environment,\n assetManifest: AssetManifestBuilder,\n resources: EnvironmentResources,\n overrideTemplate?: any,\n): Promise<TemplateBodyParameter> {\n // If the template has already been uploaded to S3, just use it from there.\n if (stack.stackTemplateAssetObjectUrl && !overrideTemplate) {\n return {\n TemplateURL: await restUrlFromManifest(stack.stackTemplateAssetObjectUrl, resolvedEnvironment),\n };\n }\n\n // Otherwise, pass via API call (if small) or upload here (if large)\n const templateJson = toYAML(overrideTemplate ?? stack.template);\n\n if (templateJson.length <= LARGE_TEMPLATE_SIZE_KB * 1024) {\n return { TemplateBody: templateJson };\n }\n\n const toolkitInfo = await resources.lookupToolkit();\n if (!toolkitInfo.found) {\n await ioHelper.notify(\n IO.DEFAULT_TOOLKIT_ERROR.msg(util.format(\n `The template for stack \"${stack.displayName}\" is ${Math.round(templateJson.length / 1024)}KiB. ` +\n `Templates larger than ${LARGE_TEMPLATE_SIZE_KB}KiB must be uploaded to S3.\\n` +\n 'Run the following command in order to setup an S3 bucket in this environment, and then re-deploy:\\n\\n',\n chalk.blue(`\\t$ cdk bootstrap ${resolvedEnvironment.name}\\n`),\n )),\n );\n\n throw new ToolkitError('Template too large to deploy (\"cdk bootstrap\" is required)');\n }\n\n const templateHash = contentHash(templateJson);\n const key = `cdk/${stack.id}/${templateHash}.yml`;\n\n let templateFile = stack.templateFile;\n if (overrideTemplate) {\n // Add a variant of this template\n templateFile = `${stack.templateFile}-${templateHash}.yaml`;\n const templateFilePath = path.join(stack.assembly.directory, templateFile);\n await fs.writeFile(templateFilePath, templateJson, { encoding: 'utf-8' });\n }\n\n assetManifest.addFileAsset(\n templateHash,\n {\n path: templateFile,\n },\n {\n bucketName: toolkitInfo.bucketName,\n objectKey: key,\n },\n );\n\n const templateURL = `${toolkitInfo.bucketUrl}/${key}`;\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Storing template in S3 at: ${templateURL}`));\n return { TemplateURL: templateURL };\n}\n\n/**\n * Format an S3 URL in the manifest for use with CloudFormation\n *\n * Replaces environment placeholders (which this field may contain),\n * and reformats s3://.../... urls into S3 REST URLs (which CloudFormation\n * expects)\n */\nasync function restUrlFromManifest(url: string, environment: Environment): Promise<string> {\n const doNotUseMarker = '**DONOTUSE**';\n const region = environment.region;\n // This URL may contain placeholders, so still substitute those.\n url = EnvironmentPlaceholders.replace(url, {\n accountId: environment.account,\n region,\n partition: doNotUseMarker,\n });\n\n // Yes, this is extremely crude, but we don't actually need this so I'm not inclined to spend\n // a lot of effort trying to thread the right value to this location.\n if (url.indexOf(doNotUseMarker) > -1) {\n throw new ToolkitError(\"Cannot use '${AWS::Partition}' in the 'stackTemplateAssetObjectUrl' field\");\n }\n\n const s3Url = url.match(/s3:\\/\\/([^/]+)\\/(.*)$/);\n if (!s3Url) {\n return url;\n }\n\n // We need to pass an 'https://s3.REGION.amazonaws.com[.cn]/bucket/object' URL to CloudFormation, but we\n // got an 's3://bucket/object' URL instead. Construct the rest API URL here.\n const bucketName = s3Url[1];\n const objectKey = s3Url[2];\n\n // SDK v3 no longer allows for getting endpoints from only region.\n // A command and client config must now be provided.\n const s3 = new S3Client({ region });\n const endpoint = await getEndpointFromInstructions({}, HeadObjectCommand, {\n ...s3.config,\n });\n endpoint.url.hostname;\n\n return `${endpoint.url.origin}/${bucketName}/${objectKey}`;\n}\n", "import * as path from 'path';\nimport type { CloudFormationStackArtifact } from '@aws-cdk/cx-api';\nimport * as fs from 'fs-extra';\nimport { formatErrorMessage } from '../../util';\nimport type { SDK } from '../aws-auth';\nimport { LazyListStackResources, type ListStackResources } from './evaluate-cloudformation-template';\nimport { CloudFormationStack, type Template } from './stack-helpers';\n\nexport interface RootTemplateWithNestedStacks {\n readonly deployedRootTemplate: Template;\n readonly nestedStacks: {\n [nestedStackLogicalId: string]: NestedStackTemplates;\n };\n}\n\n/**\n * Reads the currently deployed template and all of its nested stack templates from CloudFormation.\n */\nexport async function loadCurrentTemplateWithNestedStacks(\n rootStackArtifact: CloudFormationStackArtifact,\n sdk: SDK,\n retrieveProcessedTemplate: boolean = false,\n): Promise<RootTemplateWithNestedStacks> {\n const deployedRootTemplate = await loadCurrentTemplate(rootStackArtifact, sdk, retrieveProcessedTemplate);\n const nestedStacks = await loadNestedStacks(rootStackArtifact, sdk, {\n generatedTemplate: rootStackArtifact.template,\n deployedTemplate: deployedRootTemplate,\n deployedStackName: rootStackArtifact.stackName,\n });\n\n return {\n deployedRootTemplate,\n nestedStacks,\n };\n}\n\n/**\n * Returns the currently deployed template from CloudFormation that corresponds to `stackArtifact`.\n */\nexport async function loadCurrentTemplate(\n stackArtifact: CloudFormationStackArtifact,\n sdk: SDK,\n retrieveProcessedTemplate: boolean = false,\n): Promise<Template> {\n return loadCurrentStackTemplate(stackArtifact.stackName, sdk, retrieveProcessedTemplate);\n}\n\nasync function loadCurrentStackTemplate(\n stackName: string,\n sdk: SDK,\n retrieveProcessedTemplate: boolean = false,\n): Promise<Template> {\n const cfn = sdk.cloudFormation();\n const stack = await CloudFormationStack.lookup(cfn, stackName, retrieveProcessedTemplate);\n return stack.template();\n}\n\nasync function loadNestedStacks(\n rootStackArtifact: CloudFormationStackArtifact,\n sdk: SDK,\n parentTemplates: StackTemplates,\n): Promise<{ [nestedStackLogicalId: string]: NestedStackTemplates }> {\n const listStackResources = parentTemplates.deployedStackName\n ? new LazyListStackResources(sdk, parentTemplates.deployedStackName)\n : undefined;\n const nestedStacks: { [nestedStackLogicalId: string]: NestedStackTemplates } = {};\n for (const [nestedStackLogicalId, generatedNestedStackResource] of Object.entries(\n parentTemplates.generatedTemplate.Resources ?? {},\n )) {\n if (!isCdkManagedNestedStack(generatedNestedStackResource)) {\n continue;\n }\n\n const assetPath = generatedNestedStackResource.Metadata['aws:asset:path'];\n const nestedStackTemplates = await getNestedStackTemplates(\n rootStackArtifact,\n assetPath,\n nestedStackLogicalId,\n listStackResources,\n sdk,\n );\n\n nestedStacks[nestedStackLogicalId] = {\n deployedTemplate: nestedStackTemplates.deployedTemplate,\n generatedTemplate: nestedStackTemplates.generatedTemplate,\n physicalName: nestedStackTemplates.deployedStackName,\n nestedStackTemplates: await loadNestedStacks(rootStackArtifact, sdk, nestedStackTemplates),\n };\n }\n\n return nestedStacks;\n}\n\nasync function getNestedStackTemplates(\n rootStackArtifact: CloudFormationStackArtifact,\n nestedTemplateAssetPath: string,\n nestedStackLogicalId: string,\n listStackResources: ListStackResources | undefined,\n sdk: SDK,\n): Promise<StackTemplates> {\n const nestedTemplatePath = path.join(rootStackArtifact.assembly.directory, nestedTemplateAssetPath);\n\n // CFN generates the nested stack name in the form `ParentStackName-NestedStackLogicalID-SomeHashWeCan'tCompute,\n // the arn is of the form: arn:aws:cloudformation:region:123456789012:stack/NestedStackName/AnotherHashWeDon'tNeed\n // so we get the ARN and manually extract the name.\n const nestedStackArn = await getNestedStackArn(nestedStackLogicalId, listStackResources);\n const deployedStackName = nestedStackArn?.slice(nestedStackArn.indexOf('/') + 1, nestedStackArn.lastIndexOf('/'));\n\n return {\n generatedTemplate: JSON.parse(fs.readFileSync(nestedTemplatePath, 'utf-8')),\n deployedTemplate: deployedStackName ? await loadCurrentStackTemplate(deployedStackName, sdk) : {},\n deployedStackName,\n };\n}\n\nasync function getNestedStackArn(\n nestedStackLogicalId: string,\n listStackResources?: ListStackResources,\n): Promise<string | undefined> {\n try {\n const stackResources = await listStackResources?.listStackResources();\n return stackResources?.find((sr) => sr.LogicalResourceId === nestedStackLogicalId)?.PhysicalResourceId;\n } catch (e: any) {\n if (formatErrorMessage(e).startsWith('Stack with id ') && formatErrorMessage(e).endsWith(' does not exist')) {\n return;\n }\n throw e;\n }\n}\n\nfunction isCdkManagedNestedStack(stackResource: any): stackResource is NestedStackResource {\n return (\n stackResource.Type === 'AWS::CloudFormation::Stack' &&\n stackResource.Metadata &&\n stackResource.Metadata['aws:asset:path']\n );\n}\n\nexport interface NestedStackTemplates {\n readonly physicalName: string | undefined;\n readonly deployedTemplate: Template;\n readonly generatedTemplate: Template;\n readonly nestedStackTemplates: {\n [nestedStackLogicalId: string]: NestedStackTemplates;\n };\n}\n\ninterface StackTemplates {\n readonly generatedTemplate: any;\n readonly deployedTemplate: any;\n readonly deployedStackName: string | undefined;\n}\n\ninterface NestedStackResource {\n readonly Metadata: { 'aws:asset:path': string };\n readonly Properties: any;\n}\n", "import * as util from 'util';\nimport type { CloudFormationStackArtifact } from '@aws-cdk/cx-api';\nimport type { StackActivity } from '@aws-cdk/tmp-toolkit-helpers';\nimport * as uuid from 'uuid';\nimport { StackEventPoller } from './stack-event-poller';\nimport { StackProgressMonitor } from './stack-progress-monitor';\nimport { stackEventHasErrorMessage } from '../../util';\nimport type { ICloudFormationClient } from '../aws-auth';\nimport { IO, type IoHelper } from '../io/private';\nimport { resourceMetadata } from '../resource-metadata/resource-metadata';\n\nexport interface StackActivityMonitorProps {\n /**\n * The CloudFormation client\n */\n readonly cfn: ICloudFormationClient;\n\n /**\n * The IoHelper used for messaging\n */\n readonly ioHelper: IoHelper;\n\n /**\n * The stack artifact that is getting deployed\n */\n readonly stack: CloudFormationStackArtifact;\n\n /**\n * The name of the Stack that is getting deployed\n */\n readonly stackName: string;\n\n /**\n * Total number of resources to update\n *\n * Used to calculate a progress bar.\n *\n * @default - No progress reporting.\n */\n readonly resourcesTotal?: number;\n\n /**\n * Creation time of the change set\n *\n * This will be used to filter events, only showing those from after the change\n * set creation time.\n *\n * It is recommended to use this, otherwise the filtering will be subject\n * to clock drift between local and cloud machines.\n *\n * @default - local machine's current time\n */\n readonly changeSetCreationTime?: Date;\n\n /**\n * Time to wait between fetching new activities.\n *\n * Must wait a reasonable amount of time between polls, since we need to consider CloudFormation API limits\n *\n * @default 2_000\n */\n readonly pollingInterval?: number;\n}\n\nexport class StackActivityMonitor {\n /**\n * The poller used to read stack events\n */\n private readonly poller: StackEventPoller;\n\n /**\n * Fetch new activity every 1 second\n * Printers can decide to update a view less frequently if desired\n */\n private readonly pollingInterval: number;\n\n public readonly errors: string[] = [];\n\n private monitorId?: string;\n\n private readonly progressMonitor: StackProgressMonitor;\n\n /**\n * Current tick timer\n */\n private tickTimer?: ReturnType<typeof setTimeout>;\n\n /**\n * Set to the activity of reading the current events\n */\n private readPromise?: Promise<any>;\n\n private readonly ioHelper: IoHelper;\n private readonly stackName: string;\n private readonly stack: CloudFormationStackArtifact;\n\n constructor({\n cfn,\n ioHelper,\n stack,\n stackName,\n resourcesTotal,\n changeSetCreationTime,\n pollingInterval = 2_000,\n }: StackActivityMonitorProps) {\n this.ioHelper = ioHelper;\n this.stack = stack;\n this.stackName = stackName;\n\n this.progressMonitor = new StackProgressMonitor(resourcesTotal);\n this.pollingInterval = pollingInterval;\n this.poller = new StackEventPoller(cfn, {\n stackName,\n startTime: changeSetCreationTime?.getTime() ?? Date.now(),\n });\n }\n\n public async start() {\n this.monitorId = uuid.v4();\n await this.ioHelper.notify(IO.CDK_TOOLKIT_I5501.msg(`Deploying ${this.stackName}`, {\n deployment: this.monitorId,\n stack: this.stack,\n stackName: this.stackName,\n resourcesTotal: this.progressMonitor.total,\n }));\n this.scheduleNextTick();\n return this;\n }\n\n public async stop() {\n const oldMonitorId = this.monitorId!;\n this.monitorId = undefined;\n if (this.tickTimer) {\n clearTimeout(this.tickTimer);\n }\n\n // Do a final poll for all events. This is to handle the situation where DescribeStackStatus\n // already returned an error, but the monitor hasn't seen all the events yet and we'd end\n // up not printing the failure reason to users.\n await this.finalPollToEnd(oldMonitorId);\n\n await this.ioHelper.notify(IO.CDK_TOOLKIT_I5503.msg(`Completed ${this.stackName}`, {\n deployment: oldMonitorId,\n stack: this.stack,\n stackName: this.stackName,\n resourcesTotal: this.progressMonitor.total,\n }));\n }\n\n private scheduleNextTick() {\n if (!this.monitorId) {\n return;\n }\n\n this.tickTimer = setTimeout(() => void this.tick(), this.pollingInterval);\n }\n\n private async tick() {\n if (!this.monitorId) {\n return;\n }\n\n try {\n this.readPromise = this.readNewEvents(this.monitorId);\n await this.readPromise;\n this.readPromise = undefined;\n\n // We might have been stop()ped while the network call was in progress.\n if (!this.monitorId) {\n return;\n }\n } catch (e) {\n await this.ioHelper.notify(IO.CDK_TOOLKIT_E5500.msg(\n util.format('Error occurred while monitoring stack: %s', e),\n { error: e as any },\n ));\n }\n this.scheduleNextTick();\n }\n\n private findMetadataFor(logicalId: string | undefined) {\n const metadata = this.stack.manifest?.metadata;\n if (!logicalId || !metadata) {\n return undefined;\n }\n return resourceMetadata(this.stack, logicalId);\n }\n\n /**\n * Reads all new events from the stack history\n *\n * The events are returned in reverse chronological order; we continue to the next page if we\n * see a next page and the last event in the page is new to us (and within the time window).\n * haven't seen the final event\n */\n private async readNewEvents(monitorId: string): Promise<void> {\n const pollEvents = await this.poller.poll();\n\n for (const resourceEvent of pollEvents) {\n this.progressMonitor.process(resourceEvent.event);\n\n const activity: StackActivity = {\n deployment: monitorId,\n event: resourceEvent.event,\n metadata: this.findMetadataFor(resourceEvent.event.LogicalResourceId),\n progress: this.progressMonitor.progress,\n };\n\n this.checkForErrors(activity);\n await this.ioHelper.notify(IO.CDK_TOOLKIT_I5502.msg(this.formatActivity(activity, true), activity));\n }\n }\n\n /**\n * Perform a final poll to the end and flush out all events to the printer\n *\n * Finish any poll currently in progress, then do a final one until we've\n * reached the last page.\n */\n private async finalPollToEnd(monitorId: string) {\n // If we were doing a poll, finish that first. It was started before\n // the moment we were sure we weren't going to get any new events anymore\n // so we need to do a new one anyway. Need to wait for this one though\n // because our state is single-threaded.\n if (this.readPromise) {\n await this.readPromise;\n }\n\n await this.readNewEvents(monitorId);\n }\n\n /**\n * Formats a stack activity into a basic string\n */\n private formatActivity(activity: StackActivity, progress: boolean): string {\n const event = activity.event;\n const metadata = activity.metadata;\n\n const resourceName = metadata ? metadata.constructPath : event.LogicalResourceId || '';\n const logicalId = resourceName !== event.LogicalResourceId ? `(${event.LogicalResourceId}) ` : '';\n\n return util.format(\n '%s | %s%s | %s | %s | %s %s%s%s',\n event.StackName,\n progress !== false ? `${activity.progress.formatted} | ` : '',\n new Date(event.Timestamp!).toLocaleTimeString(),\n event.ResourceStatus || '',\n event.ResourceType,\n resourceName,\n logicalId,\n event.ResourceStatusReason ? event.ResourceStatusReason : '',\n metadata?.entry.trace ? `\\n\\t${metadata.entry.trace.join('\\n\\t\\\\_ ')}` : '',\n );\n }\n\n private checkForErrors(activity: StackActivity) {\n if (stackEventHasErrorMessage(activity.event.ResourceStatus ?? '')) {\n const isCancelled = (activity.event.ResourceStatusReason ?? '').indexOf('cancelled') > -1;\n\n // Cancelled is not an interesting failure reason, nor is the stack message (stack\n // message will just say something like \"stack failed to update\")\n if (!isCancelled && activity.event.StackName !== activity.event.LogicalResourceId) {\n this.errors.push(activity.event.ResourceStatusReason ?? '');\n }\n }\n }\n}\n", "import type { StackEvent } from '@aws-sdk/client-cloudformation';\nimport { formatErrorMessage } from '../../util';\nimport type { ICloudFormationClient } from '../aws-auth';\n\nexport interface StackEventPollerProps {\n /**\n * The stack to poll\n */\n readonly stackName: string;\n\n /**\n * IDs of parent stacks of this resource, in case of resources in nested stacks\n */\n readonly parentStackLogicalIds?: string[];\n\n /**\n * Timestamp for the oldest event we're interested in\n *\n * @default - Read all events\n */\n readonly startTime?: number;\n\n /**\n * Stop reading when we see the stack entering this status\n *\n * Should be something like `CREATE_IN_PROGRESS`, `UPDATE_IN_PROGRESS`,\n * `DELETE_IN_PROGRESS, `ROLLBACK_IN_PROGRESS`.\n *\n * @default - Read all events\n */\n readonly stackStatuses?: string[];\n}\n\nexport interface ResourceEvent {\n /**\n * The Stack Event as received from CloudFormation\n */\n readonly event: StackEvent;\n\n /**\n * IDs of parent stacks of the resource, in case of resources in nested stacks\n */\n readonly parentStackLogicalIds: string[];\n\n /**\n * Whether this event regards the root stack\n *\n * @default false\n */\n readonly isStackEvent?: boolean;\n}\n\nexport class StackEventPoller {\n public readonly events: ResourceEvent[] = [];\n public complete: boolean = false;\n\n private readonly eventIds = new Set<string>();\n private readonly nestedStackPollers: Record<string, StackEventPoller> = {};\n\n constructor(\n private readonly cfn: ICloudFormationClient,\n private readonly props: StackEventPollerProps,\n ) {\n }\n\n /**\n * From all accumulated events, return only the errors\n */\n public get resourceErrors(): ResourceEvent[] {\n return this.events.filter((e) => e.event.ResourceStatus?.endsWith('_FAILED') && !e.isStackEvent);\n }\n\n /**\n * Poll for new stack events\n *\n * Will not return events older than events indicated by the constructor filters.\n *\n * Recurses into nested stacks, and returns events old-to-new.\n */\n public async poll(): Promise<ResourceEvent[]> {\n const events: ResourceEvent[] = await this.doPoll();\n\n // Also poll all nested stacks we're currently tracking\n for (const [logicalId, poller] of Object.entries(this.nestedStackPollers)) {\n events.push(...(await poller.poll()));\n if (poller.complete) {\n delete this.nestedStackPollers[logicalId];\n }\n }\n\n // Return what we have so far\n events.sort((a, b) => a.event.Timestamp!.valueOf() - b.event.Timestamp!.valueOf());\n this.events.push(...events);\n return events;\n }\n\n private async doPoll(): Promise<ResourceEvent[]> {\n const events: ResourceEvent[] = [];\n try {\n let nextToken: string | undefined;\n let finished = false;\n\n while (!finished) {\n const page = await this.cfn.describeStackEvents({ StackName: this.props.stackName, NextToken: nextToken });\n for (const event of page?.StackEvents ?? []) {\n // Event from before we were interested in 'em\n if (this.props.startTime !== undefined && event.Timestamp!.valueOf() < this.props.startTime) {\n return events;\n }\n\n // Already seen this one\n if (this.eventIds.has(event.EventId!)) {\n return events;\n }\n this.eventIds.add(event.EventId!);\n\n // The events for the stack itself are also included next to events about resources; we can test for them in this way.\n const isParentStackEvent = event.PhysicalResourceId === event.StackId;\n\n if (isParentStackEvent && this.props.stackStatuses?.includes(event.ResourceStatus ?? '')) {\n return events;\n }\n\n // Fresh event\n const resEvent: ResourceEvent = {\n event: event,\n parentStackLogicalIds: this.props.parentStackLogicalIds ?? [],\n isStackEvent: isParentStackEvent,\n };\n events.push(resEvent);\n\n if (\n !isParentStackEvent &&\n event.ResourceType === 'AWS::CloudFormation::Stack' &&\n isStackBeginOperationState(event.ResourceStatus)\n ) {\n // If the event is not for `this` stack and has a physical resource Id, recursively call for events in the nested stack\n this.trackNestedStack(event, [...(this.props.parentStackLogicalIds ?? []), event.LogicalResourceId ?? '']);\n }\n\n if (isParentStackEvent && isStackTerminalState(event.ResourceStatus)) {\n this.complete = true;\n }\n }\n\n nextToken = page?.NextToken;\n if (nextToken === undefined) {\n finished = true;\n }\n }\n } catch (e: any) {\n if (!(e.name === 'ValidationError' && formatErrorMessage(e) === `Stack [${this.props.stackName}] does not exist`)) {\n throw e;\n }\n }\n\n return events;\n }\n\n /**\n * On the CREATE_IN_PROGRESS, UPDATE_IN_PROGRESS, DELETE_IN_PROGRESS event of a nested stack, poll the nested stack updates\n */\n private trackNestedStack(event: StackEvent, parentStackLogicalIds: string[]) {\n const logicalId = event.LogicalResourceId;\n const physicalResourceId = event.PhysicalResourceId;\n\n // The CREATE_IN_PROGRESS event for a Nested Stack is emitted twice; first without a PhysicalResourceId\n // and then with. Ignore this event if we don't have that property yet.\n //\n // (At this point, I also don't trust that logicalId is always going to be there so validate that as well)\n if (!logicalId || !physicalResourceId) {\n return;\n }\n\n if (!this.nestedStackPollers[logicalId]) {\n this.nestedStackPollers[logicalId] = new StackEventPoller(this.cfn, {\n stackName: physicalResourceId,\n parentStackLogicalIds: parentStackLogicalIds,\n startTime: event.Timestamp!.valueOf(),\n });\n }\n }\n}\n\nfunction isStackBeginOperationState(state: string | undefined) {\n return [\n 'CREATE_IN_PROGRESS',\n 'UPDATE_IN_PROGRESS',\n 'DELETE_IN_PROGRESS',\n 'UPDATE_ROLLBACK_IN_PROGRESS',\n 'ROLLBACK_IN_PROGRESS',\n ].includes(state ?? '');\n}\n\nfunction isStackTerminalState(state: string | undefined) {\n return !(state ?? '').endsWith('_IN_PROGRESS');\n}\n", "import * as util from 'util';\nimport type { StackProgress } from '@aws-cdk/tmp-toolkit-helpers';\nimport type { StackEvent } from '@aws-sdk/client-cloudformation';\nimport { padLeft } from '../../util';\n\n/**\n * Monitors stack progress.s\n */\nexport class StackProgressMonitor {\n /**\n * Previous completion state observed by logical ID\n *\n * We use this to detect that if we see a DELETE_COMPLETE after a\n * CREATE_COMPLETE, it's actually a rollback and we should DECREASE\n * resourcesDone instead of increase it\n */\n private resourcesPrevCompleteState: Record<string, string> = {};\n\n /**\n * Count of resources that have reported a _COMPLETE status\n */\n private resourcesDone: number = 0;\n\n /**\n * How many digits we need to represent the total count (for lining up the status reporting)\n */\n private readonly resourceDigits: number = 0;\n\n /**\n * Number of expected resources in the monitor.\n */\n private readonly resourcesTotal?: number;\n\n constructor(resourcesTotal?: number) {\n // +1 because the stack also emits a \"COMPLETE\" event at the end, and that wasn't\n // counted yet. This makes it line up with the amount of events we expect.\n this.resourcesTotal = resourcesTotal ? resourcesTotal + 1 : undefined;\n\n // How many digits does this number take to represent?\n this.resourceDigits = this.resourcesTotal ? Math.ceil(Math.log10(this.resourcesTotal)) : 0;\n }\n\n /**\n * Report the stack progress\n */\n public get progress(): StackProgress {\n return {\n total: this.total,\n completed: this.completed,\n formatted: this.formatted,\n };\n }\n\n /**\n * The total number of progress monitored resources.\n */\n public get total(): number | undefined {\n return this.resourcesTotal;\n }\n\n /**\n * The number of completed resources.\n */\n public get completed(): number {\n return this.resourcesDone;\n }\n\n /**\n * Report the current progress as a [34/42] string, or just [34] if the total is unknown\n */\n public get formatted(): string {\n if (this.resourcesTotal == null) {\n // Don't have total, show simple count and hope the human knows\n return padLeft(3, util.format('%s', this.resourcesDone)); // max 500 resources\n }\n\n return util.format(\n '%s/%s',\n padLeft(this.resourceDigits, this.resourcesDone.toString()),\n padLeft(this.resourceDigits, this.resourcesTotal.toString()),\n );\n }\n\n /**\n * Process as stack event and update the progress state.\n */\n public process(event: StackEvent): void {\n const status = event.ResourceStatus;\n if (!status || !event.LogicalResourceId) {\n return;\n }\n\n if (status.endsWith('_COMPLETE_CLEANUP_IN_PROGRESS')) {\n this.resourcesDone++;\n }\n\n if (status.endsWith('_COMPLETE')) {\n const prevState = this.resourcesPrevCompleteState[event.LogicalResourceId];\n if (!prevState) {\n this.resourcesDone++;\n } else {\n // If we completed this before and we're completing it AGAIN, means we're rolling back.\n // Protect against silly underflow.\n this.resourcesDone--;\n if (this.resourcesDone < 0) {\n this.resourcesDone = 0;\n }\n }\n this.resourcesPrevCompleteState[event.LogicalResourceId] = status;\n }\n }\n}\n", "import { type Stack, StackStatus as _StackStatus } from '@aws-sdk/client-cloudformation';\n\n/**\n * A utility class to inspect CloudFormation stack statuses.\n *\n * @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-describing-stacks.html\n */\nexport class StackStatus {\n public static fromStackDescription(description: Stack) {\n return new StackStatus(description.StackStatus!, description.StackStatusReason);\n }\n\n constructor(\n public readonly name: string,\n public readonly reason?: string,\n ) {\n }\n\n get isCreationFailure(): boolean {\n return this.name === _StackStatus.ROLLBACK_COMPLETE || this.name === _StackStatus.ROLLBACK_FAILED;\n }\n\n get isDeleted(): boolean {\n return this.name.startsWith('DELETE_');\n }\n\n get isFailure(): boolean {\n return this.name.endsWith('FAILED');\n }\n\n get isInProgress(): boolean {\n return this.name.endsWith('_IN_PROGRESS') && !this.isReviewInProgress;\n }\n\n get isReviewInProgress(): boolean {\n return this.name === _StackStatus.REVIEW_IN_PROGRESS;\n }\n\n get isNotFound(): boolean {\n return this.name === 'NOT_FOUND';\n }\n\n get isDeploySuccess(): boolean {\n return (\n !this.isNotFound &&\n (this.name === _StackStatus.CREATE_COMPLETE ||\n this.name === _StackStatus.UPDATE_COMPLETE ||\n this.name === _StackStatus.IMPORT_COMPLETE)\n );\n }\n\n get isRollbackSuccess(): boolean {\n return this.name === _StackStatus.ROLLBACK_COMPLETE || this.name === _StackStatus.UPDATE_ROLLBACK_COMPLETE;\n }\n\n /**\n * Whether the stack is in a paused state due to `--no-rollback`.\n *\n * The possible actions here are retrying a new `--no-rollback` deployment, or initiating a rollback.\n */\n get rollbackChoice(): RollbackChoice {\n switch (this.name) {\n case _StackStatus.CREATE_FAILED:\n case _StackStatus.UPDATE_FAILED:\n return RollbackChoice.START_ROLLBACK;\n case _StackStatus.UPDATE_ROLLBACK_FAILED:\n return RollbackChoice.CONTINUE_UPDATE_ROLLBACK;\n case _StackStatus.ROLLBACK_FAILED:\n // Unfortunately there is no option to continue a failed rollback without\n // a stable target state.\n return RollbackChoice.ROLLBACK_FAILED;\n default:\n return RollbackChoice.NONE;\n }\n }\n\n get isRollbackable(): boolean {\n return [RollbackChoice.START_ROLLBACK, RollbackChoice.CONTINUE_UPDATE_ROLLBACK].includes(this.rollbackChoice);\n }\n\n public toString(): string {\n return this.name + (this.reason ? ` (${this.reason})` : '');\n }\n}\n\n/**\n * Describe the current rollback options for this state\n */\nexport enum RollbackChoice {\n START_ROLLBACK,\n CONTINUE_UPDATE_ROLLBACK,\n /**\n * A sign that stack creation AND its rollback have failed.\n *\n * There is no way to recover from this, other than recreating the stack.\n */\n ROLLBACK_FAILED,\n NONE,\n}\n", "import type { Stack, Tag } from '@aws-sdk/client-cloudformation';\nimport { formatErrorMessage, deserializeStructure } from '../../util';\nimport type { ICloudFormationClient } from '../aws-auth';\nimport { StackStatus } from '../stack-events';\nimport { ToolkitError } from '../toolkit-error';\n\nexport interface Template {\n Parameters?: Record<string, TemplateParameter>;\n [section: string]: any;\n}\n\nexport interface TemplateParameter {\n Type: string;\n Default?: any;\n Description?: string;\n [key: string]: any;\n}\n\n/**\n * Represents an (existing) Stack in CloudFormation\n *\n * Bundle and cache some information that we need during deployment (so we don't have to make\n * repeated calls to CloudFormation).\n */\nexport class CloudFormationStack {\n public static async lookup(\n cfn: ICloudFormationClient,\n stackName: string,\n retrieveProcessedTemplate: boolean = false,\n ): Promise<CloudFormationStack> {\n try {\n const response = await cfn.describeStacks({ StackName: stackName });\n return new CloudFormationStack(cfn, stackName, response.Stacks && response.Stacks[0], retrieveProcessedTemplate);\n } catch (e: any) {\n if (e.name === 'ValidationError' && formatErrorMessage(e) === `Stack with id ${stackName} does not exist`) {\n return new CloudFormationStack(cfn, stackName, undefined);\n }\n throw e;\n }\n }\n\n /**\n * Return a copy of the given stack that does not exist\n *\n * It's a little silly that it needs arguments to do that, but there we go.\n */\n public static doesNotExist(cfn: ICloudFormationClient, stackName: string) {\n return new CloudFormationStack(cfn, stackName);\n }\n\n /**\n * From static information (for testing)\n */\n public static fromStaticInformation(cfn: ICloudFormationClient, stackName: string, stack: Stack) {\n return new CloudFormationStack(cfn, stackName, stack);\n }\n\n private _template: any;\n\n protected constructor(\n private readonly cfn: ICloudFormationClient,\n public readonly stackName: string,\n private readonly stack?: Stack,\n private readonly retrieveProcessedTemplate: boolean = false,\n ) {\n }\n\n /**\n * Retrieve the stack's deployed template\n *\n * Cached, so will only be retrieved once. Will return an empty\n * structure if the stack does not exist.\n */\n public async template(): Promise<Template> {\n if (!this.exists) {\n return {};\n }\n\n if (this._template === undefined) {\n const response = await this.cfn.getTemplate({\n StackName: this.stackName,\n TemplateStage: this.retrieveProcessedTemplate ? 'Processed' : 'Original',\n });\n this._template = (response.TemplateBody && deserializeStructure(response.TemplateBody)) || {};\n }\n return this._template;\n }\n\n /**\n * Whether the stack exists\n */\n public get exists() {\n return this.stack !== undefined;\n }\n\n /**\n * The stack's ID (which is the same as its ARN)\n *\n * Throws if the stack doesn't exist.\n */\n public get stackId() {\n this.assertExists();\n return this.stack!.StackId!;\n }\n\n /**\n * The stack's current outputs\n *\n * Empty object if the stack doesn't exist\n */\n public get outputs(): Record<string, string> {\n if (!this.exists) {\n return {};\n }\n const result: { [name: string]: string } = {};\n (this.stack!.Outputs || []).forEach((output) => {\n result[output.OutputKey!] = output.OutputValue!;\n });\n return result;\n }\n\n /**\n * The stack's status\n *\n * Special status NOT_FOUND if the stack does not exist.\n */\n public get stackStatus(): StackStatus {\n if (!this.exists) {\n return new StackStatus('NOT_FOUND', 'Stack not found during lookup');\n }\n return StackStatus.fromStackDescription(this.stack!);\n }\n\n /**\n * The stack's current tags\n *\n * Empty list if the stack does not exist\n */\n public get tags(): Tag[] {\n return this.stack?.Tags || [];\n }\n\n /**\n * SNS Topic ARNs that will receive stack events.\n *\n * Empty list if the stack does not exist\n */\n public get notificationArns(): string[] {\n return this.stack?.NotificationARNs ?? [];\n }\n\n /**\n * Return the names of all current parameters to the stack\n *\n * Empty list if the stack does not exist.\n */\n public get parameterNames(): string[] {\n return Object.keys(this.parameters);\n }\n\n /**\n * Return the names and values of all current parameters to the stack\n *\n * Empty object if the stack does not exist.\n */\n public get parameters(): Record<string, string> {\n if (!this.exists) {\n return {};\n }\n const ret: Record<string, string> = {};\n for (const param of this.stack!.Parameters ?? []) {\n ret[param.ParameterKey!] = param.ResolvedValue ?? param.ParameterValue!;\n }\n return ret;\n }\n\n /**\n * Return the termination protection of the stack\n */\n public get terminationProtection(): boolean | undefined {\n return this.stack?.EnableTerminationProtection;\n }\n\n private assertExists() {\n if (!this.exists) {\n throw new ToolkitError(`No stack named '${this.stackName}'`);\n }\n }\n}\n", "import type { SDK } from '../aws-auth';\nimport { IO, type IoHelper } from '../io/private';\nimport { ToolkitError } from '../toolkit-error';\n\nexport async function determineAllowCrossAccountAssetPublishing(\n sdk: SDK,\n ioHelper: IoHelper,\n customStackName?: string,\n): Promise<boolean> {\n try {\n const stackName = customStackName || 'CDKToolkit';\n const stackInfo = await getBootstrapStackInfo(sdk, stackName);\n\n if (!stackInfo.hasStagingBucket) {\n // indicates an intentional cross account setup\n return true;\n }\n\n if (stackInfo.bootstrapVersion >= 21) {\n // bootstrap stack version 21 contains a fix that will prevent cross\n // account publishing on the IAM level\n // https://github.com/aws/aws-cdk/pull/30823\n return true;\n }\n\n // If there is a staging bucket AND the bootstrap version is old, then we want to protect\n // against accidental cross-account publishing.\n return false;\n } catch (e) {\n // You would think we would need to fail closed here, but the reality is\n // that we get here if we couldn't find the bootstrap stack: that is\n // completely valid, and many large organizations may have their own method\n // of creating bootstrap resources. If they do, there's nothing for us to validate,\n // but we can't use that as a reason to disallow cross-account publishing. We'll just\n // have to trust they did their due diligence. So we fail open.\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Error determining cross account asset publishing: ${e}`));\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg('Defaulting to allowing cross account asset publishing'));\n return true;\n }\n}\n\ninterface BootstrapStackInfo {\n hasStagingBucket: boolean;\n bootstrapVersion: number;\n}\n\nexport async function getBootstrapStackInfo(sdk: SDK, stackName: string): Promise<BootstrapStackInfo> {\n try {\n const cfn = sdk.cloudFormation();\n const stackResponse = await cfn.describeStacks({ StackName: stackName });\n\n if (!stackResponse.Stacks || stackResponse.Stacks.length === 0) {\n throw new ToolkitError(`Toolkit stack ${stackName} not found`);\n }\n\n const stack = stackResponse.Stacks[0];\n const versionOutput = stack.Outputs?.find(output => output.OutputKey === 'BootstrapVersion');\n\n if (!versionOutput?.OutputValue) {\n throw new ToolkitError(`Unable to find BootstrapVersion output in the toolkit stack ${stackName}`);\n }\n\n const bootstrapVersion = parseInt(versionOutput.OutputValue);\n if (isNaN(bootstrapVersion)) {\n throw new ToolkitError(`Invalid BootstrapVersion value: ${versionOutput.OutputValue}`);\n }\n\n // try to get bucketname from the logical resource id. If there is no\n // bucketname, or the value doesn't look like an S3 bucket name, we assume\n // the bucket doesn't exist (this is for the case where a template customizer did\n // not dare to remove the Output, but put a dummy value there like '' or '-' or '***').\n //\n // We would have preferred to look at the stack resources here, but\n // unfortunately the deploy role doesn't have permissions call DescribeStackResources.\n const bucketName = stack.Outputs?.find(output => output.OutputKey === 'BucketName')?.OutputValue;\n // Must begin and end with letter or number.\n const hasStagingBucket = !!(bucketName && bucketName.match(/^[a-z0-9]/) && bucketName.match(/[a-z0-9]$/));\n\n return {\n hasStagingBucket,\n bootstrapVersion,\n };\n } catch (e) {\n throw new ToolkitError(`Error retrieving toolkit stack info: ${e}`);\n }\n}\n", "import { format } from 'util';\nimport type * as cxapi from '@aws-cdk/cx-api';\nimport type {\n CreateChangeSetCommandInput,\n CreateStackCommandInput,\n DescribeChangeSetCommandOutput,\n ExecuteChangeSetCommandInput,\n UpdateStackCommandInput,\n Tag,\n} from '@aws-sdk/client-cloudformation';\nimport * as chalk from 'chalk';\nimport * as uuid from 'uuid';\nimport { AssetManifestBuilder } from './asset-manifest-builder';\nimport { publishAssets } from './asset-publishing';\nimport { addMetadataAssetsToManifest } from './assets';\nimport type {\n ParameterValues,\n ParameterChanges,\n} from './cfn-api';\nimport {\n changeSetHasNoChanges,\n TemplateParameters,\n waitForChangeSet,\n waitForStackDeploy,\n waitForStackDelete,\n} from './cfn-api';\nimport { determineAllowCrossAccountAssetPublishing } from './checks';\nimport type { ChangeSetDeploymentMethod, DeploymentMethod } from './deployment-method';\nimport type { DeployStackResult, SuccessfulDeployStackResult } from './deployment-result';\nimport { formatErrorMessage } from '../../util';\nimport type { SDK, SdkProvider, ICloudFormationClient } from '../aws-auth';\nimport type { TemplateBodyParameter } from '../cloudformation';\nimport { makeBodyParameter, CfnEvaluationException, CloudFormationStack } from '../cloudformation';\nimport type { EnvironmentResources, StringWithoutPlaceholders } from '../environment';\nimport { HotswapMode, HotswapPropertyOverrides, ICON } from '../hotswap/common';\nimport { tryHotswapDeployment } from '../hotswap/hotswap-deployments';\nimport { IO, type IoHelper } from '../io/private';\nimport type { ResourcesToImport } from '../resource-import';\nimport { StackActivityMonitor } from '../stack-events';\nimport { ToolkitError } from '../toolkit-error';\n\nexport interface DeployStackOptions {\n /**\n * The stack to be deployed\n */\n readonly stack: cxapi.CloudFormationStackArtifact;\n\n /**\n * The environment to deploy this stack in\n *\n * The environment on the stack artifact may be unresolved, this one\n * must be resolved.\n */\n readonly resolvedEnvironment: cxapi.Environment;\n\n /**\n * The SDK to use for deploying the stack\n *\n * Should have been initialized with the correct role with which\n * stack operations should be performed.\n */\n readonly sdk: SDK;\n\n /**\n * SDK provider (seeded with default credentials)\n *\n * Will be used to:\n *\n * - Publish assets, either legacy assets or large CFN templates\n * that aren't themselves assets from a manifest. (Needs an SDK\n * Provider because the file publishing role is declared as part\n * of the asset).\n * - Hotswap\n */\n readonly sdkProvider: SdkProvider;\n\n /**\n * Information about the bootstrap stack found in the target environment\n */\n readonly envResources: EnvironmentResources;\n\n /**\n * Role to pass to CloudFormation to execute the change set\n *\n * To obtain a `StringWithoutPlaceholders`, run a regular\n * string though `TargetEnvironment.replacePlaceholders`.\n *\n * @default - No execution role; CloudFormation either uses the role currently associated with\n * the stack, or otherwise uses current AWS credentials.\n */\n readonly roleArn?: StringWithoutPlaceholders;\n\n /**\n * Notification ARNs to pass to CloudFormation to notify when the change set has completed\n *\n * @default - No notifications\n */\n readonly notificationArns?: string[];\n\n /**\n * Name to deploy the stack under\n *\n * @default - Name from assembly\n */\n readonly deployName?: string;\n\n /**\n * List of asset IDs which shouldn't be built\n *\n * @default - Build all assets\n */\n readonly reuseAssets?: string[];\n\n /**\n * Tags to pass to CloudFormation to add to stack\n *\n * @default - No tags\n */\n readonly tags?: Tag[];\n\n /**\n * What deployment method to use\n *\n * @default - Change set with defaults\n */\n readonly deploymentMethod?: DeploymentMethod;\n\n /**\n * The collection of extra parameters\n * (in addition to those used for assets)\n * to pass to the deployed template.\n * Note that parameters with `undefined` or empty values will be ignored,\n * and not passed to the template.\n *\n * @default - no additional parameters will be passed to the template\n */\n readonly parameters?: { [name: string]: string | undefined };\n\n /**\n * Use previous values for unspecified parameters\n *\n * If not set, all parameters must be specified for every deployment.\n *\n * @default false\n */\n readonly usePreviousParameters?: boolean;\n\n /**\n * Deploy even if the deployed template is identical to the one we are about to deploy.\n * @default false\n */\n readonly forceDeployment?: boolean;\n\n /**\n * Rollback failed deployments\n *\n * @default true\n */\n readonly rollback?: boolean;\n\n /*\n * Whether to perform a 'hotswap' deployment.\n * A 'hotswap' deployment will attempt to short-circuit CloudFormation\n * and update the affected resources like Lambda functions directly.\n *\n * @default - `HotswapMode.FULL_DEPLOYMENT` for regular deployments, `HotswapMode.HOTSWAP_ONLY` for 'watch' deployments\n */\n readonly hotswap?: HotswapMode;\n\n /**\n * Extra properties that configure hotswap behavior\n */\n readonly hotswapPropertyOverrides?: HotswapPropertyOverrides;\n\n /**\n * The extra string to append to the User-Agent header when performing AWS SDK calls.\n *\n * @default - nothing extra is appended to the User-Agent header\n */\n readonly extraUserAgent?: string;\n\n /**\n * If set, change set of type IMPORT will be created, and resourcesToImport\n * passed to it.\n */\n readonly resourcesToImport?: ResourcesToImport;\n\n /**\n * If present, use this given template instead of the stored one\n *\n * @default - Use the stored template\n */\n readonly overrideTemplate?: any;\n\n /**\n * Whether to build/publish assets in parallel\n *\n * @default true To remain backward compatible.\n */\n readonly assetParallelism?: boolean;\n}\n\nexport async function deployStack(options: DeployStackOptions, ioHelper: IoHelper): Promise<DeployStackResult> {\n const stackArtifact = options.stack;\n\n const stackEnv = options.resolvedEnvironment;\n\n options.sdk.appendCustomUserAgent(options.extraUserAgent);\n const cfn = options.sdk.cloudFormation();\n const deployName = options.deployName || stackArtifact.stackName;\n let cloudFormationStack = await CloudFormationStack.lookup(cfn, deployName);\n\n if (cloudFormationStack.stackStatus.isCreationFailure) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(\n `Found existing stack ${deployName} that had previously failed creation. Deleting it before attempting to re-create it.`,\n ));\n await cfn.deleteStack({ StackName: deployName });\n const deletedStack = await waitForStackDelete(cfn, ioHelper, deployName);\n if (deletedStack && deletedStack.stackStatus.name !== 'DELETE_COMPLETE') {\n throw new ToolkitError(\n `Failed deleting stack ${deployName} that had previously failed creation (current state: ${deletedStack.stackStatus})`,\n );\n }\n // Update variable to mark that the stack does not exist anymore, but avoid\n // doing an actual lookup in CloudFormation (which would be silly to do if\n // we just deleted it).\n cloudFormationStack = CloudFormationStack.doesNotExist(cfn, deployName);\n }\n\n // Detect \"legacy\" assets (which remain in the metadata) and publish them via\n // an ad-hoc asset manifest, while passing their locations via template\n // parameters.\n const legacyAssets = new AssetManifestBuilder();\n const assetParams = await addMetadataAssetsToManifest(\n ioHelper,\n stackArtifact,\n legacyAssets,\n options.envResources,\n options.reuseAssets,\n );\n\n const finalParameterValues = { ...options.parameters, ...assetParams };\n\n const templateParams = TemplateParameters.fromTemplate(stackArtifact.template);\n const stackParams = options.usePreviousParameters\n ? templateParams.updateExisting(finalParameterValues, cloudFormationStack.parameters)\n : templateParams.supplyAll(finalParameterValues);\n\n const hotswapMode = options.hotswap ?? HotswapMode.FULL_DEPLOYMENT;\n const hotswapPropertyOverrides = options.hotswapPropertyOverrides ?? new HotswapPropertyOverrides();\n\n if (await canSkipDeploy(options, cloudFormationStack, stackParams.hasChanges(cloudFormationStack.parameters), ioHelper)) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${deployName}: skipping deployment (use --force to override)`));\n // if we can skip deployment and we are performing a hotswap, let the user know\n // that no hotswap deployment happened\n if (hotswapMode !== HotswapMode.FULL_DEPLOYMENT) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(\n format(\n `\\n ${ICON} %s\\n`,\n chalk.bold('hotswap deployment skipped - no changes were detected (use --force to override)'),\n ),\n ));\n }\n return {\n type: 'did-deploy-stack',\n noOp: true,\n outputs: cloudFormationStack.outputs,\n stackArn: cloudFormationStack.stackId,\n };\n } else {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${deployName}: deploying...`));\n }\n\n const bodyParameter = await makeBodyParameter(\n ioHelper,\n stackArtifact,\n options.resolvedEnvironment,\n legacyAssets,\n options.envResources,\n options.overrideTemplate,\n );\n let bootstrapStackName: string | undefined;\n try {\n bootstrapStackName = (await options.envResources.lookupToolkit()).stackName;\n } catch (e) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Could not determine the bootstrap stack name: ${e}`));\n }\n await publishAssets(legacyAssets.toManifest(stackArtifact.assembly.directory), options.sdkProvider, stackEnv, {\n parallel: options.assetParallelism,\n allowCrossAccount: await determineAllowCrossAccountAssetPublishing(options.sdk, ioHelper, bootstrapStackName),\n }, ioHelper);\n\n if (hotswapMode !== HotswapMode.FULL_DEPLOYMENT) {\n // attempt to short-circuit the deployment if possible\n try {\n const hotswapDeploymentResult = await tryHotswapDeployment(\n options.sdkProvider,\n ioHelper,\n stackParams.values,\n cloudFormationStack,\n stackArtifact,\n hotswapMode,\n hotswapPropertyOverrides,\n );\n\n if (hotswapDeploymentResult) {\n return hotswapDeploymentResult;\n }\n\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(format(\n 'Could not perform a hotswap deployment, as the stack %s contains non-Asset changes',\n stackArtifact.displayName,\n )));\n } catch (e) {\n if (!(e instanceof CfnEvaluationException)) {\n throw e;\n }\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(format(\n 'Could not perform a hotswap deployment, because the CloudFormation template could not be resolved: %s',\n formatErrorMessage(e),\n )));\n }\n\n if (hotswapMode === HotswapMode.FALL_BACK) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg('Falling back to doing a full deployment'));\n options.sdk.appendCustomUserAgent('cdk-hotswap/fallback');\n } else {\n return {\n type: 'did-deploy-stack',\n noOp: true,\n stackArn: cloudFormationStack.stackId,\n outputs: cloudFormationStack.outputs,\n };\n }\n }\n\n // could not short-circuit the deployment, perform a full CFN deploy instead\n const fullDeployment = new FullCloudFormationDeployment(\n options,\n cloudFormationStack,\n stackArtifact,\n stackParams,\n bodyParameter,\n ioHelper,\n );\n return fullDeployment.performDeployment();\n}\n\ntype CommonPrepareOptions = keyof CreateStackCommandInput &\nkeyof UpdateStackCommandInput &\nkeyof CreateChangeSetCommandInput;\ntype CommonExecuteOptions = keyof CreateStackCommandInput &\nkeyof UpdateStackCommandInput &\nkeyof ExecuteChangeSetCommandInput;\n\n/**\n * This class shares state and functionality between the different full deployment modes\n */\nclass FullCloudFormationDeployment {\n private readonly cfn: ICloudFormationClient;\n private readonly stackName: string;\n private readonly update: boolean;\n private readonly verb: string;\n private readonly uuid: string;\n\n constructor(\n private readonly options: DeployStackOptions,\n private readonly cloudFormationStack: CloudFormationStack,\n private readonly stackArtifact: cxapi.CloudFormationStackArtifact,\n private readonly stackParams: ParameterValues,\n private readonly bodyParameter: TemplateBodyParameter,\n private readonly ioHelper: IoHelper,\n ) {\n this.cfn = options.sdk.cloudFormation();\n this.stackName = options.deployName ?? stackArtifact.stackName;\n\n this.update = cloudFormationStack.exists && cloudFormationStack.stackStatus.name !== 'REVIEW_IN_PROGRESS';\n this.verb = this.update ? 'update' : 'create';\n this.uuid = uuid.v4();\n }\n\n public async performDeployment(): Promise<DeployStackResult> {\n const deploymentMethod = this.options.deploymentMethod ?? {\n method: 'change-set',\n };\n\n if (deploymentMethod.method === 'direct' && this.options.resourcesToImport) {\n throw new ToolkitError('Importing resources requires a changeset deployment');\n }\n\n switch (deploymentMethod.method) {\n case 'change-set':\n return this.changeSetDeployment(deploymentMethod);\n\n case 'direct':\n return this.directDeployment();\n }\n }\n\n private async changeSetDeployment(deploymentMethod: ChangeSetDeploymentMethod): Promise<DeployStackResult> {\n const changeSetName = deploymentMethod.changeSetName ?? 'cdk-deploy-change-set';\n const execute = deploymentMethod.execute ?? true;\n const importExistingResources = deploymentMethod.importExistingResources ?? false;\n const changeSetDescription = await this.createChangeSet(changeSetName, execute, importExistingResources);\n await this.updateTerminationProtection();\n\n if (changeSetHasNoChanges(changeSetDescription)) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(format('No changes are to be performed on %s.', this.stackName)));\n if (execute) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(format('Deleting empty change set %s', changeSetDescription.ChangeSetId)));\n await this.cfn.deleteChangeSet({\n StackName: this.stackName,\n ChangeSetName: changeSetName,\n });\n }\n\n if (this.options.forceDeployment) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_WARN.msg(\n [\n 'You used the --force flag, but CloudFormation reported that the deployment would not make any changes.',\n 'According to CloudFormation, all resources are already up-to-date with the state in your CDK app.',\n '',\n 'You cannot use the --force flag to get rid of changes you made in the console. Try using',\n 'CloudFormation drift detection instead: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-stack-drift.html',\n ].join('\\n'),\n ));\n }\n\n return {\n type: 'did-deploy-stack',\n noOp: true,\n outputs: this.cloudFormationStack.outputs,\n stackArn: changeSetDescription.StackId!,\n };\n }\n\n if (!execute) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(format(\n 'Changeset %s created and waiting in review for manual execution (--no-execute)',\n changeSetDescription.ChangeSetId,\n )));\n return {\n type: 'did-deploy-stack',\n noOp: false,\n outputs: this.cloudFormationStack.outputs,\n stackArn: changeSetDescription.StackId!,\n };\n }\n\n // If there are replacements in the changeset, check the rollback flag and stack status\n const replacement = hasReplacement(changeSetDescription);\n const isPausedFailState = this.cloudFormationStack.stackStatus.isRollbackable;\n const rollback = this.options.rollback ?? true;\n if (isPausedFailState && replacement) {\n return { type: 'failpaused-need-rollback-first', reason: 'replacement', status: this.cloudFormationStack.stackStatus.name };\n }\n if (isPausedFailState && rollback) {\n return { type: 'failpaused-need-rollback-first', reason: 'not-norollback', status: this.cloudFormationStack.stackStatus.name };\n }\n if (!rollback && replacement) {\n return { type: 'replacement-requires-rollback' };\n }\n\n return this.executeChangeSet(changeSetDescription);\n }\n\n private async createChangeSet(changeSetName: string, willExecute: boolean, importExistingResources: boolean) {\n await this.cleanupOldChangeset(changeSetName);\n\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Attempting to create ChangeSet with name ${changeSetName} to ${this.verb} stack ${this.stackName}`));\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(format('%s: creating CloudFormation changeset...', chalk.bold(this.stackName))));\n const changeSet = await this.cfn.createChangeSet({\n StackName: this.stackName,\n ChangeSetName: changeSetName,\n ChangeSetType: this.options.resourcesToImport ? 'IMPORT' : this.update ? 'UPDATE' : 'CREATE',\n ResourcesToImport: this.options.resourcesToImport,\n Description: `CDK Changeset for execution ${this.uuid}`,\n ClientToken: `create${this.uuid}`,\n ImportExistingResources: importExistingResources,\n ...this.commonPrepareOptions(),\n });\n\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(format('Initiated creation of changeset: %s; waiting for it to finish creating...', changeSet.Id)));\n // Fetching all pages if we'll execute, so we can have the correct change count when monitoring.\n return waitForChangeSet(this.cfn, this.ioHelper, this.stackName, changeSetName, {\n fetchAll: willExecute,\n });\n }\n\n private async executeChangeSet(changeSet: DescribeChangeSetCommandOutput): Promise<SuccessfulDeployStackResult> {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(format('Initiating execution of changeset %s on stack %s', changeSet.ChangeSetId, this.stackName)));\n\n await this.cfn.executeChangeSet({\n StackName: this.stackName,\n ChangeSetName: changeSet.ChangeSetName!,\n ClientRequestToken: `exec${this.uuid}`,\n ...this.commonExecuteOptions(),\n });\n\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(\n format(\n 'Execution of changeset %s on stack %s has started; waiting for the update to complete...',\n changeSet.ChangeSetId,\n this.stackName,\n ),\n ));\n\n // +1 for the extra event emitted from updates.\n const changeSetLength: number = (changeSet.Changes ?? []).length + (this.update ? 1 : 0);\n return this.monitorDeployment(changeSet.CreationTime!, changeSetLength);\n }\n\n private async cleanupOldChangeset(changeSetName: string) {\n if (this.cloudFormationStack.exists) {\n // Delete any existing change sets generated by CDK since change set names must be unique.\n // The delete request is successful as long as the stack exists (even if the change set does not exist).\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Removing existing change set with name ${changeSetName} if it exists`));\n await this.cfn.deleteChangeSet({\n StackName: this.stackName,\n ChangeSetName: changeSetName,\n });\n }\n }\n\n private async updateTerminationProtection() {\n // Update termination protection only if it has changed.\n const terminationProtection = this.stackArtifact.terminationProtection ?? false;\n if (!!this.cloudFormationStack.terminationProtection !== terminationProtection) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(\n format (\n 'Updating termination protection from %s to %s for stack %s',\n this.cloudFormationStack.terminationProtection,\n terminationProtection,\n this.stackName,\n ),\n ));\n await this.cfn.updateTerminationProtection({\n StackName: this.stackName,\n EnableTerminationProtection: terminationProtection,\n });\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(format('Termination protection updated to %s for stack %s', terminationProtection, this.stackName)));\n }\n }\n\n private async directDeployment(): Promise<SuccessfulDeployStackResult> {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(format('%s: %s stack...', chalk.bold(this.stackName), this.update ? 'updating' : 'creating')));\n\n const startTime = new Date();\n\n if (this.update) {\n await this.updateTerminationProtection();\n\n try {\n await this.cfn.updateStack({\n StackName: this.stackName,\n ClientRequestToken: `update${this.uuid}`,\n ...this.commonPrepareOptions(),\n ...this.commonExecuteOptions(),\n });\n } catch (err: any) {\n if (err.message === 'No updates are to be performed.') {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(format('No updates are to be performed for stack %s', this.stackName)));\n return {\n type: 'did-deploy-stack',\n noOp: true,\n outputs: this.cloudFormationStack.outputs,\n stackArn: this.cloudFormationStack.stackId,\n };\n }\n throw err;\n }\n\n return this.monitorDeployment(startTime, undefined);\n } else {\n // Take advantage of the fact that we can set termination protection during create\n const terminationProtection = this.stackArtifact.terminationProtection ?? false;\n\n await this.cfn.createStack({\n StackName: this.stackName,\n ClientRequestToken: `create${this.uuid}`,\n ...(terminationProtection ? { EnableTerminationProtection: true } : undefined),\n ...this.commonPrepareOptions(),\n ...this.commonExecuteOptions(),\n });\n\n return this.monitorDeployment(startTime, undefined);\n }\n }\n\n private async monitorDeployment(startTime: Date, expectedChanges: number | undefined): Promise<SuccessfulDeployStackResult> {\n const monitor = new StackActivityMonitor({\n cfn: this.cfn,\n stack: this.stackArtifact,\n stackName: this.stackName,\n resourcesTotal: expectedChanges,\n ioHelper: this.ioHelper,\n changeSetCreationTime: startTime,\n });\n await monitor.start();\n\n let finalState = this.cloudFormationStack;\n try {\n const successStack = await waitForStackDeploy(this.cfn, this.ioHelper, this.stackName);\n\n // This shouldn't really happen, but catch it anyway. You never know.\n if (!successStack) {\n throw new ToolkitError('Stack deploy failed (the stack disappeared while we were deploying it)');\n }\n finalState = successStack;\n } catch (e: any) {\n throw new ToolkitError(suffixWithErrors(formatErrorMessage(e), monitor.errors));\n } finally {\n await monitor.stop();\n }\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(format('Stack %s has completed updating', this.stackName)));\n return {\n type: 'did-deploy-stack',\n noOp: false,\n outputs: finalState.outputs,\n stackArn: finalState.stackId,\n };\n }\n\n /**\n * Return the options that are shared between CreateStack, UpdateStack and CreateChangeSet\n */\n private commonPrepareOptions(): Partial<Pick<UpdateStackCommandInput, CommonPrepareOptions>> {\n return {\n Capabilities: ['CAPABILITY_IAM', 'CAPABILITY_NAMED_IAM', 'CAPABILITY_AUTO_EXPAND'],\n NotificationARNs: this.options.notificationArns,\n Parameters: this.stackParams.apiParameters,\n RoleARN: this.options.roleArn,\n TemplateBody: this.bodyParameter.TemplateBody,\n TemplateURL: this.bodyParameter.TemplateURL,\n Tags: this.options.tags,\n };\n }\n\n /**\n * Return the options that are shared between UpdateStack and CreateChangeSet\n *\n * Be careful not to add in keys for options that aren't used, as the features may not have been\n * deployed everywhere yet.\n */\n private commonExecuteOptions(): Partial<Pick<UpdateStackCommandInput, CommonExecuteOptions>> {\n const shouldDisableRollback = this.options.rollback === false;\n\n return {\n StackName: this.stackName,\n ...(shouldDisableRollback ? { DisableRollback: true } : undefined),\n };\n }\n}\n\nexport interface DestroyStackOptions {\n /**\n * The stack to be destroyed\n */\n stack: cxapi.CloudFormationStackArtifact;\n\n sdk: SDK;\n roleArn?: string;\n deployName?: string;\n}\n\nexport interface DestroyStackResult {\n /**\n * The ARN of the stack that was destroyed, if any.\n *\n * If the stack didn't exist to begin with, the operation will succeed\n * but this value will be undefined.\n */\n readonly stackArn?: string;\n}\n\nexport async function destroyStack(options: DestroyStackOptions, ioHelper: IoHelper): Promise<DestroyStackResult> {\n const deployName = options.deployName || options.stack.stackName;\n const cfn = options.sdk.cloudFormation();\n\n const currentStack = await CloudFormationStack.lookup(cfn, deployName);\n if (!currentStack.exists) {\n return {};\n }\n const monitor = new StackActivityMonitor({\n cfn,\n stack: options.stack,\n stackName: deployName,\n ioHelper: ioHelper,\n });\n await monitor.start();\n\n try {\n await cfn.deleteStack({ StackName: deployName, RoleARN: options.roleArn });\n const destroyedStack = await waitForStackDelete(cfn, ioHelper, deployName);\n if (destroyedStack && destroyedStack.stackStatus.name !== 'DELETE_COMPLETE') {\n throw new ToolkitError(`Failed to destroy ${deployName}: ${destroyedStack.stackStatus}`);\n }\n\n return { stackArn: currentStack.stackId };\n } catch (e: any) {\n throw new ToolkitError(suffixWithErrors(formatErrorMessage(e), monitor.errors));\n } finally {\n if (monitor) {\n await monitor.stop();\n }\n }\n}\n\n/**\n * Checks whether we can skip deployment\n *\n * We do this in a complicated way by preprocessing (instead of just\n * looking at the changeset), because if there are nested stacks involved\n * the changeset will always show the nested stacks as needing to be\n * updated, and the deployment will take a long time to in effect not\n * do anything.\n */\nasync function canSkipDeploy(\n deployStackOptions: DeployStackOptions,\n cloudFormationStack: CloudFormationStack,\n parameterChanges: ParameterChanges,\n ioHelper: IoHelper,\n): Promise<boolean> {\n const deployName = deployStackOptions.deployName || deployStackOptions.stack.stackName;\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${deployName}: checking if we can skip deploy`));\n\n // Forced deploy\n if (deployStackOptions.forceDeployment) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${deployName}: forced deployment`));\n return false;\n }\n\n // Creating changeset only (default true), never skip\n if (\n deployStackOptions.deploymentMethod?.method === 'change-set' &&\n deployStackOptions.deploymentMethod.execute === false\n ) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${deployName}: --no-execute, always creating change set`));\n return false;\n }\n\n // No existing stack\n if (!cloudFormationStack.exists) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${deployName}: no existing stack`));\n return false;\n }\n\n // Template has changed (assets taken into account here)\n if (JSON.stringify(deployStackOptions.stack.template) !== JSON.stringify(await cloudFormationStack.template())) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${deployName}: template has changed`));\n return false;\n }\n\n // Tags have changed\n if (!compareTags(cloudFormationStack.tags, deployStackOptions.tags ?? [])) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${deployName}: tags have changed`));\n return false;\n }\n\n // Notification arns have changed\n if (!arrayEquals(cloudFormationStack.notificationArns, deployStackOptions.notificationArns ?? [])) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${deployName}: notification arns have changed`));\n return false;\n }\n\n // Termination protection has been updated\n if (!!deployStackOptions.stack.terminationProtection !== !!cloudFormationStack.terminationProtection) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${deployName}: termination protection has been updated`));\n return false;\n }\n\n // Parameters have changed\n if (parameterChanges) {\n if (parameterChanges === 'ssm') {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${deployName}: some parameters come from SSM so we have to assume they may have changed`));\n } else {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${deployName}: parameters have changed`));\n }\n return false;\n }\n\n // Existing stack is in a failed state\n if (cloudFormationStack.stackStatus.isFailure) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${deployName}: stack is in a failure state`));\n return false;\n }\n\n // We can skip deploy\n return true;\n}\n\n/**\n * Compares two list of tags, returns true if identical.\n */\nfunction compareTags(a: Tag[], b: Tag[]): boolean {\n if (a.length !== b.length) {\n return false;\n }\n\n for (const aTag of a) {\n const bTag = b.find((tag) => tag.Key === aTag.Key);\n\n if (!bTag || bTag.Value !== aTag.Value) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction suffixWithErrors(msg: string, errors?: string[]) {\n return errors && errors.length > 0 ? `${msg}: ${errors.join(', ')}` : msg;\n}\n\nfunction arrayEquals(a: any[], b: any[]): boolean {\n return a.every((item) => b.includes(item)) && b.every((item) => a.includes(item));\n}\n\nfunction hasReplacement(cs: DescribeChangeSetCommandOutput) {\n return (cs.Changes ?? []).some(c => {\n const a = c.ResourceChange?.PolicyAction;\n return a === 'ReplaceAndDelete' || a === 'ReplaceAndRetain' || a === 'ReplaceAndSnapshot';\n });\n}\n", "// eslint-disable-next-line max-len\nimport * as path from 'path';\nimport * as cxschema from '@aws-cdk/cloud-assembly-schema';\nimport * as cxapi from '@aws-cdk/cx-api';\nimport * as chalk from 'chalk';\nimport type { AssetManifestBuilder } from './asset-manifest-builder';\nimport type { EnvironmentResources } from '../environment';\nimport { IO, type IoHelper } from '../io/private';\nimport { ToolkitError } from '../toolkit-error';\nimport type { ToolkitInfo } from '../toolkit-info';\n\n/**\n * Take the metadata assets from the given stack and add them to the given asset manifest\n *\n * Returns the CloudFormation parameters that need to be sent to the template to\n * pass Asset coordinates.\n */\nexport async function addMetadataAssetsToManifest(\n ioHelper: IoHelper,\n stack: cxapi.CloudFormationStackArtifact,\n assetManifest: AssetManifestBuilder,\n envResources: EnvironmentResources,\n reuse?: string[],\n): Promise<Record<string, string>> {\n reuse = reuse || [];\n const assets = stack.assets;\n\n if (assets.length === 0) {\n return {};\n }\n\n const toolkitInfo = await envResources.lookupToolkit();\n if (!toolkitInfo.found) {\n // eslint-disable-next-line max-len\n throw new ToolkitError(`This stack uses assets, so the toolkit stack must be deployed to the environment (Run \"${chalk.blue('cdk bootstrap ' + stack.environment!.name)}\")`);\n }\n\n const params: Record<string, string> = {};\n\n for (const asset of assets) {\n // FIXME: Should have excluded by construct path here instead of by unique ID, preferably using\n // minimatch so we can support globs. Maybe take up during artifact refactoring.\n const reuseAsset = reuse.indexOf(asset.id) > -1;\n\n if (reuseAsset) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Reusing asset ${asset.id}: ${JSON.stringify(asset)}`));\n continue;\n }\n\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Preparing asset ${asset.id}: ${JSON.stringify(asset)}`));\n if (!stack.assembly) {\n throw new ToolkitError('Unexpected: stack assembly is required in order to find assets in assembly directory');\n }\n\n Object.assign(params, await prepareAsset(ioHelper, asset, assetManifest, envResources, toolkitInfo));\n }\n\n return params;\n}\n\n// eslint-disable-next-line max-len\nasync function prepareAsset(\n ioHelper: IoHelper,\n asset: cxschema.AssetMetadataEntry,\n assetManifest: AssetManifestBuilder,\n envResources: EnvironmentResources,\n toolkitInfo: ToolkitInfo,\n): Promise<Record<string, string>> {\n switch (asset.packaging) {\n case 'zip':\n case 'file':\n return prepareFileAsset(\n ioHelper,\n asset,\n assetManifest,\n toolkitInfo,\n asset.packaging === 'zip' ? cxschema.FileAssetPackaging.ZIP_DIRECTORY : cxschema.FileAssetPackaging.FILE);\n case 'container-image':\n return prepareDockerImageAsset(asset, assetManifest, envResources);\n default:\n // eslint-disable-next-line max-len\n throw new ToolkitError(`Unsupported packaging type: ${(asset as any).packaging}. You might need to upgrade your aws-cdk toolkit to support this asset type.`);\n }\n}\n\nasync function prepareFileAsset(\n ioHelper: IoHelper,\n asset: cxschema.FileAssetMetadataEntry,\n assetManifest: AssetManifestBuilder,\n toolkitInfo: ToolkitInfo,\n packaging: cxschema.FileAssetPackaging,\n): Promise<Record<string, string>> {\n const extension = packaging === cxschema.FileAssetPackaging.ZIP_DIRECTORY ? '.zip' : path.extname(asset.path);\n const baseName = `${asset.sourceHash}${extension}`;\n // Simplify key: assets/abcdef/abcdef.zip is kinda silly and unnecessary, so if they're the same just pick one component.\n const s3Prefix = asset.id === asset.sourceHash ? 'assets/' : `assets/${asset.id}/`;\n const key = `${s3Prefix}${baseName}`;\n const s3url = `s3://${toolkitInfo.bucketName}/${key}`;\n\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Storing asset ${asset.path} at ${s3url}`));\n\n assetManifest.addFileAsset(asset.sourceHash, {\n path: asset.path,\n packaging,\n }, {\n bucketName: toolkitInfo.bucketName,\n objectKey: key,\n });\n\n return {\n [asset.s3BucketParameter]: toolkitInfo.bucketName,\n [asset.s3KeyParameter]: `${s3Prefix}${cxapi.ASSET_PREFIX_SEPARATOR}${baseName}`,\n [asset.artifactHashParameter]: asset.sourceHash,\n };\n}\n\nasync function prepareDockerImageAsset(\n asset: cxschema.ContainerImageAssetMetadataEntry,\n assetManifest: AssetManifestBuilder,\n envResources: EnvironmentResources): Promise<Record<string, string>> {\n // Pre-1.21.0, repositoryName can be specified by the user or can be left out, in which case we make\n // a per-asset repository which will get adopted and cleaned up along with the stack.\n // Post-1.21.0, repositoryName will always be specified and it will be a shared repository between\n // all assets, and asset will have imageTag specified as well. Validate the combination.\n if (!asset.imageNameParameter && (!asset.repositoryName || !asset.imageTag)) {\n throw new ToolkitError('Invalid Docker image asset configuration: \"repositoryName\" and \"imageTag\" are required when \"imageNameParameter\" is left out');\n }\n\n const repositoryName = asset.repositoryName ?? 'cdk/' + asset.id.replace(/[:/]/g, '-').toLowerCase();\n\n // Make sure the repository exists, since the 'cdk-assets' tool will not create it for us.\n const { repositoryUri } = await envResources.prepareEcrRepository(repositoryName);\n const imageTag = asset.imageTag ?? asset.sourceHash;\n\n assetManifest.addDockerImageAsset(asset.sourceHash, {\n directory: asset.path,\n dockerBuildArgs: asset.buildArgs,\n dockerBuildSsh: asset.buildSsh,\n dockerBuildTarget: asset.target,\n dockerFile: asset.file,\n networkMode: asset.networkMode,\n platform: asset.platform,\n dockerOutputs: asset.outputs,\n }, {\n repositoryName,\n imageTag,\n });\n\n if (!asset.imageNameParameter) {\n return {};\n }\n return { [asset.imageNameParameter]: `${repositoryUri}:${imageTag}` };\n}\n", "import type { PropertyDifference } from '@aws-cdk/cloudformation-diff';\nimport type { HotswappableChange, NonHotswappableChange, ResourceChange } from '../../payloads/hotswap';\nimport { NonHotswappableReason } from '../../payloads/hotswap';\nimport type { SDK } from '../aws-auth';\nimport { ToolkitError } from '../toolkit-error';\n\nexport const ICON = '\u2728';\n\nexport interface HotswapOperation {\n /**\n * Marks the operation as hotswappable\n */\n readonly hotswappable: true;\n\n /**\n * The name of the service being hotswapped.\n * Used to set a custom User-Agent for SDK calls.\n */\n readonly service: string;\n\n /**\n * Description of the change that is applied as part of the operation\n */\n readonly change: HotswappableChange;\n\n /**\n * Applies the hotswap operation\n */\n readonly apply: (sdk: SDK) => Promise<void>;\n}\n\nexport interface RejectedChange {\n /**\n * Marks the change as not hotswappable\n */\n readonly hotswappable: false;\n /**\n * The change that got rejected\n */\n readonly change: NonHotswappableChange;\n /**\n * Whether or not to show this change when listing non-hotswappable changes in HOTSWAP_ONLY mode. Does not affect\n * listing in FALL_BACK mode.\n *\n * @default true\n */\n readonly hotswapOnlyVisible?: boolean;\n}\n\nexport type HotswapChange = HotswapOperation | RejectedChange;\n\nexport enum HotswapMode {\n /**\n * Will fall back to CloudFormation when a non-hotswappable change is detected\n */\n FALL_BACK = 'fall-back',\n\n /**\n * Will not fall back to CloudFormation when a non-hotswappable change is detected\n */\n HOTSWAP_ONLY = 'hotswap-only',\n\n /**\n * Will not attempt to hotswap anything and instead go straight to CloudFormation\n */\n FULL_DEPLOYMENT = 'full-deployment',\n}\n\n/**\n * Represents configuration property overrides for hotswap deployments\n */\nexport class HotswapPropertyOverrides {\n // Each supported resource type will have its own properties. Currently this is ECS\n ecsHotswapProperties?: EcsHotswapProperties;\n\n public constructor (ecsHotswapProperties?: EcsHotswapProperties) {\n this.ecsHotswapProperties = ecsHotswapProperties;\n }\n}\n\n/**\n * Represents configuration properties for ECS hotswap deployments\n */\nexport class EcsHotswapProperties {\n // The lower limit on the number of your service's tasks that must remain in the RUNNING state during a deployment, as a percentage of the desiredCount\n readonly minimumHealthyPercent?: number;\n // The upper limit on the number of your service's tasks that are allowed in the RUNNING or PENDING state during a deployment, as a percentage of the desiredCount\n readonly maximumHealthyPercent?: number;\n\n public constructor (minimumHealthyPercent?: number, maximumHealthyPercent?: number) {\n if (minimumHealthyPercent !== undefined && minimumHealthyPercent < 0 ) {\n throw new ToolkitError('hotswap-ecs-minimum-healthy-percent can\\'t be a negative number');\n }\n if (maximumHealthyPercent !== undefined && maximumHealthyPercent < 0 ) {\n throw new ToolkitError('hotswap-ecs-maximum-healthy-percent can\\'t be a negative number');\n }\n // In order to preserve the current behaviour, when minimumHealthyPercent is not defined, it will be set to the currently default value of 0\n if (minimumHealthyPercent == undefined) {\n this.minimumHealthyPercent = 0;\n } else {\n this.minimumHealthyPercent = minimumHealthyPercent;\n }\n this.maximumHealthyPercent = maximumHealthyPercent;\n }\n\n /**\n * Check if any hotswap properties are defined\n * @returns true if all properties are undefined, false otherwise\n */\n public isEmpty(): boolean {\n return this.minimumHealthyPercent === 0 && this.maximumHealthyPercent === undefined;\n }\n}\n\ntype PropDiffs = Record<string, PropertyDifference<any>>;\n\nclass ClassifiedChanges {\n public constructor(\n public readonly change: ResourceChange,\n public readonly hotswappableProps: PropDiffs,\n public readonly nonHotswappableProps: PropDiffs,\n ) {\n }\n\n public reportNonHotswappablePropertyChanges(ret: HotswapChange[]): void {\n const nonHotswappablePropNames = Object.keys(this.nonHotswappableProps);\n if (nonHotswappablePropNames.length > 0) {\n const tagOnlyChange = nonHotswappablePropNames.length === 1 && nonHotswappablePropNames[0] === 'Tags';\n const reason = tagOnlyChange ? NonHotswappableReason.TAGS : NonHotswappableReason.PROPERTIES;\n const description = tagOnlyChange ? 'Tags are not hotswappable' : `resource properties '${nonHotswappablePropNames}' are not hotswappable on this resource type`;\n\n ret.push(nonHotswappableChange(\n this.change,\n reason,\n description,\n this.nonHotswappableProps,\n ));\n }\n }\n\n public get namesOfHotswappableProps(): string[] {\n return Object.keys(this.hotswappableProps);\n }\n}\n\nexport function classifyChanges(xs: ResourceChange, hotswappablePropNames: string[]): ClassifiedChanges {\n const hotswappableProps: PropDiffs = {};\n const nonHotswappableProps: PropDiffs = {};\n\n for (const [name, propDiff] of Object.entries(xs.propertyUpdates)) {\n if (hotswappablePropNames.includes(name)) {\n hotswappableProps[name] = propDiff;\n } else {\n nonHotswappableProps[name] = propDiff;\n }\n }\n\n return new ClassifiedChanges(xs, hotswappableProps, nonHotswappableProps);\n}\n\nexport function nonHotswappableChange(\n change: ResourceChange,\n reason: NonHotswappableReason,\n description: string,\n nonHotswappableProps?: PropDiffs,\n hotswapOnlyVisible: boolean = true,\n): RejectedChange {\n return {\n hotswappable: false,\n hotswapOnlyVisible,\n change: {\n reason,\n description,\n subject: {\n type: 'Resource',\n logicalId: change.logicalId,\n resourceType: change.newValue.Type,\n rejectedProperties: Object.keys(nonHotswappableProps ?? change.propertyUpdates),\n metadata: change.metadata,\n },\n },\n };\n}\n\nexport function nonHotswappableResource(change: ResourceChange): RejectedChange {\n return {\n hotswappable: false,\n change: {\n reason: NonHotswappableReason.RESOURCE_UNSUPPORTED,\n description: 'This resource type is not supported for hotswap deployments',\n subject: {\n type: 'Resource',\n logicalId: change.logicalId,\n resourceType: change.newValue.Type,\n rejectedProperties: Object.keys(change.propertyUpdates),\n metadata: change.metadata,\n },\n },\n };\n}\n", "import { format } from 'util';\nimport * as cfn_diff from '@aws-cdk/cloudformation-diff';\nimport type * as cxapi from '@aws-cdk/cx-api';\nimport type { WaiterResult } from '@smithy/util-waiter';\nimport * as chalk from 'chalk';\nimport type { AffectedResource, HotswapResult, ResourceSubject, ResourceChange, NonHotswappableChange } from '../../payloads';\nimport { NonHotswappableReason } from '../../payloads';\nimport { formatErrorMessage } from '../../util';\nimport type { SDK, SdkProvider } from '../aws-auth';\nimport type { CloudFormationStack, NestedStackTemplates } from '../cloudformation';\nimport { loadCurrentTemplateWithNestedStacks, EvaluateCloudFormationTemplate } from '../cloudformation';\nimport { isHotswappableAppSyncChange } from './appsync-mapping-templates';\nimport { isHotswappableCodeBuildProjectChange } from './code-build-projects';\nimport type {\n HotswapChange,\n HotswapOperation,\n RejectedChange,\n HotswapPropertyOverrides,\n} from './common';\nimport {\n ICON,\n nonHotswappableResource,\n} from './common';\nimport { isHotswappableEcsServiceChange } from './ecs-services';\nimport { isHotswappableLambdaFunctionChange } from './lambda-functions';\nimport {\n skipChangeForS3DeployCustomResourcePolicy,\n isHotswappableS3BucketDeploymentChange,\n} from './s3-bucket-deployments';\nimport { isHotswappableStateMachineChange } from './stepfunctions-state-machines';\nimport type { SuccessfulDeployStackResult } from '../deployments';\nimport { IO, SPAN } from '../io/private';\nimport type { IMessageSpan, IoHelper } from '../io/private';\nimport { Mode } from '../plugin';\nimport { ToolkitError } from '../toolkit-error';\n\n// Must use a require() otherwise esbuild complains about calling a namespace\n// eslint-disable-next-line @typescript-eslint/no-require-imports,@typescript-eslint/consistent-type-imports\nconst pLimit: typeof import('p-limit') = require('p-limit');\n\ntype HotswapDetector = (\n logicalId: string,\n change: ResourceChange,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n hotswapPropertyOverrides: HotswapPropertyOverrides,\n) => Promise<HotswapChange[]>;\n\ntype HotswapMode = 'hotswap-only' | 'fall-back';\n\nconst RESOURCE_DETECTORS: { [key: string]: HotswapDetector } = {\n // Lambda\n 'AWS::Lambda::Function': isHotswappableLambdaFunctionChange,\n 'AWS::Lambda::Version': isHotswappableLambdaFunctionChange,\n 'AWS::Lambda::Alias': isHotswappableLambdaFunctionChange,\n\n // AppSync\n 'AWS::AppSync::Resolver': isHotswappableAppSyncChange,\n 'AWS::AppSync::FunctionConfiguration': isHotswappableAppSyncChange,\n 'AWS::AppSync::GraphQLSchema': isHotswappableAppSyncChange,\n 'AWS::AppSync::ApiKey': isHotswappableAppSyncChange,\n\n 'AWS::ECS::TaskDefinition': isHotswappableEcsServiceChange,\n 'AWS::CodeBuild::Project': isHotswappableCodeBuildProjectChange,\n 'AWS::StepFunctions::StateMachine': isHotswappableStateMachineChange,\n 'Custom::CDKBucketDeployment': isHotswappableS3BucketDeploymentChange,\n 'AWS::IAM::Policy': async (\n logicalId: string,\n change: ResourceChange,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n ): Promise<HotswapChange[]> => {\n // If the policy is for a S3BucketDeploymentChange, we can ignore the change\n if (await skipChangeForS3DeployCustomResourcePolicy(logicalId, change, evaluateCfnTemplate)) {\n return [];\n }\n\n return [nonHotswappableResource(change)];\n },\n\n 'AWS::CDK::Metadata': async () => [],\n};\n\n/**\n * Perform a hotswap deployment, short-circuiting CloudFormation if possible.\n * If it's not possible to short-circuit the deployment\n * (because the CDK Stack contains changes that cannot be deployed without CloudFormation),\n * returns `undefined`.\n */\nexport async function tryHotswapDeployment(\n sdkProvider: SdkProvider,\n ioHelper: IoHelper,\n assetParams: { [key: string]: string },\n cloudFormationStack: CloudFormationStack,\n stackArtifact: cxapi.CloudFormationStackArtifact,\n hotswapMode: HotswapMode,\n hotswapPropertyOverrides: HotswapPropertyOverrides,\n): Promise<SuccessfulDeployStackResult | undefined> {\n const hotswapSpan = await ioHelper.span(SPAN.HOTSWAP).begin({\n stack: stackArtifact,\n mode: hotswapMode,\n });\n\n const result = await hotswapDeployment(\n sdkProvider,\n hotswapSpan,\n assetParams,\n stackArtifact,\n hotswapMode,\n hotswapPropertyOverrides,\n );\n\n await hotswapSpan.end(result);\n\n if (result?.hotswapped === true) {\n return {\n type: 'did-deploy-stack',\n noOp: result.hotswappableChanges.length === 0,\n stackArn: cloudFormationStack.stackId,\n outputs: cloudFormationStack.outputs,\n };\n }\n\n return undefined;\n}\n\n/**\n * Perform a hotswap deployment, short-circuiting CloudFormation if possible.\n * Returns information about the attempted hotswap deployment\n */\nasync function hotswapDeployment(\n sdkProvider: SdkProvider,\n ioSpan: IMessageSpan<any>,\n assetParams: { [key: string]: string },\n stack: cxapi.CloudFormationStackArtifact,\n hotswapMode: HotswapMode,\n hotswapPropertyOverrides: HotswapPropertyOverrides,\n): Promise<Omit<HotswapResult, 'duration'>> {\n // resolve the environment, so we can substitute things like AWS::Region in CFN expressions\n const resolvedEnv = await sdkProvider.resolveEnvironment(stack.environment);\n // create a new SDK using the CLI credentials, because the default one will not work for new-style synthesis -\n // it assumes the bootstrap deploy Role, which doesn't have permissions to update Lambda functions\n const sdk = (await sdkProvider.forEnvironment(resolvedEnv, Mode.ForWriting)).sdk;\n\n const currentTemplate = await loadCurrentTemplateWithNestedStacks(stack, sdk);\n\n const evaluateCfnTemplate = new EvaluateCloudFormationTemplate({\n stackArtifact: stack,\n parameters: assetParams,\n account: resolvedEnv.account,\n region: resolvedEnv.region,\n partition: (await sdk.currentAccount()).partition,\n sdk,\n nestedStacks: currentTemplate.nestedStacks,\n });\n\n const stackChanges = cfn_diff.fullDiff(currentTemplate.deployedRootTemplate, stack.template);\n const { hotswappable, nonHotswappable } = await classifyResourceChanges(\n stackChanges,\n evaluateCfnTemplate,\n sdk,\n currentTemplate.nestedStacks, hotswapPropertyOverrides,\n );\n\n await logRejectedChanges(ioSpan, nonHotswappable, hotswapMode);\n\n const hotswappableChanges = hotswappable.map(o => o.change);\n const nonHotswappableChanges = nonHotswappable.map(n => n.change);\n\n await ioSpan.notify(IO.CDK_TOOLKIT_I5401.msg('Hotswap plan created', {\n stack,\n mode: hotswapMode,\n hotswappableChanges,\n nonHotswappableChanges,\n }));\n\n // preserve classic hotswap behavior\n if (hotswapMode === 'fall-back') {\n if (nonHotswappableChanges.length > 0) {\n return {\n stack,\n mode: hotswapMode,\n hotswapped: false,\n hotswappableChanges,\n nonHotswappableChanges,\n };\n }\n }\n\n // apply the short-circuitable changes\n await applyAllHotswapOperations(sdk, ioSpan, hotswappable);\n\n return {\n stack,\n mode: hotswapMode,\n hotswapped: true,\n hotswappableChanges,\n nonHotswappableChanges,\n };\n}\n\ninterface ClassifiedChanges {\n hotswappable: HotswapOperation[];\n nonHotswappable: RejectedChange[];\n}\n\n/**\n * Classifies all changes to all resources as either hotswappable or not.\n * Metadata changes are excluded from the list of (non)hotswappable resources.\n */\nasync function classifyResourceChanges(\n stackChanges: cfn_diff.TemplateDiff,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n sdk: SDK,\n nestedStackNames: { [nestedStackName: string]: NestedStackTemplates },\n hotswapPropertyOverrides: HotswapPropertyOverrides,\n): Promise<ClassifiedChanges> {\n const resourceDifferences = getStackResourceDifferences(stackChanges);\n\n const promises: Array<() => Promise<HotswapChange[]>> = [];\n const hotswappableResources = new Array<HotswapOperation>();\n const nonHotswappableResources = new Array<RejectedChange>();\n for (const logicalId of Object.keys(stackChanges.outputs.changes)) {\n nonHotswappableResources.push({\n hotswappable: false,\n change: {\n reason: NonHotswappableReason.OUTPUT,\n description: 'output was changed',\n subject: {\n type: 'Output',\n logicalId,\n metadata: evaluateCfnTemplate.metadataFor(logicalId),\n },\n },\n });\n }\n // gather the results of the detector functions\n for (const [logicalId, change] of Object.entries(resourceDifferences)) {\n if (change.newValue?.Type === 'AWS::CloudFormation::Stack' && change.oldValue?.Type === 'AWS::CloudFormation::Stack') {\n const nestedHotswappableResources = await findNestedHotswappableChanges(\n logicalId,\n change,\n nestedStackNames,\n evaluateCfnTemplate,\n sdk,\n hotswapPropertyOverrides,\n );\n hotswappableResources.push(...nestedHotswappableResources.hotswappable);\n nonHotswappableResources.push(...nestedHotswappableResources.nonHotswappable);\n\n continue;\n }\n\n const hotswappableChangeCandidate = isCandidateForHotswapping(logicalId, change, evaluateCfnTemplate);\n // we don't need to run this through the detector functions, we can already judge this\n if ('hotswappable' in hotswappableChangeCandidate) {\n if (!hotswappableChangeCandidate.hotswappable) {\n nonHotswappableResources.push(hotswappableChangeCandidate);\n }\n\n continue;\n }\n\n const resourceType: string = hotswappableChangeCandidate.newValue.Type;\n if (resourceType in RESOURCE_DETECTORS) {\n // run detector functions lazily to prevent unhandled promise rejections\n promises.push(() =>\n RESOURCE_DETECTORS[resourceType](logicalId, hotswappableChangeCandidate, evaluateCfnTemplate, hotswapPropertyOverrides),\n );\n } else {\n nonHotswappableResources.push(nonHotswappableResource(hotswappableChangeCandidate));\n }\n }\n\n // resolve all detector results\n const changesDetectionResults: Array<HotswapChange[]> = [];\n for (const detectorResultPromises of promises) {\n // Constant set of promises per resource\n // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism\n const hotswapDetectionResults = await Promise.all(await detectorResultPromises());\n changesDetectionResults.push(hotswapDetectionResults);\n }\n\n for (const resourceDetectionResults of changesDetectionResults) {\n for (const propertyResult of resourceDetectionResults) {\n propertyResult.hotswappable\n ? hotswappableResources.push(propertyResult)\n : nonHotswappableResources.push(propertyResult);\n }\n }\n\n return {\n hotswappable: hotswappableResources,\n nonHotswappable: nonHotswappableResources,\n };\n}\n\n/**\n * Returns all changes to resources in the given Stack.\n *\n * @param stackChanges the collection of all changes to a given Stack\n */\nfunction getStackResourceDifferences(stackChanges: cfn_diff.TemplateDiff): {\n [logicalId: string]: cfn_diff.ResourceDifference;\n} {\n // we need to collapse logical ID rename changes into one change,\n // as they are represented in stackChanges as a pair of two changes: one addition and one removal\n const allResourceChanges: { [logId: string]: cfn_diff.ResourceDifference } = stackChanges.resources.changes;\n const allRemovalChanges = filterDict(allResourceChanges, (resChange) => resChange.isRemoval);\n const allNonRemovalChanges = filterDict(allResourceChanges, (resChange) => !resChange.isRemoval);\n for (const [logId, nonRemovalChange] of Object.entries(allNonRemovalChanges)) {\n if (nonRemovalChange.isAddition) {\n const addChange = nonRemovalChange;\n // search for an identical removal change\n const identicalRemovalChange = Object.entries(allRemovalChanges).find(([_, remChange]) => {\n return changesAreForSameResource(remChange, addChange);\n });\n // if we found one, then this means this is a rename change\n if (identicalRemovalChange) {\n const [removedLogId, removedResourceChange] = identicalRemovalChange;\n allNonRemovalChanges[logId] = makeRenameDifference(removedResourceChange, addChange);\n // delete the removal change that forms the rename pair\n delete allRemovalChanges[removedLogId];\n }\n }\n }\n // the final result are all of the remaining removal changes,\n // plus all of the non-removal changes\n // (we saved the rename changes in that object already)\n return {\n ...allRemovalChanges,\n ...allNonRemovalChanges,\n };\n}\n\n/** Filters an object with string keys based on whether the callback returns 'true' for the given value in the object. */\nfunction filterDict<T>(dict: { [key: string]: T }, func: (t: T) => boolean): { [key: string]: T } {\n return Object.entries(dict).reduce(\n (acc, [key, t]) => {\n if (func(t)) {\n acc[key] = t;\n }\n return acc;\n },\n {} as { [key: string]: T },\n );\n}\n\n/** Finds any hotswappable changes in all nested stacks. */\nasync function findNestedHotswappableChanges(\n logicalId: string,\n change: cfn_diff.ResourceDifference,\n nestedStackTemplates: { [nestedStackName: string]: NestedStackTemplates },\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n sdk: SDK,\n hotswapPropertyOverrides: HotswapPropertyOverrides,\n): Promise<ClassifiedChanges> {\n const nestedStack = nestedStackTemplates[logicalId];\n if (!nestedStack.physicalName) {\n return {\n hotswappable: [],\n nonHotswappable: [\n {\n hotswappable: false,\n change: {\n reason: NonHotswappableReason.NESTED_STACK_CREATION,\n description: 'newly created nested stacks cannot be hotswapped',\n subject: {\n type: 'Resource',\n logicalId,\n resourceType: 'AWS::CloudFormation::Stack',\n metadata: evaluateCfnTemplate.metadataFor(logicalId),\n },\n },\n },\n ],\n };\n }\n\n const evaluateNestedCfnTemplate = await evaluateCfnTemplate.createNestedEvaluateCloudFormationTemplate(\n nestedStack.physicalName,\n nestedStack.generatedTemplate,\n change.newValue?.Properties?.Parameters,\n );\n\n const nestedDiff = cfn_diff.fullDiff(\n nestedStackTemplates[logicalId].deployedTemplate,\n nestedStackTemplates[logicalId].generatedTemplate,\n );\n\n return classifyResourceChanges(\n nestedDiff,\n evaluateNestedCfnTemplate,\n sdk,\n nestedStackTemplates[logicalId].nestedStackTemplates,\n hotswapPropertyOverrides,\n );\n}\n\n/** Returns 'true' if a pair of changes is for the same resource. */\nfunction changesAreForSameResource(\n oldChange: cfn_diff.ResourceDifference,\n newChange: cfn_diff.ResourceDifference,\n): boolean {\n return (\n oldChange.oldResourceType === newChange.newResourceType &&\n // this isn't great, but I don't want to bring in something like underscore just for this comparison\n JSON.stringify(oldChange.oldProperties) === JSON.stringify(newChange.newProperties)\n );\n}\n\nfunction makeRenameDifference(\n remChange: cfn_diff.ResourceDifference,\n addChange: cfn_diff.ResourceDifference,\n): cfn_diff.ResourceDifference {\n return new cfn_diff.ResourceDifference(\n // we have to fill in the old value, because otherwise this will be classified as a non-hotswappable change\n remChange.oldValue,\n addChange.newValue,\n {\n resourceType: {\n oldType: remChange.oldResourceType,\n newType: addChange.newResourceType,\n },\n propertyDiffs: (addChange as any).propertyDiffs,\n otherDiffs: (addChange as any).otherDiffs,\n },\n );\n}\n\n/**\n * Returns a `HotswappableChangeCandidate` if the change is hotswappable\n * Returns an empty `HotswappableChange` if the change is to CDK::Metadata\n * Returns a `NonHotswappableChange` if the change is not hotswappable\n */\nfunction isCandidateForHotswapping(\n logicalId: string,\n change: cfn_diff.ResourceDifference,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): RejectedChange | ResourceChange {\n // a resource has been removed OR a resource has been added; we can't short-circuit that change\n if (!change.oldValue) {\n return {\n hotswappable: false,\n change: {\n reason: NonHotswappableReason.RESOURCE_CREATION,\n description: `resource '${logicalId}' was created by this deployment`,\n subject: {\n type: 'Resource',\n logicalId,\n resourceType: change.newValue!.Type,\n metadata: evaluateCfnTemplate.metadataFor(logicalId),\n },\n },\n };\n } else if (!change.newValue) {\n return {\n hotswappable: false,\n logicalId,\n change: {\n reason: NonHotswappableReason.RESOURCE_DELETION,\n description: `resource '${logicalId}' was destroyed by this deployment`,\n subject: {\n type: 'Resource',\n logicalId,\n resourceType: change.oldValue.Type,\n metadata: evaluateCfnTemplate.metadataFor(logicalId),\n },\n },\n };\n }\n\n // a resource has had its type changed\n if (change.newValue.Type !== change.oldValue.Type) {\n return {\n hotswappable: false,\n change: {\n reason: NonHotswappableReason.RESOURCE_TYPE_CHANGED,\n description: `resource '${logicalId}' had its type changed from '${change.oldValue?.Type}' to '${change.newValue?.Type}'`,\n subject: {\n type: 'Resource',\n logicalId,\n resourceType: change.newValue.Type,\n metadata: evaluateCfnTemplate.metadataFor(logicalId),\n },\n },\n };\n }\n\n return {\n logicalId,\n oldValue: change.oldValue,\n newValue: change.newValue,\n propertyUpdates: change.propertyUpdates,\n metadata: evaluateCfnTemplate.metadataFor(logicalId),\n };\n}\n\nasync function applyAllHotswapOperations(sdk: SDK, ioSpan: IMessageSpan<any>, hotswappableChanges: HotswapOperation[]): Promise<void[]> {\n if (hotswappableChanges.length === 0) {\n return Promise.resolve([]);\n }\n\n await ioSpan.notify(IO.DEFAULT_TOOLKIT_INFO.msg(`\\n${ICON} hotswapping resources:`));\n const limit = pLimit(10);\n // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism\n return Promise.all(hotswappableChanges.map(hotswapOperation => limit(() => {\n return applyHotswapOperation(sdk, ioSpan, hotswapOperation);\n })));\n}\n\nasync function applyHotswapOperation(sdk: SDK, ioSpan: IMessageSpan<any>, hotswapOperation: HotswapOperation): Promise<void> {\n // note the type of service that was successfully hotswapped in the User-Agent\n const customUserAgent = `cdk-hotswap/success-${hotswapOperation.service}`;\n sdk.appendCustomUserAgent(customUserAgent);\n const resourceText = (r: AffectedResource) => r.description ?? `${r.resourceType} '${r.physicalName ?? r.logicalId}'`;\n\n await ioSpan.notify(IO.CDK_TOOLKIT_I5402.msg(\n hotswapOperation.change.resources.map(r => format(` ${ICON} %s`, chalk.bold(resourceText(r)))).join('\\n'),\n hotswapOperation.change,\n ));\n\n // if the SDK call fails, an error will be thrown by the SDK\n // and will prevent the green 'hotswapped!' text from being displayed\n try {\n await hotswapOperation.apply(sdk);\n } catch (e: any) {\n if (e.name === 'TimeoutError' || e.name === 'AbortError') {\n const result: WaiterResult = JSON.parse(formatErrorMessage(e));\n const error = new ToolkitError(formatWaiterErrorResult(result));\n error.name = e.name;\n throw error;\n }\n throw e;\n }\n\n await ioSpan.notify(IO.CDK_TOOLKIT_I5403.msg(\n hotswapOperation.change.resources.map(r => format(` ${ICON} %s %s`, chalk.bold(resourceText(r)), chalk.green('hotswapped!'))).join('\\n'),\n hotswapOperation.change,\n ));\n\n sdk.removeCustomUserAgent(customUserAgent);\n}\n\nfunction formatWaiterErrorResult(result: WaiterResult) {\n const main = [\n `Resource is not in the expected state due to waiter status: ${result.state}`,\n result.reason ? `${result.reason}.` : '',\n ].join('. ');\n\n if (result.observedResponses != null) {\n const observedResponses = Object\n .entries(result.observedResponses)\n .map(([msg, count]) => ` - ${msg} (${count})`)\n .join('\\n');\n\n return `${main} Observed responses:\\n${observedResponses}`;\n }\n\n return main;\n}\n\nasync function logRejectedChanges(\n ioSpan: IMessageSpan<any>,\n rejectedChanges: RejectedChange[],\n hotswapMode: HotswapMode,\n): Promise<void> {\n if (rejectedChanges.length === 0) {\n return;\n }\n /**\n * EKS Services can have a task definition that doesn't refer to the task definition being updated.\n * We have to log this as a non-hotswappable change to the task definition, but when we do,\n * we wind up hotswapping the task definition and logging it as a non-hotswappable change.\n *\n * This logic prevents us from logging that change as non-hotswappable when we hotswap it.\n */\n if (hotswapMode === 'hotswap-only') {\n rejectedChanges = rejectedChanges.filter((change) => change.hotswapOnlyVisible === true);\n\n if (rejectedChanges.length === 0) {\n return;\n }\n }\n\n const messages = ['']; // start with empty line\n\n if (hotswapMode === 'hotswap-only') {\n messages.push(format('%s %s', chalk.red('\u26A0\uFE0F'), chalk.red('The following non-hotswappable changes were found. To reconcile these using CloudFormation, specify --hotswap-fallback')));\n } else {\n messages.push(format('%s %s', chalk.red('\u26A0\uFE0F'), chalk.red('The following non-hotswappable changes were found:')));\n }\n\n for (const { change } of rejectedChanges) {\n messages.push(' ' + nonHotswappableChangeMessage(change));\n }\n messages.push(''); // newline\n\n await ioSpan.notify(IO.DEFAULT_TOOLKIT_INFO.msg(messages.join('\\n')));\n}\n\n/**\n * Formats a NonHotswappableChange\n */\nfunction nonHotswappableChangeMessage(change: NonHotswappableChange): string {\n const subject = change.subject;\n const reason = change.description ?? change.reason;\n\n switch (subject.type) {\n case 'Output':\n return format(\n 'output: %s, reason: %s',\n chalk.bold(subject.logicalId),\n chalk.red(reason),\n );\n case 'Resource':\n return nonHotswappableResourceMessage(subject, reason);\n }\n}\n\n/**\n * Formats a non-hotswappable resource subject\n */\nfunction nonHotswappableResourceMessage(subject: ResourceSubject, reason: string): string {\n if (subject.rejectedProperties?.length) {\n return format(\n 'resource: %s, type: %s, rejected changes: %s, reason: %s',\n chalk.bold(subject.logicalId),\n chalk.bold(subject.resourceType),\n chalk.bold(subject.rejectedProperties),\n chalk.red(reason),\n );\n }\n\n return format(\n 'resource: %s, type: %s, reason: %s',\n chalk.bold(subject.logicalId),\n chalk.bold(subject.resourceType),\n chalk.red(reason),\n );\n}\n", "import { ToolkitError } from '../toolkit-error';\n\nexport type DeployStackResult =\n | SuccessfulDeployStackResult\n | NeedRollbackFirstDeployStackResult\n | ReplacementRequiresRollbackStackResult\n ;\n\n/** Successfully deployed a stack */\nexport interface SuccessfulDeployStackResult {\n readonly type: 'did-deploy-stack';\n readonly noOp: boolean;\n readonly outputs: { [name: string]: string };\n readonly stackArn: string;\n}\n\n/** The stack is currently in a failpaused state, and needs to be rolled back before the deployment */\nexport interface NeedRollbackFirstDeployStackResult {\n readonly type: 'failpaused-need-rollback-first';\n readonly reason: 'not-norollback' | 'replacement';\n readonly status: string;\n}\n\n/** The upcoming change has a replacement, which requires deploying with --rollback */\nexport interface ReplacementRequiresRollbackStackResult {\n readonly type: 'replacement-requires-rollback';\n}\n\nexport function assertIsSuccessfulDeployStackResult(x: DeployStackResult): asserts x is SuccessfulDeployStackResult {\n if (x.type !== 'did-deploy-stack') {\n throw new ToolkitError(`Unexpected deployStack result. This should not happen: ${JSON.stringify(x)}. If you are seeing this error, please report it at https://github.com/aws/aws-cdk/issues/new/choose.`);\n }\n}\n", "import type {\n GetSchemaCreationStatusCommandOutput,\n GetSchemaCreationStatusCommandInput,\n} from '@aws-sdk/client-appsync';\nimport {\n type HotswapChange,\n classifyChanges,\n} from './common';\nimport type { ResourceChange } from '../../payloads/hotswap';\nimport { lowerCaseFirstCharacter, transformObjectKeys } from '../../util';\nimport type { SDK } from '../aws-auth';\n\nimport type { EvaluateCloudFormationTemplate } from '../cloudformation';\nimport { ToolkitError } from '../toolkit-error';\n\nexport async function isHotswappableAppSyncChange(\n logicalId: string,\n change: ResourceChange,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): Promise<HotswapChange[]> {\n const isResolver = change.newValue.Type === 'AWS::AppSync::Resolver';\n const isFunction = change.newValue.Type === 'AWS::AppSync::FunctionConfiguration';\n const isGraphQLSchema = change.newValue.Type === 'AWS::AppSync::GraphQLSchema';\n const isAPIKey = change.newValue.Type === 'AWS::AppSync::ApiKey';\n if (!isResolver && !isFunction && !isGraphQLSchema && !isAPIKey) {\n return [];\n }\n\n const ret: HotswapChange[] = [];\n\n const classifiedChanges = classifyChanges(change, [\n 'RequestMappingTemplate',\n 'RequestMappingTemplateS3Location',\n 'ResponseMappingTemplate',\n 'ResponseMappingTemplateS3Location',\n 'Code',\n 'CodeS3Location',\n 'Definition',\n 'DefinitionS3Location',\n 'Expires',\n ]);\n classifiedChanges.reportNonHotswappablePropertyChanges(ret);\n\n const namesOfHotswappableChanges = Object.keys(classifiedChanges.hotswappableProps);\n if (namesOfHotswappableChanges.length > 0) {\n let physicalName: string | undefined = undefined;\n const arn = await evaluateCfnTemplate.establishResourcePhysicalName(\n logicalId,\n isFunction ? change.newValue.Properties?.Name : undefined,\n );\n if (isResolver) {\n const arnParts = arn?.split('/');\n physicalName = arnParts ? `${arnParts[3]}.${arnParts[5]}` : undefined;\n } else {\n physicalName = arn;\n }\n\n // nothing do here\n if (!physicalName) {\n return ret;\n }\n\n ret.push({\n change: {\n cause: change,\n resources: [{\n logicalId,\n resourceType: change.newValue.Type,\n physicalName,\n metadata: evaluateCfnTemplate.metadataFor(logicalId),\n }],\n },\n hotswappable: true,\n service: 'appsync',\n apply: async (sdk: SDK) => {\n const sdkProperties: { [name: string]: any } = {\n ...change.oldValue.Properties,\n Definition: change.newValue.Properties?.Definition,\n DefinitionS3Location: change.newValue.Properties?.DefinitionS3Location,\n requestMappingTemplate: change.newValue.Properties?.RequestMappingTemplate,\n requestMappingTemplateS3Location: change.newValue.Properties?.RequestMappingTemplateS3Location,\n responseMappingTemplate: change.newValue.Properties?.ResponseMappingTemplate,\n responseMappingTemplateS3Location: change.newValue.Properties?.ResponseMappingTemplateS3Location,\n code: change.newValue.Properties?.Code,\n codeS3Location: change.newValue.Properties?.CodeS3Location,\n expires: change.newValue.Properties?.Expires,\n };\n const evaluatedResourceProperties = await evaluateCfnTemplate.evaluateCfnExpression(sdkProperties);\n const sdkRequestObject = transformObjectKeys(evaluatedResourceProperties, lowerCaseFirstCharacter);\n\n // resolve s3 location files as SDK doesn't take in s3 location but inline code\n if (sdkRequestObject.requestMappingTemplateS3Location) {\n sdkRequestObject.requestMappingTemplate = await fetchFileFromS3(\n sdkRequestObject.requestMappingTemplateS3Location,\n sdk,\n );\n delete sdkRequestObject.requestMappingTemplateS3Location;\n }\n if (sdkRequestObject.responseMappingTemplateS3Location) {\n sdkRequestObject.responseMappingTemplate = await fetchFileFromS3(\n sdkRequestObject.responseMappingTemplateS3Location,\n sdk,\n );\n delete sdkRequestObject.responseMappingTemplateS3Location;\n }\n if (sdkRequestObject.definitionS3Location) {\n sdkRequestObject.definition = await fetchFileFromS3(sdkRequestObject.definitionS3Location, sdk);\n delete sdkRequestObject.definitionS3Location;\n }\n if (sdkRequestObject.codeS3Location) {\n sdkRequestObject.code = await fetchFileFromS3(sdkRequestObject.codeS3Location, sdk);\n delete sdkRequestObject.codeS3Location;\n }\n\n if (isResolver) {\n await sdk.appsync().updateResolver(sdkRequestObject);\n } else if (isFunction) {\n // Function version is only applicable when using VTL and mapping templates\n // Runtime only applicable when using code (JS mapping templates)\n if (sdkRequestObject.code) {\n delete sdkRequestObject.functionVersion;\n } else {\n delete sdkRequestObject.runtime;\n }\n\n const functions = await sdk.appsync().listFunctions({ apiId: sdkRequestObject.apiId });\n const { functionId } = functions.find((fn) => fn.name === physicalName) ?? {};\n // Updating multiple functions at the same time or along with graphql schema results in `ConcurrentModificationException`\n await exponentialBackOffRetry(\n () =>\n sdk.appsync().updateFunction({\n ...sdkRequestObject,\n functionId: functionId,\n }),\n 6,\n 1000,\n 'ConcurrentModificationException',\n );\n } else if (isGraphQLSchema) {\n let schemaCreationResponse: GetSchemaCreationStatusCommandOutput = await sdk\n .appsync()\n .startSchemaCreation(sdkRequestObject);\n while (\n schemaCreationResponse.status &&\n ['PROCESSING', 'DELETING'].some((status) => status === schemaCreationResponse.status)\n ) {\n await sleep(1000); // poll every second\n const getSchemaCreationStatusRequest: GetSchemaCreationStatusCommandInput = {\n apiId: sdkRequestObject.apiId,\n };\n schemaCreationResponse = await sdk.appsync().getSchemaCreationStatus(getSchemaCreationStatusRequest);\n }\n if (schemaCreationResponse.status === 'FAILED') {\n throw new ToolkitError(schemaCreationResponse.details ?? 'Schema creation has failed.');\n }\n } else {\n // isApiKey\n if (!sdkRequestObject.id) {\n // ApiKeyId is optional in CFN but required in SDK. Grab the KeyId from physicalArn if not available as part of CFN template\n const arnParts = physicalName?.split('/');\n if (arnParts && arnParts.length === 4) {\n sdkRequestObject.id = arnParts[3];\n }\n }\n await sdk.appsync().updateApiKey(sdkRequestObject);\n }\n },\n });\n }\n\n return ret;\n}\n\nasync function fetchFileFromS3(s3Url: string, sdk: SDK) {\n const s3PathParts = s3Url.split('/');\n const s3Bucket = s3PathParts[2]; // first two are \"s3:\" and \"\" due to s3://\n const s3Key = s3PathParts.splice(3).join('/'); // after removing first three we reconstruct the key\n return (await sdk.s3().getObject({ Bucket: s3Bucket, Key: s3Key })).Body?.transformToString();\n}\n\nasync function exponentialBackOffRetry(fn: () => Promise<any>, numOfRetries: number, backOff: number, errorCodeToRetry: string) {\n try {\n await fn();\n } catch (error: any) {\n if (error && error.name === errorCodeToRetry && numOfRetries > 0) {\n await sleep(backOff); // time to wait doubles everytime function fails, starts at 1 second\n await exponentialBackOffRetry(fn, numOfRetries - 1, backOff * 2, errorCodeToRetry);\n } else {\n throw error;\n }\n }\n}\n\nasync function sleep(ms: number) {\n return new Promise((ok) => setTimeout(ok, ms));\n}\n", "import type { UpdateProjectCommandInput } from '@aws-sdk/client-codebuild';\nimport {\n type HotswapChange,\n classifyChanges,\n} from './common';\nimport type { ResourceChange } from '../../payloads/hotswap';\nimport { lowerCaseFirstCharacter, transformObjectKeys } from '../../util';\nimport type { SDK } from '../aws-auth';\nimport type { EvaluateCloudFormationTemplate } from '../cloudformation';\n\nexport async function isHotswappableCodeBuildProjectChange(\n logicalId: string,\n change: ResourceChange,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): Promise<HotswapChange[]> {\n if (change.newValue.Type !== 'AWS::CodeBuild::Project') {\n return [];\n }\n\n const ret: HotswapChange[] = [];\n\n const classifiedChanges = classifyChanges(change, ['Source', 'Environment', 'SourceVersion']);\n classifiedChanges.reportNonHotswappablePropertyChanges(ret);\n if (classifiedChanges.namesOfHotswappableProps.length > 0) {\n const updateProjectInput: UpdateProjectCommandInput = {\n name: '',\n };\n const projectName = await evaluateCfnTemplate.establishResourcePhysicalName(\n logicalId,\n change.newValue.Properties?.Name,\n );\n\n // nothing to do jere\n if (!projectName) {\n return ret;\n }\n\n ret.push({\n change: {\n cause: change,\n resources: [{\n logicalId: logicalId,\n resourceType: change.newValue.Type,\n physicalName: projectName,\n metadata: evaluateCfnTemplate.metadataFor(logicalId),\n }],\n },\n hotswappable: true,\n service: 'codebuild',\n apply: async (sdk: SDK) => {\n updateProjectInput.name = projectName;\n\n for (const updatedPropName in change.propertyUpdates) {\n const updatedProp = change.propertyUpdates[updatedPropName];\n switch (updatedPropName) {\n case 'Source':\n updateProjectInput.source = transformObjectKeys(\n await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue),\n convertSourceCloudformationKeyToSdkKey,\n );\n break;\n case 'Environment':\n updateProjectInput.environment = await transformObjectKeys(\n await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue),\n lowerCaseFirstCharacter,\n );\n break;\n case 'SourceVersion':\n updateProjectInput.sourceVersion = await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue);\n break;\n }\n }\n\n await sdk.codeBuild().updateProject(updateProjectInput);\n },\n });\n }\n\n return ret;\n}\n\nfunction convertSourceCloudformationKeyToSdkKey(key: string): string {\n if (key.toLowerCase() === 'buildspec') {\n return key.toLowerCase();\n }\n return lowerCaseFirstCharacter(key);\n}\n", "import type {\n HotswapPropertyOverrides,\n HotswapChange,\n} from './common';\nimport {\n classifyChanges,\n nonHotswappableChange,\n} from './common';\nimport { NonHotswappableReason, type ResourceChange } from '../../payloads/hotswap';\nimport { lowerCaseFirstCharacter, transformObjectKeys } from '../../util';\nimport type { SDK } from '../aws-auth';\nimport type { EvaluateCloudFormationTemplate } from '../cloudformation';\n\nconst ECS_SERVICE_RESOURCE_TYPE = 'AWS::ECS::Service';\n\nexport async function isHotswappableEcsServiceChange(\n logicalId: string,\n change: ResourceChange,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n hotswapPropertyOverrides: HotswapPropertyOverrides,\n): Promise<HotswapChange[]> {\n // the only resource change we can evaluate here is an ECS TaskDefinition\n if (change.newValue.Type !== 'AWS::ECS::TaskDefinition') {\n return [];\n }\n\n const ret: HotswapChange[] = [];\n\n // We only allow a change in the ContainerDefinitions of the TaskDefinition for now -\n // it contains the image and environment variables, so seems like a safe bet for now.\n // We might revisit this decision in the future though!\n const classifiedChanges = classifyChanges(change, ['ContainerDefinitions']);\n classifiedChanges.reportNonHotswappablePropertyChanges(ret);\n\n // find all ECS Services that reference the TaskDefinition that changed\n const resourcesReferencingTaskDef = evaluateCfnTemplate.findReferencesTo(logicalId);\n const ecsServiceResourcesReferencingTaskDef = resourcesReferencingTaskDef.filter(\n (r) => r.Type === ECS_SERVICE_RESOURCE_TYPE,\n );\n const ecsServicesReferencingTaskDef = new Array<EcsService>();\n for (const ecsServiceResource of ecsServiceResourcesReferencingTaskDef) {\n const serviceArn = await evaluateCfnTemplate.findPhysicalNameFor(ecsServiceResource.LogicalId);\n if (serviceArn) {\n ecsServicesReferencingTaskDef.push({\n logicalId: ecsServiceResource.LogicalId,\n serviceArn,\n });\n }\n }\n if (ecsServicesReferencingTaskDef.length === 0) {\n /**\n * ECS Services can have a task definition that doesn't refer to the task definition being updated.\n * We have to log this as a non-hotswappable change to the task definition, but when we do,\n * we wind up hotswapping the task definition and logging it as a non-hotswappable change.\n *\n * This logic prevents us from logging that change as non-hotswappable when we hotswap it.\n */\n ret.push(nonHotswappableChange(\n change,\n NonHotswappableReason.DEPENDENCY_UNSUPPORTED,\n 'No ECS services reference the changed task definition',\n undefined,\n false,\n ));\n }\n if (resourcesReferencingTaskDef.length > ecsServicesReferencingTaskDef.length) {\n // if something besides an ECS Service is referencing the TaskDefinition,\n // hotswap is not possible in FALL_BACK mode\n const nonEcsServiceTaskDefRefs = resourcesReferencingTaskDef.filter((r) => r.Type !== ECS_SERVICE_RESOURCE_TYPE);\n for (const taskRef of nonEcsServiceTaskDefRefs) {\n ret.push(nonHotswappableChange(\n change,\n NonHotswappableReason.DEPENDENCY_UNSUPPORTED,\n `A resource '${taskRef.LogicalId}' with Type '${taskRef.Type}' that is not an ECS Service was found referencing the changed TaskDefinition '${logicalId}'`,\n ));\n }\n }\n\n const namesOfHotswappableChanges = Object.keys(classifiedChanges.hotswappableProps);\n if (namesOfHotswappableChanges.length > 0) {\n const taskDefinitionResource = await prepareTaskDefinitionChange(evaluateCfnTemplate, logicalId, change);\n ret.push({\n change: {\n cause: change,\n resources: [\n {\n logicalId,\n resourceType: change.newValue.Type,\n physicalName: await taskDefinitionResource.Family,\n metadata: evaluateCfnTemplate.metadataFor(logicalId),\n },\n ...ecsServicesReferencingTaskDef.map((ecsService) => ({\n resourceType: ECS_SERVICE_RESOURCE_TYPE,\n physicalName: ecsService.serviceArn.split('/')[2],\n logicalId: ecsService.logicalId,\n metadata: evaluateCfnTemplate.metadataFor(ecsService.logicalId),\n })),\n ],\n },\n hotswappable: true,\n service: 'ecs-service',\n apply: async (sdk: SDK) => {\n // Step 1 - update the changed TaskDefinition, creating a new TaskDefinition Revision\n // we need to lowercase the evaluated TaskDef from CloudFormation,\n // as the AWS SDK uses lowercase property names for these\n\n // The SDK requires more properties here than its worth doing explicit typing for\n // instead, just use all the old values in the diff to fill them in implicitly\n const lowercasedTaskDef = transformObjectKeys(taskDefinitionResource, lowerCaseFirstCharacter, {\n // All the properties that take arbitrary string as keys i.e. { \"string\" : \"string\" }\n // https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_RegisterTaskDefinition.html#API_RegisterTaskDefinition_RequestSyntax\n ContainerDefinitions: {\n DockerLabels: true,\n FirelensConfiguration: {\n Options: true,\n },\n LogConfiguration: {\n Options: true,\n },\n },\n Volumes: {\n DockerVolumeConfiguration: {\n DriverOpts: true,\n Labels: true,\n },\n },\n });\n const registerTaskDefResponse = await sdk.ecs().registerTaskDefinition(lowercasedTaskDef);\n const taskDefRevArn = registerTaskDefResponse.taskDefinition?.taskDefinitionArn;\n\n let ecsHotswapProperties = hotswapPropertyOverrides.ecsHotswapProperties;\n let minimumHealthyPercent = ecsHotswapProperties?.minimumHealthyPercent;\n let maximumHealthyPercent = ecsHotswapProperties?.maximumHealthyPercent;\n\n // Step 2 - update the services using that TaskDefinition to point to the new TaskDefinition Revision\n // Forcing New Deployment and setting Minimum Healthy Percent to 0.\n // As CDK HotSwap is development only, this seems the most efficient way to ensure all tasks are replaced immediately, regardless of original amount\n // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism\n await Promise.all(\n ecsServicesReferencingTaskDef.map(async (service) => {\n const cluster = service.serviceArn.split('/')[1];\n const update = await sdk.ecs().updateService({\n service: service.serviceArn,\n taskDefinition: taskDefRevArn,\n cluster,\n forceNewDeployment: true,\n deploymentConfiguration: {\n minimumHealthyPercent: minimumHealthyPercent !== undefined ? minimumHealthyPercent : 0,\n maximumPercent: maximumHealthyPercent !== undefined ? maximumHealthyPercent : undefined,\n },\n });\n\n await sdk.ecs().waitUntilServicesStable({\n cluster: update.service?.clusterArn,\n services: [service.serviceArn],\n });\n }),\n );\n },\n });\n }\n\n return ret;\n}\n\ninterface EcsService {\n readonly logicalId: string;\n readonly serviceArn: string;\n}\n\nasync function prepareTaskDefinitionChange(\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n logicalId: string,\n change: ResourceChange,\n) {\n const taskDefinitionResource: { [name: string]: any } = {\n ...change.oldValue.Properties,\n ContainerDefinitions: change.newValue.Properties?.ContainerDefinitions,\n };\n // first, let's get the name of the family\n const familyNameOrArn = await evaluateCfnTemplate.establishResourcePhysicalName(\n logicalId,\n taskDefinitionResource?.Family,\n );\n if (!familyNameOrArn) {\n // if the Family property has not been provided, and we can't find it in the current Stack,\n // this means hotswapping is not possible\n return;\n }\n // the physical name of the Task Definition in CloudFormation includes its current revision number at the end,\n // remove it if needed\n const familyNameOrArnParts = familyNameOrArn.split(':');\n const family =\n familyNameOrArnParts.length > 1\n ? // familyNameOrArn is actually an ARN, of the format 'arn:aws:ecs:region:account:task-definition/<family-name>:<revision-nr>'\n // so, take the 6th element, at index 5, and split it on '/'\n familyNameOrArnParts[5].split('/')[1]\n : // otherwise, familyNameOrArn is just the simple name evaluated from the CloudFormation template\n familyNameOrArn;\n // then, let's evaluate the body of the remainder of the TaskDef (without the Family property)\n return {\n ...(await evaluateCfnTemplate.evaluateCfnExpression({\n ...(taskDefinitionResource ?? {}),\n Family: undefined,\n })),\n Family: family,\n };\n}\n", "import { Writable } from 'stream';\nimport type { PropertyDifference } from '@aws-cdk/cloudformation-diff';\nimport type { FunctionConfiguration, UpdateFunctionConfigurationCommandInput } from '@aws-sdk/client-lambda';\nimport type { HotswapChange } from './common';\nimport { classifyChanges } from './common';\nimport type { AffectedResource, ResourceChange } from '../../payloads/hotswap';\nimport { flatMap } from '../../util';\nimport type { ILambdaClient, SDK } from '../aws-auth';\nimport { CfnEvaluationException, type EvaluateCloudFormationTemplate } from '../cloudformation';\nimport { ToolkitError } from '../toolkit-error';\n\n// namespace object imports won't work in the bundle for function exports\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nconst archiver = require('archiver');\n\nexport async function isHotswappableLambdaFunctionChange(\n logicalId: string,\n change: ResourceChange,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): Promise<HotswapChange[]> {\n // if the change is for a Lambda Version, we just ignore it\n // we will publish a new version when we get to hotswapping the actual Function this Version points to\n // (Versions can't be changed in CloudFormation anyway, they're immutable)\n if (change.newValue.Type === 'AWS::Lambda::Version') {\n return [];\n }\n\n // we handle Aliases specially too\n // the actual alias update will happen if we change the function\n if (change.newValue.Type === 'AWS::Lambda::Alias') {\n return classifyAliasChanges(change);\n }\n\n if (change.newValue.Type !== 'AWS::Lambda::Function') {\n return [];\n }\n\n const ret: HotswapChange[] = [];\n const classifiedChanges = classifyChanges(change, ['Code', 'Environment', 'Description']);\n classifiedChanges.reportNonHotswappablePropertyChanges(ret);\n\n const functionName = await evaluateCfnTemplate.establishResourcePhysicalName(\n logicalId,\n change.newValue.Properties?.FunctionName,\n );\n const namesOfHotswappableChanges = Object.keys(classifiedChanges.hotswappableProps);\n if (functionName && namesOfHotswappableChanges.length > 0) {\n const lambdaCodeChange = await evaluateLambdaFunctionProps(\n classifiedChanges.hotswappableProps,\n change.newValue.Properties?.Runtime,\n evaluateCfnTemplate,\n );\n\n // nothing to do here\n if (lambdaCodeChange === undefined) {\n return ret;\n }\n\n const dependencies = await dependantResources(logicalId, functionName, evaluateCfnTemplate);\n\n ret.push({\n change: {\n cause: change,\n resources: [\n {\n logicalId,\n resourceType: change.newValue.Type,\n physicalName: functionName,\n metadata: evaluateCfnTemplate.metadataFor(logicalId),\n },\n ...dependencies,\n ],\n },\n hotswappable: true,\n service: 'lambda',\n apply: async (sdk: SDK) => {\n const lambda = sdk.lambda();\n const operations: Promise<any>[] = [];\n\n if (lambdaCodeChange.code !== undefined || lambdaCodeChange.configurations !== undefined) {\n if (lambdaCodeChange.code !== undefined) {\n const updateFunctionCodeResponse = await lambda.updateFunctionCode({\n FunctionName: functionName,\n S3Bucket: lambdaCodeChange.code.s3Bucket,\n S3Key: lambdaCodeChange.code.s3Key,\n ImageUri: lambdaCodeChange.code.imageUri,\n ZipFile: lambdaCodeChange.code.functionCodeZip,\n S3ObjectVersion: lambdaCodeChange.code.s3ObjectVersion,\n });\n\n await waitForLambdasPropertiesUpdateToFinish(updateFunctionCodeResponse, lambda, functionName);\n }\n\n if (lambdaCodeChange.configurations !== undefined) {\n const updateRequest: UpdateFunctionConfigurationCommandInput = {\n FunctionName: functionName,\n };\n if (lambdaCodeChange.configurations.description !== undefined) {\n updateRequest.Description = lambdaCodeChange.configurations.description;\n }\n if (lambdaCodeChange.configurations.environment !== undefined) {\n updateRequest.Environment = lambdaCodeChange.configurations.environment;\n }\n const updateFunctionCodeResponse = await lambda.updateFunctionConfiguration(updateRequest);\n await waitForLambdasPropertiesUpdateToFinish(updateFunctionCodeResponse, lambda, functionName);\n }\n\n // only if the code changed is there any point in publishing a new Version\n const versions = dependencies.filter((d) => d.resourceType === 'AWS::Lambda::Version');\n if (versions.length) {\n const publishVersionPromise = lambda.publishVersion({\n FunctionName: functionName,\n });\n\n const aliases = dependencies.filter((d) => d.resourceType === 'AWS::Lambda::Alias');\n if (aliases.length) {\n // we need to wait for the Version to finish publishing\n const versionUpdate = await publishVersionPromise;\n for (const alias of aliases) {\n operations.push(\n lambda.updateAlias({\n FunctionName: functionName,\n Name: alias.physicalName,\n FunctionVersion: versionUpdate.Version,\n }),\n );\n }\n } else {\n operations.push(publishVersionPromise);\n }\n }\n }\n\n // run all of our updates in parallel\n // Limited set of updates per function\n // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism\n await Promise.all(operations);\n },\n });\n }\n\n return ret;\n}\n\n/**\n * Determines which changes to this Alias are hotswappable or not\n */\nfunction classifyAliasChanges(change: ResourceChange): HotswapChange[] {\n const ret: HotswapChange[] = [];\n const classifiedChanges = classifyChanges(change, ['FunctionVersion']);\n classifiedChanges.reportNonHotswappablePropertyChanges(ret);\n\n // we only want to report not hotswappable changes to aliases\n // the actual alias update will happen if we change the function\n\n return ret;\n}\n\n/**\n * Evaluates the hotswappable properties of an AWS::Lambda::Function and\n * Returns a `LambdaFunctionChange` if the change is hotswappable.\n * Returns `undefined` if the change is not hotswappable.\n */\nasync function evaluateLambdaFunctionProps(\n hotswappablePropChanges: Record<string, PropertyDifference<any>>,\n runtime: string,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): Promise<LambdaFunctionChange | undefined> {\n /*\n * At first glance, we would want to initialize these using the \"previous\" values (change.oldValue),\n * in case only one of them changed, like the key, and the Bucket stayed the same.\n * However, that actually fails for old-style synthesis, which uses CFN Parameters!\n * Because the names of the Parameters depend on the hash of the Asset,\n * the Parameters used for the \"old\" values no longer exist in `assetParams` at this point,\n * which means we don't have the correct values available to evaluate the CFN expression with.\n * Fortunately, the diff will always include both the s3Bucket and s3Key parts of the Lambda's Code property,\n * even if only one of them was actually changed,\n * which means we don't need the \"old\" values at all, and we can safely initialize these with just `''`.\n */\n let code: LambdaFunctionCode | undefined = undefined;\n let description: string | undefined = undefined;\n let environment: { [key: string]: string } | undefined = undefined;\n\n for (const updatedPropName in hotswappablePropChanges) {\n const updatedProp = hotswappablePropChanges[updatedPropName];\n\n switch (updatedPropName) {\n case 'Code':\n let s3Bucket, s3Key, s3ObjectVersion, imageUri, functionCodeZip;\n\n for (const newPropName in updatedProp.newValue) {\n switch (newPropName) {\n case 'S3Bucket':\n s3Bucket = await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue[newPropName]);\n break;\n case 'S3Key':\n s3Key = await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue[newPropName]);\n break;\n case 'S3ObjectVersion':\n s3ObjectVersion = await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue[newPropName]);\n break;\n case 'ImageUri':\n imageUri = await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue[newPropName]);\n break;\n case 'ZipFile':\n // We must create a zip package containing a file with the inline code\n const functionCode = await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue[newPropName]);\n const functionRuntime = await evaluateCfnTemplate.evaluateCfnExpression(runtime);\n if (!functionRuntime) {\n return undefined;\n }\n // file extension must be chosen depending on the runtime\n const codeFileExt = determineCodeFileExtFromRuntime(functionRuntime);\n functionCodeZip = await zipString(`index.${codeFileExt}`, functionCode);\n break;\n }\n }\n code = {\n s3Bucket,\n s3Key,\n s3ObjectVersion,\n imageUri,\n functionCodeZip,\n };\n break;\n case 'Description':\n description = await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue);\n break;\n case 'Environment':\n environment = await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue);\n break;\n default:\n // we will never get here, but just in case we do throw an error\n throw new ToolkitError(\n 'while apply()ing, found a property that cannot be hotswapped. Please report this at github.com/aws/aws-cdk/issues/new/choose',\n );\n }\n }\n\n const configurations = description || environment ? { description, environment } : undefined;\n return code || configurations ? { code, configurations } : undefined;\n}\n\ninterface LambdaFunctionCode {\n readonly s3Bucket?: string;\n readonly s3Key?: string;\n readonly s3ObjectVersion?: string;\n readonly imageUri?: string;\n readonly functionCodeZip?: Buffer;\n}\n\ninterface LambdaFunctionConfigurations {\n readonly description?: string;\n readonly environment?: { [key: string]: string };\n}\n\ninterface LambdaFunctionChange {\n readonly code?: LambdaFunctionCode;\n readonly configurations?: LambdaFunctionConfigurations;\n}\n\n/**\n * Compress a string as a file, returning a promise for the zip buffer\n * https://github.com/archiverjs/node-archiver/issues/342\n */\nfunction zipString(fileName: string, rawString: string): Promise<Buffer> {\n return new Promise((resolve, reject) => {\n const buffers: Buffer[] = [];\n\n const converter = new Writable();\n\n converter._write = (chunk: Buffer, _: string, callback: () => void) => {\n buffers.push(chunk);\n process.nextTick(callback);\n };\n\n converter.on('finish', () => {\n resolve(Buffer.concat(buffers));\n });\n\n const archive = archiver('zip');\n\n archive.on('error', (err: any) => {\n reject(err);\n });\n\n archive.pipe(converter);\n\n archive.append(rawString, {\n name: fileName,\n date: new Date('1980-01-01T00:00:00.000Z'), // Add date to make resulting zip file deterministic\n });\n\n void archive.finalize();\n });\n}\n\n/**\n * After a Lambda Function is updated, it cannot be updated again until the\n * `State=Active` and the `LastUpdateStatus=Successful`.\n *\n * Depending on the configuration of the Lambda Function this could happen relatively quickly\n * or very slowly. For example, Zip based functions _not_ in a VPC can take ~1 second whereas VPC\n * or Container functions can take ~25 seconds (and 'idle' VPC functions can take minutes).\n */\nasync function waitForLambdasPropertiesUpdateToFinish(\n currentFunctionConfiguration: FunctionConfiguration,\n lambda: ILambdaClient,\n functionName: string,\n): Promise<void> {\n const functionIsInVpcOrUsesDockerForCode =\n currentFunctionConfiguration.VpcConfig?.VpcId || currentFunctionConfiguration.PackageType === 'Image';\n\n // if the function is deployed in a VPC or if it is a container image function\n // then the update will take much longer and we can wait longer between checks\n // otherwise, the update will be quick, so a 1-second delay is fine\n const delaySeconds = functionIsInVpcOrUsesDockerForCode ? 5 : 1;\n\n await lambda.waitUntilFunctionUpdated(delaySeconds, {\n FunctionName: functionName,\n });\n}\n\n/**\n * Get file extension from Lambda runtime string.\n * We use this extension to create a deployment package from Lambda inline code.\n */\nfunction determineCodeFileExtFromRuntime(runtime: string): string {\n if (runtime.startsWith('node')) {\n return 'js';\n }\n if (runtime.startsWith('python')) {\n return 'py';\n }\n // Currently inline code only supports Node.js and Python, ignoring other runtimes.\n // https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-code.html#aws-properties-lambda-function-code-properties\n throw new CfnEvaluationException(\n `runtime ${runtime} is unsupported, only node.js and python runtimes are currently supported.`,\n );\n}\n\n/**\n * Finds all Versions that reference an AWS::Lambda::Function with logical ID `logicalId`\n * and Aliases that reference those Versions.\n */\nasync function versionsAndAliases(logicalId: string, evaluateCfnTemplate: EvaluateCloudFormationTemplate) {\n // find all Lambda Versions that reference this Function\n const versionsReferencingFunction = evaluateCfnTemplate\n .findReferencesTo(logicalId)\n .filter((r) => r.Type === 'AWS::Lambda::Version');\n // find all Lambda Aliases that reference the above Versions\n const aliasesReferencingVersions = flatMap(versionsReferencingFunction, v =>\n evaluateCfnTemplate.findReferencesTo(v.LogicalId));\n\n return { versionsReferencingFunction, aliasesReferencingVersions };\n}\n\nasync function dependantResources(\n logicalId: string,\n functionName: string,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): Promise<Array<AffectedResource>> {\n const candidates = await versionsAndAliases(logicalId, evaluateCfnTemplate);\n\n // Limited set of updates per function\n // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism\n const aliases = await Promise.all(candidates.aliasesReferencingVersions.map(async (a) => {\n const name = await evaluateCfnTemplate.evaluateCfnExpression(a.Properties?.Name);\n return {\n logicalId: a.LogicalId,\n resourceType: a.Type,\n physicalName: name,\n description: `${a.Type} '${name}' for AWS::Lambda::Function '${functionName}'`,\n metadata: evaluateCfnTemplate.metadataFor(a.LogicalId),\n };\n }));\n\n const versions = candidates.versionsReferencingFunction.map((v) => (\n {\n logicalId: v.LogicalId,\n resourceType: v.Type,\n description: `${v.Type} for AWS::Lambda::Function '${functionName}'`,\n metadata: evaluateCfnTemplate.metadataFor(v.LogicalId),\n }\n ));\n\n return [\n ...versions,\n ...aliases,\n ];\n}\n", "import type { HotswapChange } from './common';\nimport type { ResourceChange } from '../../payloads/hotswap';\nimport type { SDK } from '../aws-auth';\nimport type { EvaluateCloudFormationTemplate } from '../cloudformation';\n\n/**\n * This means that the value is required to exist by CloudFormation's Custom Resource API (or our S3 Bucket Deployment Lambda's API)\n * but the actual value specified is irrelevant\n */\nconst REQUIRED_BY_CFN = 'required-to-be-present-by-cfn';\n\nconst CDK_BUCKET_DEPLOYMENT_CFN_TYPE = 'Custom::CDKBucketDeployment';\n\nexport async function isHotswappableS3BucketDeploymentChange(\n logicalId: string,\n change: ResourceChange,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): Promise<HotswapChange[]> {\n // In old-style synthesis, the policy used by the lambda to copy assets Ref's the assets directly,\n // meaning that the changes made to the Policy are artifacts that can be safely ignored\n const ret: HotswapChange[] = [];\n\n if (change.newValue.Type !== CDK_BUCKET_DEPLOYMENT_CFN_TYPE) {\n return [];\n }\n\n // no classification to be done here; all the properties of this custom resource thing are hotswappable\n const customResourceProperties = await evaluateCfnTemplate.evaluateCfnExpression({\n ...change.newValue.Properties,\n ServiceToken: undefined,\n });\n\n // note that this gives the ARN of the lambda, not the name. This is fine though, the invoke() sdk call will take either\n const functionName = await evaluateCfnTemplate.evaluateCfnExpression(change.newValue.Properties?.ServiceToken);\n if (!functionName) {\n return ret;\n }\n\n ret.push({\n change: {\n cause: change,\n resources: [{\n logicalId,\n physicalName: customResourceProperties.DestinationBucketName,\n resourceType: CDK_BUCKET_DEPLOYMENT_CFN_TYPE,\n description: `Contents of AWS::S3::Bucket '${customResourceProperties.DestinationBucketName}'`,\n metadata: evaluateCfnTemplate.metadataFor(logicalId),\n }],\n },\n hotswappable: true,\n service: 'custom-s3-deployment',\n apply: async (sdk: SDK) => {\n await sdk.lambda().invokeCommand({\n FunctionName: functionName,\n // Lambda refuses to take a direct JSON object and requires it to be stringify()'d\n Payload: JSON.stringify({\n RequestType: 'Update',\n ResponseURL: REQUIRED_BY_CFN,\n PhysicalResourceId: REQUIRED_BY_CFN,\n StackId: REQUIRED_BY_CFN,\n RequestId: REQUIRED_BY_CFN,\n LogicalResourceId: REQUIRED_BY_CFN,\n ResourceProperties: stringifyObject(customResourceProperties), // JSON.stringify() doesn't turn the actual objects to strings, but the lambda expects strings\n }),\n });\n },\n });\n\n return ret;\n}\n\nexport async function skipChangeForS3DeployCustomResourcePolicy(\n iamPolicyLogicalId: string,\n change: ResourceChange,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): Promise<boolean> {\n if (change.newValue.Type !== 'AWS::IAM::Policy') {\n return false;\n }\n const roles: string[] = change.newValue.Properties?.Roles;\n\n // If no roles are referenced, the policy is definitely not used for a S3Deployment\n if (!roles || !roles.length) {\n return false;\n }\n\n // Check if every role this policy is referenced by is only used for a S3Deployment\n for (const role of roles) {\n const roleArn = await evaluateCfnTemplate.evaluateCfnExpression(role);\n const roleLogicalId = await evaluateCfnTemplate.findLogicalIdForPhysicalName(roleArn);\n\n // We must assume this role is used for something else, because we can't check it\n if (!roleLogicalId) {\n return false;\n }\n\n // Find all interesting reference to the role\n const roleRefs = evaluateCfnTemplate\n .findReferencesTo(roleLogicalId)\n // we are not interested in the reference from the original policy - it always exists\n .filter((roleRef) => !(roleRef.Type == 'AWS::IAM::Policy' && roleRef.LogicalId === iamPolicyLogicalId));\n\n // Check if the role is only used for S3Deployment\n // We know this is the case, if S3Deployment -> Lambda -> Role is satisfied for every reference\n // And we have at least one reference.\n const isRoleOnlyForS3Deployment =\n roleRefs.length >= 1 &&\n roleRefs.every((roleRef) => {\n if (roleRef.Type === 'AWS::Lambda::Function') {\n const lambdaRefs = evaluateCfnTemplate.findReferencesTo(roleRef.LogicalId);\n // Every reference must be to the custom resource and at least one reference must be present\n return (\n lambdaRefs.length >= 1 && lambdaRefs.every((lambdaRef) => lambdaRef.Type === 'Custom::CDKBucketDeployment')\n );\n }\n return false;\n });\n\n // We have determined this role is used for something else, so we can't skip the change\n if (!isRoleOnlyForS3Deployment) {\n return false;\n }\n }\n\n // We have checked that any use of this policy is only for S3Deployment and we can safely skip it\n return true;\n}\n\nfunction stringifyObject(obj: any): any {\n if (obj == null) {\n return obj;\n }\n if (Array.isArray(obj)) {\n return obj.map(stringifyObject);\n }\n if (typeof obj !== 'object') {\n return obj.toString();\n }\n\n const ret: { [k: string]: any } = {};\n for (const [k, v] of Object.entries(obj)) {\n ret[k] = stringifyObject(v);\n }\n return ret;\n}\n", "import { type HotswapChange, classifyChanges } from './common';\nimport type { ResourceChange } from '../../payloads/hotswap';\nimport type { SDK } from '../aws-auth';\nimport type { EvaluateCloudFormationTemplate } from '../cloudformation';\n\nexport async function isHotswappableStateMachineChange(\n logicalId: string,\n change: ResourceChange,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): Promise<HotswapChange[]> {\n if (change.newValue.Type !== 'AWS::StepFunctions::StateMachine') {\n return [];\n }\n const ret: HotswapChange[] = [];\n const classifiedChanges = classifyChanges(change, ['DefinitionString']);\n classifiedChanges.reportNonHotswappablePropertyChanges(ret);\n\n const namesOfHotswappableChanges = Object.keys(classifiedChanges.hotswappableProps);\n if (namesOfHotswappableChanges.length > 0) {\n const stateMachineNameInCfnTemplate = change.newValue?.Properties?.StateMachineName;\n const stateMachineArn = stateMachineNameInCfnTemplate\n ? await evaluateCfnTemplate.evaluateCfnExpression({\n 'Fn::Sub':\n 'arn:${AWS::Partition}:states:${AWS::Region}:${AWS::AccountId}:stateMachine:' +\n stateMachineNameInCfnTemplate,\n })\n : await evaluateCfnTemplate.findPhysicalNameFor(logicalId);\n\n // nothing to do\n if (!stateMachineArn) {\n return ret;\n }\n\n ret.push({\n change: {\n cause: change,\n resources: [{\n logicalId,\n resourceType: change.newValue.Type,\n physicalName: stateMachineArn?.split(':')[6],\n metadata: evaluateCfnTemplate.metadataFor(logicalId),\n }],\n },\n hotswappable: true,\n service: 'stepfunctions-service',\n apply: async (sdk: SDK) => {\n // not passing the optional properties leaves them unchanged\n await sdk.stepFunctions().updateStateMachine({\n stateMachineArn,\n definition: await evaluateCfnTemplate.evaluateCfnExpression(change.propertyUpdates.DefinitionString.newValue),\n });\n },\n });\n }\n\n return ret;\n}\n", "import type { ClientRequest } from 'http';\nimport type { RequestOptions } from 'https';\nimport * as https from 'node:https';\nimport * as path from 'path';\nimport type { Environment } from '@aws-cdk/cx-api';\nimport * as fs from 'fs-extra';\nimport * as semver from 'semver';\nimport { ProxyAgentProvider } from './aws-auth';\nimport type { SdkHttpOptions } from './aws-auth';\nimport type { Context } from './context';\nimport type { IIoHost } from './io';\nimport type { IoHelper } from './io/private';\nimport { IO, asIoHelper, IoDefaultMessages } from './io/private';\nimport { ToolkitError } from './toolkit-error';\nimport { loadTreeFromDir } from './tree';\nimport type { ConstructTreeNode } from './tree';\nimport { cdkCacheDir, formatErrorMessage } from '../util';\n\nconst CACHE_FILE_PATH = path.join(cdkCacheDir(), 'notices.json');\n\nexport interface NoticesProps {\n /**\n * CDK context\n */\n readonly context: Context;\n\n /**\n * Include notices that have already been acknowledged.\n *\n * @default false\n */\n readonly includeAcknowledged?: boolean;\n\n /**\n * Global CLI option for output directory for synthesized cloud assembly\n *\n * @default 'cdk.out'\n */\n readonly output?: string;\n\n /**\n * Options for the HTTP request\n */\n readonly httpOptions?: SdkHttpOptions;\n\n /**\n * Where messages are going to be sent\n */\n readonly ioHost: IIoHost;\n\n /**\n * The version of the CLI\n */\n readonly cliVersion: string;\n}\n\nexport interface NoticesPrintOptions {\n\n /**\n * Whether to append the total number of unacknowledged notices to the display.\n *\n * @default false\n */\n readonly showTotal?: boolean;\n}\n\nexport interface NoticesRefreshOptions {\n /**\n * Whether to force a cache refresh regardless of expiration time.\n *\n * @default false\n */\n readonly force?: boolean;\n\n /**\n * Data source for fetch notices from.\n *\n * @default - WebsiteNoticeDataSource\n */\n readonly dataSource?: NoticeDataSource;\n}\n\nexport interface NoticesFilterFilterOptions {\n readonly data: Notice[];\n readonly cliVersion: string;\n readonly outDir: string;\n readonly bootstrappedEnvironments: BootstrappedEnvironment[];\n}\n\nexport class NoticesFilter {\n constructor(private readonly ioMessages: IoDefaultMessages) {\n }\n\n public filter(options: NoticesFilterFilterOptions): FilteredNotice[] {\n const components = [\n ...this.constructTreeComponents(options.outDir),\n ...this.otherComponents(options),\n ];\n\n return this.findForNamedComponents(options.data, components);\n }\n\n /**\n * From a set of input options, return the notices components we are searching for\n */\n private otherComponents(options: NoticesFilterFilterOptions): ActualComponent[] {\n return [\n // CLI\n {\n name: 'cli',\n version: options.cliVersion,\n },\n\n // Node version\n {\n name: 'node',\n version: process.version.replace(/^v/, ''), // remove the 'v' prefix.\n dynamicName: 'node',\n },\n\n // Bootstrap environments\n ...options.bootstrappedEnvironments.flatMap(env => {\n const semverBootstrapVersion = semver.coerce(env.bootstrapStackVersion);\n if (!semverBootstrapVersion) {\n // we don't throw because notices should never crash the cli.\n this.ioMessages.warning(`While filtering notices, could not coerce bootstrap version '${env.bootstrapStackVersion}' into semver`);\n return [];\n }\n\n return [{\n name: 'bootstrap',\n version: `${semverBootstrapVersion}`,\n dynamicName: 'ENVIRONMENTS',\n dynamicValue: env.environment.name,\n }];\n }),\n ];\n }\n\n /**\n * Based on a set of component names, find all notices that match one of the given components\n */\n private findForNamedComponents(data: Notice[], actualComponents: ActualComponent[]): FilteredNotice[] {\n return data.flatMap(notice => {\n const ors = this.resolveAliases(normalizeComponents(notice.components));\n\n // Find the first set of the disjunctions of which all components match against the actual components.\n // Return the actual components we found so that we can inject their dynamic values. A single filter\n // component can match more than one actual component\n for (const ands of ors) {\n const matched = ands.map(affected => actualComponents.filter(actual =>\n this.componentNameMatches(affected, actual) && semver.satisfies(actual.version, affected.version, { includePrerelease: true })));\n\n // For every clause in the filter we matched one or more components\n if (matched.every(xs => xs.length > 0)) {\n const ret = new FilteredNotice(notice);\n this.addDynamicValues(matched.flatMap(x => x), ret);\n return [ret];\n }\n }\n\n return [];\n });\n }\n\n /**\n * Whether the given \"affected component\" name applies to the given actual component name.\n *\n * The name matches if the name is exactly the same, or the name in the notice\n * is a prefix of the node name when the query ends in '.'.\n */\n private componentNameMatches(pattern: Component, actual: ActualComponent): boolean {\n return pattern.name.endsWith('.') ? actual.name.startsWith(pattern.name) : pattern.name === actual.name;\n }\n\n /**\n * Adds dynamic values from the given ActualComponents\n *\n * If there are multiple components with the same dynamic name, they are joined\n * by a comma.\n */\n private addDynamicValues(comps: ActualComponent[], notice: FilteredNotice) {\n const dynamicValues: Record<string, string[]> = {};\n for (const comp of comps) {\n if (comp.dynamicName) {\n dynamicValues[comp.dynamicName] = dynamicValues[comp.dynamicName] ?? [];\n dynamicValues[comp.dynamicName].push(comp.dynamicValue ?? comp.version);\n }\n }\n for (const [key, values] of Object.entries(dynamicValues)) {\n notice.addDynamicValue(key, values.join(','));\n }\n }\n\n /**\n * Treat 'framework' as an alias for either `aws-cdk-lib.` or `@aws-cdk/core.`.\n *\n * Because it's EITHER `aws-cdk-lib` or `@aws-cdk/core`, we need to add multiple\n * arrays at the top level.\n */\n private resolveAliases(ors: Component[][]): Component[][] {\n return ors.flatMap(ands => {\n const hasFramework = ands.find(c => c.name === 'framework');\n if (!hasFramework) {\n return [ands];\n }\n\n return [\n ands.map(c => c.name === 'framework' ? { ...c, name: '@aws-cdk/core.' } : c),\n ands.map(c => c.name === 'framework' ? { ...c, name: 'aws-cdk-lib.' } : c),\n ];\n });\n }\n\n /**\n * Load the construct tree from the given directory and return its components\n */\n private constructTreeComponents(manifestDir: string): ActualComponent[] {\n const tree = loadTreeFromDir(manifestDir, (msg: string) => void this.ioMessages.notify(IO.DEFAULT_ASSEMBLY_TRACE.msg(msg)));\n if (!tree) {\n return [];\n }\n\n const ret: ActualComponent[] = [];\n recurse(tree);\n return ret;\n\n function recurse(x: ConstructTreeNode) {\n if (x.constructInfo?.fqn && x.constructInfo?.version) {\n ret.push({\n name: x.constructInfo?.fqn,\n version: x.constructInfo?.version,\n });\n }\n\n for (const child of Object.values(x.children ?? {})) {\n recurse(child);\n }\n }\n }\n}\n\ninterface ActualComponent {\n /**\n * Name of the component\n */\n readonly name: string;\n\n /**\n * Version of the component\n */\n readonly version: string;\n\n /**\n * If matched, under what name should it be added to the set of dynamic values\n *\n * These will be used to substitute placeholders in the message string, where\n * placeholders look like `{resolve:XYZ}`.\n *\n * If there is more than one component with the same dynamic name, they are\n * joined by ','.\n *\n * @default - Don't add to the set of dynamic values.\n */\n readonly dynamicName?: string;\n\n /**\n * If matched, what we should put in the set of dynamic values insstead of the version.\n *\n * Only used if `dynamicName` is set; by default we will add the actual version\n * of the component.\n *\n * @default - The version.\n */\n readonly dynamicValue?: string;\n}\n\n/**\n * Information about a bootstrapped environment.\n */\nexport interface BootstrappedEnvironment {\n readonly bootstrapStackVersion: number;\n readonly environment: Environment;\n}\n\n/**\n * Provides access to notices the CLI can display.\n */\nexport class Notices {\n /**\n * Create an instance. Note that this replaces the singleton.\n */\n public static create(props: NoticesProps): Notices {\n this._instance = new Notices(props);\n return this._instance;\n }\n\n /**\n * Get the singleton instance. May return `undefined` if `create` has not been called.\n */\n public static get(): Notices | undefined {\n return this._instance;\n }\n\n private static _instance: Notices | undefined;\n\n private readonly context: Context;\n private readonly output: string;\n private readonly acknowledgedIssueNumbers: Set<Number>;\n private readonly includeAcknowlegded: boolean;\n private readonly httpOptions: SdkHttpOptions;\n private readonly ioHelper: IoHelper;\n private readonly ioMessages: IoDefaultMessages;\n private readonly cliVersion: string;\n\n private data: Set<Notice> = new Set();\n\n // sets don't deduplicate interfaces, so we use a map.\n private readonly bootstrappedEnvironments: Map<string, BootstrappedEnvironment> = new Map();\n\n private constructor(props: NoticesProps) {\n this.context = props.context;\n this.acknowledgedIssueNumbers = new Set(this.context.get('acknowledged-issue-numbers') ?? []);\n this.includeAcknowlegded = props.includeAcknowledged ?? false;\n this.output = props.output ?? 'cdk.out';\n this.httpOptions = props.httpOptions ?? {};\n this.ioHelper = asIoHelper(props.ioHost, 'notices' as any /* forcing a CliAction to a ToolkitAction */);\n this.ioMessages = new IoDefaultMessages(this.ioHelper);\n this.cliVersion = props.cliVersion;\n }\n\n /**\n * Add a bootstrap information to filter on. Can have multiple values\n * in case of multi-environment deployments.\n */\n public addBootstrappedEnvironment(bootstrapped: BootstrappedEnvironment) {\n const key = [\n bootstrapped.bootstrapStackVersion,\n bootstrapped.environment.account,\n bootstrapped.environment.region,\n bootstrapped.environment.name,\n ].join(':');\n this.bootstrappedEnvironments.set(key, bootstrapped);\n }\n\n /**\n * Refresh the list of notices this instance is aware of.\n * To make sure this never crashes the CLI process, all failures are caught and\n * silently logged.\n *\n * If context is configured to not display notices, this will no-op.\n */\n public async refresh(options: NoticesRefreshOptions = {}) {\n try {\n const underlyingDataSource = options.dataSource ?? new WebsiteNoticeDataSource(this.ioHelper, this.httpOptions);\n const dataSource = new CachedDataSource(this.ioMessages, CACHE_FILE_PATH, underlyingDataSource, options.force ?? false);\n const notices = await dataSource.fetch();\n this.data = new Set(this.includeAcknowlegded ? notices : notices.filter(n => !this.acknowledgedIssueNumbers.has(n.issueNumber)));\n } catch (e: any) {\n this.ioMessages.debug(`Could not refresh notices: ${e}`);\n }\n }\n\n /**\n * Display the relevant notices (unless context dictates we shouldn't).\n */\n public display(options: NoticesPrintOptions = {}) {\n const filteredNotices = new NoticesFilter(this.ioMessages).filter({\n data: Array.from(this.data),\n cliVersion: this.cliVersion,\n outDir: this.output,\n bootstrappedEnvironments: Array.from(this.bootstrappedEnvironments.values()),\n });\n\n if (filteredNotices.length > 0) {\n void this.ioMessages.notify(IO.CDK_TOOLKIT_I0100.msg([\n '',\n 'NOTICES (What\\'s this? https://github.com/aws/aws-cdk/wiki/CLI-Notices)',\n '',\n ].join('\\n')));\n for (const filtered of filteredNotices) {\n const formatted = filtered.format() + '\\n';\n switch (filtered.notice.severity) {\n case 'warning':\n void this.ioMessages.notify(IO.CDK_TOOLKIT_W0101.msg(formatted));\n break;\n case 'error':\n void this.ioMessages.notify(IO.CDK_TOOLKIT_E0101.msg(formatted));\n break;\n default:\n void this.ioMessages.notify(IO.CDK_TOOLKIT_I0101.msg(formatted));\n break;\n }\n }\n void this.ioMessages.notify(IO.CDK_TOOLKIT_I0100.msg(\n `If you don\u2019t want to see a notice anymore, use \"cdk acknowledge <id>\". For example, \"cdk acknowledge ${filteredNotices[0].notice.issueNumber}\".`,\n ));\n }\n\n if (options.showTotal ?? false) {\n void this.ioMessages.notify(IO.CDK_TOOLKIT_I0100.msg(\n `\\nThere are ${filteredNotices.length} unacknowledged notice(s).`,\n ));\n }\n }\n}\n\nexport interface Component {\n name: string;\n\n /**\n * The range of affected versions\n */\n version: string;\n}\n\nexport interface Notice {\n title: string;\n issueNumber: number;\n overview: string;\n /**\n * A set of affected components\n *\n * The canonical form of a list of components is in Disjunctive Normal Form\n * (i.e., an OR of ANDs). This is the form when the list of components is a\n * doubly nested array: the notice matches if all components of at least one\n * of the top-level array matches.\n *\n * If the `components` is a single-level array, it is evaluated as an OR; it\n * matches if any of the components matches.\n */\n components: Array<Component | Component[]>;\n schemaVersion: string;\n severity?: string;\n}\n\n/**\n * Normalizes the given components structure into DNF form\n */\nfunction normalizeComponents(xs: Array<Component | Component[]>): Component[][] {\n return xs.map(x => Array.isArray(x) ? x : [x]);\n}\n\nfunction renderConjunction(xs: Component[]): string {\n return xs.map(c => `${c.name}: ${c.version}`).join(' AND ');\n}\n\n/**\n * Notice after passing the filter. A filter can augment a notice with\n * dynamic values as it has access to the dynamic matching data.\n */\nexport class FilteredNotice {\n private readonly dynamicValues: { [key: string]: string } = {};\n\n public constructor(public readonly notice: Notice) {\n }\n\n public addDynamicValue(key: string, value: string) {\n this.dynamicValues[`{resolve:${key}}`] = value;\n }\n\n public format(): string {\n const componentsValue = normalizeComponents(this.notice.components).map(renderConjunction).join(', ');\n return this.resolveDynamicValues([\n `${this.notice.issueNumber}\\t${this.notice.title}`,\n this.formatOverview(),\n `\\tAffected versions: ${componentsValue}`,\n `\\tMore information at: https://github.com/aws/aws-cdk/issues/${this.notice.issueNumber}`,\n ].join('\\n\\n') + '\\n');\n }\n\n private formatOverview() {\n const wrap = (s: string) => s.replace(/(?![^\\n]{1,60}$)([^\\n]{1,60})\\s/g, '$1\\n');\n\n const heading = 'Overview: ';\n const separator = `\\n\\t${' '.repeat(heading.length)}`;\n const content = wrap(this.notice.overview)\n .split('\\n')\n .join(separator);\n\n return '\\t' + heading + content;\n }\n\n private resolveDynamicValues(input: string): string {\n const pattern = new RegExp(Object.keys(this.dynamicValues).join('|'), 'g');\n return input.replace(pattern, (matched) => this.dynamicValues[matched] ?? matched);\n }\n}\n\nexport interface NoticeDataSource {\n fetch(): Promise<Notice[]>;\n}\n\nexport class WebsiteNoticeDataSource implements NoticeDataSource {\n private readonly options: SdkHttpOptions;\n\n constructor(private readonly ioHelper: IoHelper, options: SdkHttpOptions = {}) {\n this.options = options;\n }\n\n async fetch(): Promise<Notice[]> {\n const timeout = 3000;\n\n const options: RequestOptions = {\n agent: await new ProxyAgentProvider(this.ioHelper).create(this.options),\n };\n\n const notices = await new Promise<Notice[]>((resolve, reject) => {\n let req: ClientRequest | undefined;\n\n let timer = setTimeout(() => {\n if (req) {\n req.destroy(new ToolkitError('Request timed out'));\n }\n }, timeout);\n\n timer.unref();\n\n try {\n req = https.get('https://cli.cdk.dev-tools.aws.dev/notices.json',\n options,\n res => {\n if (res.statusCode === 200) {\n res.setEncoding('utf8');\n let rawData = '';\n res.on('data', (chunk) => {\n rawData += chunk;\n });\n res.on('end', () => {\n try {\n const data = JSON.parse(rawData).notices as Notice[];\n if (!data) {\n throw new ToolkitError(\"'notices' key is missing\");\n }\n resolve(data ?? []);\n } catch (e: any) {\n reject(new ToolkitError(`Failed to parse notices: ${formatErrorMessage(e)}`));\n }\n });\n res.on('error', e => {\n reject(new ToolkitError(`Failed to fetch notices: ${formatErrorMessage(e)}`));\n });\n } else {\n reject(new ToolkitError(`Failed to fetch notices. Status code: ${res.statusCode}`));\n }\n });\n req.on('error', reject);\n } catch (e: any) {\n reject(new ToolkitError(`HTTPS 'get' call threw an error: ${formatErrorMessage(e)}`));\n }\n });\n\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg('Notices refreshed'));\n return notices;\n }\n}\n\ninterface CachedNotices {\n expiration: number;\n notices: Notice[];\n}\n\nconst TIME_TO_LIVE_SUCCESS = 60 * 60 * 1000; // 1 hour\nconst TIME_TO_LIVE_ERROR = 1 * 60 * 1000; // 1 minute\n\nexport class CachedDataSource implements NoticeDataSource {\n constructor(\n private readonly ioMessages: IoDefaultMessages,\n private readonly fileName: string,\n private readonly dataSource: NoticeDataSource,\n private readonly skipCache?: boolean) {\n }\n\n async fetch(): Promise<Notice[]> {\n const cachedData = await this.load();\n const data = cachedData.notices;\n const expiration = cachedData.expiration ?? 0;\n\n if (Date.now() > expiration || this.skipCache) {\n const freshData = await this.fetchInner();\n await this.save(freshData);\n return freshData.notices;\n } else {\n this.ioMessages.debug(`Reading cached notices from ${this.fileName}`);\n return data;\n }\n }\n\n private async fetchInner(): Promise<CachedNotices> {\n try {\n return {\n expiration: Date.now() + TIME_TO_LIVE_SUCCESS,\n notices: await this.dataSource.fetch(),\n };\n } catch (e) {\n this.ioMessages.debug(`Could not refresh notices: ${e}`);\n return {\n expiration: Date.now() + TIME_TO_LIVE_ERROR,\n notices: [],\n };\n }\n }\n\n private async load(): Promise<CachedNotices> {\n const defaultValue = {\n expiration: 0,\n notices: [],\n };\n\n try {\n return fs.existsSync(this.fileName)\n ? await fs.readJSON(this.fileName) as CachedNotices\n : defaultValue;\n } catch (e) {\n this.ioMessages.debug(`Failed to load notices from cache: ${e}`);\n return defaultValue;\n }\n }\n\n private async save(cached: CachedNotices): Promise<void> {\n try {\n await fs.writeJSON(this.fileName, cached);\n } catch (e) {\n this.ioMessages.debug(`Failed to store notices in the cache: ${e}`);\n }\n }\n}\n", "import * as path from 'node:path';\nimport type { CloudAssembly } from '@aws-cdk/cx-api';\nimport * as fs from 'fs-extra';\n\n/**\n * Source information on a construct (class fqn and version)\n */\nexport interface ConstructInfo {\n readonly fqn: string;\n readonly version: string;\n}\n\n/**\n * A node in the construct tree.\n */\nexport interface ConstructTreeNode {\n readonly id: string;\n readonly path: string;\n readonly children?: { [key: string]: ConstructTreeNode };\n readonly attributes?: { [key: string]: any };\n\n /**\n * Information on the construct class that led to this node, if available\n */\n readonly constructInfo?: ConstructInfo;\n}\n\n/**\n * Whether the provided predicate is true for at least one element in the construct (sub-)tree.\n */\nexport function some(node: ConstructTreeNode | undefined, predicate: (n: ConstructTreeNode) => boolean): boolean {\n return node != null && (predicate(node) || findInChildren());\n\n function findInChildren(): boolean {\n return Object.values(node?.children ?? {}).some(child => some(child, predicate));\n }\n}\n\nexport async function loadTree(assembly: CloudAssembly, trace: (msg: string) => Promise<void>): Promise<ConstructTreeNode | undefined > {\n try {\n const outdir = assembly.directory;\n const fileName = assembly.tree()?.file;\n return fileName ? fs.readJSONSync(path.join(outdir, fileName)).tree : ({} as ConstructTreeNode);\n } catch (e) {\n await trace(`Failed to get tree.json file: ${e}. Proceeding with empty tree.`);\n return undefined;\n }\n}\n\nexport function loadTreeFromDir(outdir: string, trace: (msg: string) => void): ConstructTreeNode | undefined {\n try {\n return fs.readJSONSync(path.join(outdir, 'tree.json')).tree;\n } catch (e) {\n trace(`Failed to get tree.json file: ${e}. Proceeding with empty tree.`);\n return undefined;\n }\n}\n", "import { format } from 'util';\nimport type * as cxapi from '@aws-cdk/cx-api';\nimport * as chalk from 'chalk';\nimport type { SDK } from './aws-auth';\nimport {\n BOOTSTRAP_VARIANT_PARAMETER,\n BOOTSTRAP_VERSION_OUTPUT,\n BUCKET_DOMAIN_NAME_OUTPUT,\n BUCKET_NAME_OUTPUT,\n DEFAULT_BOOTSTRAP_VARIANT,\n REPOSITORY_NAME_OUTPUT,\n} from './bootstrap/bootstrap-props';\nimport type { CloudFormationStack } from './cloudformation';\nimport { stabilizeStack } from './deployments/cfn-api';\nimport { IO, type IoHelper } from './io/private';\nimport { ToolkitError } from './toolkit-error';\n\nexport const DEFAULT_TOOLKIT_STACK_NAME = 'CDKToolkit';\n\n/**\n * Information on the Bootstrap stack of the environment we're deploying to.\n *\n * This class serves to:\n *\n * - Inspect the bootstrap stack, and return various properties of it for successful\n * asset deployment (in case of legacy-synthesized stacks).\n * - Validate the version of the target environment, and nothing else (in case of\n * default-synthesized stacks).\n *\n * An object of this type might represent a bootstrap stack that could not be found.\n * This is not an issue unless any members are used that require the bootstrap stack\n * to have been found, in which case an error is thrown (default-synthesized stacks\n * should never run into this as they don't need information from the bootstrap\n * stack, all information is already encoded into the Cloud Assembly Manifest).\n *\n * Nevertheless, an instance of this class exists to serve as a cache for SSM\n * parameter lookups (otherwise, the \"bootstrap stack version\" parameter would\n * need to be read repeatedly).\n *\n * Called \"ToolkitInfo\" for historical reasons.\n *\n */\nexport abstract class ToolkitInfo {\n public static determineName(overrideName?: string) {\n return overrideName ?? DEFAULT_TOOLKIT_STACK_NAME;\n }\n\n public static async lookup(\n environment: cxapi.Environment,\n sdk: SDK,\n ioHelper: IoHelper,\n stackName: string | undefined,\n ): Promise<ToolkitInfo> {\n const cfn = sdk.cloudFormation();\n stackName = ToolkitInfo.determineName(stackName);\n try {\n const stack = await stabilizeStack(cfn, ioHelper, stackName);\n if (!stack) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(\n format(\n \"The environment %s doesn't have the CDK toolkit stack (%s) installed. Use %s to setup your environment for use with the toolkit.\",\n environment.name,\n stackName,\n chalk.blue(`cdk bootstrap \"${environment.name}\"`),\n ),\n ));\n return ToolkitInfo.bootstrapStackNotFoundInfo(stackName);\n }\n if (stack.stackStatus.isCreationFailure) {\n // Treat a \"failed to create\" bootstrap stack as an absent one.\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(\n format(\n 'The environment %s has a CDK toolkit stack (%s) that failed to create. Use %s to try provisioning it again.',\n environment.name,\n stackName,\n chalk.blue(`cdk bootstrap \"${environment.name}\"`),\n ),\n ));\n return ToolkitInfo.bootstrapStackNotFoundInfo(stackName);\n }\n\n return new ExistingToolkitInfo(stack);\n } catch (e: any) {\n return ToolkitInfo.bootstrapStackLookupError(stackName, e);\n }\n }\n\n public static fromStack(stack: CloudFormationStack): ToolkitInfo {\n return new ExistingToolkitInfo(stack);\n }\n\n public static bootstrapStackNotFoundInfo(stackName: string): ToolkitInfo {\n return new BootstrapStackNotFoundInfo(\n stackName,\n \"This deployment requires a bootstrap stack with a known name; pass '--toolkit-stack-name' or switch to using the 'DefaultStackSynthesizer' (see https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html)\",\n );\n }\n\n public static bootstrapStackLookupError(stackName: string, e: Error): ToolkitInfo {\n return new BootstrapStackNotFoundInfo(\n stackName,\n `This deployment requires a bootstrap stack with a known name, but during its lookup the following error occurred: ${e}; pass \\'--toolkit-stack-name\\' or switch to using the \\'DefaultStackSynthesizer\\' (see https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html)`,\n );\n }\n\n public abstract readonly found: boolean;\n public abstract readonly bucketUrl: string;\n public abstract readonly bucketName: string;\n public abstract readonly repositoryName: string;\n public abstract readonly version: number;\n public abstract readonly variant: string;\n public abstract readonly bootstrapStack: CloudFormationStack;\n public abstract readonly stackName: string;\n\n constructor() {\n }\n}\n\n/**\n * Returned when a bootstrap stack is found\n */\nclass ExistingToolkitInfo extends ToolkitInfo {\n public readonly found = true;\n\n constructor(public readonly bootstrapStack: CloudFormationStack) {\n super();\n }\n\n public get bucketUrl() {\n return `https://${this.requireOutput(BUCKET_DOMAIN_NAME_OUTPUT)}`;\n }\n\n public get bucketName() {\n return this.requireOutput(BUCKET_NAME_OUTPUT);\n }\n\n public get repositoryName() {\n return this.requireOutput(REPOSITORY_NAME_OUTPUT);\n }\n\n public get version() {\n return parseInt(this.bootstrapStack.outputs[BOOTSTRAP_VERSION_OUTPUT] ?? '0', 10);\n }\n\n public get variant() {\n return this.bootstrapStack.parameters[BOOTSTRAP_VARIANT_PARAMETER] ?? DEFAULT_BOOTSTRAP_VARIANT;\n }\n\n public get parameters(): Record<string, string> {\n return this.bootstrapStack.parameters ?? {};\n }\n\n public get terminationProtection(): boolean {\n return this.bootstrapStack.terminationProtection ?? false;\n }\n\n public get stackName(): string {\n return this.bootstrapStack.stackName;\n }\n\n /**\n * Prepare an ECR repository for uploading to using Docker\n *\n */\n private requireOutput(output: string): string {\n if (!(output in this.bootstrapStack.outputs)) {\n throw new ToolkitError(\n `The CDK toolkit stack (${this.bootstrapStack.stackName}) does not have an output named ${output}. Use 'cdk bootstrap' to correct this.`,\n );\n }\n return this.bootstrapStack.outputs[output];\n }\n}\n\n/**\n * Returned when a bootstrap stack could not be found\n *\n * This is not an error in principle, UNTIL one of the members is called that requires\n * the bootstrap stack to have been found, in which case the lookup error is still thrown\n * belatedly.\n *\n * The errors below serve as a last stop-gap message--normally calling code should have\n * checked `toolkit.found` and produced an appropriate error message.\n */\nclass BootstrapStackNotFoundInfo extends ToolkitInfo {\n public readonly found = false;\n\n constructor(\n public readonly stackName: string,\n private readonly errorMessage: string,\n ) {\n super();\n }\n\n public get bootstrapStack(): CloudFormationStack {\n throw new ToolkitError(this.errorMessage);\n }\n\n public get bucketUrl(): string {\n throw new ToolkitError(this.errorMessage);\n }\n\n public get bucketName(): string {\n throw new ToolkitError(this.errorMessage);\n }\n\n public get repositoryName(): string {\n throw new ToolkitError(this.errorMessage);\n }\n\n public get version(): number {\n throw new ToolkitError(this.errorMessage);\n }\n\n public get variant(): string {\n throw new ToolkitError(this.errorMessage);\n }\n\n public prepareEcrRepository(): Promise<EcrRepositoryInfo> {\n throw new ToolkitError(this.errorMessage);\n }\n}\n\nexport interface EcrRepositoryInfo {\n repositoryUri: string;\n}\n\nexport interface EcrCredentials {\n username: string;\n password: string;\n endpoint: string;\n}\n", "import type { Environment } from '@aws-cdk/cx-api';\nimport { formatErrorMessage } from '../../util';\nimport type { SDK } from '../aws-auth';\nimport { IO, type IoHelper } from '../io/private';\nimport { Notices } from '../notices';\nimport { ToolkitError } from '../toolkit-error';\nimport { type EcrRepositoryInfo, ToolkitInfo } from '../toolkit-info';\n\n/**\n * Registry class for `EnvironmentResources`.\n *\n * The state management of this class is a bit non-standard. We want to cache\n * data related to toolkit stacks and SSM parameters, but we are not in charge\n * of ensuring caching of SDKs. Since `EnvironmentResources` needs an SDK to\n * function, we treat it as an ephemeral class, and store the actual cached data\n * in `EnvironmentResourcesRegistry`.\n */\nexport class EnvironmentResourcesRegistry {\n private readonly cache = new Map<string, EnvironmentCache>();\n\n constructor(private readonly toolkitStackName?: string) {\n }\n\n public for(resolvedEnvironment: Environment, sdk: SDK, ioHelper: IoHelper) {\n const key = `${resolvedEnvironment.account}:${resolvedEnvironment.region}`;\n let envCache = this.cache.get(key);\n if (!envCache) {\n envCache = emptyCache();\n this.cache.set(key, envCache);\n }\n return new EnvironmentResources(resolvedEnvironment, sdk, ioHelper, envCache, this.toolkitStackName);\n }\n}\n\n/**\n * Interface with the account and region we're deploying into\n *\n * Manages lookups for bootstrapped resources, falling back to the legacy \"CDK Toolkit\"\n * original bootstrap stack if necessary.\n *\n * The state management of this class is a bit non-standard. We want to cache\n * data related to toolkit stacks and SSM parameters, but we are not in charge\n * of ensuring caching of SDKs. Since `EnvironmentResources` needs an SDK to\n * function, we treat it as an ephemeral class, and store the actual cached data\n * in `EnvironmentResourcesRegistry`.\n */\nexport class EnvironmentResources {\n constructor(\n public readonly environment: Environment,\n private readonly sdk: SDK,\n private readonly ioHelper: IoHelper,\n private readonly cache: EnvironmentCache,\n private readonly toolkitStackName?: string,\n ) {\n }\n\n /**\n * Look up the toolkit for a given environment, using a given SDK\n */\n public async lookupToolkit() {\n if (!this.cache.toolkitInfo) {\n this.cache.toolkitInfo = await ToolkitInfo.lookup(this.environment, this.sdk, this.ioHelper, this.toolkitStackName);\n }\n return this.cache.toolkitInfo;\n }\n\n /**\n * Validate that the bootstrap stack version matches or exceeds the expected version\n *\n * Use the SSM parameter name to read the version number if given, otherwise use the version\n * discovered on the bootstrap stack.\n *\n * Pass in the SSM parameter name so we can cache the lookups an don't need to do the same\n * lookup again and again for every artifact.\n */\n public async validateVersion(expectedVersion: number | undefined, ssmParameterName: string | undefined) {\n if (expectedVersion === undefined) {\n // No requirement\n return;\n }\n const defExpectedVersion = expectedVersion;\n\n if (ssmParameterName !== undefined) {\n try {\n doValidate(await this.versionFromSsmParameter(ssmParameterName), this.environment);\n return;\n } catch (e: any) {\n if (e.name !== 'AccessDeniedException') {\n throw e;\n }\n\n // This is a fallback! The bootstrap template that goes along with this change introduces\n // a new 'ssm:GetParameter' permission, but when run using the previous bootstrap template we\n // won't have the permissions yet to read the version, so we won't be able to show the\n // message telling the user they need to update! When we see an AccessDeniedException, fall\n // back to the version we read from Stack Outputs; but ONLY if the version we discovered via\n // outputs is legitimately an old version. If it's newer than that, something else must be broken,\n // so let it fail as it would if we didn't have this fallback.\n const bootstrapStack = await this.lookupToolkit();\n if (bootstrapStack.found && bootstrapStack.version < BOOTSTRAP_TEMPLATE_VERSION_INTRODUCING_GETPARAMETER) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_WARN.msg(\n `Could not read SSM parameter ${ssmParameterName}: ${formatErrorMessage(e)}, falling back to version from ${bootstrapStack}`,\n ));\n doValidate(bootstrapStack.version, this.environment);\n return;\n }\n\n throw new ToolkitError(\n `This CDK deployment requires bootstrap stack version '${expectedVersion}', but during the confirmation via SSM parameter ${ssmParameterName} the following error occurred: ${e}`,\n );\n }\n }\n\n // No SSM parameter\n const bootstrapStack = await this.lookupToolkit();\n doValidate(bootstrapStack.version, this.environment);\n\n function doValidate(version: number, environment: Environment) {\n const notices = Notices.get();\n if (notices) {\n // if `Notices` hasn't been initialized there is probably a good\n // reason for it. handle gracefully.\n notices.addBootstrappedEnvironment({ bootstrapStackVersion: version, environment });\n }\n if (defExpectedVersion > version) {\n throw new ToolkitError(\n `This CDK deployment requires bootstrap stack version '${expectedVersion}', found '${version}'. Please run 'cdk bootstrap'.`,\n );\n }\n }\n }\n\n /**\n * Read a version from an SSM parameter, cached\n */\n public async versionFromSsmParameter(parameterName: string): Promise<number> {\n const existing = this.cache.ssmParameters.get(parameterName);\n if (existing !== undefined) {\n return existing;\n }\n\n const ssm = this.sdk.ssm();\n\n try {\n const result = await ssm.getParameter({ Name: parameterName });\n\n const asNumber = parseInt(`${result.Parameter?.Value}`, 10);\n if (isNaN(asNumber)) {\n throw new ToolkitError(`SSM parameter ${parameterName} not a number: ${result.Parameter?.Value}`);\n }\n\n this.cache.ssmParameters.set(parameterName, asNumber);\n return asNumber;\n } catch (e: any) {\n if (e.name === 'ParameterNotFound') {\n throw new ToolkitError(\n `SSM parameter ${parameterName} not found. Has the environment been bootstrapped? Please run \\'cdk bootstrap\\' (see https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html)`,\n );\n }\n throw e;\n }\n }\n\n public async prepareEcrRepository(repositoryName: string): Promise<EcrRepositoryInfo> {\n if (!this.sdk) {\n throw new ToolkitError('ToolkitInfo needs to have been initialized with an sdk to call prepareEcrRepository');\n }\n const ecr = this.sdk.ecr();\n\n // check if repo already exists\n try {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${repositoryName}: checking if ECR repository already exists`));\n const describeResponse = await ecr.describeRepositories({\n repositoryNames: [repositoryName],\n });\n const existingRepositoryUri = describeResponse.repositories![0]?.repositoryUri;\n if (existingRepositoryUri) {\n return { repositoryUri: existingRepositoryUri };\n }\n } catch (e: any) {\n if (e.name !== 'RepositoryNotFoundException') {\n throw e;\n }\n }\n\n // create the repo (tag it so it will be easier to garbage collect in the future)\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${repositoryName}: creating ECR repository`));\n const assetTag = { Key: 'awscdk:asset', Value: 'true' };\n const response = await ecr.createRepository({\n repositoryName,\n tags: [assetTag],\n });\n const repositoryUri = response.repository?.repositoryUri;\n if (!repositoryUri) {\n throw new ToolkitError(`CreateRepository did not return a repository URI for ${repositoryUri}`);\n }\n\n // configure image scanning on push (helps in identifying software vulnerabilities, no additional charge)\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${repositoryName}: enable image scanning`));\n await ecr.putImageScanningConfiguration({\n repositoryName,\n imageScanningConfiguration: { scanOnPush: true },\n });\n\n return { repositoryUri };\n }\n}\n\nexport class NoBootstrapStackEnvironmentResources extends EnvironmentResources {\n constructor(environment: Environment, sdk: SDK, ioHelper: IoHelper) {\n super(environment, sdk, ioHelper, emptyCache());\n }\n\n /**\n * Look up the toolkit for a given environment, using a given SDK\n */\n public async lookupToolkit(): Promise<ToolkitInfo> {\n throw new ToolkitError(\n 'Trying to perform an operation that requires a bootstrap stack; you should not see this error, this is a bug in the CDK CLI.',\n );\n }\n}\n\n/**\n * Data that is cached on a per-environment level\n *\n * This cache may be shared between different instances of the `EnvironmentResources` class.\n */\ninterface EnvironmentCache {\n readonly ssmParameters: Map<string, number>;\n toolkitInfo?: ToolkitInfo;\n}\n\nfunction emptyCache(): EnvironmentCache {\n return {\n ssmParameters: new Map(),\n toolkitInfo: undefined,\n };\n}\n\n/**\n * The bootstrap template version that introduced ssm:GetParameter\n */\nconst BOOTSTRAP_TEMPLATE_VERSION_INTRODUCING_GETPARAMETER = 5;\n", "import { type Environment, EnvironmentPlaceholders } from '@aws-cdk/cx-api';\nimport type { Branded } from '../../util';\nimport type { SdkProvider } from '../aws-auth';\nimport { Mode } from '../plugin';\n\n/**\n * Replace the {ACCOUNT} and {REGION} placeholders in all strings found in a complex object.\n */\nexport async function replaceEnvPlaceholders<A extends Record<string, string | undefined>>(\n object: A,\n env: Environment,\n sdkProvider: SdkProvider,\n): Promise<{[k in keyof A]: StringWithoutPlaceholders | undefined}> {\n return EnvironmentPlaceholders.replaceAsync(object, {\n accountId: () => Promise.resolve(env.account),\n region: () => Promise.resolve(env.region),\n partition: async () => {\n // There's no good way to get the partition!\n // We should have had it already, except we don't.\n //\n // Best we can do is ask the \"base credentials\" for this environment for their partition. Cross-partition\n // AssumeRole'ing will never work anyway, so this answer won't be wrong (it will just be slow!)\n return (await sdkProvider.baseCredentialsPartition(env, Mode.ForReading)) ?? 'aws';\n },\n });\n}\n\nexport type StringWithoutPlaceholders = Branded<string, 'NoPlaceholders'>;\n", "import type * as cxapi from '@aws-cdk/cx-api';\nimport { ToolkitError } from '../toolkit-error';\nimport type { EnvironmentResources } from './environment-resources';\nimport { EnvironmentResourcesRegistry } from './environment-resources';\nimport type { StringWithoutPlaceholders } from './placeholders';\nimport { replaceEnvPlaceholders } from './placeholders';\nimport { formatErrorMessage } from '../../util';\nimport type { SDK, CredentialsOptions, SdkForEnvironment, SdkProvider } from '../aws-auth';\nimport { IO, type IoHelper } from '../io/private';\nimport { Mode } from '../plugin';\n\n/**\n * Access particular AWS resources, based on information from the CX manifest\n *\n * It is not possible to grab direct access to AWS credentials; 9 times out of 10\n * we have to allow for role assumption, and role assumption can only work if\n * there is a CX Manifest that contains a role ARN.\n *\n * This class exists so new code isn't tempted to go and get SDK credentials directly.\n */\nexport class EnvironmentAccess {\n private readonly sdkCache = new Map<string, SdkForEnvironment>();\n private readonly environmentResources: EnvironmentResourcesRegistry;\n private readonly ioHelper: IoHelper;\n\n constructor(private readonly sdkProvider: SdkProvider, toolkitStackName: string, ioHelper: IoHelper) {\n this.environmentResources = new EnvironmentResourcesRegistry(toolkitStackName);\n this.ioHelper = ioHelper;\n }\n\n /**\n * Resolves the environment for a stack.\n */\n public async resolveStackEnvironment(stack: cxapi.CloudFormationStackArtifact): Promise<cxapi.Environment> {\n return this.sdkProvider.resolveEnvironment(stack.environment);\n }\n\n /**\n * Get an SDK to access the given stack's environment for stack operations\n *\n * Will ask plugins for readonly credentials if available, use the default\n * AWS credentials if not.\n *\n * Will assume the deploy role if configured on the stack. Check the default `deploy-role`\n * policies to see what you can do with this role.\n */\n public async accessStackForReadOnlyStackOperations(stack: cxapi.CloudFormationStackArtifact): Promise<TargetEnvironment> {\n return this.accessStackForStackOperations(stack, Mode.ForReading);\n }\n\n /**\n * Get an SDK to access the given stack's environment for stack operations\n *\n * Will ask plugins for mutating credentials if available, use the default AWS\n * credentials if not. The `mode` parameter is only used for querying\n * plugins.\n *\n * Will assume the deploy role if configured on the stack. Check the default `deploy-role`\n * policies to see what you can do with this role.\n */\n public async accessStackForMutableStackOperations(stack: cxapi.CloudFormationStackArtifact): Promise<TargetEnvironment> {\n return this.accessStackForStackOperations(stack, Mode.ForWriting);\n }\n\n /**\n * Get an SDK to access the given stack's environment for environmental lookups\n *\n * Will use a plugin if available, use the default AWS credentials if not.\n * The `mode` parameter is only used for querying plugins.\n *\n * Will assume the lookup role if configured on the stack. Check the default `lookup-role`\n * policies to see what you can do with this role. It can generally read everything\n * in the account that does not require KMS access.\n *\n * ---\n *\n * For backwards compatibility reasons, there are some scenarios that are handled here:\n *\n * 1. The lookup role may not exist (it was added in bootstrap stack version 7). If so:\n * a. Return the default credentials if the default credentials are for the stack account\n * (you will notice this as `isFallbackCredentials=true`).\n * b. Throw an error if the default credentials are not for the stack account.\n *\n * 2. The lookup role may not have the correct permissions (for example, ReadOnlyAccess was added in\n * bootstrap stack version 8); the stack will have a minimum version number on it.\n * a. If it does not we throw an error which should be handled in the calling\n * function (and fallback to use a different role, etc)\n *\n * Upon success, caller will have an SDK for the right account, which may or may not have\n * the right permissions.\n */\n public async accessStackForLookup(stack: cxapi.CloudFormationStackArtifact): Promise<TargetEnvironment> {\n if (!stack.environment) {\n throw new ToolkitError(`The stack ${stack.displayName} does not have an environment`);\n }\n\n const lookupEnv = await this.prepareSdk({\n environment: stack.environment,\n mode: Mode.ForReading,\n assumeRoleArn: stack.lookupRole?.arn,\n assumeRoleExternalId: stack.lookupRole?.assumeRoleExternalId,\n assumeRoleAdditionalOptions: stack.lookupRole?.assumeRoleAdditionalOptions,\n });\n\n // if we succeed in assuming the lookup role, make sure we have the correct bootstrap stack version\n if (lookupEnv.didAssumeRole && stack.lookupRole?.bootstrapStackVersionSsmParameter && stack.lookupRole.requiresBootstrapStackVersion) {\n const version = await lookupEnv.resources.versionFromSsmParameter(stack.lookupRole.bootstrapStackVersionSsmParameter);\n if (version < stack.lookupRole.requiresBootstrapStackVersion) {\n throw new ToolkitError(`Bootstrap stack version '${stack.lookupRole.requiresBootstrapStackVersion}' is required, found version '${version}'. To get rid of this error, please upgrade to bootstrap version >= ${stack.lookupRole.requiresBootstrapStackVersion}`);\n }\n }\n if (lookupEnv.isFallbackCredentials) {\n const arn = await lookupEnv.replacePlaceholders(stack.lookupRole?.arn);\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_WARN.msg(`Lookup role ${arn} was not assumed. Proceeding with default credentials.`));\n }\n return lookupEnv;\n }\n\n /**\n * Get an SDK to access the given stack's environment for reading stack attributes\n *\n * Will use a plugin if available, use the default AWS credentials if not.\n * The `mode` parameter is only used for querying plugins.\n *\n * Will try to assume the lookup role if given, will use the regular stack operations\n * access (deploy-role) otherwise. When calling this, you should assume that you will get\n * the least privileged role, so don't try to use it for anything the `deploy-role`\n * wouldn't be able to do. Also you cannot rely on being able to read encrypted anything.\n */\n public async accessStackForLookupBestEffort(stack: cxapi.CloudFormationStackArtifact): Promise<TargetEnvironment> {\n if (!stack.environment) {\n throw new ToolkitError(`The stack ${stack.displayName} does not have an environment`);\n }\n\n try {\n return await this.accessStackForLookup(stack);\n } catch (e: any) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_WARN.msg(`${formatErrorMessage(e)}`));\n }\n return this.accessStackForStackOperations(stack, Mode.ForReading);\n }\n\n /**\n * Get an SDK to access the given stack's environment for stack operations\n *\n * Will use a plugin if available, use the default AWS credentials if not.\n * The `mode` parameter is only used for querying plugins.\n *\n * Will assume the deploy role if configured on the stack. Check the default `deploy-role`\n * policies to see what you can do with this role.\n */\n private async accessStackForStackOperations(stack: cxapi.CloudFormationStackArtifact, mode: Mode): Promise<TargetEnvironment> {\n if (!stack.environment) {\n throw new ToolkitError(`The stack ${stack.displayName} does not have an environment`);\n }\n\n return this.prepareSdk({\n environment: stack.environment,\n mode,\n assumeRoleArn: stack.assumeRoleArn,\n assumeRoleExternalId: stack.assumeRoleExternalId,\n assumeRoleAdditionalOptions: stack.assumeRoleAdditionalOptions,\n });\n }\n\n /**\n * Prepare an SDK for use in the given environment and optionally with a role assumed.\n */\n private async prepareSdk(\n options: PrepareSdkRoleOptions,\n ): Promise<TargetEnvironment> {\n const resolvedEnvironment = await this.sdkProvider.resolveEnvironment(options.environment);\n\n // Substitute any placeholders with information about the current environment\n const { assumeRoleArn } = await replaceEnvPlaceholders({\n assumeRoleArn: options.assumeRoleArn,\n }, resolvedEnvironment, this.sdkProvider);\n\n const stackSdk = await this.cachedSdkForEnvironment(resolvedEnvironment, options.mode, {\n assumeRoleArn,\n assumeRoleExternalId: options.assumeRoleExternalId,\n assumeRoleAdditionalOptions: options.assumeRoleAdditionalOptions,\n });\n\n return {\n sdk: stackSdk.sdk,\n resolvedEnvironment,\n resources: this.environmentResources.for(resolvedEnvironment, stackSdk.sdk, this.ioHelper),\n // If we asked for a role, did not successfully assume it, and yet got here without an exception: that\n // means we must have fallback credentials.\n isFallbackCredentials: !stackSdk.didAssumeRole && !!assumeRoleArn,\n didAssumeRole: stackSdk.didAssumeRole,\n replacePlaceholders: async <A extends string | undefined>(str: A) => {\n const ret = await replaceEnvPlaceholders({ str }, resolvedEnvironment, this.sdkProvider);\n return ret.str;\n },\n };\n }\n\n private async cachedSdkForEnvironment(\n environment: cxapi.Environment,\n mode: Mode,\n options?: CredentialsOptions,\n ) {\n const cacheKeyElements = [\n environment.account,\n environment.region,\n `${mode}`,\n options?.assumeRoleArn ?? '',\n options?.assumeRoleExternalId ?? '',\n ];\n\n if (options?.assumeRoleAdditionalOptions) {\n cacheKeyElements.push(JSON.stringify(options.assumeRoleAdditionalOptions));\n }\n\n const cacheKey = cacheKeyElements.join(':');\n const existing = this.sdkCache.get(cacheKey);\n if (existing) {\n return existing;\n }\n const ret = await this.sdkProvider.forEnvironment(environment, mode, options);\n this.sdkCache.set(cacheKey, ret);\n return ret;\n }\n}\n\n/**\n * SDK obtained by assuming the deploy role\n * for a given environment\n */\nexport interface TargetEnvironment {\n /**\n * The SDK for the given environment\n */\n readonly sdk: SDK;\n\n /**\n * The resolved environment for the stack\n * (no more 'unknown-account/unknown-region')\n */\n readonly resolvedEnvironment: cxapi.Environment;\n\n /**\n * Access class for environmental resources to help the deployment\n */\n readonly resources: EnvironmentResources;\n\n /**\n * Whether or not we assumed a role in the process of getting these credentials\n */\n readonly didAssumeRole: boolean;\n\n /**\n * Whether or not these are fallback credentials\n *\n * Fallback credentials means that assuming the intended role failed, but the\n * base credentials happen to be for the right account so we just picked those\n * and hope the future SDK calls succeed.\n *\n * This is a backwards compatibility mechanism from around the time we introduced\n * deployment roles.\n */\n readonly isFallbackCredentials: boolean;\n\n /**\n * Replace environment placeholders according to the current environment\n */\n replacePlaceholders(x: string | undefined): Promise<StringWithoutPlaceholders | undefined>;\n}\n\ninterface PrepareSdkRoleOptions {\n readonly environment: cxapi.Environment;\n readonly mode: Mode;\n readonly assumeRoleArn?: string;\n readonly assumeRoleExternalId?: string;\n readonly assumeRoleAdditionalOptions?: { [key: string]: any };\n}\n", "import type { BootstrappingParameters } from './bootstrap-props';\nimport { BUCKET_DOMAIN_NAME_OUTPUT, BUCKET_NAME_OUTPUT } from './bootstrap-props';\n\nexport function legacyBootstrapTemplate(params: BootstrappingParameters): any {\n return {\n Description: 'The CDK Toolkit Stack. It was created by `cdk bootstrap` and manages resources necessary for managing your Cloud Applications with AWS CDK.',\n Conditions: {\n UsePublicAccessBlockConfiguration: {\n 'Fn::Equals': [\n params.publicAccessBlockConfiguration || params.publicAccessBlockConfiguration === undefined ? 'true' : 'false',\n 'true',\n ],\n },\n },\n Resources: {\n StagingBucket: {\n Type: 'AWS::S3::Bucket',\n Properties: {\n BucketName: params.bucketName,\n AccessControl: 'Private',\n BucketEncryption: {\n ServerSideEncryptionConfiguration: [{\n ServerSideEncryptionByDefault: {\n SSEAlgorithm: 'aws:kms',\n KMSMasterKeyID: params.kmsKeyId,\n },\n }],\n },\n PublicAccessBlockConfiguration: {\n 'Fn::If': [\n 'UsePublicAccessBlockConfiguration',\n {\n BlockPublicAcls: true,\n BlockPublicPolicy: true,\n IgnorePublicAcls: true,\n RestrictPublicBuckets: true,\n },\n { Ref: 'AWS::NoValue' },\n ],\n },\n },\n },\n StagingBucketPolicy: {\n Type: 'AWS::S3::BucketPolicy',\n Properties: {\n Bucket: { Ref: 'StagingBucket' },\n PolicyDocument: {\n Id: 'AccessControl',\n Version: '2012-10-17',\n Statement: [\n {\n Sid: 'AllowSSLRequestsOnly',\n Action: 's3:*',\n Effect: 'Deny',\n Resource: [\n { 'Fn::Sub': '${StagingBucket.Arn}' },\n { 'Fn::Sub': '${StagingBucket.Arn}/*' },\n ],\n Condition: {\n Bool: { 'aws:SecureTransport': 'false' },\n },\n Principal: '*',\n },\n ],\n },\n },\n },\n },\n Outputs: {\n [BUCKET_NAME_OUTPUT]: {\n Description: 'The name of the S3 bucket owned by the CDK toolkit stack',\n Value: { Ref: 'StagingBucket' },\n },\n [BUCKET_DOMAIN_NAME_OUTPUT]: {\n Description: 'The domain name of the S3 bucket owned by the CDK toolkit stack',\n Value: { 'Fn::GetAtt': ['StagingBucket', 'RegionalDomainName'] },\n },\n },\n };\n}\n", "import * as path from 'path';\nimport { format } from 'util';\nimport * as cxapi from '@aws-cdk/cx-api';\nimport * as fs from 'fs-extra';\nimport type { SdkProvider } from '../aws-auth';\nimport type { Settings } from '../settings';\n\n/**\n * If we don't have region/account defined in context, we fall back to the default SDK behavior\n * where region is retrieved from ~/.aws/config and account is based on default credentials provider\n * chain and then STS is queried.\n *\n * This is done opportunistically: for example, if we can't access STS for some reason or the region\n * is not configured, the context value will be 'null' and there could failures down the line. In\n * some cases, synthesis does not require region/account information at all, so that might be perfectly\n * fine in certain scenarios.\n *\n * @param context The context key/value bash.\n */\nexport async function prepareDefaultEnvironment(\n aws: SdkProvider,\n debugFn: (msg: string) => Promise<void>,\n): Promise<{ [key: string]: string }> {\n const env: { [key: string]: string } = { };\n\n env[cxapi.DEFAULT_REGION_ENV] = aws.defaultRegion;\n await debugFn(`Setting \"${cxapi.DEFAULT_REGION_ENV}\" environment variable to ${env[cxapi.DEFAULT_REGION_ENV]}`);\n\n const accountId = (await aws.defaultAccount())?.accountId;\n if (accountId) {\n env[cxapi.DEFAULT_ACCOUNT_ENV] = accountId;\n await debugFn(`Setting \"${cxapi.DEFAULT_ACCOUNT_ENV}\" environment variable to ${env[cxapi.DEFAULT_ACCOUNT_ENV]}`);\n }\n\n return env;\n}\n\n/**\n * Settings related to synthesis are read from context.\n * The merging of various configuration sources like cli args or cdk.json has already happened.\n * We now need to set the final values to the context.\n */\nexport async function prepareContext(\n settings: Settings,\n context: {[key: string]: any},\n env: { [key: string]: string | undefined},\n debugFn: (msg: string) => Promise<void>,\n) {\n const debugMode: boolean = settings.get(['debug']) ?? true;\n if (debugMode) {\n env.CDK_DEBUG = 'true';\n }\n\n const pathMetadata: boolean = settings.get(['pathMetadata']) ?? true;\n if (pathMetadata) {\n context[cxapi.PATH_METADATA_ENABLE_CONTEXT] = true;\n }\n\n const assetMetadata: boolean = settings.get(['assetMetadata']) ?? true;\n if (assetMetadata) {\n context[cxapi.ASSET_RESOURCE_METADATA_ENABLED_CONTEXT] = true;\n }\n\n const versionReporting: boolean = settings.get(['versionReporting']) ?? true;\n if (versionReporting) {\n context[cxapi.ANALYTICS_REPORTING_ENABLED_CONTEXT] = true;\n }\n // We need to keep on doing this for framework version from before this flag was deprecated.\n if (!versionReporting) {\n context['aws:cdk:disable-version-reporting'] = true;\n }\n\n const stagingEnabled = settings.get(['staging']) ?? true;\n if (!stagingEnabled) {\n context[cxapi.DISABLE_ASSET_STAGING_CONTEXT] = true;\n }\n\n const bundlingStacks = settings.get(['bundlingStacks']) ?? ['**'];\n context[cxapi.BUNDLING_STACKS] = bundlingStacks;\n\n await debugFn(format('context:', context));\n\n return context;\n}\n\nexport function spaceAvailableForContext(env: { [key: string]: string }, limit: number) {\n const size = (value: string) => value != null ? Buffer.byteLength(value) : 0;\n\n const usedSpace = Object.entries(env)\n .map(([k, v]) => k === cxapi.CONTEXT_ENV ? size(k) : size(k) + size(v))\n .reduce((a, b) => a + b, 0);\n\n return Math.max(0, limit - usedSpace);\n}\n\n/**\n * Guess the executable from the command-line argument\n *\n * Only do this if the file is NOT marked as executable. If it is,\n * we'll defer to the shebang inside the file itself.\n *\n * If we're on Windows, we ALWAYS take the handler, since it's hard to\n * verify if registry associations have or have not been set up for this\n * file type, so we'll assume the worst and take control.\n */\nexport async function guessExecutable(app: string, debugFn: (msg: string) => Promise<void>) {\n const commandLine = appToArray(app);\n if (commandLine.length === 1) {\n let fstat;\n\n try {\n fstat = await fs.stat(commandLine[0]);\n } catch {\n await debugFn(`Not a file: '${commandLine[0]}'. Using '${commandLine}' as command-line`);\n return commandLine;\n }\n\n // eslint-disable-next-line no-bitwise\n const isExecutable = (fstat.mode & fs.constants.X_OK) !== 0;\n const isWindows = process.platform === 'win32';\n\n const handler = EXTENSION_MAP.get(path.extname(commandLine[0]));\n if (handler && (!isExecutable || isWindows)) {\n return handler(commandLine[0]);\n }\n }\n return commandLine;\n}\n\n/**\n * Mapping of extensions to command-line generators\n */\nconst EXTENSION_MAP = new Map<string, CommandGenerator>([\n ['.js', executeNode],\n]);\n\ntype CommandGenerator = (file: string) => string[];\n\n/**\n * Execute the given file with the same 'node' process as is running the current process\n */\nfunction executeNode(scriptFile: string): string[] {\n return [process.execPath, scriptFile];\n}\n\n/**\n * Make sure the 'app' is an array\n *\n * If it's a string, split on spaces as a trivial way of tokenizing the command line.\n */\nfunction appToArray(app: any) {\n return typeof app === 'string' ? app.split(' ') : app;\n}\n", "import type * as cxapi from '@aws-cdk/cx-api';\nimport * as chalk from 'chalk';\nimport { minimatch } from 'minimatch';\nimport { StackCollection } from './stack-collection';\nimport { flatten } from '../../util';\nimport { IO } from '../io/private';\nimport type { IoHelper } from '../io/private/io-helper';\n\nexport interface IStackAssembly {\n /**\n * The directory this CloudAssembly was read from\n */\n directory: string;\n\n /**\n * Select a single stack by its ID\n */\n stackById(stackId: string): StackCollection;\n}\n\n/**\n * When selecting stacks, what other stacks to include because of dependencies\n */\nexport enum ExtendedStackSelection {\n /**\n * Don't select any extra stacks\n */\n None,\n\n /**\n * Include stacks that this stack depends on\n */\n Upstream,\n\n /**\n * Include stacks that depend on this stack\n */\n Downstream,\n}\n\n/**\n * A single Cloud Assembly and the operations we do on it to deploy the artifacts inside\n */\nexport abstract class BaseStackAssembly implements IStackAssembly {\n /**\n * Sanitize a list of stack match patterns\n */\n protected static sanitizePatterns(patterns: string[]): string[] {\n let sanitized = patterns.filter(s => s != null); // filter null/undefined\n sanitized = [...new Set(sanitized)]; // make them unique\n return sanitized;\n }\n\n /**\n * The directory this CloudAssembly was read from\n */\n public readonly directory: string;\n\n /**\n * The IoHelper used for messaging\n */\n protected readonly ioHelper: IoHelper;\n\n constructor(public readonly assembly: cxapi.CloudAssembly, ioHelper: IoHelper) {\n this.directory = assembly.directory;\n this.ioHelper = ioHelper;\n }\n\n /**\n * Select a single stack by its ID\n */\n public stackById(stackId: string) {\n return new StackCollection(this, [this.assembly.getStackArtifact(stackId)]);\n }\n\n protected async selectMatchingStacks(\n stacks: cxapi.CloudFormationStackArtifact[],\n patterns: string[],\n extend: ExtendedStackSelection = ExtendedStackSelection.None,\n ): Promise<StackCollection> {\n const matchingPattern = (pattern: string) => (stack: cxapi.CloudFormationStackArtifact) => minimatch(stack.hierarchicalId, pattern);\n const matchedStacks = flatten(patterns.map(pattern => stacks.filter(matchingPattern(pattern))));\n\n return this.extendStacks(matchedStacks, stacks, extend);\n }\n\n protected async extendStacks(\n matched: cxapi.CloudFormationStackArtifact[],\n all: cxapi.CloudFormationStackArtifact[],\n extend: ExtendedStackSelection = ExtendedStackSelection.None,\n ) {\n const allStacks = new Map<string, cxapi.CloudFormationStackArtifact>();\n for (const stack of all) {\n allStacks.set(stack.hierarchicalId, stack);\n }\n\n const index = indexByHierarchicalId(matched);\n\n switch (extend) {\n case ExtendedStackSelection.Downstream:\n await includeDownstreamStacks(this.ioHelper, index, allStacks);\n break;\n case ExtendedStackSelection.Upstream:\n await includeUpstreamStacks(this.ioHelper, index, allStacks);\n break;\n }\n\n // Filter original array because it is in the right order\n const selectedList = all.filter(s => index.has(s.hierarchicalId));\n\n return new StackCollection(this, selectedList);\n }\n}\n\nfunction indexByHierarchicalId(stacks: cxapi.CloudFormationStackArtifact[]): Map<string, cxapi.CloudFormationStackArtifact> {\n const result = new Map<string, cxapi.CloudFormationStackArtifact>();\n\n for (const stack of stacks) {\n result.set(stack.hierarchicalId, stack);\n }\n\n return result;\n}\n\n/**\n * Calculate the transitive closure of stack dependents.\n *\n * Modifies `selectedStacks` in-place.\n */\nasync function includeDownstreamStacks(\n ioHelper: IoHelper,\n selectedStacks: Map<string, cxapi.CloudFormationStackArtifact>,\n allStacks: Map<string, cxapi.CloudFormationStackArtifact>,\n) {\n const added = new Array<string>();\n\n let madeProgress;\n do {\n madeProgress = false;\n\n for (const [id, stack] of allStacks) {\n // Select this stack if it's not selected yet AND it depends on a stack that's in the selected set\n if (!selectedStacks.has(id) && (stack.dependencies || []).some(dep => selectedStacks.has(dep.id))) {\n selectedStacks.set(id, stack);\n added.push(id);\n madeProgress = true;\n }\n }\n } while (madeProgress);\n\n if (added.length > 0) {\n await ioHelper.notify(IO.DEFAULT_ASSEMBLY_INFO.msg(`Including depending stacks: ${chalk.bold(added.join(', '))}`));\n }\n}\n\n/**\n * Calculate the transitive closure of stack dependencies.\n *\n * Modifies `selectedStacks` in-place.\n */\nasync function includeUpstreamStacks(\n ioHelper: IoHelper,\n selectedStacks: Map<string, cxapi.CloudFormationStackArtifact>,\n allStacks: Map<string, cxapi.CloudFormationStackArtifact>,\n) {\n const added = new Array<string>();\n let madeProgress = true;\n while (madeProgress) {\n madeProgress = false;\n\n for (const stack of selectedStacks.values()) {\n // Select an additional stack if it's not selected yet and a dependency of a selected stack (and exists, obviously)\n for (const dependencyId of stack.dependencies.map(x => x.manifest.displayName ?? x.id)) {\n if (!selectedStacks.has(dependencyId) && allStacks.has(dependencyId)) {\n added.push(dependencyId);\n selectedStacks.set(dependencyId, allStacks.get(dependencyId)!);\n madeProgress = true;\n }\n }\n }\n }\n\n if (added.length > 0) {\n await ioHelper.notify(IO.DEFAULT_ASSEMBLY_INFO.msg(`Including dependency stacks: ${chalk.bold(added.join(', '))}`));\n }\n}\n", "import type * as cxapi from '@aws-cdk/cx-api';\nimport { SynthesisMessageLevel } from '@aws-cdk/cx-api';\nimport { AssemblyError, ToolkitError } from '../toolkit-error';\nimport type { IStackAssembly } from './stack-assembly';\nimport { type StackDetails } from '../../payloads/stack-details';\n\n/**\n * A collection of stacks and related artifacts\n *\n * In practice, not all artifacts in the CloudAssembly are created equal;\n * stacks can be selected independently, but other artifacts such as asset\n * bundles cannot.\n */\nexport class StackCollection {\n constructor(public readonly assembly: IStackAssembly, public readonly stackArtifacts: cxapi.CloudFormationStackArtifact[]) {\n }\n\n public get stackCount() {\n return this.stackArtifacts.length;\n }\n\n public get firstStack() {\n if (this.stackCount < 1) {\n throw new ToolkitError('StackCollection contains no stack artifacts (trying to access the first one)');\n }\n return this.stackArtifacts[0];\n }\n\n public get stackIds(): string[] {\n return this.stackArtifacts.map(s => s.id);\n }\n\n public get hierarchicalIds(): string[] {\n return this.stackArtifacts.map(s => s.hierarchicalId);\n }\n\n public withDependencies(): StackDetails[] {\n const allData: StackDetails[] = [];\n\n for (const stack of this.stackArtifacts) {\n const data: StackDetails = {\n id: stack.displayName ?? stack.id,\n name: stack.stackName,\n environment: stack.environment,\n dependencies: [],\n };\n\n for (const dependencyId of stack.dependencies.map(x => x.id)) {\n if (dependencyId.includes('.assets')) {\n continue;\n }\n\n const depStack = this.assembly.stackById(dependencyId);\n\n if (depStack.firstStack.dependencies.filter((dep) => !(dep.id).includes('.assets')).length > 0) {\n for (const stackDetail of depStack.withDependencies()) {\n data.dependencies.push({\n id: stackDetail.id,\n dependencies: stackDetail.dependencies,\n });\n }\n } else {\n data.dependencies.push({\n id: depStack.firstStack.displayName ?? depStack.firstStack.id,\n dependencies: [],\n });\n }\n }\n\n allData.push(data);\n }\n\n return allData;\n }\n\n public reversed() {\n const arts = [...this.stackArtifacts];\n arts.reverse();\n return new StackCollection(this.assembly, arts);\n }\n\n public filter(predicate: (art: cxapi.CloudFormationStackArtifact) => boolean): StackCollection {\n return new StackCollection(this.assembly, this.stackArtifacts.filter(predicate));\n }\n\n public concat(...others: StackCollection[]): StackCollection {\n return new StackCollection(this.assembly, this.stackArtifacts.concat(...others.map(o => o.stackArtifacts)));\n }\n\n /**\n * Extracts 'aws:cdk:warning|info|error' metadata entries from the stack synthesis\n */\n public async validateMetadata(\n failAt: 'warn' | 'error' | 'none' = 'error',\n logger: (level: 'info' | 'error' | 'warn', msg: cxapi.SynthesisMessage) => Promise<void> = async () => {\n },\n ) {\n let warnings = false;\n let errors = false;\n\n for (const stack of this.stackArtifacts) {\n for (const message of stack.messages) {\n switch (message.level) {\n case SynthesisMessageLevel.WARNING:\n warnings = true;\n await logger('warn', message);\n break;\n case SynthesisMessageLevel.ERROR:\n errors = true;\n await logger('error', message);\n break;\n case SynthesisMessageLevel.INFO:\n await logger('info', message);\n break;\n }\n }\n }\n\n if (errors && failAt != 'none') {\n throw AssemblyError.withStacks('Found errors', this.stackArtifacts);\n }\n\n if (warnings && failAt === 'warn') {\n throw AssemblyError.withStacks('Found warnings (--strict mode)', this.stackArtifacts);\n }\n }\n}\n", "/**\n * Which stacks should be selected from a cloud assembly\n */\nexport enum StackSelectionStrategy {\n /**\n * Returns all stacks in the app regardless of patterns,\n * including stacks inside nested assemblies.\n */\n ALL_STACKS = 'all-stacks',\n\n /**\n * Returns all stacks in the main (top level) assembly only.\n */\n MAIN_ASSEMBLY = 'main-assembly',\n\n /**\n * If the assembly includes a single stack, returns it.\n * Otherwise throws an exception.\n */\n ONLY_SINGLE = 'only-single',\n\n /**\n * Return stacks matched by patterns.\n * If no stacks are found, execution is halted successfully.\n * Most likely you don't want to use this but `StackSelectionStrategy.MUST_MATCH_PATTERN`\n */\n PATTERN_MATCH = 'pattern-match',\n\n /**\n * Return stacks matched by patterns.\n * Throws an exception if the patterns don't match at least one stack in the assembly.\n */\n PATTERN_MUST_MATCH = 'pattern-must-match',\n\n /**\n * Returns if exactly one stack is matched by the pattern(s).\n * Throws an exception if no stack, or more than exactly one stack are matched.\n */\n PATTERN_MUST_MATCH_SINGLE = 'pattern-must-match-single',\n}\n\n/**\n * When selecting stacks, what other stacks to include because of dependencies\n */\nexport enum ExpandStackSelection {\n /**\n * Don't select any extra stacks\n */\n NONE = 'none',\n\n /**\n * Include stacks that this stack depends on\n */\n UPSTREAM = 'upstream',\n\n /**\n * Include stacks that depend on this stack\n */\n DOWNSTREAM = 'downstream',\n\n /**\n * @TODO\n * Include both directions.\n * I.e. stacks that this stack depends on, and stacks that depend on this stack.\n */\n // FULL = 'full',\n}\n\n/**\n * A specification of which stacks should be selected\n */\nexport interface StackSelector {\n /**\n * The behavior if if no selectors are provided.\n */\n strategy: StackSelectionStrategy;\n\n /**\n * A list of patterns to match the stack hierarchical ids\n * Only used with `PATTERN_*` selection strategies.\n */\n patterns?: string[];\n\n /**\n * Expand the selection to upstream/downstream stacks.\n * @default ExpandStackSelection.None only select the specified/matched stacks\n */\n expand?: ExpandStackSelection;\n\n /**\n * By default, we throw an exception if the assembly contains no stacks.\n * Set to `false`, to halt execution for empty assemblies without error.\n *\n * Note that actions can still throw if a stack selection result is empty,\n * but the assembly contains stacks in principle.\n *\n * @default true\n */\n failOnEmpty?: boolean;\n}\n", "import * as os from 'os';\nimport * as fs_path from 'path';\nimport * as fs from 'fs-extra';\nimport { ToolkitError } from './toolkit-error';\nimport * as util from '../util';\n\nexport type SettingsMap = { [key: string]: any };\n\n/**\n * If a context value is an object with this key set to a truthy value, it won't be saved to cdk.context.json\n */\nexport const TRANSIENT_CONTEXT_KEY = '$dontSaveContext';\n\n/**\n * A single bag of settings\n */\nexport class Settings {\n public static mergeAll(...settings: Settings[]): Settings {\n let ret = new Settings();\n for (const setting of settings) {\n ret = ret.merge(setting);\n }\n return ret;\n }\n\n constructor(\n private settings: SettingsMap = {},\n public readonly readOnly = false,\n ) {\n }\n\n public async save(fileName: string): Promise<this> {\n const expanded = expandHomeDir(fileName);\n await fs.writeJson(expanded, stripTransientValues(this.settings), {\n spaces: 2,\n });\n return this;\n }\n\n public get all(): any {\n return this.get([]);\n }\n\n public merge(other: Settings): Settings {\n return new Settings(util.deepMerge(this.settings, other.settings));\n }\n\n public subSettings(keyPrefix: string[]) {\n return new Settings(this.get(keyPrefix) || {}, false);\n }\n\n public makeReadOnly(): Settings {\n return new Settings(this.settings, true);\n }\n\n public clear() {\n if (this.readOnly) {\n throw new ToolkitError('Cannot clear(): settings are readonly');\n }\n this.settings = {};\n }\n\n public get empty(): boolean {\n return Object.keys(this.settings).length === 0;\n }\n\n public get(path: string[]): any {\n return util.deepClone(util.deepGet(this.settings, path));\n }\n\n public set(path: string[], value: any): Settings {\n if (this.readOnly) {\n throw new ToolkitError(`Can't set ${path}: settings object is readonly`);\n }\n if (path.length === 0) {\n // deepSet can't handle this case\n this.settings = value;\n } else {\n util.deepSet(this.settings, path, value);\n }\n return this;\n }\n\n public unset(path: string[]) {\n this.set(path, undefined);\n }\n}\n\nfunction expandHomeDir(x: string) {\n if (x.startsWith('~')) {\n return fs_path.join(os.homedir(), x.slice(1));\n }\n return x;\n}\n\n/**\n * Return all context value that are not transient context values\n */\nfunction stripTransientValues(obj: { [key: string]: any }) {\n const ret: any = {};\n for (const [key, value] of Object.entries(obj)) {\n if (!isTransientValue(value)) {\n ret[key] = value;\n }\n }\n return ret;\n}\n\n/**\n * Return whether the given value is a transient context value\n *\n * Values that are objects with a magic key set to a truthy value are considered transient.\n */\nfunction isTransientValue(value: any) {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as any)[TRANSIENT_CONTEXT_KEY]\n );\n}\n", "import { Settings } from './settings';\nimport { ToolkitError } from './toolkit-error';\n\nexport { TRANSIENT_CONTEXT_KEY } from './settings';\nexport const PROJECT_CONTEXT = 'cdk.context.json';\n\ninterface ContextBag {\n /**\n * The file name of the context. Will be used to potentially\n * save new context back to the original file.\n */\n fileName?: string;\n\n /**\n * The context values.\n */\n bag: Settings;\n}\n\n/**\n * Class that supports overlaying property bags\n *\n * Reads come from the first property bag that can has the given key,\n * writes go to the first property bag that is not readonly. A write\n * will remove the value from all property bags after the first\n * writable one.\n */\nexport class Context {\n private readonly bags: Settings[];\n private readonly fileNames: (string | undefined)[];\n\n constructor(...bags: ContextBag[]) {\n this.bags = bags.length > 0 ? bags.map((b) => b.bag) : [new Settings()];\n this.fileNames =\n bags.length > 0 ? bags.map((b) => b.fileName) : ['default'];\n }\n\n public get keys(): string[] {\n return Object.keys(this.all);\n }\n\n public has(key: string) {\n return this.keys.indexOf(key) > -1;\n }\n\n public get all(): { [key: string]: any } {\n let ret = new Settings();\n\n // In reverse order so keys to the left overwrite keys to the right of them\n for (const bag of [...this.bags].reverse()) {\n ret = ret.merge(bag);\n }\n\n return ret.all;\n }\n\n public get(key: string): any {\n for (const bag of this.bags) {\n const v = bag.get([key]);\n if (v !== undefined) {\n return v;\n }\n }\n return undefined;\n }\n\n public set(key: string, value: any) {\n for (const bag of this.bags) {\n if (bag.readOnly) {\n continue;\n }\n\n // All bags past the first one have the value erased\n bag.set([key], value);\n value = undefined;\n }\n }\n\n public unset(key: string) {\n this.set(key, undefined);\n }\n\n public clear() {\n for (const key of this.keys) {\n this.unset(key);\n }\n }\n\n /**\n * Save a specific context file\n */\n public async save(fileName: string): Promise<this> {\n const index = this.fileNames.indexOf(fileName);\n\n // File not found, don't do anything in this scenario\n if (index === -1) {\n return this;\n }\n\n const bag = this.bags[index];\n if (bag.readOnly) {\n throw new ToolkitError(`Context file ${fileName} is read only!`);\n }\n\n await bag.save(fileName);\n return this;\n }\n}\n", "import { format } from 'node:util';\nimport { Writable } from 'stream';\nimport * as cxschema from '@aws-cdk/cloud-assembly-schema';\nimport {\n type TemplateDiff,\n fullDiff,\n formatSecurityChanges,\n formatDifferences,\n mangleLikeCloudFormation,\n} from '@aws-cdk/cloudformation-diff';\nimport type * as cxapi from '@aws-cdk/cx-api';\nimport * as chalk from 'chalk';\nimport type { NestedStackTemplates } from '../cloudformation';\nimport type { IoHelper } from '../io/private';\nimport { IoDefaultMessages } from '../io/private';\nimport { RequireApproval } from '../require-approval';\nimport { ToolkitError } from '../toolkit-error';\n\n/*\n * Custom writable stream that collects text into a string buffer.\n * Used on classes that take in and directly write to a stream, but\n * we intend to capture the output rather than print.\n */\nclass StringWriteStream extends Writable {\n private buffer: string[] = [];\n\n constructor() {\n super();\n }\n\n _write(chunk: any, _encoding: string, callback: (error?: Error | null) => void): void {\n this.buffer.push(chunk.toString());\n callback();\n }\n\n toString(): string {\n return this.buffer.join('');\n }\n}\n\n/**\n * Output of formatSecurityDiff\n */\ninterface FormatSecurityDiffOutput {\n /**\n * Complete formatted security diff, if it is prompt-worthy\n */\n readonly formattedDiff?: string;\n}\n\n/**\n * Output of formatStackDiff\n */\ninterface FormatStackDiffOutput {\n /**\n * Number of stacks with diff changes\n */\n readonly numStacksWithChanges: number;\n\n /**\n * Complete formatted diff\n */\n readonly formattedDiff: string;\n}\n\n/**\n * Props for the Diff Formatter\n */\ninterface DiffFormatterProps {\n /**\n * Helper for the IoHost class\n */\n readonly ioHelper: IoHelper;\n\n /**\n * The relevant information for the Template that is being diffed.\n * Includes the old/current state of the stack as well as the new state.\n */\n readonly templateInfo: TemplateInfo;\n}\n\n/**\n * Properties specific to formatting the security diff\n */\ninterface FormatSecurityDiffOptions {\n /**\n * The approval level of the security diff\n */\n readonly requireApproval: RequireApproval;\n}\n\n/**\n * PRoperties specific to formatting the stack diff\n */\ninterface FormatStackDiffOptions {\n /**\n * do not filter out AWS::CDK::Metadata or Rules\n *\n * @default false\n */\n readonly strict?: boolean;\n\n /**\n * lines of context to use in arbitrary JSON diff\n *\n * @default 3\n */\n readonly context?: number;\n\n /**\n * silences \\'There were no differences\\' messages\n *\n * @default false\n */\n readonly quiet?: boolean;\n}\n\ninterface ReusableStackDiffOptions extends FormatStackDiffOptions {\n readonly ioDefaultHelper: IoDefaultMessages;\n}\n\n/**\n * Information on a template's old/new state\n * that is used for diff.\n */\nexport interface TemplateInfo {\n /**\n * The old/existing template\n */\n readonly oldTemplate: any;\n\n /**\n * The new template\n */\n readonly newTemplate: cxapi.CloudFormationStackArtifact;\n\n /**\n * A CloudFormation ChangeSet to help the diff operation.\n * Probably created via `createDiffChangeSet`.\n *\n * @default undefined\n */\n readonly changeSet?: any;\n\n /**\n * The name of the stack\n *\n * @default undefined\n */\n readonly stackName?: string;\n\n /**\n * Whether or not there are any imported resources\n *\n * @default false\n */\n readonly isImport?: boolean;\n\n /**\n * Any nested stacks included in the template\n *\n * @default {}\n */\n readonly nestedStacks?: {\n [nestedStackLogicalId: string]: NestedStackTemplates;\n };\n}\n\n/**\n * Class for formatting the diff output\n */\nexport class DiffFormatter {\n private readonly ioHelper: IoHelper;\n private readonly oldTemplate: any;\n private readonly newTemplate: cxapi.CloudFormationStackArtifact;\n private readonly stackName?: string;\n private readonly changeSet?: any;\n private readonly nestedStacks: { [nestedStackLogicalId: string]: NestedStackTemplates } | undefined;\n private readonly isImport: boolean;\n\n constructor(props: DiffFormatterProps) {\n this.ioHelper = props.ioHelper;\n this.oldTemplate = props.templateInfo.oldTemplate;\n this.newTemplate = props.templateInfo.newTemplate;\n this.stackName = props.templateInfo.stackName;\n this.changeSet = props.templateInfo.changeSet;\n this.nestedStacks = props.templateInfo.nestedStacks;\n this.isImport = props.templateInfo.isImport ?? false;\n }\n\n /**\n * Format the stack diff\n */\n public formatStackDiff(options: FormatStackDiffOptions = {}): FormatStackDiffOutput {\n const ioDefaultHelper = new IoDefaultMessages(this.ioHelper);\n return this.formatStackDiffHelper(\n this.oldTemplate,\n this.stackName,\n this.nestedStacks,\n {\n ...options,\n ioDefaultHelper,\n },\n );\n }\n\n private formatStackDiffHelper(\n oldTemplate: any,\n stackName: string | undefined,\n nestedStackTemplates: { [nestedStackLogicalId: string]: NestedStackTemplates } | undefined,\n options: ReusableStackDiffOptions,\n ) {\n let diff = fullDiff(oldTemplate, this.newTemplate.template, this.changeSet, this.isImport);\n\n // The stack diff is formatted via `Formatter`, which takes in a stream\n // and sends its output directly to that stream. To faciliate use of the\n // global CliIoHost, we create our own stream to capture the output of\n // `Formatter` and return the output as a string for the consumer of\n // `formatStackDiff` to decide what to do with it.\n const stream = new StringWriteStream();\n\n let numStacksWithChanges = 0;\n let formattedDiff = '';\n let filteredChangesCount = 0;\n try {\n // must output the stack name if there are differences, even if quiet\n if (stackName && (!options.quiet || !diff.isEmpty)) {\n stream.write(format(`Stack ${chalk.bold(stackName)}\\n`));\n }\n\n if (!options.quiet && this.isImport) {\n stream.write('Parameters and rules created during migration do not affect resource configuration.\\n');\n }\n\n // detect and filter out mangled characters from the diff\n if (diff.differenceCount && !options.strict) {\n const mangledNewTemplate = JSON.parse(mangleLikeCloudFormation(JSON.stringify(this.newTemplate.template)));\n const mangledDiff = fullDiff(this.oldTemplate, mangledNewTemplate, this.changeSet);\n filteredChangesCount = Math.max(0, diff.differenceCount - mangledDiff.differenceCount);\n if (filteredChangesCount > 0) {\n diff = mangledDiff;\n }\n }\n\n // filter out 'AWS::CDK::Metadata' resources from the template\n // filter out 'CheckBootstrapVersion' rules from the template\n if (!options.strict) {\n obscureDiff(diff);\n }\n\n if (!diff.isEmpty) {\n numStacksWithChanges++;\n\n // formatDifferences updates the stream with the formatted stack diff\n formatDifferences(stream, diff, {\n ...logicalIdMapFromTemplate(this.oldTemplate),\n ...buildLogicalToPathMap(this.newTemplate),\n }, options.context);\n } else if (!options.quiet) {\n stream.write(chalk.green('There were no differences\\n'));\n }\n\n if (filteredChangesCount > 0) {\n stream.write(chalk.yellow(`Omitted ${filteredChangesCount} changes because they are likely mangled non-ASCII characters. Use --strict to print them.\\n`));\n }\n } finally {\n // store the stream containing a formatted stack diff\n formattedDiff = stream.toString();\n stream.end();\n }\n\n for (const nestedStackLogicalId of Object.keys(nestedStackTemplates ?? {})) {\n if (!nestedStackTemplates) {\n break;\n }\n const nestedStack = nestedStackTemplates[nestedStackLogicalId];\n\n (this.newTemplate as any)._template = nestedStack.generatedTemplate;\n const nextDiff = this.formatStackDiffHelper(\n nestedStack.deployedTemplate,\n nestedStack.physicalName ?? nestedStackLogicalId,\n nestedStack.nestedStackTemplates,\n options,\n );\n numStacksWithChanges += nextDiff.numStacksWithChanges;\n formattedDiff += nextDiff.formattedDiff;\n }\n\n return {\n numStacksWithChanges,\n formattedDiff,\n };\n }\n\n /**\n * Format the security diff\n */\n public formatSecurityDiff(options: FormatSecurityDiffOptions): FormatSecurityDiffOutput {\n const ioDefaultHelper = new IoDefaultMessages(this.ioHelper);\n\n const diff = fullDiff(this.oldTemplate, this.newTemplate.template, this.changeSet);\n\n if (diffRequiresApproval(diff, options.requireApproval)) {\n // The security diff is formatted via `Formatter`, which takes in a stream\n // and sends its output directly to that stream. To faciliate use of the\n // global CliIoHost, we create our own stream to capture the output of\n // `Formatter` and return the output as a string for the consumer of\n // `formatSecurityDiff` to decide what to do with it.\n const stream = new StringWriteStream();\n\n stream.write(format(`Stack ${chalk.bold(this.stackName)}\\n`));\n\n // eslint-disable-next-line max-len\n ioDefaultHelper.warning(`This deployment will make potentially sensitive changes according to your current security approval level (--require-approval ${options.requireApproval}).`);\n ioDefaultHelper.warning('Please confirm you intend to make the following modifications:\\n');\n try {\n // formatSecurityChanges updates the stream with the formatted security diff\n formatSecurityChanges(stream, diff, buildLogicalToPathMap(this.newTemplate));\n } finally {\n stream.end();\n }\n // store the stream containing a formatted stack diff\n const formattedDiff = stream.toString();\n return { formattedDiff };\n }\n return {};\n }\n}\n\n/**\n * Return whether the diff has security-impacting changes that need confirmation\n *\n * TODO: Filter the security impact determination based off of an enum that allows\n * us to pick minimum \"severities\" to alert on.\n */\nfunction diffRequiresApproval(diff: TemplateDiff, requireApproval: RequireApproval) {\n switch (requireApproval) {\n case RequireApproval.NEVER: return false;\n case RequireApproval.ANY_CHANGE: return diff.permissionsAnyChanges;\n case RequireApproval.BROADENING: return diff.permissionsBroadened;\n default: throw new ToolkitError(`Unrecognized approval level: ${requireApproval}`);\n }\n}\n\nfunction buildLogicalToPathMap(stack: cxapi.CloudFormationStackArtifact) {\n const map: { [id: string]: string } = {};\n for (const md of stack.findMetadataByType(cxschema.ArtifactMetadataEntryType.LOGICAL_ID)) {\n map[md.data as string] = md.path;\n }\n return map;\n}\n\nfunction logicalIdMapFromTemplate(template: any) {\n const ret: Record<string, string> = {};\n\n for (const [logicalId, resource] of Object.entries(template.Resources ?? {})) {\n const path = (resource as any)?.Metadata?.['aws:cdk:path'];\n if (path) {\n ret[logicalId] = path;\n }\n }\n return ret;\n}\n\n/**\n * Remove any template elements that we don't want to show users.\n * This is currently:\n * - AWS::CDK::Metadata resource\n * - CheckBootstrapVersion Rule\n */\nfunction obscureDiff(diff: TemplateDiff) {\n if (diff.unknown) {\n // see https://github.com/aws/aws-cdk/issues/17942\n diff.unknown = diff.unknown.filter(change => {\n if (!change) {\n return true;\n }\n if (change.newValue?.CheckBootstrapVersion) {\n return false;\n }\n if (change.oldValue?.CheckBootstrapVersion) {\n return false;\n }\n return true;\n });\n }\n\n if (diff.resources) {\n diff.resources = diff.resources.filter(change => {\n if (!change) {\n return true;\n }\n if (change.newResourceType === 'AWS::CDK::Metadata') {\n return false;\n }\n if (change.oldResourceType === 'AWS::CDK::Metadata') {\n return false;\n }\n return true;\n });\n }\n}\n", "/**\n * @deprecated\n */\nexport enum RequireApproval {\n /**\n * Never require any security approvals\n */\n NEVER = 'never',\n /**\n * Any security changes require an approval\n */\n ANY_CHANGE = 'any-change',\n /**\n * Require approval only for changes that are access broadening\n */\n BROADENING = 'broadening',\n}\n", "import type * as cxapi from '@aws-cdk/cx-api';\nimport type { ImageIdentifier } from '@aws-sdk/client-ecr';\nimport type { Tag } from '@aws-sdk/client-s3';\nimport * as chalk from 'chalk';\nimport * as promptly from 'promptly';\nimport type { IECRClient, IS3Client, SDK, SdkProvider } from '../aws-auth';\nimport { DEFAULT_TOOLKIT_STACK_NAME, ToolkitInfo } from '../toolkit-info';\nimport { ProgressPrinter } from './progress-printer';\nimport { ActiveAssetCache, BackgroundStackRefresh, refreshStacks } from './stack-refresh';\nimport { IO, type IoHelper } from '../io/private';\nimport { Mode } from '../plugin';\nimport { ToolkitError } from '../toolkit-error';\n\n// Must use a require() otherwise esbuild complains\n// eslint-disable-next-line @typescript-eslint/no-require-imports,@typescript-eslint/consistent-type-imports\nconst pLimit: typeof import('p-limit') = require('p-limit');\n\nexport const S3_ISOLATED_TAG = 'aws-cdk:isolated';\nexport const ECR_ISOLATED_TAG = 'aws-cdk.isolated'; // ':' is not valid in ECR tags\nconst P_LIMIT = 50;\nconst DAY = 24 * 60 * 60 * 1000; // Number of milliseconds in a day\n\nexport type GcAsset = ImageAsset | ObjectAsset;\n\n/**\n * An image asset that lives in the bootstrapped ECR Repository\n */\nexport class ImageAsset {\n public constructor(\n public readonly digest: string,\n public readonly size: number,\n public readonly tags: string[],\n public readonly manifest: string,\n ) {\n }\n\n private getTag(tag: string) {\n return this.tags.find(t => t.includes(tag));\n }\n\n private hasTag(tag: string) {\n return this.tags.some(t => t.includes(tag));\n }\n\n public hasIsolatedTag() {\n return this.hasTag(ECR_ISOLATED_TAG);\n }\n\n public getIsolatedTag() {\n return this.getTag(ECR_ISOLATED_TAG);\n }\n\n public isolatedTagBefore(date: Date) {\n const dateIsolated = this.dateIsolated();\n if (!dateIsolated || dateIsolated == '') {\n return false;\n }\n return new Date(dateIsolated) < date;\n }\n\n public buildImageTag(inc: number) {\n // isolatedTag will look like \"X-aws-cdk.isolated-YYYYY\"\n return `${inc}-${ECR_ISOLATED_TAG}-${String(Date.now())}`;\n }\n\n public dateIsolated() {\n // isolatedTag will look like \"X-aws-cdk.isolated-YYYYY\"\n return this.getIsolatedTag()?.split('-')[3];\n }\n}\n\n/**\n * An object asset that lives in the bootstrapped S3 Bucket\n */\nexport class ObjectAsset {\n private cached_tags: Tag[] | undefined = undefined;\n\n public constructor(private readonly bucket: string, public readonly key: string, public readonly size: number) {\n }\n\n public fileName(): string {\n return this.key.split('.')[0];\n }\n\n public async allTags(s3: IS3Client) {\n if (this.cached_tags) {\n return this.cached_tags;\n }\n\n const response = await s3.getObjectTagging({ Bucket: this.bucket, Key: this.key });\n this.cached_tags = response.TagSet;\n return this.cached_tags;\n }\n\n private getTag(tag: string) {\n if (!this.cached_tags) {\n throw new ToolkitError('Cannot call getTag before allTags');\n }\n return this.cached_tags.find((t: any) => t.Key === tag)?.Value;\n }\n\n private hasTag(tag: string) {\n if (!this.cached_tags) {\n throw new ToolkitError('Cannot call hasTag before allTags');\n }\n return this.cached_tags.some((t: any) => t.Key === tag);\n }\n\n public hasIsolatedTag() {\n return this.hasTag(S3_ISOLATED_TAG);\n }\n\n public isolatedTagBefore(date: Date) {\n const tagValue = this.getTag(S3_ISOLATED_TAG);\n if (!tagValue || tagValue == '') {\n return false;\n }\n return new Date(tagValue) < date;\n }\n}\n\n/**\n * Props for the Garbage Collector\n */\ninterface GarbageCollectorProps {\n /**\n * The action to perform. Specify this if you want to perform a truncated set\n * of actions available.\n */\n readonly action: 'print' | 'tag' | 'delete-tagged' | 'full';\n\n /**\n * The type of asset to garbage collect.\n */\n readonly type: 's3' | 'ecr' | 'all';\n\n /**\n * The days an asset must be in isolation before being actually deleted.\n */\n readonly rollbackBufferDays: number;\n\n /**\n * Refuse deletion of any assets younger than this number of days.\n */\n readonly createdBufferDays: number;\n\n /**\n * The environment to deploy this stack in\n *\n * The environment on the stack artifact may be unresolved, this one\n * must be resolved.\n */\n readonly resolvedEnvironment: cxapi.Environment;\n\n /**\n * SDK provider (seeded with default credentials)\n *\n * Will be used to make SDK calls to CloudFormation, S3, and ECR.\n */\n readonly sdkProvider: SdkProvider;\n\n /**\n * Used to send messages.\n */\n readonly ioHelper: IoHelper;\n\n /**\n * The name of the bootstrap stack to look for.\n *\n * @default DEFAULT_TOOLKIT_STACK_NAME\n */\n readonly bootstrapStackName?: string;\n\n /**\n * Confirm with the user before actual deletion happens\n *\n * @default true\n */\n readonly confirm?: boolean;\n}\n\n/**\n * A class to facilitate Garbage Collection of S3 and ECR assets\n */\nexport class GarbageCollector {\n private garbageCollectS3Assets: boolean;\n private garbageCollectEcrAssets: boolean;\n private permissionToDelete: boolean;\n private permissionToTag: boolean;\n private bootstrapStackName: string;\n private confirm: boolean;\n private ioHelper: IoHelper;\n\n public constructor(readonly props: GarbageCollectorProps) {\n this.ioHelper = props.ioHelper;\n\n this.garbageCollectS3Assets = ['s3', 'all'].includes(props.type);\n this.garbageCollectEcrAssets = ['ecr', 'all'].includes(props.type);\n\n this.permissionToDelete = ['delete-tagged', 'full'].includes(props.action);\n this.permissionToTag = ['tag', 'full'].includes(props.action);\n this.confirm = props.confirm ?? true;\n\n this.bootstrapStackName = props.bootstrapStackName ?? DEFAULT_TOOLKIT_STACK_NAME;\n }\n\n /**\n * Perform garbage collection on the resolved environment.\n */\n public async garbageCollect() {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${this.garbageCollectS3Assets} ${this.garbageCollectEcrAssets}`));\n\n // SDKs\n const sdk = (await this.props.sdkProvider.forEnvironment(this.props.resolvedEnvironment, Mode.ForWriting)).sdk;\n const cfn = sdk.cloudFormation();\n\n const qualifier = await this.bootstrapQualifier(sdk, this.bootstrapStackName);\n const activeAssets = new ActiveAssetCache();\n\n // Grab stack templates first\n await refreshStacks(cfn, this.ioHelper, activeAssets, qualifier);\n // Start the background refresh\n const backgroundStackRefresh = new BackgroundStackRefresh({\n cfn,\n ioHelper: this.ioHelper,\n activeAssets,\n qualifier,\n });\n backgroundStackRefresh.start();\n\n try {\n if (this.garbageCollectS3Assets) {\n await this.garbageCollectS3(sdk, activeAssets, backgroundStackRefresh);\n }\n\n if (this.garbageCollectEcrAssets) {\n await this.garbageCollectEcr(sdk, activeAssets, backgroundStackRefresh);\n }\n } catch (err: any) {\n throw new ToolkitError(err);\n } finally {\n backgroundStackRefresh.stop();\n }\n }\n\n /**\n * Perform garbage collection on ECR assets\n */\n public async garbageCollectEcr(sdk: SDK, activeAssets: ActiveAssetCache, backgroundStackRefresh: BackgroundStackRefresh) {\n const ecr = sdk.ecr();\n const repo = await this.bootstrapRepositoryName(sdk, this.bootstrapStackName);\n const numImages = await this.numImagesInRepo(ecr, repo);\n const printer = new ProgressPrinter(this.ioHelper, numImages, 1000);\n\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Found bootstrap repo ${repo} with ${numImages} images`));\n\n try {\n // const batches = 1;\n const batchSize = 1000;\n const currentTime = Date.now();\n const graceDays = this.props.rollbackBufferDays;\n\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Parsing through ${numImages} images in batches`));\n\n printer.start();\n\n for await (const batch of this.readRepoInBatches(ecr, repo, batchSize, currentTime)) {\n await backgroundStackRefresh.noOlderThan(600_000); // 10 mins\n\n const { included: isolated, excluded: notIsolated } = partition(batch, asset => !asset.tags.some(t => activeAssets.contains(t)));\n\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${isolated.length} isolated images`));\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${notIsolated.length} not isolated images`));\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${batch.length} images total`));\n\n let deletables: ImageAsset[] = isolated;\n let taggables: ImageAsset[] = [];\n let untaggables: ImageAsset[] = [];\n\n if (graceDays > 0) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg('Filtering out images that are not old enough to delete'));\n\n // We delete images that are not referenced in ActiveAssets and have the Isolated Tag with a date\n // earlier than the current time - grace period.\n deletables = isolated.filter(img => img.isolatedTagBefore(new Date(currentTime - (graceDays * DAY))));\n\n // We tag images that are not referenced in ActiveAssets and do not have the Isolated Tag.\n taggables = isolated.filter(img => !img.hasIsolatedTag());\n\n // We untag images that are referenced in ActiveAssets and currently have the Isolated Tag.\n untaggables = notIsolated.filter(img => img.hasIsolatedTag());\n }\n\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${deletables.length} deletable assets`));\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${taggables.length} taggable assets`));\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${untaggables.length} assets to untag`));\n\n if (this.permissionToDelete && deletables.length > 0) {\n await this.confirmationPrompt(printer, deletables, 'image');\n await this.parallelDeleteEcr(ecr, repo, deletables, printer);\n }\n\n if (this.permissionToTag && taggables.length > 0) {\n await this.parallelTagEcr(ecr, repo, taggables, printer);\n }\n\n if (this.permissionToTag && untaggables.length > 0) {\n await this.parallelUntagEcr(ecr, repo, untaggables);\n }\n\n printer.reportScannedAsset(batch.length);\n }\n } catch (err: any) {\n throw new ToolkitError(err);\n } finally {\n printer.stop();\n }\n }\n\n /**\n * Perform garbage collection on S3 assets\n */\n public async garbageCollectS3(sdk: SDK, activeAssets: ActiveAssetCache, backgroundStackRefresh: BackgroundStackRefresh) {\n const s3 = sdk.s3();\n const bucket = await this.bootstrapBucketName(sdk, this.bootstrapStackName);\n const numObjects = await this.numObjectsInBucket(s3, bucket);\n const printer = new ProgressPrinter(this.ioHelper, numObjects, 1000);\n\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Found bootstrap bucket ${bucket} with ${numObjects} objects`));\n\n try {\n const batchSize = 1000;\n const currentTime = Date.now();\n const graceDays = this.props.rollbackBufferDays;\n\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Parsing through ${numObjects} objects in batches`));\n\n printer.start();\n\n // Process objects in batches of 1000\n // This is the batch limit of s3.DeleteObject and we intend to optimize for the \"worst case\" scenario\n // where gc is run for the first time on a long-standing bucket where ~100% of objects are isolated.\n for await (const batch of this.readBucketInBatches(s3, bucket, batchSize, currentTime)) {\n await backgroundStackRefresh.noOlderThan(600_000); // 10 mins\n\n const { included: isolated, excluded: notIsolated } = partition(batch, asset => !activeAssets.contains(asset.fileName()));\n\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${isolated.length} isolated assets`));\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${notIsolated.length} not isolated assets`));\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${batch.length} objects total`));\n\n let deletables: ObjectAsset[] = isolated;\n let taggables: ObjectAsset[] = [];\n let untaggables: ObjectAsset[] = [];\n\n if (graceDays > 0) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg('Filtering out assets that are not old enough to delete'));\n await this.parallelReadAllTags(s3, batch);\n\n // We delete objects that are not referenced in ActiveAssets and have the Isolated Tag with a date\n // earlier than the current time - grace period.\n deletables = isolated.filter(obj => obj.isolatedTagBefore(new Date(currentTime - (graceDays * DAY))));\n\n // We tag objects that are not referenced in ActiveAssets and do not have the Isolated Tag.\n taggables = isolated.filter(obj => !obj.hasIsolatedTag());\n\n // We untag objects that are referenced in ActiveAssets and currently have the Isolated Tag.\n untaggables = notIsolated.filter(obj => obj.hasIsolatedTag());\n }\n\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${deletables.length} deletable assets`));\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${taggables.length} taggable assets`));\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${untaggables.length} assets to untag`));\n\n if (this.permissionToDelete && deletables.length > 0) {\n await this.confirmationPrompt(printer, deletables, 'object');\n await this.parallelDeleteS3(s3, bucket, deletables, printer);\n }\n\n if (this.permissionToTag && taggables.length > 0) {\n await this.parallelTagS3(s3, bucket, taggables, currentTime, printer);\n }\n\n if (this.permissionToTag && untaggables.length > 0) {\n await this.parallelUntagS3(s3, bucket, untaggables);\n }\n\n printer.reportScannedAsset(batch.length);\n }\n } catch (err: any) {\n throw new ToolkitError(err);\n } finally {\n printer.stop();\n }\n }\n\n private async parallelReadAllTags(s3: IS3Client, objects: ObjectAsset[]) {\n const limit = pLimit(P_LIMIT);\n\n for (const obj of objects) {\n await limit(() => obj.allTags(s3));\n }\n }\n\n /**\n * Untag assets that were previously tagged, but now currently referenced.\n * Since this is treated as an implementation detail, we do not print the results in the printer.\n */\n private async parallelUntagEcr(ecr: IECRClient, repo: string, untaggables: ImageAsset[]) {\n const limit = pLimit(P_LIMIT);\n\n for (const img of untaggables) {\n const tag = img.getIsolatedTag();\n await limit(() =>\n ecr.batchDeleteImage({\n repositoryName: repo,\n imageIds: [{\n imageTag: tag,\n }],\n }),\n );\n }\n\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Untagged ${untaggables.length} assets`));\n }\n\n /**\n * Untag assets that were previously tagged, but now currently referenced.\n * Since this is treated as an implementation detail, we do not print the results in the printer.\n */\n private async parallelUntagS3(s3: IS3Client, bucket: string, untaggables: ObjectAsset[]) {\n const limit = pLimit(P_LIMIT);\n\n for (const obj of untaggables) {\n const tags = await obj.allTags(s3) ?? [];\n const updatedTags = tags.filter((tag: Tag) => tag.Key !== S3_ISOLATED_TAG);\n await limit(() =>\n s3.deleteObjectTagging({\n Bucket: bucket,\n Key: obj.key,\n\n }),\n );\n await limit(() =>\n s3.putObjectTagging({\n Bucket: bucket,\n Key: obj.key,\n Tagging: {\n TagSet: updatedTags,\n },\n }),\n );\n }\n\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Untagged ${untaggables.length} assets`));\n }\n\n /**\n * Tag images in parallel using p-limit\n */\n private async parallelTagEcr(ecr: IECRClient, repo: string, taggables: ImageAsset[], printer: ProgressPrinter) {\n const limit = pLimit(P_LIMIT);\n\n for (let i = 0; i < taggables.length; i++) {\n const img = taggables[i];\n const tagEcr = async () => {\n try {\n await ecr.putImage({\n repositoryName: repo,\n imageDigest: img.digest,\n imageManifest: img.manifest,\n imageTag: img.buildImageTag(i),\n });\n } catch (error) {\n // This is a false negative -- an isolated asset is untagged\n // likely due to an imageTag collision. We can safely ignore,\n // and the isolated asset will be tagged next time.\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Warning: unable to tag image ${JSON.stringify(img.tags)} with ${img.buildImageTag(i)} due to the following error: ${error}`));\n }\n };\n await limit(() => tagEcr());\n }\n\n printer.reportTaggedAsset(taggables);\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Tagged ${taggables.length} assets`));\n }\n\n /**\n * Tag objects in parallel using p-limit. The putObjectTagging API does not\n * support batch tagging so we must handle the parallelism client-side.\n */\n private async parallelTagS3(s3: IS3Client, bucket: string, taggables: ObjectAsset[], date: number, printer: ProgressPrinter) {\n const limit = pLimit(P_LIMIT);\n\n for (const obj of taggables) {\n await limit(() =>\n s3.putObjectTagging({\n Bucket: bucket,\n Key: obj.key,\n Tagging: {\n TagSet: [\n {\n Key: S3_ISOLATED_TAG,\n Value: String(date),\n },\n ],\n },\n }),\n );\n }\n\n printer.reportTaggedAsset(taggables);\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Tagged ${taggables.length} assets`));\n }\n\n /**\n * Delete images in parallel. The deleteImage API supports batches of 100.\n */\n private async parallelDeleteEcr(ecr: IECRClient, repo: string, deletables: ImageAsset[], printer: ProgressPrinter) {\n const batchSize = 100;\n const imagesToDelete = deletables.map(img => ({\n imageDigest: img.digest,\n }));\n\n try {\n const batches = [];\n for (let i = 0; i < imagesToDelete.length; i += batchSize) {\n batches.push(imagesToDelete.slice(i, i + batchSize));\n }\n // Delete images in batches\n for (const batch of batches) {\n await ecr.batchDeleteImage({\n imageIds: batch,\n repositoryName: repo,\n });\n\n const deletedCount = batch.length;\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Deleted ${deletedCount} assets`));\n printer.reportDeletedAsset(deletables.slice(0, deletedCount));\n }\n } catch (err) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_ERROR.msg(`Error deleting images: ${err}`));\n }\n }\n\n /**\n * Delete objects in parallel. The deleteObjects API supports batches of 1000.\n */\n private async parallelDeleteS3(s3: IS3Client, bucket: string, deletables: ObjectAsset[], printer: ProgressPrinter) {\n const batchSize = 1000;\n const objectsToDelete = deletables.map(asset => ({\n Key: asset.key,\n }));\n\n try {\n const batches = [];\n for (let i = 0; i < objectsToDelete.length; i += batchSize) {\n batches.push(objectsToDelete.slice(i, i + batchSize));\n }\n // Delete objects in batches\n for (const batch of batches) {\n await s3.deleteObjects({\n Bucket: bucket,\n Delete: {\n Objects: batch,\n Quiet: true,\n },\n });\n\n const deletedCount = batch.length;\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Deleted ${deletedCount} assets`));\n printer.reportDeletedAsset(deletables.slice(0, deletedCount));\n }\n } catch (err) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(chalk.red(`Error deleting objects: ${err}`)));\n }\n }\n\n private async bootstrapBucketName(sdk: SDK, bootstrapStackName: string): Promise<string> {\n const toolkitInfo = await ToolkitInfo.lookup(this.props.resolvedEnvironment, sdk, this.ioHelper, bootstrapStackName);\n return toolkitInfo.bucketName;\n }\n\n private async bootstrapRepositoryName(sdk: SDK, bootstrapStackName: string): Promise<string> {\n const toolkitInfo = await ToolkitInfo.lookup(this.props.resolvedEnvironment, sdk, this.ioHelper, bootstrapStackName);\n return toolkitInfo.repositoryName;\n }\n\n private async bootstrapQualifier(sdk: SDK, bootstrapStackName: string): Promise<string | undefined> {\n const toolkitInfo = await ToolkitInfo.lookup(this.props.resolvedEnvironment, sdk, this.ioHelper, bootstrapStackName);\n return toolkitInfo.bootstrapStack.parameters.Qualifier;\n }\n\n private async numObjectsInBucket(s3: IS3Client, bucket: string): Promise<number> {\n let totalCount = 0;\n let continuationToken: string | undefined;\n\n do {\n const response = await s3.listObjectsV2({\n Bucket: bucket,\n ContinuationToken: continuationToken,\n });\n\n totalCount += response.KeyCount ?? 0;\n continuationToken = response.NextContinuationToken;\n } while (continuationToken);\n\n return totalCount;\n }\n\n private async numImagesInRepo(ecr: IECRClient, repo: string): Promise<number> {\n let totalCount = 0;\n let nextToken: string | undefined;\n\n do {\n const response = await ecr.listImages({\n repositoryName: repo,\n nextToken: nextToken,\n });\n\n totalCount += response.imageIds?.length ?? 0;\n nextToken = response.nextToken;\n } while (nextToken);\n\n return totalCount;\n }\n\n private async *readRepoInBatches(ecr: IECRClient, repo: string, batchSize: number = 1000, currentTime: number): AsyncGenerator<ImageAsset[]> {\n let continuationToken: string | undefined;\n\n do {\n const batch: ImageAsset[] = [];\n\n while (batch.length < batchSize) {\n const response = await ecr.listImages({\n repositoryName: repo,\n nextToken: continuationToken,\n });\n\n // No images in the repository\n if (!response.imageIds || response.imageIds.length === 0) {\n break;\n }\n\n // map unique image digest to (possibly multiple) tags\n const images = imageMap(response.imageIds ?? []);\n\n const imageIds = Object.keys(images).map(key => ({\n imageDigest: key,\n }));\n\n const describeImageInfo = await ecr.describeImages({\n repositoryName: repo,\n imageIds: imageIds,\n });\n\n const getImageInfo = await ecr.batchGetImage({\n repositoryName: repo,\n imageIds: imageIds,\n });\n\n const combinedImageInfo = describeImageInfo.imageDetails?.map(imageDetail => {\n const matchingImage = getImageInfo.images?.find(\n img => img.imageId?.imageDigest === imageDetail.imageDigest,\n );\n\n return {\n ...imageDetail,\n manifest: matchingImage?.imageManifest,\n };\n });\n\n for (const image of combinedImageInfo ?? []) {\n const lastModified = image.imagePushedAt ?? new Date(currentTime);\n // Store the image if it was pushed earlier than today - createdBufferDays\n if (image.imageDigest && lastModified < new Date(currentTime - (this.props.createdBufferDays * DAY))) {\n batch.push(new ImageAsset(image.imageDigest, image.imageSizeInBytes ?? 0, image.imageTags ?? [], image.manifest ?? ''));\n }\n }\n\n continuationToken = response.nextToken;\n\n if (!continuationToken) break; // No more images to fetch\n }\n\n if (batch.length > 0) {\n yield batch;\n }\n } while (continuationToken);\n }\n\n /**\n * Generator function that reads objects from the S3 Bucket in batches.\n */\n private async *readBucketInBatches(s3: IS3Client, bucket: string, batchSize: number = 1000, currentTime: number): AsyncGenerator<ObjectAsset[]> {\n let continuationToken: string | undefined;\n\n do {\n const batch: ObjectAsset[] = [];\n\n while (batch.length < batchSize) {\n const response = await s3.listObjectsV2({\n Bucket: bucket,\n ContinuationToken: continuationToken,\n });\n\n response.Contents?.forEach((obj: any) => {\n const key = obj.Key ?? '';\n const size = obj.Size ?? 0;\n const lastModified = obj.LastModified ?? new Date(currentTime);\n // Store the object if it has a Key and\n // if it has not been modified since today - createdBufferDays\n if (key && lastModified < new Date(currentTime - (this.props.createdBufferDays * DAY))) {\n batch.push(new ObjectAsset(bucket, key, size));\n }\n });\n\n continuationToken = response.NextContinuationToken;\n\n if (!continuationToken) break; // No more objects to fetch\n }\n\n if (batch.length > 0) {\n yield batch;\n }\n } while (continuationToken);\n }\n\n private async confirmationPrompt(printer: ProgressPrinter, deletables: GcAsset[], type: string) {\n const pluralize = (name: string, count: number): string => {\n return count === 1 ? name : `${name}s`;\n };\n\n if (this.confirm) {\n const message = [\n `Found ${deletables.length} ${pluralize(type, deletables.length)} to delete based off of the following criteria:`,\n `- ${type}s have been isolated for > ${this.props.rollbackBufferDays} days`,\n `- ${type}s were created > ${this.props.createdBufferDays} days ago`,\n '',\n 'Delete this batch (yes/no/delete-all)?',\n ].join('\\n');\n printer.pause();\n const response = await promptly.prompt(message,\n { trim: true },\n );\n\n // Anything other than yes/y/delete-all is treated as no\n if (!response || !['yes', 'y', 'delete-all'].includes(response.toLowerCase())) {\n throw new ToolkitError('Deletion aborted by user');\n } else if (response.toLowerCase() == 'delete-all') {\n this.confirm = false;\n }\n }\n printer.resume();\n }\n}\n\nfunction partition<A>(xs: Iterable<A>, pred: (x: A) => boolean): { included: A[]; excluded: A[] } {\n const result = {\n included: [] as A[],\n excluded: [] as A[],\n };\n\n for (const x of xs) {\n if (pred(x)) {\n result.included.push(x);\n } else {\n result.excluded.push(x);\n }\n }\n\n return result;\n}\n\nfunction imageMap(imageIds: ImageIdentifier[]) {\n const images: Record<string, string[]> = {};\n for (const image of imageIds ?? []) {\n if (!image.imageDigest || !image.imageTag) {\n continue;\n }\n if (!images[image.imageDigest]) {\n images[image.imageDigest] = [];\n }\n images[image.imageDigest].push(image.imageTag);\n }\n return images;\n}\n", "import * as chalk from 'chalk';\nimport type { GcAsset as GCAsset } from './garbage-collector';\nimport { IO, type IoHelper } from '../io/private';\nimport { ToolkitError } from '../toolkit-error';\n\nexport class ProgressPrinter {\n private ioHelper: IoHelper;\n private totalAssets: number;\n private assetsScanned: number;\n private taggedAsset: number;\n private taggedAssetsSizeMb: number;\n private deletedAssets: number;\n private deletedAssetsSizeMb: number;\n private interval: number;\n private setInterval?: ReturnType<typeof setTimeout>;\n private isPaused: boolean;\n\n constructor(ioHelper: IoHelper, totalAssets: number, interval?: number) {\n this.ioHelper = ioHelper;\n this.totalAssets = totalAssets;\n this.assetsScanned = 0;\n this.taggedAsset = 0;\n this.taggedAssetsSizeMb = 0;\n this.deletedAssets = 0;\n this.deletedAssetsSizeMb = 0;\n this.interval = interval ?? 10_000;\n this.isPaused = false;\n }\n\n public reportScannedAsset(amt: number) {\n this.assetsScanned += amt;\n }\n\n public reportTaggedAsset(assets: GCAsset[]) {\n this.taggedAsset += assets.length;\n const sizeInBytes = assets.reduce((total, asset) => total + asset.size, 0);\n this.taggedAssetsSizeMb += sizeInBytes / 1_048_576;\n }\n\n public reportDeletedAsset(assets: GCAsset[]) {\n this.deletedAssets += assets.length;\n const sizeInBytes = assets.reduce((total, asset) => total + asset.size, 0);\n this.deletedAssetsSizeMb += sizeInBytes / 1_048_576;\n }\n\n public start() {\n // If there is already a running setInterval, throw an error.\n // This is because if this.setInterval is reassigned to another setInterval,\n // the original setInterval remains and can no longer be cleared.\n if (this.setInterval) {\n throw new ToolkitError('ProgressPrinter is already running. Stop it first using the stop() method before starting it again.');\n }\n\n this.setInterval = setInterval(() => {\n if (!this.isPaused) {\n this.print();\n }\n }, this.interval);\n }\n\n public pause() {\n this.isPaused = true;\n }\n\n public resume() {\n this.isPaused = false;\n }\n\n public stop() {\n clearInterval(this.setInterval);\n // print one last time if not paused\n if (!this.isPaused) {\n this.print();\n }\n }\n\n private print() {\n const percentage = ((this.assetsScanned / this.totalAssets) * 100).toFixed(2);\n // print in MiB until we hit at least 1 GiB of data tagged/deleted\n if (Math.max(this.taggedAssetsSizeMb, this.deletedAssetsSizeMb) >= 1000) {\n void this.ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(chalk.green(`[${percentage}%] ${this.assetsScanned} files scanned: ${this.taggedAsset} assets (${(this.taggedAssetsSizeMb / 1000).toFixed(2)} GiB) tagged, ${this.deletedAssets} assets (${(this.deletedAssetsSizeMb / 1000).toFixed(2)} GiB) deleted.`)));\n } else {\n void this.ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(chalk.green(`[${percentage}%] ${this.assetsScanned} files scanned: ${this.taggedAsset} assets (${this.taggedAssetsSizeMb.toFixed(2)} MiB) tagged, ${this.deletedAssets} assets (${this.deletedAssetsSizeMb.toFixed(2)} MiB) deleted.`)));\n }\n }\n}\n", "import type { ParameterDeclaration } from '@aws-sdk/client-cloudformation';\nimport type { ICloudFormationClient } from '../aws-auth';\nimport { IO, type IoHelper } from '../io/private';\nimport { ToolkitError } from '../toolkit-error';\n\nexport class ActiveAssetCache {\n private readonly stacks: Set<string> = new Set();\n\n public rememberStack(stackTemplate: string) {\n this.stacks.add(stackTemplate);\n }\n\n public contains(asset: string): boolean {\n for (const stack of this.stacks) {\n if (stack.includes(asset)) {\n return true;\n }\n }\n return false;\n }\n}\n\nasync function paginateSdkCall(cb: (nextToken?: string) => Promise<string | undefined>) {\n let finished = false;\n let nextToken: string | undefined;\n while (!finished) {\n nextToken = await cb(nextToken);\n if (nextToken === undefined) {\n finished = true;\n }\n }\n}\n\n/**\n * Fetches all relevant stack templates from CloudFormation. It ignores the following stacks:\n * - stacks in DELETE_COMPLETE or DELETE_IN_PROGRESS stage\n * - stacks that are using a different bootstrap qualifier\n */\nasync function fetchAllStackTemplates(cfn: ICloudFormationClient, ioHelper: IoHelper, qualifier?: string) {\n const stackNames: string[] = [];\n await paginateSdkCall(async (nextToken) => {\n const stacks = await cfn.listStacks({ NextToken: nextToken });\n\n // We ignore stacks with these statuses because their assets are no longer live\n const ignoredStatues = ['CREATE_FAILED', 'DELETE_COMPLETE', 'DELETE_IN_PROGRESS', 'DELETE_FAILED', 'REVIEW_IN_PROGRESS'];\n stackNames.push(\n ...(stacks.StackSummaries ?? [])\n .filter((s: any) => !ignoredStatues.includes(s.StackStatus))\n .map((s: any) => s.StackId ?? s.StackName),\n );\n\n return stacks.NextToken;\n });\n\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Parsing through ${stackNames.length} stacks`));\n\n const templates: string[] = [];\n for (const stack of stackNames) {\n let summary;\n summary = await cfn.getTemplateSummary({\n StackName: stack,\n });\n\n if (bootstrapFilter(summary.Parameters, qualifier)) {\n // This stack is definitely bootstrapped to a different qualifier so we can safely ignore it\n continue;\n } else {\n const template = await cfn.getTemplate({\n StackName: stack,\n });\n\n templates.push((template.TemplateBody ?? '') + JSON.stringify(summary?.Parameters));\n }\n }\n\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg('Done parsing through stacks'));\n\n return templates;\n}\n\n/**\n * Filter out stacks that we KNOW are using a different bootstrap qualifier\n * This is mostly necessary for the integration tests that can run the same app (with the same assets)\n * under different qualifiers.\n * This is necessary because a stack under a different bootstrap could coincidentally reference the same hash\n * and cause a false negative (cause an asset to be preserved when its isolated)\n * This is intentionally done in a way where we ONLY filter out stacks that are meant for a different qualifier\n * because we are okay with false positives.\n */\nfunction bootstrapFilter(parameters?: ParameterDeclaration[], qualifier?: string) {\n const bootstrapVersion = parameters?.find((p) => p.ParameterKey === 'BootstrapVersion');\n const splitBootstrapVersion = bootstrapVersion?.DefaultValue?.split('/');\n // We find the qualifier in a specific part of the bootstrap version parameter\n return (qualifier &&\n splitBootstrapVersion &&\n splitBootstrapVersion.length == 4 &&\n splitBootstrapVersion[2] != qualifier);\n}\n\nexport async function refreshStacks(cfn: ICloudFormationClient, ioHelper: IoHelper, activeAssets: ActiveAssetCache, qualifier?: string) {\n try {\n const stacks = await fetchAllStackTemplates(cfn, ioHelper, qualifier);\n for (const stack of stacks) {\n activeAssets.rememberStack(stack);\n }\n } catch (err) {\n throw new ToolkitError(`Error refreshing stacks: ${err}`);\n }\n}\n\n/**\n * Background Stack Refresh properties\n */\nexport interface BackgroundStackRefreshProps {\n /**\n * The CFN SDK handler\n */\n readonly cfn: ICloudFormationClient;\n\n /**\n * Used to send messages.\n */\n readonly ioHelper: IoHelper;\n\n /**\n * Active Asset storage\n */\n readonly activeAssets: ActiveAssetCache;\n\n /**\n * Stack bootstrap qualifier\n */\n readonly qualifier?: string;\n}\n\n/**\n * Class that controls scheduling of the background stack refresh\n */\nexport class BackgroundStackRefresh {\n private timeout?: NodeJS.Timeout;\n private lastRefreshTime: number;\n private queuedPromises: Array<(value: unknown) => void> = [];\n\n constructor(private readonly props: BackgroundStackRefreshProps) {\n this.lastRefreshTime = Date.now();\n }\n\n public start() {\n // Since start is going to be called right after the first invocation of refreshStacks,\n // lets wait some time before beginning the background refresh.\n this.timeout = setTimeout(() => this.refresh(), 300_000); // 5 minutes\n }\n\n private async refresh() {\n const startTime = Date.now();\n\n await refreshStacks(this.props.cfn, this.props.ioHelper, this.props.activeAssets, this.props.qualifier);\n this.justRefreshedStacks();\n\n // If the last invocation of refreshStacks takes <5 minutes, the next invocation starts 5 minutes after the last one started.\n // If the last invocation of refreshStacks takes >5 minutes, the next invocation starts immediately.\n this.timeout = setTimeout(() => this.refresh(), Math.max(startTime + 300_000 - Date.now(), 0));\n }\n\n private justRefreshedStacks() {\n this.lastRefreshTime = Date.now();\n for (const p of this.queuedPromises.splice(0, this.queuedPromises.length)) {\n p(undefined);\n }\n }\n\n /**\n * Checks if the last successful background refresh happened within the specified time frame.\n * If the last refresh is older than the specified time frame, it returns a Promise that resolves\n * when the next background refresh completes or rejects if the refresh takes too long.\n */\n public noOlderThan(ms: number) {\n const horizon = Date.now() - ms;\n\n // The last refresh happened within the time frame\n if (this.lastRefreshTime >= horizon) {\n return Promise.resolve();\n }\n\n // The last refresh happened earlier than the time frame\n // We will wait for the latest refresh to land or reject if it takes too long\n return Promise.race([\n new Promise(resolve => this.queuedPromises.push(resolve)),\n new Promise((_, reject) => setTimeout(() => reject(new ToolkitError('refreshStacks took too long; the background thread likely threw an error')), ms)),\n ]);\n }\n\n public stop() {\n clearTimeout(this.timeout);\n }\n}\n", "import * as util from 'util';\nimport type * as cxapi from '@aws-cdk/cx-api';\nimport * as chalk from 'chalk';\nimport * as uuid from 'uuid';\nimport type { CloudWatchLogEvent } from '../../payloads/logs-monitor';\nimport { flatten } from '../../util';\nimport type { SDK } from '../aws-auth';\nimport { IO } from '../io/private';\nimport type { IoHelper } from '../io/private';\n\n/**\n * Configuration tracking information on the log groups that are\n * being monitored\n */\ninterface LogGroupsAccessSettings {\n /**\n * The SDK for a given environment (account/region)\n */\n readonly sdk: SDK;\n\n /**\n * A map of log groups and associated startTime in a given account.\n *\n * The monitor will read events from the log group starting at the\n * associated startTime\n */\n readonly logGroupsStartTimes: { [logGroupName: string]: number };\n}\n\nexport interface CloudWatchLogEventMonitorProps {\n /**\n * The IoHost used for messaging\n */\n readonly ioHelper: IoHelper;\n\n /**\n * The time from which we start reading log messages\n *\n * @default - now\n */\n readonly startTime?: Date;\n}\n\nexport class CloudWatchLogEventMonitor {\n /**\n * Determines which events not to display\n */\n private startTime: number;\n\n /**\n * Map of environment (account:region) to LogGroupsAccessSettings\n */\n private readonly envsLogGroupsAccessSettings = new Map<string, LogGroupsAccessSettings>();\n\n /**\n * After reading events from all CloudWatch log groups\n * how long should we wait to read more events.\n *\n * If there is some error with reading events (i.e. Throttle)\n * then this is also how long we wait until we try again\n */\n private readonly pollingInterval: number = 2_000;\n\n public monitorId?: string;\n private readonly ioHelper: IoHelper;\n\n constructor(props: CloudWatchLogEventMonitorProps) {\n this.startTime = props.startTime?.getTime() ?? Date.now();\n this.ioHelper = props.ioHelper;\n }\n\n /**\n * resume reading/printing events\n */\n public async activate(): Promise<void> {\n this.monitorId = uuid.v4();\n\n await this.ioHelper.notify(IO.CDK_TOOLKIT_I5032.msg('Start monitoring log groups', {\n monitor: this.monitorId,\n logGroupNames: this.logGroupNames(),\n }));\n\n await this.tick();\n this.scheduleNextTick();\n }\n\n /**\n * deactivates the monitor so no new events are read\n * use case for this is when we are in the middle of performing a deployment\n * and don't want to interweave all the logs together with the CFN\n * deployment logs\n *\n * Also resets the start time to be when the new deployment was triggered\n * and clears the list of tracked log groups\n */\n public async deactivate(): Promise<void> {\n const oldMonitorId = this.monitorId!;\n this.monitorId = undefined;\n this.startTime = Date.now();\n\n await this.ioHelper.notify(IO.CDK_TOOLKIT_I5034.msg('Stopped monitoring log groups', {\n monitor: oldMonitorId,\n logGroupNames: this.logGroupNames(),\n }));\n\n this.envsLogGroupsAccessSettings.clear();\n }\n\n /**\n * Adds CloudWatch log groups to read log events from.\n * Since we could be watching multiple stacks that deploy to\n * multiple environments (account+region), we need to store a list of log groups\n * per env along with the SDK object that has access to read from\n * that environment.\n */\n public addLogGroups(env: cxapi.Environment, sdk: SDK, logGroupNames: string[]): void {\n const awsEnv = `${env.account}:${env.region}`;\n const logGroupsStartTimes = logGroupNames.reduce(\n (acc, groupName) => {\n acc[groupName] = this.startTime;\n return acc;\n },\n {} as { [logGroupName: string]: number },\n );\n this.envsLogGroupsAccessSettings.set(awsEnv, {\n sdk,\n logGroupsStartTimes: {\n ...this.envsLogGroupsAccessSettings.get(awsEnv)?.logGroupsStartTimes,\n ...logGroupsStartTimes,\n },\n });\n }\n\n private logGroupNames(): string[] {\n return Array.from(this.envsLogGroupsAccessSettings.values()).flatMap((settings) => Object.keys(settings.logGroupsStartTimes));\n }\n\n private scheduleNextTick(): void {\n if (!this.monitorId) {\n return;\n }\n\n setTimeout(() => void this.tick(), this.pollingInterval);\n }\n\n private async tick(): Promise<void> {\n // excluding from codecoverage because this\n // doesn't always run (depends on timing)\n /* c8 ignore start */\n if (!this.monitorId) {\n return;\n }\n /* c8 ignore stop */\n\n try {\n const events = flatten(await this.readNewEvents());\n for (const event of events) {\n await this.print(event);\n }\n\n // We might have been stop()ped while the network call was in progress.\n if (!this.monitorId) {\n return;\n }\n } catch (e: any) {\n await this.ioHelper.notify(IO.CDK_TOOLKIT_E5035.msg('Error occurred while monitoring logs: %s', { error: e }));\n }\n\n this.scheduleNextTick();\n }\n\n /**\n * Reads all new log events from a set of CloudWatch Log Groups\n * in parallel\n */\n private async readNewEvents(): Promise<Array<Array<CloudWatchLogEvent>>> {\n const promises: Array<Promise<Array<CloudWatchLogEvent>>> = [];\n for (const settings of this.envsLogGroupsAccessSettings.values()) {\n for (const group of Object.keys(settings.logGroupsStartTimes)) {\n promises.push(this.readEventsFromLogGroup(settings, group));\n }\n }\n // Limited set of log groups\n // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism\n return Promise.all(promises);\n }\n\n /**\n * Print out a cloudwatch event\n */\n private async print(event: CloudWatchLogEvent): Promise<void> {\n await this.ioHelper.notify(IO.CDK_TOOLKIT_I5033.msg(\n util.format(\n '[%s] %s %s',\n chalk.blue(event.logGroupName),\n chalk.yellow(event.timestamp.toLocaleTimeString()),\n event.message.trim(),\n ),\n event,\n ));\n }\n\n /**\n * Reads all new log events from a CloudWatch Log Group\n * starting at either the time the hotswap was triggered or\n * when the last event was read on the previous tick\n */\n private async readEventsFromLogGroup(\n logGroupsAccessSettings: LogGroupsAccessSettings,\n logGroupName: string,\n ): Promise<Array<CloudWatchLogEvent>> {\n const events: CloudWatchLogEvent[] = [];\n\n // log events from some service are ingested faster than others\n // so we need to track the start/end time for each log group individually\n // to make sure that we process all events from each log group\n const startTime = logGroupsAccessSettings.logGroupsStartTimes[logGroupName] ?? this.startTime;\n let endTime = startTime;\n try {\n const response = await logGroupsAccessSettings.sdk.cloudWatchLogs().filterLogEvents({\n logGroupName: logGroupName,\n limit: 100,\n startTime: startTime,\n });\n const filteredEvents = response.events ?? [];\n\n for (const event of filteredEvents) {\n if (event.message) {\n events.push({\n message: event.message,\n logGroupName,\n timestamp: event.timestamp ? new Date(event.timestamp) : new Date(),\n });\n\n if (event.timestamp && endTime < event.timestamp) {\n endTime = event.timestamp;\n }\n }\n }\n // As long as there are _any_ events in the log group `filterLogEvents` will return a nextToken.\n // This is true even if these events are before `startTime`. So if we have 100 events and a nextToken\n // then assume that we have hit the limit and let the user know some messages have been suppressed.\n // We are essentially showing them a sampling (10000 events printed out is not very useful)\n if (filteredEvents.length === 100 && response.nextToken) {\n events.push({\n message: '>>> `watch` shows only the first 100 log messages - the rest have been truncated...',\n logGroupName,\n timestamp: new Date(endTime),\n });\n }\n } catch (e: any) {\n // with Lambda functions the CloudWatch is not created\n // until something is logged, so just keep polling until\n // there is somthing to find\n if (e.name === 'ResourceNotFoundException') {\n return [];\n }\n throw e;\n }\n logGroupsAccessSettings.logGroupsStartTimes[logGroupName] = endTime + 1;\n return events;\n }\n}\n", "import type { CloudFormationStackArtifact, Environment } from '@aws-cdk/cx-api';\nimport type { StackResourceSummary } from '@aws-sdk/client-cloudformation';\nimport { formatErrorMessage } from '../../util';\nimport type { SDK, SdkProvider } from '../aws-auth';\nimport { EvaluateCloudFormationTemplate, LazyListStackResources } from '../cloudformation';\nimport { EnvironmentAccess } from '../environment';\nimport { IO } from '../io/private';\nimport type { IoHelper } from '../io/private';\nimport { Mode } from '../plugin';\nimport { DEFAULT_TOOLKIT_STACK_NAME } from '../toolkit-info';\n\n// resource types that have associated CloudWatch Log Groups that should _not_ be monitored\nconst IGNORE_LOGS_RESOURCE_TYPES = ['AWS::EC2::FlowLog', 'AWS::CloudTrail::Trail', 'AWS::CodeBuild::Project'];\n\n/**\n * Configuration needed to monitor CloudWatch Log Groups\n * found in a given CloudFormation Stack\n */\nexport interface FoundLogGroupsResult {\n /**\n * The resolved environment (account/region) that the log\n * groups are deployed in\n */\n readonly env: Environment;\n\n /**\n * The SDK that can be used to read events from the CloudWatch\n * Log Groups in the given environment\n */\n readonly sdk: SDK;\n\n /**\n * The names of the relevant CloudWatch Log Groups\n * in the given CloudFormation template\n */\n readonly logGroupNames: string[];\n}\n\nexport async function findCloudWatchLogGroups(\n sdkProvider: SdkProvider,\n ioHelper: IoHelper,\n stackArtifact: CloudFormationStackArtifact,\n): Promise<FoundLogGroupsResult> {\n let sdk: SDK;\n const resolvedEnv = await sdkProvider.resolveEnvironment(stackArtifact.environment);\n // try to assume the lookup role and fallback to the default credentials\n try {\n sdk = (await new EnvironmentAccess(sdkProvider, DEFAULT_TOOLKIT_STACK_NAME, ioHelper).accessStackForLookup(stackArtifact)).sdk;\n } catch (e: any) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Failed to access SDK environment: ${formatErrorMessage(e)}`));\n sdk = (await sdkProvider.forEnvironment(resolvedEnv, Mode.ForReading)).sdk;\n }\n\n const listStackResources = new LazyListStackResources(sdk, stackArtifact.stackName);\n const evaluateCfnTemplate = new EvaluateCloudFormationTemplate({\n stackArtifact,\n parameters: {},\n account: resolvedEnv.account,\n region: resolvedEnv.region,\n partition: (await sdk.currentAccount()).partition,\n sdk,\n });\n\n const stackResources = await listStackResources.listStackResources();\n const logGroupNames = findAllLogGroupNames(stackResources, evaluateCfnTemplate);\n\n return {\n env: resolvedEnv,\n sdk,\n logGroupNames,\n };\n}\n\n/**\n * Determine if a CloudWatch Log Group is associated\n * with an ignored resource\n */\nfunction isReferencedFromIgnoredResource(\n logGroupResource: StackResourceSummary,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): boolean {\n const resourcesReferencingLogGroup = evaluateCfnTemplate.findReferencesTo(logGroupResource.LogicalResourceId!);\n return resourcesReferencingLogGroup.some((reference) => {\n return IGNORE_LOGS_RESOURCE_TYPES.includes(reference.Type);\n });\n}\n\ntype CloudWatchLogsResolver = (\n resource: StackResourceSummary,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n) => string | undefined;\n\nconst cloudWatchLogsResolvers: Record<string, CloudWatchLogsResolver> = {\n 'AWS::Logs::LogGroup': (resource, evaluateCfnTemplate) => {\n if (isReferencedFromIgnoredResource(resource, evaluateCfnTemplate)) {\n return undefined;\n }\n return resource.PhysicalResourceId?.toString();\n },\n\n // Resource types that will create a CloudWatch log group with a specific name if one is not provided.\n // The keys are CFN resource types, and the values are the name of the physical name property of that resource\n // and the service name that is used in the automatically created CloudWatch log group.\n 'AWS::Lambda::Function': (resource, evaluateCfnTemplate) => {\n const loggingConfig = evaluateCfnTemplate.getResourceProperty(resource.LogicalResourceId!, 'LoggingConfig');\n if (loggingConfig?.LogGroup) {\n // if LogGroup is a string then use it as the LogGroupName as it is referred by LogGroup.fromLogGroupArn in CDK\n if (typeof loggingConfig.LogGroup === 'string') {\n return loggingConfig.LogGroup;\n }\n\n // if { Ref: '...' } is used then try to resolve the LogGroupName from the referenced resource in the template\n if (typeof loggingConfig.LogGroup === 'object') {\n if (loggingConfig.LogGroup.Ref) {\n return evaluateCfnTemplate.getResourceProperty(loggingConfig.LogGroup.Ref, 'LogGroupName');\n }\n }\n }\n\n return `/aws/lambda/${resource.PhysicalResourceId}`;\n },\n};\n\n/**\n * Find all CloudWatch Log Groups in the deployed template.\n * This will find both explicitly created Log Groups (excluding those associated with ignored resources)\n * and Log Groups created implicitly (i.e. Lambda Functions)\n */\nfunction findAllLogGroupNames(\n stackResources: StackResourceSummary[],\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): string[] {\n const logGroupNames: string[] = [];\n\n for (const resource of stackResources) {\n const logGroupResolver = cloudWatchLogsResolvers[resource.ResourceType!];\n if (logGroupResolver) {\n const logGroupName = logGroupResolver(resource, evaluateCfnTemplate);\n if (logGroupName) {\n logGroupNames.push(logGroupName);\n }\n }\n }\n\n return logGroupNames;\n}\n", "import { format } from 'util';\nimport * as cfnDiff from '@aws-cdk/cloudformation-diff';\nimport type { ResourceDifference } from '@aws-cdk/cloudformation-diff';\nimport type * as cxapi from '@aws-cdk/cx-api';\nimport type { ResourceIdentifierSummary, ResourceToImport } from '@aws-sdk/client-cloudformation';\nimport * as chalk from 'chalk';\nimport * as fs from 'fs-extra';\nimport * as promptly from 'promptly';\nimport type { DeploymentMethod, Deployments } from '../deployments';\nimport { assertIsSuccessfulDeployStackResult } from '../deployments';\nimport { IO, type IoHelper } from '../io/private';\nimport type { Tag } from '../tags';\nimport { ToolkitError } from '../toolkit-error';\n\nexport type ResourcesToImport = ResourceToImport[];\nexport type ResourceIdentifierSummaries = ResourceIdentifierSummary[];\n\nexport interface ResourceImporterProps {\n deployments: Deployments;\n ioHelper: IoHelper;\n}\n\nexport interface ImportDeploymentOptions {\n /**\n * Role to pass to CloudFormation for deployment\n *\n * @default - Default stack role\n */\n readonly roleArn?: string;\n\n /**\n * Deployment method\n *\n * @default - Change set with default options\n */\n readonly deploymentMethod?: DeploymentMethod;\n\n /**\n * Stack tags (pass through to CloudFormation)\n *\n * @default - No tags\n */\n readonly tags?: Tag[];\n\n /**\n * Use previous values for unspecified parameters\n *\n * If not set, all parameters must be specified for every deployment.\n *\n * @default true\n */\n readonly usePreviousParameters?: boolean;\n\n /**\n * Rollback failed deployments\n *\n * @default true\n */\n readonly rollback?: boolean;\n}\n\n/**\n * Set of parameters that uniquely identify a physical resource of a given type\n * for the import operation, example:\n *\n * ```\n * {\n * \"AWS::S3::Bucket\": [[\"BucketName\"]],\n * \"AWS::DynamoDB::GlobalTable\": [[\"TableName\"], [\"TableArn\"], [\"TableStreamArn\"]],\n * \"AWS::Route53::KeySigningKey\": [[\"HostedZoneId\", \"Name\"]],\n * }\n * ```\n */\nexport type ResourceIdentifiers = { [resourceType: string]: string[][] };\n\ntype ResourceIdentifierProperties = Record<string, string>;\n\n/**\n * Mapping of CDK resources (L1 constructs) to physical resources to be imported\n * in their place, example:\n *\n * ```\n * {\n * \"MyStack/MyS3Bucket/Resource\": {\n * \"BucketName\": \"my-manually-created-s3-bucket\"\n * },\n * \"MyStack/MyVpc/Resource\": {\n * \"VpcId\": \"vpc-123456789\"\n * }\n * }\n * ```\n */\ntype ResourceMap = { [logicalResource: string]: ResourceIdentifierProperties };\n\n/**\n * Resource importing utility class\n *\n * - Determines the resources added to a template (compared to the deployed version)\n * - Look up the identification information\n * - Load them from a file, or\n * - Ask the user, based on information supplied to us by CloudFormation's GetTemplateSummary\n * - Translate the input to a structure expected by CloudFormation, update the template to add the\n * importable resources, then run an IMPORT changeset.\n */\nexport class ResourceImporter {\n private _currentTemplate: any;\n\n private readonly stack: cxapi.CloudFormationStackArtifact;\n private readonly cfn: Deployments;\n private readonly ioHelper: IoHelper;\n\n constructor(\n stack: cxapi.CloudFormationStackArtifact,\n props: ResourceImporterProps,\n ) {\n this.stack = stack;\n this.cfn = props.deployments;\n this.ioHelper = props.ioHelper;\n }\n\n /**\n * Ask the user for resources to import\n */\n public async askForResourceIdentifiers(available: ImportableResource[]): Promise<ImportMap> {\n const ret: ImportMap = { importResources: [], resourceMap: {} };\n const resourceIdentifiers = await this.resourceIdentifiers();\n\n for (const resource of available) {\n const identifier = await this.askForResourceIdentifier(resourceIdentifiers, resource);\n if (!identifier) {\n continue;\n }\n\n ret.importResources.push(resource);\n ret.resourceMap[resource.logicalId] = identifier;\n }\n\n return ret;\n }\n\n /**\n * Load the resources to import from a file\n */\n public async loadResourceIdentifiers(available: ImportableResource[], filename: string): Promise<ImportMap> {\n const contents = await fs.readJson(filename);\n\n const ret: ImportMap = { importResources: [], resourceMap: {} };\n for (const resource of available) {\n const descr = this.describeResource(resource.logicalId);\n const idProps = contents[resource.logicalId];\n if (idProps) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(format('%s: importing using %s', chalk.blue(descr), chalk.blue(fmtdict(idProps)))));\n\n ret.importResources.push(resource);\n ret.resourceMap[resource.logicalId] = idProps;\n delete contents[resource.logicalId];\n } else {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(format('%s: skipping', chalk.blue(descr))));\n }\n }\n\n const unknown = Object.keys(contents);\n if (unknown.length > 0) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_WARN.msg(`Unrecognized resource identifiers in mapping file: ${unknown.join(', ')}`));\n }\n\n return ret;\n }\n\n /**\n * Based on the provided resource mapping, prepare CFN structures for import (template,\n * ResourcesToImport structure) and perform the import operation (CloudFormation deployment)\n *\n * @param importMap Mapping from CDK construct tree path to physical resource import identifiers\n * @param options Options to pass to CloudFormation deploy operation\n */\n public async importResourcesFromMap(importMap: ImportMap, options: ImportDeploymentOptions = {}) {\n const resourcesToImport: ResourcesToImport = await this.makeResourcesToImport(importMap);\n const updatedTemplate = await this.currentTemplateWithAdditions(importMap.importResources);\n\n await this.importResources(updatedTemplate, resourcesToImport, options);\n }\n\n /**\n * Based on the app and resources file generated by cdk migrate. Removes all items from the template that\n * cannot be included in an import change-set for new stacks and performs the import operation,\n * creating the new stack.\n *\n * @param resourcesToImport The mapping created by cdk migrate\n * @param options Options to pass to CloudFormation deploy operation\n */\n public async importResourcesFromMigrate(resourcesToImport: ResourcesToImport, options: ImportDeploymentOptions = {}) {\n const updatedTemplate = this.removeNonImportResources();\n\n await this.importResources(updatedTemplate, resourcesToImport, options);\n }\n\n private async importResources(overrideTemplate: any, resourcesToImport: ResourcesToImport, options: ImportDeploymentOptions) {\n try {\n const result = await this.cfn.deployStack({\n stack: this.stack,\n deployName: this.stack.stackName,\n ...options,\n overrideTemplate,\n resourcesToImport,\n });\n\n assertIsSuccessfulDeployStackResult(result);\n\n const message = result.noOp\n ? ' \u2705 %s (no changes)'\n : ' \u2705 %s';\n\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg('\\n' + chalk.green(format(message, this.stack.displayName))));\n } catch (e) {\n await this.ioHelper.notify(IO.CDK_TOOLKIT_E3900.msg(format('\\n \u274C %s failed: %s', chalk.bold(this.stack.displayName), e), { error: e as any }));\n throw e;\n }\n }\n\n /**\n * Perform a diff between the currently running and the new template, ensure that it is valid\n * for importing and return a list of resources that are being added in the new version\n *\n * @return mapping logicalResourceId -> resourceDifference\n */\n public async discoverImportableResources(allowNonAdditions = false): Promise<DiscoverImportableResourcesResult> {\n const currentTemplate = await this.currentTemplate();\n\n const diff = cfnDiff.fullDiff(currentTemplate, this.stack.template);\n\n // Ignore changes to CDKMetadata\n const resourceChanges = Object.entries(diff.resources.changes)\n .filter(([logicalId, _]) => logicalId !== 'CDKMetadata');\n\n // Split the changes into additions and non-additions. Imports only make sense\n // for newly-added resources.\n const nonAdditions = resourceChanges.filter(([_, dif]) => !dif.isAddition);\n const additions = resourceChanges.filter(([_, dif]) => dif.isAddition);\n\n if (nonAdditions.length) {\n const offendingResources = nonAdditions.map(([logId, _]) => this.describeResource(logId));\n\n if (allowNonAdditions) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_WARN.msg(`Ignoring updated/deleted resources (--force): ${offendingResources.join(', ')}`));\n } else {\n throw new ToolkitError('No resource updates or deletes are allowed on import operation. Make sure to resolve pending changes ' +\n `to existing resources, before attempting an import. Updated/deleted resources: ${offendingResources.join(', ')} (--force to override)`);\n }\n }\n\n // Resources in the new template, that are not present in the current template, are a potential import candidates\n return {\n additions: additions.map(([logicalId, resourceDiff]) => ({\n logicalId,\n resourceDiff,\n resourceDefinition: addDefaultDeletionPolicy(this.stack.template?.Resources?.[logicalId] ?? {}),\n })),\n hasNonAdditions: nonAdditions.length > 0,\n };\n }\n\n /**\n * Resolves the environment of a stack.\n */\n public async resolveEnvironment(): Promise<cxapi.Environment> {\n return this.cfn.resolveEnvironment(this.stack);\n }\n\n /**\n * Get currently deployed template of the given stack (SINGLETON)\n *\n * @returns Currently deployed CloudFormation template\n */\n private async currentTemplate(): Promise<any> {\n if (!this._currentTemplate) {\n this._currentTemplate = await this.cfn.readCurrentTemplate(this.stack);\n }\n return this._currentTemplate;\n }\n\n /**\n * Return the current template, with the given resources added to it\n */\n private async currentTemplateWithAdditions(additions: ImportableResource[]): Promise<any> {\n const template = await this.currentTemplate();\n if (!template.Resources) {\n template.Resources = {};\n }\n\n for (const add of additions) {\n template.Resources[add.logicalId] = add.resourceDefinition;\n }\n\n return template;\n }\n\n /**\n * Get a list of import identifiers for all resource types used in the given\n * template that do support the import operation (SINGLETON)\n *\n * @returns a mapping from a resource type to a list of property names that together identify the resource for import\n */\n private async resourceIdentifiers(): Promise<ResourceIdentifiers> {\n const ret: ResourceIdentifiers = {};\n const resourceIdentifierSummaries = await this.cfn.resourceIdentifierSummaries(this.stack);\n for (const summary of resourceIdentifierSummaries) {\n if ('ResourceType' in summary && summary.ResourceType && 'ResourceIdentifiers' in summary && summary.ResourceIdentifiers) {\n ret[summary.ResourceType] = (summary.ResourceIdentifiers ?? [])?.map(x => x.split(','));\n }\n }\n return ret;\n }\n\n /**\n * Ask for the importable identifier for the given resource\n *\n * There may be more than one identifier under which a resource can be imported. The `import`\n * operation needs exactly one of them.\n *\n * - If we can get one from the template, we will use one.\n * - Otherwise, we will ask the user for one of them.\n */\n private async askForResourceIdentifier(\n resourceIdentifiers: ResourceIdentifiers,\n chg: ImportableResource,\n ): Promise<ResourceIdentifierProperties | undefined> {\n const resourceName = this.describeResource(chg.logicalId);\n\n // Skip resources that do not support importing\n const resourceType = chg.resourceDiff.newResourceType;\n if (resourceType === undefined || !(resourceType in resourceIdentifiers)) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_WARN.msg(`${resourceName}: unsupported resource type ${resourceType}, skipping import.`));\n return undefined;\n }\n\n const idPropSets = resourceIdentifiers[resourceType];\n\n // Retain only literal strings: strip potential CFN intrinsics\n const resourceProps = Object.fromEntries(Object.entries(chg.resourceDefinition.Properties ?? {})\n .filter(([_, v]) => typeof v === 'string')) as Record<string, string>;\n\n // Find property sets that are fully satisfied in the template, ask the user to confirm them\n const satisfiedPropSets = idPropSets.filter(ps => ps.every(p => resourceProps[p]));\n for (const satisfiedPropSet of satisfiedPropSets) {\n const candidateProps = Object.fromEntries(satisfiedPropSet.map(p => [p, resourceProps[p]]));\n const displayCandidateProps = fmtdict(candidateProps);\n\n if (await promptly.confirm(\n `${chalk.blue(resourceName)} (${resourceType}): import with ${chalk.yellow(displayCandidateProps)} (yes/no) [default: yes]? `,\n { default: 'yes' },\n )) {\n return candidateProps;\n }\n }\n\n // If we got here and the user rejected any available identifiers, then apparently they don't want the resource at all\n if (satisfiedPropSets.length > 0) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(chalk.grey(`Skipping import of ${resourceName}`)));\n return undefined;\n }\n\n // We cannot auto-import this, ask the user for one of the props\n // The only difference between these cases is what we print: for multiple properties, we print a preamble\n const prefix = `${chalk.blue(resourceName)} (${resourceType})`;\n let preamble;\n let promptPattern;\n if (idPropSets.length > 1) {\n preamble = `${prefix}: enter one of ${idPropSets.map(x => chalk.blue(x.join('+'))).join(', ')} to import (all empty to skip)`;\n promptPattern = `${prefix}: enter %`;\n } else {\n promptPattern = `${prefix}: enter %`;\n }\n\n // Do the input loop here\n if (preamble) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(preamble));\n }\n for (const idProps of idPropSets) {\n const input: Record<string, string> = {};\n for (const idProp of idProps) {\n // If we have a value from the template, use it as default. This will only be a partial\n // identifier if present, otherwise we would have done the import already above.\n const defaultValue = resourceProps[idProp] ?? '';\n\n const prompt = [\n promptPattern.replace(/%/g, chalk.blue(idProp)),\n defaultValue\n ? `[${defaultValue}]`\n : '(empty to skip)',\n ].join(' ') + ':';\n const response = await promptly.prompt(prompt,\n { default: defaultValue, trim: true },\n );\n\n if (!response) {\n break;\n }\n\n input[idProp] = response;\n // Also stick this property into 'resourceProps', so that it may be reused by a subsequent question\n // (for a different compound identifier that involves the same property). Just a small UX enhancement.\n resourceProps[idProp] = response;\n }\n\n // If the user gave inputs for all values, we are complete\n if (Object.keys(input).length === idProps.length) {\n return input;\n }\n }\n\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(chalk.grey(`Skipping import of ${resourceName}`)));\n return undefined;\n }\n\n /**\n * Convert the internal \"resource mapping\" structure to CloudFormation accepted \"ResourcesToImport\" structure\n */\n private async makeResourcesToImport(resourceMap: ImportMap): Promise<ResourcesToImport> {\n return resourceMap.importResources.map(res => ({\n LogicalResourceId: res.logicalId,\n ResourceType: res.resourceDiff.newResourceType!,\n ResourceIdentifier: resourceMap.resourceMap[res.logicalId],\n }));\n }\n\n /**\n * Convert CloudFormation logical resource ID to CDK construct tree path\n *\n * @param logicalId CloudFormation logical ID of the resource (the key in the template's Resources section)\n * @returns Forward-slash separated path of the resource in CDK construct tree, e.g. MyStack/MyBucket/Resource\n */\n private describeResource(logicalId: string): string {\n return this.stack.template?.Resources?.[logicalId]?.Metadata?.['aws:cdk:path'] ?? logicalId;\n }\n\n /**\n * Removes CDKMetadata and Outputs in the template so that only resources for importing are left.\n * @returns template with import resources only\n */\n private removeNonImportResources() {\n return removeNonImportResources(this.stack);\n }\n}\n\n/**\n * Information about a resource in the template that is importable\n */\nexport interface ImportableResource {\n /**\n * The logical ID of the resource\n */\n readonly logicalId: string;\n\n /**\n * The resource definition in the new template\n */\n readonly resourceDefinition: any;\n\n /**\n * The diff as reported by `cloudformation-diff`.\n */\n readonly resourceDiff: ResourceDifference;\n}\n\n/**\n * The information necessary to execute an import operation\n */\nexport interface ImportMap {\n /**\n * Mapping logical IDs to physical names\n */\n readonly resourceMap: ResourceMap;\n\n /**\n * The selection of resources we are actually importing\n *\n * For each of the resources in this list, there is a corresponding entry in\n * the `resourceMap` map.\n */\n readonly importResources: ImportableResource[];\n}\n\nfunction fmtdict<A>(xs: Record<string, A>) {\n return Object.entries(xs).map(([k, v]) => `${k}=${v}`).join(', ');\n}\n\n/**\n * Add a default `DeletionPolicy` policy.\n * The default value is set to 'Retain', to lower risk of unintentionally\n * deleting stateful resources in the process of importing to CDK.\n */\nfunction addDefaultDeletionPolicy(resource: any): any {\n if (resource.DeletionPolicy) {\n return resource;\n }\n\n return {\n ...resource,\n DeletionPolicy: 'Retain',\n };\n}\n\nexport interface DiscoverImportableResourcesResult {\n readonly additions: ImportableResource[];\n readonly hasNonAdditions: boolean;\n}\n\nexport function removeNonImportResources(stack:cxapi.CloudFormationStackArtifact) {\n const template = stack.template;\n delete template.Resources.CDKMetadata;\n delete template.Outputs;\n return template;\n}\n", "import type * as cxapi from '@aws-cdk/cx-api';\nimport * as chalk from 'chalk';\nimport * as fs from 'fs-extra';\nimport type { ImportDeploymentOptions, ResourcesToImport } from './importer';\nimport { ResourceImporter } from './importer';\nimport { formatTime } from '../../util';\nimport type { StackCollection } from '../cloud-assembly';\nimport type { Deployments } from '../deployments';\nimport { IO, type IoHelper } from '../io/private';\n\nexport interface ResourceMigratorProps {\n deployments: Deployments;\n ioHelper: IoHelper;\n}\n\nexport class ResourceMigrator {\n private readonly props: ResourceMigratorProps;\n private readonly ioHelper: IoHelper;\n\n public constructor(props: ResourceMigratorProps) {\n this.props = props;\n this.ioHelper = props.ioHelper;\n }\n\n /**\n * Checks to see if a migrate.json file exists. If it does and the source is either `filepath` or\n * is in the same environment as the stack deployment, a new stack is created and the resources are\n * migrated to the stack using an IMPORT changeset. The normal deployment will resume after this is complete\n * to add back in any outputs and the CDKMetadata.\n */\n public async tryMigrateResources(stacks: StackCollection, options: ImportDeploymentOptions): Promise<void> {\n const stack = stacks.stackArtifacts[0];\n const migrateDeployment = new ResourceImporter(stack, {\n deployments: this.props.deployments,\n ioHelper: this.ioHelper,\n });\n const resourcesToImport = await this.tryGetResources(await migrateDeployment.resolveEnvironment());\n\n if (resourcesToImport) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(`${chalk.bold(stack.displayName)}: creating stack for resource migration...`));\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(`${chalk.bold(stack.displayName)}: importing resources into stack...`));\n\n await this.performResourceMigration(migrateDeployment, resourcesToImport, options);\n\n fs.rmSync('migrate.json');\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(`${chalk.bold(stack.displayName)}: applying CDKMetadata and Outputs to stack (if applicable)...`));\n }\n }\n\n /**\n * Creates a new stack with just the resources to be migrated\n */\n private async performResourceMigration(\n migrateDeployment: ResourceImporter,\n resourcesToImport: ResourcesToImport,\n options: ImportDeploymentOptions,\n ) {\n const startDeployTime = new Date().getTime();\n let elapsedDeployTime = 0;\n\n // Initial Deployment\n await migrateDeployment.importResourcesFromMigrate(resourcesToImport, {\n roleArn: options.roleArn,\n deploymentMethod: options.deploymentMethod,\n usePreviousParameters: true,\n rollback: options.rollback,\n });\n\n elapsedDeployTime = new Date().getTime() - startDeployTime;\n await this.ioHelper.notify(IO.CDK_TOOLKIT_I5002.msg(`'\\n\u2728 Resource migration time: ${formatTime(elapsedDeployTime)}s\\n'`, {\n duration: elapsedDeployTime,\n }));\n }\n\n public async tryGetResources(environment: cxapi.Environment): Promise<ResourcesToImport | undefined> {\n try {\n const migrateFile = fs.readJsonSync('migrate.json', {\n encoding: 'utf-8',\n });\n const sourceEnv = (migrateFile.Source as string).split(':');\n if (\n sourceEnv[0] === 'localfile' ||\n (sourceEnv[4] === environment.account && sourceEnv[3] === environment.region)\n ) {\n return migrateFile.Resources;\n }\n } catch (e) {\n // Nothing to do\n }\n\n return undefined;\n }\n}\n\n", "import { promises as fs } from 'fs';\nimport * as path from 'path';\nimport { ToolkitError } from './toolkit-error';\n\n/**\n * A single-writer/multi-reader lock on a directory\n *\n * It uses marker files with PIDs in them as a locking marker; the PIDs will be\n * checked for liveness, so that if the process exits without cleaning up the\n * files the lock is implicitly released.\n *\n * This class is not 100% race safe, but in practice it should be a lot\n * better than the 0 protection we have today.\n */\n/* c8 ignore start */ // code paths are unpredictable\nexport class RWLock {\n private readonly pidString: string;\n private readonly writerFile: string;\n private readCounter = 0;\n\n constructor(public readonly directory: string) {\n this.pidString = `${process.pid}`;\n\n this.writerFile = path.join(this.directory, 'synth.lock');\n }\n\n /**\n * Acquire a writer lock.\n *\n * No other readers or writers must exist for the given directory.\n */\n public async acquireWrite(): Promise<IWriterLock> {\n await this.assertNoOtherWriters();\n\n const readers = await this.currentReaders();\n if (readers.length > 0) {\n throw new ToolkitError(`Other CLIs (PID=${readers}) are currently reading from ${this.directory}. Invoke the CLI in sequence, or use '--output' to synth into different directories.`);\n }\n\n await writeFileAtomic(this.writerFile, this.pidString);\n\n return {\n release: async () => {\n await deleteFile(this.writerFile);\n },\n convertToReaderLock: async () => {\n // Acquire the read lock before releasing the write lock. Slightly less\n // chance of racing!\n const ret = await this.doAcquireRead();\n await deleteFile(this.writerFile);\n return ret;\n },\n };\n }\n\n /**\n * Acquire a read lock\n *\n * Will fail if there are any writers.\n */\n public async acquireRead(): Promise<ILock> {\n await this.assertNoOtherWriters();\n return this.doAcquireRead();\n }\n\n /**\n * Obtains the name fo a (new) `readerFile` to use. This includes a counter so\n * that if multiple threads of the same PID attempt to concurrently acquire\n * the same lock, they're guaranteed to use a different reader file name (only\n * one thread will ever execute JS code at once, guaranteeing the readCounter\n * is incremented \"atomically\" from the point of view of this PID.).\n */\n private readerFile(): string {\n return path.join(this.directory, `read.${this.pidString}.${++this.readCounter}.lock`);\n }\n\n /**\n * Do the actual acquiring of a read lock.\n */\n private async doAcquireRead(): Promise<ILock> {\n const readerFile = this.readerFile();\n await writeFileAtomic(readerFile, this.pidString);\n return {\n release: async () => {\n await deleteFile(readerFile);\n },\n };\n }\n\n private async assertNoOtherWriters() {\n const writer = await this.currentWriter();\n if (writer) {\n throw new ToolkitError(`Another CLI (PID=${writer}) is currently synthing to ${this.directory}. Invoke the CLI in sequence, or use '--output' to synth into different directories.`);\n }\n }\n\n /**\n * Check the current writer (if any)\n */\n private async currentWriter(): Promise<number | undefined> {\n const contents = await readFileIfExists(this.writerFile);\n if (!contents) {\n return undefined;\n }\n\n const pid = parseInt(contents, 10);\n if (!processExists(pid)) {\n // Do cleanup of a stray file now\n await deleteFile(this.writerFile);\n return undefined;\n }\n\n return pid;\n }\n\n /**\n * Check the current readers (if any)\n */\n private async currentReaders(): Promise<number[]> {\n const re = /^read\\.([^.]+)\\.[^.]+\\.lock$/;\n const ret = new Array<number>();\n\n let children;\n try {\n children = await fs.readdir(this.directory, { encoding: 'utf-8' });\n } catch (e: any) {\n // Can't be locked if the directory doesn't exist\n if (e.code === 'ENOENT') {\n return [];\n }\n throw e;\n }\n\n for (const fname of children) {\n const m = fname.match(re);\n if (m) {\n const pid = parseInt(m[1], 10);\n if (processExists(pid)) {\n ret.push(pid);\n } else {\n // Do cleanup of a stray file now\n await deleteFile(path.join(this.directory, fname));\n }\n }\n }\n return ret;\n }\n}\n/* c8 ignore stop */\n\n/**\n * An acquired lock\n */\nexport interface ILock {\n release(): Promise<void>;\n}\n\n/**\n * An acquired writer lock\n */\nexport interface IWriterLock extends ILock {\n /**\n * Convert the writer lock to a reader lock\n */\n convertToReaderLock(): Promise<ILock>;\n}\n\n/* c8 ignore start */ // code paths are unpredictable\nasync function readFileIfExists(filename: string): Promise<string | undefined> {\n try {\n return await fs.readFile(filename, { encoding: 'utf-8' });\n } catch (e: any) {\n if (e.code === 'ENOENT') {\n return undefined;\n }\n throw e;\n }\n}\n/* c8 ignore stop */\n\nlet tmpCounter = 0;\n/* c8 ignore start */ // code paths are unpredictable\nasync function writeFileAtomic(filename: string, contents: string): Promise<void> {\n await fs.mkdir(path.dirname(filename), { recursive: true });\n const tmpFile = `${filename}.${process.pid}_${++tmpCounter}`;\n await fs.writeFile(tmpFile, contents, { encoding: 'utf-8' });\n await fs.rename(tmpFile, filename);\n}\n/* c8 ignore stop */\n\n/* c8 ignore start */ // code paths are unpredictable\nasync function deleteFile(filename: string) {\n try {\n await fs.unlink(filename);\n } catch (e: any) {\n if (e.code === 'ENOENT') {\n return;\n }\n throw e;\n }\n}\n/* c8 ignore stop */\n\n/* c8 ignore start */ // code paths are unpredictable\nfunction processExists(pid: number) {\n try {\n process.kill(pid, 0);\n return true;\n } catch (e) {\n return false;\n }\n}\n/* c8 ignore stop */\n", "import type * as cxapi from '@aws-cdk/cx-api';\nimport type { AssetManifest, IManifestEntry } from 'cdk-assets';\n\nexport enum DeploymentState {\n PENDING = 'pending',\n QUEUED = 'queued',\n DEPLOYING = 'deploying',\n COMPLETED = 'completed',\n FAILED = 'failed',\n SKIPPED = 'skipped',\n}\n\nexport type WorkNode = StackNode | AssetBuildNode | AssetPublishNode;\n\nexport interface WorkNodeCommon {\n readonly id: string;\n readonly dependencies: Set<string>;\n deploymentState: DeploymentState;\n /** Some readable information to attach to the id, which may be unreadable */\n readonly note?: string;\n}\n\nexport interface StackNode extends WorkNodeCommon {\n readonly type: 'stack';\n readonly stack: cxapi.CloudFormationStackArtifact;\n /** Sort by priority when picking up work, higher is earlier */\n readonly priority?: number;\n}\n\nexport interface AssetBuildNode extends WorkNodeCommon {\n readonly type: 'asset-build';\n /** The asset manifest this asset resides in (artifact) */\n readonly assetManifestArtifact: cxapi.AssetManifestArtifact;\n /** The asset manifest this asset resides in */\n readonly assetManifest: AssetManifest;\n /** The stack this asset was defined in (used for environment settings) */\n readonly parentStack: cxapi.CloudFormationStackArtifact;\n /** The asset that needs to be built */\n readonly asset: IManifestEntry;\n /** Sort by priority when picking up work, higher is earlier */\n readonly priority?: number;\n}\n\nexport interface AssetPublishNode extends WorkNodeCommon {\n readonly type: 'asset-publish';\n /** The asset manifest this asset resides in (artifact) */\n readonly assetManifestArtifact: cxapi.AssetManifestArtifact;\n /** The asset manifest this asset resides in */\n readonly assetManifest: AssetManifest;\n /** The stack this asset was defined in (used for environment settings) */\n readonly parentStack: cxapi.CloudFormationStackArtifact;\n /** The asset that needs to be published */\n readonly asset: IManifestEntry;\n /** Sort by priority when picking up work, higher is earlier */\n readonly priority?: number;\n}\n", "import type { WorkNode, StackNode, AssetBuildNode, AssetPublishNode } from './work-graph-types';\nimport { DeploymentState } from './work-graph-types';\nimport { parallelPromises } from '../../util';\nimport { IO, type IoHelper } from '../io/private';\nimport { ToolkitError } from '../toolkit-error';\nexport type Concurrency = number | Record<WorkNode['type'], number>;\n\nexport class WorkGraph {\n public readonly nodes: Record<string, WorkNode>;\n private readonly readyPool: Array<WorkNode> = [];\n private readonly lazyDependencies = new Map<string, string[]>();\n private readonly ioHelper: IoHelper;\n\n public error?: Error;\n\n public constructor(nodes: Record<string, WorkNode>, ioHelper: IoHelper) {\n this.nodes = { ...nodes };\n this.ioHelper = ioHelper;\n }\n\n public addNodes(...nodes: WorkNode[]) {\n for (const node of nodes) {\n if (this.nodes[node.id]) {\n throw new ToolkitError(`Duplicate use of node id: ${node.id}`);\n }\n\n const ld = this.lazyDependencies.get(node.id);\n if (ld) {\n for (const x of ld) {\n node.dependencies.add(x);\n }\n this.lazyDependencies.delete(node.id);\n }\n\n this.nodes[node.id] = node;\n }\n }\n\n public removeNode(nodeId: string | WorkNode) {\n const id = typeof nodeId === 'string' ? nodeId : nodeId.id;\n const removedNode = this.nodes[id];\n\n this.lazyDependencies.delete(id);\n delete this.nodes[id];\n\n if (removedNode) {\n for (const node of Object.values(this.nodes)) {\n node.dependencies.delete(removedNode.id);\n }\n }\n }\n\n /**\n * Return all nodes of a given type\n */\n public nodesOfType<T extends WorkNode['type']>(type: T): Extract<WorkNode, { type: T }>[] {\n return Object.values(this.nodes).filter(n => n.type === type) as any;\n }\n\n /**\n * Return all nodes that depend on a given node\n */\n public dependees(nodeId: string | WorkNode) {\n const id = typeof nodeId === 'string' ? nodeId : nodeId.id;\n return Object.values(this.nodes).filter(n => n.dependencies.has(id));\n }\n\n /**\n * Add a dependency, that may come before or after the nodes involved\n */\n public addDependency(fromId: string, toId: string) {\n const node = this.nodes[fromId];\n if (node) {\n node.dependencies.add(toId);\n return;\n }\n let lazyDeps = this.lazyDependencies.get(fromId);\n if (!lazyDeps) {\n lazyDeps = [];\n this.lazyDependencies.set(fromId, lazyDeps);\n }\n lazyDeps.push(toId);\n }\n\n public tryGetNode(id: string): WorkNode | undefined {\n return this.nodes[id];\n }\n\n public node(id: string) {\n const ret = this.nodes[id];\n if (!ret) {\n throw new ToolkitError(`No node with id ${id} among ${Object.keys(this.nodes)}`);\n }\n return ret;\n }\n\n public absorb(graph: WorkGraph) {\n this.addNodes(...Object.values(graph.nodes));\n }\n\n private hasFailed(): boolean {\n return Object.values(this.nodes).some((n) => n.deploymentState === DeploymentState.FAILED);\n }\n\n public doParallel(concurrency: Concurrency, actions: WorkGraphActions) {\n return this.forAllArtifacts(concurrency, async (x: WorkNode) => {\n switch (x.type) {\n case 'stack':\n await actions.deployStack(x);\n break;\n case 'asset-build':\n await actions.buildAsset(x);\n break;\n case 'asset-publish':\n await actions.publishAsset(x);\n break;\n }\n });\n }\n\n /**\n * Return the set of unblocked nodes\n */\n public async ready(): Promise<ReadonlyArray<WorkNode>> {\n await this.updateReadyPool();\n return this.readyPool;\n }\n\n private forAllArtifacts(n: Concurrency, fn: (x: WorkNode) => Promise<void>): Promise<void> {\n const graph = this;\n\n // If 'n' is a number, we limit all concurrency equally (effectively we will be using totalMax)\n // If 'n' is a record, we limit each job independently (effectively we will be using max)\n const max: Record<WorkNode['type'], number> = typeof n === 'number' ?\n {\n 'asset-build': n,\n 'asset-publish': n,\n 'stack': n,\n } : n;\n const totalMax = typeof n === 'number' ? n : sum(Object.values(n));\n\n return new Promise((ok, fail) => {\n let active: Record<WorkNode['type'], number> = {\n 'asset-build': 0,\n 'asset-publish': 0,\n 'stack': 0,\n };\n function totalActive() {\n return sum(Object.values(active));\n }\n\n start();\n\n function start() {\n graph.updateReadyPool().then(() => {\n for (let i = 0; i < graph.readyPool.length; ) {\n const node = graph.readyPool[i];\n\n if (active[node.type] < max[node.type] && totalActive() < totalMax) {\n graph.readyPool.splice(i, 1);\n startOne(node);\n } else {\n i += 1;\n }\n }\n\n if (totalActive() === 0) {\n if (graph.done()) {\n ok();\n }\n // wait for other active deploys to finish before failing\n if (graph.hasFailed()) {\n fail(graph.error);\n }\n }\n }).catch((e) => {\n fail(e);\n });\n }\n\n function startOne(x: WorkNode) {\n x.deploymentState = DeploymentState.DEPLOYING;\n active[x.type]++;\n void fn(x)\n .finally(() => {\n active[x.type]--;\n })\n .then(() => {\n graph.deployed(x);\n start();\n }).catch((err) => {\n // By recording the failure immediately as the queued task exits, we prevent the next\n // queued task from starting.\n graph.failed(x, err);\n start();\n });\n }\n });\n }\n\n private done(): boolean {\n return Object.values(this.nodes).every((n) => DeploymentState.COMPLETED === n.deploymentState);\n }\n\n private deployed(node: WorkNode) {\n node.deploymentState = DeploymentState.COMPLETED;\n }\n\n private failed(node: WorkNode, error?: Error) {\n this.error = error;\n node.deploymentState = DeploymentState.FAILED;\n this.skipRest();\n this.readyPool.splice(0);\n }\n\n public toString() {\n return [\n 'digraph D {',\n ...Object.entries(this.nodes).flatMap(([id, node]) => renderNode(id, node)),\n '}',\n ].join('\\n');\n\n function renderNode(id: string, node: WorkNode): string[] {\n const ret = [];\n if (node.deploymentState === DeploymentState.COMPLETED) {\n ret.push(` ${gv(id, { style: 'filled', fillcolor: 'yellow', comment: node.note })};`);\n } else {\n ret.push(` ${gv(id, { comment: node.note })};`);\n }\n for (const dep of node.dependencies) {\n ret.push(` ${gv(id)} -> ${gv(dep)};`);\n }\n return ret;\n }\n }\n\n /**\n * Ensure all dependencies actually exist. This protects against scenarios such as the following:\n * StackA depends on StackB, but StackB is not selected to deploy. The dependency is redundant\n * and will be dropped.\n * This assumes the manifest comes uncorrupted so we will not fail if a dependency is not found.\n */\n public removeUnavailableDependencies() {\n for (const node of Object.values(this.nodes)) {\n const removeDeps = Array.from(node.dependencies).filter((dep) => this.nodes[dep] === undefined);\n\n removeDeps.forEach((d) => {\n node.dependencies.delete(d);\n });\n }\n }\n\n /**\n * Remove all asset publishing steps for assets that are already published, and then build\n * that aren't used anymore.\n *\n * Do this in parallel, because there may be a lot of assets in an application (seen in practice: >100 assets)\n */\n public async removeUnnecessaryAssets(isUnnecessary: (x: AssetPublishNode) => Promise<boolean>) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg('Checking for previously published assets'));\n\n const publishes = this.nodesOfType('asset-publish');\n\n const classifiedNodes = await parallelPromises(\n 8,\n publishes.map((assetNode) => async() => [assetNode, await isUnnecessary(assetNode)] as const));\n\n const alreadyPublished = classifiedNodes.filter(([_, unnecessary]) => unnecessary).map(([assetNode, _]) => assetNode);\n for (const assetNode of alreadyPublished) {\n this.removeNode(assetNode);\n }\n\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${publishes.length} total assets, ${publishes.length - alreadyPublished.length} still need to be published`));\n\n // Now also remove any asset build steps that don't have any dependencies on them anymore\n const unusedBuilds = this.nodesOfType('asset-build').filter(build => this.dependees(build).length === 0);\n for (const unusedBuild of unusedBuilds) {\n this.removeNode(unusedBuild);\n }\n }\n\n private async updateReadyPool() {\n const activeCount = Object.values(this.nodes).filter((x) => x.deploymentState === DeploymentState.DEPLOYING).length;\n const pendingCount = Object.values(this.nodes).filter((x) => x.deploymentState === DeploymentState.PENDING).length;\n\n const newlyReady = Object.values(this.nodes).filter((x) =>\n x.deploymentState === DeploymentState.PENDING &&\n Array.from(x.dependencies).every((id) => this.node(id).deploymentState === DeploymentState.COMPLETED));\n\n // Add newly available nodes to the ready pool\n for (const node of newlyReady) {\n node.deploymentState = DeploymentState.QUEUED;\n this.readyPool.push(node);\n }\n\n // Remove nodes from the ready pool that have already started deploying\n retainOnly(this.readyPool, (node) => node.deploymentState === DeploymentState.QUEUED);\n\n // Sort by reverse priority\n this.readyPool.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));\n\n if (this.readyPool.length === 0 && activeCount === 0 && pendingCount > 0) {\n const cycle = this.findCycle() ?? ['No cycle found!'];\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_TRACE.msg(`Cycle ${cycle.join(' -> ')} in graph ${this}`));\n throw new ToolkitError(`Unable to make progress anymore, dependency cycle between remaining artifacts: ${cycle.join(' -> ')} (run with -vv for full graph)`);\n }\n }\n\n private skipRest() {\n for (const node of Object.values(this.nodes)) {\n if ([DeploymentState.QUEUED, DeploymentState.PENDING].includes(node.deploymentState)) {\n node.deploymentState = DeploymentState.SKIPPED;\n }\n }\n }\n\n /**\n * Find cycles in a graph\n *\n * Not the fastest, but effective and should be rare\n */\n public findCycle(): string[] | undefined {\n const seen = new Set<string>();\n const self = this;\n for (const nodeId of Object.keys(this.nodes)) {\n const cycle = recurse(nodeId, [nodeId]);\n if (cycle) {\n return cycle;\n }\n }\n return undefined;\n\n function recurse(nodeId: string, path: string[]): string[] | undefined {\n if (seen.has(nodeId)) {\n return undefined;\n }\n try {\n for (const dep of self.nodes[nodeId].dependencies ?? []) {\n const index = path.indexOf(dep);\n if (index > -1) {\n return [...path.slice(index), dep];\n }\n\n const cycle = recurse(dep, [...path, dep]);\n if (cycle) {\n return cycle;\n }\n }\n\n return undefined;\n } finally {\n seen.add(nodeId);\n }\n }\n }\n\n /**\n * Whether the `end` node is reachable from the `start` node, following the dependency arrows\n */\n public reachable(start: string, end: string): boolean {\n const seen = new Set<string>();\n const self = this;\n return recurse(start);\n\n function recurse(current: string) {\n if (seen.has(current)) {\n return false;\n }\n seen.add(current);\n\n if (current === end) {\n return true;\n }\n for (const dep of self.nodes[current].dependencies) {\n if (recurse(dep)) {\n return true;\n }\n }\n return false;\n }\n }\n}\n\nexport interface WorkGraphActions {\n deployStack: (stackNode: StackNode) => Promise<void>;\n buildAsset: (assetNode: AssetBuildNode) => Promise<void>;\n publishAsset: (assetNode: AssetPublishNode) => Promise<void>;\n}\n\nfunction sum(xs: number[]) {\n let ret = 0;\n for (const x of xs) {\n ret += x;\n }\n return ret;\n}\n\nfunction retainOnly<A>(xs: A[], pred: (x: A) => boolean) {\n xs.splice(0, xs.length, ...xs.filter(pred));\n}\n\nfunction gv(id: string, attrs?: Record<string, string | undefined>) {\n const attrString = Object.entries(attrs ?? {}).flatMap(([k, v]) => v !== undefined ? [`${k}=\"${v}\"`] : []).join(',');\n\n return attrString ? `\"${simplifyId(id)}\" [${attrString}]` : `\"${simplifyId(id)}\"`;\n}\n\nfunction simplifyId(id: string) {\n return id.replace(/([0-9a-f]{6})[0-9a-f]{6,}/g, '$1');\n}\n", "import * as cxapi from '@aws-cdk/cx-api';\nimport { AssetManifest, type IManifestEntry } from 'cdk-assets';\nimport { WorkGraph } from './work-graph';\nimport type { AssetBuildNode, WorkNode } from './work-graph-types';\nimport { DeploymentState } from './work-graph-types';\nimport { contentHashAny } from '../../util';\nimport type { IoHelper } from '../io/private';\nimport { ToolkitError } from '../toolkit-error';\n\nexport class WorkGraphBuilder {\n /**\n * Default priorities for nodes\n *\n * Assets builds have higher priority than the other two operations, to make good on our promise that\n * '--prebuild-assets' will actually do assets before stacks (if it can). Unfortunately it is the\n * default :(\n *\n * But between stack dependencies and publish dependencies, stack dependencies go first\n */\n public static PRIORITIES: Record<WorkNode['type'], number> = {\n 'asset-build': 10,\n 'asset-publish': 0,\n 'stack': 5,\n };\n private readonly graph: WorkGraph;\n private readonly ioHelper: IoHelper;\n\n constructor(\n ioHelper: IoHelper,\n private readonly prebuildAssets: boolean,\n private readonly idPrefix = '',\n ) {\n this.graph = new WorkGraph({}, ioHelper);\n this.ioHelper = ioHelper;\n }\n\n private addStack(artifact: cxapi.CloudFormationStackArtifact) {\n this.graph.addNodes({\n type: 'stack',\n id: `${this.idPrefix}${artifact.id}`,\n dependencies: new Set(this.stackArtifactIds(onlyStacks(artifact.dependencies))),\n stack: artifact,\n deploymentState: DeploymentState.PENDING,\n priority: WorkGraphBuilder.PRIORITIES.stack,\n });\n }\n\n /**\n * Oof, see this parameter list\n */\n // eslint-disable-next-line max-len\n private addAsset(parentStack: cxapi.CloudFormationStackArtifact, assetManifestArtifact: cxapi.AssetManifestArtifact, assetManifest: AssetManifest, asset: IManifestEntry) {\n // Just the artifact identifier\n const assetId = asset.id.assetId;\n\n const buildId = `build-${assetId}-${contentHashAny([assetId, asset.genericSource]).substring(0, 10)}`;\n const publishId = `publish-${assetId}-${contentHashAny([assetId, asset.genericDestination]).substring(0, 10)}`;\n\n // Build node only gets added once because they are all the same\n if (!this.graph.tryGetNode(buildId)) {\n const node: AssetBuildNode = {\n type: 'asset-build',\n id: buildId,\n note: asset.displayName(false),\n dependencies: new Set([\n ...this.stackArtifactIds(assetManifestArtifact.dependencies),\n // If we disable prebuild, then assets inherit (stack) dependencies from their parent stack\n ...!this.prebuildAssets ? this.stackArtifactIds(onlyStacks(parentStack.dependencies)) : [],\n ]),\n parentStack: parentStack,\n assetManifestArtifact,\n assetManifest,\n asset,\n deploymentState: DeploymentState.PENDING,\n priority: WorkGraphBuilder.PRIORITIES['asset-build'],\n };\n this.graph.addNodes(node);\n }\n\n const publishNode = this.graph.tryGetNode(publishId);\n if (!publishNode) {\n this.graph.addNodes({\n type: 'asset-publish',\n id: publishId,\n note: asset.displayName(true),\n dependencies: new Set([\n buildId,\n ]),\n parentStack,\n assetManifestArtifact,\n assetManifest,\n asset,\n deploymentState: DeploymentState.PENDING,\n priority: WorkGraphBuilder.PRIORITIES['asset-publish'],\n });\n }\n\n for (const inheritedDep of this.stackArtifactIds(onlyStacks(parentStack.dependencies))) {\n // The asset publish step also depends on the stacks that the parent depends on.\n // This is purely cosmetic: if we don't do this, the progress printing of asset publishing\n // is going to interfere with the progress bar of the stack deployment. We could remove this\n // for overall faster deployments if we ever have a better method of progress displaying.\n // Note: this may introduce a cycle if one of the parent's dependencies is another stack that\n // depends on this asset. To workaround this we remove these cycles once all nodes have\n // been added to the graph.\n this.graph.addDependency(publishId, inheritedDep);\n }\n\n // This will work whether the stack node has been added yet or not\n this.graph.addDependency(`${this.idPrefix}${parentStack.id}`, publishId);\n }\n\n public build(artifacts: cxapi.CloudArtifact[]): WorkGraph {\n const parentStacks = stacksFromAssets(artifacts);\n\n for (const artifact of artifacts) {\n if (cxapi.CloudFormationStackArtifact.isCloudFormationStackArtifact(artifact)) {\n this.addStack(artifact);\n } else if (cxapi.AssetManifestArtifact.isAssetManifestArtifact(artifact)) {\n const manifest = AssetManifest.fromFile(artifact.file);\n\n for (const entry of manifest.entries) {\n const parentStack = parentStacks.get(artifact);\n if (parentStack === undefined) {\n throw new ToolkitError('Found an asset manifest that is not associated with a stack');\n }\n this.addAsset(parentStack, artifact, manifest, entry);\n }\n } else if (cxapi.NestedCloudAssemblyArtifact.isNestedCloudAssemblyArtifact(artifact)) {\n const assembly = new cxapi.CloudAssembly(artifact.fullPath, { topoSort: false });\n const nestedGraph = new WorkGraphBuilder(\n this.ioHelper,\n this.prebuildAssets,\n `${this.idPrefix}${artifact.id}.`,\n ).build(assembly.artifacts);\n this.graph.absorb(nestedGraph);\n } else {\n // Ignore whatever else\n }\n }\n\n this.graph.removeUnavailableDependencies();\n\n // Remove any potentially introduced cycles between asset publishing and the stacks that depend on them.\n this.removeStackPublishCycles();\n\n return this.graph;\n }\n\n private stackArtifactIds(deps: cxapi.CloudArtifact[]): string[] {\n return deps.flatMap((d) => cxapi.CloudFormationStackArtifact.isCloudFormationStackArtifact(d) ? [this.stackArtifactId(d)] : []);\n }\n\n private stackArtifactId(artifact: cxapi.CloudArtifact): string {\n if (!cxapi.CloudFormationStackArtifact.isCloudFormationStackArtifact(artifact)) {\n throw new ToolkitError(`Can only call this on CloudFormationStackArtifact, got: ${artifact.constructor.name}`);\n }\n return `${this.idPrefix}${artifact.id}`;\n }\n\n /**\n * We may have accidentally introduced cycles in an attempt to make the messages printed to the\n * console not interfere with each other too much. Remove them again.\n */\n private removeStackPublishCycles() {\n const publishSteps = this.graph.nodesOfType('asset-publish');\n for (const publishStep of publishSteps) {\n for (const dep of publishStep.dependencies) {\n if (this.graph.reachable(dep, publishStep.id)) {\n publishStep.dependencies.delete(dep);\n }\n }\n }\n }\n}\n\nfunction stacksFromAssets(artifacts: cxapi.CloudArtifact[]) {\n const ret = new Map<cxapi.AssetManifestArtifact, cxapi.CloudFormationStackArtifact>();\n for (const stack of artifacts.filter(x => cxapi.CloudFormationStackArtifact.isCloudFormationStackArtifact(x))) {\n const assetArtifacts = stack.dependencies.filter((x) => cxapi.AssetManifestArtifact.isAssetManifestArtifact(x));\n for (const art of assetArtifacts) {\n ret.set(art, stack);\n }\n }\n\n return ret;\n}\n\nfunction onlyStacks(artifacts: cxapi.CloudArtifact[]) {\n return artifacts.filter(x => cxapi.CloudFormationStackArtifact.isCloudFormationStackArtifact(x));\n}\n", "import type * as cxapi from '@aws-cdk/cx-api';\n\n/**\n * @returns an array with the tags available in the stack metadata.\n */\nexport function tagsForStack(stack: cxapi.CloudFormationStackArtifact): Tag[] {\n return Object.entries(stack.tags).map(([Key, Value]) => ({ Key, Value }));\n}\n\nexport interface Tag {\n readonly Key: string;\n readonly Value: string;\n}\n", "import * as cxschema from '@aws-cdk/cloud-assembly-schema';\nimport * as cxapi from '@aws-cdk/cx-api';\nimport { AmiContextProviderPlugin } from './ami';\nimport { AZContextProviderPlugin } from './availability-zones';\nimport { CcApiContextProviderPlugin } from './cc-api-provider';\nimport { EndpointServiceAZContextProviderPlugin } from './endpoint-service-availability-zones';\nimport { HostedZoneContextProviderPlugin } from './hosted-zones';\nimport { KeyContextProviderPlugin } from './keys';\nimport { LoadBalancerContextProviderPlugin, LoadBalancerListenerContextProviderPlugin } from './load-balancers';\nimport { SecurityGroupContextProviderPlugin } from './security-groups';\nimport { SSMContextProviderPlugin } from './ssm-parameters';\nimport { VpcNetworkContextProviderPlugin } from './vpcs';\nimport type { SdkProvider } from '../api/aws-auth';\nimport type { Context } from '../api/context';\nimport { TRANSIENT_CONTEXT_KEY } from '../api/context';\nimport { replaceEnvPlaceholders } from '../api/environment';\nimport { IO } from '../api/io/private';\nimport type { IoHelper } from '../api/io/private';\nimport { PluginHost } from '../api/plugin';\nimport type { ContextProviderPlugin } from '../api/plugin';\nimport { ContextProviderError } from '../api/toolkit-error';\nimport { formatErrorMessage } from '../util';\n\ntype ContextProviderFactory = ((sdk: SdkProvider, io: IContextProviderMessages) => ContextProviderPlugin);\ntype ProviderMap = {[name: string]: ContextProviderFactory};\n\nconst PLUGIN_PROVIDER_PREFIX = 'plugin';\n\nexport interface IContextProviderMessages {\n /**\n * A message that is presented to users in normal mode of operation.\n *\n * Should be used sparingly. The Context Provider framework already provides useful output by default.\n * This can be uses in exceptionally situations, e.g. if a lookup call is expected to take a long time.\n */\n info(message: string): Promise<void>;\n\n /**\n * A message that helps users debugging the context provider.\n *\n * Should be used in most cases to note on current action.\n */\n debug(message: string): Promise<void>;\n}\n\nclass ContextProviderMessages implements IContextProviderMessages {\n private readonly ioHelper: IoHelper;\n private readonly providerName: string;\n\n public constructor(ioHelper: IoHelper, providerName: string) {\n this.ioHelper = ioHelper;\n this.providerName = providerName;\n }\n\n public async info(message: string): Promise<void> {\n return this.ioHelper.notify(IO.CDK_ASSEMBLY_I0300.msg(message, {\n provider: this.providerName,\n }));\n }\n\n public async debug(message: string): Promise<void> {\n return this.ioHelper.notify(IO.CDK_ASSEMBLY_I0301.msg(message, {\n provider: this.providerName,\n }));\n }\n}\n\n/**\n * Iterate over the list of missing context values and invoke the appropriate providers from the map to retrieve them\n */\nexport async function provideContextValues(\n missingValues: cxschema.MissingContext[],\n context: Context,\n sdk: SdkProvider,\n ioHelper: IoHelper,\n) {\n for (const missingContext of missingValues) {\n const key = missingContext.key;\n\n const providerName = missingContext.provider === cxschema.ContextProvider.PLUGIN\n ? `${PLUGIN_PROVIDER_PREFIX}:${(missingContext.props as cxschema.PluginContextQuery).pluginName}`\n : missingContext.provider;\n\n let factory;\n if (providerName.startsWith(`${PLUGIN_PROVIDER_PREFIX}:`)) {\n const plugin = PluginHost.instance.contextProviderPlugins[providerName.substring(PLUGIN_PROVIDER_PREFIX.length + 1)];\n if (!plugin) {\n // eslint-disable-next-line max-len\n throw new ContextProviderError(`Unrecognized plugin context provider name: ${missingContext.provider}.`);\n }\n factory = () => plugin;\n } else {\n factory = availableContextProviders[providerName];\n if (!factory) {\n // eslint-disable-next-line max-len\n throw new ContextProviderError(`Unrecognized context provider name: ${missingContext.provider}. You might need to update the toolkit to match the version of the construct library.`);\n }\n }\n\n const provider = factory(sdk, new ContextProviderMessages(ioHelper, providerName));\n\n let value;\n try {\n const environment = missingContext.props.account && missingContext.props.region\n ? cxapi.EnvironmentUtils.make(missingContext.props.account, missingContext.props.region)\n : undefined;\n\n const resolvedEnvironment: cxapi.Environment = environment\n ? await sdk.resolveEnvironment(environment)\n : { account: '?', region: '?', name: '?' };\n\n const arns = await replaceEnvPlaceholders({\n lookupRoleArn: missingContext.props.lookupRoleArn,\n }, resolvedEnvironment, sdk);\n\n value = await provider.getValue({ ...missingContext.props, lookupRoleArn: arns.lookupRoleArn });\n } catch (e: any) {\n // Set a specially formatted provider value which will be interpreted\n // as a lookup failure in the toolkit.\n value = { [cxapi.PROVIDER_ERROR_KEY]: formatErrorMessage(e), [TRANSIENT_CONTEXT_KEY]: true };\n }\n context.set(key, value);\n await ioHelper.notify(IO.DEFAULT_ASSEMBLY_DEBUG.msg(`Setting \"${key}\" context to ${JSON.stringify(value)}`));\n }\n}\n\n/**\n * Register a context provider\n *\n * A context provider cannot reuse the SDKs authentication mechanisms.\n */\nexport function registerContextProvider(name: string, provider: ContextProviderPlugin) {\n availableContextProviders[name] = () => provider;\n}\n\n/**\n * Register a plugin context provider\n *\n * A plugin provider cannot reuse the SDKs authentication mechanisms.\n */\nexport function registerPluginContextProvider(name: string, provider: ContextProviderPlugin) {\n registerContextProvider(`${PLUGIN_PROVIDER_PREFIX}:${name}`, provider);\n}\n\n/**\n * Register a context provider factory\n *\n * A context provider factory takes an SdkProvider and returns the context provider plugin.\n */\nexport function registerContextProviderFactory(name: string, provider: ContextProviderFactory) {\n availableContextProviders[name] = provider;\n}\n\nconst availableContextProviders: ProviderMap = {\n [cxschema.ContextProvider.AVAILABILITY_ZONE_PROVIDER]: (s, io) => new AZContextProviderPlugin(s, io),\n [cxschema.ContextProvider.SSM_PARAMETER_PROVIDER]: (s, io) => new SSMContextProviderPlugin(s, io),\n [cxschema.ContextProvider.HOSTED_ZONE_PROVIDER]: (s, io) => new HostedZoneContextProviderPlugin(s, io),\n [cxschema.ContextProvider.VPC_PROVIDER]: (s, io) => new VpcNetworkContextProviderPlugin(s, io),\n [cxschema.ContextProvider.AMI_PROVIDER]: (s, io) => new AmiContextProviderPlugin(s, io),\n [cxschema.ContextProvider.ENDPOINT_SERVICE_AVAILABILITY_ZONE_PROVIDER]: (s, io) => new EndpointServiceAZContextProviderPlugin(s, io),\n [cxschema.ContextProvider.SECURITY_GROUP_PROVIDER]: (s) => new SecurityGroupContextProviderPlugin(s),\n [cxschema.ContextProvider.LOAD_BALANCER_PROVIDER]: (s) => new LoadBalancerContextProviderPlugin(s),\n [cxschema.ContextProvider.LOAD_BALANCER_LISTENER_PROVIDER]: (s) => new LoadBalancerListenerContextProviderPlugin(s),\n [cxschema.ContextProvider.KEY_PROVIDER]: (s, io) => new KeyContextProviderPlugin(s, io),\n [cxschema.ContextProvider.CC_API_PROVIDER]: (s) => new CcApiContextProviderPlugin(s),\n};\n", "import type { AmiContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport type { IContextProviderMessages } from '.';\nimport { type SdkProvider, initContextProviderSdk } from '../api/aws-auth';\nimport type { ContextProviderPlugin } from '../api/plugin';\nimport { ContextProviderError } from '../api/toolkit-error';\n\n/**\n * Plugin to search AMIs for the current account\n */\nexport class AmiContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider, private readonly io: IContextProviderMessages) {\n }\n\n public async getValue(args: AmiContextQuery) {\n const region = args.region;\n const account = args.account;\n\n // Normally we'd do this only as 'debug', but searching AMIs typically takes dozens\n // of seconds, so be little more verbose about it so users know what is going on.\n await this.io.info(`Searching for AMI in ${account}:${region}`);\n await this.io.debug(`AMI search parameters: ${JSON.stringify(args)}`);\n\n const ec2 = (await initContextProviderSdk(this.aws, args)).ec2();\n const response = await ec2.describeImages({\n Owners: args.owners,\n Filters: Object.entries(args.filters).map(([key, values]) => ({\n Name: key,\n Values: values,\n })),\n });\n\n const images = [...(response.Images || [])].filter((i) => i.ImageId !== undefined);\n\n if (images.length === 0) {\n throw new ContextProviderError('No AMI found that matched the search criteria');\n }\n\n // Return the most recent one\n // Note: Date.parse() is not going to respect the timezone of the string,\n // but since we only care about the relative values that is okay.\n images.sort(descending((i) => Date.parse(i.CreationDate || '1970')));\n\n await this.io.debug(`Selected image '${images[0].ImageId}' created at '${images[0].CreationDate}'`);\n return images[0].ImageId!;\n }\n}\n\n/**\n * Make a comparator that sorts in descending order given a sort key extractor\n */\nfunction descending<A>(valueOf: (x: A) => number) {\n return (a: A, b: A) => {\n return valueOf(b) - valueOf(a);\n };\n}\n", "import type { AvailabilityZonesContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport type { AvailabilityZone } from '@aws-sdk/client-ec2';\nimport type { IContextProviderMessages } from '.';\nimport { type SdkProvider, initContextProviderSdk } from '../api/aws-auth';\nimport type { ContextProviderPlugin } from '../api/plugin';\n\n/**\n * Plugin to retrieve the Availability Zones for the current account\n */\nexport class AZContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider, private readonly io: IContextProviderMessages) {\n }\n\n public async getValue(args: AvailabilityZonesContextQuery) {\n const region = args.region;\n const account = args.account;\n await this.io.debug(`Reading AZs for ${account}:${region}`);\n const ec2 = (await initContextProviderSdk(this.aws, args)).ec2();\n const response = await ec2.describeAvailabilityZones({});\n if (!response.AvailabilityZones) {\n return [];\n }\n const azs = response.AvailabilityZones.filter((zone: AvailabilityZone) => zone.State === 'available').map(\n (zone: AvailabilityZone) => zone.ZoneName,\n );\n return azs;\n }\n}\n", "import type { CcApiContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport type { ResourceDescription } from '@aws-sdk/client-cloudcontrol';\nimport { ResourceNotFoundException } from '@aws-sdk/client-cloudcontrol';\nimport type { ICloudControlClient, SdkProvider } from '../api/aws-auth';\nimport { initContextProviderSdk } from '../api/aws-auth';\nimport type { ContextProviderPlugin } from '../api/plugin';\nimport { ContextProviderError } from '../api/toolkit-error';\nimport { findJsonValue, getResultObj } from '../util';\n\nexport class CcApiContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider) {\n }\n\n /**\n * This returns a data object with the value from CloudControl API result.\n *\n * See the documentation in the Cloud Assembly Schema for the semantics of\n * each query parameter.\n */\n public async getValue(args: CcApiContextQuery) {\n // Validate input\n if (args.exactIdentifier && args.propertyMatch) {\n throw new ContextProviderError(`Provider protocol error: specify either exactIdentifier or propertyMatch, but not both (got ${JSON.stringify(args)})`);\n }\n if (args.ignoreErrorOnMissingContext && args.dummyValue === undefined) {\n throw new ContextProviderError(`Provider protocol error: if ignoreErrorOnMissingContext is set, a dummyValue must be supplied (got ${JSON.stringify(args)})`);\n }\n if (args.dummyValue !== undefined && (!Array.isArray(args.dummyValue) || !args.dummyValue.every(isObject))) {\n throw new ContextProviderError(`Provider protocol error: dummyValue must be an array of objects (got ${JSON.stringify(args.dummyValue)})`);\n }\n\n // Do the lookup\n const cloudControl = (await initContextProviderSdk(this.aws, args)).cloudControl();\n\n try {\n let resources: FoundResource[];\n if (args.exactIdentifier) {\n // use getResource to get the exact indentifier\n resources = await this.getResource(cloudControl, args.typeName, args.exactIdentifier);\n } else if (args.propertyMatch) {\n // use listResource\n resources = await this.listResources(cloudControl, args.typeName, args.propertyMatch, args.expectedMatchCount);\n } else {\n throw new ContextProviderError(`Provider protocol error: neither exactIdentifier nor propertyMatch is specified in ${JSON.stringify(args)}.`);\n }\n\n return resources.map((r) => getResultObj(r.properties, r.identifier, args.propertiesToReturn));\n } catch (err) {\n if (err instanceof ZeroResourcesFoundError && args.ignoreErrorOnMissingContext) {\n // We've already type-checked dummyValue.\n return args.dummyValue;\n }\n throw err;\n }\n }\n\n /**\n * Calls getResource from CC API to get the resource.\n * See https://docs.aws.amazon.com/cli/latest/reference/cloudcontrol/get-resource.html\n *\n * Will always return exactly one resource, or fail.\n */\n private async getResource(\n cc: ICloudControlClient,\n typeName: string,\n exactIdentifier: string,\n ): Promise<FoundResource[]> {\n try {\n const result = await cc.getResource({\n TypeName: typeName,\n Identifier: exactIdentifier,\n });\n if (!result.ResourceDescription) {\n throw new ContextProviderError('Unexpected CloudControl API behavior: returned empty response');\n }\n\n return [foundResourceFromCcApi(result.ResourceDescription)];\n } catch (err: any) {\n if (err instanceof ResourceNotFoundException || (err as any).name === 'ResourceNotFoundException') {\n throw new ZeroResourcesFoundError(`No resource of type ${typeName} with identifier: ${exactIdentifier}`);\n }\n if (!(err instanceof ContextProviderError)) {\n throw new ContextProviderError(`Encountered CC API error while getting ${typeName} resource ${exactIdentifier}: ${err.message}`);\n }\n throw err;\n }\n }\n\n /**\n * Calls listResources from CC API to get the resources and apply args.propertyMatch to find the resources.\n * See https://docs.aws.amazon.com/cli/latest/reference/cloudcontrol/list-resources.html\n *\n * Will return 0 or more resources.\n *\n * Does not currently paginate through more than one result page.\n */\n private async listResources(\n cc: ICloudControlClient,\n typeName: string,\n propertyMatch: Record<string, unknown>,\n expectedMatchCount?: CcApiContextQuery['expectedMatchCount'],\n ): Promise<FoundResource[]> {\n try {\n const result = await cc.listResources({\n TypeName: typeName,\n\n });\n const found = (result.ResourceDescriptions ?? [])\n .map(foundResourceFromCcApi)\n .filter((r) => {\n return Object.entries(propertyMatch).every(([propPath, expected]) => {\n const actual = findJsonValue(r.properties, propPath);\n return propertyMatchesFilter(actual, expected);\n });\n });\n\n if ((expectedMatchCount === 'at-least-one' || expectedMatchCount === 'exactly-one') && found.length === 0) {\n throw new ZeroResourcesFoundError(`Could not find any resources matching ${JSON.stringify(propertyMatch)}`);\n }\n if ((expectedMatchCount === 'at-most-one' || expectedMatchCount === 'exactly-one') && found.length > 1) {\n throw new ContextProviderError(`Found ${found.length} resources matching ${JSON.stringify(propertyMatch)}; please narrow the search criteria`);\n }\n\n return found;\n } catch (err: any) {\n if (!(err instanceof ContextProviderError) && !(err instanceof ZeroResourcesFoundError)) {\n throw new ContextProviderError(`Encountered CC API error while listing ${typeName} resources matching ${JSON.stringify(propertyMatch)}: ${err.message}`);\n }\n throw err;\n }\n }\n}\n\n/**\n * Convert a CC API response object into a nicer object (parse the JSON)\n */\nfunction foundResourceFromCcApi(desc: ResourceDescription): FoundResource {\n return {\n identifier: desc.Identifier ?? '*MISSING*',\n properties: JSON.parse(desc.Properties ?? '{}'),\n };\n}\n\n/**\n * Whether the given property value matches the given filter\n *\n * For now we just check for strict equality, but we can implement pattern matching and fuzzy matching here later\n */\nfunction propertyMatchesFilter(actual: unknown, expected: unknown) {\n return expected === actual;\n}\n\nfunction isObject(x: unknown): x is {[key: string]: unknown} {\n return typeof x === 'object' && x !== null && !Array.isArray(x);\n}\n\n/**\n * A parsed version of the return value from CCAPI\n */\ninterface FoundResource {\n readonly identifier: string;\n readonly properties: Record<string, unknown>;\n}\n\n/**\n * A specific lookup failure indicating 0 resources found that can be recovered\n */\nclass ZeroResourcesFoundError extends Error {\n}\n", "import type { EndpointServiceAvailabilityZonesContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport type { IContextProviderMessages } from '.';\nimport { type SdkProvider, initContextProviderSdk } from '../api/aws-auth';\nimport type { ContextProviderPlugin } from '../api/plugin';\n\n/**\n * Plugin to retrieve the Availability Zones for an endpoint service\n */\nexport class EndpointServiceAZContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider, private readonly io: IContextProviderMessages) {\n }\n\n public async getValue(args: EndpointServiceAvailabilityZonesContextQuery) {\n const region = args.region;\n const account = args.account;\n const serviceName = args.serviceName;\n await this.io.debug(`Reading AZs for ${account}:${region}:${serviceName}`);\n const ec2 = (await initContextProviderSdk(this.aws, args)).ec2();\n const response = await ec2.describeVpcEndpointServices({\n ServiceNames: [serviceName],\n });\n\n // expect a service in the response\n if (!response.ServiceDetails || response.ServiceDetails.length === 0) {\n await this.io.debug(`Could not retrieve service details for ${account}:${region}:${serviceName}`);\n return [];\n }\n const azs = response.ServiceDetails[0].AvailabilityZones;\n await this.io.debug(`Endpoint service ${account}:${region}:${serviceName} is available in availability zones ${azs}`);\n return azs;\n }\n}\n", "import type { HostedZoneContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport type { HostedZone } from '@aws-sdk/client-route-53';\nimport type { IContextProviderMessages } from '.';\nimport type { IRoute53Client, SdkProvider } from '../api/aws-auth';\nimport { initContextProviderSdk } from '../api/aws-auth';\nimport type { ContextProviderPlugin } from '../api/plugin';\nimport { ContextProviderError } from '../api/toolkit-error';\n\nexport class HostedZoneContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider, private readonly io: IContextProviderMessages) {\n }\n\n public async getValue(args: HostedZoneContextQuery): Promise<object> {\n const account = args.account;\n const region = args.region;\n if (!this.isHostedZoneQuery(args)) {\n throw new ContextProviderError(`HostedZoneProvider requires domainName property to be set in ${args}`);\n }\n const domainName = args.domainName;\n await this.io.debug(`Reading hosted zone ${account}:${region}:${domainName}`);\n const r53 = (await initContextProviderSdk(this.aws, args)).route53();\n const response = await r53.listHostedZonesByName({ DNSName: domainName });\n if (!response.HostedZones) {\n throw new ContextProviderError(`Hosted Zone not found in account ${account}, region ${region}: ${domainName}`);\n }\n const candidateZones = await this.filterZones(r53, response.HostedZones, args);\n if (candidateZones.length !== 1) {\n const filteProps = `dns:${domainName}, privateZone:${args.privateZone}, vpcId:${args.vpcId}`;\n throw new ContextProviderError(`Found zones: ${JSON.stringify(candidateZones)} for ${filteProps}, but wanted exactly 1 zone`);\n }\n\n return {\n Id: candidateZones[0].Id,\n Name: candidateZones[0].Name,\n };\n }\n\n private async filterZones(\n r53: IRoute53Client,\n zones: HostedZone[],\n props: HostedZoneContextQuery,\n ): Promise<HostedZone[]> {\n let candidates: HostedZone[] = [];\n const domainName = props.domainName.endsWith('.') ? props.domainName : `${props.domainName}.`;\n await this.io.debug(`Found the following zones ${JSON.stringify(zones)}`);\n candidates = zones.filter((zone) => zone.Name === domainName);\n await this.io.debug(`Found the following matched name zones ${JSON.stringify(candidates)}`);\n if (props.privateZone) {\n candidates = candidates.filter((zone) => zone.Config && zone.Config.PrivateZone);\n } else {\n candidates = candidates.filter((zone) => !zone.Config || !zone.Config.PrivateZone);\n }\n if (props.vpcId) {\n const vpcZones: HostedZone[] = [];\n for (const zone of candidates) {\n const data = await r53.getHostedZone({ Id: zone.Id });\n if (!data.VPCs) {\n await this.io.debug(`Expected VPC for private zone but no VPC found ${zone.Id}`);\n continue;\n }\n if (data.VPCs.map((vpc) => vpc.VPCId).includes(props.vpcId)) {\n vpcZones.push(zone);\n }\n }\n return vpcZones;\n }\n return candidates;\n }\n\n private isHostedZoneQuery(props: HostedZoneContextQuery | any): props is HostedZoneContextQuery {\n return (props as HostedZoneContextQuery).domainName !== undefined;\n }\n}\n", "import type { KeyContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport type { KeyContextResponse } from '@aws-cdk/cx-api';\nimport type { AliasListEntry, ListAliasesCommandOutput } from '@aws-sdk/client-kms';\nimport type { IContextProviderMessages } from '.';\nimport type { IKMSClient, SdkProvider } from '../api/aws-auth';\nimport { initContextProviderSdk } from '../api/aws-auth';\nimport type { ContextProviderPlugin } from '../api/plugin';\nimport { ContextProviderError } from '../api/toolkit-error';\n\nexport class KeyContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider, private readonly io: IContextProviderMessages) {\n }\n\n public async getValue(args: KeyContextQuery) {\n const kms = (await initContextProviderSdk(this.aws, args)).kms();\n\n const aliasListEntry = await this.findKey(kms, args);\n\n return this.readKeyProps(aliasListEntry, args);\n }\n\n // TODO: use paginator function\n private async findKey(kms: IKMSClient, args: KeyContextQuery): Promise<AliasListEntry> {\n await this.io.debug(`Listing keys in ${args.account}:${args.region}`);\n\n let response: ListAliasesCommandOutput;\n let nextMarker: string | undefined;\n do {\n response = await kms.listAliases({\n Marker: nextMarker,\n });\n\n const aliases = response.Aliases || [];\n for (const alias of aliases) {\n if (alias.AliasName == args.aliasName) {\n return alias;\n }\n }\n\n nextMarker = response.NextMarker;\n } while (nextMarker);\n\n const suppressError = 'ignoreErrorOnMissingContext' in args && args.ignoreErrorOnMissingContext as boolean;\n const hasDummyKeyId = 'dummyValue' in args && typeof args.dummyValue === 'object' && args.dummyValue !== null && 'keyId' in args.dummyValue;\n if (suppressError && hasDummyKeyId) {\n const keyId = (args.dummyValue as { keyId: string }).keyId;\n return { TargetKeyId: keyId };\n }\n throw new ContextProviderError(`Could not find any key with alias named ${args.aliasName}`);\n }\n\n private async readKeyProps(alias: AliasListEntry, args: KeyContextQuery): Promise<KeyContextResponse> {\n if (!alias.TargetKeyId) {\n throw new ContextProviderError(`Could not find any key with alias named ${args.aliasName}`);\n }\n\n await this.io.debug(`Key found ${alias.TargetKeyId}`);\n\n return {\n keyId: alias.TargetKeyId,\n };\n }\n}\n", "import type { LoadBalancerContextQuery, LoadBalancerListenerContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport type {\n LoadBalancerContextResponse,\n LoadBalancerListenerContextResponse,\n} from '@aws-cdk/cx-api';\nimport {\n LoadBalancerIpAddressType,\n} from '@aws-cdk/cx-api';\nimport type { LoadBalancer, Listener, TagDescription } from '@aws-sdk/client-elastic-load-balancing-v2';\nimport type { IElasticLoadBalancingV2Client, SdkProvider } from '../api/aws-auth';\nimport { initContextProviderSdk } from '../api/aws-auth';\nimport type { ContextProviderPlugin } from '../api/plugin';\nimport { ContextProviderError } from '../api/toolkit-error';\n\n/**\n * Provides load balancer context information.\n */\nexport class LoadBalancerContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider) {\n }\n\n async getValue(query: LoadBalancerContextQuery): Promise<LoadBalancerContextResponse> {\n if (!query.loadBalancerArn && !query.loadBalancerTags) {\n throw new ContextProviderError('The load balancer lookup query must specify either `loadBalancerArn` or `loadBalancerTags`');\n }\n\n const loadBalancer = await (await LoadBalancerProvider.getClient(this.aws, query)).getLoadBalancer();\n\n const ipAddressType =\n loadBalancer.IpAddressType === 'ipv4' ? LoadBalancerIpAddressType.IPV4 : LoadBalancerIpAddressType.DUAL_STACK;\n\n return {\n loadBalancerArn: loadBalancer.LoadBalancerArn!,\n loadBalancerCanonicalHostedZoneId: loadBalancer.CanonicalHostedZoneId!,\n loadBalancerDnsName: loadBalancer.DNSName!,\n vpcId: loadBalancer.VpcId!,\n securityGroupIds: loadBalancer.SecurityGroups ?? [],\n ipAddressType: ipAddressType,\n };\n }\n}\n\n/**\n * Provides load balancer listener context information\n */\nexport class LoadBalancerListenerContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider) {\n }\n\n async getValue(query: LoadBalancerListenerContextQuery): Promise<LoadBalancerListenerContextResponse> {\n if (!query.listenerArn && !query.loadBalancerArn && !query.loadBalancerTags) {\n throw new ContextProviderError(\n 'The load balancer listener query must specify at least one of: `listenerArn`, `loadBalancerArn` or `loadBalancerTags`',\n );\n }\n\n return (await LoadBalancerProvider.getClient(this.aws, query)).getListener();\n }\n}\n\nclass LoadBalancerProvider {\n public static async getClient(\n aws: SdkProvider,\n query: LoadBalancerListenerContextQuery,\n ): Promise<LoadBalancerProvider> {\n const client = (await initContextProviderSdk(aws, query)).elbv2();\n\n try {\n const listener = query.listenerArn\n ? // Assert we're sure there's at least one so it throws if not\n (await client.describeListeners({ ListenerArns: [query.listenerArn] })).Listeners![0]!\n : undefined;\n return new LoadBalancerProvider(\n client,\n { ...query, loadBalancerArn: listener?.LoadBalancerArn || query.loadBalancerArn },\n listener,\n );\n } catch (err) {\n throw new ContextProviderError(`No load balancer listeners found matching arn ${query.listenerArn}`);\n }\n }\n\n constructor(\n private readonly client: IElasticLoadBalancingV2Client,\n private readonly filter: LoadBalancerListenerContextQuery,\n private readonly listener?: Listener,\n ) {\n }\n\n public async getLoadBalancer(): Promise<LoadBalancer> {\n const loadBalancers = await this.getLoadBalancers();\n\n if (loadBalancers.length === 0) {\n throw new ContextProviderError(`No load balancers found matching ${JSON.stringify(this.filter)}`);\n }\n\n if (loadBalancers.length > 1) {\n throw new ContextProviderError(\n `Multiple load balancers found matching ${JSON.stringify(this.filter)} - please provide more specific criteria`,\n );\n }\n\n return loadBalancers[0];\n }\n\n public async getListener(): Promise<LoadBalancerListenerContextResponse> {\n if (this.listener) {\n try {\n const loadBalancer = await this.getLoadBalancer();\n return {\n listenerArn: this.listener.ListenerArn!,\n listenerPort: this.listener.Port!,\n securityGroupIds: loadBalancer.SecurityGroups || [],\n };\n } catch (err) {\n throw new ContextProviderError(`No associated load balancer found for listener arn ${this.filter.listenerArn}`);\n }\n }\n\n const loadBalancers = await this.getLoadBalancers();\n if (loadBalancers.length === 0) {\n throw new ContextProviderError(\n `No associated load balancers found for load balancer listener query ${JSON.stringify(this.filter)}`,\n );\n }\n\n const listeners = (await this.getListenersForLoadBalancers(loadBalancers)).filter((listener) => {\n return (\n (!this.filter.listenerPort || listener.Port === this.filter.listenerPort) &&\n (!this.filter.listenerProtocol || listener.Protocol === this.filter.listenerProtocol)\n );\n });\n\n if (listeners.length === 0) {\n throw new ContextProviderError(`No load balancer listeners found matching ${JSON.stringify(this.filter)}`);\n }\n\n if (listeners.length > 1) {\n throw new ContextProviderError(\n `Multiple load balancer listeners found matching ${JSON.stringify(this.filter)} - please provide more specific criteria`,\n );\n }\n\n return {\n listenerArn: listeners[0].ListenerArn!,\n listenerPort: listeners[0].Port!,\n securityGroupIds:\n loadBalancers.find((lb) => listeners[0].LoadBalancerArn === lb.LoadBalancerArn)?.SecurityGroups || [],\n };\n }\n\n private async getLoadBalancers() {\n const loadBalancerArns = this.filter.loadBalancerArn ? [this.filter.loadBalancerArn] : undefined;\n const loadBalancers = (\n await this.client.paginateDescribeLoadBalancers({\n LoadBalancerArns: loadBalancerArns,\n })\n ).filter((lb) => lb.Type === this.filter.loadBalancerType);\n\n return this.filterByTags(loadBalancers);\n }\n\n private async filterByTags(loadBalancers: LoadBalancer[]): Promise<LoadBalancer[]> {\n if (!this.filter.loadBalancerTags) {\n return loadBalancers;\n }\n return (await this.describeTags(loadBalancers.map((lb) => lb.LoadBalancerArn!)))\n .filter((tagDescription) => {\n // For every tag in the filter, there is some tag in the LB that matches it.\n // In other words, the set of tags in the filter is a subset of the set of tags in the LB.\n return this.filter.loadBalancerTags!.every((filter) => {\n return tagDescription.Tags?.some((tag) =>\n filter.key === tag.Key && filter.value === tag.Value);\n });\n })\n .flatMap((tag) => loadBalancers.filter((loadBalancer) => tag.ResourceArn === loadBalancer.LoadBalancerArn));\n }\n\n /**\n * Returns tag descriptions associated with the resources. The API doesn't support\n * pagination, so this function breaks the resource list into chunks and issues\n * the appropriate requests.\n */\n private async describeTags(resourceArns: string[]): Promise<TagDescription[]> {\n // Max of 20 resource arns per request.\n const chunkSize = 20;\n const tags = Array<TagDescription>();\n for (let i = 0; i < resourceArns.length; i += chunkSize) {\n const chunk = resourceArns.slice(i, Math.min(i + chunkSize, resourceArns.length));\n const chunkTags = await this.client.describeTags({\n ResourceArns: chunk,\n });\n\n tags.push(...(chunkTags.TagDescriptions || []));\n }\n return tags;\n }\n\n private async getListenersForLoadBalancers(loadBalancers: LoadBalancer[]): Promise<Listener[]> {\n const listeners: Listener[] = [];\n for (const loadBalancer of loadBalancers.map((lb) => lb.LoadBalancerArn)) {\n listeners.push(...(await this.client.paginateDescribeListeners({ LoadBalancerArn: loadBalancer })));\n }\n return listeners;\n }\n}\n", "import type { SecurityGroupContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport type { SecurityGroupContextResponse } from '@aws-cdk/cx-api';\nimport type { Filter, SecurityGroup } from '@aws-sdk/client-ec2';\nimport { type SdkProvider, initContextProviderSdk } from '../api/aws-auth';\nimport type { ContextProviderPlugin } from '../api/plugin';\nimport { ContextProviderError } from '../api/toolkit-error';\n\nexport class SecurityGroupContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider) {\n }\n\n async getValue(args: SecurityGroupContextQuery): Promise<SecurityGroupContextResponse> {\n if (args.securityGroupId && args.securityGroupName) {\n throw new ContextProviderError(\n \"'securityGroupId' and 'securityGroupName' can not be specified both when looking up a security group\",\n );\n }\n\n if (!args.securityGroupId && !args.securityGroupName) {\n throw new ContextProviderError(\"'securityGroupId' or 'securityGroupName' must be specified to look up a security group\");\n }\n\n const ec2 = (await initContextProviderSdk(this.aws, args)).ec2();\n\n const filters: Filter[] = [];\n if (args.vpcId) {\n filters.push({\n Name: 'vpc-id',\n Values: [args.vpcId],\n });\n }\n if (args.securityGroupName) {\n filters.push({\n Name: 'group-name',\n Values: [args.securityGroupName],\n });\n }\n\n const response = await ec2.describeSecurityGroups({\n GroupIds: args.securityGroupId ? [args.securityGroupId] : undefined,\n Filters: filters.length > 0 ? filters : undefined,\n });\n\n const securityGroups = response.SecurityGroups ?? [];\n if (securityGroups.length === 0) {\n throw new ContextProviderError(`No security groups found matching ${JSON.stringify(args)}`);\n }\n\n if (securityGroups.length > 1) {\n throw new ContextProviderError(`More than one security groups found matching ${JSON.stringify(args)}`);\n }\n\n const [securityGroup] = securityGroups;\n\n return {\n securityGroupId: securityGroup.GroupId!,\n allowAllOutbound: hasAllTrafficEgress(securityGroup),\n };\n }\n}\n\n/**\n * @internal\n */\nexport function hasAllTrafficEgress(securityGroup: SecurityGroup) {\n let hasAllTrafficCidrV4 = false;\n let hasAllTrafficCidrV6 = false;\n\n for (const ipPermission of securityGroup.IpPermissionsEgress ?? []) {\n const isAllProtocols = ipPermission.IpProtocol === '-1';\n\n if (isAllProtocols && ipPermission.IpRanges?.some((m) => m.CidrIp === '0.0.0.0/0')) {\n hasAllTrafficCidrV4 = true;\n }\n\n if (isAllProtocols && ipPermission.Ipv6Ranges?.some((m) => m.CidrIpv6 === '::/0')) {\n hasAllTrafficCidrV6 = true;\n }\n }\n\n return hasAllTrafficCidrV4 && hasAllTrafficCidrV6;\n}\n", "import type { SSMParameterContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport type { GetParameterCommandOutput } from '@aws-sdk/client-ssm';\nimport type { IContextProviderMessages } from '.';\nimport { type SdkProvider, initContextProviderSdk } from '../api/aws-auth';\nimport type { ContextProviderPlugin } from '../api/plugin';\nimport { ContextProviderError } from '../api/toolkit-error';\n\n/**\n * Plugin to read arbitrary SSM parameter names\n */\nexport class SSMContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider, private readonly io: IContextProviderMessages) {\n }\n\n public async getValue(args: SSMParameterContextQuery) {\n const region = args.region;\n const account = args.account;\n\n if (!('parameterName' in args)) {\n throw new ContextProviderError('parameterName must be provided in props for SSMContextProviderPlugin');\n }\n const parameterName = args.parameterName;\n await this.io.debug(`Reading SSM parameter ${account}:${region}:${parameterName}`);\n\n const response = await this.getSsmParameterValue(args);\n const parameterNotFound: boolean = !response.Parameter || response.Parameter.Value === undefined;\n const suppressError = 'ignoreErrorOnMissingContext' in args && (args.ignoreErrorOnMissingContext as boolean);\n if (parameterNotFound && suppressError && 'dummyValue' in args) {\n return args.dummyValue;\n }\n if (parameterNotFound) {\n throw new ContextProviderError(`SSM parameter not available in account ${account}, region ${region}: ${parameterName}`);\n }\n // will not be undefined because we've handled undefined cases above\n return response.Parameter!.Value;\n }\n\n /**\n * Gets the value of an SSM Parameter, while not throwin if the parameter does not exist.\n * @param account the account in which the SSM Parameter is expected to be.\n * @param region the region in which the SSM Parameter is expected to be.\n * @param parameterName the name of the SSM Parameter\n * @param lookupRoleArn the ARN of the lookup role.\n *\n * @returns the result of the ``GetParameter`` operation.\n *\n * @throws Error if a service error (other than ``ParameterNotFound``) occurs.\n */\n private async getSsmParameterValue(args: SSMParameterContextQuery): Promise<GetParameterCommandOutput> {\n const ssm = (await initContextProviderSdk(this.aws, args)).ssm();\n try {\n return await ssm.getParameter({ Name: args.parameterName });\n } catch (e: any) {\n if (e.name === 'ParameterNotFound') {\n return { $metadata: {} };\n }\n throw e;\n }\n }\n}\n", "import type { VpcContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport { type VpcContextResponse, type VpcSubnetGroup, VpcSubnetGroupType } from '@aws-cdk/cx-api';\nimport type { Filter, RouteTable, Tag, Vpc } from '@aws-sdk/client-ec2';\nimport type { IContextProviderMessages } from '.';\nimport type { IEC2Client, SdkProvider } from '../api/aws-auth';\nimport { initContextProviderSdk } from '../api/aws-auth';\nimport type { ContextProviderPlugin } from '../api/plugin';\nimport { ContextProviderError } from '../api/toolkit-error';\n\nexport class VpcNetworkContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider, private readonly io: IContextProviderMessages) {\n }\n\n public async getValue(args: VpcContextQuery) {\n const ec2 = (await initContextProviderSdk(this.aws, args)).ec2();\n\n const vpcId = await this.findVpc(ec2, args);\n\n return this.readVpcProps(ec2, vpcId, args);\n }\n\n private async findVpc(ec2: IEC2Client, args: VpcContextQuery): Promise<Vpc> {\n // Build request filter (map { Name -> Value } to list of [{ Name, Values }])\n const filters: Filter[] = Object.entries(args.filter).map(([tag, value]) => ({ Name: tag, Values: [value] }));\n\n await this.io.debug(`Listing VPCs in ${args.account}:${args.region}`);\n const response = await ec2.describeVpcs({ Filters: filters });\n\n const vpcs = response.Vpcs || [];\n if (vpcs.length === 0) {\n throw new ContextProviderError(`Could not find any VPCs matching ${JSON.stringify(args)}`);\n }\n if (vpcs.length > 1) {\n throw new ContextProviderError(`Found ${vpcs.length} VPCs matching ${JSON.stringify(args)}; please narrow the search criteria`);\n }\n\n return vpcs[0];\n }\n\n private async readVpcProps(ec2: IEC2Client, vpc: Vpc, args: VpcContextQuery): Promise<VpcContextResponse> {\n const vpcId = vpc.VpcId!;\n\n await this.io.debug(`Describing VPC ${vpcId}`);\n\n const filters = { Filters: [{ Name: 'vpc-id', Values: [vpcId] }] };\n\n const subnetsResponse = await ec2.describeSubnets(filters);\n const listedSubnets = subnetsResponse.Subnets || [];\n\n const routeTablesResponse = await ec2.describeRouteTables(filters);\n const routeTables = new RouteTables(routeTablesResponse.RouteTables || []);\n\n // Now comes our job to separate these subnets out into AZs and subnet groups (Public, Private, Isolated)\n // We have the following attributes to go on:\n // - Type tag, we tag subnets with their type. In absence of this tag, we\n // determine the subnet must be Public if either:\n // a) it has the property MapPublicIpOnLaunch\n // b) it has a route to an Internet Gateway\n // If both of the above is false but the subnet has a route to a NAT Gateway\n // and the destination CIDR block is \"0.0.0.0/0\", we assume it to be a Private subnet.\n // Anything else is considered Isolated.\n // - Name tag, we tag subnets with their subnet group name. In absence of this tag,\n // we use the type as the name.\n\n const azs = Array.from(new Set<string>(listedSubnets.map((s) => s.AvailabilityZone!)));\n azs.sort();\n\n const subnets: Subnet[] = listedSubnets.map((subnet) => {\n let type = getTag('aws-cdk:subnet-type', subnet.Tags);\n if (type === undefined && subnet.MapPublicIpOnLaunch) {\n type = SubnetType.Public;\n }\n if (type === undefined && routeTables.hasRouteToIgw(subnet.SubnetId)) {\n type = SubnetType.Public;\n }\n if (type === undefined && routeTables.hasRouteToNatGateway(subnet.SubnetId)) {\n type = SubnetType.Private;\n }\n if (type === undefined && routeTables.hasRouteToTransitGateway(subnet.SubnetId)) {\n type = SubnetType.Private;\n }\n if (type === undefined) {\n type = SubnetType.Isolated;\n }\n\n if (!isValidSubnetType(type)) {\n // eslint-disable-next-line max-len\n throw new ContextProviderError(\n `Subnet ${subnet.SubnetArn} has invalid subnet type ${type} (must be ${SubnetType.Public}, ${SubnetType.Private} or ${SubnetType.Isolated})`,\n );\n }\n\n if (args.subnetGroupNameTag && !getTag(args.subnetGroupNameTag, subnet.Tags)) {\n throw new ContextProviderError(\n `Invalid subnetGroupNameTag: Subnet ${subnet.SubnetArn} does not have an associated tag with Key='${args.subnetGroupNameTag}'`,\n );\n }\n\n const name = getTag(args.subnetGroupNameTag || 'aws-cdk:subnet-name', subnet.Tags) || type;\n const routeTableId = routeTables.routeTableIdForSubnetId(subnet.SubnetId);\n\n if (!routeTableId) {\n throw new ContextProviderError(\n `Subnet ${subnet.SubnetArn} does not have an associated route table (and there is no \"main\" table)`,\n );\n }\n\n return {\n az: subnet.AvailabilityZone!,\n cidr: subnet.CidrBlock!,\n type,\n name,\n subnetId: subnet.SubnetId!,\n routeTableId,\n };\n });\n\n let grouped: SubnetGroups;\n let assymetricSubnetGroups: VpcSubnetGroup[] | undefined;\n if (args.returnAsymmetricSubnets) {\n grouped = { azs: [], groups: [] };\n assymetricSubnetGroups = groupAsymmetricSubnets(subnets);\n } else {\n grouped = groupSubnets(subnets);\n assymetricSubnetGroups = undefined;\n }\n\n // Find attached+available VPN gateway for this VPC\n const vpnGatewayResponse =\n (args.returnVpnGateways ?? true)\n ? await ec2.describeVpnGateways({\n Filters: [\n {\n Name: 'attachment.vpc-id',\n Values: [vpcId],\n },\n {\n Name: 'attachment.state',\n Values: ['attached'],\n },\n {\n Name: 'state',\n Values: ['available'],\n },\n ],\n })\n : undefined;\n const vpnGatewayId =\n vpnGatewayResponse?.VpnGateways?.length === 1 ? vpnGatewayResponse.VpnGateways[0].VpnGatewayId : undefined;\n\n return {\n vpcId,\n vpcCidrBlock: vpc.CidrBlock!,\n ownerAccountId: vpc.OwnerId,\n availabilityZones: grouped.azs,\n isolatedSubnetIds: collapse(\n flatMap(findGroups(SubnetType.Isolated, grouped), (group) => group.subnets.map((s) => s.subnetId)),\n ),\n isolatedSubnetNames: collapse(\n flatMap(findGroups(SubnetType.Isolated, grouped), (group) => (group.name ? [group.name] : [])),\n ),\n isolatedSubnetRouteTableIds: collapse(\n flatMap(findGroups(SubnetType.Isolated, grouped), (group) => group.subnets.map((s) => s.routeTableId)),\n ),\n privateSubnetIds: collapse(\n flatMap(findGroups(SubnetType.Private, grouped), (group) => group.subnets.map((s) => s.subnetId)),\n ),\n privateSubnetNames: collapse(\n flatMap(findGroups(SubnetType.Private, grouped), (group) => (group.name ? [group.name] : [])),\n ),\n privateSubnetRouteTableIds: collapse(\n flatMap(findGroups(SubnetType.Private, grouped), (group) => group.subnets.map((s) => s.routeTableId)),\n ),\n publicSubnetIds: collapse(\n flatMap(findGroups(SubnetType.Public, grouped), (group) => group.subnets.map((s) => s.subnetId)),\n ),\n publicSubnetNames: collapse(\n flatMap(findGroups(SubnetType.Public, grouped), (group) => (group.name ? [group.name] : [])),\n ),\n publicSubnetRouteTableIds: collapse(\n flatMap(findGroups(SubnetType.Public, grouped), (group) => group.subnets.map((s) => s.routeTableId)),\n ),\n vpnGatewayId,\n subnetGroups: assymetricSubnetGroups,\n };\n }\n}\n\nclass RouteTables {\n public readonly mainRouteTable?: RouteTable;\n\n constructor(private readonly tables: RouteTable[]) {\n this.mainRouteTable = this.tables.find(\n (table) => !!table.Associations && table.Associations.some((assoc) => !!assoc.Main),\n );\n }\n\n public routeTableIdForSubnetId(subnetId: string | undefined): string | undefined {\n const table = this.tableForSubnet(subnetId);\n return (table && table.RouteTableId) || (this.mainRouteTable && this.mainRouteTable.RouteTableId);\n }\n\n /**\n * Whether the given subnet has a route to a NAT Gateway\n */\n public hasRouteToNatGateway(subnetId: string | undefined): boolean {\n const table = this.tableForSubnet(subnetId) || this.mainRouteTable;\n\n return (\n !!table &&\n !!table.Routes &&\n table.Routes.some((route) => !!route.NatGatewayId && route.DestinationCidrBlock === '0.0.0.0/0')\n );\n }\n\n /**\n * Whether the given subnet has a route to a Transit Gateway\n */\n public hasRouteToTransitGateway(subnetId: string | undefined): boolean {\n const table = this.tableForSubnet(subnetId) || this.mainRouteTable;\n\n return (\n !!table &&\n !!table.Routes &&\n table.Routes.some((route) => !!route.TransitGatewayId && route.DestinationCidrBlock === '0.0.0.0/0')\n );\n }\n\n /**\n * Whether the given subnet has a route to an IGW\n */\n public hasRouteToIgw(subnetId: string | undefined): boolean {\n const table = this.tableForSubnet(subnetId) || this.mainRouteTable;\n\n return (\n !!table && !!table.Routes && table.Routes.some((route) => !!route.GatewayId && route.GatewayId.startsWith('igw-'))\n );\n }\n\n public tableForSubnet(subnetId: string | undefined) {\n return this.tables.find(\n (table) => !!table.Associations && table.Associations.some((assoc) => assoc.SubnetId === subnetId),\n );\n }\n}\n\n/**\n * Return the value of a tag from a set of tags\n */\nfunction getTag(name: string, tags?: Tag[]): string | undefined {\n for (const tag of tags || []) {\n if (tag.Key === name) {\n return tag.Value;\n }\n }\n return undefined;\n}\n\n/**\n * Group subnets of the same type together, and order by AZ\n */\nfunction groupSubnets(subnets: Subnet[]): SubnetGroups {\n const grouping: { [key: string]: Subnet[] } = {};\n for (const subnet of subnets) {\n const key = [subnet.type, subnet.name].toString();\n if (!(key in grouping)) {\n grouping[key] = [];\n }\n grouping[key].push(subnet);\n }\n\n const groups = Object.values(grouping).map((sns) => {\n sns.sort((a: Subnet, b: Subnet) => a.az.localeCompare(b.az));\n return {\n type: sns[0].type,\n name: sns[0].name,\n subnets: sns,\n };\n });\n\n const azs = groups[0].subnets.map((s) => s.az);\n\n for (const group of groups) {\n const groupAZs = group.subnets.map((s) => s.az);\n if (!arraysEqual(groupAZs, azs)) {\n throw new ContextProviderError(`Not all subnets in VPC have the same AZs: ${groupAZs} vs ${azs}`);\n }\n }\n\n return { azs, groups };\n}\n\nfunction groupAsymmetricSubnets(subnets: Subnet[]): VpcSubnetGroup[] {\n const grouping: { [key: string]: Subnet[] } = {};\n for (const subnet of subnets) {\n const key = [subnet.type, subnet.name].toString();\n if (!(key in grouping)) {\n grouping[key] = [];\n }\n grouping[key].push(subnet);\n }\n\n return Object.values(grouping).map((subnetArray) => {\n subnetArray.sort((subnet1: Subnet, subnet2: Subnet) => subnet1.az.localeCompare(subnet2.az));\n\n return {\n name: subnetArray[0].name,\n type: subnetTypeToVpcSubnetType(subnetArray[0].type),\n subnets: subnetArray.map((subnet) => ({\n subnetId: subnet.subnetId,\n cidr: subnet.cidr,\n availabilityZone: subnet.az,\n routeTableId: subnet.routeTableId,\n })),\n };\n });\n}\n\nfunction subnetTypeToVpcSubnetType(type: SubnetType): VpcSubnetGroupType {\n switch (type) {\n case SubnetType.Isolated:\n return VpcSubnetGroupType.ISOLATED;\n case SubnetType.Private:\n return VpcSubnetGroupType.PRIVATE;\n case SubnetType.Public:\n return VpcSubnetGroupType.PUBLIC;\n }\n}\n\nenum SubnetType {\n Public = 'Public',\n Private = 'Private',\n Isolated = 'Isolated',\n}\n\nfunction isValidSubnetType(val: string): val is SubnetType {\n return val === SubnetType.Public || val === SubnetType.Private || val === SubnetType.Isolated;\n}\n\ninterface Subnet {\n az: string;\n cidr: string;\n type: SubnetType;\n name: string;\n routeTableId: string;\n subnetId: string;\n}\n\ninterface SubnetGroup {\n type: SubnetType;\n name: string;\n subnets: Subnet[];\n}\n\ninterface SubnetGroups {\n azs: string[];\n groups: SubnetGroup[];\n}\n\nfunction arraysEqual(as: string[], bs: string[]): boolean {\n if (as.length !== bs.length) {\n return false;\n }\n\n for (let i = 0; i < as.length; i++) {\n if (as[i] !== bs[i]) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction findGroups(type: SubnetType, groups: SubnetGroups): SubnetGroup[] {\n return groups.groups.filter((g) => g.type === type);\n}\n\nfunction flatMap<T, U>(xs: T[], fn: (x: T) => U[]): U[] {\n const ret = new Array<U>();\n for (const x of xs) {\n ret.push(...fn(x));\n }\n return ret;\n}\n\nfunction collap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CAAU,0BAAgB,0BAA0B,GAAG,CAAC,GAAG,OAAO,IAAI,wBAAwB,GAAG,EAAE;AAAA,EACnG,CAAU,0BAAgB,sBAAsB,GAAG,CAAC,GAAG,OAAO,IAAI,yBAAyB,GAAG,EAAE;AAAA,EAChG,CAAU,0BAAgB,oBAAoB,GAAG,CAAC,GAAG,OAAO,IAAI,gCAAgC,GAAG,EAAE;AAAA,EACrG,CAAU,0BAAgB,YAAY,GAAG,CAAC,GAAG,OAAO,IAAI,gCAAgC,GAAG,EAAE;AAAA,EAC7F,CAAU,0BAAgB,YAAY,GAAG,CAAC,GAAG,OAAO,IAAI,yBAAyB,GAAG,EAAE;AAAA,EACtF,CAAU,0BAAgB,2CAA2C,GAAG,CAAC,GAAG,OAAO,IAAI,uCAAuC,GAAG,EAAE;AAAA,EACnI,CAAU,0BAAgB,uBAAuB,GAAG,CAAC,MAAM,IAAI,mCAAmC,CAAC;AAAA,EACnG,CAAU,0BAAgB,sBAAsB,GAAG,CAAC,MAAM,IAAI,kCAAkC,CAAC;AAAA,EACjG,CAAU,0BAAgB,+BAA+B,GAAG,CAAC,MAAM,IAAI,0CAA0C,CAAC;AAAA,EAClH,CAAU,0BAAgB,YAAY,GAAG,CAAC,GAAG,OAAO,IAAI,yBAAyB,GAAG,EAAE;AAAA,EACtF,CAAU,0BAAgB,eAAe,GAAG,CAAC,MAAM,IAAI,2BAA2B,CAAC;AACrF;",
6
- "names": ["error", "message", "error", "dirname", "path", "path", "error", "result", "fs", "message", "util", "message", "util", "util", "chalk", "trace", "fs", "path", "path", "fs", "cached", "path", "fs", "ECRDescribeImagesCommand", "result", "partition", "os", "import_credential_providers", "import_util", "import_util", "Mode", "import_util", "path", "os", "path", "import_cloud_assembly_schema", "import_cx_api", "fs", "chalk", "import_cx_api", "import_cdk_assets", "import_util", "import_cx_api", "import_client_cloudformation", "import_cdk_assets", "path", "fs", "path", "util", "import_cx_api", "import_client_s3", "import_middleware_endpoint", "chalk", "path", "fs", "util", "uuid", "util", "import_client_cloudformation", "_StackStatus", "RollbackChoice", "result", "result", "import_util", "chalk", "uuid", "path", "cxschema", "cxapi", "chalk", "HotswapMode", "import_util", "chalk", "error", "archiver", "resolve", "result", "error", "path", "fs", "semver", "path", "fs", "trace", "resolve", "cached", "import_util", "chalk", "bootstrapStack", "result", "import_cx_api", "suffixWithErrors", "partition", "request", "path", "import_util", "cxapi", "fs", "chalk", "import_cx_api", "message", "ExtendedStackSelection", "result", "StackSelectionStrategy", "ExpandStackSelection", "os", "fs", "path", "import_node_util", "import_stream", "cxschema", "chalk", "RequireApproval", "path", "chalk", "promptly", "chalk", "resolve", "pLimit", "error", "message", "result", "util", "chalk", "uuid", "import_util", "chalk", "fs", "promptly", "result", "message", "prompt", "chalk", "fs", "path", "fs", "DeploymentState", "error", "path", "cxapi", "import_cdk_assets", "cxschema", "cxapi", "import_client_cloudcontrol", "isObject", "result", "import_cx_api", "import_cx_api", "flatMap", "flatMap", "message"]
3
+ "sources": ["shared-private.ts", "../../../tmp-toolkit-helpers/src/api/io/private/span.ts", "../../../tmp-toolkit-helpers/src/util/archive.ts", "../../../tmp-toolkit-helpers/src/util/format-error.ts", "../../../tmp-toolkit-helpers/src/util/arrays.ts", "../../../tmp-toolkit-helpers/src/util/bytes.ts", "../../../tmp-toolkit-helpers/src/util/cloudformation.ts", "../../../tmp-toolkit-helpers/src/util/content-hash.ts", "../../../tmp-toolkit-helpers/src/util/directories.ts", "../../../tmp-toolkit-helpers/src/api/toolkit-error.ts", "../../../tmp-toolkit-helpers/src/util/json.ts", "../../../tmp-toolkit-helpers/src/util/types.ts", "../../../tmp-toolkit-helpers/src/util/objects.ts", "../../../tmp-toolkit-helpers/src/util/parallel.ts", "../../../tmp-toolkit-helpers/src/util/serialize.ts", "../../../tmp-toolkit-helpers/src/util/yaml-cfn.ts", "../../../tmp-toolkit-helpers/src/util/string-manipulation.ts", "../../../tmp-toolkit-helpers/src/util/version-range.ts", "../../../tmp-toolkit-helpers/src/api/io/private/io-helper.ts", "../../../tmp-toolkit-helpers/src/api/io/private/level-priority.ts", "../../../tmp-toolkit-helpers/src/api/io/private/message-maker.ts", "../../../tmp-toolkit-helpers/src/api/io/private/messages.ts", "../../../tmp-toolkit-helpers/src/api/io/private/io-default-messages.ts", "../../../tmp-toolkit-helpers/src/private/activity-printer/base.ts", "../../../tmp-toolkit-helpers/src/private/activity-printer/history.ts", "../../../tmp-toolkit-helpers/src/private/activity-printer/current.ts", "../../../tmp-toolkit-helpers/src/private/activity-printer/display.ts", "../../../tmp-toolkit-helpers/src/api/aws-auth/proxy-agent.ts", "../../../tmp-toolkit-helpers/src/api/aws-auth/sdk.ts", "../../../tmp-toolkit-helpers/src/api/aws-auth/account-cache.ts", "../../../tmp-toolkit-helpers/src/api/aws-auth/cached.ts", "../../../tmp-toolkit-helpers/src/api/aws-auth/tracing.ts", "../../../tmp-toolkit-helpers/src/api/aws-auth/user-agent.ts", "../../../tmp-toolkit-helpers/src/api/aws-auth/util.ts", "../../../tmp-toolkit-helpers/src/api/aws-auth/sdk-provider.ts", "../../../tmp-toolkit-helpers/src/api/aws-auth/awscli-compatible.ts", "../../../tmp-toolkit-helpers/src/api/aws-auth/provider-caching.ts", "../../../tmp-toolkit-helpers/src/api/aws-auth/credential-plugins.ts", "../../../tmp-toolkit-helpers/src/api/plugin/plugin.ts", "../../../tmp-toolkit-helpers/src/api/plugin/context-provider-plugin.ts", "../../../tmp-toolkit-helpers/src/api/plugin/mode.ts", "../../../tmp-toolkit-helpers/src/api/aws-auth/sdk-logger.ts", "../../../tmp-toolkit-helpers/src/api/bootstrap/bootstrap-environment.ts", "../../../tmp-toolkit-helpers/src/api/bootstrap/deploy-bootstrap.ts", "../../../tmp-toolkit-helpers/src/api/bootstrap/bootstrap-props.ts", "../../../tmp-toolkit-helpers/src/api/deployments/deployments.ts", "../../../tmp-toolkit-helpers/src/api/deployments/asset-manifest-builder.ts", "../../../tmp-toolkit-helpers/src/api/deployments/asset-publishing.ts", "../../../tmp-toolkit-helpers/src/api/deployments/cfn-api.ts", "../../../tmp-toolkit-helpers/src/api/resource-metadata/resource-metadata.ts", "../../../tmp-toolkit-helpers/src/api/cloudformation/evaluate-cloudformation-template.ts", "../../../tmp-toolkit-helpers/src/api/cloudformation/template-body-parameter.ts", "../../../tmp-toolkit-helpers/src/api/cloudformation/nested-stack-helpers.ts", "../../../tmp-toolkit-helpers/src/api/stack-events/stack-activity-monitor.ts", "../../../tmp-toolkit-helpers/src/api/stack-events/stack-event-poller.ts", "../../../tmp-toolkit-helpers/src/api/stack-events/stack-progress-monitor.ts", "../../../tmp-toolkit-helpers/src/api/stack-events/stack-status.ts", "../../../tmp-toolkit-helpers/src/api/cloudformation/stack-helpers.ts", "../../../tmp-toolkit-helpers/src/api/deployments/checks.ts", "../../../tmp-toolkit-helpers/src/api/deployments/deploy-stack.ts", "../../../tmp-toolkit-helpers/src/api/deployments/assets.ts", "../../../tmp-toolkit-helpers/src/api/hotswap/common.ts", "../../../tmp-toolkit-helpers/src/api/hotswap/hotswap-deployments.ts", "../../../tmp-toolkit-helpers/src/api/deployments/deployment-result.ts", "../../../tmp-toolkit-helpers/src/api/hotswap/appsync-mapping-templates.ts", "../../../tmp-toolkit-helpers/src/api/hotswap/code-build-projects.ts", "../../../tmp-toolkit-helpers/src/api/hotswap/ecs-services.ts", "../../../tmp-toolkit-helpers/src/api/hotswap/lambda-functions.ts", "../../../tmp-toolkit-helpers/src/api/hotswap/s3-bucket-deployments.ts", "../../../tmp-toolkit-helpers/src/api/hotswap/stepfunctions-state-machines.ts", "../../../tmp-toolkit-helpers/src/api/notices.ts", "../../../tmp-toolkit-helpers/src/api/tree.ts", "../../../tmp-toolkit-helpers/src/api/toolkit-info.ts", "../../../tmp-toolkit-helpers/src/api/environment/environment-resources.ts", "../../../tmp-toolkit-helpers/src/api/environment/placeholders.ts", "../../../tmp-toolkit-helpers/src/api/environment/environment-access.ts", "../../../tmp-toolkit-helpers/src/api/bootstrap/legacy-template.ts", "../../../tmp-toolkit-helpers/src/api/cloud-assembly/environment.ts", "../../../tmp-toolkit-helpers/src/api/cloud-assembly/stack-assembly.ts", "../../../tmp-toolkit-helpers/src/api/cloud-assembly/stack-collection.ts", "../../../tmp-toolkit-helpers/src/api/cloud-assembly/stack-selector.ts", "../../../tmp-toolkit-helpers/src/api/settings.ts", "../../../tmp-toolkit-helpers/src/api/context.ts", "../../../tmp-toolkit-helpers/src/api/diff/diff-formatter.ts", "../../../tmp-toolkit-helpers/src/api/require-approval.ts", "../../../tmp-toolkit-helpers/src/api/streams.ts", "../../../tmp-toolkit-helpers/src/api/garbage-collection/garbage-collector.ts", "../../../tmp-toolkit-helpers/src/api/garbage-collection/progress-printer.ts", "../../../tmp-toolkit-helpers/src/api/garbage-collection/stack-refresh.ts", "../../../tmp-toolkit-helpers/src/api/logs-monitor/logs-monitor.ts", "../../../tmp-toolkit-helpers/src/api/logs-monitor/find-cloudwatch-logs.ts", "../../../tmp-toolkit-helpers/src/api/refactoring/index.ts", "../../../tmp-toolkit-helpers/src/api/refactoring/digest.ts", "../../../tmp-toolkit-helpers/src/api/resource-import/importer.ts", "../../../tmp-toolkit-helpers/src/api/resource-import/migrator.ts", "../../../tmp-toolkit-helpers/src/api/rwlock.ts", "../../../tmp-toolkit-helpers/src/api/work-graph/work-graph-types.ts", "../../../tmp-toolkit-helpers/src/api/work-graph/work-graph.ts", "../../../tmp-toolkit-helpers/src/api/work-graph/work-graph-builder.ts", "../../../tmp-toolkit-helpers/src/api/tags.ts", "../../../tmp-toolkit-helpers/src/context-providers/index.ts", "../../../tmp-toolkit-helpers/src/context-providers/ami.ts", "../../../tmp-toolkit-helpers/src/context-providers/availability-zones.ts", "../../../tmp-toolkit-helpers/src/context-providers/cc-api-provider.ts", "../../../tmp-toolkit-helpers/src/context-providers/endpoint-service-availability-zones.ts", "../../../tmp-toolkit-helpers/src/context-providers/hosted-zones.ts", "../../../tmp-toolkit-helpers/src/context-providers/keys.ts", "../../../tmp-toolkit-helpers/src/context-providers/load-balancers.ts", "../../../tmp-toolkit-helpers/src/context-providers/security-groups.ts", "../../../tmp-toolkit-helpers/src/context-providers/ssm-parameters.ts", "../../../tmp-toolkit-helpers/src/context-providers/vpcs.ts"],
4
+ "sourcesContent": ["/* eslint-disable import/no-restricted-paths */\n\nexport * from '../../../tmp-toolkit-helpers/src/api/io/private';\nexport * from '../../../tmp-toolkit-helpers/src/private';\nexport * from '../../../tmp-toolkit-helpers/src/api';\nexport * as cfnApi from '../../../tmp-toolkit-helpers/src/api/deployments/cfn-api';\n\n// Context Providers\nexport * as contextproviders from '../../../tmp-toolkit-helpers/src/context-providers';\n", "import * as util from 'node:util';\nimport * as uuid from 'uuid';\nimport type { ActionLessMessage, IoHelper } from './io-helper';\nimport type { IoMessageMaker } from './message-maker';\nimport type { Duration } from '../../../payloads/types';\nimport { formatTime } from '../../../util';\n\nexport interface SpanEnd {\n readonly duration: number;\n}\n\n/**\n * Describes a specific span\n *\n * A span definition is a pair of `IoMessageMaker`s to create a start and end message of the span respectively.\n * It also has a display name, that is used for auto-generated message text when they are not provided.\n */\nexport interface SpanDefinition<S extends object, E extends SpanEnd> {\n readonly name: string;\n readonly start: IoMessageMaker<S>;\n readonly end: IoMessageMaker<E>;\n}\n\n/**\n * Used in conditional types to check if a type (e.g. after omitting fields) is an empty object\n * This is needed because counter-intuitive neither `object` nor `{}` represent that.\n */\ntype EmptyObject = {\n [index: string | number | symbol]: never;\n}\n\n/**\n * Helper type to force a parameter to be not present of the computed type is an empty object\n */\ntype VoidWhenEmpty<T> = T extends EmptyObject ? void : T\n\n/**\n * Helper type to force a parameter to be an empty object if the computed type is an empty object\n * This is weird, but some computed types (e.g. using `Omit`) don't end up enforcing this.\n */\ntype ForceEmpty<T> = T extends EmptyObject ? EmptyObject : T\n\n/**\n * Make some properties optional\n */\ntype Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>;\n\n/**\n * Ending the span returns the observed duration\n */\ninterface ElapsedTime {\n readonly asMs: number;\n readonly asSec: number;\n}\n\n/**\n * A message span that can be ended and read times from\n */\nexport interface IMessageSpan<E extends SpanEnd> {\n /**\n * Get the time elapsed since the start\n */\n elapsedTime(): Promise<ElapsedTime>;\n /**\n * Sends a simple, generic message with the current timing\n * For more complex intermediate messages, get the `elapsedTime` and use `notify`\n */\n timing(maker: IoMessageMaker<Duration>, message?: string): Promise<ElapsedTime>;\n /**\n * Sends an arbitrary intermediate message as part of the span\n */\n notify(message: ActionLessMessage<unknown>): Promise<void>;\n /**\n * End the span with a payload\n */\n end(payload: VoidWhenEmpty<Omit<E, keyof SpanEnd>>): Promise<ElapsedTime>;\n /**\n * End the span with a payload, overwriting\n */\n end(payload: VoidWhenEmpty<Optional<E, keyof SpanEnd>>): Promise<ElapsedTime>;\n /**\n * End the span with a message and payload\n */\n end(message: string, payload: ForceEmpty<Optional<E, keyof SpanEnd>>): Promise<ElapsedTime>;\n}\n\n/**\n * Helper class to make spans around blocks of work\n *\n * Blocks are enclosed by a start and end message.\n * All messages of the span share a unique id.\n * The end message contains the time passed between start and end.\n */\nexport class SpanMaker<S extends object, E extends SpanEnd> {\n private readonly definition: SpanDefinition<S, E>;\n private readonly ioHelper: IoHelper;\n\n public constructor(ioHelper: IoHelper, definition: SpanDefinition<S, E>) {\n this.definition = definition;\n this.ioHelper = ioHelper;\n }\n\n /**\n * Starts the span and initially notifies the IoHost\n * @returns a message span\n */\n public async begin(payload: VoidWhenEmpty<S>): Promise<IMessageSpan<E>>;\n public async begin(message: string, payload: S): Promise<IMessageSpan<E>>;\n public async begin(a: any, b?: S): Promise<IMessageSpan<E>> {\n const spanId = uuid.v4();\n const startTime = new Date().getTime();\n\n const notify = (msg: ActionLessMessage<unknown>): Promise<void> => {\n return this.ioHelper.notify(withSpanId(spanId, msg));\n };\n\n const startInput = parseArgs<S>(a, b);\n const startMsg = startInput.message ?? `Starting ${this.definition.name} ...`;\n const startPayload = startInput.payload;\n\n await notify(this.definition.start.msg(\n startMsg,\n startPayload,\n ));\n\n const timingMsgTemplate = '\\n\u2728 %s time: %ds\\n';\n const time = () => {\n const elapsedTime = new Date().getTime() - startTime;\n return {\n asMs: elapsedTime,\n asSec: formatTime(elapsedTime),\n };\n };\n\n return {\n elapsedTime: async (): Promise<ElapsedTime> => {\n return time();\n },\n\n notify: async(msg: ActionLessMessage<unknown>): Promise<void> => {\n await notify(msg);\n },\n\n timing: async(maker: IoMessageMaker<Duration>, message?: string): Promise<ElapsedTime> => {\n const duration = time();\n const timingMsg = message ? message : util.format(timingMsgTemplate, this.definition.name, duration.asSec);\n await notify(maker.msg(timingMsg, {\n duration: duration.asMs,\n }));\n return duration;\n },\n\n end: async (x: any, y?: ForceEmpty<Optional<E, keyof SpanEnd>>): Promise<ElapsedTime> => {\n const duration = time();\n\n const endInput = parseArgs<ForceEmpty<Optional<E, keyof SpanEnd>>>(x, y);\n const endMsg = endInput.message ?? util.format(timingMsgTemplate, this.definition.name, duration.asSec);\n const endPayload = endInput.payload;\n\n await notify(this.definition.end.msg(\n endMsg, {\n duration: duration.asMs,\n ...endPayload,\n } as E));\n\n return duration;\n },\n };\n }\n}\n\nfunction parseArgs<S extends object>(first: any, second?: S): { message: string | undefined; payload: S } {\n const firstIsMessage = typeof first === 'string';\n\n // When the first argument is a string or we have a second argument, then the first arg is the message\n const message = (firstIsMessage || second) ? first : undefined;\n\n // When the first argument is a string or we have a second argument,\n // then the second arg is the payload, otherwise the first arg is the payload\n const payload = (firstIsMessage || second) ? second : first;\n\n return {\n message,\n payload,\n };\n}\n\nfunction withSpanId(span: string, message: ActionLessMessage<unknown>): ActionLessMessage<unknown> {\n return {\n ...message,\n span,\n };\n}\n", "import { error } from 'console';\nimport { createWriteStream, promises as fs } from 'fs';\nimport * as path from 'path';\nimport * as glob from 'glob';\nimport { formatErrorMessage } from './format-error';\n\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nconst archiver = require('archiver');\n\n// Adapted from cdk-assets\nexport async function zipDirectory(directory: string, outputFile: string): Promise<void> {\n // We write to a temporary file and rename at the last moment. This is so that if we are\n // interrupted during this process, we don't leave a half-finished file in the target location.\n const temporaryOutputFile = `${outputFile}.${randomString()}._tmp`;\n await writeZipFile(directory, temporaryOutputFile);\n await moveIntoPlace(temporaryOutputFile, outputFile);\n}\n\nfunction writeZipFile(directory: string, outputFile: string): Promise<void> {\n return new Promise(async (ok, fail) => {\n // The below options are needed to support following symlinks when building zip files:\n // - nodir: This will prevent symlinks themselves from being copied into the zip.\n // - follow: This will follow symlinks and copy the files within.\n const globOptions = {\n dot: true,\n nodir: true,\n follow: true,\n cwd: directory,\n };\n const files = glob.sync('**', globOptions); // The output here is already sorted\n\n const output = createWriteStream(outputFile);\n\n const archive = archiver('zip');\n archive.on('warning', fail);\n archive.on('error', fail);\n\n // archive has been finalized and the output file descriptor has closed, resolve promise\n // this has to be done before calling `finalize` since the events may fire immediately after.\n // see https://www.npmjs.com/package/archiver\n output.once('close', ok);\n\n archive.pipe(output);\n\n // Append files serially to ensure file order\n for (const file of files) {\n const fullPath = path.resolve(directory, file);\n // Exactly 2 promises\n // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism\n const [data, stat] = await Promise.all([fs.readFile(fullPath), fs.stat(fullPath)]);\n archive.append(data, {\n name: file,\n mode: stat.mode,\n });\n }\n\n await archive.finalize();\n });\n}\n\n/**\n * Rename the file to the target location, taking into account:\n *\n * - That we may see EPERM on Windows while an Antivirus scanner still has the\n * file open, so retry a couple of times.\n * - This same function may be called in parallel and be interrupted at any point.\n */\nasync function moveIntoPlace(source: string, target: string) {\n let delay = 100;\n let attempts = 5;\n while (true) {\n try {\n // 'rename' is guaranteed to overwrite an existing target, as long as it is a file (not a directory)\n await fs.rename(source, target);\n return;\n } catch (e: any) {\n if (e.code !== 'EPERM' || attempts-- <= 0) {\n throw e;\n }\n error(formatErrorMessage(e));\n await sleep(Math.floor(Math.random() * delay));\n delay *= 2;\n }\n }\n}\n\nfunction sleep(ms: number) {\n return new Promise(ok => setTimeout(ok, ms));\n}\n\nfunction randomString() {\n return Math.random().toString(36).replace(/[^a-z0-9]+/g, '');\n}\n", "/**\n * Takes in an error and returns a correctly formatted string of its error message.\n * If it is an AggregateError, it will return a string with all the inner errors\n * formatted and separated by a newline.\n *\n * @param error The error to format\n * @returns A string with the error message(s) of the error\n */\nexport function formatErrorMessage(error: any): string {\n if (error && Array.isArray(error.errors)) {\n const innerMessages = error.errors\n .map((innerError: { message: any; toString: () => any }) => (innerError?.message || innerError?.toString()))\n .join('\\n');\n return `AggregateError: ${innerMessages}`;\n }\n\n // Fallback for regular Error or other types\n return error?.message || error?.toString() || 'Unknown error';\n}\n", "/**\n * Map a function over an array and concatenate the results\n */\nexport function flatMap<T, U>(xs: T[], fn: ((x: T, i: number) => U[])): U[] {\n return flatten(xs.map(fn));\n}\n\n/**\n * Flatten a list of lists into a list of elements\n */\nexport function flatten<T>(xs: T[][]): T[] {\n return Array.prototype.concat.apply([], xs);\n}\n\n/**\n * Partition a collection by removing and returning all elements that match a predicate\n *\n * Note: the input collection is modified in-place!\n */\nexport function partition<T>(collection: T[], pred: (x: T) => boolean): T[] {\n const ret: T[] = [];\n let i = 0;\n while (i < collection.length) {\n if (pred(collection[i])) {\n ret.push(collection.splice(i, 1)[0]);\n } else {\n i++;\n }\n }\n return ret;\n}\n", "/**\n * Format bytes as a human readable string\n *\n * @param bytes Number of bytes to format\n * @param decimals Number of decimal places to show (default 2)\n * @returns Formatted string with appropriate unit suffix\n */\nexport function formatBytes(bytes: number, decimals: number = 2): string {\n decimals = decimals < 0 ? 0 : decimals;\n\n if (bytes === 0) {\n return '0 Bytes';\n }\n\n const k = 1024;\n const sizes = ['Bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];\n\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n\n return `${parseFloat((bytes / Math.pow(k, i)).toFixed(decimals))} ${sizes[i]}`;\n}\n", "/**\n * Validate SNS topic arn\n */\nexport function validateSnsTopicArn(arn: string): boolean {\n return /^arn:aws:sns:[a-z0-9\\-]+:[0-9]+:[a-z0-9\\-\\_]+$/i.test(arn);\n}\n\n/**\n * Does a Stack Event have an error message based on the status.\n */\nexport function stackEventHasErrorMessage(status: string): boolean {\n return status.endsWith('_FAILED') || status === 'ROLLBACK_IN_PROGRESS' || status === 'UPDATE_ROLLBACK_IN_PROGRESS';\n}\n\n/**\n * Calculate the maximal length of all resource types for a given template.\n *\n * @param template the stack template to analyze\n * @param startWidth the initial width to start with. Defaults to the length of 'AWS::CloudFormation::Stack'.\n * @returns the determined width\n */\nexport function maxResourceTypeLength(template: any, startWidth = 'AWS::CloudFormation::Stack'.length): number {\n const resources = (template && template.Resources) || {};\n let maxWidth = startWidth;\n for (const id of Object.keys(resources)) {\n const type = resources[id].Type || '';\n if (type.length > maxWidth) {\n maxWidth = type.length;\n }\n }\n return maxWidth;\n}\n", "import * as crypto from 'crypto';\n\nexport function contentHash(data: string | Buffer | DataView) {\n return crypto.createHash('sha256').update(data).digest('hex');\n}\n\n/**\n * A stably sorted hash of an arbitrary JS object\n */\nexport function contentHashAny(value: unknown) {\n const ret = crypto.createHash('sha256');\n recurse(value);\n return ret.digest('hex');\n\n function recurse(x: unknown) {\n if (typeof x === 'string') {\n ret.update(x);\n return;\n }\n\n if (Array.isArray(x)) {\n ret.update('[');\n for (const e of x) {\n recurse(e);\n ret.update('||');\n }\n ret.update(']');\n return;\n }\n\n if (x && typeof x === 'object') {\n ret.update('{');\n for (const key of Object.keys(x).sort()) {\n ret.update(key);\n ret.update(':');\n recurse((x as any)[key]);\n }\n ret.update('}');\n return;\n }\n\n ret.update(`${x}${typeof x}`); // typeof to make sure hash('123') !== hash(123)\n }\n}\n", "import * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\nimport { ToolkitError } from '../api/toolkit-error';\n\n/**\n * Return a location that will be used as the CDK home directory.\n * Currently the only thing that is placed here is the cache.\n *\n * First try to use the users home directory (i.e. /home/someuser/),\n * but if that directory does not exist for some reason create a tmp directory.\n *\n * Typically it wouldn't make sense to create a one time use tmp directory for\n * the purpose of creating a cache, but since this only applies to users that do\n * not have a home directory (some CI systems?) this should be fine.\n */\nexport function cdkHomeDir() {\n const tmpDir = fs.realpathSync(os.tmpdir());\n let home;\n try {\n let userInfoHome: string | undefined = os.userInfo().homedir;\n // Node returns this if the user doesn't have a home directory\n /* c8 ignore start */ // will not happen in normal setups\n if (userInfoHome == '/var/empty') {\n userInfoHome = undefined;\n }\n /* c8 ignore stop */\n home = path.join((userInfoHome ?? os.homedir()).trim(), '.cdk');\n } catch {\n }\n return process.env.CDK_HOME\n ? path.resolve(process.env.CDK_HOME)\n : home || fs.mkdtempSync(path.join(tmpDir, '.cdk')).trim();\n}\n\nexport function cdkCacheDir() {\n return path.join(cdkHomeDir(), 'cache');\n}\n\n/**\n * From the start location, find the directory that contains the bundled package's package.json\n *\n * You must assume the caller of this function will be bundled and the package root dir\n * is not going to be the same as the package the caller currently lives in.\n */\nexport function bundledPackageRootDir(start: string): string;\nexport function bundledPackageRootDir(start: string, fail: true): string;\nexport function bundledPackageRootDir(start: string, fail: false): string | undefined;\nexport function bundledPackageRootDir(start: string, fail?: boolean) {\n function _rootDir(dirname: string): string | undefined {\n const manifestPath = path.join(dirname, 'package.json');\n if (fs.existsSync(manifestPath)) {\n return dirname;\n }\n if (path.dirname(dirname) === dirname) {\n if (fail ?? true) {\n throw new ToolkitError('Unable to find package manifest');\n }\n return undefined;\n }\n return _rootDir(path.dirname(dirname));\n }\n\n return _rootDir(start);\n}\n", "import type * as cxapi from '@aws-cdk/cx-api';\n\nconst TOOLKIT_ERROR_SYMBOL = Symbol.for('@aws-cdk/toolkit-lib.ToolkitError');\nconst AUTHENTICATION_ERROR_SYMBOL = Symbol.for('@aws-cdk/toolkit-lib.AuthenticationError');\nconst ASSEMBLY_ERROR_SYMBOL = Symbol.for('@aws-cdk/toolkit-lib.AssemblyError');\nconst CONTEXT_PROVIDER_ERROR_SYMBOL = Symbol.for('@aws-cdk/toolkit-lib.ContextProviderError');\n\n/**\n * Represents a general toolkit error in the AWS CDK Toolkit.\n */\nexport class ToolkitError extends Error {\n /**\n * Determines if a given error is an instance of ToolkitError.\n */\n public static isToolkitError(x: any): x is ToolkitError {\n return x !== null && typeof(x) === 'object' && TOOLKIT_ERROR_SYMBOL in x;\n }\n\n /**\n * Determines if a given error is an instance of AuthenticationError.\n */\n public static isAuthenticationError(x: any): x is AuthenticationError {\n return this.isToolkitError(x) && AUTHENTICATION_ERROR_SYMBOL in x;\n }\n\n /**\n * Determines if a given error is an instance of AssemblyError.\n */\n public static isAssemblyError(x: any): x is AssemblyError {\n return this.isToolkitError(x) && ASSEMBLY_ERROR_SYMBOL in x;\n }\n\n /**\n * Determines if a given error is an instance of AssemblyError.\n */\n public static isContextProviderError(x: any): x is ContextProviderError {\n return this.isToolkitError(x) && CONTEXT_PROVIDER_ERROR_SYMBOL in x;\n }\n\n /**\n * An AssemblyError with an original error as cause\n */\n public static withCause(message: string, error: unknown): ToolkitError {\n return new ToolkitError(message, 'toolkit', error);\n }\n\n /**\n * The type of the error, defaults to \"toolkit\".\n */\n public readonly type: string;\n\n /**\n * Denotes the source of the error as the toolkit.\n */\n public readonly source: 'toolkit' | 'user';\n\n /**\n * The specific original cause of the error, if available\n */\n public readonly cause?: unknown;\n\n constructor(message: string, type: string = 'toolkit', cause?: unknown) {\n super(message);\n Object.setPrototypeOf(this, ToolkitError.prototype);\n Object.defineProperty(this, TOOLKIT_ERROR_SYMBOL, { value: true });\n this.name = new.target.name;\n this.type = type;\n this.source = 'toolkit';\n this.cause = cause;\n }\n}\n\n/**\n * Represents an authentication-specific error in the AWS CDK Toolkit.\n */\nexport class AuthenticationError extends ToolkitError {\n /**\n * Denotes the source of the error as user.\n */\n public readonly source = 'user';\n\n constructor(message: string) {\n super(message, 'authentication');\n Object.setPrototypeOf(this, AuthenticationError.prototype);\n Object.defineProperty(this, AUTHENTICATION_ERROR_SYMBOL, { value: true });\n }\n}\n\n/**\n * Represents an error causes by cloud assembly synthesis\n *\n * This includes errors thrown during app execution, as well as failing annotations.\n */\nexport class AssemblyError extends ToolkitError {\n /**\n * An AssemblyError with an original error as cause\n */\n public static withCause(message: string, error: unknown): AssemblyError {\n return new AssemblyError(message, undefined, error);\n }\n\n /**\n * An AssemblyError with a list of stacks as cause\n */\n public static withStacks(message: string, stacks?: cxapi.CloudFormationStackArtifact[]): AssemblyError {\n return new AssemblyError(message, stacks);\n }\n\n /**\n * Denotes the source of the error as user.\n */\n public readonly source = 'user';\n\n /**\n * The stacks that caused the error, if available\n *\n * The `messages` property of each `cxapi.CloudFormationStackArtifact` will contain the respective errors.\n * Absence indicates synthesis didn't fully complete.\n */\n public readonly stacks?: cxapi.CloudFormationStackArtifact[];\n\n private constructor(message: string, stacks?: cxapi.CloudFormationStackArtifact[], cause?: unknown) {\n super(message, 'assembly', cause);\n Object.setPrototypeOf(this, AssemblyError.prototype);\n Object.defineProperty(this, ASSEMBLY_ERROR_SYMBOL, { value: true });\n this.stacks = stacks;\n }\n}\n\n/**\n * Represents an error originating from a Context Provider\n */\nexport class ContextProviderError extends ToolkitError {\n /**\n * Denotes the source of the error as user.\n */\n public readonly source = 'user';\n\n constructor(message: string) {\n super(message, 'context-provider');\n Object.setPrototypeOf(this, ContextProviderError.prototype);\n Object.defineProperty(this, CONTEXT_PROVIDER_ERROR_SYMBOL, { value: true });\n }\n}\n", "/**\n * This gets the values of the jsonObject at the paths specified in propertiesToReturn.\n *\n * For example, jsonObject = {\n * key1: 'abc',\n * key2: {\n * foo: 'qwerty',\n * bar: 'data',\n * }\n * }\n *\n * propertiesToReturn = ['key1', 'key2.foo'];\n *\n * The returned object is:\n *\n * ```\n * {\n * key1: 'abc',\n * 'key2.foo': 'qwerty',\n * Identifier: identifier\n * }\n * ```\n */\nexport function getResultObj(jsonObject: any, identifier: string, propertiesToReturn: string[]): {[key: string]: any} {\n const propsObj = {};\n propertiesToReturn.forEach((propName) => {\n Object.assign(propsObj, { [propName]: findJsonValue(jsonObject, propName) });\n });\n Object.assign(propsObj, { ['Identifier']: identifier });\n return propsObj;\n}\n\n/**\n * This finds the value of the jsonObject at the path. Path is delimited by '.'.\n *\n * For example, jsonObject = {\n * key1: 'abc',\n * key2: {\n * foo: 'qwerty',\n * bar: 'data',\n * }\n * }\n *\n * If path is 'key1', then it will return 'abc'.\n * If path is 'key2.foo', then it will return 'qwerty'.\n * If path is 'key2', then it will return the object:\n * {\n * foo: 'qwerty',\n * bar: 'data',\n * }\n *\n * If the path is not found, an Error will be thrown stating which token is missing.\n */\nexport function findJsonValue(jsonObject: any, path: string): any {\n const paths = path.split('.');\n let obj = jsonObject;\n paths.forEach(p => {\n obj = obj[p];\n if (obj === undefined) {\n throw new TypeError(`Cannot read field ${path}. ${p} is not found.`);\n }\n });\n return obj;\n}\n", "/**\n * Type of a map mapping strings to some arbitrary type\n *\n * Name is not ideal, but:\n *\n * - Cannot call it Object, that already means something.\n * - Cannot call it Dict or Dictionary, since in other languages\n * those also allow specifying the key type.\n */\nexport type Obj<T> = {[key: string]: T};\n\n/**\n * Return whether the given value is an object\n *\n * Even though arrays technically are objects, we usually want to treat them differently,\n * so we return false in those cases.\n */\nexport function isObject(x: any): x is Obj<any> {\n return x !== null && typeof x === 'object' && !isArray(x);\n}\n\n/**\n * Return whether the given value is an array\n */\nexport const isArray = Array.isArray;\n\n/**\n * Return the value of the first argument if it's not undefined, otherwise the default\n */\nexport function ifDefined<T>(x: T | undefined, def: T): T {\n return typeof x !== 'undefined' ? x : def;\n}\n", "import type { Obj } from './types';\nimport { isArray, isObject } from './types';\nimport { ToolkitError } from '../api/toolkit-error';\n\n/**\n * Return a new object by adding missing keys into another object\n */\nexport function applyDefaults(hash: any, defaults: any) {\n const result: any = { };\n\n Object.keys(hash).forEach(k => result[k] = hash[k]);\n\n Object.keys(defaults)\n .filter(k => !(k in result))\n .forEach(k => result[k] = defaults[k]);\n\n return result;\n}\n\n/**\n * Return whether the given parameter is an empty object or empty list.\n */\nexport function isEmpty(x: any) {\n if (x == null) {\n return false;\n }\n if (isArray(x)) {\n return x.length === 0;\n }\n return Object.keys(x).length === 0;\n}\n\n/**\n * Deep clone a tree of objects, lists or scalars\n *\n * Does not support cycles.\n */\nexport function deepClone(x: any): any {\n if (typeof x === 'undefined') {\n return undefined;\n }\n if (x === null) {\n return null;\n }\n if (isArray(x)) {\n return x.map(deepClone);\n }\n if (isObject(x)) {\n return makeObject(mapObject(x, (k, v) => [k, deepClone(v)] as [string, any]));\n }\n return x;\n}\n\n/**\n * Map over an object, treating it as a dictionary\n */\nexport function mapObject<T, U>(x: Obj<T>, fn: (key: string, value: T) => U): U[] {\n const ret: U[] = [];\n Object.keys(x).forEach(key => {\n ret.push(fn(key, x[key]));\n });\n return ret;\n}\n\n/**\n * Construct an object from a list of (k, v) pairs\n */\nexport function makeObject<T>(pairs: Array<[string, T]>): Obj<T> {\n const ret: Obj<T> = {};\n for (const pair of pairs) {\n ret[pair[0]] = pair[1];\n }\n return ret;\n}\n\n/**\n * Deep get a value from a tree of nested objects\n *\n * Returns undefined if any part of the path was unset or\n * not an object.\n */\nexport function deepGet(x: any, path: string[]): any {\n path = path.slice();\n\n while (path.length > 0 && isObject(x)) {\n const key = path.shift()!;\n x = x[key];\n }\n return path.length === 0 ? x : undefined;\n}\n\n/**\n * Deep set a value in a tree of nested objects\n *\n * Throws an error if any part of the path is not an object.\n */\nexport function deepSet(x: any, path: string[], value: any) {\n path = path.slice();\n\n if (path.length === 0) {\n throw new ToolkitError('Path may not be empty');\n }\n\n while (path.length > 1 && isObject(x)) {\n const key = path.shift()!;\n\n if (isPrototypePollutingKey(key)) {\n continue;\n }\n\n if (!(key in x)) {\n x[key] = {};\n }\n x = x[key];\n }\n\n if (!isObject(x)) {\n throw new ToolkitError(`Expected an object, got '${x}'`);\n }\n\n const finalKey = path[0];\n\n if (isPrototypePollutingKey(finalKey)) {\n return;\n }\n\n if (value !== undefined) {\n x[finalKey] = value;\n } else {\n delete x[finalKey];\n }\n}\n\n/**\n * Helper to detect prototype polluting keys\n *\n * A key matching this, MUST NOT be used in an assignment.\n * Use this to check user-input.\n */\nfunction isPrototypePollutingKey(key: string) {\n return key === '__proto__' || key === 'constructor' || key === 'prototype';\n}\n\n/**\n * Recursively merge objects together\n *\n * The leftmost object is mutated and returned. Arrays are not merged\n * but overwritten just like scalars.\n *\n * If an object is merged into a non-object, the non-object is lost.\n */\nexport function deepMerge(...objects: Array<Obj<any> | undefined>) {\n function mergeOne(target: Obj<any>, source: Obj<any>) {\n for (const key of Object.keys(source)) {\n if (isPrototypePollutingKey(key)) {\n continue;\n }\n\n const value = source[key];\n\n if (isObject(value)) {\n if (!isObject(target[key])) {\n target[key] = {};\n } // Overwrite on purpose\n mergeOne(target[key], value);\n } else if (typeof value !== 'undefined') {\n target[key] = value;\n }\n }\n }\n\n const others = objects.filter(x => x != null) as Array<Obj<any>>;\n\n if (others.length === 0) {\n return {};\n }\n const into = others.splice(0, 1)[0];\n\n others.forEach(other => mergeOne(into, other));\n return into;\n}\n\n/**\n * Splits the given object into two, such that:\n *\n * 1. The size of the first object (after stringified in UTF-8) is less than or equal to the provided size limit.\n * 2. Merging the two objects results in the original one.\n */\nexport function splitBySize(data: any, maxSizeBytes: number): [any, any] {\n if (maxSizeBytes < 2) {\n // It's impossible to fit anything in the first object\n return [undefined, data];\n }\n const entries = Object.entries(data);\n return recurse(0, 0);\n\n function recurse(index: number, runningTotalSize: number): [any, any] {\n if (index >= entries.length) {\n // Everything fits in the first object\n return [data, undefined];\n }\n\n const size = runningTotalSize + entrySize(entries[index]);\n return (size > maxSizeBytes) ? cutAt(index) : recurse(index + 1, size);\n }\n\n function entrySize(entry: [string, unknown]) {\n return Buffer.byteLength(JSON.stringify(Object.fromEntries([entry])));\n }\n\n function cutAt(index: number): [any, any] {\n return [\n Object.fromEntries(entries.slice(0, index)),\n Object.fromEntries(entries.slice(index)),\n ];\n }\n}\n\ntype Exclude = { [key: string]: Exclude | true };\n\n/**\n * This function transforms all keys (recursively) in the provided `val` object.\n *\n * @param val The object whose keys need to be transformed.\n * @param transform The function that will be applied to each key.\n * @param exclude The keys that will not be transformed and copied to output directly\n * @returns A new object with the same values as `val`, but with all keys transformed according to `transform`.\n */\nexport function transformObjectKeys(val: any, transform: (str: string) => string, exclude: Exclude = {}): any {\n if (val == null || typeof val !== 'object') {\n return val;\n }\n if (Array.isArray(val)) {\n // For arrays we just pass parent's exclude object directly\n // since it makes no sense to specify different exclude options for each array element\n return val.map((input: any) => transformObjectKeys(input, transform, exclude));\n }\n const ret: { [k: string]: any } = {};\n for (const [k, v] of Object.entries(val)) {\n const childExclude = exclude[k];\n if (childExclude === true) {\n // we don't transform this object if the key is specified in exclude\n ret[transform(k)] = v;\n } else {\n ret[transform(k)] = transformObjectKeys(v, transform, childExclude);\n }\n }\n return ret;\n}\n", "/**\n * Run a number of promise generators with max parallelism\n *\n * Order is not maintained between the input and output.\n */\nexport async function parallelPromises<A>(n: number, promises: Array<() => Promise<A>>): Promise<Array<A>> {\n const ret = new Array<A>();\n let count = 0;\n let error: Error | undefined;\n const queue = [...promises];\n\n return new Promise((ok, ko) => {\n tick();\n\n function tick() {\n if (count === 0 && error) {\n ko(error);\n return;\n }\n if (count === 0 && queue.length === 0) {\n ok(ret);\n return;\n }\n\n while (count < n && queue.length > 0 && !error) {\n const next = queue.shift();\n if (next !== undefined) {\n start(next);\n }\n }\n }\n\n function start(fn: () => Promise<A>) {\n count += 1;\n fn()\n .then((result) => {\n ret.push(result);\n })\n .catch((e) => {\n error = e;\n })\n .finally(() => {\n count -= 1;\n tick();\n });\n }\n });\n}\n", "import * as fs from 'fs/promises';\nimport { formatBytes } from './bytes';\nimport * as yaml_cfn from './yaml-cfn';\n\n/**\n * Stringify to YAML\n */\nexport function toYAML(obj: any): string {\n return yaml_cfn.serialize(obj);\n}\n\n/**\n * Parse either YAML or JSON\n */\nexport function deserializeStructure(str: string): any {\n return yaml_cfn.deserialize(str);\n}\n\n/**\n * Serialize to either YAML or JSON\n */\nexport function serializeStructure(object: any, json: boolean) {\n if (json) {\n return JSON.stringify(object, undefined, 2);\n } else {\n return toYAML(object);\n }\n}\n\n/**\n * Load a YAML or JSON file from disk\n */\nexport async function loadStructuredFile(fileName: string) {\n const contents = await fs.readFile(fileName, { encoding: 'utf-8' });\n return deserializeStructure(contents);\n}\n\n/**\n * Remove any template elements that we don't want to show users.\n */\nexport function obscureTemplate(template: any = {}) {\n if (template.Rules) {\n // see https://github.com/aws/aws-cdk/issues/17942\n if (template.Rules.CheckBootstrapVersion) {\n if (Object.keys(template.Rules).length > 1) {\n delete template.Rules.CheckBootstrapVersion;\n } else {\n delete template.Rules;\n }\n }\n }\n\n return template;\n}\n\n/**\n * Detects a buffer that has been converted to a JSON-like object\n * In Node, `Buffer`s have `toJSON()` method that converts the buffer\n * into a JS object that can be JSON stringified.\n * Unfortunately this conversion happens before the replacer is called,\n * so normal means of detecting a `Buffer` objet don't work anymore.\n * @see https://github.com/nodejs/node-v0.x-archive/issues/5110\n */\nfunction isJsonBuffer(value: any): value is {\n type: 'Buffer';\n data: number[];\n} {\n return typeof value === 'object'\n && 'type' in value\n && value.type === 'Buffer'\n && 'data' in value\n && Array.isArray(value.data);\n}\n\n/**\n * A JSON.stringify() replacer that converts Buffers into a string with information\n * Use this if you plan to print out JSON stringified objects that may contain a Buffer.\n * Without this, large buffers (think: Megabytes) will completely fill up the output\n * and even crash the system.\n */\nexport function replacerBufferWithInfo(_key: any, value: any): any {\n if (isJsonBuffer(value)) {\n return `<Buffer: ${formatBytes(value.data.length)}>`;\n }\n return value;\n}\n", "import * as yaml from 'yaml';\nimport type * as yaml_cst from 'yaml/parse-cst';\nimport * as yaml_types from 'yaml/types';\n\n/**\n * Serializes the given data structure into valid YAML.\n *\n * @param obj the data structure to serialize\n * @returns a string containing the YAML representation of {@param obj}\n */\nexport function serialize(obj: any): string {\n const oldFold = yaml_types.strOptions.fold.lineWidth;\n try {\n yaml_types.strOptions.fold.lineWidth = 0;\n return yaml.stringify(obj, { schema: 'yaml-1.1' });\n } finally {\n yaml_types.strOptions.fold.lineWidth = oldFold;\n }\n}\n\n/**\n * Deserialize the YAML into the appropriate data structure.\n *\n * @param str the string containing YAML\n * @returns the data structure the YAML represents\n * (most often in case of CloudFormation, an object)\n */\nexport function deserialize(str: string): any {\n return parseYamlStrWithCfnTags(str);\n}\n\nfunction makeTagForCfnIntrinsic(intrinsicName: string, addFnPrefix: boolean): yaml_types.Schema.CustomTag {\n return {\n identify(value: any) {\n return typeof value === 'string';\n },\n tag: `!${intrinsicName}`,\n resolve: (_doc: yaml.Document, cstNode: yaml_cst.CST.Node) => {\n const ret: any = {};\n ret[addFnPrefix ? `Fn::${intrinsicName}` : intrinsicName] =\n // the +1 is to account for the ! the short form begins with\n parseYamlStrWithCfnTags(cstNode.toString().substring(intrinsicName.length + 1));\n return ret;\n },\n };\n}\n\nconst shortForms: yaml_types.Schema.CustomTag[] = [\n 'Base64', 'Cidr', 'FindInMap', 'GetAZs', 'ImportValue', 'Join', 'Sub',\n 'Select', 'Split', 'Transform', 'And', 'Equals', 'If', 'Not', 'Or', 'GetAtt',\n].map(name => makeTagForCfnIntrinsic(name, true)).concat(\n makeTagForCfnIntrinsic('Ref', false),\n makeTagForCfnIntrinsic('Condition', false),\n);\n\nfunction parseYamlStrWithCfnTags(text: string): any {\n return yaml.parse(text, {\n customTags: shortForms,\n schema: 'core',\n });\n}\n", "/**\n * Pad 's' on the left with 'char' until it is n characters wide\n */\nexport function padLeft(n: number, x: string, char: string = ' '): string {\n return char.repeat(Math.max(0, n - x.length)) + x;\n}\n\n/**\n * Pad 's' on the right with 'char' until it is n characters wide\n */\nexport function padRight(n: number, x: string, char: string = ' '): string {\n return x + char.repeat(Math.max(0, n - x.length));\n}\n\n/**\n * Formats time in milliseconds (which we get from 'Date.getTime()')\n * to a human-readable time; returns time in seconds rounded to 2\n * decimal places.\n */\nexport function formatTime(num: number): number {\n return roundPercentage(millisecondsToSeconds(num));\n}\n\n/**\n * Rounds a decimal number to two decimal points.\n * The function is useful for fractions that need to be outputted as percentages.\n */\nfunction roundPercentage(num: number): number {\n return Math.round(100 * num) / 100;\n}\n\n/**\n * Given a time in milliseconds, return an equivalent amount in seconds.\n */\nfunction millisecondsToSeconds(num: number): number {\n return num / 1000;\n}\n\n/**\n * This function lower cases the first character of the string provided.\n */\nexport function lowerCaseFirstCharacter(str: string): string {\n return str.length > 0 ? `${str[0].toLowerCase()}${str.slice(1)}` : str;\n}\n", "import * as semver from 'semver';\nimport { ToolkitError } from '../api/toolkit-error';\n\n// bracket - https://docs.oracle.com/middleware/1212/core/MAVEN/maven_version.htm#MAVEN401\n// pep - https://www.python.org/dev/peps/pep-0440/#version-specifiers\nexport type RangeType = 'bracket' | 'pep'\n\nexport function rangeFromSemver(ver: string, targetType: RangeType) {\n const re = ver.match(/^([^\\d]*)([\\d.]*)$/);\n if (!re || !semver.valid(re[2])) {\n throw new ToolkitError('not a semver or unsupported range syntax');\n }\n const prefixPart = re[1];\n const verPart = re[2];\n\n switch (targetType) {\n case 'bracket':\n switch (prefixPart) {\n case '':\n // if there's no prefix and the remaining is a valid semver, there's no range specified\n return ver;\n case '^':\n return `[${verPart},${semver.major(verPart)+1}.0.0)`;\n default:\n throw new ToolkitError(`unsupported range syntax - ${prefixPart}`);\n }\n case 'pep':\n switch (prefixPart) {\n case '':\n // if there's no prefix and the remaining is a valid semver, there's no range specified\n return `==${ver}`;\n case '^':\n return `>=${verPart},<${semver.major(verPart)+1}.0.0`;\n default:\n throw new ToolkitError(`unsupported range syntax - ${prefixPart}`);\n }\n }\n}\n", "import type { IIoHost } from '../io-host';\nimport type { IoMessage, IoRequest } from '../io-message';\nimport type { ToolkitAction } from '../toolkit-action';\nimport type { SpanEnd, SpanDefinition } from './span';\nimport { SpanMaker } from './span';\n\nexport type ActionLessMessage<T> = Omit<IoMessage<T>, 'action'>;\nexport type ActionLessRequest<T, U> = Omit<IoRequest<T, U>, 'action'>;\n\n/**\n * A class containing helper tools to interact with IoHost\n */\nexport class IoHelper implements IIoHost {\n public static fromIoHost(ioHost: IIoHost, action: ToolkitAction) {\n return new IoHelper(ioHost, action);\n }\n\n private readonly ioHost: IIoHost;\n private readonly action: ToolkitAction;\n\n private constructor(ioHost: IIoHost, action: ToolkitAction) {\n this.ioHost = ioHost;\n this.action = action;\n }\n\n /**\n * Forward a message to the IoHost, while injection the current action\n */\n public notify(msg: ActionLessMessage<unknown>): Promise<void> {\n return this.ioHost.notify({\n ...msg,\n action: this.action,\n });\n }\n\n /**\n * Forward a request to the IoHost, while injection the current action\n */\n public requestResponse<T, U>(msg: ActionLessRequest<T, U>): Promise<U> {\n return this.ioHost.requestResponse({\n ...msg,\n action: this.action,\n });\n }\n\n /**\n * Create a new marker from a given registry entry\n */\n public span<S extends object, E extends SpanEnd>(definition: SpanDefinition<S, E>) {\n return new SpanMaker(this, definition);\n }\n}\n\n/**\n * Wraps an IoHost and creates an IoHelper from it\n */\nexport function asIoHelper(ioHost: IIoHost, action: ToolkitAction): IoHelper {\n return IoHelper.fromIoHost(ioHost, action);\n}\n", "import type { IoMessageLevel } from '../';\n\n/**\n * Keep this list ordered from most to least verbose.\n * Every level \"includes\" all of the levels below it.\n * This is used to compare levels of messages to determine what should be logged.\n */\nconst levels = [\n 'trace',\n 'debug',\n 'info',\n 'warn',\n 'result',\n 'error',\n] as const;\n\n// compare levels helper\n// helper to convert the array into a map with numbers\nconst orderedLevels: Record<typeof levels[number], number> = Object.fromEntries(Object.entries(levels).map(a => a.reverse()));\nfunction compareFn(a: IoMessageLevel, b: IoMessageLevel): number {\n return orderedLevels[a] - orderedLevels[b];\n}\n\n/**\n * Determines if a message is relevant for the given log level.\n *\n * @param msg The message to compare.\n * @param level The level to compare against.\n * @returns true if the message is relevant for the given level.\n */\nexport function isMessageRelevantForLevel(msg: { level: IoMessageLevel}, level: IoMessageLevel): boolean {\n return compareFn(msg.level, level) >= 0;\n}\n\n", "import type { IoMessage, IoMessageCode, IoMessageLevel } from '../io-message';\nimport type { ActionLessMessage, ActionLessRequest } from './io-helper';\n\n/**\n * Information for each IO Message Code.\n */\ninterface CodeInfo {\n /**\n * The message code.\n */\n readonly code: IoMessageCode;\n\n /**\n * A brief description of the meaning of this IO Message.\n */\n readonly description: string;\n\n /**\n * The name of the payload interface, if applicable.\n * Some Io Messages include a payload, with a specific interface. The name of\n * the interface is specified here so that it can be linked with the message\n * when documentation is generated.\n *\n * The interface _must_ be exposed directly from toolkit-lib, so that it will\n * have a documentation page generated (that can be linked to).\n */\n readonly interface?: string;\n}\n\n/**\n * Information for each IO Message\n */\ninterface MessageInfo extends CodeInfo {\n /**\n * The message level\n */\n readonly level: IoMessageLevel;\n}\n\n/**\n * An interface that can produce messages for a specific code.\n */\nexport interface IoMessageMaker<T> extends MessageInfo {\n /**\n * Create a message for this code, with or without payload.\n */\n msg: [T] extends [AbsentData] ? (message: string) => ActionLessMessage<AbsentData> : (message: string, data: T) => ActionLessMessage<T>;\n\n /**\n * Returns whether the given `IoMessage` instance matches the current message definition\n */\n is(x: IoMessage<unknown>): x is IoMessage<T>;\n}\n\n/**\n * Produce an IoMessageMaker for the provided level and code info.\n */\nfunction message<T = AbsentData>(level: IoMessageLevel, details: CodeInfo): IoMessageMaker<T> {\n const maker = (text: string, data: T) => ({\n time: new Date(),\n level,\n code: details.code,\n message: text,\n data,\n } as ActionLessMessage<T>);\n\n return {\n ...details,\n level,\n msg: maker as any,\n is: (m): m is IoMessage<T> => m.code === details.code,\n };\n}\n\n/**\n * A type that is impossible for a user to replicate\n * This is used to ensure that results always have a proper type generic declared.\n */\ndeclare const privateKey: unique symbol;\nexport type ImpossibleType = {\n readonly [privateKey]: typeof privateKey;\n};\n\n// Create `IoMessageMaker`s for a given level and type check that calls with payload are using the correct interface\ntype CodeInfoMaybeInterface<T> = [T] extends [AbsentData] ? Omit<CodeInfo, 'interface'> : Required<CodeInfo>;\n\n/**\n * The type we use to represent an absent data field\n *\n * This is here to make it easy to change between `undefined`, `void`\n * and `never`.\n *\n * Not a lot of difference between `undefined` and `void`, but `void`\n * reads better.\n */\ntype AbsentData = void;\n\nexport const trace = <T = AbsentData>(details: CodeInfoMaybeInterface<T>) => message<T>('trace', details);\nexport const debug = <T = AbsentData>(details: CodeInfoMaybeInterface<T>) => message<T>('debug', details);\nexport const info = <T = AbsentData>(details: CodeInfoMaybeInterface<T>) => message<T>('info', details);\nexport const warn = <T = AbsentData>(details: CodeInfoMaybeInterface<T>) => message<T>('warn', details);\nexport const error = <T = AbsentData>(details: CodeInfoMaybeInterface<T>) => message<T>('error', details);\nexport const result = <T extends object = ImpossibleType>(details: Required<CodeInfo>) => message<T>('result', details);\n\ninterface RequestInfo<U> extends CodeInfo {\n readonly defaultResponse: U;\n}\n\n/**\n * An interface that can produce requests for a specific code.\n */\nexport interface IoRequestMaker<T, U> extends MessageInfo {\n /**\n * Create a message for this code, with or without payload.\n */\n req: [T] extends [AbsentData] ? (message: string) => ActionLessMessage<AbsentData> : (message: string, data: T) => ActionLessRequest<T, U>;\n}\n\n/**\n * Produce an IoRequestMaker for the provided level and request info.\n */\nfunction request<T = AbsentData, U = ImpossibleType>(level: IoMessageLevel, details: RequestInfo<U>): IoRequestMaker<T, U> {\n const maker = (text: string, data: T) => ({\n time: new Date(),\n level,\n code: details.code,\n message: text,\n data,\n defaultResponse: details.defaultResponse,\n } as ActionLessRequest<T, U>);\n\n return {\n ...details,\n level,\n req: maker as any,\n };\n}\n\n/**\n * A request that is a simple yes/no question, with the expectation that 'yes' is the default.\n */\nexport const confirm = <T extends object = ImpossibleType>(details: Required<Omit<RequestInfo<boolean>, 'defaultResponse'>>) => request<T, boolean>('info', {\n ...details,\n defaultResponse: true,\n});\n", "import type * as cxapi from '@aws-cdk/cx-api';\nimport * as make from './message-maker';\nimport type { SpanDefinition } from './span';\nimport type { DiffResult } from '../../../payloads';\nimport type { BootstrapEnvironmentProgress } from '../../../payloads/bootstrap-environment-progress';\nimport type { MissingContext, UpdatedContext } from '../../../payloads/context';\nimport type { BuildAsset, DeployConfirmationRequest, PublishAsset, StackDeployProgress, SuccessfulDeployStackResult } from '../../../payloads/deploy';\nimport type { StackDestroy, StackDestroyProgress } from '../../../payloads/destroy';\nimport type { HotswapDeploymentDetails, HotswapDeploymentAttempt, HotswappableChange, HotswapResult } from '../../../payloads/hotswap';\nimport type { StackDetailsPayload } from '../../../payloads/list';\nimport type { CloudWatchLogEvent, CloudWatchLogMonitorControlEvent } from '../../../payloads/logs-monitor';\nimport type { RefactorResult } from '../../../payloads/refactor';\nimport type { StackRollbackProgress } from '../../../payloads/rollback';\nimport type { SdkTrace } from '../../../payloads/sdk-trace';\nimport type { StackActivity, StackMonitoringControlEvent } from '../../../payloads/stack-activity';\nimport type { StackSelectionDetails } from '../../../payloads/synth';\nimport type { AssemblyData, ConfirmationRequest, ContextProviderMessageSource, Duration, ErrorPayload, StackAndAssemblyData } from '../../../payloads/types';\nimport type { FileWatchEvent, WatchSettings } from '../../../payloads/watch';\n\n/**\n * We have a rough system by which we assign message codes:\n * - First digit groups messages by action, e.g. synth or deploy\n * - X000-X009 are reserved for timings\n * - X900-X999 are reserved for results\n */\nexport const IO = {\n // Defaults (0000)\n DEFAULT_TOOLKIT_INFO: make.info({\n code: 'CDK_TOOLKIT_I0000',\n description: 'Default info messages emitted from the Toolkit',\n }),\n DEFAULT_TOOLKIT_DEBUG: make.debug({\n code: 'CDK_TOOLKIT_I0000',\n description: 'Default debug messages emitted from the Toolkit',\n }),\n DEFAULT_TOOLKIT_WARN: make.warn({\n code: 'CDK_TOOLKIT_W0000',\n description: 'Default warning messages emitted from the Toolkit',\n }),\n DEFAULT_TOOLKIT_ERROR: make.error({\n code: 'CDK_TOOLKIT_E0000',\n description: 'Default error messages emitted from the Toolkit',\n }),\n DEFAULT_TOOLKIT_TRACE: make.trace({\n code: 'CDK_TOOLKIT_I0000',\n description: 'Default trace messages emitted from the Toolkit',\n }),\n\n // warnings & errors\n CDK_TOOLKIT_W0100: make.warn({\n code: 'CDK_TOOLKIT_W0100',\n description: 'Credential plugin warnings',\n }),\n\n // 1: Synth (1xxx)\n CDK_TOOLKIT_I1000: make.info<Duration>({\n code: 'CDK_TOOLKIT_I1000',\n description: 'Provides synthesis times.',\n interface: 'Duration',\n }),\n CDK_TOOLKIT_I1001: make.trace<StackSelectionDetails>({\n code: 'CDK_TOOLKIT_I1001',\n description: 'Cloud Assembly synthesis is starting',\n interface: 'StackSelectionDetails',\n }),\n CDK_TOOLKIT_I1901: make.result<StackAndAssemblyData>({\n code: 'CDK_TOOLKIT_I1901',\n description: 'Provides stack data',\n interface: 'StackAndAssemblyData',\n }),\n CDK_TOOLKIT_I1902: make.result<AssemblyData>({\n code: 'CDK_TOOLKIT_I1902',\n description: 'Successfully deployed stacks',\n interface: 'AssemblyData',\n }),\n\n // 2: List (2xxx)\n CDK_TOOLKIT_I2901: make.result<StackDetailsPayload>({\n code: 'CDK_TOOLKIT_I2901',\n description: 'Provides details on the selected stacks and their dependencies',\n interface: 'StackDetailsPayload',\n }),\n\n // 3: Import & Migrate\n CDK_TOOLKIT_E3900: make.error<ErrorPayload>({\n code: 'CDK_TOOLKIT_E3900',\n description: 'Resource import failed',\n interface: 'ErrorPayload',\n }),\n\n // 4: Diff (4xxx)\n CDK_TOOLKIT_I4000: make.trace<StackSelectionDetails>({\n code: 'CDK_TOOLKIT_I4000',\n description: 'Diff stacks is starting',\n interface: 'StackSelectionDetails',\n }),\n CDK_TOOLKIT_I4001: make.info<DiffResult>({\n code: 'CDK_TOOLKIT_I4001',\n description: 'Output of the diff command',\n interface: 'DiffResult',\n }),\n\n // 5: Deploy & Watch (5xxx)\n CDK_TOOLKIT_I5000: make.info<Duration>({\n code: 'CDK_TOOLKIT_I5000',\n description: 'Provides deployment times',\n interface: 'Duration',\n }),\n CDK_TOOLKIT_I5001: make.info<Duration>({\n code: 'CDK_TOOLKIT_I5001',\n description: 'Provides total time in deploy action, including synth and rollback',\n interface: 'Duration',\n }),\n CDK_TOOLKIT_I5002: make.info<Duration>({\n code: 'CDK_TOOLKIT_I5002',\n description: 'Provides time for resource migration',\n interface: 'Duration',\n }),\n CDK_TOOLKIT_W5021: make.warn({\n code: 'CDK_TOOLKIT_W5021',\n description: 'Empty non-existent stack, deployment is skipped',\n }),\n CDK_TOOLKIT_W5022: make.warn({\n code: 'CDK_TOOLKIT_W5022',\n description: 'Empty existing stack, stack will be destroyed',\n }),\n CDK_TOOLKIT_I5031: make.info({\n code: 'CDK_TOOLKIT_I5031',\n description: 'Informs about any log groups that are traced as part of the deployment',\n }),\n CDK_TOOLKIT_I5032: make.debug<CloudWatchLogMonitorControlEvent>({\n code: 'CDK_TOOLKIT_I5032',\n description: 'Start monitoring log groups',\n interface: 'CloudWatchLogMonitorControlEvent',\n }),\n CDK_TOOLKIT_I5033: make.info<CloudWatchLogEvent>({\n code: 'CDK_TOOLKIT_I5033',\n description: 'A log event received from Cloud Watch',\n interface: 'CloudWatchLogEvent',\n }),\n CDK_TOOLKIT_I5034: make.debug<CloudWatchLogMonitorControlEvent>({\n code: 'CDK_TOOLKIT_I5034',\n description: 'Stop monitoring log groups',\n interface: 'CloudWatchLogMonitorControlEvent',\n }),\n CDK_TOOLKIT_E5035: make.error<ErrorPayload>({\n code: 'CDK_TOOLKIT_E5035',\n description: 'A log monitoring error',\n interface: 'ErrorPayload',\n }),\n CDK_TOOLKIT_I5050: make.confirm<ConfirmationRequest>({\n code: 'CDK_TOOLKIT_I5050',\n description: 'Confirm rollback during deployment',\n interface: 'ConfirmationRequest',\n }),\n CDK_TOOLKIT_I5060: make.confirm<DeployConfirmationRequest>({\n code: 'CDK_TOOLKIT_I5060',\n description: 'Confirm deploy security sensitive changes',\n interface: 'DeployConfirmationRequest',\n }),\n CDK_TOOLKIT_I5100: make.info<StackDeployProgress>({\n code: 'CDK_TOOLKIT_I5100',\n description: 'Stack deploy progress',\n interface: 'StackDeployProgress',\n }),\n\n // Assets (52xx)\n CDK_TOOLKIT_I5210: make.trace<BuildAsset>({\n code: 'CDK_TOOLKIT_I5210',\n description: 'Started building a specific asset',\n interface: 'BuildAsset',\n }),\n CDK_TOOLKIT_I5211: make.trace<Duration>({\n code: 'CDK_TOOLKIT_I5211',\n description: 'Building the asset has completed',\n interface: 'Duration',\n }),\n CDK_TOOLKIT_I5220: make.trace<PublishAsset>({\n code: 'CDK_TOOLKIT_I5220',\n description: 'Started publishing a specific asset',\n interface: 'PublishAsset',\n }),\n CDK_TOOLKIT_I5221: make.trace<Duration>({\n code: 'CDK_TOOLKIT_I5221',\n description: 'Publishing the asset has completed',\n interface: 'Duration',\n }),\n\n // Watch (53xx)\n CDK_TOOLKIT_I5310: make.debug<WatchSettings>({\n code: 'CDK_TOOLKIT_I5310',\n description: 'The computed settings used for file watching',\n interface: 'WatchSettings',\n }),\n CDK_TOOLKIT_I5311: make.info<FileWatchEvent>({\n code: 'CDK_TOOLKIT_I5311',\n description: 'File watching started',\n interface: 'FileWatchEvent',\n }),\n CDK_TOOLKIT_I5312: make.info<FileWatchEvent>({\n code: 'CDK_TOOLKIT_I5312',\n description: 'File event detected, starting deployment',\n interface: 'FileWatchEvent',\n }),\n CDK_TOOLKIT_I5313: make.info<FileWatchEvent>({\n code: 'CDK_TOOLKIT_I5313',\n description: 'File event detected during active deployment, changes are queued',\n interface: 'FileWatchEvent',\n }),\n CDK_TOOLKIT_I5314: make.info({\n code: 'CDK_TOOLKIT_I5314',\n description: 'Initial watch deployment started',\n }),\n CDK_TOOLKIT_I5315: make.info({\n code: 'CDK_TOOLKIT_I5315',\n description: 'Queued watch deployment started',\n }),\n\n // Hotswap (54xx)\n CDK_TOOLKIT_I5400: make.trace<HotswapDeploymentAttempt>({\n code: 'CDK_TOOLKIT_I5400',\n description: 'Attempting a hotswap deployment',\n interface: 'HotswapDeploymentAttempt',\n }),\n CDK_TOOLKIT_I5401: make.trace<HotswapDeploymentDetails>({\n code: 'CDK_TOOLKIT_I5401',\n description: 'Computed details for the hotswap deployment',\n interface: 'HotswapDeploymentDetails',\n }),\n CDK_TOOLKIT_I5402: make.info<HotswappableChange>({\n code: 'CDK_TOOLKIT_I5402',\n description: 'A hotswappable change is processed as part of a hotswap deployment',\n interface: 'HotswappableChange',\n }),\n CDK_TOOLKIT_I5403: make.info<HotswappableChange>({\n code: 'CDK_TOOLKIT_I5403',\n description: 'The hotswappable change has completed processing',\n interface: 'HotswappableChange',\n }),\n CDK_TOOLKIT_I5410: make.info<HotswapResult>({\n code: 'CDK_TOOLKIT_I5410',\n description: 'Hotswap deployment has ended, a full deployment might still follow if needed',\n interface: 'HotswapResult',\n }),\n\n // Stack Monitor (55xx)\n CDK_TOOLKIT_I5501: make.info<StackMonitoringControlEvent>({\n code: 'CDK_TOOLKIT_I5501',\n description: 'Stack Monitoring: Start monitoring of a single stack',\n interface: 'StackMonitoringControlEvent',\n }),\n CDK_TOOLKIT_I5502: make.info<StackActivity>({\n code: 'CDK_TOOLKIT_I5502',\n description: 'Stack Monitoring: Activity event for a single stack',\n interface: 'StackActivity',\n }),\n CDK_TOOLKIT_I5503: make.info<StackMonitoringControlEvent>({\n code: 'CDK_TOOLKIT_I5503',\n description: 'Stack Monitoring: Finished monitoring of a single stack',\n interface: 'StackMonitoringControlEvent',\n }),\n\n // Success (59xx)\n CDK_TOOLKIT_I5900: make.result<SuccessfulDeployStackResult>({\n code: 'CDK_TOOLKIT_I5900',\n description: 'Deployment results on success',\n interface: 'SuccessfulDeployStackResult',\n }),\n CDK_TOOLKIT_I5901: make.info({\n code: 'CDK_TOOLKIT_I5901',\n description: 'Generic deployment success messages',\n }),\n CDK_TOOLKIT_W5400: make.warn({\n code: 'CDK_TOOLKIT_W5400',\n description: 'Hotswap disclosure message',\n }),\n\n CDK_TOOLKIT_E5001: make.error({\n code: 'CDK_TOOLKIT_E5001',\n description: 'No stacks found',\n }),\n CDK_TOOLKIT_E5500: make.error<ErrorPayload>({\n code: 'CDK_TOOLKIT_E5500',\n description: 'Stack Monitoring error',\n interface: 'ErrorPayload',\n }),\n\n // 6: Rollback (6xxx)\n CDK_TOOLKIT_I6000: make.info<Duration>({\n code: 'CDK_TOOLKIT_I6000',\n description: 'Provides rollback times',\n interface: 'Duration',\n }),\n CDK_TOOLKIT_I6100: make.info<StackRollbackProgress>({\n code: 'CDK_TOOLKIT_I6100',\n description: 'Stack rollback progress',\n interface: 'StackRollbackProgress',\n }),\n\n CDK_TOOLKIT_E6001: make.error({\n code: 'CDK_TOOLKIT_E6001',\n description: 'No stacks found',\n }),\n CDK_TOOLKIT_E6900: make.error<ErrorPayload>({\n code: 'CDK_TOOLKIT_E6900',\n description: 'Rollback failed',\n interface: 'ErrorPayload',\n }),\n\n // 7: Destroy (7xxx)\n CDK_TOOLKIT_I7000: make.info<Duration>({\n code: 'CDK_TOOLKIT_I7000',\n description: 'Provides destroy times',\n interface: 'Duration',\n }),\n CDK_TOOLKIT_I7001: make.trace<Duration>({\n code: 'CDK_TOOLKIT_I7001',\n description: 'Provides destroy time for a single stack',\n interface: 'Duration',\n }),\n CDK_TOOLKIT_I7010: make.confirm<ConfirmationRequest>({\n code: 'CDK_TOOLKIT_I7010',\n description: 'Confirm destroy stacks',\n interface: 'ConfirmationRequest',\n }),\n CDK_TOOLKIT_I7100: make.info<StackDestroyProgress>({\n code: 'CDK_TOOLKIT_I7100',\n description: 'Stack destroy progress',\n interface: 'StackDestroyProgress',\n }),\n CDK_TOOLKIT_I7101: make.trace<StackDestroy>({\n code: 'CDK_TOOLKIT_I7101',\n description: 'Start stack destroying',\n interface: 'StackDestroy',\n }),\n\n CDK_TOOLKIT_I7900: make.result<cxapi.CloudFormationStackArtifact>({\n code: 'CDK_TOOLKIT_I7900',\n description: 'Stack deletion succeeded',\n interface: 'cxapi.CloudFormationStackArtifact',\n }),\n\n CDK_TOOLKIT_E7010: make.error({\n code: 'CDK_TOOLKIT_E7010',\n description: 'Action was aborted due to negative confirmation of request',\n }),\n CDK_TOOLKIT_E7900: make.error<ErrorPayload>({\n code: 'CDK_TOOLKIT_E7900',\n description: 'Stack deletion failed',\n interface: 'ErrorPayload',\n }),\n\n // 8. Refactor (8xxx)\n CDK_TOOLKIT_I8900: make.result<RefactorResult>({\n code: 'CDK_TOOLKIT_I8900',\n description: 'Refactor result',\n interface: 'RefactorResult',\n }),\n\n CDK_TOOLKIT_W8010: make.warn({\n code: 'CDK_TOOLKIT_W8010',\n description: 'Refactor execution not yet supported',\n }),\n\n // 9: Bootstrap (9xxx)\n CDK_TOOLKIT_I9000: make.info<Duration>({\n code: 'CDK_TOOLKIT_I9000',\n description: 'Provides bootstrap times',\n interface: 'Duration',\n }),\n CDK_TOOLKIT_I9100: make.info<BootstrapEnvironmentProgress>({\n code: 'CDK_TOOLKIT_I9100',\n description: 'Bootstrap progress',\n interface: 'BootstrapEnvironmentProgress',\n }),\n\n CDK_TOOLKIT_I9900: make.result<{ environment: cxapi.Environment }>({\n code: 'CDK_TOOLKIT_I9900',\n description: 'Bootstrap results on success',\n interface: 'cxapi.Environment',\n }),\n CDK_TOOLKIT_E9900: make.error<ErrorPayload>({\n code: 'CDK_TOOLKIT_E9900',\n description: 'Bootstrap failed',\n interface: 'ErrorPayload',\n }),\n\n // Notices\n CDK_TOOLKIT_I0100: make.info({\n code: 'CDK_TOOLKIT_I0100',\n description: 'Notices decoration (the header or footer of a list of notices)',\n }),\n CDK_TOOLKIT_W0101: make.warn({\n code: 'CDK_TOOLKIT_W0101',\n description: 'A notice that is marked as a warning',\n }),\n CDK_TOOLKIT_E0101: make.error({\n code: 'CDK_TOOLKIT_E0101',\n description: 'A notice that is marked as an error',\n }),\n CDK_TOOLKIT_I0101: make.info({\n code: 'CDK_TOOLKIT_I0101',\n description: 'A notice that is marked as informational',\n }),\n\n // Assembly codes\n DEFAULT_ASSEMBLY_TRACE: make.trace({\n code: 'CDK_ASSEMBLY_I0000',\n description: 'Default trace messages emitted from Cloud Assembly operations',\n }),\n DEFAULT_ASSEMBLY_DEBUG: make.debug({\n code: 'CDK_ASSEMBLY_I0000',\n description: 'Default debug messages emitted from Cloud Assembly operations',\n }),\n DEFAULT_ASSEMBLY_INFO: make.info({\n code: 'CDK_ASSEMBLY_I0000',\n description: 'Default info messages emitted from Cloud Assembly operations',\n }),\n DEFAULT_ASSEMBLY_WARN: make.warn({\n code: 'CDK_ASSEMBLY_W0000',\n description: 'Default warning messages emitted from Cloud Assembly operations',\n }),\n\n CDK_ASSEMBLY_I0010: make.debug({\n code: 'CDK_ASSEMBLY_I0010',\n description: 'Generic environment preparation debug messages',\n }),\n CDK_ASSEMBLY_W0010: make.warn({\n code: 'CDK_ASSEMBLY_W0010',\n description: 'Emitted if the found framework version does not support context overflow',\n }),\n CDK_ASSEMBLY_I0042: make.debug<UpdatedContext>({\n code: 'CDK_ASSEMBLY_I0042',\n description: 'Writing updated context',\n interface: 'UpdatedContext',\n }),\n CDK_ASSEMBLY_I0240: make.debug<MissingContext>({\n code: 'CDK_ASSEMBLY_I0240',\n description: 'Context lookup was stopped as no further progress was made. ',\n interface: 'MissingContext',\n }),\n CDK_ASSEMBLY_I0241: make.debug<MissingContext>({\n code: 'CDK_ASSEMBLY_I0241',\n description: 'Fetching missing context. This is an iterative message that may appear multiple times with different missing keys.',\n interface: 'MissingContext',\n }),\n CDK_ASSEMBLY_I1000: make.debug({\n code: 'CDK_ASSEMBLY_I1000',\n description: 'Cloud assembly output starts',\n }),\n CDK_ASSEMBLY_I1001: make.info({\n code: 'CDK_ASSEMBLY_I1001',\n description: 'Output lines emitted by the cloud assembly to stdout',\n }),\n CDK_ASSEMBLY_E1002: make.error({\n code: 'CDK_ASSEMBLY_E1002',\n description: 'Output lines emitted by the cloud assembly to stderr',\n }),\n CDK_ASSEMBLY_I1003: make.info({\n code: 'CDK_ASSEMBLY_I1003',\n description: 'Cloud assembly output finished',\n }),\n CDK_ASSEMBLY_E1111: make.error<ErrorPayload>({\n code: 'CDK_ASSEMBLY_E1111',\n description: 'Incompatible CDK CLI version. Upgrade needed.',\n interface: 'ErrorPayload',\n }),\n\n CDK_ASSEMBLY_I0150: make.debug<never>({\n code: 'CDK_ASSEMBLY_I0150',\n description: 'Indicates the use of a pre-synthesized cloud assembly directory',\n }),\n\n CDK_ASSEMBLY_I0300: make.info<ContextProviderMessageSource>({\n code: 'CDK_ASSEMBLY_I0300',\n description: 'An info message emitted by a Context Provider',\n interface: 'ContextProviderMessageSource',\n }),\n CDK_ASSEMBLY_I0301: make.debug<ContextProviderMessageSource>({\n code: 'CDK_ASSEMBLY_I0301',\n description: 'A debug message emitted by a Context Provider',\n interface: 'ContextProviderMessageSource',\n }),\n\n // Assembly Annotations\n CDK_ASSEMBLY_I9999: make.info<cxapi.SynthesisMessage>({\n code: 'CDK_ASSEMBLY_I9999',\n description: 'Annotations emitted by the cloud assembly',\n interface: 'cxapi.SynthesisMessage',\n }),\n CDK_ASSEMBLY_W9999: make.warn<cxapi.SynthesisMessage>({\n code: 'CDK_ASSEMBLY_W9999',\n description: 'Warnings emitted by the cloud assembly',\n interface: 'cxapi.SynthesisMessage',\n }),\n CDK_ASSEMBLY_E9999: make.error<cxapi.SynthesisMessage>({\n code: 'CDK_ASSEMBLY_E9999',\n description: 'Errors emitted by the cloud assembly',\n interface: 'cxapi.SynthesisMessage',\n }),\n\n // SDK codes\n DEFAULT_SDK_TRACE: make.trace({\n code: 'CDK_SDK_I0000',\n description: 'An SDK trace message.',\n }),\n DEFAULT_SDK_DEBUG: make.debug({\n code: 'CDK_SDK_I0000',\n description: 'An SDK debug message.',\n }),\n DEFAULT_SDK_WARN: make.warn({\n code: 'CDK_SDK_W0000',\n description: 'An SDK warning message.',\n }),\n CDK_SDK_I0100: make.trace<SdkTrace>({\n code: 'CDK_SDK_I0100',\n description: 'An SDK trace. SDK traces are emitted as traces to the IoHost, but contain the original SDK logging level.',\n interface: 'SdkTrace',\n }),\n};\n\n//////////////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Payload type of the end message must extend Duration\n */\nexport const SPAN = {\n SYNTH_ASSEMBLY: {\n name: 'Synthesis',\n start: IO.CDK_TOOLKIT_I1001,\n end: IO.CDK_TOOLKIT_I1000,\n },\n DEPLOY_STACK: {\n name: 'Deployment',\n start: IO.CDK_TOOLKIT_I5100,\n end: IO.CDK_TOOLKIT_I5001,\n },\n ROLLBACK_STACK: {\n name: 'Rollback',\n start: IO.CDK_TOOLKIT_I6100,\n end: IO.CDK_TOOLKIT_I6000,\n },\n DIFF_STACK: {\n name: 'Diff',\n start: IO.CDK_TOOLKIT_I4000,\n end: IO.CDK_TOOLKIT_I4001,\n },\n DESTROY_STACK: {\n name: 'Destroy',\n start: IO.CDK_TOOLKIT_I7100,\n end: IO.CDK_TOOLKIT_I7001,\n },\n DESTROY_ACTION: {\n name: 'Destroy',\n start: IO.CDK_TOOLKIT_I7101,\n end: IO.CDK_TOOLKIT_I7000,\n },\n BOOTSTRAP_SINGLE: {\n name: 'Bootstrap',\n start: IO.CDK_TOOLKIT_I9100,\n end: IO.CDK_TOOLKIT_I9000,\n },\n BUILD_ASSET: {\n name: 'Build Asset',\n start: IO.CDK_TOOLKIT_I5210,\n end: IO.CDK_TOOLKIT_I5211,\n },\n PUBLISH_ASSET: {\n name: 'Publish Asset',\n start: IO.CDK_TOOLKIT_I5220,\n end: IO.CDK_TOOLKIT_I5221,\n },\n HOTSWAP: {\n name: 'hotswap-deployment',\n start: IO.CDK_TOOLKIT_I5400,\n end: IO.CDK_TOOLKIT_I5410,\n },\n} satisfies Record<string, SpanDefinition<any, any>>;\n", "import * as util from 'util';\nimport type { ActionLessMessage, ActionLessRequest, IoHelper } from './io-helper';\nimport type { IoMessageMaker } from './message-maker';\nimport { IO } from './messages';\n\n/**\n * Helper class to emit standard log messages to an IoHost\n *\n * It wraps an `IoHelper`, and adds convenience methods to emit default messages\n * for the various log levels.\n */\nexport class IoDefaultMessages {\n constructor(private readonly ioHelper: IoHelper) {\n }\n\n public notify(msg: ActionLessMessage<unknown>): Promise<void> {\n return this.ioHelper.notify(msg);\n }\n\n public requestResponse<T, U>(msg: ActionLessRequest<T, U>): Promise<U> {\n return this.ioHelper.requestResponse(msg);\n }\n\n public error(input: string, ...args: unknown[]) {\n this.emitMessage(IO.DEFAULT_TOOLKIT_ERROR, input, ...args);\n }\n\n public warn(input: string, ...args: unknown[]) {\n this.emitMessage(IO.DEFAULT_TOOLKIT_WARN, input, ...args);\n }\n\n public warning(input: string, ...args: unknown[]) {\n this.emitMessage(IO.DEFAULT_TOOLKIT_WARN, input, ...args);\n }\n\n public info(input: string, ...args: unknown[]) {\n this.emitMessage(IO.DEFAULT_TOOLKIT_INFO, input, ...args);\n }\n\n public debug(input: string, ...args: unknown[]) {\n this.emitMessage(IO.DEFAULT_TOOLKIT_DEBUG, input, ...args);\n }\n\n public trace(input: string, ...args: unknown[]) {\n this.emitMessage(IO.DEFAULT_TOOLKIT_TRACE, input, ...args);\n }\n\n public result(input: string, ...args: unknown[]) {\n const message = args.length > 0 ? util.format(input, ...args) : input;\n // This is just the default \"info\" message but with a level of \"result\"\n void this.ioHelper.notify({\n time: new Date(),\n code: IO.DEFAULT_TOOLKIT_INFO.code,\n level: 'result',\n message,\n data: undefined,\n });\n }\n\n private emitMessage(maker: IoMessageMaker<void>, input: string, ...args: unknown[]) {\n // Format message if args are provided\n const message = args.length > 0 ? util.format(input, ...args) : input;\n void this.ioHelper.notify(maker.msg(message));\n }\n}\n", "import type { CloudFormationStackArtifact } from '@aws-cdk/cx-api';\nimport type { IoMessage } from '../../api/io';\nimport { IO } from '../../api/io/private';\nimport { type StackActivity, type StackProgress } from '../../payloads';\nimport { maxResourceTypeLength, stackEventHasErrorMessage } from '../../util';\n\nexport interface IActivityPrinter {\n notify(msg: IoMessage<unknown>): void;\n}\n\nexport interface ActivityPrinterProps {\n /**\n * Stream to write to\n */\n readonly stream: NodeJS.WriteStream;\n}\n\nexport abstract class ActivityPrinterBase implements IActivityPrinter {\n protected static readonly TIMESTAMP_WIDTH = 12;\n protected static readonly STATUS_WIDTH = 20;\n\n /**\n * Stream to write to\n */\n protected readonly stream: NodeJS.WriteStream;\n\n /**\n * The with of the \"resource type\" column.\n */\n protected resourceTypeColumnWidth: number = maxResourceTypeLength({});\n\n /**\n * A list of resource IDs which are currently being processed\n */\n protected resourcesInProgress: Record<string, StackActivity> = {};\n\n protected stackProgress?: StackProgress;\n\n protected rollingBack = false;\n\n protected readonly failures = new Array<StackActivity>();\n\n protected hookFailureMap = new Map<string, Map<string, string>>();\n\n constructor(protected readonly props: ActivityPrinterProps) {\n this.stream = props.stream;\n }\n\n protected abstract print(): void;\n\n /**\n * Receive a stack activity message\n */\n public notify(msg: IoMessage<unknown>): void {\n switch (true) {\n case IO.CDK_TOOLKIT_I5501.is(msg):\n this.start(msg.data);\n break;\n case IO.CDK_TOOLKIT_I5502.is(msg):\n this.activity(msg.data);\n break;\n case IO.CDK_TOOLKIT_I5503.is(msg):\n this.stop();\n break;\n default:\n // ignore all other messages\n break;\n }\n }\n\n public start({ stack }: { stack: CloudFormationStackArtifact}) {\n this.resourceTypeColumnWidth = maxResourceTypeLength(stack.template);\n }\n\n public activity(activity: StackActivity) {\n // process the activity and then call print\n this.addActivity(activity);\n this.print();\n }\n\n public stop() {\n // final print after the stack is done\n this.print();\n }\n\n protected addActivity(activity: StackActivity) {\n const status = activity.event.ResourceStatus;\n const hookStatus = activity.event.HookStatus;\n const hookType = activity.event.HookType;\n if (!status || !activity.event.LogicalResourceId) {\n return;\n }\n\n this.stackProgress = activity.progress;\n\n if (status === 'ROLLBACK_IN_PROGRESS' || status === 'UPDATE_ROLLBACK_IN_PROGRESS') {\n // Only triggered on the stack once we've started doing a rollback\n this.rollingBack = true;\n }\n\n if (status.endsWith('_IN_PROGRESS')) {\n this.resourcesInProgress[activity.event.LogicalResourceId] = activity;\n }\n\n if (stackEventHasErrorMessage(status)) {\n const isCancelled = (activity.event.ResourceStatusReason ?? '').indexOf('cancelled') > -1;\n\n // Cancelled is not an interesting failure reason\n if (!isCancelled) {\n this.failures.push(activity);\n }\n }\n\n if (status.endsWith('_COMPLETE') || status.endsWith('_FAILED')) {\n delete this.resourcesInProgress[activity.event.LogicalResourceId];\n }\n\n if (\n hookStatus !== undefined &&\n hookStatus.endsWith('_COMPLETE_FAILED') &&\n activity.event.LogicalResourceId !== undefined &&\n hookType !== undefined\n ) {\n if (this.hookFailureMap.has(activity.event.LogicalResourceId)) {\n this.hookFailureMap.get(activity.event.LogicalResourceId)?.set(hookType, activity.event.HookStatusReason ?? '');\n } else {\n this.hookFailureMap.set(activity.event.LogicalResourceId, new Map<string, string>());\n this.hookFailureMap.get(activity.event.LogicalResourceId)?.set(hookType, activity.event.HookStatusReason ?? '');\n }\n }\n }\n\n protected failureReason(activity: StackActivity) {\n const resourceStatusReason = activity.event.ResourceStatusReason ?? '';\n const logicalResourceId = activity.event.LogicalResourceId ?? '';\n const hookFailureReasonMap = this.hookFailureMap.get(logicalResourceId);\n\n if (hookFailureReasonMap !== undefined) {\n for (const hookType of hookFailureReasonMap.keys()) {\n if (resourceStatusReason.includes(hookType)) {\n return resourceStatusReason + ' : ' + hookFailureReasonMap.get(hookType);\n }\n }\n }\n return resourceStatusReason;\n }\n\n /**\n * Is the activity a meta activity for the stack itself.\n */\n protected isActivityForTheStack(activity: StackActivity) {\n return activity.event.PhysicalResourceId === activity.event.StackId;\n }\n}\n", "import * as util from 'util';\nimport * as chalk from 'chalk';\nimport type { ActivityPrinterProps } from './base';\nimport { ActivityPrinterBase } from './base';\nimport type { StackActivity } from '../../payloads';\nimport { padRight } from '../../util';\n\n/**\n * Activity Printer which shows a full log of all CloudFormation events\n *\n * When there hasn't been activity for a while, it will print the resources\n * that are currently in progress, to show what's holding up the deployment.\n */\nexport class HistoryActivityPrinter extends ActivityPrinterBase {\n /**\n * Last time we printed something to the console.\n *\n * Used to measure timeout for progress reporting.\n */\n private lastPrintTime = Date.now();\n\n private lastPrinted?: StackActivity;\n\n /**\n * Number of ms of change absence before we tell the user about the resources that are currently in progress.\n */\n private readonly inProgressDelay = 30_000;\n\n private readonly printable = new Array<StackActivity>();\n\n constructor(props: ActivityPrinterProps) {\n super(props);\n }\n\n public activity(activity: StackActivity) {\n this.printable.push(activity);\n super.activity(activity);\n }\n\n public stop() {\n super.stop();\n\n // Print failures at the end\n if (this.failures.length > 0) {\n this.stream.write('\\nFailed resources:\\n');\n for (const failure of this.failures) {\n // Root stack failures are not interesting\n if (this.isActivityForTheStack(failure)) {\n continue;\n }\n\n this.printOne(failure, false);\n }\n }\n }\n\n protected print() {\n for (const activity of this.printable) {\n this.printOne(activity);\n this.lastPrinted = activity;\n }\n this.printable.splice(0, this.printable.length);\n this.printInProgress(this.lastPrinted?.progress.formatted);\n }\n\n private printOne(activity: StackActivity, progress?: boolean) {\n const event = activity.event;\n const color = colorFromStatusResult(event.ResourceStatus);\n let reasonColor = chalk.cyan;\n\n let stackTrace = '';\n const metadata = activity.metadata;\n\n if (event.ResourceStatus && event.ResourceStatus.indexOf('FAILED') !== -1) {\n if (progress == undefined || progress) {\n event.ResourceStatusReason = event.ResourceStatusReason ? this.failureReason(activity) : '';\n }\n if (metadata) {\n stackTrace = metadata.entry.trace ? `\\n\\t${metadata.entry.trace.join('\\n\\t\\\\_ ')}` : '';\n }\n reasonColor = chalk.red;\n }\n\n const resourceName = metadata ? metadata.constructPath : event.LogicalResourceId || '';\n const logicalId = resourceName !== event.LogicalResourceId ? `(${event.LogicalResourceId}) ` : '';\n\n this.stream.write(\n util.format(\n '%s | %s%s | %s | %s | %s %s%s%s\\n',\n event.StackName,\n progress !== false ? `${activity.progress.formatted} | ` : '',\n new Date(event.Timestamp!).toLocaleTimeString(),\n color(padRight(HistoryActivityPrinter.STATUS_WIDTH, (event.ResourceStatus || '').slice(0, HistoryActivityPrinter.STATUS_WIDTH))), // pad left and trim\n padRight(this.resourceTypeColumnWidth, event.ResourceType || ''),\n color(chalk.bold(resourceName)),\n logicalId,\n reasonColor(chalk.bold(event.ResourceStatusReason ? event.ResourceStatusReason : '')),\n reasonColor(stackTrace),\n ),\n );\n\n this.lastPrintTime = Date.now();\n }\n\n /**\n * If some resources are taking a while to create, notify the user about what's currently in progress\n */\n private printInProgress(progress?: string) {\n if (!progress || Date.now() < this.lastPrintTime + this.inProgressDelay) {\n return;\n }\n\n if (Object.keys(this.resourcesInProgress).length > 0) {\n this.stream.write(\n util.format(\n '%s Currently in progress: %s\\n',\n progress,\n chalk.bold(Object.keys(this.resourcesInProgress).join(', ')),\n ),\n );\n }\n\n // We cheat a bit here. To prevent printInProgress() from repeatedly triggering,\n // we set the timestamp into the future. It will be reset whenever a regular print\n // occurs, after which we can be triggered again.\n this.lastPrintTime = +Infinity;\n }\n}\n\nfunction colorFromStatusResult(status?: string) {\n if (!status) {\n return chalk.reset;\n }\n\n if (status.indexOf('FAILED') !== -1) {\n return chalk.red;\n }\n if (status.indexOf('ROLLBACK') !== -1) {\n return chalk.yellow;\n }\n if (status.indexOf('COMPLETE') !== -1) {\n return chalk.green;\n }\n\n return chalk.reset;\n}\n", "import * as util from 'util';\nimport * as chalk from 'chalk';\nimport type { ActivityPrinterProps } from './base';\nimport { ActivityPrinterBase } from './base';\nimport { RewritableBlock } from './display';\nimport type { StackActivity } from '../../payloads';\nimport { padLeft, padRight, stackEventHasErrorMessage } from '../../util';\n\n/**\n * Activity Printer which shows the resources currently being updated\n *\n * It will continuously re-update the terminal and show only the resources\n * that are currently being updated, in addition to a progress bar which\n * shows how far along the deployment is.\n *\n * Resources that have failed will always be shown, and will be recapitulated\n * along with their stack trace when the monitoring ends.\n *\n * Resources that failed deployment because they have been cancelled are\n * not included.\n */\nexport class CurrentActivityPrinter extends ActivityPrinterBase {\n /**\n * Continuously write to the same output block.\n */\n private block: RewritableBlock;\n\n constructor(props: ActivityPrinterProps) {\n super(props);\n this.block = new RewritableBlock(this.stream);\n }\n\n protected print(): void {\n const lines = [];\n\n // Add a progress bar at the top\n const progressWidth = Math.max(\n Math.min((this.block.width ?? 80) - PROGRESSBAR_EXTRA_SPACE - 1, MAX_PROGRESSBAR_WIDTH),\n MIN_PROGRESSBAR_WIDTH,\n );\n const prog = this.progressBar(progressWidth);\n if (prog) {\n lines.push(' ' + prog, '');\n }\n\n // Normally we'd only print \"resources in progress\", but it's also useful\n // to keep an eye on the failures and know about the specific errors asquickly\n // as possible (while the stack is still rolling back), so add those in.\n const toPrint: StackActivity[] = [...this.failures, ...Object.values(this.resourcesInProgress)];\n toPrint.sort((a, b) => a.event.Timestamp!.getTime() - b.event.Timestamp!.getTime());\n\n lines.push(\n ...toPrint.map((res) => {\n const color = colorFromStatusActivity(res.event.ResourceStatus);\n const resourceName = res.metadata?.constructPath ?? res.event.LogicalResourceId ?? '';\n\n return util.format(\n '%s | %s | %s | %s%s',\n padLeft(CurrentActivityPrinter.TIMESTAMP_WIDTH, new Date(res.event.Timestamp!).toLocaleTimeString()),\n color(padRight(CurrentActivityPrinter.STATUS_WIDTH, (res.event.ResourceStatus || '').slice(0, CurrentActivityPrinter.STATUS_WIDTH))),\n padRight(this.resourceTypeColumnWidth, res.event.ResourceType || ''),\n color(chalk.bold(shorten(40, resourceName))),\n this.failureReasonOnNextLine(res),\n );\n }),\n );\n\n this.block.displayLines(lines);\n }\n\n public stop() {\n super.stop();\n\n // Print failures at the end\n const lines = new Array<string>();\n for (const failure of this.failures) {\n // Root stack failures are not interesting\n if (this.isActivityForTheStack(failure)) {\n continue;\n }\n\n lines.push(\n util.format(\n chalk.red('%s | %s | %s | %s%s') + '\\n',\n padLeft(CurrentActivityPrinter.TIMESTAMP_WIDTH, new Date(failure.event.Timestamp!).toLocaleTimeString()),\n padRight(CurrentActivityPrinter.STATUS_WIDTH, (failure.event.ResourceStatus || '').slice(0, CurrentActivityPrinter.STATUS_WIDTH)),\n padRight(this.resourceTypeColumnWidth, failure.event.ResourceType || ''),\n shorten(40, failure.event.LogicalResourceId ?? ''),\n this.failureReasonOnNextLine(failure),\n ),\n );\n\n const trace = failure.metadata?.entry?.trace;\n if (trace) {\n lines.push(chalk.red(`\\t${trace.join('\\n\\t\\\\_ ')}\\n`));\n }\n }\n\n // Display in the same block space, otherwise we're going to have silly empty lines.\n this.block.displayLines(lines);\n this.block.removeEmptyLines();\n }\n\n private progressBar(width: number) {\n if (!this.stackProgress || !this.stackProgress.total) {\n return '';\n }\n const fraction = Math.min(this.stackProgress.completed / this.stackProgress.total, 1);\n const innerWidth = Math.max(1, width - 2);\n const chars = innerWidth * fraction;\n const remainder = chars - Math.floor(chars);\n\n const fullChars = FULL_BLOCK.repeat(Math.floor(chars));\n const partialChar = PARTIAL_BLOCK[Math.floor(remainder * PARTIAL_BLOCK.length)];\n const filler = '\u00B7'.repeat(innerWidth - Math.floor(chars) - (partialChar ? 1 : 0));\n\n const color = this.rollingBack ? chalk.yellow : chalk.green;\n\n return '[' + color(fullChars + partialChar) + filler + `] (${this.stackProgress.completed}/${this.stackProgress.total})`;\n }\n\n private failureReasonOnNextLine(activity: StackActivity) {\n return stackEventHasErrorMessage(activity.event.ResourceStatus ?? '')\n ? `\\n${' '.repeat(CurrentActivityPrinter.TIMESTAMP_WIDTH + CurrentActivityPrinter.STATUS_WIDTH + 6)}${chalk.red(this.failureReason(activity) ?? '')}`\n : '';\n }\n}\n\nconst FULL_BLOCK = '\u2588';\nconst PARTIAL_BLOCK = ['', '\u258F', '\u258E', '\u258D', '\u258C', '\u258B', '\u258A', '\u2589'];\nconst MAX_PROGRESSBAR_WIDTH = 60;\nconst MIN_PROGRESSBAR_WIDTH = 10;\nconst PROGRESSBAR_EXTRA_SPACE =\n 2 /* leading spaces */ + 2 /* brackets */ + 4 /* progress number decoration */ + 6; /* 2 progress numbers up to 999 */\n\nfunction colorFromStatusActivity(status?: string) {\n if (!status) {\n return chalk.reset;\n }\n\n if (status.endsWith('_FAILED')) {\n return chalk.red;\n }\n\n if (status.startsWith('CREATE_') || status.startsWith('UPDATE_') || status.startsWith('IMPORT_')) {\n return chalk.green;\n }\n // For stacks, it may also be 'UPDDATE_ROLLBACK_IN_PROGRESS'\n if (status.indexOf('ROLLBACK_') !== -1) {\n return chalk.yellow;\n }\n if (status.startsWith('DELETE_')) {\n return chalk.yellow;\n }\n\n return chalk.reset;\n}\n\nfunction shorten(maxWidth: number, p: string) {\n if (p.length <= maxWidth) {\n return p;\n }\n const half = Math.floor((maxWidth - 3) / 2);\n return p.slice(0, half) + '...' + p.slice(-half);\n}\n\n", "// namespace object imports won't work in the bundle for function exports\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nconst wrapAnsi = require('wrap-ansi');\n\n/**\n * A class representing rewritable display lines\n */\nexport class RewritableBlock {\n private lastHeight = 0;\n private trailingEmptyLines = 0;\n\n constructor(private readonly stream: NodeJS.WriteStream) {\n }\n\n public get width() {\n // Might get changed if the user resizes the terminal\n return this.stream.columns;\n }\n\n public get height() {\n // Might get changed if the user resizes the terminal\n return this.stream.rows;\n }\n\n public displayLines(lines: string[]) {\n lines = terminalWrap(this.width, expandNewlines(lines));\n lines = lines.slice(0, getMaxBlockHeight(this.height, this.lastHeight, lines));\n\n this.stream.write(cursorUp(this.lastHeight));\n for (const line of lines) {\n this.stream.write(cll() + line + '\\n');\n }\n\n this.trailingEmptyLines = Math.max(0, this.lastHeight - lines.length);\n\n // Clear remainder of unwritten lines\n for (let i = 0; i < this.trailingEmptyLines; i++) {\n this.stream.write(cll() + '\\n');\n }\n\n // The block can only ever get bigger\n this.lastHeight = Math.max(this.lastHeight, lines.length);\n }\n\n public removeEmptyLines() {\n this.stream.write(cursorUp(this.trailingEmptyLines));\n }\n}\n\nconst ESC = '\\u001b';\n\n/*\n * Move cursor up `n` lines. Default is 1\n */\nfunction cursorUp(n: number) {\n n = typeof n === 'number' ? n : 1;\n return n > 0 ? ESC + '[' + n + 'A' : '';\n}\n\n/**\n * Clear to end of line\n */\nfunction cll() {\n return ESC + '[K';\n}\n\nfunction terminalWrap(width: number | undefined, lines: string[]) {\n if (width === undefined) {\n return lines;\n }\n\n return lines.flatMap(line => wrapAnsi(line, width - 1, {\n hard: true,\n trim: true,\n wordWrap: false,\n }).split('\\n'));\n}\n\n/**\n * Make sure there are no hidden newlines in the gin strings\n */\nfunction expandNewlines(lines: string[]): string[] {\n return lines.flatMap(line => line.split('\\n'));\n}\n\nfunction getMaxBlockHeight(windowHeight: number | undefined, lastHeight: number, lines: string[]): number {\n if (windowHeight === undefined) {\n return Math.max(lines.length, lastHeight);\n }\n return lines.length < windowHeight ? lines.length : windowHeight - 1;\n}\n", "import * as fs from 'fs-extra';\nimport { ProxyAgent } from 'proxy-agent';\nimport type { SdkHttpOptions } from './sdk-provider';\nimport { IO, type IoHelper } from '../io/private';\n\nexport class ProxyAgentProvider {\n private readonly ioHelper: IoHelper;\n\n public constructor(ioHelper: IoHelper) {\n this.ioHelper = ioHelper;\n }\n\n public async create(options: SdkHttpOptions) {\n // Force it to use the proxy provided through the command line.\n // Otherwise, let the ProxyAgent auto-detect the proxy using environment variables.\n const getProxyForUrl = options.proxyAddress != null\n ? () => Promise.resolve(options.proxyAddress!)\n : undefined;\n\n return new ProxyAgent({\n ca: await this.tryGetCACert(options.caBundlePath),\n getProxyForUrl,\n });\n }\n\n private async tryGetCACert(bundlePath?: string) {\n const path = bundlePath || this.caBundlePathFromEnvironment();\n if (path) {\n await this.ioHelper.notify(IO.DEFAULT_SDK_DEBUG.msg(`Using CA bundle path: ${path}`));\n try {\n if (!fs.pathExistsSync(path)) {\n return undefined;\n }\n return fs.readFileSync(path, { encoding: 'utf-8' });\n } catch (e: any) {\n await this.ioHelper.notify(IO.DEFAULT_SDK_DEBUG.msg(String(e)));\n return undefined;\n }\n }\n return undefined;\n }\n\n /**\n * Find and return a CA certificate bundle path to be passed into the SDK.\n */\n private caBundlePathFromEnvironment(): string | undefined {\n if (process.env.aws_ca_bundle) {\n return process.env.aws_ca_bundle;\n }\n if (process.env.AWS_CA_BUNDLE) {\n return process.env.AWS_CA_BUNDLE;\n }\n return undefined;\n }\n}\n\n", "import type {\n FunctionConfiguration,\n GetSchemaCreationStatusCommandInput,\n GetSchemaCreationStatusCommandOutput,\n ListFunctionsCommandInput,\n StartSchemaCreationCommandInput,\n StartSchemaCreationCommandOutput,\n UpdateApiKeyCommandInput,\n UpdateApiKeyCommandOutput,\n UpdateFunctionCommandInput,\n UpdateFunctionCommandOutput,\n UpdateResolverCommandInput,\n UpdateResolverCommandOutput,\n} from '@aws-sdk/client-appsync';\nimport {\n AppSyncClient,\n GetSchemaCreationStatusCommand,\n paginateListFunctions,\n StartSchemaCreationCommand,\n UpdateApiKeyCommand,\n UpdateFunctionCommand,\n UpdateResolverCommand,\n} from '@aws-sdk/client-appsync';\nimport type {\n GetResourceCommandInput,\n GetResourceCommandOutput,\n ListResourcesCommandInput,\n ListResourcesCommandOutput,\n} from '@aws-sdk/client-cloudcontrol';\nimport {\n CloudControlClient,\n GetResourceCommand,\n ListResourcesCommand,\n} from '@aws-sdk/client-cloudcontrol';\nimport type {\n ContinueUpdateRollbackCommandInput,\n ContinueUpdateRollbackCommandOutput,\n DescribeStackEventsCommandOutput,\n DescribeStackResourcesCommandInput,\n DescribeStackResourcesCommandOutput,\n ListStacksCommandInput,\n ListStacksCommandOutput,\n RollbackStackCommandInput,\n RollbackStackCommandOutput,\n StackResourceSummary,\n CreateChangeSetCommandInput,\n CreateChangeSetCommandOutput,\n CreateGeneratedTemplateCommandInput,\n CreateGeneratedTemplateCommandOutput,\n CreateStackCommandInput,\n CreateStackCommandOutput,\n DeleteChangeSetCommandInput,\n DeleteChangeSetCommandOutput,\n DeleteGeneratedTemplateCommandInput,\n DeleteGeneratedTemplateCommandOutput,\n DeleteStackCommandInput,\n DeleteStackCommandOutput,\n DescribeChangeSetCommandInput,\n DescribeChangeSetCommandOutput,\n DescribeGeneratedTemplateCommandInput,\n DescribeGeneratedTemplateCommandOutput,\n DescribeResourceScanCommandInput,\n DescribeResourceScanCommandOutput,\n DescribeStackEventsCommandInput,\n DescribeStacksCommandInput,\n DescribeStacksCommandOutput,\n ExecuteChangeSetCommandInput,\n ExecuteChangeSetCommandOutput,\n GetGeneratedTemplateCommandInput,\n GetGeneratedTemplateCommandOutput,\n GetTemplateCommandInput,\n GetTemplateCommandOutput,\n GetTemplateSummaryCommandInput,\n GetTemplateSummaryCommandOutput,\n ListExportsCommandInput,\n ListExportsCommandOutput,\n ListResourceScanRelatedResourcesCommandInput,\n ListResourceScanRelatedResourcesCommandOutput,\n ListResourceScanResourcesCommandInput,\n ListResourceScanResourcesCommandOutput,\n ListResourceScansCommandInput,\n ListResourceScansCommandOutput,\n ListStackResourcesCommandInput,\n StartResourceScanCommandInput,\n StartResourceScanCommandOutput,\n UpdateStackCommandInput,\n UpdateStackCommandOutput,\n UpdateTerminationProtectionCommandInput,\n UpdateTerminationProtectionCommandOutput,\n StackSummary,\n} from '@aws-sdk/client-cloudformation';\nimport {\n paginateListStacks,\n CloudFormationClient,\n ContinueUpdateRollbackCommand,\n CreateChangeSetCommand,\n CreateGeneratedTemplateCommand,\n CreateStackCommand,\n DeleteChangeSetCommand,\n DeleteGeneratedTemplateCommand,\n DeleteStackCommand,\n DescribeChangeSetCommand,\n DescribeGeneratedTemplateCommand,\n DescribeResourceScanCommand,\n DescribeStackEventsCommand,\n DescribeStackResourcesCommand,\n DescribeStacksCommand,\n ExecuteChangeSetCommand,\n GetGeneratedTemplateCommand,\n GetTemplateCommand,\n GetTemplateSummaryCommand,\n ListExportsCommand,\n ListResourceScanRelatedResourcesCommand,\n ListResourceScanResourcesCommand,\n ListResourceScansCommand,\n ListStacksCommand,\n paginateListStackResources,\n RollbackStackCommand,\n StartResourceScanCommand,\n UpdateStackCommand,\n UpdateTerminationProtectionCommand,\n} from '@aws-sdk/client-cloudformation';\nimport type {\n FilterLogEventsCommandInput,\n FilterLogEventsCommandOutput,\n DescribeLogGroupsCommandInput,\n DescribeLogGroupsCommandOutput,\n} from '@aws-sdk/client-cloudwatch-logs';\nimport {\n CloudWatchLogsClient,\n DescribeLogGroupsCommand,\n FilterLogEventsCommand,\n} from '@aws-sdk/client-cloudwatch-logs';\nimport {\n CodeBuildClient,\n UpdateProjectCommand,\n type UpdateProjectCommandInput,\n type UpdateProjectCommandOutput,\n} from '@aws-sdk/client-codebuild';\nimport {\n DescribeAvailabilityZonesCommand,\n type DescribeAvailabilityZonesCommandInput,\n type DescribeAvailabilityZonesCommandOutput,\n DescribeImagesCommand,\n type DescribeImagesCommandInput,\n type DescribeImagesCommandOutput,\n DescribeInstancesCommand,\n type DescribeInstancesCommandInput,\n type DescribeInstancesCommandOutput,\n DescribeRouteTablesCommand,\n type DescribeRouteTablesCommandInput,\n type DescribeRouteTablesCommandOutput,\n DescribeSecurityGroupsCommand,\n type DescribeSecurityGroupsCommandInput,\n type DescribeSecurityGroupsCommandOutput,\n DescribeSubnetsCommand,\n type DescribeSubnetsCommandInput,\n type DescribeSubnetsCommandOutput,\n DescribeVpcEndpointServicesCommand,\n type DescribeVpcEndpointServicesCommandInput,\n type DescribeVpcEndpointServicesCommandOutput,\n DescribeVpcsCommand,\n type DescribeVpcsCommandInput,\n type DescribeVpcsCommandOutput,\n DescribeVpnGatewaysCommand,\n type DescribeVpnGatewaysCommandInput,\n type DescribeVpnGatewaysCommandOutput,\n EC2Client,\n} from '@aws-sdk/client-ec2';\nimport type {\n BatchDeleteImageCommandInput,\n BatchDeleteImageCommandOutput,\n ListImagesCommandInput,\n ListImagesCommandOutput,\n PutImageCommandInput,\n PutImageCommandOutput,\n BatchGetImageCommandInput,\n BatchGetImageCommandOutput,\n CreateRepositoryCommandInput,\n CreateRepositoryCommandOutput,\n DescribeImagesCommandInput as ECRDescribeImagesCommandInput,\n DescribeImagesCommandOutput as ECRDescribeImagesCommandOutput,\n DescribeRepositoriesCommandInput,\n DescribeRepositoriesCommandOutput,\n GetAuthorizationTokenCommandInput,\n GetAuthorizationTokenCommandOutput,\n PutImageScanningConfigurationCommandInput,\n PutImageScanningConfigurationCommandOutput,\n} from '@aws-sdk/client-ecr';\nimport {\n BatchDeleteImageCommand,\n CreateRepositoryCommand,\n DescribeImagesCommand as ECRDescribeImagesCommand,\n DescribeRepositoriesCommand,\n ECRClient,\n GetAuthorizationTokenCommand,\n ListImagesCommand,\n PutImageCommand,\n PutImageScanningConfigurationCommand,\n BatchGetImageCommand,\n} from '@aws-sdk/client-ecr';\nimport type {\n DescribeServicesCommandInput,\n RegisterTaskDefinitionCommandInput,\n ListClustersCommandInput,\n ListClustersCommandOutput,\n RegisterTaskDefinitionCommandOutput,\n UpdateServiceCommandInput,\n UpdateServiceCommandOutput,\n} from '@aws-sdk/client-ecs';\nimport {\n ECSClient,\n ListClustersCommand,\n RegisterTaskDefinitionCommand,\n UpdateServiceCommand,\n waitUntilServicesStable,\n} from '@aws-sdk/client-ecs';\nimport type {\n Listener,\n LoadBalancer,\n DescribeListenersCommandInput,\n DescribeListenersCommandOutput,\n DescribeLoadBalancersCommandInput,\n DescribeLoadBalancersCommandOutput,\n DescribeTagsCommandInput,\n DescribeTagsCommandOutput,\n} from '@aws-sdk/client-elastic-load-balancing-v2';\nimport {\n DescribeListenersCommand,\n DescribeLoadBalancersCommand,\n DescribeTagsCommand,\n ElasticLoadBalancingV2Client,\n paginateDescribeListeners,\n paginateDescribeLoadBalancers,\n} from '@aws-sdk/client-elastic-load-balancing-v2';\nimport {\n CreatePolicyCommand,\n type CreatePolicyCommandInput,\n type CreatePolicyCommandOutput,\n GetPolicyCommand,\n type GetPolicyCommandInput,\n type GetPolicyCommandOutput,\n GetRoleCommand,\n type GetRoleCommandInput,\n type GetRoleCommandOutput,\n IAMClient,\n} from '@aws-sdk/client-iam';\nimport {\n DescribeKeyCommand,\n type DescribeKeyCommandInput,\n type DescribeKeyCommandOutput,\n KMSClient,\n ListAliasesCommand,\n type ListAliasesCommandInput,\n type ListAliasesCommandOutput,\n} from '@aws-sdk/client-kms';\nimport {\n InvokeCommand,\n type InvokeCommandInput,\n type InvokeCommandOutput,\n LambdaClient,\n PublishVersionCommand,\n type PublishVersionCommandInput,\n type PublishVersionCommandOutput,\n UpdateAliasCommand,\n type UpdateAliasCommandInput,\n type UpdateAliasCommandOutput,\n UpdateFunctionCodeCommand,\n type UpdateFunctionCodeCommandInput,\n type UpdateFunctionCodeCommandOutput,\n UpdateFunctionConfigurationCommand,\n type UpdateFunctionConfigurationCommandInput,\n type UpdateFunctionConfigurationCommandOutput,\n waitUntilFunctionUpdatedV2,\n} from '@aws-sdk/client-lambda';\nimport {\n GetHostedZoneCommand,\n type GetHostedZoneCommandInput,\n type GetHostedZoneCommandOutput,\n ListHostedZonesByNameCommand,\n type ListHostedZonesByNameCommandInput,\n type ListHostedZonesByNameCommandOutput,\n ListHostedZonesCommand,\n type ListHostedZonesCommandInput,\n type ListHostedZonesCommandOutput,\n Route53Client,\n} from '@aws-sdk/client-route-53';\nimport type {\n DeleteObjectsCommandInput,\n DeleteObjectsCommandOutput,\n DeleteObjectTaggingCommandInput,\n DeleteObjectTaggingCommandOutput,\n GetObjectTaggingCommandInput,\n GetObjectTaggingCommandOutput,\n PutObjectTaggingCommandInput,\n PutObjectTaggingCommandOutput,\n CompleteMultipartUploadCommandOutput,\n GetBucketEncryptionCommandInput,\n GetBucketEncryptionCommandOutput,\n GetBucketLocationCommandInput,\n GetBucketLocationCommandOutput,\n GetObjectCommandInput,\n GetObjectCommandOutput,\n ListObjectsV2CommandInput,\n ListObjectsV2CommandOutput,\n PutObjectCommandInput,\n} from '@aws-sdk/client-s3';\nimport {\n DeleteObjectsCommand,\n DeleteObjectTaggingCommand,\n GetBucketEncryptionCommand,\n GetBucketLocationCommand,\n GetObjectCommand,\n GetObjectTaggingCommand,\n ListObjectsV2Command,\n PutObjectTaggingCommand,\n S3Client,\n} from '@aws-sdk/client-s3';\nimport {\n GetSecretValueCommand,\n type GetSecretValueCommandInput,\n type GetSecretValueCommandOutput,\n SecretsManagerClient,\n} from '@aws-sdk/client-secrets-manager';\nimport type {\n UpdateStateMachineCommandInput,\n UpdateStateMachineCommandOutput,\n} from '@aws-sdk/client-sfn';\nimport {\n SFNClient,\n UpdateStateMachineCommand,\n} from '@aws-sdk/client-sfn';\nimport {\n GetParameterCommand,\n type GetParameterCommandInput,\n type GetParameterCommandOutput,\n SSMClient,\n} from '@aws-sdk/client-ssm';\nimport { GetCallerIdentityCommand, STSClient } from '@aws-sdk/client-sts';\nimport { Upload } from '@aws-sdk/lib-storage';\nimport { getEndpointFromInstructions } from '@smithy/middleware-endpoint';\nimport type { NodeHttpHandlerOptions } from '@smithy/node-http-handler';\nimport type { AwsCredentialIdentityProvider, Logger } from '@smithy/types';\nimport { ConfiguredRetryStrategy } from '@smithy/util-retry';\nimport type { WaiterResult } from '@smithy/util-waiter';\nimport { AccountAccessKeyCache } from './account-cache';\nimport { cachedAsync } from './cached';\nimport type { Account } from './sdk-provider';\nimport { traceMemberMethods } from './tracing';\nimport { defaultCliUserAgent } from './user-agent';\nimport { formatErrorMessage } from '../../util';\nimport { IO, type IoHelper } from '../io/private';\nimport { AuthenticationError } from '../toolkit-error';\n\nexport interface S3ClientOptions {\n /**\n * If APIs are used that require MD5 checksums.\n *\n * Some S3 APIs in SDKv2 have a bug that always requires them to use a MD5 checksum.\n * These APIs are not going to be supported in a FIPS environment.\n */\n needsMd5Checksums?: boolean;\n}\n\n/**\n * Additional SDK configuration options\n */\nexport interface SdkOptions {\n /**\n * Additional descriptive strings that indicate where the \"AssumeRole\" credentials are coming from\n *\n * Will be printed in an error message to help users diagnose auth problems.\n */\n readonly assumeRoleCredentialsSourceDescription?: string;\n}\n\n// TODO: still some cleanup here. Make the pagination functions do all the work here instead of in individual packages.\n// Also add async/await. Does that actually matter in this context? Find out and update accordingly.\n\n// Also add notes to the PR about why you imported everything individually and used 'type' so reviewers don't have to ask.\n\nexport interface ConfigurationOptions {\n region: string;\n credentials: AwsCredentialIdentityProvider;\n requestHandler: NodeHttpHandlerOptions;\n retryStrategy: ConfiguredRetryStrategy;\n customUserAgent: string;\n logger?: Logger;\n s3DisableBodySigning?: boolean;\n computeChecksums?: boolean;\n}\n\nexport interface IAppSyncClient {\n getSchemaCreationStatus(input: GetSchemaCreationStatusCommandInput): Promise<GetSchemaCreationStatusCommandOutput>;\n startSchemaCreation(input: StartSchemaCreationCommandInput): Promise<StartSchemaCreationCommandOutput>;\n updateApiKey(input: UpdateApiKeyCommandInput): Promise<UpdateApiKeyCommandOutput>;\n updateFunction(input: UpdateFunctionCommandInput): Promise<UpdateFunctionCommandOutput>;\n updateResolver(input: UpdateResolverCommandInput): Promise<UpdateResolverCommandOutput>;\n // Pagination functions\n listFunctions(input: ListFunctionsCommandInput): Promise<FunctionConfiguration[]>;\n}\n\nexport interface ICloudControlClient{\n listResources(input: ListResourcesCommandInput): Promise<ListResourcesCommandOutput>;\n getResource(input: GetResourceCommandInput): Promise<GetResourceCommandOutput>;\n}\n\nexport interface ICloudFormationClient {\n continueUpdateRollback(input: ContinueUpdateRollbackCommandInput): Promise<ContinueUpdateRollbackCommandOutput>;\n createChangeSet(input: CreateChangeSetCommandInput): Promise<CreateChangeSetCommandOutput>;\n createGeneratedTemplate(input: CreateGeneratedTemplateCommandInput): Promise<CreateGeneratedTemplateCommandOutput>;\n createStack(input: CreateStackCommandInput): Promise<CreateStackCommandOutput>;\n deleteChangeSet(input: DeleteChangeSetCommandInput): Promise<DeleteChangeSetCommandOutput>;\n deleteGeneratedTemplate(input: DeleteGeneratedTemplateCommandInput): Promise<DeleteGeneratedTemplateCommandOutput>;\n deleteStack(input: DeleteStackCommandInput): Promise<DeleteStackCommandOutput>;\n describeChangeSet(input: DescribeChangeSetCommandInput): Promise<DescribeChangeSetCommandOutput>;\n describeGeneratedTemplate(\n input: DescribeGeneratedTemplateCommandInput,\n ): Promise<DescribeGeneratedTemplateCommandOutput>;\n describeResourceScan(input: DescribeResourceScanCommandInput): Promise<DescribeResourceScanCommandOutput>;\n describeStacks(input: DescribeStacksCommandInput): Promise<DescribeStacksCommandOutput>;\n describeStackResources(input: DescribeStackResourcesCommandInput): Promise<DescribeStackResourcesCommandOutput>;\n executeChangeSet(input: ExecuteChangeSetCommandInput): Promise<ExecuteChangeSetCommandOutput>;\n getGeneratedTemplate(input: GetGeneratedTemplateCommandInput): Promise<GetGeneratedTemplateCommandOutput>;\n getTemplate(input: GetTemplateCommandInput): Promise<GetTemplateCommandOutput>;\n getTemplateSummary(input: GetTemplateSummaryCommandInput): Promise<GetTemplateSummaryCommandOutput>;\n listExports(input: ListExportsCommandInput): Promise<ListExportsCommandOutput>;\n listResourceScanRelatedResources(\n input: ListResourceScanRelatedResourcesCommandInput,\n ): Promise<ListResourceScanRelatedResourcesCommandOutput>;\n listResourceScanResources(\n input: ListResourceScanResourcesCommandInput,\n ): Promise<ListResourceScanResourcesCommandOutput>;\n listResourceScans(input?: ListResourceScansCommandInput): Promise<ListResourceScansCommandOutput>;\n listStacks(input: ListStacksCommandInput): Promise<ListStacksCommandOutput>;\n rollbackStack(input: RollbackStackCommandInput): Promise<RollbackStackCommandOutput>;\n startResourceScan(input: StartResourceScanCommandInput): Promise<StartResourceScanCommandOutput>;\n updateStack(input: UpdateStackCommandInput): Promise<UpdateStackCommandOutput>;\n updateTerminationProtection(\n input: UpdateTerminationProtectionCommandInput,\n ): Promise<UpdateTerminationProtectionCommandOutput>;\n // Pagination functions\n describeStackEvents(input: DescribeStackEventsCommandInput): Promise<DescribeStackEventsCommandOutput>;\n listStackResources(input: ListStackResourcesCommandInput): Promise<StackResourceSummary[]>;\n paginatedListStacks(input: ListStacksCommandInput): Promise<StackSummary[]>;\n}\n\nexport interface ICloudWatchLogsClient {\n describeLogGroups(input: DescribeLogGroupsCommandInput): Promise<DescribeLogGroupsCommandOutput>;\n filterLogEvents(input: FilterLogEventsCommandInput): Promise<FilterLogEventsCommandOutput>;\n}\n\nexport interface ICodeBuildClient {\n updateProject(input: UpdateProjectCommandInput): Promise<UpdateProjectCommandOutput>;\n}\nexport interface IEC2Client {\n describeAvailabilityZones(\n input: DescribeAvailabilityZonesCommandInput,\n ): Promise<DescribeAvailabilityZonesCommandOutput>;\n describeImages(input: DescribeImagesCommandInput): Promise<DescribeImagesCommandOutput>;\n describeInstances(input: DescribeInstancesCommandInput): Promise<DescribeInstancesCommandOutput>;\n describeRouteTables(input: DescribeRouteTablesCommandInput): Promise<DescribeRouteTablesCommandOutput>;\n describeSecurityGroups(input: DescribeSecurityGroupsCommandInput): Promise<DescribeSecurityGroupsCommandOutput>;\n describeSubnets(input: DescribeSubnetsCommandInput): Promise<DescribeSubnetsCommandOutput>;\n describeVpcEndpointServices(\n input: DescribeVpcEndpointServicesCommandInput,\n ): Promise<DescribeVpcEndpointServicesCommandOutput>;\n describeVpcs(input: DescribeVpcsCommandInput): Promise<DescribeVpcsCommandOutput>;\n describeVpnGateways(input: DescribeVpnGatewaysCommandInput): Promise<DescribeVpnGatewaysCommandOutput>;\n}\n\nexport interface IECRClient {\n batchDeleteImage(input: BatchDeleteImageCommandInput): Promise<BatchDeleteImageCommandOutput>;\n batchGetImage(input: BatchGetImageCommandInput): Promise<BatchGetImageCommandOutput>;\n createRepository(input: CreateRepositoryCommandInput): Promise<CreateRepositoryCommandOutput>;\n describeImages(input: ECRDescribeImagesCommandInput): Promise<ECRDescribeImagesCommandOutput>;\n describeRepositories(input: DescribeRepositoriesCommandInput): Promise<DescribeRepositoriesCommandOutput>;\n getAuthorizationToken(input: GetAuthorizationTokenCommandInput): Promise<GetAuthorizationTokenCommandOutput>;\n listImages(input: ListImagesCommandInput): Promise<ListImagesCommandOutput>;\n putImage(input: PutImageCommandInput): Promise<PutImageCommandOutput>;\n putImageScanningConfiguration(\n input: PutImageScanningConfigurationCommandInput,\n ): Promise<PutImageScanningConfigurationCommandOutput>;\n}\n\nexport interface IECSClient {\n listClusters(input: ListClustersCommandInput): Promise<ListClustersCommandOutput>;\n registerTaskDefinition(input: RegisterTaskDefinitionCommandInput): Promise<RegisterTaskDefinitionCommandOutput>;\n updateService(input: UpdateServiceCommandInput): Promise<UpdateServiceCommandOutput>;\n // Waiters\n waitUntilServicesStable(input: DescribeServicesCommandInput): Promise<WaiterResult>;\n}\n\nexport interface IElasticLoadBalancingV2Client {\n describeListeners(input: DescribeListenersCommandInput): Promise<DescribeListenersCommandOutput>;\n describeLoadBalancers(input: DescribeLoadBalancersCommandInput): Promise<DescribeLoadBalancersCommandOutput>;\n describeTags(input: DescribeTagsCommandInput): Promise<DescribeTagsCommandOutput>;\n // Pagination\n paginateDescribeListeners(input: DescribeListenersCommandInput): Promise<Listener[]>;\n paginateDescribeLoadBalancers(input: DescribeLoadBalancersCommandInput): Promise<LoadBalancer[]>;\n}\n\nexport interface IIAMClient {\n createPolicy(input: CreatePolicyCommandInput): Promise<CreatePolicyCommandOutput>;\n getPolicy(input: GetPolicyCommandInput): Promise<GetPolicyCommandOutput>;\n getRole(input: GetRoleCommandInput): Promise<GetRoleCommandOutput>;\n}\n\nexport interface IKMSClient {\n describeKey(input: DescribeKeyCommandInput): Promise<DescribeKeyCommandOutput>;\n listAliases(input: ListAliasesCommandInput): Promise<ListAliasesCommandOutput>;\n}\n\nexport interface ILambdaClient {\n invokeCommand(input: InvokeCommandInput): Promise<InvokeCommandOutput>;\n publishVersion(input: PublishVersionCommandInput): Promise<PublishVersionCommandOutput>;\n updateAlias(input: UpdateAliasCommandInput): Promise<UpdateAliasCommandOutput>;\n updateFunctionCode(input: UpdateFunctionCodeCommandInput): Promise<UpdateFunctionCodeCommandOutput>;\n updateFunctionConfiguration(\n input: UpdateFunctionConfigurationCommandInput,\n ): Promise<UpdateFunctionConfigurationCommandOutput>;\n // Waiters\n waitUntilFunctionUpdated(delaySeconds: number, input: UpdateFunctionConfigurationCommandInput): Promise<WaiterResult>;\n}\n\nexport interface IRoute53Client {\n getHostedZone(input: GetHostedZoneCommandInput): Promise<GetHostedZoneCommandOutput>;\n listHostedZones(input: ListHostedZonesCommandInput): Promise<ListHostedZonesCommandOutput>;\n listHostedZonesByName(input: ListHostedZonesByNameCommandInput): Promise<ListHostedZonesByNameCommandOutput>;\n}\n\nexport interface IS3Client {\n deleteObjects(input: DeleteObjectsCommandInput): Promise<DeleteObjectsCommandOutput>;\n deleteObjectTagging(input: DeleteObjectTaggingCommandInput): Promise<DeleteObjectTaggingCommandOutput>;\n getBucketEncryption(input: GetBucketEncryptionCommandInput): Promise<GetBucketEncryptionCommandOutput>;\n getBucketLocation(input: GetBucketLocationCommandInput): Promise<GetBucketLocationCommandOutput>;\n getObject(input: GetObjectCommandInput): Promise<GetObjectCommandOutput>;\n getObjectTagging(input: GetObjectTaggingCommandInput): Promise<GetObjectTaggingCommandOutput>;\n listObjectsV2(input: ListObjectsV2CommandInput): Promise<ListObjectsV2CommandOutput>;\n putObjectTagging(input: PutObjectTaggingCommandInput): Promise<PutObjectTaggingCommandOutput>;\n upload(input: PutObjectCommandInput): Promise<CompleteMultipartUploadCommandOutput>;\n}\n\nexport interface ISecretsManagerClient {\n getSecretValue(input: GetSecretValueCommandInput): Promise<GetSecretValueCommandOutput>;\n}\n\nexport interface ISSMClient {\n getParameter(input: GetParameterCommandInput): Promise<GetParameterCommandOutput>;\n}\n\nexport interface IStepFunctionsClient {\n updateStateMachine(input: UpdateStateMachineCommandInput): Promise<UpdateStateMachineCommandOutput>;\n}\n\n/**\n * Base functionality of SDK without credential fetching\n */\n@traceMemberMethods\nexport class SDK {\n public readonly currentRegion: string;\n\n public readonly config: ConfigurationOptions;\n\n protected readonly logger?: Logger;\n\n private readonly accountCache;\n\n /**\n * STS is used to check credential validity, don't do too many retries.\n */\n private readonly stsRetryStrategy = new ConfiguredRetryStrategy(3, (attempt) => 100 * (2 ** attempt));\n\n /**\n * Whether we have proof that the credentials have not expired\n *\n * We need to do some manual plumbing around this because the JS SDKv2 treats `ExpiredToken`\n * as retriable and we have hefty retries on CFN calls making the CLI hang for a good 15 minutes\n * if the credentials have expired.\n */\n private _credentialsValidated = false;\n\n /**\n * A function to create debug messages\n */\n private readonly debug: (msg: string) => Promise<void>;\n\n constructor(\n private readonly credProvider: AwsCredentialIdentityProvider,\n region: string,\n requestHandler: NodeHttpHandlerOptions,\n ioHelper: IoHelper,\n logger?: Logger,\n ) {\n const debugFn = async (msg: string) => ioHelper.notify(IO.DEFAULT_SDK_DEBUG.msg(msg));\n this.accountCache = new AccountAccessKeyCache(AccountAccessKeyCache.DEFAULT_PATH, debugFn);\n this.debug = debugFn;\n this.config = {\n region,\n credentials: credProvider,\n requestHandler,\n retryStrategy: new ConfiguredRetryStrategy(7, (attempt) => 300 * (2 ** attempt)),\n customUserAgent: defaultCliUserAgent(),\n logger,\n };\n this.logger = logger;\n this.currentRegion = region;\n }\n\n public appendCustomUserAgent(userAgentData?: string): void {\n if (!userAgentData) {\n return;\n }\n\n const currentCustomUserAgent = this.config.customUserAgent;\n this.config.customUserAgent = currentCustomUserAgent ? `${currentCustomUserAgent} ${userAgentData}` : userAgentData;\n }\n\n public removeCustomUserAgent(userAgentData: string): void {\n this.config.customUserAgent = this.config.customUserAgent?.replace(userAgentData, '');\n }\n\n public appsync(): IAppSyncClient {\n const client = new AppSyncClient(this.config);\n return {\n getSchemaCreationStatus: (\n input: GetSchemaCreationStatusCommandInput,\n ): Promise<GetSchemaCreationStatusCommandOutput> => client.send(new GetSchemaCreationStatusCommand(input)),\n startSchemaCreation: (input: StartSchemaCreationCommandInput): Promise<StartSchemaCreationCommandOutput> =>\n client.send(new StartSchemaCreationCommand(input)),\n updateApiKey: (input: UpdateApiKeyCommandInput): Promise<UpdateApiKeyCommandOutput> =>\n client.send(new UpdateApiKeyCommand(input)),\n updateFunction: (input: UpdateFunctionCommandInput): Promise<UpdateFunctionCommandOutput> =>\n client.send(new UpdateFunctionCommand(input)),\n updateResolver: (input: UpdateResolverCommandInput): Promise<UpdateResolverCommandOutput> =>\n client.send(new UpdateResolverCommand(input)),\n\n // Pagination Functions\n listFunctions: async (input: ListFunctionsCommandInput): Promise<FunctionConfiguration[]> => {\n const functions = Array<FunctionConfiguration>();\n const paginator = paginateListFunctions({ client }, input);\n for await (const page of paginator) {\n functions.push(...(page.functions || []));\n }\n return functions;\n },\n };\n }\n\n public cloudControl(): ICloudControlClient {\n const client = new CloudControlClient(this.config);\n return {\n listResources: (input: ListResourcesCommandInput): Promise<ListResourcesCommandOutput> =>\n client.send(new ListResourcesCommand(input)),\n getResource: (input: GetResourceCommandInput): Promise<GetResourceCommandOutput> =>\n client.send(new GetResourceCommand(input)),\n };\n }\n\n public cloudFormation(): ICloudFormationClient {\n const client = new CloudFormationClient({\n ...this.config,\n retryStrategy: new ConfiguredRetryStrategy(11, (attempt: number) => 1000 * (2 ** attempt)),\n });\n return {\n continueUpdateRollback: async (\n input: ContinueUpdateRollbackCommandInput,\n ): Promise<ContinueUpdateRollbackCommandOutput> => client.send(new ContinueUpdateRollbackCommand(input)),\n createChangeSet: (input: CreateChangeSetCommandInput): Promise<CreateChangeSetCommandOutput> =>\n client.send(new CreateChangeSetCommand(input)),\n createGeneratedTemplate: (\n input: CreateGeneratedTemplateCommandInput,\n ): Promise<CreateGeneratedTemplateCommandOutput> => client.send(new CreateGeneratedTemplateCommand(input)),\n createStack: (input: CreateStackCommandInput): Promise<CreateStackCommandOutput> =>\n client.send(new CreateStackCommand(input)),\n deleteChangeSet: (input: DeleteChangeSetCommandInput): Promise<DeleteChangeSetCommandOutput> =>\n client.send(new DeleteChangeSetCommand(input)),\n deleteGeneratedTemplate: (\n input: DeleteGeneratedTemplateCommandInput,\n ): Promise<DeleteGeneratedTemplateCommandOutput> => client.send(new DeleteGeneratedTemplateCommand(input)),\n deleteStack: (input: DeleteStackCommandInput): Promise<DeleteStackCommandOutput> =>\n client.send(new DeleteStackCommand(input)),\n describeChangeSet: (input: DescribeChangeSetCommandInput): Promise<DescribeChangeSetCommandOutput> =>\n client.send(new DescribeChangeSetCommand(input)),\n describeGeneratedTemplate: (\n input: DescribeGeneratedTemplateCommandInput,\n ): Promise<DescribeGeneratedTemplateCommandOutput> => client.send(new DescribeGeneratedTemplateCommand(input)),\n describeResourceScan: (input: DescribeResourceScanCommandInput): Promise<DescribeResourceScanCommandOutput> =>\n client.send(new DescribeResourceScanCommand(input)),\n describeStacks: (input: DescribeStacksCommandInput): Promise<DescribeStacksCommandOutput> =>\n client.send(new DescribeStacksCommand(input)),\n describeStackResources: (input: DescribeStackResourcesCommandInput): Promise<DescribeStackResourcesCommandOutput> =>\n client.send(new DescribeStackResourcesCommand(input)),\n executeChangeSet: (input: ExecuteChangeSetCommandInput): Promise<ExecuteChangeSetCommandOutput> =>\n client.send(new ExecuteChangeSetCommand(input)),\n getGeneratedTemplate: (input: GetGeneratedTemplateCommandInput): Promise<GetGeneratedTemplateCommandOutput> =>\n client.send(new GetGeneratedTemplateCommand(input)),\n getTemplate: (input: GetTemplateCommandInput): Promise<GetTemplateCommandOutput> =>\n client.send(new GetTemplateCommand(input)),\n getTemplateSummary: (input: GetTemplateSummaryCommandInput): Promise<GetTemplateSummaryCommandOutput> =>\n client.send(new GetTemplateSummaryCommand(input)),\n listExports: (input: ListExportsCommandInput): Promise<ListExportsCommandOutput> =>\n client.send(new ListExportsCommand(input)),\n listResourceScanRelatedResources: (\n input: ListResourceScanRelatedResourcesCommandInput,\n ): Promise<ListResourceScanRelatedResourcesCommandOutput> =>\n client.send(new ListResourceScanRelatedResourcesCommand(input)),\n listResourceScanResources: (\n input: ListResourceScanResourcesCommandInput,\n ): Promise<ListResourceScanResourcesCommandOutput> => client.send(new ListResourceScanResourcesCommand(input)),\n listResourceScans: (input: ListResourceScansCommandInput): Promise<ListResourceScansCommandOutput> =>\n client.send(new ListResourceScansCommand(input)),\n listStacks: (input: ListStacksCommandInput): Promise<ListStacksCommandOutput> =>\n client.send(new ListStacksCommand(input)),\n rollbackStack: (input: RollbackStackCommandInput): Promise<RollbackStackCommandOutput> =>\n client.send(new RollbackStackCommand(input)),\n startResourceScan: (input: StartResourceScanCommandInput): Promise<StartResourceScanCommandOutput> =>\n client.send(new StartResourceScanCommand(input)),\n updateStack: (input: UpdateStackCommandInput): Promise<UpdateStackCommandOutput> =>\n client.send(new UpdateStackCommand(input)),\n updateTerminationProtection: (\n input: UpdateTerminationProtectionCommandInput,\n ): Promise<UpdateTerminationProtectionCommandOutput> =>\n client.send(new UpdateTerminationProtectionCommand(input)),\n describeStackEvents: (input: DescribeStackEventsCommandInput): Promise<DescribeStackEventsCommandOutput> => {\n return client.send(new DescribeStackEventsCommand(input));\n },\n listStackResources: async (input: ListStackResourcesCommandInput): Promise<StackResourceSummary[]> => {\n const stackResources = Array<StackResourceSummary>();\n const paginator = paginateListStackResources({ client }, input);\n for await (const page of paginator) {\n stackResources.push(...(page?.StackResourceSummaries || []));\n }\n return stackResources;\n },\n paginatedListStacks: async (input: ListStacksCommandInput): Promise<StackSummary[]> => {\n const stackResources = Array<StackSummary>();\n const paginator = paginateListStacks({ client }, input);\n for await (const page of paginator) {\n stackResources.push(...(page?.StackSummaries || []));\n }\n return stackResources;\n },\n };\n }\n\n public cloudWatchLogs(): ICloudWatchLogsClient {\n const client = new CloudWatchLogsClient(this.config);\n return {\n describeLogGroups: (input: DescribeLogGroupsCommandInput): Promise<DescribeLogGroupsCommandOutput> =>\n client.send(new DescribeLogGroupsCommand(input)),\n filterLogEvents: (input: FilterLogEventsCommandInput): Promise<FilterLogEventsCommandOutput> =>\n client.send(new FilterLogEventsCommand(input)),\n };\n }\n\n public codeBuild(): ICodeBuildClient {\n const client = new CodeBuildClient(this.config);\n return {\n updateProject: (input: UpdateProjectCommandInput): Promise<UpdateProjectCommandOutput> =>\n client.send(new UpdateProjectCommand(input)),\n };\n }\n\n public ec2(): IEC2Client {\n const client = new EC2Client(this.config);\n return {\n describeAvailabilityZones: (\n input: DescribeAvailabilityZonesCommandInput,\n ): Promise<DescribeAvailabilityZonesCommandOutput> => client.send(new DescribeAvailabilityZonesCommand(input)),\n describeImages: (input: DescribeImagesCommandInput): Promise<DescribeImagesCommandOutput> =>\n client.send(new DescribeImagesCommand(input)),\n describeInstances: (input: DescribeInstancesCommandInput): Promise<DescribeInstancesCommandOutput> =>\n client.send(new DescribeInstancesCommand(input)),\n describeRouteTables: (input: DescribeRouteTablesCommandInput): Promise<DescribeRouteTablesCommandOutput> =>\n client.send(new DescribeRouteTablesCommand(input)),\n describeSecurityGroups: (\n input: DescribeSecurityGroupsCommandInput,\n ): Promise<DescribeSecurityGroupsCommandOutput> => client.send(new DescribeSecurityGroupsCommand(input)),\n describeSubnets: (input: DescribeSubnetsCommandInput): Promise<DescribeSubnetsCommandOutput> =>\n client.send(new DescribeSubnetsCommand(input)),\n describeVpcEndpointServices: (\n input: DescribeVpcEndpointServicesCommandInput,\n ): Promise<DescribeVpcEndpointServicesCommandOutput> =>\n client.send(new DescribeVpcEndpointServicesCommand(input)),\n describeVpcs: (input: DescribeVpcsCommandInput): Promise<DescribeVpcsCommandOutput> =>\n client.send(new DescribeVpcsCommand(input)),\n describeVpnGateways: (input: DescribeVpnGatewaysCommandInput): Promise<DescribeVpnGatewaysCommandOutput> =>\n client.send(new DescribeVpnGatewaysCommand(input)),\n };\n }\n\n public ecr(): IECRClient {\n const client = new ECRClient(this.config);\n return {\n batchDeleteImage: (input: BatchDeleteImageCommandInput): Promise<BatchDeleteImageCommandOutput> =>\n client.send(new BatchDeleteImageCommand(input)),\n batchGetImage: (input: BatchGetImageCommandInput): Promise<BatchGetImageCommandOutput> =>\n client.send(new BatchGetImageCommand(input)),\n createRepository: (input: CreateRepositoryCommandInput): Promise<CreateRepositoryCommandOutput> =>\n client.send(new CreateRepositoryCommand(input)),\n describeImages: (input: ECRDescribeImagesCommandInput): Promise<ECRDescribeImagesCommandOutput> =>\n client.send(new ECRDescribeImagesCommand(input)),\n describeRepositories: (input: DescribeRepositoriesCommandInput): Promise<DescribeRepositoriesCommandOutput> =>\n client.send(new DescribeRepositoriesCommand(input)),\n getAuthorizationToken: (input: GetAuthorizationTokenCommandInput): Promise<GetAuthorizationTokenCommandOutput> =>\n client.send(new GetAuthorizationTokenCommand(input)),\n listImages: (input: ListImagesCommandInput): Promise<ListImagesCommandOutput> =>\n client.send(new ListImagesCommand(input)),\n putImage: (input: PutImageCommandInput): Promise<PutImageCommandOutput> =>\n client.send(new PutImageCommand(input)),\n putImageScanningConfiguration: (\n input: PutImageScanningConfigurationCommandInput,\n ): Promise<PutImageScanningConfigurationCommandOutput> =>\n client.send(new PutImageScanningConfigurationCommand(input)),\n };\n }\n\n public ecs(): IECSClient {\n const client = new ECSClient(this.config);\n return {\n listClusters: (input: ListClustersCommandInput): Promise<ListClustersCommandOutput> =>\n client.send(new ListClustersCommand(input)),\n registerTaskDefinition: (\n input: RegisterTaskDefinitionCommandInput,\n ): Promise<RegisterTaskDefinitionCommandOutput> => client.send(new RegisterTaskDefinitionCommand(input)),\n updateService: (input: UpdateServiceCommandInput): Promise<UpdateServiceCommandOutput> =>\n client.send(new UpdateServiceCommand(input)),\n // Waiters\n waitUntilServicesStable: (input: DescribeServicesCommandInput): Promise<WaiterResult> => {\n return waitUntilServicesStable(\n {\n client,\n maxWaitTime: 600,\n minDelay: 6,\n maxDelay: 6,\n },\n input,\n );\n },\n };\n }\n\n public elbv2(): IElasticLoadBalancingV2Client {\n const client = new ElasticLoadBalancingV2Client(this.config);\n return {\n describeListeners: (input: DescribeListenersCommandInput): Promise<DescribeListenersCommandOutput> =>\n client.send(new DescribeListenersCommand(input)),\n describeLoadBalancers: (input: DescribeLoadBalancersCommandInput): Promise<DescribeLoadBalancersCommandOutput> =>\n client.send(new DescribeLoadBalancersCommand(input)),\n describeTags: (input: DescribeTagsCommandInput): Promise<DescribeTagsCommandOutput> =>\n client.send(new DescribeTagsCommand(input)),\n // Pagination Functions\n paginateDescribeListeners: async (input: DescribeListenersCommandInput): Promise<Listener[]> => {\n const listeners = Array<Listener>();\n const paginator = paginateDescribeListeners({ client }, input);\n for await (const page of paginator) {\n listeners.push(...(page?.Listeners || []));\n }\n return listeners;\n },\n paginateDescribeLoadBalancers: async (input: DescribeLoadBalancersCommandInput): Promise<LoadBalancer[]> => {\n const loadBalancers = Array<LoadBalancer>();\n const paginator = paginateDescribeLoadBalancers({ client }, input);\n for await (const page of paginator) {\n loadBalancers.push(...(page?.LoadBalancers || []));\n }\n return loadBalancers;\n },\n };\n }\n\n public iam(): IIAMClient {\n const client = new IAMClient(this.config);\n return {\n createPolicy: (input: CreatePolicyCommandInput): Promise<CreatePolicyCommandOutput> =>\n client.send(new CreatePolicyCommand(input)),\n getPolicy: (input: GetPolicyCommandInput): Promise<GetPolicyCommandOutput> =>\n client.send(new GetPolicyCommand(input)),\n getRole: (input: GetRoleCommandInput): Promise<GetRoleCommandOutput> => client.send(new GetRoleCommand(input)),\n };\n }\n\n public kms(): IKMSClient {\n const client = new KMSClient(this.config);\n return {\n describeKey: (input: DescribeKeyCommandInput): Promise<DescribeKeyCommandOutput> =>\n client.send(new DescribeKeyCommand(input)),\n listAliases: (input: ListAliasesCommandInput): Promise<ListAliasesCommandOutput> =>\n client.send(new ListAliasesCommand(input)),\n };\n }\n\n public lambda(): ILambdaClient {\n const client = new LambdaClient(this.config);\n return {\n invokeCommand: (input: InvokeCommandInput): Promise<InvokeCommandOutput> => client.send(new InvokeCommand(input)),\n publishVersion: (input: PublishVersionCommandInput): Promise<PublishVersionCommandOutput> =>\n client.send(new PublishVersionCommand(input)),\n updateAlias: (input: UpdateAliasCommandInput): Promise<UpdateAliasCommandOutput> =>\n client.send(new UpdateAliasCommand(input)),\n updateFunctionCode: (input: UpdateFunctionCodeCommandInput): Promise<UpdateFunctionCodeCommandOutput> =>\n client.send(new UpdateFunctionCodeCommand(input)),\n updateFunctionConfiguration: (\n input: UpdateFunctionConfigurationCommandInput,\n ): Promise<UpdateFunctionConfigurationCommandOutput> =>\n client.send(new UpdateFunctionConfigurationCommand(input)),\n // Waiters\n waitUntilFunctionUpdated: (\n delaySeconds: number,\n input: UpdateFunctionConfigurationCommandInput,\n ): Promise<WaiterResult> => {\n return waitUntilFunctionUpdatedV2(\n {\n client,\n maxDelay: delaySeconds,\n minDelay: delaySeconds,\n maxWaitTime: delaySeconds * 60,\n },\n input,\n );\n },\n };\n }\n\n public route53(): IRoute53Client {\n const client = new Route53Client(this.config);\n return {\n getHostedZone: (input: GetHostedZoneCommandInput): Promise<GetHostedZoneCommandOutput> =>\n client.send(new GetHostedZoneCommand(input)),\n listHostedZones: (input: ListHostedZonesCommandInput): Promise<ListHostedZonesCommandOutput> =>\n client.send(new ListHostedZonesCommand(input)),\n listHostedZonesByName: (input: ListHostedZonesByNameCommandInput): Promise<ListHostedZonesByNameCommandOutput> =>\n client.send(new ListHostedZonesByNameCommand(input)),\n };\n }\n\n public s3(): IS3Client {\n const client = new S3Client(this.config);\n return {\n deleteObjects: (input: DeleteObjectsCommandInput): Promise<DeleteObjectsCommandOutput> =>\n client.send(new DeleteObjectsCommand({\n ...input,\n ChecksumAlgorithm: 'SHA256',\n })),\n deleteObjectTagging: (input: DeleteObjectTaggingCommandInput): Promise<DeleteObjectTaggingCommandOutput> =>\n client.send(new DeleteObjectTaggingCommand(input)),\n getBucketEncryption: (input: GetBucketEncryptionCommandInput): Promise<GetBucketEncryptionCommandOutput> =>\n client.send(new GetBucketEncryptionCommand(input)),\n getBucketLocation: (input: GetBucketLocationCommandInput): Promise<GetBucketLocationCommandOutput> =>\n client.send(new GetBucketLocationCommand(input)),\n getObject: (input: GetObjectCommandInput): Promise<GetObjectCommandOutput> =>\n client.send(new GetObjectCommand(input)),\n getObjectTagging: (input: GetObjectTaggingCommandInput): Promise<GetObjectTaggingCommandOutput> =>\n client.send(new GetObjectTaggingCommand(input)),\n listObjectsV2: (input: ListObjectsV2CommandInput): Promise<ListObjectsV2CommandOutput> =>\n client.send(new ListObjectsV2Command(input)),\n putObjectTagging: (input: PutObjectTaggingCommandInput): Promise<PutObjectTaggingCommandOutput> =>\n client.send(new PutObjectTaggingCommand({\n ...input,\n ChecksumAlgorithm: 'SHA256',\n })),\n upload: (input: PutObjectCommandInput): Promise<CompleteMultipartUploadCommandOutput> => {\n try {\n const upload = new Upload({\n client,\n params: { ...input, ChecksumAlgorithm: 'SHA256' },\n });\n\n return upload.done();\n } catch (e: any) {\n throw new AuthenticationError(`Upload failed: ${formatErrorMessage(e)}`);\n }\n },\n };\n }\n\n public secretsManager(): ISecretsManagerClient {\n const client = new SecretsManagerClient(this.config);\n return {\n getSecretValue: (input: GetSecretValueCommandInput): Promise<GetSecretValueCommandOutput> =>\n client.send(new GetSecretValueCommand(input)),\n };\n }\n\n public ssm(): ISSMClient {\n const client = new SSMClient(this.config);\n return {\n getParameter: (input: GetParameterCommandInput): Promise<GetParameterCommandOutput> =>\n client.send(new GetParameterCommand(input)),\n };\n }\n\n public stepFunctions(): IStepFunctionsClient {\n const client = new SFNClient(this.config);\n return {\n updateStateMachine: (input: UpdateStateMachineCommandInput): Promise<UpdateStateMachineCommandOutput> =>\n client.send(new UpdateStateMachineCommand(input)),\n };\n }\n\n /**\n * The AWS SDK v3 requires a client config and a command in order to get an endpoint for\n * any given service.\n */\n public async getUrlSuffix(region: string): Promise<string> {\n const cfn = new CloudFormationClient({ region });\n const endpoint = await getEndpointFromInstructions({}, DescribeStackResourcesCommand, { ...cfn.config });\n return endpoint.url.hostname.split(`${region}.`).pop()!;\n }\n\n public async currentAccount(): Promise<Account> {\n return cachedAsync(this, CURRENT_ACCOUNT_KEY, async () => {\n const creds = await this.credProvider();\n return this.accountCache.fetch(creds.accessKeyId, async () => {\n // if we don't have one, resolve from STS and store in cache.\n await this.debug('Looking up default account ID from STS');\n const client = new STSClient({\n ...this.config,\n retryStrategy: this.stsRetryStrategy,\n });\n const command = new GetCallerIdentityCommand({});\n const result = await client.send(command);\n const accountId = result.Account;\n const partition = result.Arn!.split(':')[1];\n if (!accountId) {\n throw new AuthenticationError(\"STS didn't return an account ID\");\n }\n await this.debug(`Default account ID: ${accountId}`);\n\n // Save another STS call later if this one already succeeded\n this._credentialsValidated = true;\n return { accountId, partition };\n });\n });\n }\n\n /**\n * Make sure the the current credentials are not expired\n */\n public async validateCredentials() {\n if (this._credentialsValidated) {\n return;\n }\n\n const client = new STSClient({ ...this.config, retryStrategy: this.stsRetryStrategy });\n await client.send(new GetCallerIdentityCommand({}));\n this._credentialsValidated = true;\n }\n}\n\nconst CURRENT_ACCOUNT_KEY = Symbol('current_account_key');\n", "import * as path from 'path';\nimport * as fs from 'fs-extra';\nimport type { Account } from './sdk-provider';\nimport { cdkCacheDir } from '../../util';\n\n/**\n * Disk cache which maps access key IDs to account IDs.\n * Usage:\n * cache.get(accessKey) => accountId | undefined\n * cache.put(accessKey, accountId)\n */\nexport class AccountAccessKeyCache {\n /**\n * Max number of entries in the cache, after which the cache will be reset.\n */\n public static readonly MAX_ENTRIES = 1000;\n\n /**\n * The default path used for the accounts access key cache\n */\n public static get DEFAULT_PATH(): string {\n // needs to be a getter because cdkCacheDir can be set via env variable and might change\n return path.join(cdkCacheDir(), 'accounts_partitions.json');\n }\n\n private readonly cacheFile: string;\n\n private readonly debug: (msg: string) => Promise<void>;\n\n /**\n * @param filePath Path to the cache file\n */\n constructor(filePath: string = AccountAccessKeyCache.DEFAULT_PATH, debugFn: (msg: string) => Promise<void>) {\n this.cacheFile = filePath;\n this.debug = debugFn;\n }\n\n /**\n * Tries to fetch the account ID from cache. If it's not in the cache, invokes\n * the resolver function which should retrieve the account ID and return it.\n * Then, it will be stored into disk cache returned.\n *\n * Example:\n *\n * const accountId = cache.fetch(accessKey, async () => {\n * return await fetchAccountIdFromSomewhere(accessKey);\n * });\n */\n public async fetch<A extends Account>(accessKeyId: string, resolver: () => Promise<A>) {\n // try to get account ID based on this access key ID from disk.\n const cached = await this.get(accessKeyId);\n if (cached) {\n await this.debug(`Retrieved account ID ${cached.accountId} from disk cache`);\n return cached;\n }\n\n // if it's not in the cache, resolve and put in cache.\n const account = await resolver();\n if (account) {\n await this.put(accessKeyId, account);\n }\n\n return account;\n }\n\n /** Get the account ID from an access key or undefined if not in cache */\n public async get(accessKeyId: string): Promise<Account | undefined> {\n const map = await this.loadMap();\n return map[accessKeyId];\n }\n\n /** Put a mapping between access key and account ID */\n public async put(accessKeyId: string, account: Account) {\n let map = await this.loadMap();\n\n // nuke cache if it's too big.\n if (Object.keys(map).length >= AccountAccessKeyCache.MAX_ENTRIES) {\n map = {};\n }\n\n map[accessKeyId] = account;\n await this.saveMap(map);\n }\n\n private async loadMap(): Promise<{ [accessKeyId: string]: Account }> {\n try {\n return await fs.readJson(this.cacheFile);\n } catch (e: any) {\n // File doesn't exist or is not readable. This is a cache,\n // pretend we successfully loaded an empty map.\n if (e.code === 'ENOENT' || e.code === 'EACCES') {\n return {};\n }\n // File is not JSON, could be corrupted because of concurrent writes.\n // Again, an empty cache is fine.\n if (e instanceof SyntaxError) {\n return {};\n }\n throw e;\n }\n }\n\n private async saveMap(map: { [accessKeyId: string]: Account }) {\n try {\n await fs.ensureFile(this.cacheFile);\n await fs.writeJson(this.cacheFile, map, { spaces: 2 });\n } catch (e: any) {\n // File doesn't exist or file/dir isn't writable. This is a cache,\n // if we can't write it then too bad.\n if (e.code === 'ENOENT' || e.code === 'EACCES' || e.code === 'EROFS') {\n return;\n }\n throw e;\n }\n }\n}\n", "/**\n * Cache the result of a function on an object\n *\n * We could have used @decorators to make this nicer but we don't use them anywhere yet,\n * so let's keep it simple and readable.\n */\nexport function cached<A extends object, B>(obj: A, sym: symbol, fn: () => B): B {\n if (!(sym in obj)) {\n (obj as any)[sym] = fn();\n }\n return (obj as any)[sym];\n}\n\n/**\n * Like 'cached', but async\n */\nexport async function cachedAsync<A extends object, B>(obj: A, sym: symbol, fn: () => Promise<B>): Promise<B> {\n if (!(sym in obj)) {\n (obj as any)[sym] = await fn();\n }\n return (obj as any)[sym];\n}\n", "import type { Logger } from '@smithy/types';\n\nlet ENABLED = false;\nlet INDENT = 0;\n\nexport function setSdkTracing(enabled: boolean) {\n ENABLED = enabled;\n}\n\n/**\n * Method decorator to trace a single static or member method, any time it's called\n */\nexport function callTrace(fn: string, className?: string, logger?: Logger) {\n if (!ENABLED || !logger) {\n return;\n }\n\n logger.info(`[trace] ${' '.repeat(INDENT)}${className || '(anonymous)'}#${fn}()`);\n}\n\n/**\n * Method decorator to trace a single member method any time it's called\n */\nfunction traceCall(receiver: object, _propertyKey: string, descriptor: PropertyDescriptor, parentClassName?: string) {\n const fn = descriptor.value;\n const className = typeof receiver === 'function' ? receiver.name : parentClassName;\n\n descriptor.value = function (...args: any[]) {\n const logger = (this as any).logger;\n if (!ENABLED || typeof logger?.info !== 'function') {\n return fn.apply(this, args);\n }\n\n logger.info.apply(logger, [`[trace] ${' '.repeat(INDENT)}${className || this.constructor.name || '(anonymous)'}#${fn.name}()`]);\n INDENT += 2;\n\n const ret = fn.apply(this, args);\n if (ret instanceof Promise) {\n return ret.finally(() => {\n INDENT -= 2;\n });\n } else {\n INDENT -= 2;\n return ret;\n }\n };\n return descriptor;\n}\n\n/**\n * Class decorator, enable tracing for all member methods on this class\n * @deprecated this doesn't work well with localized logging instances, don't use\n */\nexport function traceMemberMethods(constructor: Function) {\n // Instance members\n for (const [name, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(constructor.prototype))) {\n if (typeof descriptor.value !== 'function') {\n continue;\n }\n const newDescriptor = traceCall(constructor.prototype, name, descriptor, constructor.name) ?? descriptor;\n Object.defineProperty(constructor.prototype, name, newDescriptor);\n }\n}\n", "import * as path from 'path';\nimport { readIfPossible } from './util';\nimport { bundledPackageRootDir } from '../../util';\n/**\n * Find the package.json from the main toolkit.\n *\n * If we can't read it for some reason, try to do something reasonable anyway.\n * Fall back to argv[1], or a standard string if that is undefined for some reason.\n */\nexport function defaultCliUserAgent() {\n const root = bundledPackageRootDir(__dirname, false);\n const pkg = JSON.parse((root ? readIfPossible(path.join(root, 'package.json')) : undefined) ?? '{}');\n const name = pkg.name ?? path.basename(process.argv[1] ?? 'cdk-cli');\n const version = pkg.version ?? '<unknown>';\n return `${name}/${version}`;\n}\n", "import * as fs from 'fs-extra';\n\n/**\n * Read a file if it exists, or return undefined\n *\n * Not async because it is used in the constructor\n */\nexport function readIfPossible(filename: string): string | undefined {\n try {\n if (!fs.pathExistsSync(filename)) {\n return undefined;\n }\n return fs.readFileSync(filename, { encoding: 'utf-8' });\n } catch (e: any) {\n return undefined;\n }\n}\n", "import * as os from 'os';\nimport type { ContextLookupRoleOptions } from '@aws-cdk/cloud-assembly-schema';\nimport type { Environment } from '@aws-cdk/cx-api';\nimport { EnvironmentUtils, UNKNOWN_ACCOUNT, UNKNOWN_REGION } from '@aws-cdk/cx-api';\nimport type { AssumeRoleCommandInput } from '@aws-sdk/client-sts';\nimport { fromTemporaryCredentials } from '@aws-sdk/credential-providers';\nimport type { NodeHttpHandlerOptions } from '@smithy/node-http-handler';\nimport type { AwsCredentialIdentityProvider, Logger } from '@smithy/types';\nimport { AwsCliCompatible } from './awscli-compatible';\nimport { cached } from './cached';\nimport { CredentialPlugins } from './credential-plugins';\nimport { makeCachingProvider } from './provider-caching';\nimport { SDK } from './sdk';\nimport { callTrace, traceMemberMethods } from './tracing';\nimport { formatErrorMessage } from '../../util';\nimport { IO, type IoHelper } from '../io/private';\nimport { Mode, PluginHost } from '../plugin';\nimport { AuthenticationError } from '../toolkit-error';\n\nexport type AssumeRoleAdditionalOptions = Partial<Omit<AssumeRoleCommandInput, 'ExternalId' | 'RoleArn'>>;\n\n/**\n * Options for the default SDK provider\n */\nexport interface SdkProviderOptions {\n /**\n * IoHelper for messaging\n */\n readonly ioHelper: IoHelper;\n\n /**\n * Profile to read from ~/.aws\n *\n * @default - No profile\n */\n readonly profile?: string;\n\n /**\n * HTTP options for SDK\n */\n readonly httpOptions?: SdkHttpOptions;\n\n /**\n * The logger for sdk calls.\n */\n readonly logger?: Logger;\n}\n\n/**\n * Options for individual SDKs\n */\nexport interface SdkHttpOptions {\n /**\n * Proxy address to use\n *\n * @default No proxy\n */\n readonly proxyAddress?: string;\n\n /**\n * A path to a certificate bundle that contains a cert to be trusted.\n *\n * @default No certificate bundle\n */\n readonly caBundlePath?: string;\n}\n\nconst CACHED_ACCOUNT = Symbol('cached_account');\n\n/**\n * SDK configuration for a given environment\n * 'forEnvironment' will attempt to assume a role and if it\n * is not successful, then it will either:\n * 1. Check to see if the default credentials (local credentials the CLI was executed with)\n * are for the given environment. If they are then return those.\n * 2. If the default credentials are not for the given environment then\n * throw an error\n *\n * 'didAssumeRole' allows callers to whether they are receiving the assume role\n * credentials or the default credentials.\n */\nexport interface SdkForEnvironment {\n /**\n * The SDK for the given environment\n */\n readonly sdk: SDK;\n\n /**\n * Whether or not the assume role was successful.\n * If the assume role was not successful (false)\n * then that means that the 'sdk' returned contains\n * the default credentials (not the assume role credentials)\n */\n readonly didAssumeRole: boolean;\n}\n\n/**\n * Creates instances of the AWS SDK appropriate for a given account/region.\n *\n * Behavior is as follows:\n *\n * - First, a set of \"base\" credentials are established\n * - If a target environment is given and the default (\"current\") SDK credentials are for\n * that account, return those; otherwise\n * - If a target environment is given, scan all credential provider plugins\n * for credentials, and return those if found; otherwise\n * - Return default (\"current\") SDK credentials, noting that they might be wrong.\n *\n * - Second, a role may optionally need to be assumed. Use the base credentials\n * established in the previous process to assume that role.\n * - If assuming the role fails and the base credentials are for the correct\n * account, return those. This is a fallback for people who are trying to interact\n * with a Default Synthesized stack and already have right credentials setup.\n *\n * Typical cases we see in the wild:\n * - Credential plugin setup that, although not recommended, works for them\n * - Seeded terminal with `ReadOnly` credentials in order to do `cdk diff`--the `ReadOnly`\n * role doesn't have `sts:AssumeRole` and will fail for no real good reason.\n */\n@traceMemberMethods\nexport class SdkProvider {\n /**\n * Create a new SdkProvider which gets its defaults in a way that behaves like the AWS CLI does\n *\n * The AWS SDK for JS behaves slightly differently from the AWS CLI in a number of ways; see the\n * class `AwsCliCompatible` for the details.\n */\n public static async withAwsCliCompatibleDefaults(options: SdkProviderOptions) {\n const builder = new AwsCliCompatible(options.ioHelper);\n callTrace(SdkProvider.withAwsCliCompatibleDefaults.name, SdkProvider.constructor.name, options.logger);\n const credentialProvider = await builder.credentialChainBuilder({\n profile: options.profile,\n httpOptions: options.httpOptions,\n logger: options.logger,\n });\n\n const region = await builder.region(options.profile);\n const requestHandler = await builder.requestHandlerBuilder(options.httpOptions);\n return new SdkProvider(credentialProvider, region, requestHandler, options.ioHelper, options.logger);\n }\n\n private readonly plugins;\n\n public constructor(\n private readonly defaultCredentialProvider: AwsCredentialIdentityProvider,\n /**\n * Default region\n */\n public readonly defaultRegion: string,\n private readonly requestHandler: NodeHttpHandlerOptions = {},\n private readonly ioHelper: IoHelper,\n private readonly logger?: Logger,\n ) {\n this.plugins = new CredentialPlugins(PluginHost.instance, ioHelper);\n }\n\n /**\n * Return an SDK which can do operations in the given environment\n *\n * The `environment` parameter is resolved first (see `resolveEnvironment()`).\n */\n public async forEnvironment(\n environment: Environment,\n mode: Mode,\n options?: CredentialsOptions,\n quiet = false,\n ): Promise<SdkForEnvironment> {\n const env = await this.resolveEnvironment(environment);\n\n const baseCreds = await this.obtainBaseCredentials(env.account, mode);\n\n // At this point, we need at least SOME credentials\n if (baseCreds.source === 'none') {\n throw new AuthenticationError(fmtObtainCredentialsError(env.account, baseCreds));\n }\n\n // Simple case is if we don't need to \"assumeRole\" here. If so, we must now have credentials for the right\n // account.\n if (options?.assumeRoleArn === undefined) {\n if (baseCreds.source === 'incorrectDefault') {\n throw new AuthenticationError(fmtObtainCredentialsError(env.account, baseCreds));\n }\n\n // Our current credentials must be valid and not expired. Confirm that before we get into doing\n // actual CloudFormation calls, which might take a long time to hang.\n const sdk = new SDK(baseCreds.credentials, env.region, this.requestHandler, this.ioHelper, this.logger);\n await sdk.validateCredentials();\n return { sdk, didAssumeRole: false };\n }\n\n try {\n // We will proceed to AssumeRole using whatever we've been given.\n const sdk = await this.withAssumedRole(\n baseCreds,\n options.assumeRoleArn,\n options.assumeRoleExternalId,\n options.assumeRoleAdditionalOptions,\n env.region,\n );\n\n return { sdk, didAssumeRole: true };\n } catch (err: any) {\n if (err.name === 'ExpiredToken') {\n throw err;\n }\n\n // AssumeRole failed. Proceed and warn *if and only if* the baseCredentials were already for the right account\n // or returned from a plugin. This is to cover some current setups for people using plugins or preferring to\n // feed the CLI credentials which are sufficient by themselves. Prefer to assume the correct role if we can,\n // but if we can't then let's just try with available credentials anyway.\n if (baseCreds.source === 'correctDefault' || baseCreds.source === 'plugin') {\n await this.ioHelper.notify(IO.DEFAULT_SDK_DEBUG.msg(err.message));\n\n const maker = quiet ? IO.DEFAULT_SDK_DEBUG : IO.DEFAULT_SDK_WARN;\n await this.ioHelper.notify(maker.msg(\n `${fmtObtainedCredentials(baseCreds)} could not be used to assume '${options.assumeRoleArn}', but are for the right account. Proceeding anyway.`,\n ));\n return {\n sdk: new SDK(baseCreds.credentials, env.region, this.requestHandler, this.ioHelper, this.logger),\n didAssumeRole: false,\n };\n }\n\n throw err;\n }\n }\n\n /**\n * Return the partition that base credentials are for\n *\n * Returns `undefined` if there are no base credentials.\n */\n public async baseCredentialsPartition(environment: Environment, mode: Mode): Promise<string | undefined> {\n const env = await this.resolveEnvironment(environment);\n const baseCreds = await this.obtainBaseCredentials(env.account, mode);\n if (baseCreds.source === 'none') {\n return undefined;\n }\n return (await new SDK(baseCreds.credentials, env.region, this.requestHandler, this.ioHelper, this.logger).currentAccount()).partition;\n }\n\n /**\n * Resolve the environment for a stack\n *\n * Replaces the magic values `UNKNOWN_REGION` and `UNKNOWN_ACCOUNT`\n * with the defaults for the current SDK configuration (`~/.aws/config` or\n * otherwise).\n *\n * It is an error if `UNKNOWN_ACCOUNT` is used but the user hasn't configured\n * any SDK credentials.\n */\n public async resolveEnvironment(env: Environment): Promise<Environment> {\n const region = env.region !== UNKNOWN_REGION ? env.region : this.defaultRegion;\n const account = env.account !== UNKNOWN_ACCOUNT ? env.account : (await this.defaultAccount())?.accountId;\n\n if (!account) {\n throw new AuthenticationError(\n 'Unable to resolve AWS account to use. It must be either configured when you define your CDK Stack, or through the environment',\n );\n }\n\n return {\n region,\n account,\n name: EnvironmentUtils.format(account, region),\n };\n }\n\n /**\n * The account we'd auth into if we used default credentials.\n *\n * Default credentials are the set of ambiently configured credentials using\n * one of the environment variables, or ~/.aws/credentials, or the *one*\n * profile that was passed into the CLI.\n *\n * Might return undefined if there are no default/ambient credentials\n * available (in which case the user should better hope they have\n * credential plugins configured).\n *\n * Uses a cache to avoid STS calls if we don't need 'em.\n */\n public async defaultAccount(): Promise<Account | undefined> {\n return cached(this, CACHED_ACCOUNT, async () => {\n try {\n return await new SDK(this.defaultCredentialProvider, this.defaultRegion, this.requestHandler, this.ioHelper, this.logger).currentAccount();\n } catch (e: any) {\n // Treat 'ExpiredToken' specially. This is a common situation that people may find themselves in, and\n // they are complaining about if we fail 'cdk synth' on them. We loudly complain in order to show that\n // the current situation is probably undesirable, but we don't fail.\n if (e.name === 'ExpiredToken') {\n await this.ioHelper.notify(IO.DEFAULT_SDK_WARN.msg(\n 'There are expired AWS credentials in your environment. The CDK app will synth without current account information.',\n ));\n return undefined;\n }\n\n await this.ioHelper.notify(IO.DEFAULT_SDK_DEBUG.msg(`Unable to determine the default AWS account (${e.name}): ${formatErrorMessage(e)}`));\n return undefined;\n }\n });\n }\n\n /**\n * Get credentials for the given account ID in the given mode\n *\n * 1. Use the default credentials if the destination account matches the\n * current credentials' account.\n * 2. Otherwise try all credential plugins.\n * 3. Fail if neither of these yield any credentials.\n * 4. Return a failure if any of them returned credentials\n */\n private async obtainBaseCredentials(accountId: string, mode: Mode): Promise<ObtainBaseCredentialsResult> {\n // First try 'current' credentials\n const defaultAccountId = (await this.defaultAccount())?.accountId;\n if (defaultAccountId === accountId) {\n return {\n source: 'correctDefault',\n credentials: await this.defaultCredentialProvider,\n };\n }\n\n // Then try the plugins\n const pluginCreds = await this.plugins.fetchCredentialsFor(accountId, mode);\n if (pluginCreds) {\n return { source: 'plugin', ...pluginCreds };\n }\n\n // Fall back to default credentials with a note that they're not the right ones yet\n if (defaultAccountId !== undefined) {\n return {\n source: 'incorrectDefault',\n accountId: defaultAccountId,\n credentials: await this.defaultCredentialProvider,\n unusedPlugins: this.plugins.availablePluginNames,\n };\n }\n\n // Apparently we didn't find any at all\n return {\n source: 'none',\n unusedPlugins: this.plugins.availablePluginNames,\n };\n }\n\n /**\n * Return an SDK which uses assumed role credentials\n *\n * The base credentials used to retrieve the assumed role credentials will be the\n * same credentials returned by obtainCredentials if an environment and mode is passed,\n * otherwise it will be the current credentials.\n */\n private async withAssumedRole(\n mainCredentials: Exclude<ObtainBaseCredentialsResult, { source: 'none' }>,\n roleArn: string,\n externalId?: string,\n additionalOptions?: AssumeRoleAdditionalOptions,\n region?: string,\n ): Promise<SDK> {\n await this.ioHelper.notify(IO.DEFAULT_SDK_DEBUG.msg(`Assuming role '${roleArn}'.`));\n\n region = region ?? this.defaultRegion;\n\n const sourceDescription = fmtObtainedCredentials(mainCredentials);\n\n try {\n const credentials = await makeCachingProvider(fromTemporaryCredentials({\n masterCredentials: mainCredentials.credentials,\n params: {\n RoleArn: roleArn,\n ExternalId: externalId,\n RoleSessionName: `aws-cdk-${safeUsername()}`,\n ...additionalOptions,\n TransitiveTagKeys: additionalOptions?.Tags ? additionalOptions.Tags.map((t) => t.Key!) : undefined,\n },\n clientConfig: {\n region,\n requestHandler: this.requestHandler,\n customUserAgent: 'aws-cdk',\n logger: this.logger,\n },\n logger: this.logger,\n }));\n\n // Call the provider at least once here, to catch an error if it occurs\n await credentials();\n\n return new SDK(credentials, region, this.requestHandler, this.ioHelper, this.logger);\n } catch (err: any) {\n if (err.name === 'ExpiredToken') {\n throw err;\n }\n\n await this.ioHelper.notify(IO.DEFAULT_SDK_DEBUG.msg(`Assuming role failed: ${err.message}`));\n throw new AuthenticationError(\n [\n 'Could not assume role in target account',\n ...(sourceDescription ? [`using ${sourceDescription}`] : []),\n err.message,\n \". Please make sure that this role exists in the account. If it doesn't exist, (re)-bootstrap the environment \" +\n \"with the right '--trust', using the latest version of the CDK CLI.\",\n ].join(' '),\n );\n }\n }\n}\n\n/**\n * An AWS account\n *\n * An AWS account always exists in only one partition. Usually we don't care about\n * the partition, but when we need to form ARNs we do.\n */\nexport interface Account {\n /**\n * The account number\n */\n readonly accountId: string;\n\n /**\n * The partition ('aws' or 'aws-cn' or otherwise)\n */\n readonly partition: string;\n}\n\n/**\n * Return the username with characters invalid for a RoleSessionName removed\n *\n * @see https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html#API_AssumeRole_RequestParameters\n */\nfunction safeUsername() {\n try {\n return os.userInfo().username.replace(/[^\\w+=,.@-]/g, '@');\n } catch {\n return 'noname';\n }\n}\n\n/**\n * Options for obtaining credentials for an environment\n */\nexport interface CredentialsOptions {\n /**\n * The ARN of the role that needs to be assumed, if any\n */\n readonly assumeRoleArn?: string;\n\n /**\n * External ID required to assume the given role.\n */\n readonly assumeRoleExternalId?: string;\n\n /**\n * Session tags required to assume the given role.\n */\n readonly assumeRoleAdditionalOptions?: AssumeRoleAdditionalOptions;\n}\n\n/**\n * Result of obtaining base credentials\n */\ntype ObtainBaseCredentialsResult =\n | { source: 'correctDefault'; credentials: AwsCredentialIdentityProvider }\n | { source: 'plugin'; pluginName: string; credentials: AwsCredentialIdentityProvider }\n | {\n source: 'incorrectDefault';\n credentials: AwsCredentialIdentityProvider;\n accountId: string;\n unusedPlugins: string[];\n }\n | { source: 'none'; unusedPlugins: string[] };\n\n/**\n * Isolating the code that translates calculation errors into human error messages\n *\n * We cover the following cases:\n *\n * - No credentials are available at all\n * - Default credentials are for the wrong account\n */\nfunction fmtObtainCredentialsError(\n targetAccountId: string,\n obtainResult: ObtainBaseCredentialsResult & {\n source: 'none' | 'incorrectDefault';\n },\n): string {\n const msg = [`Need to perform AWS calls for account ${targetAccountId}`];\n switch (obtainResult.source) {\n case 'incorrectDefault':\n msg.push(`but the current credentials are for ${obtainResult.accountId}`);\n break;\n case 'none':\n msg.push('but no credentials have been configured');\n }\n if (obtainResult.unusedPlugins.length > 0) {\n msg.push(`and none of these plugins found any: ${obtainResult.unusedPlugins.join(', ')}`);\n }\n return msg.join(', ');\n}\n\n/**\n * Format a message indicating where we got base credentials for the assume role\n *\n * We cover the following cases:\n *\n * - Default credentials for the right account\n * - Default credentials for the wrong account\n * - Credentials returned from a plugin\n */\nfunction fmtObtainedCredentials(obtainResult: Exclude<ObtainBaseCredentialsResult, { source: 'none' }>): string {\n switch (obtainResult.source) {\n case 'correctDefault':\n return 'current credentials';\n case 'plugin':\n return `credentials returned by plugin '${obtainResult.pluginName}'`;\n case 'incorrectDefault':\n const msg = [];\n msg.push(`current credentials (which are for account ${obtainResult.accountId}`);\n\n if (obtainResult.unusedPlugins.length > 0) {\n msg.push(`, and none of the following plugins provided credentials: ${obtainResult.unusedPlugins.join(', ')}`);\n }\n msg.push(')');\n\n return msg.join('');\n }\n}\n\n/**\n * Instantiate an SDK for context providers. This function ensures that all\n * lookup assume role options are used when context providers perform lookups.\n */\nexport async function initContextProviderSdk(aws: SdkProvider, options: ContextLookupRoleOptions): Promise<SDK> {\n const account = options.account;\n const region = options.region;\n\n const creds: CredentialsOptions = {\n assumeRoleArn: options.lookupRoleArn,\n assumeRoleExternalId: options.lookupRoleExternalId,\n assumeRoleAdditionalOptions: options.assumeRoleAdditionalOptions,\n };\n\n return (await aws.forEnvironment(EnvironmentUtils.make(account, region), Mode.ForReading, creds)).sdk;\n}\n", "import { format } from 'node:util';\nimport { createCredentialChain, fromEnv, fromIni, fromNodeProviderChain } from '@aws-sdk/credential-providers';\nimport { MetadataService } from '@aws-sdk/ec2-metadata-service';\nimport type { NodeHttpHandlerOptions } from '@smithy/node-http-handler';\nimport { loadSharedConfigFiles } from '@smithy/shared-ini-file-loader';\nimport type { AwsCredentialIdentityProvider, Logger } from '@smithy/types';\nimport * as promptly from 'promptly';\nimport { makeCachingProvider } from './provider-caching';\nimport { ProxyAgentProvider } from './proxy-agent';\nimport type { SdkHttpOptions } from './sdk-provider';\nimport { IO, type IoHelper } from '../io/private';\nimport { AuthenticationError } from '../toolkit-error';\n\nconst DEFAULT_CONNECTION_TIMEOUT = 10000;\nconst DEFAULT_TIMEOUT = 300000;\n\n/**\n * Behaviors to match AWS CLI\n *\n * See these links:\n *\n * https://docs.aws.amazon.com/cli/latest/topic/config-vars.html\n * https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-envvars.html\n */\nexport class AwsCliCompatible {\n private readonly ioHelper: IoHelper;\n\n public constructor(ioHelper: IoHelper) {\n this.ioHelper = ioHelper;\n }\n\n /**\n * Build an AWS CLI-compatible credential chain provider\n *\n * The credential chain returned by this function is always caching.\n */\n public async credentialChainBuilder(\n options: CredentialChainOptions = {},\n ): Promise<AwsCredentialIdentityProvider> {\n const clientConfig = {\n requestHandler: await this.requestHandlerBuilder(options.httpOptions),\n customUserAgent: 'aws-cdk',\n logger: options.logger,\n };\n\n // Super hacky solution to https://github.com/aws/aws-cdk/issues/32510, proposed by the SDK team.\n //\n // Summary of the problem: we were reading the region from the config file and passing it to\n // the credential providers. However, in the case of SSO, this makes the credential provider\n // use that region to do the SSO flow, which is incorrect. The region that should be used for\n // that is the one set in the sso_session section of the config file.\n //\n // The idea here: the \"clientConfig\" is for configuring the inner auth client directly,\n // and has the highest priority, whereas \"parentClientConfig\" is the upper data client\n // and has lower priority than the sso_region but still higher priority than STS global region.\n const parentClientConfig = {\n region: await this.region(options.profile),\n };\n /**\n * The previous implementation matched AWS CLI behavior:\n *\n * If a profile is explicitly set using `--profile`,\n * we use that to the exclusion of everything else.\n *\n * Note: this does not apply to AWS_PROFILE,\n * environment credentials still take precedence over AWS_PROFILE\n */\n if (options.profile) {\n return makeCachingProvider(fromIni({\n profile: options.profile,\n ignoreCache: true,\n mfaCodeProvider: this.tokenCodeFn.bind(this),\n clientConfig,\n parentClientConfig,\n logger: options.logger,\n }));\n }\n\n const envProfile = process.env.AWS_PROFILE || process.env.AWS_DEFAULT_PROFILE;\n\n /**\n * Env AWS - EnvironmentCredentials with string AWS\n * Env Amazon - EnvironmentCredentials with string AMAZON\n * Profile Credentials - PatchedSharedIniFileCredentials with implicit profile, credentials file, http options, and token fn\n * SSO with implicit profile only\n * SharedIniFileCredentials with implicit profile and preferStaticCredentials true (profile with source_profile)\n * Shared Credential file that points to Environment Credentials with AWS prefix\n * Shared Credential file that points to EC2 Metadata\n * Shared Credential file that points to ECS Credentials\n * SSO Credentials - SsoCredentials with implicit profile and http options\n * ProcessCredentials with implicit profile\n * ECS Credentials - ECSCredentials with no input OR Web Identity - TokenFileWebIdentityCredentials with no input OR EC2 Metadata - EC2MetadataCredentials with no input\n *\n * These translate to:\n * fromEnv()\n * fromSSO()/fromIni()\n * fromProcess()\n * fromContainerMetadata()\n * fromTokenFile()\n * fromInstanceMetadata()\n *\n * The NodeProviderChain is already cached.\n */\n const nodeProviderChain = fromNodeProviderChain({\n profile: envProfile,\n clientConfig,\n parentClientConfig,\n logger: options.logger,\n mfaCodeProvider: this.tokenCodeFn.bind(this),\n ignoreCache: true,\n });\n\n return shouldPrioritizeEnv()\n ? createCredentialChain(fromEnv(), nodeProviderChain).expireAfter(60 * 60_000)\n : nodeProviderChain;\n }\n\n public async requestHandlerBuilder(options: SdkHttpOptions = {}): Promise<NodeHttpHandlerOptions> {\n const agent = await new ProxyAgentProvider(this.ioHelper).create(options);\n\n return {\n connectionTimeout: DEFAULT_CONNECTION_TIMEOUT,\n requestTimeout: DEFAULT_TIMEOUT,\n httpsAgent: agent,\n httpAgent: agent,\n };\n }\n\n /**\n * Attempts to get the region from a number of sources and falls back to us-east-1 if no region can be found,\n * as is done in the AWS CLI.\n *\n * The order of priority is the following:\n *\n * 1. Environment variables specifying region, with both an AWS prefix and AMAZON prefix\n * to maintain backwards compatibility, and without `DEFAULT` in the name because\n * Lambda and CodeBuild set the $AWS_REGION variable.\n * 2. Regions listed in the Shared Ini Files - First checking for the profile provided\n * and then checking for the default profile.\n * 3. IMDS instance identity region from the Metadata Service.\n * 4. us-east-1\n */\n public async region(maybeProfile?: string): Promise<string> {\n const defaultRegion = 'us-east-1';\n const profile = maybeProfile || process.env.AWS_PROFILE || process.env.AWS_DEFAULT_PROFILE || 'default';\n\n const region =\n process.env.AWS_REGION ||\n process.env.AMAZON_REGION ||\n process.env.AWS_DEFAULT_REGION ||\n process.env.AMAZON_DEFAULT_REGION ||\n (await this.getRegionFromIni(profile)) ||\n (await this.regionFromMetadataService());\n\n if (!region) {\n const usedProfile = !profile ? '' : ` (profile: \"${profile}\")`;\n await this.ioHelper.notify(IO.DEFAULT_SDK_DEBUG.msg(\n `Unable to determine AWS region from environment or AWS configuration${usedProfile}, defaulting to '${defaultRegion}'`,\n ));\n return defaultRegion;\n }\n\n return region;\n }\n\n /**\n * The MetadataService class will attempt to fetch the instance identity document from\n * IMDSv2 first, and then will attempt v1 as a fallback.\n *\n * If this fails, we will use us-east-1 as the region so no error should be thrown.\n * @returns The region for the instance identity\n */\n private async regionFromMetadataService() {\n await this.ioHelper.notify(IO.DEFAULT_SDK_DEBUG.msg('Looking up AWS region in the EC2 Instance Metadata Service (IMDS).'));\n try {\n const metadataService = new MetadataService({\n httpOptions: {\n timeout: 1000,\n },\n });\n\n await metadataService.fetchMetadataToken();\n const document = await metadataService.request('/latest/dynamic/instance-identity/document', {});\n return JSON.parse(document).region;\n } catch (e) {\n await this.ioHelper.notify(IO.DEFAULT_SDK_DEBUG.msg(`Unable to retrieve AWS region from IMDS: ${e}`));\n }\n }\n\n /**\n * Looks up the region of the provided profile. If no region is present,\n * it will attempt to lookup the default region.\n * @param profile The profile to use to lookup the region\n * @returns The region for the profile or default profile, if present. Otherwise returns undefined.\n */\n private async getRegionFromIni(profile: string): Promise<string | undefined> {\n const sharedFiles = await loadSharedConfigFiles({ ignoreCache: true });\n\n // Priority:\n //\n // credentials come before config because aws-cli v1 behaves like that.\n //\n // 1. profile-region-in-credentials\n // 2. profile-region-in-config\n // 3. default-region-in-credentials\n // 4. default-region-in-config\n\n return this.getRegionFromIniFile(profile, sharedFiles.credentialsFile)\n ?? this.getRegionFromIniFile(profile, sharedFiles.configFile)\n ?? this.getRegionFromIniFile('default', sharedFiles.credentialsFile)\n ?? this.getRegionFromIniFile('default', sharedFiles.configFile);\n }\n\n private getRegionFromIniFile(profile: string, data?: any) {\n return data?.[profile]?.region;\n }\n\n /**\n * Ask user for MFA token for given serial\n *\n * Result is send to callback function for SDK to authorize the request\n */\n private async tokenCodeFn(serialArn: string): Promise<string> {\n const debugFn = (msg: string, ...args: any[]) => this.ioHelper.notify(IO.DEFAULT_SDK_DEBUG.msg(format(msg, ...args)));\n await debugFn('Require MFA token for serial ARN', serialArn);\n try {\n const token: string = await promptly.prompt(`MFA token for ${serialArn}: `, {\n trim: true,\n default: '',\n });\n await debugFn('Successfully got MFA token from user');\n return token;\n } catch (err: any) {\n await debugFn('Failed to get MFA token', err);\n const e = new AuthenticationError(`Error fetching MFA token: ${err.message ?? err}`);\n e.name = 'SharedIniFileCredentialsProviderFailure';\n throw e;\n }\n }\n}\n\n/**\n * We used to support both AWS and AMAZON prefixes for these environment variables.\n *\n * Adding this for backward compatibility.\n */\nfunction shouldPrioritizeEnv() {\n const id = process.env.AWS_ACCESS_KEY_ID || process.env.AMAZON_ACCESS_KEY_ID;\n const key = process.env.AWS_SECRET_ACCESS_KEY || process.env.AMAZON_SECRET_ACCESS_KEY;\n\n if (!!id && !!key) {\n process.env.AWS_ACCESS_KEY_ID = id;\n process.env.AWS_SECRET_ACCESS_KEY = key;\n\n const sessionToken = process.env.AWS_SESSION_TOKEN ?? process.env.AMAZON_SESSION_TOKEN;\n if (sessionToken) {\n process.env.AWS_SESSION_TOKEN = sessionToken;\n }\n\n return true;\n }\n\n return false;\n}\n\nexport interface CredentialChainOptions {\n readonly profile?: string;\n readonly httpOptions?: SdkHttpOptions;\n readonly logger?: Logger;\n}\n", "import { memoize } from '@smithy/property-provider';\nimport type { AwsCredentialIdentity, AwsCredentialIdentityProvider } from '@smithy/types';\n\n/**\n * Wrap a credential provider in a cache\n *\n * Some credential providers in the SDKv3 are cached (the default Node\n * chain, specifically) but most others are not.\n *\n * Since we want to avoid duplicate calls to `AssumeRole`, or duplicate\n * MFA prompts or what have you, we are going to liberally wrap providers\n * in caches which will return the cached value until it expires.\n */\nexport function makeCachingProvider(provider: AwsCredentialIdentityProvider): AwsCredentialIdentityProvider {\n return memoize(\n provider,\n credentialsAboutToExpire,\n (token) => !!token.expiration,\n );\n}\n\nexport function credentialsAboutToExpire(token: AwsCredentialIdentity) {\n const expiryMarginSecs = 5;\n // token.expiration is sometimes null\n return !!token.expiration && token.expiration.getTime() - Date.now() < expiryMarginSecs * 1000;\n}\n", "import { inspect } from 'util';\nimport type { CredentialProviderSource, ForReading, ForWriting, PluginProviderResult, SDKv2CompatibleCredentials, SDKv3CompatibleCredentialProvider, SDKv3CompatibleCredentials } from '@aws-cdk/cli-plugin-contract';\nimport type { AwsCredentialIdentity, AwsCredentialIdentityProvider } from '@smithy/types';\nimport { credentialsAboutToExpire, makeCachingProvider } from './provider-caching';\nimport { formatErrorMessage } from '../../util';\nimport { IO, type IoHelper } from '../io/private';\nimport type { Mode } from '../plugin/mode';\nimport type { PluginHost } from '../plugin/plugin';\nimport { AuthenticationError } from '../toolkit-error';\n\n/**\n * Cache for credential providers.\n *\n * Given an account and an operating mode (read or write) will return an\n * appropriate credential provider for credentials for the given account. The\n * credential provider will be cached so that multiple AWS clients for the same\n * environment will not make multiple network calls to obtain credentials.\n *\n * Will use default credentials if they are for the right account; otherwise,\n * all loaded credential provider plugins will be tried to obtain credentials\n * for the given account.\n */\nexport class CredentialPlugins {\n private readonly cache: { [key: string]: PluginCredentialsFetchResult | undefined } = {};\n private readonly host: PluginHost;\n private readonly ioHelper: IoHelper;\n\n constructor(host: PluginHost, ioHelper: IoHelper) {\n this.host = host;\n this.ioHelper = ioHelper;\n }\n\n public async fetchCredentialsFor(awsAccountId: string, mode: Mode): Promise<PluginCredentialsFetchResult | undefined> {\n const key = `${awsAccountId}-${mode}`;\n if (!(key in this.cache)) {\n this.cache[key] = await this.lookupCredentials(awsAccountId, mode);\n }\n return this.cache[key];\n }\n\n public get availablePluginNames(): string[] {\n return this.host.credentialProviderSources.map((s) => s.name);\n }\n\n private async lookupCredentials(awsAccountId: string, mode: Mode): Promise<PluginCredentialsFetchResult | undefined> {\n const triedSources: CredentialProviderSource[] = [];\n // Otherwise, inspect the various credential sources we have\n for (const source of this.host.credentialProviderSources) {\n let available: boolean;\n try {\n available = await source.isAvailable();\n } catch (e: any) {\n // This shouldn't happen, but let's guard against it anyway\n await this.ioHelper.notify(IO.CDK_TOOLKIT_W0100.msg(`Uncaught exception in ${source.name}: ${formatErrorMessage(e)}`));\n available = false;\n }\n\n if (!available) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Credentials source ${source.name} is not available, ignoring it.`));\n continue;\n }\n triedSources.push(source);\n let canProvide: boolean;\n try {\n canProvide = await source.canProvideCredentials(awsAccountId);\n } catch (e: any) {\n // This shouldn't happen, but let's guard against it anyway\n await this.ioHelper.notify(IO.CDK_TOOLKIT_W0100.msg(`Uncaught exception in ${source.name}: ${formatErrorMessage(e)}`));\n canProvide = false;\n }\n if (!canProvide) {\n continue;\n }\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Using ${source.name} credentials for account ${awsAccountId}`));\n\n return {\n credentials: await v3ProviderFromPlugin(() => source.getProvider(awsAccountId, mode as ForReading | ForWriting, {\n supportsV3Providers: true,\n })),\n pluginName: source.name,\n };\n }\n return undefined;\n }\n}\n\n/**\n * Result from trying to fetch credentials from the Plugin host\n */\nexport interface PluginCredentialsFetchResult {\n /**\n * SDK-v3 compatible credential provider\n */\n readonly credentials: AwsCredentialIdentityProvider;\n\n /**\n * Name of plugin that successfully provided credentials\n */\n readonly pluginName: string;\n}\n\n/**\n * Take a function that calls the plugin, and turn it into an SDKv3-compatible credential provider.\n *\n * What we will do is the following:\n *\n * - Query the plugin and see what kind of result it gives us.\n * - If the result is self-refreshing or doesn't need refreshing, we turn it into an SDKv3 provider\n * and return it directly.\n * * If the underlying return value is a provider, we will make it a caching provider\n * (because we can't know if it will cache by itself or not).\n * * If the underlying return value is a static credential, caching isn't relevant.\n * * If the underlying return value is V2 credentials, those have caching built-in.\n * - If the result is a static credential that expires, we will wrap it in an SDKv3 provider\n * that will query the plugin again when the credential expires.\n */\nasync function v3ProviderFromPlugin(producer: () => Promise<PluginProviderResult>): Promise<AwsCredentialIdentityProvider> {\n const initial = await producer();\n\n if (isV3Provider(initial)) {\n // Already a provider, make caching\n return makeCachingProvider(initial);\n } else if (isV3Credentials(initial) && initial.expiration === undefined) {\n // Static credentials that don't need refreshing nor caching\n return () => Promise.resolve(initial);\n } else if (isV3Credentials(initial) && initial.expiration !== undefined) {\n // Static credentials that do need refreshing and caching\n return refreshFromPluginProvider(initial, producer);\n } else if (isV2Credentials(initial)) {\n // V2 credentials that refresh and cache themselves\n return v3ProviderFromV2Credentials(initial);\n } else {\n throw new AuthenticationError(`Plugin returned a value that doesn't resemble AWS credentials: ${inspect(initial)}`);\n }\n}\n\n/**\n * Converts a V2 credential into a V3-compatible provider\n */\nfunction v3ProviderFromV2Credentials(x: SDKv2CompatibleCredentials): AwsCredentialIdentityProvider {\n return async () => {\n // Get will fetch or refresh as necessary\n await x.getPromise();\n\n return {\n accessKeyId: x.accessKeyId,\n secretAccessKey: x.secretAccessKey,\n sessionToken: x.sessionToken,\n expiration: x.expireTime ?? undefined,\n };\n };\n}\n\nfunction refreshFromPluginProvider(current: AwsCredentialIdentity, producer: () => Promise<PluginProviderResult>): AwsCredentialIdentityProvider {\n return async () => {\n if (credentialsAboutToExpire(current)) {\n const newCreds = await producer();\n if (!isV3Credentials(newCreds)) {\n throw new AuthenticationError(`Plugin initially returned static V3 credentials but now returned something else: ${inspect(newCreds)}`);\n }\n current = newCreds;\n }\n return current;\n };\n}\n\nfunction isV3Provider(x: PluginProviderResult): x is SDKv3CompatibleCredentialProvider {\n return typeof x === 'function';\n}\n\nfunction isV2Credentials(x: PluginProviderResult): x is SDKv2CompatibleCredentials {\n return !!(x && typeof x === 'object' && (x as SDKv2CompatibleCredentials).getPromise);\n}\n\nfunction isV3Credentials(x: PluginProviderResult): x is SDKv3CompatibleCredentials {\n return !!(x && typeof x === 'object' && x.accessKeyId && !isV2Credentials(x));\n}\n", "import { inspect } from 'util';\nimport type { CredentialProviderSource, IPluginHost, Plugin } from '@aws-cdk/cli-plugin-contract';\nimport { type ContextProviderPlugin, isContextProviderPlugin } from './context-provider-plugin';\nimport { ToolkitError } from '../toolkit-error';\n\nexport let TESTING = false;\n\nexport function markTesting() {\n TESTING = true;\n}\n\n/**\n * A utility to manage plug-ins.\n *\n */\nexport class PluginHost implements IPluginHost {\n public static instance = new PluginHost();\n\n /**\n * Access the currently registered CredentialProviderSources. New sources can\n * be registered using the +registerCredentialProviderSource+ method.\n */\n public readonly credentialProviderSources = new Array<CredentialProviderSource>();\n\n public readonly contextProviderPlugins: Record<string, ContextProviderPlugin> = {};\n\n constructor() {\n if (!TESTING && PluginHost.instance && PluginHost.instance !== this) {\n throw new ToolkitError('New instances of PluginHost must not be built. Use PluginHost.instance instead!');\n }\n }\n\n /**\n * Loads a plug-in into this PluginHost.\n *\n * @param moduleSpec the specification (path or name) of the plug-in module to be loaded.\n */\n public load(moduleSpec: string) {\n try {\n /* eslint-disable @typescript-eslint/no-require-imports */\n const plugin = require(moduleSpec);\n /* eslint-enable */\n if (!isPlugin(plugin)) {\n throw new ToolkitError(`Module ${moduleSpec} is not a valid plug-in, or has an unsupported version.`);\n }\n if (plugin.init) {\n plugin.init(this);\n }\n } catch (e: any) {\n throw ToolkitError.withCause(`Unable to load plug-in '${moduleSpec}'`, e);\n }\n\n function isPlugin(x: any): x is Plugin {\n return x != null && x.version === '1';\n }\n }\n\n /**\n * Allows plug-ins to register new CredentialProviderSources.\n *\n * @param source a new CredentialProviderSource to register.\n */\n public registerCredentialProviderSource(source: CredentialProviderSource) {\n // Forward to the right credentials-related plugin host\n this.credentialProviderSources.push(source);\n }\n\n /**\n * (EXPERIMENTAL) Allow plugins to register context providers\n *\n * Context providers are objects with the following method:\n *\n * ```ts\n * getValue(args: {[key: string]: any}): Promise<any>;\n * ```\n *\n * Currently, they cannot reuse the CDK's authentication mechanisms, so they\n * must be prepared to either not make AWS calls or use their own source of\n * AWS credentials.\n *\n * This feature is experimental, and only intended to be used internally at Amazon\n * as a trial.\n *\n * After registering with 'my-plugin-name', the provider must be addressed as follows:\n *\n * ```ts\n * const value = ContextProvider.getValue(this, {\n * providerName: 'plugin',\n * props: {\n * pluginName: 'my-plugin-name',\n * myParameter1: 'xyz',\n * },\n * includeEnvironment: true | false,\n * dummyValue: 'what-to-return-on-the-first-pass',\n * })\n * ```\n *\n * @experimental\n */\n public registerContextProviderAlpha(pluginProviderName: string, provider: ContextProviderPlugin) {\n if (!isContextProviderPlugin(provider)) {\n throw new ToolkitError(`Object you gave me does not look like a ContextProviderPlugin: ${inspect(provider)}`);\n }\n this.contextProviderPlugins[pluginProviderName] = provider;\n }\n}\n", "export interface ContextProviderPlugin {\n getValue(args: {[key: string]: any}): Promise<any>;\n}\n\nexport function isContextProviderPlugin(x: unknown): x is ContextProviderPlugin {\n return typeof x === 'object' && !!x && !!(x as any).getValue;\n}\n", "import type { ForReading as PluginForReading, ForWriting as PluginForWriting } from '@aws-cdk/cli-plugin-contract';\n\nexport enum Mode {\n ForReading = 0 satisfies PluginForReading,\n ForWriting = 1 satisfies PluginForWriting,\n}\n", "import { inspect, format } from 'util';\nimport type { Logger } from '@smithy/types';\nimport { replacerBufferWithInfo } from '../../util';\nimport type { IoHelper } from '../io/private';\nimport { IO } from '../io/private';\n\nexport class SdkToCliLogger implements Logger {\n private readonly ioHelper: IoHelper;\n\n public constructor(ioHelper: IoHelper) {\n this.ioHelper = ioHelper;\n }\n\n private notify(level: 'info' | 'warn' | 'error', ...content: any[]) {\n void this.ioHelper.notify(IO.CDK_SDK_I0100.msg(format('[SDK %s] %s', level, formatSdkLoggerContent(content)), {\n sdkLevel: level,\n content,\n }));\n }\n\n public trace(..._content: any[]) {\n // This is too much detail for our logs\n // this.notify('trace', ...content);\n }\n\n public debug(..._content: any[]) {\n // This is too much detail for our logs\n // this.notify('debug', ...content);\n }\n\n /**\n * Info is called mostly (exclusively?) for successful API calls\n *\n * Payload:\n *\n * (Note the input contains entire CFN templates, for example)\n *\n * ```\n * {\n * clientName: 'S3Client',\n * commandName: 'GetBucketLocationCommand',\n * input: {\n * Bucket: '.....',\n * ExpectedBucketOwner: undefined\n * },\n * output: { LocationConstraint: 'eu-central-1' },\n * metadata: {\n * httpStatusCode: 200,\n * requestId: '....',\n * extendedRequestId: '...',\n * cfId: undefined,\n * attempts: 1,\n * totalRetryDelay: 0\n * }\n * }\n * ```\n */\n public info(...content: any[]) {\n this.notify('info', ...content);\n }\n\n public warn(...content: any[]) {\n this.notify('warn', ...content);\n }\n\n /**\n * Error is called mostly (exclusively?) for failing API calls\n *\n * Payload (input would be the entire API call arguments).\n *\n * ```\n * {\n * clientName: 'STSClient',\n * commandName: 'GetCallerIdentityCommand',\n * input: {},\n * error: AggregateError [ECONNREFUSED]:\n * at internalConnectMultiple (node:net:1121:18)\n * at afterConnectMultiple (node:net:1688:7) {\n * code: 'ECONNREFUSED',\n * '$metadata': { attempts: 3, totalRetryDelay: 600 },\n * [errors]: [ [Error], [Error] ]\n * },\n * metadata: { attempts: 3, totalRetryDelay: 600 }\n * }\n * ```\n */\n public error(...content: any[]) {\n this.notify('error', ...content);\n }\n}\n\n/**\n * This can be anything.\n *\n * For debug, it seems to be mostly strings.\n * For info, it seems to be objects.\n *\n * Stringify and join without separator.\n */\nexport function formatSdkLoggerContent(content: any[]) {\n if (content.length === 1) {\n const apiFmt = formatApiCall(content[0]);\n if (apiFmt) {\n return apiFmt;\n }\n }\n return content.map((x) => typeof x === 'string' ? x : inspect(x)).join('');\n}\n\nfunction formatApiCall(content: any): string | undefined {\n if (!isSdkApiCallSuccess(content) && !isSdkApiCallError(content)) {\n return undefined;\n }\n\n const service = content.clientName.replace(/Client$/, '');\n const api = content.commandName.replace(/Command$/, '');\n\n const parts = [];\n if ((content.metadata?.attempts ?? 0) > 1) {\n parts.push(`[${content.metadata?.attempts} attempts, ${content.metadata?.totalRetryDelay}ms retry]`);\n }\n\n parts.push(`${service}.${api}(${JSON.stringify(content.input, replacerBufferWithInfo)})`);\n\n if (isSdkApiCallSuccess(content)) {\n parts.push('-> OK');\n } else {\n parts.push(`-> ${content.error}`);\n }\n\n return parts.join(' ');\n}\n\ninterface SdkApiCallBase {\n clientName: string;\n commandName: string;\n input: Record<string, unknown>;\n metadata?: {\n httpStatusCode?: number;\n requestId?: string;\n extendedRequestId?: string;\n cfId?: string;\n attempts?: number;\n totalRetryDelay?: number;\n };\n}\n\ntype SdkApiCallSuccess = SdkApiCallBase & { output: Record<string, unknown> };\ntype SdkApiCallError = SdkApiCallBase & { error: Error };\n\nfunction isSdkApiCallSuccess(x: any): x is SdkApiCallSuccess {\n return x && typeof x === 'object' && x.commandName && x.output;\n}\n\nfunction isSdkApiCallError(x: any): x is SdkApiCallError {\n return x && typeof x === 'object' && x.commandName && x.error;\n}\n", "import * as path from 'path';\nimport type * as cxapi from '@aws-cdk/cx-api';\nimport type { BootstrapEnvironmentOptions, BootstrappingParameters } from './bootstrap-props';\nimport { BootstrapStack, bootstrapVersionFromTemplate } from './deploy-bootstrap';\nimport { legacyBootstrapTemplate } from './legacy-template';\nimport { bundledPackageRootDir, loadStructuredFile, serializeStructure } from '../../util';\nimport type { SDK, SdkProvider } from '../aws-auth';\nimport type { SuccessfulDeployStackResult } from '../deployments';\nimport { IO, type IoHelper } from '../io/private';\nimport { Mode } from '../plugin';\nimport { ToolkitError } from '../toolkit-error';\nimport { DEFAULT_TOOLKIT_STACK_NAME } from '../toolkit-info';\n\nexport type BootstrapSource = { source: 'legacy' } | { source: 'default' } | { source: 'custom'; templateFile: string };\n\nexport class Bootstrapper {\n private readonly ioHelper: IoHelper;\n\n constructor(\n private readonly source: BootstrapSource = { source: 'default' },\n ioHelper: IoHelper,\n ) {\n this.ioHelper = ioHelper;\n }\n\n public bootstrapEnvironment(\n environment: cxapi.Environment,\n sdkProvider: SdkProvider,\n options: BootstrapEnvironmentOptions = {},\n ): Promise<SuccessfulDeployStackResult> {\n switch (this.source.source) {\n case 'legacy':\n return this.legacyBootstrap(environment, sdkProvider, options);\n case 'default':\n return this.modernBootstrap(environment, sdkProvider, options);\n case 'custom':\n return this.customBootstrap(environment, sdkProvider, options);\n }\n }\n\n public async showTemplate(json: boolean) {\n const template = await this.loadTemplate();\n process.stdout.write(`${serializeStructure(template, json)}\\n`);\n }\n\n /**\n * Deploy legacy bootstrap stack\n *\n */\n private async legacyBootstrap(\n environment: cxapi.Environment,\n sdkProvider: SdkProvider,\n options: BootstrapEnvironmentOptions = {},\n ): Promise<SuccessfulDeployStackResult> {\n const params = options.parameters ?? {};\n\n if (params.trustedAccounts?.length) {\n throw new ToolkitError('--trust can only be passed for the modern bootstrap experience.');\n }\n if (params.cloudFormationExecutionPolicies?.length) {\n throw new ToolkitError('--cloudformation-execution-policies can only be passed for the modern bootstrap experience.');\n }\n if (params.createCustomerMasterKey !== undefined) {\n throw new ToolkitError('--bootstrap-customer-key can only be passed for the modern bootstrap experience.');\n }\n if (params.qualifier) {\n throw new ToolkitError('--qualifier can only be passed for the modern bootstrap experience.');\n }\n\n const toolkitStackName = options.toolkitStackName ?? DEFAULT_TOOLKIT_STACK_NAME;\n const current = await BootstrapStack.lookup(sdkProvider, environment, toolkitStackName, this.ioHelper);\n return current.update(\n await this.loadTemplate(params),\n {},\n {\n ...options,\n terminationProtection: options.terminationProtection ?? current.terminationProtection,\n },\n );\n }\n\n /**\n * Deploy CI/CD-ready bootstrap stack from template\n *\n */\n private async modernBootstrap(\n environment: cxapi.Environment,\n sdkProvider: SdkProvider,\n options: BootstrapEnvironmentOptions = {},\n ): Promise<SuccessfulDeployStackResult> {\n const params = options.parameters ?? {};\n\n const bootstrapTemplate = await this.loadTemplate();\n\n const toolkitStackName = options.toolkitStackName ?? DEFAULT_TOOLKIT_STACK_NAME;\n const current = await BootstrapStack.lookup(sdkProvider, environment, toolkitStackName, this.ioHelper);\n const partition = await current.partition();\n\n if (params.createCustomerMasterKey !== undefined && params.kmsKeyId) {\n throw new ToolkitError(\n \"You cannot pass '--bootstrap-kms-key-id' and '--bootstrap-customer-key' together. Specify one or the other\",\n );\n }\n\n // If people re-bootstrap, existing parameter values are reused so that people don't accidentally change the configuration\n // on their bootstrap stack (this happens automatically in deployStack). However, to do proper validation on the\n // combined arguments (such that if --trust has been given, --cloudformation-execution-policies is necessary as well)\n // we need to take this parameter reuse into account.\n //\n // Ideally we'd do this inside the template, but the `Rules` section of CFN\n // templates doesn't seem to be able to express the conditions that we need\n // (can't use Fn::Join or reference Conditions) so we do it here instead.\n const allTrusted = new Set([\n ...params.trustedAccounts ?? [],\n ...params.trustedAccountsForLookup ?? [],\n ]);\n const invalid = intersection(allTrusted, new Set(params.untrustedAccounts));\n if (invalid.size > 0) {\n throw new ToolkitError(`Accounts cannot be both trusted and untrusted. Found: ${[...invalid].join(',')}`);\n }\n\n const removeUntrusted = (accounts: string[]) =>\n accounts.filter(acc => !params.untrustedAccounts?.map(String).includes(String(acc)));\n\n const trustedAccounts = removeUntrusted(params.trustedAccounts ?? splitCfnArray(current.parameters.TrustedAccounts));\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(\n `Trusted accounts for deployment: ${trustedAccounts.length > 0 ? trustedAccounts.join(', ') : '(none)'}`,\n ));\n\n const trustedAccountsForLookup = removeUntrusted(\n params.trustedAccountsForLookup ?? splitCfnArray(current.parameters.TrustedAccountsForLookup),\n );\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(\n `Trusted accounts for lookup: ${trustedAccountsForLookup.length > 0 ? trustedAccountsForLookup.join(', ') : '(none)'}`,\n ));\n\n const cloudFormationExecutionPolicies =\n params.cloudFormationExecutionPolicies ?? splitCfnArray(current.parameters.CloudFormationExecutionPolicies);\n if (trustedAccounts.length === 0 && cloudFormationExecutionPolicies.length === 0) {\n // For self-trust it's okay to default to AdministratorAccess, and it improves the usability of bootstrapping a lot.\n //\n // We don't actually make the implicitly policy a physical parameter. The template will infer it instead,\n // we simply do the UI advertising that behavior here.\n //\n // If we DID make it an explicit parameter, we wouldn't be able to tell the difference between whether\n // we inferred it or whether the user told us, and the sequence:\n //\n // $ cdk bootstrap\n // $ cdk bootstrap --trust 1234\n //\n // Would leave AdministratorAccess policies with a trust relationship, without the user explicitly\n // approving the trust policy.\n const implicitPolicy = `arn:${partition}:iam::aws:policy/AdministratorAccess`;\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_WARN.msg(\n `Using default execution policy of '${implicitPolicy}'. Pass '--cloudformation-execution-policies' to customize.`,\n ));\n } else if (cloudFormationExecutionPolicies.length === 0) {\n throw new ToolkitError(\n `Please pass \\'--cloudformation-execution-policies\\' when using \\'--trust\\' to specify deployment permissions. Try a managed policy of the form \\'arn:${partition}:iam::aws:policy/<PolicyName>\\'.`,\n );\n } else {\n // Remind people what the current settings are\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(`Execution policies: ${cloudFormationExecutionPolicies.join(', ')}`));\n }\n\n // * If an ARN is given, that ARN. Otherwise:\n // * '-' if customerKey = false\n // * '' if customerKey = true\n // * if customerKey is also not given\n // * undefined if we already had a value in place (reusing what we had)\n // * '-' if this is the first time we're deploying this stack (or upgrading from old to new bootstrap)\n const currentKmsKeyId = current.parameters.FileAssetsBucketKmsKeyId;\n const kmsKeyId =\n params.kmsKeyId ??\n (params.createCustomerMasterKey === true\n ? CREATE_NEW_KEY\n : params.createCustomerMasterKey === false || currentKmsKeyId === undefined\n ? USE_AWS_MANAGED_KEY\n : undefined);\n\n /* A permissions boundary can be provided via:\n * - the flag indicating the example one should be used\n * - the name indicating the custom permissions boundary to be used\n * Re-bootstrapping will NOT be blocked by either tightening or relaxing the permissions' boundary.\n */\n\n // InputPermissionsBoundary is an `any` type and if it is not defined it\n // appears as an empty string ''. We need to force it to evaluate an empty string\n // as undefined\n const currentPermissionsBoundary: string | undefined = current.parameters.InputPermissionsBoundary || undefined;\n const inputPolicyName = params.examplePermissionsBoundary\n ? CDK_BOOTSTRAP_PERMISSIONS_BOUNDARY\n : params.customPermissionsBoundary;\n let policyName: string | undefined;\n if (inputPolicyName) {\n // If the example policy is not already in place, it must be created.\n const sdk = (await sdkProvider.forEnvironment(environment, Mode.ForWriting)).sdk;\n policyName = await this.getPolicyName(environment, sdk, inputPolicyName, partition, params);\n }\n if (currentPermissionsBoundary !== policyName) {\n if (!currentPermissionsBoundary) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_WARN.msg(\n `Adding new permissions boundary ${policyName}`,\n ));\n } else if (!policyName) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_WARN.msg(\n `Removing existing permissions boundary ${currentPermissionsBoundary}`,\n ));\n } else {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_WARN.msg(\n `Changing permissions boundary from ${currentPermissionsBoundary} to ${policyName}`,\n ));\n }\n }\n\n return current.update(\n bootstrapTemplate,\n {\n FileAssetsBucketName: params.bucketName,\n FileAssetsBucketKmsKeyId: kmsKeyId,\n // Empty array becomes empty string\n TrustedAccounts: trustedAccounts.join(','),\n TrustedAccountsForLookup: trustedAccountsForLookup.join(','),\n CloudFormationExecutionPolicies: cloudFormationExecutionPolicies.join(','),\n Qualifier: params.qualifier,\n PublicAccessBlockConfiguration:\n params.publicAccessBlockConfiguration || params.publicAccessBlockConfiguration === undefined\n ? 'true'\n : 'false',\n InputPermissionsBoundary: policyName,\n },\n {\n ...options,\n terminationProtection: options.terminationProtection ?? current.terminationProtection,\n },\n );\n }\n\n private async getPolicyName(\n environment: cxapi.Environment,\n sdk: SDK,\n permissionsBoundary: string,\n partition: string,\n params: BootstrappingParameters,\n ): Promise<string> {\n if (permissionsBoundary !== CDK_BOOTSTRAP_PERMISSIONS_BOUNDARY) {\n this.validatePolicyName(permissionsBoundary);\n return Promise.resolve(permissionsBoundary);\n }\n // if no Qualifier is supplied, resort to the default one\n const arn = await this.getExamplePermissionsBoundary(\n params.qualifier ?? 'hnb659fds',\n partition,\n environment.account,\n sdk,\n );\n const policyName = arn.split('/').pop();\n if (!policyName) {\n throw new ToolkitError('Could not retrieve the example permission boundary!');\n }\n return Promise.resolve(policyName);\n }\n\n private async getExamplePermissionsBoundary(\n qualifier: string,\n partition: string,\n account: string,\n sdk: SDK,\n ): Promise<string> {\n const iam = sdk.iam();\n\n let policyName = `cdk-${qualifier}-permissions-boundary`;\n const arn = `arn:${partition}:iam::${account}:policy/${policyName}`;\n\n try {\n let getPolicyResp = await iam.getPolicy({ PolicyArn: arn });\n if (getPolicyResp.Policy) {\n return arn;\n }\n } catch (e: any) {\n // https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetPolicy.html#API_GetPolicy_Errors\n if (e.name === 'NoSuchEntity') {\n // noop, proceed with creating the policy\n } else {\n throw e;\n }\n }\n\n const policyDoc = {\n Version: '2012-10-17',\n Statement: [\n {\n Action: ['*'],\n Resource: '*',\n Effect: 'Allow',\n Sid: 'ExplicitAllowAll',\n },\n {\n Condition: {\n StringEquals: {\n 'iam:PermissionsBoundary': `arn:${partition}:iam::${account}:policy/cdk-${qualifier}-permissions-boundary`,\n },\n },\n Action: [\n 'iam:CreateUser',\n 'iam:CreateRole',\n 'iam:PutRolePermissionsBoundary',\n 'iam:PutUserPermissionsBoundary',\n ],\n Resource: '*',\n Effect: 'Allow',\n Sid: 'DenyAccessIfRequiredPermBoundaryIsNotBeingApplied',\n },\n {\n Action: [\n 'iam:CreatePolicyVersion',\n 'iam:DeletePolicy',\n 'iam:DeletePolicyVersion',\n 'iam:SetDefaultPolicyVersion',\n ],\n Resource: `arn:${partition}:iam::${account}:policy/cdk-${qualifier}-permissions-boundary`,\n Effect: 'Deny',\n Sid: 'DenyPermBoundaryIAMPolicyAlteration',\n },\n {\n Action: ['iam:DeleteUserPermissionsBoundary', 'iam:DeleteRolePermissionsBoundary'],\n Resource: '*',\n Effect: 'Deny',\n Sid: 'DenyRemovalOfPermBoundaryFromAnyUserOrRole',\n },\n ],\n };\n const request = {\n PolicyName: policyName,\n PolicyDocument: JSON.stringify(policyDoc),\n };\n const createPolicyResponse = await iam.createPolicy(request);\n if (createPolicyResponse.Policy?.Arn) {\n return createPolicyResponse.Policy.Arn;\n } else {\n throw new ToolkitError(`Could not retrieve the example permission boundary ${arn}!`);\n }\n }\n\n private validatePolicyName(permissionsBoundary: string) {\n // https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreatePolicy.html\n // Added support for policy names with a path\n // See https://github.com/aws/aws-cdk/issues/26320\n const regexp: RegExp = /[\\w+\\/=,.@-]+/;\n const matches = regexp.exec(permissionsBoundary);\n if (!(matches && matches.length === 1 && matches[0] === permissionsBoundary)) {\n throw new ToolkitError(`The permissions boundary name ${permissionsBoundary} does not match the IAM conventions.`);\n }\n }\n\n private async customBootstrap(\n environment: cxapi.Environment,\n sdkProvider: SdkProvider,\n options: BootstrapEnvironmentOptions = {},\n ): Promise<SuccessfulDeployStackResult> {\n // Look at the template, decide whether it's most likely a legacy or modern bootstrap\n // template, and use the right bootstrapper for that.\n const version = bootstrapVersionFromTemplate(await this.loadTemplate());\n if (version === 0) {\n return this.legacyBootstrap(environment, sdkProvider, options);\n } else {\n return this.modernBootstrap(environment, sdkProvider, options);\n }\n }\n\n private async loadTemplate(params: BootstrappingParameters = {}): Promise<any> {\n switch (this.source.source) {\n case 'custom':\n return loadStructuredFile(this.source.templateFile);\n case 'default':\n return loadStructuredFile(path.join(bundledPackageRootDir(__dirname), 'lib', 'api', 'bootstrap', 'bootstrap-template.yaml'));\n case 'legacy':\n return legacyBootstrapTemplate(params);\n }\n }\n}\n\n/**\n * Magic parameter value that will cause the bootstrap-template.yml to NOT create a CMK but use the default key\n */\nconst USE_AWS_MANAGED_KEY = 'AWS_MANAGED_KEY';\n\n/**\n * Magic parameter value that will cause the bootstrap-template.yml to create a CMK\n */\nconst CREATE_NEW_KEY = '';\n/**\n * Parameter value indicating the use of the default, CDK provided permissions boundary for bootstrap-template.yml\n */\nconst CDK_BOOTSTRAP_PERMISSIONS_BOUNDARY = 'CDK_BOOTSTRAP_PERMISSIONS_BOUNDARY';\n\n/**\n * Split an array-like CloudFormation parameter on ,\n *\n * An empty string is the empty array (instead of `['']`).\n */\nfunction splitCfnArray(xs: string | undefined): string[] {\n if (xs === '' || xs === undefined) {\n return [];\n }\n return xs.split(',');\n}\n\nfunction intersection<A>(xs: Set<A>, ys: Set<A>): Set<A> {\n return new Set<A>(Array.from(xs).filter(x => ys.has(x)));\n}\n", "import * as os from 'os';\nimport * as path from 'path';\nimport { ArtifactType } from '@aws-cdk/cloud-assembly-schema';\nimport type { Environment } from '@aws-cdk/cx-api';\nimport { CloudAssemblyBuilder, EnvironmentUtils } from '@aws-cdk/cx-api';\nimport * as fs from 'fs-extra';\nimport type { BootstrapEnvironmentOptions } from './bootstrap-props';\nimport {\n BOOTSTRAP_VARIANT_PARAMETER,\n BOOTSTRAP_VERSION_OUTPUT,\n BOOTSTRAP_VERSION_RESOURCE,\n DEFAULT_BOOTSTRAP_VARIANT,\n} from './bootstrap-props';\nimport type { SDK, SdkProvider } from '../aws-auth';\nimport type { SuccessfulDeployStackResult } from '../deployments';\nimport { assertIsSuccessfulDeployStackResult } from '../deployments';\nimport { deployStack } from '../deployments/deploy-stack';\nimport { NoBootstrapStackEnvironmentResources } from '../environment';\nimport { IO, type IoHelper } from '../io/private';\nimport { Mode } from '../plugin';\nimport { DEFAULT_TOOLKIT_STACK_NAME, ToolkitInfo } from '../toolkit-info';\n\n/**\n * A class to hold state around stack bootstrapping\n *\n * This class exists so we can break bootstrapping into 2 phases:\n *\n * ```ts\n * const current = BootstrapStack.lookup(...);\n * // ...\n * current.update(newTemplate, ...);\n * ```\n *\n * And do something in between the two phases (such as look at the\n * current bootstrap stack and doing something intelligent).\n */\nexport class BootstrapStack {\n public static async lookup(sdkProvider: SdkProvider, environment: Environment, toolkitStackName: string, ioHelper: IoHelper) {\n toolkitStackName = toolkitStackName ?? DEFAULT_TOOLKIT_STACK_NAME;\n\n const resolvedEnvironment = await sdkProvider.resolveEnvironment(environment);\n const sdk = (await sdkProvider.forEnvironment(resolvedEnvironment, Mode.ForWriting)).sdk;\n\n const currentToolkitInfo = await ToolkitInfo.lookup(resolvedEnvironment, sdk, ioHelper, toolkitStackName);\n\n return new BootstrapStack(sdkProvider, sdk, resolvedEnvironment, toolkitStackName, currentToolkitInfo, ioHelper);\n }\n\n protected constructor(\n private readonly sdkProvider: SdkProvider,\n private readonly sdk: SDK,\n private readonly resolvedEnvironment: Environment,\n private readonly toolkitStackName: string,\n private readonly currentToolkitInfo: ToolkitInfo,\n private readonly ioHelper: IoHelper,\n ) {\n }\n\n public get parameters(): Record<string, string> {\n return this.currentToolkitInfo.found ? this.currentToolkitInfo.bootstrapStack.parameters : {};\n }\n\n public get terminationProtection() {\n return this.currentToolkitInfo.found ? this.currentToolkitInfo.bootstrapStack.terminationProtection : undefined;\n }\n\n public async partition(): Promise<string> {\n return (await this.sdk.currentAccount()).partition;\n }\n\n /**\n * Perform the actual deployment of a bootstrap stack, given a template and some parameters\n */\n public async update(\n template: any,\n parameters: Record<string, string | undefined>,\n options: Omit<BootstrapEnvironmentOptions, 'parameters'>,\n ): Promise<SuccessfulDeployStackResult> {\n if (this.currentToolkitInfo.found && !options.forceDeployment) {\n // Safety checks\n const abortResponse = {\n type: 'did-deploy-stack',\n noOp: true,\n outputs: {},\n stackArn: this.currentToolkitInfo.bootstrapStack.stackId,\n } satisfies SuccessfulDeployStackResult;\n\n // Validate that the bootstrap stack we're trying to replace is from the same variant as the one we're trying to deploy\n const currentVariant = this.currentToolkitInfo.variant;\n const newVariant = bootstrapVariantFromTemplate(template);\n if (currentVariant !== newVariant) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_WARN.msg(\n `Bootstrap stack already exists, containing '${currentVariant}'. Not overwriting it with a template containing '${newVariant}' (use --force if you intend to overwrite)`,\n ));\n return abortResponse;\n }\n\n // Validate that we're not downgrading the bootstrap stack\n const newVersion = bootstrapVersionFromTemplate(template);\n const currentVersion = this.currentToolkitInfo.version;\n if (newVersion < currentVersion) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_WARN.msg(\n `Bootstrap stack already at version ${currentVersion}. Not downgrading it to version ${newVersion} (use --force if you intend to downgrade)`,\n ));\n if (newVersion === 0) {\n // A downgrade with 0 as target version means we probably have a new-style bootstrap in the account,\n // and an old-style bootstrap as current target, which means the user probably forgot to put this flag in.\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_WARN.msg(\n \"(Did you set the '@aws-cdk/core:newStyleStackSynthesis' feature flag in cdk.json?)\",\n ));\n }\n return abortResponse;\n }\n }\n\n const outdir = await fs.mkdtemp(path.join(os.tmpdir(), 'cdk-bootstrap'));\n const builder = new CloudAssemblyBuilder(outdir);\n const templateFile = `${this.toolkitStackName}.template.json`;\n await fs.writeJson(path.join(builder.outdir, templateFile), template, {\n spaces: 2,\n });\n\n builder.addArtifact(this.toolkitStackName, {\n type: ArtifactType.AWS_CLOUDFORMATION_STACK,\n environment: EnvironmentUtils.format(this.resolvedEnvironment.account, this.resolvedEnvironment.region),\n properties: {\n templateFile,\n terminationProtection: options.terminationProtection ?? false,\n },\n });\n\n const assembly = builder.buildAssembly();\n\n const ret = await deployStack({\n stack: assembly.getStackByName(this.toolkitStackName),\n resolvedEnvironment: this.resolvedEnvironment,\n sdk: this.sdk,\n sdkProvider: this.sdkProvider,\n forceDeployment: options.forceDeployment,\n roleArn: options.roleArn,\n tags: options.tags,\n deploymentMethod: { method: 'change-set', execute: options.execute },\n parameters,\n usePreviousParameters: options.usePreviousParameters ?? true,\n // Obviously we can't need a bootstrap stack to deploy a bootstrap stack\n envResources: new NoBootstrapStackEnvironmentResources(this.resolvedEnvironment, this.sdk, this.ioHelper),\n }, this.ioHelper);\n\n assertIsSuccessfulDeployStackResult(ret);\n\n return ret;\n }\n}\n\nexport function bootstrapVersionFromTemplate(template: any): number {\n const versionSources = [\n template.Outputs?.[BOOTSTRAP_VERSION_OUTPUT]?.Value,\n template.Resources?.[BOOTSTRAP_VERSION_RESOURCE]?.Properties?.Value,\n ];\n\n for (const vs of versionSources) {\n if (typeof vs === 'number') {\n return vs;\n }\n if (typeof vs === 'string' && !isNaN(parseInt(vs, 10))) {\n return parseInt(vs, 10);\n }\n }\n return 0;\n}\n\nexport function bootstrapVariantFromTemplate(template: any): string {\n return template.Parameters?.[BOOTSTRAP_VARIANT_PARAMETER]?.Default ?? DEFAULT_BOOTSTRAP_VARIANT;\n}\n", "import type { BootstrapSource } from './bootstrap-environment';\nimport type { StringWithoutPlaceholders } from '../environment';\nimport type { Tag } from '../tags';\n\nexport const BUCKET_NAME_OUTPUT = 'BucketName';\nexport const REPOSITORY_NAME_OUTPUT = 'ImageRepositoryName';\nexport const BUCKET_DOMAIN_NAME_OUTPUT = 'BucketDomainName';\nexport const BOOTSTRAP_VERSION_OUTPUT = 'BootstrapVersion';\nexport const BOOTSTRAP_VERSION_RESOURCE = 'CdkBootstrapVersion';\nexport const BOOTSTRAP_VARIANT_PARAMETER = 'BootstrapVariant';\n\n/**\n * The assumed vendor of a template in case it is not set\n */\nexport const DEFAULT_BOOTSTRAP_VARIANT = 'AWS CDK: Default Resources';\n\n/**\n * Options for the bootstrapEnvironment operation(s)\n */\nexport interface BootstrapEnvironmentOptions {\n readonly toolkitStackName?: string;\n readonly roleArn?: StringWithoutPlaceholders;\n readonly parameters?: BootstrappingParameters;\n readonly forceDeployment?: boolean;\n\n /**\n * The source of the bootstrap stack\n *\n * @default - modern v2-style bootstrapping\n */\n readonly source?: BootstrapSource;\n\n /**\n * Whether to execute the changeset or only create it and leave it in review.\n * @default true\n */\n readonly execute?: boolean;\n\n /**\n * Tags for cdktoolkit stack.\n *\n * @default - None.\n */\n readonly tags?: Tag[];\n\n /**\n * Whether the stacks created by the bootstrap process should be protected from termination.\n * @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-protect-stacks.html\n * @default true\n */\n readonly terminationProtection?: boolean;\n\n /**\n * Use previous values for unspecified parameters\n *\n * If not set, all parameters must be specified for every deployment.\n *\n * @default true\n */\n usePreviousParameters?: boolean;\n}\n\n/**\n * Parameters for the bootstrapping template\n */\nexport interface BootstrappingParameters {\n /**\n * The name to be given to the CDK Bootstrap bucket.\n *\n * @default - a name is generated by CloudFormation.\n */\n readonly bucketName?: string;\n\n /**\n * The ID of an existing KMS key to be used for encrypting items in the bucket.\n *\n * @default - use the default KMS key or create a custom one\n */\n readonly kmsKeyId?: string;\n\n /**\n * Whether or not to create a new customer master key (CMK)\n *\n * Only applies to modern bootstrapping. Legacy bootstrapping will never create\n * a CMK, only use the default S3 key.\n *\n * @default false\n */\n readonly createCustomerMasterKey?: boolean;\n\n /**\n * The list of AWS account IDs that are trusted to deploy into the environment being bootstrapped.\n *\n * @default - only the bootstrapped account can deploy into this environment\n */\n readonly trustedAccounts?: string[];\n\n /**\n * The list of AWS account IDs that are trusted to look up values in the environment being bootstrapped.\n *\n * @default - only the bootstrapped account can look up values in this environment\n */\n readonly trustedAccountsForLookup?: string[];\n\n /**\n * The list of AWS account IDs that should not be trusted by the bootstrapped environment.\n * If these accounts are already trusted, they will be removed on bootstrapping.\n *\n * @default - no account will be untrusted.\n */\n readonly untrustedAccounts?: string[];\n\n /**\n * The ARNs of the IAM managed policies that should be attached to the role performing CloudFormation deployments.\n * In most cases, this will be the AdministratorAccess policy.\n * At least one policy is required if `trustedAccounts` were passed.\n *\n * @default - the role will have no policies attached\n */\n readonly cloudFormationExecutionPolicies?: string[];\n\n /**\n * Identifier to distinguish multiple bootstrapped environments\n *\n * @default - Default qualifier\n */\n readonly qualifier?: string;\n\n /**\n * Whether or not to enable S3 Staging Bucket Public Access Block Configuration\n *\n * @default true\n */\n readonly publicAccessBlockConfiguration?: boolean;\n\n /**\n * Flag for using the default permissions boundary for bootstrapping\n *\n * @default - No value, optional argument\n */\n readonly examplePermissionsBoundary?: boolean;\n\n /**\n * Name for the customer's custom permissions boundary for bootstrapping\n *\n * @default - No value, optional argument\n */\n readonly customPermissionsBoundary?: string;\n}\n", "import { randomUUID } from 'crypto';\nimport type * as cxapi from '@aws-cdk/cx-api';\nimport * as cdk_assets from 'cdk-assets';\nimport * as chalk from 'chalk';\nimport { AssetManifestBuilder } from './asset-manifest-builder';\nimport {\n BasePublishProgressListener,\n PublishingAws,\n} from './asset-publishing';\nimport {\n stabilizeStack,\n uploadStackTemplateAssets,\n} from './cfn-api';\nimport { determineAllowCrossAccountAssetPublishing } from './checks';\n\nimport { deployStack, destroyStack } from './deploy-stack';\nimport type { DeploymentMethod } from './deployment-method';\nimport type { DeployStackResult } from './deployment-result';\nimport { formatErrorMessage } from '../../util';\nimport type { SdkProvider } from '../aws-auth';\nimport type {\n Template,\n RootTemplateWithNestedStacks,\n} from '../cloudformation';\nimport {\n CloudFormationStack,\n loadCurrentTemplate,\n loadCurrentTemplateWithNestedStacks,\n makeBodyParameter,\n} from '../cloudformation';\nimport { type EnvironmentResources, EnvironmentAccess } from '../environment';\nimport type { HotswapMode, HotswapPropertyOverrides } from '../hotswap/common';\nimport { IO, type IoHelper } from '../io/private';\nimport type { ResourceIdentifierSummaries, ResourcesToImport } from '../resource-import';\nimport { StackActivityMonitor, StackEventPoller, RollbackChoice } from '../stack-events';\nimport type { Tag } from '../tags';\nimport { ToolkitError } from '../toolkit-error';\nimport { DEFAULT_TOOLKIT_STACK_NAME } from '../toolkit-info';\n\nconst BOOTSTRAP_STACK_VERSION_FOR_ROLLBACK = 23;\n\nexport interface DeployStackOptions {\n /**\n * Stack to deploy\n */\n readonly stack: cxapi.CloudFormationStackArtifact;\n\n /**\n * Execution role for the deployment (pass through to CloudFormation)\n *\n * @default - Current role\n */\n readonly roleArn?: string;\n\n /**\n * Topic ARNs to send a message when deployment finishes (pass through to CloudFormation)\n *\n * @default - No notifications\n */\n readonly notificationArns?: string[];\n\n /**\n * Override name under which stack will be deployed\n *\n * @default - Use artifact default\n */\n readonly deployName?: string;\n\n /**\n * Name of the toolkit stack, if not the default name\n *\n * @default 'CDKToolkit'\n */\n readonly toolkitStackName?: string;\n\n /**\n * List of asset IDs which should NOT be built or uploaded\n *\n * @default - Build all assets\n */\n readonly reuseAssets?: string[];\n\n /**\n * Stack tags (pass through to CloudFormation)\n */\n readonly tags?: Tag[];\n\n /**\n * Stage the change set but don't execute it\n *\n * @default - true\n * @deprecated Use 'deploymentMethod' instead\n */\n readonly execute?: boolean;\n\n /**\n * Optional name to use for the CloudFormation change set.\n * If not provided, a name will be generated automatically.\n *\n * @deprecated Use 'deploymentMethod' instead\n */\n readonly changeSetName?: string;\n\n /**\n * Select the deployment method (direct or using a change set)\n *\n * @default - Change set with default options\n */\n readonly deploymentMethod?: DeploymentMethod;\n\n /**\n * Force deployment, even if the deployed template is identical to the one we are about to deploy.\n * @default false deployment will be skipped if the template is identical\n */\n readonly forceDeployment?: boolean;\n\n /**\n * Extra parameters for CloudFormation\n * @default - no additional parameters will be passed to the template\n */\n readonly parameters?: { [name: string]: string | undefined };\n\n /**\n * Use previous values for unspecified parameters\n *\n * If not set, all parameters must be specified for every deployment.\n *\n * @default true\n */\n readonly usePreviousParameters?: boolean;\n\n /**\n * Rollback failed deployments\n *\n * @default true\n */\n readonly rollback?: boolean;\n\n /*\n * Whether to perform a 'hotswap' deployment.\n * A 'hotswap' deployment will attempt to short-circuit CloudFormation\n * and update the affected resources like Lambda functions directly.\n *\n * @default - `HotswapMode.FULL_DEPLOYMENT` for regular deployments, `HotswapMode.HOTSWAP_ONLY` for 'watch' deployments\n */\n readonly hotswap?: HotswapMode;\n\n /**\n * Properties that configure hotswap behavior\n */\n readonly hotswapPropertyOverrides?: HotswapPropertyOverrides;\n\n /**\n * The extra string to append to the User-Agent header when performing AWS SDK calls.\n *\n * @default - nothing extra is appended to the User-Agent header\n */\n readonly extraUserAgent?: string;\n\n /**\n * List of existing resources to be IMPORTED into the stack, instead of being CREATED\n */\n readonly resourcesToImport?: ResourcesToImport;\n\n /**\n * If present, use this given template instead of the stored one\n *\n * @default - Use the stored template\n */\n readonly overrideTemplate?: any;\n\n /**\n * Whether to build/publish assets in parallel\n *\n * @default true To remain backward compatible.\n */\n readonly assetParallelism?: boolean;\n\n /**\n * Whether to deploy if the app contains no stacks.\n *\n * @deprecated this option seems to be unsed inside deployments\n * @default false\n */\n readonly ignoreNoStacks?: boolean;\n}\n\nexport interface RollbackStackOptions {\n /**\n * Stack to roll back\n */\n readonly stack: cxapi.CloudFormationStackArtifact;\n\n /**\n * Execution role for the deployment (pass through to CloudFormation)\n *\n * @default - Current role\n */\n readonly roleArn?: string;\n\n /**\n * Name of the toolkit stack, if not the default name\n *\n * @default 'CDKToolkit'\n */\n readonly toolkitStackName?: string;\n\n /**\n * Whether to automatically orphan all failed resources during the rollback\n *\n * This will force a rollback that otherwise would have failed.\n *\n * @default false\n */\n readonly orphanFailedResources?: boolean;\n\n /**\n * Orphan the resources with the given logical IDs\n *\n * @default - No orphaning\n */\n readonly orphanLogicalIds?: string[];\n\n /**\n * Whether to validate the version of the bootstrap stack permissions\n *\n * @default true\n */\n readonly validateBootstrapStackVersion?: boolean;\n}\n\nexport type RollbackStackResult = { readonly stackArn: string } & (\n | { readonly notInRollbackableState: true }\n | { readonly success: true; notInRollbackableState?: undefined }\n);\n\ninterface AssetOptions {\n /**\n * Stack with assets to build.\n */\n readonly stack: cxapi.CloudFormationStackArtifact;\n\n /**\n * Execution role for the building.\n *\n * @default - Current role\n */\n readonly roleArn?: string;\n}\n\nexport interface BuildStackAssetsOptions extends AssetOptions {\n /**\n * Stack name this asset is for\n */\n readonly stackName?: string;\n}\n\ninterface PublishStackAssetsOptions extends AssetOptions {\n /**\n * Stack name this asset is for\n */\n readonly stackName?: string;\n\n /**\n * Always publish, even if it already exists\n *\n * @default false\n */\n readonly forcePublish?: boolean;\n}\n\nexport interface DestroyStackOptions {\n stack: cxapi.CloudFormationStackArtifact;\n deployName?: string;\n roleArn?: string;\n}\n\nexport interface StackExistsOptions {\n stack: cxapi.CloudFormationStackArtifact;\n deployName?: string;\n tryLookupRole?: boolean;\n}\n\nexport interface DeploymentsProps {\n readonly sdkProvider: SdkProvider;\n readonly toolkitStackName?: string;\n readonly ioHelper: IoHelper;\n}\n\n/**\n * Scope for a single set of deployments from a set of Cloud Assembly Artifacts\n *\n * Manages lookup of SDKs, Bootstrap stacks, etc.\n */\nexport class Deployments {\n public readonly envs: EnvironmentAccess;\n\n /**\n * SDK provider for asset publishing (do not use for anything else).\n *\n * This SDK provider is only allowed to be used for that purpose, nothing else.\n *\n * It's not a different object, but the field name should imply that this\n * object should not be used directly, except to pass to asset handling routines.\n */\n private readonly assetSdkProvider: SdkProvider;\n\n /**\n * SDK provider for passing to deployStack\n *\n * This SDK provider is only allowed to be used for that purpose, nothing else.\n *\n * It's not a different object, but the field name should imply that this\n * object should not be used directly, except to pass to `deployStack`.\n */\n private readonly deployStackSdkProvider: SdkProvider;\n\n private readonly publisherCache = new Map<cdk_assets.AssetManifest, cdk_assets.AssetPublishing>();\n\n private _allowCrossAccountAssetPublishing: boolean | undefined;\n\n private readonly ioHelper: IoHelper;\n\n constructor(private readonly props: DeploymentsProps) {\n this.assetSdkProvider = props.sdkProvider;\n this.deployStackSdkProvider = props.sdkProvider;\n this.ioHelper = props.ioHelper;\n this.envs = new EnvironmentAccess(\n props.sdkProvider,\n props.toolkitStackName ?? DEFAULT_TOOLKIT_STACK_NAME,\n this.ioHelper,\n );\n }\n\n /**\n * Resolves the environment for a stack.\n */\n public async resolveEnvironment(stack: cxapi.CloudFormationStackArtifact): Promise<cxapi.Environment> {\n return this.envs.resolveStackEnvironment(stack);\n }\n\n public async readCurrentTemplateWithNestedStacks(\n rootStackArtifact: cxapi.CloudFormationStackArtifact,\n retrieveProcessedTemplate: boolean = false,\n ): Promise<RootTemplateWithNestedStacks> {\n const env = await this.envs.accessStackForLookupBestEffort(rootStackArtifact);\n return loadCurrentTemplateWithNestedStacks(rootStackArtifact, env.sdk, retrieveProcessedTemplate);\n }\n\n public async readCurrentTemplate(stackArtifact: cxapi.CloudFormationStackArtifact): Promise<Template> {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Reading existing template for stack ${stackArtifact.displayName}.`));\n const env = await this.envs.accessStackForLookupBestEffort(stackArtifact);\n return loadCurrentTemplate(stackArtifact, env.sdk);\n }\n\n public async resourceIdentifierSummaries(\n stackArtifact: cxapi.CloudFormationStackArtifact,\n ): Promise<ResourceIdentifierSummaries> {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Retrieving template summary for stack ${stackArtifact.displayName}.`));\n // Currently, needs to use `deploy-role` since it may need to read templates in the staging\n // bucket which have been encrypted with a KMS key (and lookup-role may not read encrypted things)\n const env = await this.envs.accessStackForReadOnlyStackOperations(stackArtifact);\n const cfn = env.sdk.cloudFormation();\n\n await uploadStackTemplateAssets(stackArtifact, this);\n\n // Upload the template, if necessary, before passing it to CFN\n const builder = new AssetManifestBuilder();\n const cfnParam = await makeBodyParameter(\n this.ioHelper,\n stackArtifact,\n env.resolvedEnvironment,\n builder,\n env.resources,\n );\n\n // If the `makeBodyParameter` before this added assets, make sure to publish them before\n // calling the API.\n const addedAssets = builder.toManifest(stackArtifact.assembly.directory);\n for (const entry of addedAssets.entries) {\n await this.buildSingleAsset('no-version-validation', addedAssets, entry, {\n stack: stackArtifact,\n });\n await this.publishSingleAsset(addedAssets, entry, {\n stack: stackArtifact,\n });\n }\n\n const response = await cfn.getTemplateSummary(cfnParam);\n if (!response.ResourceIdentifierSummaries) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg('GetTemplateSummary API call did not return \"ResourceIdentifierSummaries\"'));\n }\n return response.ResourceIdentifierSummaries ?? [];\n }\n\n public async deployStack(options: DeployStackOptions): Promise<DeployStackResult> {\n let deploymentMethod = options.deploymentMethod;\n if (options.changeSetName || options.execute !== undefined) {\n if (deploymentMethod) {\n throw new ToolkitError(\n \"You cannot supply both 'deploymentMethod' and 'changeSetName/execute'. Supply one or the other.\",\n );\n }\n deploymentMethod = {\n method: 'change-set',\n changeSetName: options.changeSetName,\n execute: options.execute,\n };\n }\n\n const env = await this.envs.accessStackForMutableStackOperations(options.stack);\n\n // Do a verification of the bootstrap stack version\n await this.validateBootstrapStackVersion(\n options.stack.stackName,\n options.stack.requiresBootstrapStackVersion,\n options.stack.bootstrapStackVersionSsmParameter,\n env.resources);\n\n const executionRoleArn = await env.replacePlaceholders(options.roleArn ?? options.stack.cloudFormationExecutionRoleArn);\n\n return deployStack({\n stack: options.stack,\n resolvedEnvironment: env.resolvedEnvironment,\n deployName: options.deployName,\n notificationArns: options.notificationArns,\n sdk: env.sdk,\n sdkProvider: this.deployStackSdkProvider,\n roleArn: executionRoleArn,\n reuseAssets: options.reuseAssets,\n envResources: env.resources,\n tags: options.tags,\n deploymentMethod,\n forceDeployment: options.forceDeployment,\n parameters: options.parameters,\n usePreviousParameters: options.usePreviousParameters,\n rollback: options.rollback,\n hotswap: options.hotswap,\n hotswapPropertyOverrides: options.hotswapPropertyOverrides,\n extraUserAgent: options.extraUserAgent,\n resourcesToImport: options.resourcesToImport,\n overrideTemplate: options.overrideTemplate,\n assetParallelism: options.assetParallelism,\n }, this.ioHelper);\n }\n\n public async rollbackStack(options: RollbackStackOptions): Promise<RollbackStackResult> {\n let resourcesToSkip: string[] = options.orphanLogicalIds ?? [];\n if (options.orphanFailedResources && resourcesToSkip.length > 0) {\n throw new ToolkitError('Cannot combine --force with --orphan');\n }\n\n const env = await this.envs.accessStackForMutableStackOperations(options.stack);\n\n if (options.validateBootstrapStackVersion ?? true) {\n // Do a verification of the bootstrap stack version\n await this.validateBootstrapStackVersion(\n options.stack.stackName,\n BOOTSTRAP_STACK_VERSION_FOR_ROLLBACK,\n options.stack.bootstrapStackVersionSsmParameter,\n env.resources);\n }\n\n const cfn = env.sdk.cloudFormation();\n const deployName = options.stack.stackName;\n\n // We loop in case of `--force` and the stack ends up in `CONTINUE_UPDATE_ROLLBACK`.\n let maxLoops = 10;\n while (maxLoops--) {\n const cloudFormationStack = await CloudFormationStack.lookup(cfn, deployName);\n const stackArn = cloudFormationStack.stackId;\n\n const executionRoleArn = await env.replacePlaceholders(options.roleArn ?? options.stack.cloudFormationExecutionRoleArn);\n\n switch (cloudFormationStack.stackStatus.rollbackChoice) {\n case RollbackChoice.NONE:\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_WARN.msg(`Stack ${deployName} does not need a rollback: ${cloudFormationStack.stackStatus}`));\n return { stackArn: cloudFormationStack.stackId, notInRollbackableState: true };\n\n case RollbackChoice.START_ROLLBACK:\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Initiating rollback of stack ${deployName}`));\n await cfn.rollbackStack({\n StackName: deployName,\n RoleARN: executionRoleArn,\n ClientRequestToken: randomUUID(),\n // Enabling this is just the better overall default, the only reason it isn't the upstream default is backwards compatibility\n RetainExceptOnCreate: true,\n });\n break;\n\n case RollbackChoice.CONTINUE_UPDATE_ROLLBACK:\n if (options.orphanFailedResources) {\n // Find the failed resources from the deployment and automatically skip them\n // (Using deployment log because we definitely have `DescribeStackEvents` permissions, and we might not have\n // `DescribeStackResources` permissions).\n const poller = new StackEventPoller(cfn, {\n stackName: deployName,\n stackStatuses: ['ROLLBACK_IN_PROGRESS', 'UPDATE_ROLLBACK_IN_PROGRESS'],\n });\n await poller.poll();\n resourcesToSkip = poller.resourceErrors\n .filter((r) => !r.isStackEvent && r.parentStackLogicalIds.length === 0)\n .map((r) => r.event.LogicalResourceId ?? '');\n }\n\n const skipDescription = resourcesToSkip.length > 0 ? ` (orphaning: ${resourcesToSkip.join(', ')})` : '';\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_WARN.msg(`Continuing rollback of stack ${deployName}${skipDescription}`));\n await cfn.continueUpdateRollback({\n StackName: deployName,\n ClientRequestToken: randomUUID(),\n RoleARN: executionRoleArn,\n ResourcesToSkip: resourcesToSkip,\n });\n break;\n\n case RollbackChoice.ROLLBACK_FAILED:\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_WARN.msg(\n `Stack ${deployName} failed creation and rollback. This state cannot be rolled back. You can recreate this stack by running 'cdk deploy'.`,\n ));\n return { stackArn, notInRollbackableState: true };\n\n default:\n throw new ToolkitError(`Unexpected rollback choice: ${cloudFormationStack.stackStatus.rollbackChoice}`);\n }\n\n const monitor = new StackActivityMonitor({\n cfn,\n stack: options.stack,\n stackName: deployName,\n ioHelper: this.ioHelper,\n });\n await monitor.start();\n\n let stackErrorMessage: string | undefined = undefined;\n let finalStackState = cloudFormationStack;\n try {\n const successStack = await stabilizeStack(cfn, this.ioHelper, deployName);\n\n // This shouldn't really happen, but catch it anyway. You never know.\n if (!successStack) {\n throw new ToolkitError('Stack deploy failed (the stack disappeared while we were rolling it back)');\n }\n finalStackState = successStack;\n\n const errors = monitor.errors.join(', ');\n if (errors) {\n stackErrorMessage = errors;\n }\n } catch (e: any) {\n stackErrorMessage = suffixWithErrors(formatErrorMessage(e), monitor.errors);\n } finally {\n await monitor.stop();\n }\n\n if (finalStackState.stackStatus.isRollbackSuccess || !stackErrorMessage) {\n return { stackArn, success: true };\n }\n\n // Either we need to ignore some resources to continue the rollback, or something went wrong\n if (finalStackState.stackStatus.rollbackChoice === RollbackChoice.CONTINUE_UPDATE_ROLLBACK && options.orphanFailedResources) {\n // Do another loop-de-loop\n continue;\n }\n\n throw new ToolkitError(\n `${stackErrorMessage} (fix problem and retry, or orphan these resources using --orphan or --force)`,\n );\n }\n throw new ToolkitError(\n \"Rollback did not finish after a large number of iterations; stopping because it looks like we're not making progress anymore. You can retry if rollback was progressing as expected.\",\n );\n }\n\n public async destroyStack(options: DestroyStackOptions) {\n const env = await this.envs.accessStackForMutableStackOperations(options.stack);\n const executionRoleArn = await env.replacePlaceholders(options.roleArn ?? options.stack.cloudFormationExecutionRoleArn);\n\n return destroyStack({\n sdk: env.sdk,\n roleArn: executionRoleArn,\n stack: options.stack,\n deployName: options.deployName,\n }, this.ioHelper);\n }\n\n public async stackExists(options: StackExistsOptions): Promise<boolean> {\n let env;\n if (options.tryLookupRole) {\n env = await this.envs.accessStackForLookupBestEffort(options.stack);\n } else {\n env = await this.envs.accessStackForReadOnlyStackOperations(options.stack);\n }\n const stack = await CloudFormationStack.lookup(env.sdk.cloudFormation(), options.deployName ?? options.stack.stackName);\n return stack.exists;\n }\n\n /**\n * Build a single asset from an asset manifest\n *\n * If an assert manifest artifact is given, the bootstrap stack version\n * will be validated according to the constraints in that manifest artifact.\n * If that is not necessary, `'no-version-validation'` can be passed.\n */\n // eslint-disable-next-line max-len\n public async buildSingleAsset(\n assetArtifact: cxapi.AssetManifestArtifact | 'no-version-validation',\n assetManifest: cdk_assets.AssetManifest,\n asset: cdk_assets.IManifestEntry,\n options: BuildStackAssetsOptions,\n ) {\n if (assetArtifact !== 'no-version-validation') {\n const env = await this.envs.accessStackForReadOnlyStackOperations(options.stack);\n await this.validateBootstrapStackVersion(\n options.stack.stackName,\n assetArtifact.requiresBootstrapStackVersion,\n assetArtifact.bootstrapStackVersionSsmParameter,\n env.resources);\n }\n\n const resolvedEnvironment = await this.envs.resolveStackEnvironment(options.stack);\n\n const publisher = this.cachedPublisher(assetManifest, resolvedEnvironment, options.stackName);\n await publisher.buildEntry(asset);\n if (publisher.hasFailures) {\n throw new ToolkitError(`Failed to build asset ${asset.displayName(false)}`);\n }\n }\n\n /**\n * Publish a single asset from an asset manifest\n */\n public async publishSingleAsset(\n assetManifest: cdk_assets.AssetManifest,\n asset: cdk_assets.IManifestEntry,\n options: PublishStackAssetsOptions,\n ) {\n const stackEnv = await this.envs.resolveStackEnvironment(options.stack);\n\n // No need to validate anymore, we already did that during build\n const publisher = this.cachedPublisher(assetManifest, stackEnv, options.stackName);\n await publisher.publishEntry(asset, {\n allowCrossAccount: await this.allowCrossAccountAssetPublishingForEnv(options.stack),\n force: options.forcePublish,\n });\n if (publisher.hasFailures) {\n throw new ToolkitError(`Failed to publish asset ${asset.displayName(true)}`);\n }\n }\n\n private async allowCrossAccountAssetPublishingForEnv(stack: cxapi.CloudFormationStackArtifact): Promise<boolean> {\n if (this._allowCrossAccountAssetPublishing === undefined) {\n const env = await this.envs.accessStackForReadOnlyStackOperations(stack);\n this._allowCrossAccountAssetPublishing = await determineAllowCrossAccountAssetPublishing(env.sdk, this.ioHelper, this.props.toolkitStackName);\n }\n return this._allowCrossAccountAssetPublishing;\n }\n\n /**\n * Return whether a single asset has been published already\n */\n public async isSingleAssetPublished(\n assetManifest: cdk_assets.AssetManifest,\n asset: cdk_assets.IManifestEntry,\n options: PublishStackAssetsOptions,\n ) {\n const stackEnv = await this.envs.resolveStackEnvironment(options.stack);\n const publisher = this.cachedPublisher(assetManifest, stackEnv, options.stackName);\n return publisher.isEntryPublished(asset);\n }\n\n /**\n * Validate that the bootstrap stack has the right version for this stack\n *\n * Call into envResources.validateVersion, but prepend the stack name in case of failure.\n */\n private async validateBootstrapStackVersion(\n stackName: string,\n requiresBootstrapStackVersion: number | undefined,\n bootstrapStackVersionSsmParameter: string | undefined,\n envResources: EnvironmentResources,\n ) {\n try {\n await envResources.validateVersion(requiresBootstrapStackVersion, bootstrapStackVersionSsmParameter);\n } catch (e: any) {\n throw new ToolkitError(`${stackName}: ${formatErrorMessage(e)}`);\n }\n }\n\n private cachedPublisher(assetManifest: cdk_assets.AssetManifest, env: cxapi.Environment, stackName?: string) {\n const existing = this.publisherCache.get(assetManifest);\n if (existing) {\n return existing;\n }\n const prefix = stackName ? `${chalk.bold(stackName)}: ` : '';\n const publisher = new cdk_assets.AssetPublishing(assetManifest, {\n // The AssetPublishing class takes care of role assuming etc, so it's okay to\n // give it a direct `SdkProvider`.\n aws: new PublishingAws(this.assetSdkProvider, env),\n progressListener: new ParallelSafeAssetProgress(prefix, this.ioHelper),\n });\n this.publisherCache.set(assetManifest, publisher);\n return publisher;\n }\n}\n\n/**\n * Asset progress that doesn't do anything with percentages (currently)\n */\nclass ParallelSafeAssetProgress extends BasePublishProgressListener {\n private readonly prefix: string;\n\n constructor(prefix: string, ioHelper: IoHelper) {\n super(ioHelper);\n this.prefix = prefix;\n }\n\n protected getMessage(type: cdk_assets.EventType, event: cdk_assets.IPublishProgress): string {\n return `${this.prefix}${type}: ${event.message}`;\n }\n}\n\nfunction suffixWithErrors(msg: string, errors?: string[]) {\n return errors && errors.length > 0 ? `${msg}: ${errors.join(', ')}` : msg;\n}\n", "import * as cxschema from '@aws-cdk/cloud-assembly-schema';\nimport { AssetManifest } from 'cdk-assets';\n\nexport class AssetManifestBuilder {\n private readonly manifest: cxschema.AssetManifest = {\n version: cxschema.Manifest.version(),\n files: {},\n dockerImages: {},\n };\n\n public addFileAsset(id: string, source: cxschema.FileSource, destination: cxschema.FileDestination) {\n this.manifest.files![id] = {\n source,\n destinations: {\n current: destination,\n },\n };\n }\n\n public addDockerImageAsset(id: string, source: cxschema.DockerImageSource, destination: cxschema.DockerImageDestination) {\n this.manifest.dockerImages![id] = {\n source,\n destinations: {\n current: destination,\n },\n };\n }\n\n public toManifest(directory: string): AssetManifest {\n return new AssetManifest(directory, this.manifest);\n }\n}\n", "import { type Environment, UNKNOWN_ACCOUNT, UNKNOWN_REGION } from '@aws-cdk/cx-api';\nimport type {\n ClientOptions,\n EventType,\n Account,\n AssetManifest,\n IAws,\n IECRClient,\n IPublishProgress,\n IPublishProgressListener,\n IS3Client,\n ISecretsManagerClient,\n} from 'cdk-assets';\nimport {\n AssetPublishing,\n} from 'cdk-assets';\nimport type { SDK } from '..';\nimport type { SdkProvider } from '../aws-auth';\nimport type { IoMessageMaker, IoHelper } from '../io/private';\nimport { IO } from '../io/private';\nimport { Mode } from '../plugin';\nimport { ToolkitError } from '../toolkit-error';\n\ninterface PublishAssetsOptions {\n /**\n * Whether to build/publish assets in parallel\n *\n * @default true To remain backward compatible.\n */\n readonly parallel?: boolean;\n\n /**\n * Whether cdk-assets is allowed to do cross account publishing.\n */\n readonly allowCrossAccount: boolean;\n}\n\n/**\n * Use cdk-assets to publish all assets in the given manifest.\n *\n * @deprecated used in legacy deployments only, should be migrated at some point\n */\nexport async function publishAssets(\n manifest: AssetManifest,\n sdk: SdkProvider,\n targetEnv: Environment,\n options: PublishAssetsOptions,\n ioHelper: IoHelper,\n) {\n // This shouldn't really happen (it's a programming error), but we don't have\n // the types here to guide us. Do an runtime validation to be super super sure.\n if (\n targetEnv.account === undefined ||\n targetEnv.account === UNKNOWN_ACCOUNT ||\n targetEnv.region === undefined ||\n targetEnv.account === UNKNOWN_REGION\n ) {\n throw new ToolkitError(`Asset publishing requires resolved account and region, got ${JSON.stringify(targetEnv)}`);\n }\n\n const publisher = new AssetPublishing(manifest, {\n aws: new PublishingAws(sdk, targetEnv),\n progressListener: new PublishingProgressListener(ioHelper),\n throwOnError: false,\n publishInParallel: options.parallel ?? true,\n buildAssets: true,\n publishAssets: true,\n quiet: false,\n });\n await publisher.publish({ allowCrossAccount: options.allowCrossAccount });\n if (publisher.hasFailures) {\n throw new ToolkitError('Failed to publish one or more assets. See the error messages above for more information.');\n }\n}\n\nexport class PublishingAws implements IAws {\n private sdkCache: Map<String, SDK> = new Map();\n\n constructor(\n /**\n * The base SDK to work with\n */\n private readonly aws: SdkProvider,\n\n /**\n * Environment where the stack we're deploying is going\n */\n private readonly targetEnv: Environment,\n ) {\n }\n\n public async discoverPartition(): Promise<string> {\n return (await this.aws.baseCredentialsPartition(this.targetEnv, Mode.ForWriting)) ?? 'aws';\n }\n\n public async discoverDefaultRegion(): Promise<string> {\n return this.targetEnv.region;\n }\n\n public async discoverCurrentAccount(): Promise<Account> {\n const account = await this.aws.defaultAccount();\n return (\n account ?? {\n accountId: '<unknown account>',\n partition: 'aws',\n }\n );\n }\n\n public async discoverTargetAccount(options: ClientOptions): Promise<Account> {\n return (await this.sdk(options)).currentAccount();\n }\n\n public async s3Client(options: ClientOptions): Promise<IS3Client> {\n return (await this.sdk(options)).s3();\n }\n\n public async ecrClient(options: ClientOptions): Promise<IECRClient> {\n return (await this.sdk(options)).ecr();\n }\n\n public async secretsManagerClient(options: ClientOptions): Promise<ISecretsManagerClient> {\n return (await this.sdk(options)).secretsManager();\n }\n\n /**\n * Get an SDK appropriate for the given client options\n */\n private async sdk(options: ClientOptions): Promise<SDK> {\n const env = {\n ...this.targetEnv,\n region: options.region ?? this.targetEnv.region, // Default: same region as the stack\n };\n\n const cacheKeyMap: any = {\n env, // region, name, account\n assumeRuleArn: options.assumeRoleArn,\n assumeRoleExternalId: options.assumeRoleExternalId,\n quiet: options.quiet,\n };\n\n if (options.assumeRoleAdditionalOptions) {\n cacheKeyMap.assumeRoleAdditionalOptions = options.assumeRoleAdditionalOptions;\n }\n\n const cacheKey = JSON.stringify(cacheKeyMap);\n\n const maybeSdk = this.sdkCache.get(cacheKey);\n if (maybeSdk) {\n return maybeSdk;\n }\n\n const sdk = (\n await this.aws.forEnvironment(\n env,\n Mode.ForWriting,\n {\n assumeRoleArn: options.assumeRoleArn,\n assumeRoleExternalId: options.assumeRoleExternalId,\n assumeRoleAdditionalOptions: options.assumeRoleAdditionalOptions,\n },\n options.quiet,\n )\n ).sdk;\n this.sdkCache.set(cacheKey, sdk);\n\n return sdk;\n }\n}\n\nconst EVENT_TO_MSG_MAKER: Record<EventType, IoMessageMaker<any> | false> = {\n build: IO.DEFAULT_TOOLKIT_DEBUG,\n cached: IO.DEFAULT_TOOLKIT_DEBUG,\n check: IO.DEFAULT_TOOLKIT_DEBUG,\n debug: IO.DEFAULT_TOOLKIT_DEBUG,\n fail: IO.DEFAULT_TOOLKIT_ERROR,\n found: IO.DEFAULT_TOOLKIT_DEBUG,\n start: IO.DEFAULT_TOOLKIT_INFO,\n success: IO.DEFAULT_TOOLKIT_INFO,\n upload: IO.DEFAULT_TOOLKIT_DEBUG,\n shell_open: IO.DEFAULT_TOOLKIT_DEBUG,\n shell_stderr: false,\n shell_stdout: false,\n shell_close: false,\n};\n\nexport abstract class BasePublishProgressListener implements IPublishProgressListener {\n protected readonly ioHelper: IoHelper;\n\n constructor(ioHelper: IoHelper) {\n this.ioHelper = ioHelper;\n }\n\n protected abstract getMessage(type: EventType, event: IPublishProgress): string;\n\n public onPublishEvent(type: EventType, event: IPublishProgress): void {\n const maker = EVENT_TO_MSG_MAKER[type];\n if (maker) {\n void this.ioHelper.notify(maker.msg(this.getMessage(type, event)));\n }\n }\n}\n\nclass PublishingProgressListener extends BasePublishProgressListener {\n protected getMessage(type: EventType, event: IPublishProgress): string {\n return `[${event.percentComplete}%] ${type}: ${event.message}`;\n }\n}\n", "import { format } from 'util';\nimport * as cxapi from '@aws-cdk/cx-api';\nimport { SSMPARAM_NO_INVALIDATE } from '@aws-cdk/cx-api';\nimport type {\n DescribeChangeSetCommandOutput,\n Parameter,\n ResourceToImport,\n Tag,\n} from '@aws-sdk/client-cloudformation';\nimport {\n ChangeSetStatus,\n} from '@aws-sdk/client-cloudformation';\nimport type { FileManifestEntry } from 'cdk-assets';\nimport { AssetManifest } from 'cdk-assets';\nimport { AssetManifestBuilder } from './asset-manifest-builder';\nimport type { Deployments } from './deployments';\nimport type { ICloudFormationClient, SdkProvider } from '../aws-auth';\nimport type { Template, TemplateBodyParameter, TemplateParameter } from '../cloudformation';\nimport { CloudFormationStack, makeBodyParameter } from '../cloudformation';\nimport { IO, type IoHelper } from '../io/private';\nimport type { ResourcesToImport } from '../resource-import';\nimport { ToolkitError } from '../toolkit-error';\n\n/**\n * Describe a changeset in CloudFormation, regardless of its current state.\n *\n * @param cfn a CloudFormation client\n * @param stackName the name of the Stack the ChangeSet belongs to\n * @param changeSetName the name of the ChangeSet\n * @param fetchAll if true, fetches all pages of the change set description.\n *\n * @returns CloudFormation information about the ChangeSet\n */\nasync function describeChangeSet(\n cfn: ICloudFormationClient,\n stackName: string,\n changeSetName: string,\n { fetchAll }: { fetchAll: boolean },\n): Promise<DescribeChangeSetCommandOutput> {\n const response = await cfn.describeChangeSet({\n StackName: stackName,\n ChangeSetName: changeSetName,\n });\n\n // If fetchAll is true, traverse all pages from the change set description.\n while (fetchAll && response.NextToken != null) {\n const nextPage = await cfn.describeChangeSet({\n StackName: stackName,\n ChangeSetName: response.ChangeSetId ?? changeSetName,\n NextToken: response.NextToken,\n });\n\n // Consolidate the changes\n if (nextPage.Changes != null) {\n response.Changes = response.Changes != null ? response.Changes.concat(nextPage.Changes) : nextPage.Changes;\n }\n\n // Forward the new NextToken\n response.NextToken = nextPage.NextToken;\n }\n\n return response;\n}\n\n/**\n * Waits for a function to return non-+undefined+ before returning.\n *\n * @param valueProvider a function that will return a value that is not +undefined+ once the wait should be over\n * @param timeout the time to wait between two calls to +valueProvider+\n *\n * @returns the value that was returned by +valueProvider+\n */\nasync function waitFor<T>(\n valueProvider: () => Promise<T | null | undefined>,\n timeout: number = 5000,\n): Promise<T | undefined> {\n while (true) {\n const result = await valueProvider();\n if (result === null) {\n return undefined;\n } else if (result !== undefined) {\n return result;\n }\n await new Promise((cb) => setTimeout(cb, timeout));\n }\n}\n\n/**\n * Waits for a ChangeSet to be available for triggering a StackUpdate.\n *\n * Will return a changeset that is either ready to be executed or has no changes.\n * Will throw in other cases.\n *\n * @param cfn a CloudFormation client\n * @param stackName the name of the Stack that the ChangeSet belongs to\n * @param changeSetName the name of the ChangeSet\n * @param fetchAll if true, fetches all pages of the ChangeSet before returning.\n *\n * @returns the CloudFormation description of the ChangeSet\n */\nexport async function waitForChangeSet(\n cfn: ICloudFormationClient,\n ioHelper: IoHelper,\n stackName: string,\n changeSetName: string,\n { fetchAll }: { fetchAll: boolean },\n): Promise<DescribeChangeSetCommandOutput> {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(format('Waiting for changeset %s on stack %s to finish creating...', changeSetName, stackName)));\n const ret = await waitFor(async () => {\n const description = await describeChangeSet(cfn, stackName, changeSetName, {\n fetchAll,\n });\n // The following doesn't use a switch because tsc will not allow fall-through, UNLESS it is allows\n // EVERYWHERE that uses this library directly or indirectly, which is undesirable.\n if (description.Status === 'CREATE_PENDING' || description.Status === 'CREATE_IN_PROGRESS') {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(format('Changeset %s on stack %s is still creating', changeSetName, stackName)));\n return undefined;\n }\n\n if (description.Status === ChangeSetStatus.CREATE_COMPLETE || changeSetHasNoChanges(description)) {\n return description;\n }\n\n // eslint-disable-next-line max-len\n throw new ToolkitError(\n `Failed to create ChangeSet ${changeSetName} on ${stackName}: ${description.Status || 'NO_STATUS'}, ${description.StatusReason || 'no reason provided'}`,\n );\n });\n\n if (!ret) {\n throw new ToolkitError('Change set took too long to be created; aborting');\n }\n\n return ret;\n}\n\nexport type PrepareChangeSetOptions = {\n stack: cxapi.CloudFormationStackArtifact;\n deployments: Deployments;\n uuid: string;\n willExecute: boolean;\n sdkProvider: SdkProvider;\n parameters: { [name: string]: string | undefined };\n resourcesToImport?: ResourcesToImport;\n /**\n * Default behavior is to log AWS CloudFormation errors and move on. Set this property to true to instead\n * fail on errors received by AWS CloudFormation.\n *\n * @default false\n */\n failOnError?: boolean;\n}\n\nexport type CreateChangeSetOptions = {\n cfn: ICloudFormationClient;\n changeSetName: string;\n willExecute: boolean;\n exists: boolean;\n uuid: string;\n stack: cxapi.CloudFormationStackArtifact;\n bodyParameter: TemplateBodyParameter;\n parameters: { [name: string]: string | undefined };\n resourcesToImport?: ResourceToImport[];\n role?: string;\n};\n\n/**\n * Create a changeset for a diff operation\n */\nexport async function createDiffChangeSet(\n ioHelper: IoHelper,\n options: PrepareChangeSetOptions,\n): Promise<DescribeChangeSetCommandOutput | undefined> {\n // `options.stack` has been modified to include any nested stack templates directly inline with its own template, under a special `NestedTemplate` property.\n // Thus the parent template's Resources section contains the nested template's CDK metadata check, which uses Fn::Equals.\n // This causes CreateChangeSet to fail with `Template Error: Fn::Equals cannot be partially collapsed`.\n for (const resource of Object.values(options.stack.template.Resources ?? {})) {\n if ((resource as any).Type === 'AWS::CloudFormation::Stack') {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg('This stack contains one or more nested stacks, falling back to template-only diff...'));\n\n return undefined;\n }\n }\n\n return uploadBodyParameterAndCreateChangeSet(ioHelper, options);\n}\n\n/**\n * Returns all file entries from an AssetManifestArtifact that look like templates.\n *\n * This is used in the `uploadBodyParameterAndCreateChangeSet` function to find\n * all template asset files to build and publish.\n *\n * Returns a tuple of [AssetManifest, FileManifestEntry[]]\n */\nfunction templatesFromAssetManifestArtifact(\n artifact: cxapi.AssetManifestArtifact,\n): [AssetManifest, FileManifestEntry[]] {\n const assets: FileManifestEntry[] = [];\n const fileName = artifact.file;\n const assetManifest = AssetManifest.fromFile(fileName);\n\n assetManifest.entries.forEach((entry) => {\n if (entry.type === 'file') {\n const source = (entry as FileManifestEntry).source;\n if (source.path && source.path.endsWith('.template.json')) {\n assets.push(entry as FileManifestEntry);\n }\n }\n });\n return [assetManifest, assets];\n}\n\nasync function uploadBodyParameterAndCreateChangeSet(\n ioHelper: IoHelper,\n options: PrepareChangeSetOptions,\n): Promise<DescribeChangeSetCommandOutput | undefined> {\n try {\n await uploadStackTemplateAssets(options.stack, options.deployments);\n const env = await options.deployments.envs.accessStackForMutableStackOperations(options.stack);\n\n const bodyParameter = await makeBodyParameter(\n ioHelper,\n options.stack,\n env.resolvedEnvironment,\n new AssetManifestBuilder(),\n env.resources,\n );\n const cfn = env.sdk.cloudFormation();\n const exists = (await CloudFormationStack.lookup(cfn, options.stack.stackName, false)).exists;\n\n const executionRoleArn = await env.replacePlaceholders(options.stack.cloudFormationExecutionRoleArn);\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(\n 'Hold on while we create a read-only change set to get a diff with accurate replacement information (use --no-change-set to use a less accurate but faster template-only diff)\\n',\n ));\n\n return await createChangeSet(ioHelper, {\n cfn,\n changeSetName: 'cdk-diff-change-set',\n stack: options.stack,\n exists,\n uuid: options.uuid,\n willExecute: options.willExecute,\n bodyParameter,\n parameters: options.parameters,\n resourcesToImport: options.resourcesToImport,\n role: executionRoleArn,\n });\n } catch (e: any) {\n // This function is currently only used by diff so these messages are diff-specific\n if (!options.failOnError) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(String(e)));\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(\n 'Could not create a change set, will base the diff on template differences (run again with -v to see the reason)\\n',\n ));\n\n return undefined;\n }\n\n throw new ToolkitError('Could not create a change set and failOnError is set. (run again with failOnError off to base the diff on template differences)\\n', e);\n }\n}\n\n/**\n * Uploads the assets that look like templates for this CloudFormation stack\n *\n * This is necessary for any CloudFormation call that needs the template, it may need\n * to be uploaded to an S3 bucket first. We have to follow the instructions in the\n * asset manifest, because technically that is the only place that knows about\n * bucket and assumed roles and such.\n */\nexport async function uploadStackTemplateAssets(stack: cxapi.CloudFormationStackArtifact, deployments: Deployments) {\n for (const artifact of stack.dependencies) {\n // Skip artifact if it is not an Asset Manifest Artifact\n if (!cxapi.AssetManifestArtifact.isAssetManifestArtifact(artifact)) {\n continue;\n }\n\n const [assetManifest, file_entries] = templatesFromAssetManifestArtifact(artifact);\n for (const entry of file_entries) {\n await deployments.buildSingleAsset(artifact, assetManifest, entry, {\n stack,\n });\n await deployments.publishSingleAsset(assetManifest, entry, {\n stack,\n });\n }\n }\n}\n\nexport async function createChangeSet(\n ioHelper: IoHelper,\n options: CreateChangeSetOptions,\n): Promise<DescribeChangeSetCommandOutput> {\n await cleanupOldChangeset(options.cfn, ioHelper, options.changeSetName, options.stack.stackName);\n\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Attempting to create ChangeSet with name ${options.changeSetName} for stack ${options.stack.stackName}`));\n\n const templateParams = TemplateParameters.fromTemplate(options.stack.template);\n const stackParams = templateParams.supplyAll(options.parameters);\n\n const changeSet = await options.cfn.createChangeSet({\n StackName: options.stack.stackName,\n ChangeSetName: options.changeSetName,\n ChangeSetType: options.resourcesToImport ? 'IMPORT' : options.exists ? 'UPDATE' : 'CREATE',\n Description: `CDK Changeset for diff ${options.uuid}`,\n ClientToken: `diff${options.uuid}`,\n TemplateURL: options.bodyParameter.TemplateURL,\n TemplateBody: options.bodyParameter.TemplateBody,\n Parameters: stackParams.apiParameters,\n ResourcesToImport: options.resourcesToImport,\n RoleARN: options.role,\n Tags: toCfnTags(options.stack.tags),\n Capabilities: ['CAPABILITY_IAM', 'CAPABILITY_NAMED_IAM', 'CAPABILITY_AUTO_EXPAND'],\n });\n\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(format('Initiated creation of changeset: %s; waiting for it to finish creating...', changeSet.Id)));\n // Fetching all pages if we'll execute, so we can have the correct change count when monitoring.\n const createdChangeSet = await waitForChangeSet(options.cfn, ioHelper, options.stack.stackName, options.changeSetName, {\n fetchAll: options.willExecute,\n });\n await cleanupOldChangeset(options.cfn, ioHelper, options.changeSetName, options.stack.stackName);\n\n return createdChangeSet;\n}\n\nfunction toCfnTags(tags: { [id: string]: string }): Tag[] {\n return Object.entries(tags).map(([k, v]) => ({\n Key: k,\n Value: v,\n }));\n}\n\nasync function cleanupOldChangeset(\n cfn: ICloudFormationClient,\n ioHelper: IoHelper,\n changeSetName: string,\n stackName: string,\n) {\n // Delete any existing change sets generated by CDK since change set names must be unique.\n // The delete request is successful as long as the stack exists (even if the change set does not exist).\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Removing existing change set with name ${changeSetName} if it exists`));\n await cfn.deleteChangeSet({\n StackName: stackName,\n ChangeSetName: changeSetName,\n });\n}\n\n/**\n * Return true if the given change set has no changes\n *\n * This must be determined from the status, not the 'Changes' array on the\n * object; the latter can be empty because no resources were changed, but if\n * there are changes to Outputs, the change set can still be executed.\n */\nexport function changeSetHasNoChanges(description: DescribeChangeSetCommandOutput) {\n const noChangeErrorPrefixes = [\n // Error message for a regular template\n \"The submitted information didn't contain changes.\",\n // Error message when a Transform is involved (see #10650)\n 'No updates are to be performed.',\n ];\n\n return (\n description.Status === 'FAILED' && noChangeErrorPrefixes.some((p) => (description.StatusReason ?? '').startsWith(p))\n );\n}\n\n/**\n * Waits for a CloudFormation stack to stabilize in a complete/available state\n * after a delete operation is issued.\n *\n * Fails if the stack is in a FAILED state. Will not fail if the stack was\n * already deleted.\n *\n * @param cfn a CloudFormation client\n * @param stackName the name of the stack to wait for after a delete\n *\n * @returns the CloudFormation description of the stabilized stack after the delete attempt\n */\nexport async function waitForStackDelete(\n cfn: ICloudFormationClient,\n ioHelper: IoHelper,\n stackName: string,\n): Promise<CloudFormationStack | undefined> {\n const stack = await stabilizeStack(cfn, ioHelper, stackName);\n if (!stack) {\n return undefined;\n }\n\n const status = stack.stackStatus;\n if (status.isFailure) {\n throw new ToolkitError(\n `The stack named ${stackName} is in a failed state. You may need to delete it from the AWS console : ${status}`,\n );\n } else if (status.isDeleted) {\n return undefined;\n }\n return stack;\n}\n\n/**\n * Waits for a CloudFormation stack to stabilize in a complete/available state\n * after an update/create operation is issued.\n *\n * Fails if the stack is in a FAILED state, ROLLBACK state, or DELETED state.\n *\n * @param cfn a CloudFormation client\n * @param stackName the name of the stack to wait for after an update\n *\n * @returns the CloudFormation description of the stabilized stack after the update attempt\n */\nexport async function waitForStackDeploy(\n cfn: ICloudFormationClient,\n ioHelper: IoHelper,\n stackName: string,\n): Promise<CloudFormationStack | undefined> {\n const stack = await stabilizeStack(cfn, ioHelper, stackName);\n if (!stack) {\n return undefined;\n }\n\n const status = stack.stackStatus;\n\n if (status.isCreationFailure) {\n throw new ToolkitError(\n `The stack named ${stackName} failed creation, it may need to be manually deleted from the AWS console: ${status}`,\n );\n } else if (!status.isDeploySuccess) {\n throw new ToolkitError(`The stack named ${stackName} failed to deploy: ${status}`);\n }\n\n return stack;\n}\n\n/**\n * Wait for a stack to become stable (no longer _IN_PROGRESS), returning it\n */\nexport async function stabilizeStack(\n cfn: ICloudFormationClient,\n ioHelper: IoHelper,\n stackName: string,\n) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(format('Waiting for stack %s to finish creating or updating...', stackName)));\n return waitFor(async () => {\n const stack = await CloudFormationStack.lookup(cfn, stackName);\n if (!stack.exists) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(format('Stack %s does not exist', stackName)));\n return null;\n }\n const status = stack.stackStatus;\n if (status.isInProgress) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(format('Stack %s has an ongoing operation in progress and is not stable (%s)', stackName, status)));\n return undefined;\n } else if (status.isReviewInProgress) {\n // This may happen if a stack creation operation is interrupted before the ChangeSet execution starts. Recovering\n // from this would requiring manual intervention (deleting or executing the pending ChangeSet), and failing to do\n // so will result in an endless wait here (the ChangeSet wont delete or execute itself). Instead of blocking\n // \"forever\" we proceed as if the stack was existing and stable. If there is a concurrent operation that just\n // hasn't finished proceeding just yet, either this operation or the concurrent one may fail due to the other one\n // having made progress. Which is fine. I guess.\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(format('Stack %s is in REVIEW_IN_PROGRESS state. Considering this is a stable status (%s)', stackName, status)));\n }\n\n return stack;\n });\n}\n\n/**\n * The set of (formal) parameters that have been declared in a template\n */\nexport class TemplateParameters {\n public static fromTemplate(template: Template) {\n return new TemplateParameters(template.Parameters || {});\n }\n\n constructor(private readonly params: Record<string, TemplateParameter>) {\n }\n\n /**\n * Calculate stack parameters to pass from the given desired parameter values\n *\n * Will throw if parameters without a Default value or a Previous value are not\n * supplied.\n */\n public supplyAll(updates: Record<string, string | undefined>): ParameterValues {\n return new ParameterValues(this.params, updates);\n }\n\n /**\n * From the template, the given desired values and the current values, calculate the changes to the stack parameters\n *\n * Will take into account parameters already set on the template (will emit\n * 'UsePreviousValue: true' for those unless the value is changed), and will\n * throw if parameters without a Default value or a Previous value are not\n * supplied.\n */\n public updateExisting(\n updates: Record<string, string | undefined>,\n previousValues: Record<string, string>,\n ): ParameterValues {\n return new ParameterValues(this.params, updates, previousValues);\n }\n}\n\n/**\n * The set of parameters we're going to pass to a Stack\n */\nexport class ParameterValues {\n public readonly values: Record<string, string> = {};\n public readonly apiParameters: Parameter[] = [];\n\n constructor(\n private readonly formalParams: Record<string, TemplateParameter>,\n updates: Record<string, string | undefined>,\n previousValues: Record<string, string> = {},\n ) {\n const missingRequired = new Array<string>();\n\n for (const [key, formalParam] of Object.entries(this.formalParams)) {\n // Check updates first, then use the previous value (if available), then use\n // the default (if available).\n //\n // If we don't find a parameter value using any of these methods, then that's an error.\n const updatedValue = updates[key];\n if (updatedValue !== undefined) {\n this.values[key] = updatedValue;\n this.apiParameters.push({\n ParameterKey: key,\n ParameterValue: updates[key],\n });\n continue;\n }\n\n if (key in previousValues) {\n this.values[key] = previousValues[key];\n this.apiParameters.push({ ParameterKey: key, UsePreviousValue: true });\n continue;\n }\n\n if (formalParam.Default !== undefined) {\n this.values[key] = formalParam.Default;\n continue;\n }\n\n // Oh no\n missingRequired.push(key);\n }\n\n if (missingRequired.length > 0) {\n throw new ToolkitError(`The following CloudFormation Parameters are missing a value: ${missingRequired.join(', ')}`);\n }\n\n // Just append all supplied overrides that aren't really expected (this\n // will fail CFN but maybe people made typos that they want to be notified\n // of)\n const unknownParam = ([key, _]: [string, any]) => this.formalParams[key] === undefined;\n const hasValue = ([_, value]: [string, any]) => !!value;\n for (const [key, value] of Object.entries(updates).filter(unknownParam).filter(hasValue)) {\n this.values[key] = value!;\n this.apiParameters.push({ ParameterKey: key, ParameterValue: value });\n }\n }\n\n /**\n * Whether this set of parameter updates will change the actual stack values\n */\n public hasChanges(currentValues: Record<string, string>): ParameterChanges {\n // If any of the parameters are SSM parameters, deploying must always happen\n // because we can't predict what the values will be. We will allow some\n // parameters to opt out of this check by having a magic string in their description.\n if (\n Object.values(this.formalParams).some(\n (p) => p.Type.startsWith('AWS::SSM::Parameter::') && !p.Description?.includes(SSMPARAM_NO_INVALIDATE),\n )\n ) {\n return 'ssm';\n }\n\n // Otherwise we're dirty if:\n // - any of the existing values are removed, or changed\n if (Object.entries(currentValues).some(([key, value]) => !(key in this.values) || value !== this.values[key])) {\n return true;\n }\n\n // - any of the values we're setting are new\n if (Object.keys(this.values).some((key) => !(key in currentValues))) {\n return true;\n }\n\n return false;\n }\n}\n\nexport type ParameterChanges = boolean | 'ssm';\n", "import { ArtifactMetadataEntryType, type MetadataEntry } from '@aws-cdk/cloud-assembly-schema';\nimport type { CloudFormationStackArtifact } from '@aws-cdk/cx-api';\n\n/**\n * Metadata entry for a resource within a CloudFormation stack\n */\nexport interface ResourceMetadata {\n /**\n * The resource's metadata as declared in the cloud assembly\n */\n readonly entry: MetadataEntry;\n /**\n * The construct path of the resource\n */\n readonly constructPath: string;\n}\n\n/**\n * Attempts to read metadata for resources from a CloudFormation stack artifact\n *\n * @param stack The CloudFormation stack to read from\n * @param logicalId The logical ID of the resource to read\n *\n * @returns The resource metadata, or undefined if the resource was not found\n */\nexport function resourceMetadata(stack: CloudFormationStackArtifact, logicalId: string): ResourceMetadata | undefined {\n const metadata = stack.manifest?.metadata;\n if (!metadata) {\n return undefined;\n }\n\n for (const path of Object.keys(metadata)) {\n const entry = metadata[path]\n .filter((e) => e.type === ArtifactMetadataEntryType.LOGICAL_ID)\n .find((e) => e.data === logicalId);\n if (entry) {\n return {\n entry,\n constructPath: simplifyConstructPath(path, stack.stackName),\n };\n }\n }\n return undefined;\n}\n\nfunction simplifyConstructPath(path: string, stackName: string) {\n path = path.replace(/\\/Resource$/, '');\n path = path.replace(/^\\//, ''); // remove \"/\" prefix\n\n // remove \"<stack-name>/\" prefix\n if (stackName) {\n if (path.startsWith(stackName + '/')) {\n path = path.slice(stackName.length + 1);\n }\n }\n return path;\n}\n", "import type { CloudFormationStackArtifact } from '@aws-cdk/cx-api';\nimport type { Export, ListExportsCommandOutput, StackResourceSummary } from '@aws-sdk/client-cloudformation';\nimport type { SDK } from '../aws-auth';\nimport { ToolkitError } from '../toolkit-error';\nimport type { NestedStackTemplates } from './nested-stack-helpers';\nimport type { Template } from './stack-helpers';\nimport type { ResourceMetadata } from '../resource-metadata';\nimport { resourceMetadata } from '../resource-metadata';\n\nexport interface ListStackResources {\n listStackResources(): Promise<StackResourceSummary[]>;\n}\n\nexport class LazyListStackResources implements ListStackResources {\n private stackResources: Promise<StackResourceSummary[]> | undefined;\n\n constructor(\n private readonly sdk: SDK,\n private readonly stackName: string,\n ) {\n }\n\n public async listStackResources(): Promise<StackResourceSummary[]> {\n if (this.stackResources === undefined) {\n this.stackResources = this.sdk.cloudFormation().listStackResources({\n StackName: this.stackName,\n });\n }\n return this.stackResources;\n }\n}\n\nexport interface LookupExport {\n lookupExport(name: string): Promise<Export | undefined>;\n}\n\nexport class LookupExportError extends Error {\n}\n\nexport class LazyLookupExport implements LookupExport {\n private cachedExports: { [name: string]: Export } = {};\n\n constructor(private readonly sdk: SDK) {\n }\n\n async lookupExport(name: string): Promise<Export | undefined> {\n if (this.cachedExports[name]) {\n return this.cachedExports[name];\n }\n\n for await (const cfnExport of this.listExports()) {\n if (!cfnExport.Name) {\n continue; // ignore any result that omits a name\n }\n this.cachedExports[cfnExport.Name] = cfnExport;\n\n if (cfnExport.Name === name) {\n return cfnExport;\n }\n }\n\n return undefined; // export not found\n }\n\n // TODO: Paginate\n private async *listExports() {\n let nextToken: string | undefined = undefined;\n while (true) {\n const response: ListExportsCommandOutput = await this.sdk.cloudFormation().listExports({ NextToken: nextToken });\n for (const cfnExport of response.Exports ?? []) {\n yield cfnExport;\n }\n\n if (!response.NextToken) {\n return;\n }\n nextToken = response.NextToken;\n }\n }\n}\n\nexport class CfnEvaluationException extends Error {\n}\n\nexport interface ResourceDefinition {\n readonly LogicalId: string;\n readonly Type: string;\n readonly Properties: { [p: string]: any };\n}\n\nexport interface EvaluateCloudFormationTemplateProps {\n readonly stackArtifact: CloudFormationStackArtifact;\n readonly stackName?: string;\n readonly template?: Template;\n readonly parameters: { [parameterName: string]: string };\n readonly account: string;\n readonly region: string;\n readonly partition: string;\n readonly sdk: SDK;\n readonly nestedStacks?: {\n [nestedStackLogicalId: string]: NestedStackTemplates;\n };\n}\n\nexport class EvaluateCloudFormationTemplate {\n public readonly stackArtifact: CloudFormationStackArtifact;\n private readonly stackName: string;\n private readonly template: Template;\n private readonly context: { [k: string]: any };\n private readonly account: string;\n private readonly region: string;\n private readonly partition: string;\n private readonly sdk: SDK;\n private readonly nestedStacks: {\n [nestedStackLogicalId: string]: NestedStackTemplates;\n };\n private readonly stackResources: ListStackResources;\n private readonly lookupExport: LookupExport;\n\n private cachedUrlSuffix: string | undefined;\n\n constructor(props: EvaluateCloudFormationTemplateProps) {\n this.stackArtifact = props.stackArtifact;\n this.stackName = props.stackName ?? props.stackArtifact.stackName;\n this.template = props.template ?? props.stackArtifact.template;\n this.context = {\n 'AWS::AccountId': props.account,\n 'AWS::Region': props.region,\n 'AWS::Partition': props.partition,\n ...props.parameters,\n };\n this.account = props.account;\n this.region = props.region;\n this.partition = props.partition;\n this.sdk = props.sdk;\n\n // We need names of nested stack so we can evaluate cross stack references\n this.nestedStacks = props.nestedStacks ?? {};\n\n // The current resources of the Stack.\n // We need them to figure out the physical name of a resource in case it wasn't specified by the user.\n // We fetch it lazily, to save a service call, in case all hotswapped resources have their physical names set.\n this.stackResources = new LazyListStackResources(this.sdk, this.stackName);\n\n // CloudFormation Exports lookup to be able to resolve Fn::ImportValue intrinsics in template\n this.lookupExport = new LazyLookupExport(this.sdk);\n }\n\n // clones current EvaluateCloudFormationTemplate object, but updates the stack name\n public async createNestedEvaluateCloudFormationTemplate(\n stackName: string,\n nestedTemplate: Template,\n nestedStackParameters: { [parameterName: string]: any },\n ) {\n const evaluatedParams = await this.evaluateCfnExpression(nestedStackParameters);\n return new EvaluateCloudFormationTemplate({\n stackArtifact: this.stackArtifact,\n stackName,\n template: nestedTemplate,\n parameters: evaluatedParams,\n account: this.account,\n region: this.region,\n partition: this.partition,\n sdk: this.sdk,\n nestedStacks: this.nestedStacks,\n });\n }\n\n public async establishResourcePhysicalName(\n logicalId: string,\n physicalNameInCfnTemplate: any,\n ): Promise<string | undefined> {\n if (physicalNameInCfnTemplate != null) {\n try {\n return await this.evaluateCfnExpression(physicalNameInCfnTemplate);\n } catch (e) {\n // If we can't evaluate the resource's name CloudFormation expression,\n // just look it up in the currently deployed Stack\n if (!(e instanceof CfnEvaluationException)) {\n throw e;\n }\n }\n }\n return this.findPhysicalNameFor(logicalId);\n }\n\n public async findPhysicalNameFor(logicalId: string): Promise<string | undefined> {\n const stackResources = await this.stackResources.listStackResources();\n return stackResources.find((sr) => sr.LogicalResourceId === logicalId)?.PhysicalResourceId;\n }\n\n public async findLogicalIdForPhysicalName(physicalName: string): Promise<string | undefined> {\n const stackResources = await this.stackResources.listStackResources();\n return stackResources.find((sr) => sr.PhysicalResourceId === physicalName)?.LogicalResourceId;\n }\n\n public findReferencesTo(logicalId: string): Array<ResourceDefinition> {\n const ret = new Array<ResourceDefinition>();\n for (const [resourceLogicalId, resourceDef] of Object.entries(this.template?.Resources ?? {})) {\n if (logicalId !== resourceLogicalId && this.references(logicalId, resourceDef)) {\n ret.push({\n ...(resourceDef as any),\n LogicalId: resourceLogicalId,\n });\n }\n }\n return ret;\n }\n\n public async evaluateCfnExpression(cfnExpression: any): Promise<any> {\n const self = this;\n /**\n * Evaluates CloudFormation intrinsic functions\n *\n * Note that supported intrinsic functions are documented in README.md -- please update\n * list of supported functions when adding new evaluations\n *\n * See: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference.html\n */\n class CfnIntrinsics {\n public evaluateIntrinsic(intrinsic: Intrinsic): any {\n const intrinsicFunc = (this as any)[intrinsic.name];\n if (!intrinsicFunc) {\n throw new CfnEvaluationException(`CloudFormation function ${intrinsic.name} is not supported`);\n }\n\n const argsAsArray = Array.isArray(intrinsic.args) ? intrinsic.args : [intrinsic.args];\n\n return intrinsicFunc.apply(this, argsAsArray);\n }\n\n async 'Fn::Join'(separator: string, args: any[]): Promise<string> {\n const evaluatedArgs = await self.evaluateCfnExpression(args);\n return evaluatedArgs.join(separator);\n }\n\n async 'Fn::Split'(separator: string, args: any): Promise<string> {\n const evaluatedArgs = await self.evaluateCfnExpression(args);\n return evaluatedArgs.split(separator);\n }\n\n async 'Fn::Select'(index: number, args: any[]): Promise<string> {\n const evaluatedArgs = await self.evaluateCfnExpression(args);\n return evaluatedArgs[index];\n }\n\n async Ref(logicalId: string): Promise<string> {\n const refTarget = await self.findRefTarget(logicalId);\n if (refTarget) {\n return refTarget;\n } else {\n throw new CfnEvaluationException(`Parameter or resource '${logicalId}' could not be found for evaluation`);\n }\n }\n\n async 'Fn::GetAtt'(logicalId: string, attributeName: string): Promise<string> {\n // ToDo handle the 'logicalId.attributeName' form of Fn::GetAtt\n const attrValue = await self.findGetAttTarget(logicalId, attributeName);\n if (attrValue) {\n return attrValue;\n } else {\n throw new CfnEvaluationException(\n `Attribute '${attributeName}' of resource '${logicalId}' could not be found for evaluation`,\n );\n }\n }\n\n async 'Fn::Sub'(template: string, explicitPlaceholders?: { [variable: string]: string }): Promise<string> {\n const placeholders = explicitPlaceholders ? await self.evaluateCfnExpression(explicitPlaceholders) : {};\n\n return asyncGlobalReplace(template, /\\${([^}]*)}/g, (key) => {\n if (key in placeholders) {\n return placeholders[key];\n } else {\n const splitKey = key.split('.');\n return splitKey.length === 1 ? this.Ref(key) : this['Fn::GetAtt'](splitKey[0], splitKey.slice(1).join('.'));\n }\n });\n }\n\n async 'Fn::ImportValue'(name: string): Promise<string> {\n const exported = await self.lookupExport.lookupExport(name);\n if (!exported) {\n throw new CfnEvaluationException(`Export '${name}' could not be found for evaluation`);\n }\n if (!exported.Value) {\n throw new CfnEvaluationException(`Export '${name}' exists without a value`);\n }\n return exported.Value;\n }\n }\n\n if (cfnExpression == null) {\n return cfnExpression;\n }\n\n if (Array.isArray(cfnExpression)) {\n // Small arrays in practice\n // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism\n return Promise.all(cfnExpression.map((expr) => this.evaluateCfnExpression(expr)));\n }\n\n if (typeof cfnExpression === 'object') {\n const intrinsic = this.parseIntrinsic(cfnExpression);\n if (intrinsic) {\n return new CfnIntrinsics().evaluateIntrinsic(intrinsic);\n } else {\n const ret: { [key: string]: any } = {};\n for (const [key, val] of Object.entries(cfnExpression)) {\n ret[key] = await this.evaluateCfnExpression(val);\n }\n return ret;\n }\n }\n\n return cfnExpression;\n }\n\n public getResourceProperty(logicalId: string, propertyName: string): any {\n return this.template.Resources?.[logicalId]?.Properties?.[propertyName];\n }\n\n public metadataFor(logicalId: string): ResourceMetadata | undefined {\n return resourceMetadata(this.stackArtifact, logicalId);\n }\n\n private references(logicalId: string, templateElement: any): boolean {\n if (typeof templateElement === 'string') {\n return logicalId === templateElement;\n }\n\n if (templateElement == null) {\n return false;\n }\n\n if (Array.isArray(templateElement)) {\n return templateElement.some((el) => this.references(logicalId, el));\n }\n\n if (typeof templateElement === 'object') {\n return Object.values(templateElement).some((el) => this.references(logicalId, el));\n }\n\n return false;\n }\n\n private parseIntrinsic(x: any): Intrinsic | undefined {\n const keys = Object.keys(x);\n if (keys.length === 1 && (keys[0].startsWith('Fn::') || keys[0] === 'Ref')) {\n return {\n name: keys[0],\n args: x[keys[0]],\n };\n }\n return undefined;\n }\n\n private async findRefTarget(logicalId: string): Promise<string | undefined> {\n // first, check to see if the Ref is a Parameter who's value we have\n if (logicalId === 'AWS::URLSuffix') {\n if (!this.cachedUrlSuffix) {\n this.cachedUrlSuffix = await this.sdk.getUrlSuffix(this.region);\n }\n\n return this.cachedUrlSuffix;\n }\n\n // Try finding the ref in the passed in parameters\n const parameterTarget = this.context[logicalId];\n if (parameterTarget) {\n return parameterTarget;\n }\n\n // If not in the passed in parameters, see if there is a default value in the template parameter that was not passed in\n const defaultParameterValue = this.template.Parameters?.[logicalId]?.Default;\n if (defaultParameterValue) {\n return defaultParameterValue;\n }\n\n // if it's not a Parameter, we need to search in the current Stack resources\n return this.findGetAttTarget(logicalId);\n }\n\n private async findGetAttTarget(logicalId: string, attribute?: string): Promise<string | undefined> {\n // Handle case where the attribute is referencing a stack output (used in nested stacks to share parameters)\n // See https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/quickref-cloudformation.html#w2ab1c17c23c19b5\n if (logicalId === 'Outputs' && attribute) {\n return this.evaluateCfnExpression(this.template.Outputs[attribute]?.Value);\n }\n\n const stackResources = await this.stackResources.listStackResources();\n const foundResource = stackResources.find((sr) => sr.LogicalResourceId === logicalId);\n if (!foundResource) {\n return undefined;\n }\n\n if (foundResource.ResourceType == 'AWS::CloudFormation::Stack' && attribute?.startsWith('Outputs.')) {\n const dependantStack = this.findNestedStack(logicalId, this.nestedStacks);\n if (!dependantStack || !dependantStack.physicalName) {\n // this is a newly created nested stack and cannot be hotswapped\n return undefined;\n }\n const evaluateCfnTemplate = await this.createNestedEvaluateCloudFormationTemplate(\n dependantStack.physicalName,\n dependantStack.generatedTemplate,\n dependantStack.generatedTemplate.Parameters!,\n );\n\n // Split Outputs.<refName> into 'Outputs' and '<refName>' and recursively call evaluate\n return evaluateCfnTemplate.evaluateCfnExpression({\n 'Fn::GetAtt': attribute.split(/\\.(.*)/s),\n });\n }\n // now, we need to format the appropriate identifier depending on the resource type,\n // and the requested attribute name\n return this.formatResourceAttribute(foundResource, attribute);\n }\n\n private findNestedStack(\n logicalId: string,\n nestedStacks: {\n [nestedStackLogicalId: string]: NestedStackTemplates;\n },\n ): NestedStackTemplates | undefined {\n for (const nestedStackLogicalId of Object.keys(nestedStacks)) {\n if (nestedStackLogicalId === logicalId) {\n return nestedStacks[nestedStackLogicalId];\n }\n const checkInNestedChildStacks = this.findNestedStack(\n logicalId,\n nestedStacks[nestedStackLogicalId].nestedStackTemplates,\n );\n if (checkInNestedChildStacks) return checkInNestedChildStacks;\n }\n return undefined;\n }\n\n private formatResourceAttribute(resource: StackResourceSummary, attribute: string | undefined): string | undefined {\n const physicalId = resource.PhysicalResourceId;\n\n // no attribute means Ref expression, for which we use the physical ID directly\n if (!attribute) {\n return physicalId;\n }\n\n const resourceTypeFormats = RESOURCE_TYPE_ATTRIBUTES_FORMATS[resource.ResourceType!];\n if (!resourceTypeFormats) {\n throw new CfnEvaluationException(\n `We don't support attributes of the '${resource.ResourceType}' resource. This is a CDK limitation. ` +\n 'Please report it at https://github.com/aws/aws-cdk/issues/new/choose',\n );\n }\n const attributeFmtFunc = resourceTypeFormats[attribute];\n if (!attributeFmtFunc) {\n throw new CfnEvaluationException(\n `We don't support the '${attribute}' attribute of the '${resource.ResourceType}' resource. This is a CDK limitation. ` +\n 'Please report it at https://github.com/aws/aws-cdk/issues/new/choose',\n );\n }\n const service = this.getServiceOfResource(resource);\n const resourceTypeArnPart = this.getResourceTypeArnPartOfResource(resource);\n return attributeFmtFunc({\n partition: this.partition,\n service,\n region: this.region,\n account: this.account,\n resourceType: resourceTypeArnPart,\n resourceName: physicalId!,\n });\n }\n\n private getServiceOfResource(resource: StackResourceSummary): string {\n return resource.ResourceType!.split('::')[1].toLowerCase();\n }\n\n private getResourceTypeArnPartOfResource(resource: StackResourceSummary): string {\n const resourceType = resource.ResourceType!;\n const specialCaseResourceType = RESOURCE_TYPE_SPECIAL_NAMES[resourceType]?.resourceType;\n return specialCaseResourceType\n ? specialCaseResourceType\n : // this is the default case\n resourceType.split('::')[2].toLowerCase();\n }\n}\n\ninterface ArnParts {\n readonly partition: string;\n readonly service: string;\n readonly region: string;\n readonly account: string;\n readonly resourceType: string;\n readonly resourceName: string;\n}\n\n/**\n * Usually, we deduce the names of the service and the resource type used to format the ARN from the CloudFormation resource type.\n * For a CFN type like AWS::Service::ResourceType, the second segment becomes the service name, and the third the resource type\n * (after converting both of them to lowercase).\n * However, some resource types break this simple convention, and we need to special-case them.\n * This map is for storing those cases.\n */\nconst RESOURCE_TYPE_SPECIAL_NAMES: {\n [type: string]: { resourceType: string };\n} = {\n 'AWS::Events::EventBus': {\n resourceType: 'event-bus',\n },\n};\n\nconst RESOURCE_TYPE_ATTRIBUTES_FORMATS: {\n [type: string]: { [attribute: string]: (parts: ArnParts) => string };\n} = {\n 'AWS::IAM::Role': { Arn: iamArnFmt },\n 'AWS::IAM::User': { Arn: iamArnFmt },\n 'AWS::IAM::Group': { Arn: iamArnFmt },\n 'AWS::S3::Bucket': { Arn: s3ArnFmt },\n 'AWS::Lambda::Function': { Arn: stdColonResourceArnFmt },\n 'AWS::Events::EventBus': {\n Arn: stdSlashResourceArnFmt,\n // the name attribute of the EventBus is the same as the Ref\n Name: (parts) => parts.resourceName,\n },\n 'AWS::DynamoDB::Table': { Arn: stdSlashResourceArnFmt },\n 'AWS::AppSync::GraphQLApi': { ApiId: appsyncGraphQlApiApiIdFmt },\n 'AWS::AppSync::FunctionConfiguration': {\n FunctionId: appsyncGraphQlFunctionIDFmt,\n },\n 'AWS::AppSync::DataSource': { Name: appsyncGraphQlDataSourceNameFmt },\n 'AWS::KMS::Key': { Arn: stdSlashResourceArnFmt },\n};\n\nfunction iamArnFmt(parts: ArnParts): string {\n // we skip region for IAM resources\n return `arn:${parts.partition}:${parts.service}::${parts.account}:${parts.resourceType}/${parts.resourceName}`;\n}\n\nfunction s3ArnFmt(parts: ArnParts): string {\n // we skip account, region and resourceType for S3 resources\n return `arn:${parts.partition}:${parts.service}:::${parts.resourceName}`;\n}\n\nfunction stdColonResourceArnFmt(parts: ArnParts): string {\n // this is a standard format for ARNs like: arn:aws:service:region:account:resourceType:resourceName\n return `arn:${parts.partition}:${parts.service}:${parts.region}:${parts.account}:${parts.resourceType}:${parts.resourceName}`;\n}\n\nfunction stdSlashResourceArnFmt(parts: ArnParts): string {\n // this is a standard format for ARNs like: arn:aws:service:region:account:resourceType/resourceName\n return `arn:${parts.partition}:${parts.service}:${parts.region}:${parts.account}:${parts.resourceType}/${parts.resourceName}`;\n}\n\nfunction appsyncGraphQlApiApiIdFmt(parts: ArnParts): string {\n // arn:aws:appsync:us-east-1:111111111111:apis/<apiId>\n return parts.resourceName.split('/')[1];\n}\n\nfunction appsyncGraphQlFunctionIDFmt(parts: ArnParts): string {\n // arn:aws:appsync:us-east-1:111111111111:apis/<apiId>/functions/<functionId>\n return parts.resourceName.split('/')[3];\n}\n\nfunction appsyncGraphQlDataSourceNameFmt(parts: ArnParts): string {\n // arn:aws:appsync:us-east-1:111111111111:apis/<apiId>/datasources/<name>\n return parts.resourceName.split('/')[3];\n}\n\ninterface Intrinsic {\n readonly name: string;\n readonly args: any;\n}\n\nasync function asyncGlobalReplace(str: string, regex: RegExp, cb: (x: string) => Promise<string>): Promise<string> {\n if (!regex.global) {\n throw new ToolkitError('Regex must be created with /g flag');\n }\n\n const ret = new Array<string>();\n let start = 0;\n while (true) {\n const match = regex.exec(str);\n if (!match) {\n break;\n }\n\n ret.push(str.substring(start, match.index));\n ret.push(await cb(match[1]));\n\n start = regex.lastIndex;\n }\n ret.push(str.slice(start));\n\n return ret.join('');\n}\n", "import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport * as util from 'node:util';\nimport { type CloudFormationStackArtifact, type Environment, EnvironmentPlaceholders } from '@aws-cdk/cx-api';\nimport { HeadObjectCommand, S3Client } from '@aws-sdk/client-s3';\nimport { getEndpointFromInstructions } from '@smithy/middleware-endpoint';\nimport * as chalk from 'chalk';\nimport { contentHash, toYAML } from '../../util';\nimport type { AssetManifestBuilder } from '../deployments';\nimport type { EnvironmentResources } from '../environment';\nimport { IO, type IoHelper } from '../io/private';\nimport { ToolkitError } from '../toolkit-error';\n\nexport type TemplateBodyParameter = {\n TemplateBody?: string;\n TemplateURL?: string;\n};\n\nconst LARGE_TEMPLATE_SIZE_KB = 50;\n\n/**\n * Prepares the body parameter for +CreateChangeSet+.\n *\n * If the template is small enough to be inlined into the API call, just return\n * it immediately.\n *\n * Otherwise, add it to the asset manifest to get uploaded to the staging\n * bucket and return its coordinates. If there is no staging bucket, an error\n * is thrown.\n *\n * @param stack the synthesized stack that provides the CloudFormation template\n * @param toolkitInfo information about the toolkit stack\n */\nexport async function makeBodyParameter(\n ioHelper: IoHelper,\n stack: CloudFormationStackArtifact,\n resolvedEnvironment: Environment,\n assetManifest: AssetManifestBuilder,\n resources: EnvironmentResources,\n overrideTemplate?: any,\n): Promise<TemplateBodyParameter> {\n // If the template has already been uploaded to S3, just use it from there.\n if (stack.stackTemplateAssetObjectUrl && !overrideTemplate) {\n return {\n TemplateURL: await restUrlFromManifest(stack.stackTemplateAssetObjectUrl, resolvedEnvironment),\n };\n }\n\n // Otherwise, pass via API call (if small) or upload here (if large)\n const templateJson = toYAML(overrideTemplate ?? stack.template);\n\n if (templateJson.length <= LARGE_TEMPLATE_SIZE_KB * 1024) {\n return { TemplateBody: templateJson };\n }\n\n const toolkitInfo = await resources.lookupToolkit();\n if (!toolkitInfo.found) {\n await ioHelper.notify(\n IO.DEFAULT_TOOLKIT_ERROR.msg(util.format(\n `The template for stack \"${stack.displayName}\" is ${Math.round(templateJson.length / 1024)}KiB. ` +\n `Templates larger than ${LARGE_TEMPLATE_SIZE_KB}KiB must be uploaded to S3.\\n` +\n 'Run the following command in order to setup an S3 bucket in this environment, and then re-deploy:\\n\\n',\n chalk.blue(`\\t$ cdk bootstrap ${resolvedEnvironment.name}\\n`),\n )),\n );\n\n throw new ToolkitError('Template too large to deploy (\"cdk bootstrap\" is required)');\n }\n\n const templateHash = contentHash(templateJson);\n const key = `cdk/${stack.id}/${templateHash}.yml`;\n\n let templateFile = stack.templateFile;\n if (overrideTemplate) {\n // Add a variant of this template\n templateFile = `${stack.templateFile}-${templateHash}.yaml`;\n const templateFilePath = path.join(stack.assembly.directory, templateFile);\n await fs.writeFile(templateFilePath, templateJson, { encoding: 'utf-8' });\n }\n\n assetManifest.addFileAsset(\n templateHash,\n {\n path: templateFile,\n },\n {\n bucketName: toolkitInfo.bucketName,\n objectKey: key,\n },\n );\n\n const templateURL = `${toolkitInfo.bucketUrl}/${key}`;\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Storing template in S3 at: ${templateURL}`));\n return { TemplateURL: templateURL };\n}\n\n/**\n * Format an S3 URL in the manifest for use with CloudFormation\n *\n * Replaces environment placeholders (which this field may contain),\n * and reformats s3://.../... urls into S3 REST URLs (which CloudFormation\n * expects)\n */\nasync function restUrlFromManifest(url: string, environment: Environment): Promise<string> {\n const doNotUseMarker = '**DONOTUSE**';\n const region = environment.region;\n // This URL may contain placeholders, so still substitute those.\n url = EnvironmentPlaceholders.replace(url, {\n accountId: environment.account,\n region,\n partition: doNotUseMarker,\n });\n\n // Yes, this is extremely crude, but we don't actually need this so I'm not inclined to spend\n // a lot of effort trying to thread the right value to this location.\n if (url.indexOf(doNotUseMarker) > -1) {\n throw new ToolkitError(\"Cannot use '${AWS::Partition}' in the 'stackTemplateAssetObjectUrl' field\");\n }\n\n const s3Url = url.match(/s3:\\/\\/([^/]+)\\/(.*)$/);\n if (!s3Url) {\n return url;\n }\n\n // We need to pass an 'https://s3.REGION.amazonaws.com[.cn]/bucket/object' URL to CloudFormation, but we\n // got an 's3://bucket/object' URL instead. Construct the rest API URL here.\n const bucketName = s3Url[1];\n const objectKey = s3Url[2];\n\n // SDK v3 no longer allows for getting endpoints from only region.\n // A command and client config must now be provided.\n const s3 = new S3Client({ region });\n const endpoint = await getEndpointFromInstructions({}, HeadObjectCommand, {\n ...s3.config,\n });\n endpoint.url.hostname;\n\n return `${endpoint.url.origin}/${bucketName}/${objectKey}`;\n}\n", "import * as path from 'path';\nimport type { CloudFormationStackArtifact } from '@aws-cdk/cx-api';\nimport * as fs from 'fs-extra';\nimport { formatErrorMessage } from '../../util';\nimport type { SDK } from '../aws-auth';\nimport { LazyListStackResources, type ListStackResources } from './evaluate-cloudformation-template';\nimport { CloudFormationStack, type Template } from './stack-helpers';\n\nexport interface RootTemplateWithNestedStacks {\n readonly deployedRootTemplate: Template;\n readonly nestedStacks: {\n [nestedStackLogicalId: string]: NestedStackTemplates;\n };\n}\n\n/**\n * Reads the currently deployed template and all of its nested stack templates from CloudFormation.\n */\nexport async function loadCurrentTemplateWithNestedStacks(\n rootStackArtifact: CloudFormationStackArtifact,\n sdk: SDK,\n retrieveProcessedTemplate: boolean = false,\n): Promise<RootTemplateWithNestedStacks> {\n const deployedRootTemplate = await loadCurrentTemplate(rootStackArtifact, sdk, retrieveProcessedTemplate);\n const nestedStacks = await loadNestedStacks(rootStackArtifact, sdk, {\n generatedTemplate: rootStackArtifact.template,\n deployedTemplate: deployedRootTemplate,\n deployedStackName: rootStackArtifact.stackName,\n });\n\n return {\n deployedRootTemplate,\n nestedStacks,\n };\n}\n\n/**\n * Returns the currently deployed template from CloudFormation that corresponds to `stackArtifact`.\n */\nexport async function loadCurrentTemplate(\n stackArtifact: CloudFormationStackArtifact,\n sdk: SDK,\n retrieveProcessedTemplate: boolean = false,\n): Promise<Template> {\n return loadCurrentStackTemplate(stackArtifact.stackName, sdk, retrieveProcessedTemplate);\n}\n\nasync function loadCurrentStackTemplate(\n stackName: string,\n sdk: SDK,\n retrieveProcessedTemplate: boolean = false,\n): Promise<Template> {\n const cfn = sdk.cloudFormation();\n const stack = await CloudFormationStack.lookup(cfn, stackName, retrieveProcessedTemplate);\n return stack.template();\n}\n\nasync function loadNestedStacks(\n rootStackArtifact: CloudFormationStackArtifact,\n sdk: SDK,\n parentTemplates: StackTemplates,\n): Promise<{ [nestedStackLogicalId: string]: NestedStackTemplates }> {\n const listStackResources = parentTemplates.deployedStackName\n ? new LazyListStackResources(sdk, parentTemplates.deployedStackName)\n : undefined;\n const nestedStacks: { [nestedStackLogicalId: string]: NestedStackTemplates } = {};\n for (const [nestedStackLogicalId, generatedNestedStackResource] of Object.entries(\n parentTemplates.generatedTemplate.Resources ?? {},\n )) {\n if (!isCdkManagedNestedStack(generatedNestedStackResource)) {\n continue;\n }\n\n const assetPath = generatedNestedStackResource.Metadata['aws:asset:path'];\n const nestedStackTemplates = await getNestedStackTemplates(\n rootStackArtifact,\n assetPath,\n nestedStackLogicalId,\n listStackResources,\n sdk,\n );\n\n nestedStacks[nestedStackLogicalId] = {\n deployedTemplate: nestedStackTemplates.deployedTemplate,\n generatedTemplate: nestedStackTemplates.generatedTemplate,\n physicalName: nestedStackTemplates.deployedStackName,\n nestedStackTemplates: await loadNestedStacks(rootStackArtifact, sdk, nestedStackTemplates),\n };\n }\n\n return nestedStacks;\n}\n\nasync function getNestedStackTemplates(\n rootStackArtifact: CloudFormationStackArtifact,\n nestedTemplateAssetPath: string,\n nestedStackLogicalId: string,\n listStackResources: ListStackResources | undefined,\n sdk: SDK,\n): Promise<StackTemplates> {\n const nestedTemplatePath = path.join(rootStackArtifact.assembly.directory, nestedTemplateAssetPath);\n\n // CFN generates the nested stack name in the form `ParentStackName-NestedStackLogicalID-SomeHashWeCan'tCompute,\n // the arn is of the form: arn:aws:cloudformation:region:123456789012:stack/NestedStackName/AnotherHashWeDon'tNeed\n // so we get the ARN and manually extract the name.\n const nestedStackArn = await getNestedStackArn(nestedStackLogicalId, listStackResources);\n const deployedStackName = nestedStackArn?.slice(nestedStackArn.indexOf('/') + 1, nestedStackArn.lastIndexOf('/'));\n\n return {\n generatedTemplate: JSON.parse(fs.readFileSync(nestedTemplatePath, 'utf-8')),\n deployedTemplate: deployedStackName ? await loadCurrentStackTemplate(deployedStackName, sdk) : {},\n deployedStackName,\n };\n}\n\nasync function getNestedStackArn(\n nestedStackLogicalId: string,\n listStackResources?: ListStackResources,\n): Promise<string | undefined> {\n try {\n const stackResources = await listStackResources?.listStackResources();\n return stackResources?.find((sr) => sr.LogicalResourceId === nestedStackLogicalId)?.PhysicalResourceId;\n } catch (e: any) {\n if (formatErrorMessage(e).startsWith('Stack with id ') && formatErrorMessage(e).endsWith(' does not exist')) {\n return;\n }\n throw e;\n }\n}\n\nfunction isCdkManagedNestedStack(stackResource: any): stackResource is NestedStackResource {\n return (\n stackResource.Type === 'AWS::CloudFormation::Stack' &&\n stackResource.Metadata &&\n stackResource.Metadata['aws:asset:path']\n );\n}\n\nexport interface NestedStackTemplates {\n readonly physicalName: string | undefined;\n readonly deployedTemplate: Template;\n readonly generatedTemplate: Template;\n readonly nestedStackTemplates: {\n [nestedStackLogicalId: string]: NestedStackTemplates;\n };\n}\n\ninterface StackTemplates {\n readonly generatedTemplate: any;\n readonly deployedTemplate: any;\n readonly deployedStackName: string | undefined;\n}\n\ninterface NestedStackResource {\n readonly Metadata: { 'aws:asset:path': string };\n readonly Properties: any;\n}\n", "import * as util from 'util';\nimport type { CloudFormationStackArtifact } from '@aws-cdk/cx-api';\nimport type { StackActivity } from '@aws-cdk/tmp-toolkit-helpers';\nimport * as uuid from 'uuid';\nimport { StackEventPoller } from './stack-event-poller';\nimport { StackProgressMonitor } from './stack-progress-monitor';\nimport { stackEventHasErrorMessage } from '../../util';\nimport type { ICloudFormationClient } from '../aws-auth';\nimport { IO, type IoHelper } from '../io/private';\nimport { resourceMetadata } from '../resource-metadata/resource-metadata';\n\nexport interface StackActivityMonitorProps {\n /**\n * The CloudFormation client\n */\n readonly cfn: ICloudFormationClient;\n\n /**\n * The IoHelper used for messaging\n */\n readonly ioHelper: IoHelper;\n\n /**\n * The stack artifact that is getting deployed\n */\n readonly stack: CloudFormationStackArtifact;\n\n /**\n * The name of the Stack that is getting deployed\n */\n readonly stackName: string;\n\n /**\n * Total number of resources to update\n *\n * Used to calculate a progress bar.\n *\n * @default - No progress reporting.\n */\n readonly resourcesTotal?: number;\n\n /**\n * Creation time of the change set\n *\n * This will be used to filter events, only showing those from after the change\n * set creation time.\n *\n * It is recommended to use this, otherwise the filtering will be subject\n * to clock drift between local and cloud machines.\n *\n * @default - local machine's current time\n */\n readonly changeSetCreationTime?: Date;\n\n /**\n * Time to wait between fetching new activities.\n *\n * Must wait a reasonable amount of time between polls, since we need to consider CloudFormation API limits\n *\n * @default 2_000\n */\n readonly pollingInterval?: number;\n}\n\nexport class StackActivityMonitor {\n /**\n * The poller used to read stack events\n */\n private readonly poller: StackEventPoller;\n\n /**\n * Fetch new activity every 1 second\n * Printers can decide to update a view less frequently if desired\n */\n private readonly pollingInterval: number;\n\n public readonly errors: string[] = [];\n\n private monitorId?: string;\n\n private readonly progressMonitor: StackProgressMonitor;\n\n /**\n * Current tick timer\n */\n private tickTimer?: ReturnType<typeof setTimeout>;\n\n /**\n * Set to the activity of reading the current events\n */\n private readPromise?: Promise<any>;\n\n private readonly ioHelper: IoHelper;\n private readonly stackName: string;\n private readonly stack: CloudFormationStackArtifact;\n\n constructor({\n cfn,\n ioHelper,\n stack,\n stackName,\n resourcesTotal,\n changeSetCreationTime,\n pollingInterval = 2_000,\n }: StackActivityMonitorProps) {\n this.ioHelper = ioHelper;\n this.stack = stack;\n this.stackName = stackName;\n\n this.progressMonitor = new StackProgressMonitor(resourcesTotal);\n this.pollingInterval = pollingInterval;\n this.poller = new StackEventPoller(cfn, {\n stackName,\n startTime: changeSetCreationTime?.getTime() ?? Date.now(),\n });\n }\n\n public async start() {\n this.monitorId = uuid.v4();\n await this.ioHelper.notify(IO.CDK_TOOLKIT_I5501.msg(`Deploying ${this.stackName}`, {\n deployment: this.monitorId,\n stack: this.stack,\n stackName: this.stackName,\n resourcesTotal: this.progressMonitor.total,\n }));\n this.scheduleNextTick();\n return this;\n }\n\n public async stop() {\n const oldMonitorId = this.monitorId!;\n this.monitorId = undefined;\n if (this.tickTimer) {\n clearTimeout(this.tickTimer);\n }\n\n // Do a final poll for all events. This is to handle the situation where DescribeStackStatus\n // already returned an error, but the monitor hasn't seen all the events yet and we'd end\n // up not printing the failure reason to users.\n await this.finalPollToEnd(oldMonitorId);\n\n await this.ioHelper.notify(IO.CDK_TOOLKIT_I5503.msg(`Completed ${this.stackName}`, {\n deployment: oldMonitorId,\n stack: this.stack,\n stackName: this.stackName,\n resourcesTotal: this.progressMonitor.total,\n }));\n }\n\n private scheduleNextTick() {\n if (!this.monitorId) {\n return;\n }\n\n this.tickTimer = setTimeout(() => void this.tick(), this.pollingInterval);\n }\n\n private async tick() {\n if (!this.monitorId) {\n return;\n }\n\n try {\n this.readPromise = this.readNewEvents(this.monitorId);\n await this.readPromise;\n this.readPromise = undefined;\n\n // We might have been stop()ped while the network call was in progress.\n if (!this.monitorId) {\n return;\n }\n } catch (e) {\n await this.ioHelper.notify(IO.CDK_TOOLKIT_E5500.msg(\n util.format('Error occurred while monitoring stack: %s', e),\n { error: e as any },\n ));\n }\n this.scheduleNextTick();\n }\n\n private findMetadataFor(logicalId: string | undefined) {\n const metadata = this.stack.manifest?.metadata;\n if (!logicalId || !metadata) {\n return undefined;\n }\n return resourceMetadata(this.stack, logicalId);\n }\n\n /**\n * Reads all new events from the stack history\n *\n * The events are returned in reverse chronological order; we continue to the next page if we\n * see a next page and the last event in the page is new to us (and within the time window).\n * haven't seen the final event\n */\n private async readNewEvents(monitorId: string): Promise<void> {\n const pollEvents = await this.poller.poll();\n\n for (const resourceEvent of pollEvents) {\n this.progressMonitor.process(resourceEvent.event);\n\n const activity: StackActivity = {\n deployment: monitorId,\n event: resourceEvent.event,\n metadata: this.findMetadataFor(resourceEvent.event.LogicalResourceId),\n progress: this.progressMonitor.progress,\n };\n\n this.checkForErrors(activity);\n await this.ioHelper.notify(IO.CDK_TOOLKIT_I5502.msg(this.formatActivity(activity, true), activity));\n }\n }\n\n /**\n * Perform a final poll to the end and flush out all events to the printer\n *\n * Finish any poll currently in progress, then do a final one until we've\n * reached the last page.\n */\n private async finalPollToEnd(monitorId: string) {\n // If we were doing a poll, finish that first. It was started before\n // the moment we were sure we weren't going to get any new events anymore\n // so we need to do a new one anyway. Need to wait for this one though\n // because our state is single-threaded.\n if (this.readPromise) {\n await this.readPromise;\n }\n\n await this.readNewEvents(monitorId);\n }\n\n /**\n * Formats a stack activity into a basic string\n */\n private formatActivity(activity: StackActivity, progress: boolean): string {\n const event = activity.event;\n const metadata = activity.metadata;\n\n const resourceName = metadata ? metadata.constructPath : event.LogicalResourceId || '';\n const logicalId = resourceName !== event.LogicalResourceId ? `(${event.LogicalResourceId}) ` : '';\n\n return util.format(\n '%s | %s%s | %s | %s | %s %s%s%s',\n event.StackName,\n progress !== false ? `${activity.progress.formatted} | ` : '',\n new Date(event.Timestamp!).toLocaleTimeString(),\n event.ResourceStatus || '',\n event.ResourceType,\n resourceName,\n logicalId,\n event.ResourceStatusReason ? event.ResourceStatusReason : '',\n metadata?.entry.trace ? `\\n\\t${metadata.entry.trace.join('\\n\\t\\\\_ ')}` : '',\n );\n }\n\n private checkForErrors(activity: StackActivity) {\n if (stackEventHasErrorMessage(activity.event.ResourceStatus ?? '')) {\n const isCancelled = (activity.event.ResourceStatusReason ?? '').indexOf('cancelled') > -1;\n\n // Cancelled is not an interesting failure reason, nor is the stack message (stack\n // message will just say something like \"stack failed to update\")\n if (!isCancelled && activity.event.StackName !== activity.event.LogicalResourceId) {\n this.errors.push(activity.event.ResourceStatusReason ?? '');\n }\n }\n }\n}\n", "import type { StackEvent } from '@aws-sdk/client-cloudformation';\nimport { formatErrorMessage } from '../../util';\nimport type { ICloudFormationClient } from '../aws-auth';\n\nexport interface StackEventPollerProps {\n /**\n * The stack to poll\n */\n readonly stackName: string;\n\n /**\n * IDs of parent stacks of this resource, in case of resources in nested stacks\n */\n readonly parentStackLogicalIds?: string[];\n\n /**\n * Timestamp for the oldest event we're interested in\n *\n * @default - Read all events\n */\n readonly startTime?: number;\n\n /**\n * Stop reading when we see the stack entering this status\n *\n * Should be something like `CREATE_IN_PROGRESS`, `UPDATE_IN_PROGRESS`,\n * `DELETE_IN_PROGRESS, `ROLLBACK_IN_PROGRESS`.\n *\n * @default - Read all events\n */\n readonly stackStatuses?: string[];\n}\n\nexport interface ResourceEvent {\n /**\n * The Stack Event as received from CloudFormation\n */\n readonly event: StackEvent;\n\n /**\n * IDs of parent stacks of the resource, in case of resources in nested stacks\n */\n readonly parentStackLogicalIds: string[];\n\n /**\n * Whether this event regards the root stack\n *\n * @default false\n */\n readonly isStackEvent?: boolean;\n}\n\nexport class StackEventPoller {\n public readonly events: ResourceEvent[] = [];\n public complete: boolean = false;\n\n private readonly eventIds = new Set<string>();\n private readonly nestedStackPollers: Record<string, StackEventPoller> = {};\n\n constructor(\n private readonly cfn: ICloudFormationClient,\n private readonly props: StackEventPollerProps,\n ) {\n }\n\n /**\n * From all accumulated events, return only the errors\n */\n public get resourceErrors(): ResourceEvent[] {\n return this.events.filter((e) => e.event.ResourceStatus?.endsWith('_FAILED') && !e.isStackEvent);\n }\n\n /**\n * Poll for new stack events\n *\n * Will not return events older than events indicated by the constructor filters.\n *\n * Recurses into nested stacks, and returns events old-to-new.\n */\n public async poll(): Promise<ResourceEvent[]> {\n const events: ResourceEvent[] = await this.doPoll();\n\n // Also poll all nested stacks we're currently tracking\n for (const [logicalId, poller] of Object.entries(this.nestedStackPollers)) {\n events.push(...(await poller.poll()));\n if (poller.complete) {\n delete this.nestedStackPollers[logicalId];\n }\n }\n\n // Return what we have so far\n events.sort((a, b) => a.event.Timestamp!.valueOf() - b.event.Timestamp!.valueOf());\n this.events.push(...events);\n return events;\n }\n\n private async doPoll(): Promise<ResourceEvent[]> {\n const events: ResourceEvent[] = [];\n try {\n let nextToken: string | undefined;\n let finished = false;\n\n while (!finished) {\n const page = await this.cfn.describeStackEvents({ StackName: this.props.stackName, NextToken: nextToken });\n for (const event of page?.StackEvents ?? []) {\n // Event from before we were interested in 'em\n if (this.props.startTime !== undefined && event.Timestamp!.valueOf() < this.props.startTime) {\n return events;\n }\n\n // Already seen this one\n if (this.eventIds.has(event.EventId!)) {\n return events;\n }\n this.eventIds.add(event.EventId!);\n\n // The events for the stack itself are also included next to events about resources; we can test for them in this way.\n const isParentStackEvent = event.PhysicalResourceId === event.StackId;\n\n if (isParentStackEvent && this.props.stackStatuses?.includes(event.ResourceStatus ?? '')) {\n return events;\n }\n\n // Fresh event\n const resEvent: ResourceEvent = {\n event: event,\n parentStackLogicalIds: this.props.parentStackLogicalIds ?? [],\n isStackEvent: isParentStackEvent,\n };\n events.push(resEvent);\n\n if (\n !isParentStackEvent &&\n event.ResourceType === 'AWS::CloudFormation::Stack' &&\n isStackBeginOperationState(event.ResourceStatus)\n ) {\n // If the event is not for `this` stack and has a physical resource Id, recursively call for events in the nested stack\n this.trackNestedStack(event, [...(this.props.parentStackLogicalIds ?? []), event.LogicalResourceId ?? '']);\n }\n\n if (isParentStackEvent && isStackTerminalState(event.ResourceStatus)) {\n this.complete = true;\n }\n }\n\n nextToken = page?.NextToken;\n if (nextToken === undefined) {\n finished = true;\n }\n }\n } catch (e: any) {\n if (!(e.name === 'ValidationError' && formatErrorMessage(e) === `Stack [${this.props.stackName}] does not exist`)) {\n throw e;\n }\n }\n\n return events;\n }\n\n /**\n * On the CREATE_IN_PROGRESS, UPDATE_IN_PROGRESS, DELETE_IN_PROGRESS event of a nested stack, poll the nested stack updates\n */\n private trackNestedStack(event: StackEvent, parentStackLogicalIds: string[]) {\n const logicalId = event.LogicalResourceId;\n const physicalResourceId = event.PhysicalResourceId;\n\n // The CREATE_IN_PROGRESS event for a Nested Stack is emitted twice; first without a PhysicalResourceId\n // and then with. Ignore this event if we don't have that property yet.\n //\n // (At this point, I also don't trust that logicalId is always going to be there so validate that as well)\n if (!logicalId || !physicalResourceId) {\n return;\n }\n\n if (!this.nestedStackPollers[logicalId]) {\n this.nestedStackPollers[logicalId] = new StackEventPoller(this.cfn, {\n stackName: physicalResourceId,\n parentStackLogicalIds: parentStackLogicalIds,\n startTime: event.Timestamp!.valueOf(),\n });\n }\n }\n}\n\nfunction isStackBeginOperationState(state: string | undefined) {\n return [\n 'CREATE_IN_PROGRESS',\n 'UPDATE_IN_PROGRESS',\n 'DELETE_IN_PROGRESS',\n 'UPDATE_ROLLBACK_IN_PROGRESS',\n 'ROLLBACK_IN_PROGRESS',\n ].includes(state ?? '');\n}\n\nfunction isStackTerminalState(state: string | undefined) {\n return !(state ?? '').endsWith('_IN_PROGRESS');\n}\n", "import * as util from 'util';\nimport type { StackProgress } from '@aws-cdk/tmp-toolkit-helpers';\nimport type { StackEvent } from '@aws-sdk/client-cloudformation';\nimport { padLeft } from '../../util';\n\n/**\n * Monitors stack progress.s\n */\nexport class StackProgressMonitor {\n /**\n * Previous completion state observed by logical ID\n *\n * We use this to detect that if we see a DELETE_COMPLETE after a\n * CREATE_COMPLETE, it's actually a rollback and we should DECREASE\n * resourcesDone instead of increase it\n */\n private resourcesPrevCompleteState: Record<string, string> = {};\n\n /**\n * Count of resources that have reported a _COMPLETE status\n */\n private resourcesDone: number = 0;\n\n /**\n * How many digits we need to represent the total count (for lining up the status reporting)\n */\n private readonly resourceDigits: number = 0;\n\n /**\n * Number of expected resources in the monitor.\n */\n private readonly resourcesTotal?: number;\n\n constructor(resourcesTotal?: number) {\n // +1 because the stack also emits a \"COMPLETE\" event at the end, and that wasn't\n // counted yet. This makes it line up with the amount of events we expect.\n this.resourcesTotal = resourcesTotal ? resourcesTotal + 1 : undefined;\n\n // How many digits does this number take to represent?\n this.resourceDigits = this.resourcesTotal ? Math.ceil(Math.log10(this.resourcesTotal)) : 0;\n }\n\n /**\n * Report the stack progress\n */\n public get progress(): StackProgress {\n return {\n total: this.total,\n completed: this.completed,\n formatted: this.formatted,\n };\n }\n\n /**\n * The total number of progress monitored resources.\n */\n public get total(): number | undefined {\n return this.resourcesTotal;\n }\n\n /**\n * The number of completed resources.\n */\n public get completed(): number {\n return this.resourcesDone;\n }\n\n /**\n * Report the current progress as a [34/42] string, or just [34] if the total is unknown\n */\n public get formatted(): string {\n if (this.resourcesTotal == null) {\n // Don't have total, show simple count and hope the human knows\n return padLeft(3, util.format('%s', this.resourcesDone)); // max 500 resources\n }\n\n return util.format(\n '%s/%s',\n padLeft(this.resourceDigits, this.resourcesDone.toString()),\n padLeft(this.resourceDigits, this.resourcesTotal.toString()),\n );\n }\n\n /**\n * Process as stack event and update the progress state.\n */\n public process(event: StackEvent): void {\n const status = event.ResourceStatus;\n if (!status || !event.LogicalResourceId) {\n return;\n }\n\n if (status.endsWith('_COMPLETE_CLEANUP_IN_PROGRESS')) {\n this.resourcesDone++;\n }\n\n if (status.endsWith('_COMPLETE')) {\n const prevState = this.resourcesPrevCompleteState[event.LogicalResourceId];\n if (!prevState) {\n this.resourcesDone++;\n } else {\n // If we completed this before and we're completing it AGAIN, means we're rolling back.\n // Protect against silly underflow.\n this.resourcesDone--;\n if (this.resourcesDone < 0) {\n this.resourcesDone = 0;\n }\n }\n this.resourcesPrevCompleteState[event.LogicalResourceId] = status;\n }\n }\n}\n", "import { type Stack, StackStatus as _StackStatus } from '@aws-sdk/client-cloudformation';\n\n/**\n * A utility class to inspect CloudFormation stack statuses.\n *\n * @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-describing-stacks.html\n */\nexport class StackStatus {\n public static fromStackDescription(description: Stack) {\n return new StackStatus(description.StackStatus!, description.StackStatusReason);\n }\n\n constructor(\n public readonly name: string,\n public readonly reason?: string,\n ) {\n }\n\n get isCreationFailure(): boolean {\n return this.name === _StackStatus.ROLLBACK_COMPLETE || this.name === _StackStatus.ROLLBACK_FAILED;\n }\n\n get isDeleted(): boolean {\n return this.name.startsWith('DELETE_');\n }\n\n get isFailure(): boolean {\n return this.name.endsWith('FAILED');\n }\n\n get isInProgress(): boolean {\n return this.name.endsWith('_IN_PROGRESS') && !this.isReviewInProgress;\n }\n\n get isReviewInProgress(): boolean {\n return this.name === _StackStatus.REVIEW_IN_PROGRESS;\n }\n\n get isNotFound(): boolean {\n return this.name === 'NOT_FOUND';\n }\n\n get isDeploySuccess(): boolean {\n return (\n !this.isNotFound &&\n (this.name === _StackStatus.CREATE_COMPLETE ||\n this.name === _StackStatus.UPDATE_COMPLETE ||\n this.name === _StackStatus.IMPORT_COMPLETE)\n );\n }\n\n get isRollbackSuccess(): boolean {\n return this.name === _StackStatus.ROLLBACK_COMPLETE || this.name === _StackStatus.UPDATE_ROLLBACK_COMPLETE;\n }\n\n /**\n * Whether the stack is in a paused state due to `--no-rollback`.\n *\n * The possible actions here are retrying a new `--no-rollback` deployment, or initiating a rollback.\n */\n get rollbackChoice(): RollbackChoice {\n switch (this.name) {\n case _StackStatus.CREATE_FAILED:\n case _StackStatus.UPDATE_FAILED:\n return RollbackChoice.START_ROLLBACK;\n case _StackStatus.UPDATE_ROLLBACK_FAILED:\n return RollbackChoice.CONTINUE_UPDATE_ROLLBACK;\n case _StackStatus.ROLLBACK_FAILED:\n // Unfortunately there is no option to continue a failed rollback without\n // a stable target state.\n return RollbackChoice.ROLLBACK_FAILED;\n default:\n return RollbackChoice.NONE;\n }\n }\n\n get isRollbackable(): boolean {\n return [RollbackChoice.START_ROLLBACK, RollbackChoice.CONTINUE_UPDATE_ROLLBACK].includes(this.rollbackChoice);\n }\n\n public toString(): string {\n return this.name + (this.reason ? ` (${this.reason})` : '');\n }\n}\n\n/**\n * Describe the current rollback options for this state\n */\nexport enum RollbackChoice {\n START_ROLLBACK,\n CONTINUE_UPDATE_ROLLBACK,\n /**\n * A sign that stack creation AND its rollback have failed.\n *\n * There is no way to recover from this, other than recreating the stack.\n */\n ROLLBACK_FAILED,\n NONE,\n}\n", "import type { Stack, Tag } from '@aws-sdk/client-cloudformation';\nimport { formatErrorMessage, deserializeStructure } from '../../util';\nimport type { ICloudFormationClient } from '../aws-auth';\nimport { StackStatus } from '../stack-events';\nimport { ToolkitError } from '../toolkit-error';\n\nexport interface Template {\n Parameters?: Record<string, TemplateParameter>;\n [section: string]: any;\n}\n\nexport interface TemplateParameter {\n Type: string;\n Default?: any;\n Description?: string;\n [key: string]: any;\n}\n\n/**\n * Represents an (existing) Stack in CloudFormation\n *\n * Bundle and cache some information that we need during deployment (so we don't have to make\n * repeated calls to CloudFormation).\n */\nexport class CloudFormationStack {\n public static async lookup(\n cfn: ICloudFormationClient,\n stackName: string,\n retrieveProcessedTemplate: boolean = false,\n ): Promise<CloudFormationStack> {\n try {\n const response = await cfn.describeStacks({ StackName: stackName });\n return new CloudFormationStack(cfn, stackName, response.Stacks && response.Stacks[0], retrieveProcessedTemplate);\n } catch (e: any) {\n if (e.name === 'ValidationError' && formatErrorMessage(e) === `Stack with id ${stackName} does not exist`) {\n return new CloudFormationStack(cfn, stackName, undefined);\n }\n throw e;\n }\n }\n\n /**\n * Return a copy of the given stack that does not exist\n *\n * It's a little silly that it needs arguments to do that, but there we go.\n */\n public static doesNotExist(cfn: ICloudFormationClient, stackName: string) {\n return new CloudFormationStack(cfn, stackName);\n }\n\n /**\n * From static information (for testing)\n */\n public static fromStaticInformation(cfn: ICloudFormationClient, stackName: string, stack: Stack) {\n return new CloudFormationStack(cfn, stackName, stack);\n }\n\n private _template: any;\n\n protected constructor(\n private readonly cfn: ICloudFormationClient,\n public readonly stackName: string,\n private readonly stack?: Stack,\n private readonly retrieveProcessedTemplate: boolean = false,\n ) {\n }\n\n /**\n * Retrieve the stack's deployed template\n *\n * Cached, so will only be retrieved once. Will return an empty\n * structure if the stack does not exist.\n */\n public async template(): Promise<Template> {\n if (!this.exists) {\n return {};\n }\n\n if (this._template === undefined) {\n const response = await this.cfn.getTemplate({\n StackName: this.stackName,\n TemplateStage: this.retrieveProcessedTemplate ? 'Processed' : 'Original',\n });\n this._template = (response.TemplateBody && deserializeStructure(response.TemplateBody)) || {};\n }\n return this._template;\n }\n\n /**\n * Whether the stack exists\n */\n public get exists() {\n return this.stack !== undefined;\n }\n\n /**\n * The stack's ID (which is the same as its ARN)\n *\n * Throws if the stack doesn't exist.\n */\n public get stackId() {\n this.assertExists();\n return this.stack!.StackId!;\n }\n\n /**\n * The stack's current outputs\n *\n * Empty object if the stack doesn't exist\n */\n public get outputs(): Record<string, string> {\n if (!this.exists) {\n return {};\n }\n const result: { [name: string]: string } = {};\n (this.stack!.Outputs || []).forEach((output) => {\n result[output.OutputKey!] = output.OutputValue!;\n });\n return result;\n }\n\n /**\n * The stack's status\n *\n * Special status NOT_FOUND if the stack does not exist.\n */\n public get stackStatus(): StackStatus {\n if (!this.exists) {\n return new StackStatus('NOT_FOUND', 'Stack not found during lookup');\n }\n return StackStatus.fromStackDescription(this.stack!);\n }\n\n /**\n * The stack's current tags\n *\n * Empty list if the stack does not exist\n */\n public get tags(): Tag[] {\n return this.stack?.Tags || [];\n }\n\n /**\n * SNS Topic ARNs that will receive stack events.\n *\n * Empty list if the stack does not exist\n */\n public get notificationArns(): string[] {\n return this.stack?.NotificationARNs ?? [];\n }\n\n /**\n * Return the names of all current parameters to the stack\n *\n * Empty list if the stack does not exist.\n */\n public get parameterNames(): string[] {\n return Object.keys(this.parameters);\n }\n\n /**\n * Return the names and values of all current parameters to the stack\n *\n * Empty object if the stack does not exist.\n */\n public get parameters(): Record<string, string> {\n if (!this.exists) {\n return {};\n }\n const ret: Record<string, string> = {};\n for (const param of this.stack!.Parameters ?? []) {\n ret[param.ParameterKey!] = param.ResolvedValue ?? param.ParameterValue!;\n }\n return ret;\n }\n\n /**\n * Return the termination protection of the stack\n */\n public get terminationProtection(): boolean | undefined {\n return this.stack?.EnableTerminationProtection;\n }\n\n private assertExists() {\n if (!this.exists) {\n throw new ToolkitError(`No stack named '${this.stackName}'`);\n }\n }\n}\n", "import type { SDK } from '../aws-auth';\nimport { IO, type IoHelper } from '../io/private';\nimport { ToolkitError } from '../toolkit-error';\n\nexport async function determineAllowCrossAccountAssetPublishing(\n sdk: SDK,\n ioHelper: IoHelper,\n customStackName?: string,\n): Promise<boolean> {\n try {\n const stackName = customStackName || 'CDKToolkit';\n const stackInfo = await getBootstrapStackInfo(sdk, stackName);\n\n if (!stackInfo.hasStagingBucket) {\n // indicates an intentional cross account setup\n return true;\n }\n\n if (stackInfo.bootstrapVersion >= 21) {\n // bootstrap stack version 21 contains a fix that will prevent cross\n // account publishing on the IAM level\n // https://github.com/aws/aws-cdk/pull/30823\n return true;\n }\n\n // If there is a staging bucket AND the bootstrap version is old, then we want to protect\n // against accidental cross-account publishing.\n return false;\n } catch (e) {\n // You would think we would need to fail closed here, but the reality is\n // that we get here if we couldn't find the bootstrap stack: that is\n // completely valid, and many large organizations may have their own method\n // of creating bootstrap resources. If they do, there's nothing for us to validate,\n // but we can't use that as a reason to disallow cross-account publishing. We'll just\n // have to trust they did their due diligence. So we fail open.\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Error determining cross account asset publishing: ${e}`));\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg('Defaulting to allowing cross account asset publishing'));\n return true;\n }\n}\n\ninterface BootstrapStackInfo {\n hasStagingBucket: boolean;\n bootstrapVersion: number;\n}\n\nexport async function getBootstrapStackInfo(sdk: SDK, stackName: string): Promise<BootstrapStackInfo> {\n try {\n const cfn = sdk.cloudFormation();\n const stackResponse = await cfn.describeStacks({ StackName: stackName });\n\n if (!stackResponse.Stacks || stackResponse.Stacks.length === 0) {\n throw new ToolkitError(`Toolkit stack ${stackName} not found`);\n }\n\n const stack = stackResponse.Stacks[0];\n const versionOutput = stack.Outputs?.find(output => output.OutputKey === 'BootstrapVersion');\n\n if (!versionOutput?.OutputValue) {\n throw new ToolkitError(`Unable to find BootstrapVersion output in the toolkit stack ${stackName}`);\n }\n\n const bootstrapVersion = parseInt(versionOutput.OutputValue);\n if (isNaN(bootstrapVersion)) {\n throw new ToolkitError(`Invalid BootstrapVersion value: ${versionOutput.OutputValue}`);\n }\n\n // try to get bucketname from the logical resource id. If there is no\n // bucketname, or the value doesn't look like an S3 bucket name, we assume\n // the bucket doesn't exist (this is for the case where a template customizer did\n // not dare to remove the Output, but put a dummy value there like '' or '-' or '***').\n //\n // We would have preferred to look at the stack resources here, but\n // unfortunately the deploy role doesn't have permissions call DescribeStackResources.\n const bucketName = stack.Outputs?.find(output => output.OutputKey === 'BucketName')?.OutputValue;\n // Must begin and end with letter or number.\n const hasStagingBucket = !!(bucketName && bucketName.match(/^[a-z0-9]/) && bucketName.match(/[a-z0-9]$/));\n\n return {\n hasStagingBucket,\n bootstrapVersion,\n };\n } catch (e) {\n throw new ToolkitError(`Error retrieving toolkit stack info: ${e}`);\n }\n}\n", "import { format } from 'util';\nimport type * as cxapi from '@aws-cdk/cx-api';\nimport type {\n CreateChangeSetCommandInput,\n CreateStackCommandInput,\n DescribeChangeSetCommandOutput,\n ExecuteChangeSetCommandInput,\n UpdateStackCommandInput,\n Tag,\n} from '@aws-sdk/client-cloudformation';\nimport * as chalk from 'chalk';\nimport * as uuid from 'uuid';\nimport { AssetManifestBuilder } from './asset-manifest-builder';\nimport { publishAssets } from './asset-publishing';\nimport { addMetadataAssetsToManifest } from './assets';\nimport type {\n ParameterValues,\n ParameterChanges,\n} from './cfn-api';\nimport {\n changeSetHasNoChanges,\n TemplateParameters,\n waitForChangeSet,\n waitForStackDeploy,\n waitForStackDelete,\n} from './cfn-api';\nimport { determineAllowCrossAccountAssetPublishing } from './checks';\nimport type { ChangeSetDeploymentMethod, DeploymentMethod } from './deployment-method';\nimport type { DeployStackResult, SuccessfulDeployStackResult } from './deployment-result';\nimport { formatErrorMessage } from '../../util';\nimport type { SDK, SdkProvider, ICloudFormationClient } from '../aws-auth';\nimport type { TemplateBodyParameter } from '../cloudformation';\nimport { makeBodyParameter, CfnEvaluationException, CloudFormationStack } from '../cloudformation';\nimport type { EnvironmentResources, StringWithoutPlaceholders } from '../environment';\nimport { HotswapMode, HotswapPropertyOverrides, ICON } from '../hotswap/common';\nimport { tryHotswapDeployment } from '../hotswap/hotswap-deployments';\nimport { IO, type IoHelper } from '../io/private';\nimport type { ResourcesToImport } from '../resource-import';\nimport { StackActivityMonitor } from '../stack-events';\nimport { ToolkitError } from '../toolkit-error';\n\nexport interface DeployStackOptions {\n /**\n * The stack to be deployed\n */\n readonly stack: cxapi.CloudFormationStackArtifact;\n\n /**\n * The environment to deploy this stack in\n *\n * The environment on the stack artifact may be unresolved, this one\n * must be resolved.\n */\n readonly resolvedEnvironment: cxapi.Environment;\n\n /**\n * The SDK to use for deploying the stack\n *\n * Should have been initialized with the correct role with which\n * stack operations should be performed.\n */\n readonly sdk: SDK;\n\n /**\n * SDK provider (seeded with default credentials)\n *\n * Will be used to:\n *\n * - Publish assets, either legacy assets or large CFN templates\n * that aren't themselves assets from a manifest. (Needs an SDK\n * Provider because the file publishing role is declared as part\n * of the asset).\n * - Hotswap\n */\n readonly sdkProvider: SdkProvider;\n\n /**\n * Information about the bootstrap stack found in the target environment\n */\n readonly envResources: EnvironmentResources;\n\n /**\n * Role to pass to CloudFormation to execute the change set\n *\n * To obtain a `StringWithoutPlaceholders`, run a regular\n * string though `TargetEnvironment.replacePlaceholders`.\n *\n * @default - No execution role; CloudFormation either uses the role currently associated with\n * the stack, or otherwise uses current AWS credentials.\n */\n readonly roleArn?: StringWithoutPlaceholders;\n\n /**\n * Notification ARNs to pass to CloudFormation to notify when the change set has completed\n *\n * @default - No notifications\n */\n readonly notificationArns?: string[];\n\n /**\n * Name to deploy the stack under\n *\n * @default - Name from assembly\n */\n readonly deployName?: string;\n\n /**\n * List of asset IDs which shouldn't be built\n *\n * @default - Build all assets\n */\n readonly reuseAssets?: string[];\n\n /**\n * Tags to pass to CloudFormation to add to stack\n *\n * @default - No tags\n */\n readonly tags?: Tag[];\n\n /**\n * What deployment method to use\n *\n * @default - Change set with defaults\n */\n readonly deploymentMethod?: DeploymentMethod;\n\n /**\n * The collection of extra parameters\n * (in addition to those used for assets)\n * to pass to the deployed template.\n * Note that parameters with `undefined` or empty values will be ignored,\n * and not passed to the template.\n *\n * @default - no additional parameters will be passed to the template\n */\n readonly parameters?: { [name: string]: string | undefined };\n\n /**\n * Use previous values for unspecified parameters\n *\n * If not set, all parameters must be specified for every deployment.\n *\n * @default false\n */\n readonly usePreviousParameters?: boolean;\n\n /**\n * Deploy even if the deployed template is identical to the one we are about to deploy.\n * @default false\n */\n readonly forceDeployment?: boolean;\n\n /**\n * Rollback failed deployments\n *\n * @default true\n */\n readonly rollback?: boolean;\n\n /*\n * Whether to perform a 'hotswap' deployment.\n * A 'hotswap' deployment will attempt to short-circuit CloudFormation\n * and update the affected resources like Lambda functions directly.\n *\n * @default - `HotswapMode.FULL_DEPLOYMENT` for regular deployments, `HotswapMode.HOTSWAP_ONLY` for 'watch' deployments\n */\n readonly hotswap?: HotswapMode;\n\n /**\n * Extra properties that configure hotswap behavior\n */\n readonly hotswapPropertyOverrides?: HotswapPropertyOverrides;\n\n /**\n * The extra string to append to the User-Agent header when performing AWS SDK calls.\n *\n * @default - nothing extra is appended to the User-Agent header\n */\n readonly extraUserAgent?: string;\n\n /**\n * If set, change set of type IMPORT will be created, and resourcesToImport\n * passed to it.\n */\n readonly resourcesToImport?: ResourcesToImport;\n\n /**\n * If present, use this given template instead of the stored one\n *\n * @default - Use the stored template\n */\n readonly overrideTemplate?: any;\n\n /**\n * Whether to build/publish assets in parallel\n *\n * @default true To remain backward compatible.\n */\n readonly assetParallelism?: boolean;\n}\n\nexport async function deployStack(options: DeployStackOptions, ioHelper: IoHelper): Promise<DeployStackResult> {\n const stackArtifact = options.stack;\n\n const stackEnv = options.resolvedEnvironment;\n\n options.sdk.appendCustomUserAgent(options.extraUserAgent);\n const cfn = options.sdk.cloudFormation();\n const deployName = options.deployName || stackArtifact.stackName;\n let cloudFormationStack = await CloudFormationStack.lookup(cfn, deployName);\n\n if (cloudFormationStack.stackStatus.isCreationFailure) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(\n `Found existing stack ${deployName} that had previously failed creation. Deleting it before attempting to re-create it.`,\n ));\n await cfn.deleteStack({ StackName: deployName });\n const deletedStack = await waitForStackDelete(cfn, ioHelper, deployName);\n if (deletedStack && deletedStack.stackStatus.name !== 'DELETE_COMPLETE') {\n throw new ToolkitError(\n `Failed deleting stack ${deployName} that had previously failed creation (current state: ${deletedStack.stackStatus})`,\n );\n }\n // Update variable to mark that the stack does not exist anymore, but avoid\n // doing an actual lookup in CloudFormation (which would be silly to do if\n // we just deleted it).\n cloudFormationStack = CloudFormationStack.doesNotExist(cfn, deployName);\n }\n\n // Detect \"legacy\" assets (which remain in the metadata) and publish them via\n // an ad-hoc asset manifest, while passing their locations via template\n // parameters.\n const legacyAssets = new AssetManifestBuilder();\n const assetParams = await addMetadataAssetsToManifest(\n ioHelper,\n stackArtifact,\n legacyAssets,\n options.envResources,\n options.reuseAssets,\n );\n\n const finalParameterValues = { ...options.parameters, ...assetParams };\n\n const templateParams = TemplateParameters.fromTemplate(stackArtifact.template);\n const stackParams = options.usePreviousParameters\n ? templateParams.updateExisting(finalParameterValues, cloudFormationStack.parameters)\n : templateParams.supplyAll(finalParameterValues);\n\n const hotswapMode = options.hotswap ?? HotswapMode.FULL_DEPLOYMENT;\n const hotswapPropertyOverrides = options.hotswapPropertyOverrides ?? new HotswapPropertyOverrides();\n\n if (await canSkipDeploy(options, cloudFormationStack, stackParams.hasChanges(cloudFormationStack.parameters), ioHelper)) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${deployName}: skipping deployment (use --force to override)`));\n // if we can skip deployment and we are performing a hotswap, let the user know\n // that no hotswap deployment happened\n if (hotswapMode !== HotswapMode.FULL_DEPLOYMENT) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(\n format(\n `\\n ${ICON} %s\\n`,\n chalk.bold('hotswap deployment skipped - no changes were detected (use --force to override)'),\n ),\n ));\n }\n return {\n type: 'did-deploy-stack',\n noOp: true,\n outputs: cloudFormationStack.outputs,\n stackArn: cloudFormationStack.stackId,\n };\n } else {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${deployName}: deploying...`));\n }\n\n const bodyParameter = await makeBodyParameter(\n ioHelper,\n stackArtifact,\n options.resolvedEnvironment,\n legacyAssets,\n options.envResources,\n options.overrideTemplate,\n );\n let bootstrapStackName: string | undefined;\n try {\n bootstrapStackName = (await options.envResources.lookupToolkit()).stackName;\n } catch (e) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Could not determine the bootstrap stack name: ${e}`));\n }\n await publishAssets(legacyAssets.toManifest(stackArtifact.assembly.directory), options.sdkProvider, stackEnv, {\n parallel: options.assetParallelism,\n allowCrossAccount: await determineAllowCrossAccountAssetPublishing(options.sdk, ioHelper, bootstrapStackName),\n }, ioHelper);\n\n if (hotswapMode !== HotswapMode.FULL_DEPLOYMENT) {\n // attempt to short-circuit the deployment if possible\n try {\n const hotswapDeploymentResult = await tryHotswapDeployment(\n options.sdkProvider,\n ioHelper,\n stackParams.values,\n cloudFormationStack,\n stackArtifact,\n hotswapMode,\n hotswapPropertyOverrides,\n );\n\n if (hotswapDeploymentResult) {\n return hotswapDeploymentResult;\n }\n\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(format(\n 'Could not perform a hotswap deployment, as the stack %s contains non-Asset changes',\n stackArtifact.displayName,\n )));\n } catch (e) {\n if (!(e instanceof CfnEvaluationException)) {\n throw e;\n }\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(format(\n 'Could not perform a hotswap deployment, because the CloudFormation template could not be resolved: %s',\n formatErrorMessage(e),\n )));\n }\n\n if (hotswapMode === HotswapMode.FALL_BACK) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg('Falling back to doing a full deployment'));\n options.sdk.appendCustomUserAgent('cdk-hotswap/fallback');\n } else {\n return {\n type: 'did-deploy-stack',\n noOp: true,\n stackArn: cloudFormationStack.stackId,\n outputs: cloudFormationStack.outputs,\n };\n }\n }\n\n // could not short-circuit the deployment, perform a full CFN deploy instead\n const fullDeployment = new FullCloudFormationDeployment(\n options,\n cloudFormationStack,\n stackArtifact,\n stackParams,\n bodyParameter,\n ioHelper,\n );\n return fullDeployment.performDeployment();\n}\n\ntype CommonPrepareOptions = keyof CreateStackCommandInput &\nkeyof UpdateStackCommandInput &\nkeyof CreateChangeSetCommandInput;\ntype CommonExecuteOptions = keyof CreateStackCommandInput &\nkeyof UpdateStackCommandInput &\nkeyof ExecuteChangeSetCommandInput;\n\n/**\n * This class shares state and functionality between the different full deployment modes\n */\nclass FullCloudFormationDeployment {\n private readonly cfn: ICloudFormationClient;\n private readonly stackName: string;\n private readonly update: boolean;\n private readonly verb: string;\n private readonly uuid: string;\n\n constructor(\n private readonly options: DeployStackOptions,\n private readonly cloudFormationStack: CloudFormationStack,\n private readonly stackArtifact: cxapi.CloudFormationStackArtifact,\n private readonly stackParams: ParameterValues,\n private readonly bodyParameter: TemplateBodyParameter,\n private readonly ioHelper: IoHelper,\n ) {\n this.cfn = options.sdk.cloudFormation();\n this.stackName = options.deployName ?? stackArtifact.stackName;\n\n this.update = cloudFormationStack.exists && cloudFormationStack.stackStatus.name !== 'REVIEW_IN_PROGRESS';\n this.verb = this.update ? 'update' : 'create';\n this.uuid = uuid.v4();\n }\n\n public async performDeployment(): Promise<DeployStackResult> {\n const deploymentMethod = this.options.deploymentMethod ?? {\n method: 'change-set',\n };\n\n if (deploymentMethod.method === 'direct' && this.options.resourcesToImport) {\n throw new ToolkitError('Importing resources requires a changeset deployment');\n }\n\n switch (deploymentMethod.method) {\n case 'change-set':\n return this.changeSetDeployment(deploymentMethod);\n\n case 'direct':\n return this.directDeployment();\n }\n }\n\n private async changeSetDeployment(deploymentMethod: ChangeSetDeploymentMethod): Promise<DeployStackResult> {\n const changeSetName = deploymentMethod.changeSetName ?? 'cdk-deploy-change-set';\n const execute = deploymentMethod.execute ?? true;\n const importExistingResources = deploymentMethod.importExistingResources ?? false;\n const changeSetDescription = await this.createChangeSet(changeSetName, execute, importExistingResources);\n await this.updateTerminationProtection();\n\n if (changeSetHasNoChanges(changeSetDescription)) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(format('No changes are to be performed on %s.', this.stackName)));\n if (execute) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(format('Deleting empty change set %s', changeSetDescription.ChangeSetId)));\n await this.cfn.deleteChangeSet({\n StackName: this.stackName,\n ChangeSetName: changeSetName,\n });\n }\n\n if (this.options.forceDeployment) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_WARN.msg(\n [\n 'You used the --force flag, but CloudFormation reported that the deployment would not make any changes.',\n 'According to CloudFormation, all resources are already up-to-date with the state in your CDK app.',\n '',\n 'You cannot use the --force flag to get rid of changes you made in the console. Try using',\n 'CloudFormation drift detection instead: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-stack-drift.html',\n ].join('\\n'),\n ));\n }\n\n return {\n type: 'did-deploy-stack',\n noOp: true,\n outputs: this.cloudFormationStack.outputs,\n stackArn: changeSetDescription.StackId!,\n };\n }\n\n if (!execute) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(format(\n 'Changeset %s created and waiting in review for manual execution (--no-execute)',\n changeSetDescription.ChangeSetId,\n )));\n return {\n type: 'did-deploy-stack',\n noOp: false,\n outputs: this.cloudFormationStack.outputs,\n stackArn: changeSetDescription.StackId!,\n };\n }\n\n // If there are replacements in the changeset, check the rollback flag and stack status\n const replacement = hasReplacement(changeSetDescription);\n const isPausedFailState = this.cloudFormationStack.stackStatus.isRollbackable;\n const rollback = this.options.rollback ?? true;\n if (isPausedFailState && replacement) {\n return { type: 'failpaused-need-rollback-first', reason: 'replacement', status: this.cloudFormationStack.stackStatus.name };\n }\n if (isPausedFailState && rollback) {\n return { type: 'failpaused-need-rollback-first', reason: 'not-norollback', status: this.cloudFormationStack.stackStatus.name };\n }\n if (!rollback && replacement) {\n return { type: 'replacement-requires-rollback' };\n }\n\n return this.executeChangeSet(changeSetDescription);\n }\n\n private async createChangeSet(changeSetName: string, willExecute: boolean, importExistingResources: boolean) {\n await this.cleanupOldChangeset(changeSetName);\n\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Attempting to create ChangeSet with name ${changeSetName} to ${this.verb} stack ${this.stackName}`));\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(format('%s: creating CloudFormation changeset...', chalk.bold(this.stackName))));\n const changeSet = await this.cfn.createChangeSet({\n StackName: this.stackName,\n ChangeSetName: changeSetName,\n ChangeSetType: this.options.resourcesToImport ? 'IMPORT' : this.update ? 'UPDATE' : 'CREATE',\n ResourcesToImport: this.options.resourcesToImport,\n Description: `CDK Changeset for execution ${this.uuid}`,\n ClientToken: `create${this.uuid}`,\n ImportExistingResources: importExistingResources,\n ...this.commonPrepareOptions(),\n });\n\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(format('Initiated creation of changeset: %s; waiting for it to finish creating...', changeSet.Id)));\n // Fetching all pages if we'll execute, so we can have the correct change count when monitoring.\n return waitForChangeSet(this.cfn, this.ioHelper, this.stackName, changeSetName, {\n fetchAll: willExecute,\n });\n }\n\n private async executeChangeSet(changeSet: DescribeChangeSetCommandOutput): Promise<SuccessfulDeployStackResult> {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(format('Initiating execution of changeset %s on stack %s', changeSet.ChangeSetId, this.stackName)));\n\n await this.cfn.executeChangeSet({\n StackName: this.stackName,\n ChangeSetName: changeSet.ChangeSetName!,\n ClientRequestToken: `exec${this.uuid}`,\n ...this.commonExecuteOptions(),\n });\n\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(\n format(\n 'Execution of changeset %s on stack %s has started; waiting for the update to complete...',\n changeSet.ChangeSetId,\n this.stackName,\n ),\n ));\n\n // +1 for the extra event emitted from updates.\n const changeSetLength: number = (changeSet.Changes ?? []).length + (this.update ? 1 : 0);\n return this.monitorDeployment(changeSet.CreationTime!, changeSetLength);\n }\n\n private async cleanupOldChangeset(changeSetName: string) {\n if (this.cloudFormationStack.exists) {\n // Delete any existing change sets generated by CDK since change set names must be unique.\n // The delete request is successful as long as the stack exists (even if the change set does not exist).\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Removing existing change set with name ${changeSetName} if it exists`));\n await this.cfn.deleteChangeSet({\n StackName: this.stackName,\n ChangeSetName: changeSetName,\n });\n }\n }\n\n private async updateTerminationProtection() {\n // Update termination protection only if it has changed.\n const terminationProtection = this.stackArtifact.terminationProtection ?? false;\n if (!!this.cloudFormationStack.terminationProtection !== terminationProtection) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(\n format (\n 'Updating termination protection from %s to %s for stack %s',\n this.cloudFormationStack.terminationProtection,\n terminationProtection,\n this.stackName,\n ),\n ));\n await this.cfn.updateTerminationProtection({\n StackName: this.stackName,\n EnableTerminationProtection: terminationProtection,\n });\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(format('Termination protection updated to %s for stack %s', terminationProtection, this.stackName)));\n }\n }\n\n private async directDeployment(): Promise<SuccessfulDeployStackResult> {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(format('%s: %s stack...', chalk.bold(this.stackName), this.update ? 'updating' : 'creating')));\n\n const startTime = new Date();\n\n if (this.update) {\n await this.updateTerminationProtection();\n\n try {\n await this.cfn.updateStack({\n StackName: this.stackName,\n ClientRequestToken: `update${this.uuid}`,\n ...this.commonPrepareOptions(),\n ...this.commonExecuteOptions(),\n });\n } catch (err: any) {\n if (err.message === 'No updates are to be performed.') {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(format('No updates are to be performed for stack %s', this.stackName)));\n return {\n type: 'did-deploy-stack',\n noOp: true,\n outputs: this.cloudFormationStack.outputs,\n stackArn: this.cloudFormationStack.stackId,\n };\n }\n throw err;\n }\n\n return this.monitorDeployment(startTime, undefined);\n } else {\n // Take advantage of the fact that we can set termination protection during create\n const terminationProtection = this.stackArtifact.terminationProtection ?? false;\n\n await this.cfn.createStack({\n StackName: this.stackName,\n ClientRequestToken: `create${this.uuid}`,\n ...(terminationProtection ? { EnableTerminationProtection: true } : undefined),\n ...this.commonPrepareOptions(),\n ...this.commonExecuteOptions(),\n });\n\n return this.monitorDeployment(startTime, undefined);\n }\n }\n\n private async monitorDeployment(startTime: Date, expectedChanges: number | undefined): Promise<SuccessfulDeployStackResult> {\n const monitor = new StackActivityMonitor({\n cfn: this.cfn,\n stack: this.stackArtifact,\n stackName: this.stackName,\n resourcesTotal: expectedChanges,\n ioHelper: this.ioHelper,\n changeSetCreationTime: startTime,\n });\n await monitor.start();\n\n let finalState = this.cloudFormationStack;\n try {\n const successStack = await waitForStackDeploy(this.cfn, this.ioHelper, this.stackName);\n\n // This shouldn't really happen, but catch it anyway. You never know.\n if (!successStack) {\n throw new ToolkitError('Stack deploy failed (the stack disappeared while we were deploying it)');\n }\n finalState = successStack;\n } catch (e: any) {\n throw new ToolkitError(suffixWithErrors(formatErrorMessage(e), monitor.errors));\n } finally {\n await monitor.stop();\n }\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(format('Stack %s has completed updating', this.stackName)));\n return {\n type: 'did-deploy-stack',\n noOp: false,\n outputs: finalState.outputs,\n stackArn: finalState.stackId,\n };\n }\n\n /**\n * Return the options that are shared between CreateStack, UpdateStack and CreateChangeSet\n */\n private commonPrepareOptions(): Partial<Pick<UpdateStackCommandInput, CommonPrepareOptions>> {\n return {\n Capabilities: ['CAPABILITY_IAM', 'CAPABILITY_NAMED_IAM', 'CAPABILITY_AUTO_EXPAND'],\n NotificationARNs: this.options.notificationArns,\n Parameters: this.stackParams.apiParameters,\n RoleARN: this.options.roleArn,\n TemplateBody: this.bodyParameter.TemplateBody,\n TemplateURL: this.bodyParameter.TemplateURL,\n Tags: this.options.tags,\n };\n }\n\n /**\n * Return the options that are shared between UpdateStack and CreateChangeSet\n *\n * Be careful not to add in keys for options that aren't used, as the features may not have been\n * deployed everywhere yet.\n */\n private commonExecuteOptions(): Partial<Pick<UpdateStackCommandInput, CommonExecuteOptions>> {\n const shouldDisableRollback = this.options.rollback === false;\n\n return {\n StackName: this.stackName,\n ...(shouldDisableRollback ? { DisableRollback: true } : undefined),\n };\n }\n}\n\nexport interface DestroyStackOptions {\n /**\n * The stack to be destroyed\n */\n stack: cxapi.CloudFormationStackArtifact;\n\n sdk: SDK;\n roleArn?: string;\n deployName?: string;\n}\n\nexport interface DestroyStackResult {\n /**\n * The ARN of the stack that was destroyed, if any.\n *\n * If the stack didn't exist to begin with, the operation will succeed\n * but this value will be undefined.\n */\n readonly stackArn?: string;\n}\n\nexport async function destroyStack(options: DestroyStackOptions, ioHelper: IoHelper): Promise<DestroyStackResult> {\n const deployName = options.deployName || options.stack.stackName;\n const cfn = options.sdk.cloudFormation();\n\n const currentStack = await CloudFormationStack.lookup(cfn, deployName);\n if (!currentStack.exists) {\n return {};\n }\n const monitor = new StackActivityMonitor({\n cfn,\n stack: options.stack,\n stackName: deployName,\n ioHelper: ioHelper,\n });\n await monitor.start();\n\n try {\n await cfn.deleteStack({ StackName: deployName, RoleARN: options.roleArn });\n const destroyedStack = await waitForStackDelete(cfn, ioHelper, deployName);\n if (destroyedStack && destroyedStack.stackStatus.name !== 'DELETE_COMPLETE') {\n throw new ToolkitError(`Failed to destroy ${deployName}: ${destroyedStack.stackStatus}`);\n }\n\n return { stackArn: currentStack.stackId };\n } catch (e: any) {\n throw new ToolkitError(suffixWithErrors(formatErrorMessage(e), monitor.errors));\n } finally {\n if (monitor) {\n await monitor.stop();\n }\n }\n}\n\n/**\n * Checks whether we can skip deployment\n *\n * We do this in a complicated way by preprocessing (instead of just\n * looking at the changeset), because if there are nested stacks involved\n * the changeset will always show the nested stacks as needing to be\n * updated, and the deployment will take a long time to in effect not\n * do anything.\n */\nasync function canSkipDeploy(\n deployStackOptions: DeployStackOptions,\n cloudFormationStack: CloudFormationStack,\n parameterChanges: ParameterChanges,\n ioHelper: IoHelper,\n): Promise<boolean> {\n const deployName = deployStackOptions.deployName || deployStackOptions.stack.stackName;\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${deployName}: checking if we can skip deploy`));\n\n // Forced deploy\n if (deployStackOptions.forceDeployment) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${deployName}: forced deployment`));\n return false;\n }\n\n // Creating changeset only (default true), never skip\n if (\n deployStackOptions.deploymentMethod?.method === 'change-set' &&\n deployStackOptions.deploymentMethod.execute === false\n ) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${deployName}: --no-execute, always creating change set`));\n return false;\n }\n\n // No existing stack\n if (!cloudFormationStack.exists) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${deployName}: no existing stack`));\n return false;\n }\n\n // Template has changed (assets taken into account here)\n if (JSON.stringify(deployStackOptions.stack.template) !== JSON.stringify(await cloudFormationStack.template())) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${deployName}: template has changed`));\n return false;\n }\n\n // Tags have changed\n if (!compareTags(cloudFormationStack.tags, deployStackOptions.tags ?? [])) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${deployName}: tags have changed`));\n return false;\n }\n\n // Notification arns have changed\n if (!arrayEquals(cloudFormationStack.notificationArns, deployStackOptions.notificationArns ?? [])) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${deployName}: notification arns have changed`));\n return false;\n }\n\n // Termination protection has been updated\n if (!!deployStackOptions.stack.terminationProtection !== !!cloudFormationStack.terminationProtection) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${deployName}: termination protection has been updated`));\n return false;\n }\n\n // Parameters have changed\n if (parameterChanges) {\n if (parameterChanges === 'ssm') {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${deployName}: some parameters come from SSM so we have to assume they may have changed`));\n } else {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${deployName}: parameters have changed`));\n }\n return false;\n }\n\n // Existing stack is in a failed state\n if (cloudFormationStack.stackStatus.isFailure) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${deployName}: stack is in a failure state`));\n return false;\n }\n\n // We can skip deploy\n return true;\n}\n\n/**\n * Compares two list of tags, returns true if identical.\n */\nfunction compareTags(a: Tag[], b: Tag[]): boolean {\n if (a.length !== b.length) {\n return false;\n }\n\n for (const aTag of a) {\n const bTag = b.find((tag) => tag.Key === aTag.Key);\n\n if (!bTag || bTag.Value !== aTag.Value) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction suffixWithErrors(msg: string, errors?: string[]) {\n return errors && errors.length > 0 ? `${msg}: ${errors.join(', ')}` : msg;\n}\n\nfunction arrayEquals(a: any[], b: any[]): boolean {\n return a.every((item) => b.includes(item)) && b.every((item) => a.includes(item));\n}\n\nfunction hasReplacement(cs: DescribeChangeSetCommandOutput) {\n return (cs.Changes ?? []).some(c => {\n const a = c.ResourceChange?.PolicyAction;\n return a === 'ReplaceAndDelete' || a === 'ReplaceAndRetain' || a === 'ReplaceAndSnapshot';\n });\n}\n", "// eslint-disable-next-line max-len\nimport * as path from 'path';\nimport * as cxschema from '@aws-cdk/cloud-assembly-schema';\nimport * as cxapi from '@aws-cdk/cx-api';\nimport * as chalk from 'chalk';\nimport type { AssetManifestBuilder } from './asset-manifest-builder';\nimport type { EnvironmentResources } from '../environment';\nimport { IO, type IoHelper } from '../io/private';\nimport { ToolkitError } from '../toolkit-error';\nimport type { ToolkitInfo } from '../toolkit-info';\n\n/**\n * Take the metadata assets from the given stack and add them to the given asset manifest\n *\n * Returns the CloudFormation parameters that need to be sent to the template to\n * pass Asset coordinates.\n */\nexport async function addMetadataAssetsToManifest(\n ioHelper: IoHelper,\n stack: cxapi.CloudFormationStackArtifact,\n assetManifest: AssetManifestBuilder,\n envResources: EnvironmentResources,\n reuse?: string[],\n): Promise<Record<string, string>> {\n reuse = reuse || [];\n const assets = stack.assets;\n\n if (assets.length === 0) {\n return {};\n }\n\n const toolkitInfo = await envResources.lookupToolkit();\n if (!toolkitInfo.found) {\n // eslint-disable-next-line max-len\n throw new ToolkitError(`This stack uses assets, so the toolkit stack must be deployed to the environment (Run \"${chalk.blue('cdk bootstrap ' + stack.environment!.name)}\")`);\n }\n\n const params: Record<string, string> = {};\n\n for (const asset of assets) {\n // FIXME: Should have excluded by construct path here instead of by unique ID, preferably using\n // minimatch so we can support globs. Maybe take up during artifact refactoring.\n const reuseAsset = reuse.indexOf(asset.id) > -1;\n\n if (reuseAsset) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Reusing asset ${asset.id}: ${JSON.stringify(asset)}`));\n continue;\n }\n\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Preparing asset ${asset.id}: ${JSON.stringify(asset)}`));\n if (!stack.assembly) {\n throw new ToolkitError('Unexpected: stack assembly is required in order to find assets in assembly directory');\n }\n\n Object.assign(params, await prepareAsset(ioHelper, asset, assetManifest, envResources, toolkitInfo));\n }\n\n return params;\n}\n\n// eslint-disable-next-line max-len\nasync function prepareAsset(\n ioHelper: IoHelper,\n asset: cxschema.AssetMetadataEntry,\n assetManifest: AssetManifestBuilder,\n envResources: EnvironmentResources,\n toolkitInfo: ToolkitInfo,\n): Promise<Record<string, string>> {\n switch (asset.packaging) {\n case 'zip':\n case 'file':\n return prepareFileAsset(\n ioHelper,\n asset,\n assetManifest,\n toolkitInfo,\n asset.packaging === 'zip' ? cxschema.FileAssetPackaging.ZIP_DIRECTORY : cxschema.FileAssetPackaging.FILE);\n case 'container-image':\n return prepareDockerImageAsset(asset, assetManifest, envResources);\n default:\n // eslint-disable-next-line max-len\n throw new ToolkitError(`Unsupported packaging type: ${(asset as any).packaging}. You might need to upgrade your aws-cdk toolkit to support this asset type.`);\n }\n}\n\nasync function prepareFileAsset(\n ioHelper: IoHelper,\n asset: cxschema.FileAssetMetadataEntry,\n assetManifest: AssetManifestBuilder,\n toolkitInfo: ToolkitInfo,\n packaging: cxschema.FileAssetPackaging,\n): Promise<Record<string, string>> {\n const extension = packaging === cxschema.FileAssetPackaging.ZIP_DIRECTORY ? '.zip' : path.extname(asset.path);\n const baseName = `${asset.sourceHash}${extension}`;\n // Simplify key: assets/abcdef/abcdef.zip is kinda silly and unnecessary, so if they're the same just pick one component.\n const s3Prefix = asset.id === asset.sourceHash ? 'assets/' : `assets/${asset.id}/`;\n const key = `${s3Prefix}${baseName}`;\n const s3url = `s3://${toolkitInfo.bucketName}/${key}`;\n\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Storing asset ${asset.path} at ${s3url}`));\n\n assetManifest.addFileAsset(asset.sourceHash, {\n path: asset.path,\n packaging,\n }, {\n bucketName: toolkitInfo.bucketName,\n objectKey: key,\n });\n\n return {\n [asset.s3BucketParameter]: toolkitInfo.bucketName,\n [asset.s3KeyParameter]: `${s3Prefix}${cxapi.ASSET_PREFIX_SEPARATOR}${baseName}`,\n [asset.artifactHashParameter]: asset.sourceHash,\n };\n}\n\nasync function prepareDockerImageAsset(\n asset: cxschema.ContainerImageAssetMetadataEntry,\n assetManifest: AssetManifestBuilder,\n envResources: EnvironmentResources): Promise<Record<string, string>> {\n // Pre-1.21.0, repositoryName can be specified by the user or can be left out, in which case we make\n // a per-asset repository which will get adopted and cleaned up along with the stack.\n // Post-1.21.0, repositoryName will always be specified and it will be a shared repository between\n // all assets, and asset will have imageTag specified as well. Validate the combination.\n if (!asset.imageNameParameter && (!asset.repositoryName || !asset.imageTag)) {\n throw new ToolkitError('Invalid Docker image asset configuration: \"repositoryName\" and \"imageTag\" are required when \"imageNameParameter\" is left out');\n }\n\n const repositoryName = asset.repositoryName ?? 'cdk/' + asset.id.replace(/[:/]/g, '-').toLowerCase();\n\n // Make sure the repository exists, since the 'cdk-assets' tool will not create it for us.\n const { repositoryUri } = await envResources.prepareEcrRepository(repositoryName);\n const imageTag = asset.imageTag ?? asset.sourceHash;\n\n assetManifest.addDockerImageAsset(asset.sourceHash, {\n directory: asset.path,\n dockerBuildArgs: asset.buildArgs,\n dockerBuildSsh: asset.buildSsh,\n dockerBuildTarget: asset.target,\n dockerFile: asset.file,\n networkMode: asset.networkMode,\n platform: asset.platform,\n dockerOutputs: asset.outputs,\n }, {\n repositoryName,\n imageTag,\n });\n\n if (!asset.imageNameParameter) {\n return {};\n }\n return { [asset.imageNameParameter]: `${repositoryUri}:${imageTag}` };\n}\n", "import type { PropertyDifference } from '@aws-cdk/cloudformation-diff';\nimport type { HotswappableChange, NonHotswappableChange, ResourceChange } from '../../payloads/hotswap';\nimport { NonHotswappableReason } from '../../payloads/hotswap';\nimport type { SDK } from '../aws-auth';\nimport { ToolkitError } from '../toolkit-error';\n\nexport const ICON = '\u2728';\n\nexport interface HotswapOperation {\n /**\n * Marks the operation as hotswappable\n */\n readonly hotswappable: true;\n\n /**\n * The name of the service being hotswapped.\n * Used to set a custom User-Agent for SDK calls.\n */\n readonly service: string;\n\n /**\n * Description of the change that is applied as part of the operation\n */\n readonly change: HotswappableChange;\n\n /**\n * Applies the hotswap operation\n */\n readonly apply: (sdk: SDK) => Promise<void>;\n}\n\nexport interface RejectedChange {\n /**\n * Marks the change as not hotswappable\n */\n readonly hotswappable: false;\n /**\n * The change that got rejected\n */\n readonly change: NonHotswappableChange;\n /**\n * Whether or not to show this change when listing non-hotswappable changes in HOTSWAP_ONLY mode. Does not affect\n * listing in FALL_BACK mode.\n *\n * @default true\n */\n readonly hotswapOnlyVisible?: boolean;\n}\n\nexport type HotswapChange = HotswapOperation | RejectedChange;\n\nexport enum HotswapMode {\n /**\n * Will fall back to CloudFormation when a non-hotswappable change is detected\n */\n FALL_BACK = 'fall-back',\n\n /**\n * Will not fall back to CloudFormation when a non-hotswappable change is detected\n */\n HOTSWAP_ONLY = 'hotswap-only',\n\n /**\n * Will not attempt to hotswap anything and instead go straight to CloudFormation\n */\n FULL_DEPLOYMENT = 'full-deployment',\n}\n\n/**\n * Represents configuration property overrides for hotswap deployments\n */\nexport class HotswapPropertyOverrides {\n // Each supported resource type will have its own properties. Currently this is ECS\n ecsHotswapProperties?: EcsHotswapProperties;\n\n public constructor (ecsHotswapProperties?: EcsHotswapProperties) {\n this.ecsHotswapProperties = ecsHotswapProperties;\n }\n}\n\n/**\n * Represents configuration properties for ECS hotswap deployments\n */\nexport class EcsHotswapProperties {\n // The lower limit on the number of your service's tasks that must remain in the RUNNING state during a deployment, as a percentage of the desiredCount\n readonly minimumHealthyPercent?: number;\n // The upper limit on the number of your service's tasks that are allowed in the RUNNING or PENDING state during a deployment, as a percentage of the desiredCount\n readonly maximumHealthyPercent?: number;\n\n public constructor (minimumHealthyPercent?: number, maximumHealthyPercent?: number) {\n if (minimumHealthyPercent !== undefined && minimumHealthyPercent < 0 ) {\n throw new ToolkitError('hotswap-ecs-minimum-healthy-percent can\\'t be a negative number');\n }\n if (maximumHealthyPercent !== undefined && maximumHealthyPercent < 0 ) {\n throw new ToolkitError('hotswap-ecs-maximum-healthy-percent can\\'t be a negative number');\n }\n // In order to preserve the current behaviour, when minimumHealthyPercent is not defined, it will be set to the currently default value of 0\n if (minimumHealthyPercent == undefined) {\n this.minimumHealthyPercent = 0;\n } else {\n this.minimumHealthyPercent = minimumHealthyPercent;\n }\n this.maximumHealthyPercent = maximumHealthyPercent;\n }\n\n /**\n * Check if any hotswap properties are defined\n * @returns true if all properties are undefined, false otherwise\n */\n public isEmpty(): boolean {\n return this.minimumHealthyPercent === 0 && this.maximumHealthyPercent === undefined;\n }\n}\n\ntype PropDiffs = Record<string, PropertyDifference<any>>;\n\nclass ClassifiedChanges {\n public constructor(\n public readonly change: ResourceChange,\n public readonly hotswappableProps: PropDiffs,\n public readonly nonHotswappableProps: PropDiffs,\n ) {\n }\n\n public reportNonHotswappablePropertyChanges(ret: HotswapChange[]): void {\n const nonHotswappablePropNames = Object.keys(this.nonHotswappableProps);\n if (nonHotswappablePropNames.length > 0) {\n const tagOnlyChange = nonHotswappablePropNames.length === 1 && nonHotswappablePropNames[0] === 'Tags';\n const reason = tagOnlyChange ? NonHotswappableReason.TAGS : NonHotswappableReason.PROPERTIES;\n const description = tagOnlyChange ? 'Tags are not hotswappable' : `resource properties '${nonHotswappablePropNames}' are not hotswappable on this resource type`;\n\n ret.push(nonHotswappableChange(\n this.change,\n reason,\n description,\n this.nonHotswappableProps,\n ));\n }\n }\n\n public get namesOfHotswappableProps(): string[] {\n return Object.keys(this.hotswappableProps);\n }\n}\n\nexport function classifyChanges(xs: ResourceChange, hotswappablePropNames: string[]): ClassifiedChanges {\n const hotswappableProps: PropDiffs = {};\n const nonHotswappableProps: PropDiffs = {};\n\n for (const [name, propDiff] of Object.entries(xs.propertyUpdates)) {\n if (hotswappablePropNames.includes(name)) {\n hotswappableProps[name] = propDiff;\n } else {\n nonHotswappableProps[name] = propDiff;\n }\n }\n\n return new ClassifiedChanges(xs, hotswappableProps, nonHotswappableProps);\n}\n\nexport function nonHotswappableChange(\n change: ResourceChange,\n reason: NonHotswappableReason,\n description: string,\n nonHotswappableProps?: PropDiffs,\n hotswapOnlyVisible: boolean = true,\n): RejectedChange {\n return {\n hotswappable: false,\n hotswapOnlyVisible,\n change: {\n reason,\n description,\n subject: {\n type: 'Resource',\n logicalId: change.logicalId,\n resourceType: change.newValue.Type,\n rejectedProperties: Object.keys(nonHotswappableProps ?? change.propertyUpdates),\n metadata: change.metadata,\n },\n },\n };\n}\n\nexport function nonHotswappableResource(change: ResourceChange): RejectedChange {\n return {\n hotswappable: false,\n change: {\n reason: NonHotswappableReason.RESOURCE_UNSUPPORTED,\n description: 'This resource type is not supported for hotswap deployments',\n subject: {\n type: 'Resource',\n logicalId: change.logicalId,\n resourceType: change.newValue.Type,\n rejectedProperties: Object.keys(change.propertyUpdates),\n metadata: change.metadata,\n },\n },\n };\n}\n", "import { format } from 'util';\nimport * as cfn_diff from '@aws-cdk/cloudformation-diff';\nimport type * as cxapi from '@aws-cdk/cx-api';\nimport type { WaiterResult } from '@smithy/util-waiter';\nimport * as chalk from 'chalk';\nimport type { AffectedResource, HotswapResult, ResourceSubject, ResourceChange, NonHotswappableChange } from '../../payloads';\nimport { NonHotswappableReason } from '../../payloads';\nimport { formatErrorMessage } from '../../util';\nimport type { SDK, SdkProvider } from '../aws-auth';\nimport type { CloudFormationStack, NestedStackTemplates } from '../cloudformation';\nimport { loadCurrentTemplateWithNestedStacks, EvaluateCloudFormationTemplate } from '../cloudformation';\nimport { isHotswappableAppSyncChange } from './appsync-mapping-templates';\nimport { isHotswappableCodeBuildProjectChange } from './code-build-projects';\nimport type {\n HotswapChange,\n HotswapOperation,\n RejectedChange,\n HotswapPropertyOverrides,\n} from './common';\nimport {\n ICON,\n nonHotswappableResource,\n} from './common';\nimport { isHotswappableEcsServiceChange } from './ecs-services';\nimport { isHotswappableLambdaFunctionChange } from './lambda-functions';\nimport {\n skipChangeForS3DeployCustomResourcePolicy,\n isHotswappableS3BucketDeploymentChange,\n} from './s3-bucket-deployments';\nimport { isHotswappableStateMachineChange } from './stepfunctions-state-machines';\nimport type { SuccessfulDeployStackResult } from '../deployments';\nimport { IO, SPAN } from '../io/private';\nimport type { IMessageSpan, IoHelper } from '../io/private';\nimport { Mode } from '../plugin';\nimport { ToolkitError } from '../toolkit-error';\n\n// Must use a require() otherwise esbuild complains about calling a namespace\n// eslint-disable-next-line @typescript-eslint/no-require-imports,@typescript-eslint/consistent-type-imports\nconst pLimit: typeof import('p-limit') = require('p-limit');\n\ntype HotswapDetector = (\n logicalId: string,\n change: ResourceChange,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n hotswapPropertyOverrides: HotswapPropertyOverrides,\n) => Promise<HotswapChange[]>;\n\ntype HotswapMode = 'hotswap-only' | 'fall-back';\n\nconst RESOURCE_DETECTORS: { [key: string]: HotswapDetector } = {\n // Lambda\n 'AWS::Lambda::Function': isHotswappableLambdaFunctionChange,\n 'AWS::Lambda::Version': isHotswappableLambdaFunctionChange,\n 'AWS::Lambda::Alias': isHotswappableLambdaFunctionChange,\n\n // AppSync\n 'AWS::AppSync::Resolver': isHotswappableAppSyncChange,\n 'AWS::AppSync::FunctionConfiguration': isHotswappableAppSyncChange,\n 'AWS::AppSync::GraphQLSchema': isHotswappableAppSyncChange,\n 'AWS::AppSync::ApiKey': isHotswappableAppSyncChange,\n\n 'AWS::ECS::TaskDefinition': isHotswappableEcsServiceChange,\n 'AWS::CodeBuild::Project': isHotswappableCodeBuildProjectChange,\n 'AWS::StepFunctions::StateMachine': isHotswappableStateMachineChange,\n 'Custom::CDKBucketDeployment': isHotswappableS3BucketDeploymentChange,\n 'AWS::IAM::Policy': async (\n logicalId: string,\n change: ResourceChange,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n ): Promise<HotswapChange[]> => {\n // If the policy is for a S3BucketDeploymentChange, we can ignore the change\n if (await skipChangeForS3DeployCustomResourcePolicy(logicalId, change, evaluateCfnTemplate)) {\n return [];\n }\n\n return [nonHotswappableResource(change)];\n },\n\n 'AWS::CDK::Metadata': async () => [],\n};\n\n/**\n * Perform a hotswap deployment, short-circuiting CloudFormation if possible.\n * If it's not possible to short-circuit the deployment\n * (because the CDK Stack contains changes that cannot be deployed without CloudFormation),\n * returns `undefined`.\n */\nexport async function tryHotswapDeployment(\n sdkProvider: SdkProvider,\n ioHelper: IoHelper,\n assetParams: { [key: string]: string },\n cloudFormationStack: CloudFormationStack,\n stackArtifact: cxapi.CloudFormationStackArtifact,\n hotswapMode: HotswapMode,\n hotswapPropertyOverrides: HotswapPropertyOverrides,\n): Promise<SuccessfulDeployStackResult | undefined> {\n const hotswapSpan = await ioHelper.span(SPAN.HOTSWAP).begin({\n stack: stackArtifact,\n mode: hotswapMode,\n });\n\n const result = await hotswapDeployment(\n sdkProvider,\n hotswapSpan,\n assetParams,\n stackArtifact,\n hotswapMode,\n hotswapPropertyOverrides,\n );\n\n await hotswapSpan.end(result);\n\n if (result?.hotswapped === true) {\n return {\n type: 'did-deploy-stack',\n noOp: result.hotswappableChanges.length === 0,\n stackArn: cloudFormationStack.stackId,\n outputs: cloudFormationStack.outputs,\n };\n }\n\n return undefined;\n}\n\n/**\n * Perform a hotswap deployment, short-circuiting CloudFormation if possible.\n * Returns information about the attempted hotswap deployment\n */\nasync function hotswapDeployment(\n sdkProvider: SdkProvider,\n ioSpan: IMessageSpan<any>,\n assetParams: { [key: string]: string },\n stack: cxapi.CloudFormationStackArtifact,\n hotswapMode: HotswapMode,\n hotswapPropertyOverrides: HotswapPropertyOverrides,\n): Promise<Omit<HotswapResult, 'duration'>> {\n // resolve the environment, so we can substitute things like AWS::Region in CFN expressions\n const resolvedEnv = await sdkProvider.resolveEnvironment(stack.environment);\n // create a new SDK using the CLI credentials, because the default one will not work for new-style synthesis -\n // it assumes the bootstrap deploy Role, which doesn't have permissions to update Lambda functions\n const sdk = (await sdkProvider.forEnvironment(resolvedEnv, Mode.ForWriting)).sdk;\n\n const currentTemplate = await loadCurrentTemplateWithNestedStacks(stack, sdk);\n\n const evaluateCfnTemplate = new EvaluateCloudFormationTemplate({\n stackArtifact: stack,\n parameters: assetParams,\n account: resolvedEnv.account,\n region: resolvedEnv.region,\n partition: (await sdk.currentAccount()).partition,\n sdk,\n nestedStacks: currentTemplate.nestedStacks,\n });\n\n const stackChanges = cfn_diff.fullDiff(currentTemplate.deployedRootTemplate, stack.template);\n const { hotswappable, nonHotswappable } = await classifyResourceChanges(\n stackChanges,\n evaluateCfnTemplate,\n sdk,\n currentTemplate.nestedStacks, hotswapPropertyOverrides,\n );\n\n await logRejectedChanges(ioSpan, nonHotswappable, hotswapMode);\n\n const hotswappableChanges = hotswappable.map(o => o.change);\n const nonHotswappableChanges = nonHotswappable.map(n => n.change);\n\n await ioSpan.notify(IO.CDK_TOOLKIT_I5401.msg('Hotswap plan created', {\n stack,\n mode: hotswapMode,\n hotswappableChanges,\n nonHotswappableChanges,\n }));\n\n // preserve classic hotswap behavior\n if (hotswapMode === 'fall-back') {\n if (nonHotswappableChanges.length > 0) {\n return {\n stack,\n mode: hotswapMode,\n hotswapped: false,\n hotswappableChanges,\n nonHotswappableChanges,\n };\n }\n }\n\n // apply the short-circuitable changes\n await applyAllHotswapOperations(sdk, ioSpan, hotswappable);\n\n return {\n stack,\n mode: hotswapMode,\n hotswapped: true,\n hotswappableChanges,\n nonHotswappableChanges,\n };\n}\n\ninterface ClassifiedChanges {\n hotswappable: HotswapOperation[];\n nonHotswappable: RejectedChange[];\n}\n\n/**\n * Classifies all changes to all resources as either hotswappable or not.\n * Metadata changes are excluded from the list of (non)hotswappable resources.\n */\nasync function classifyResourceChanges(\n stackChanges: cfn_diff.TemplateDiff,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n sdk: SDK,\n nestedStackNames: { [nestedStackName: string]: NestedStackTemplates },\n hotswapPropertyOverrides: HotswapPropertyOverrides,\n): Promise<ClassifiedChanges> {\n const resourceDifferences = getStackResourceDifferences(stackChanges);\n\n const promises: Array<() => Promise<HotswapChange[]>> = [];\n const hotswappableResources = new Array<HotswapOperation>();\n const nonHotswappableResources = new Array<RejectedChange>();\n for (const logicalId of Object.keys(stackChanges.outputs.changes)) {\n nonHotswappableResources.push({\n hotswappable: false,\n change: {\n reason: NonHotswappableReason.OUTPUT,\n description: 'output was changed',\n subject: {\n type: 'Output',\n logicalId,\n metadata: evaluateCfnTemplate.metadataFor(logicalId),\n },\n },\n });\n }\n // gather the results of the detector functions\n for (const [logicalId, change] of Object.entries(resourceDifferences)) {\n if (change.newValue?.Type === 'AWS::CloudFormation::Stack' && change.oldValue?.Type === 'AWS::CloudFormation::Stack') {\n const nestedHotswappableResources = await findNestedHotswappableChanges(\n logicalId,\n change,\n nestedStackNames,\n evaluateCfnTemplate,\n sdk,\n hotswapPropertyOverrides,\n );\n hotswappableResources.push(...nestedHotswappableResources.hotswappable);\n nonHotswappableResources.push(...nestedHotswappableResources.nonHotswappable);\n\n continue;\n }\n\n const hotswappableChangeCandidate = isCandidateForHotswapping(logicalId, change, evaluateCfnTemplate);\n // we don't need to run this through the detector functions, we can already judge this\n if ('hotswappable' in hotswappableChangeCandidate) {\n if (!hotswappableChangeCandidate.hotswappable) {\n nonHotswappableResources.push(hotswappableChangeCandidate);\n }\n\n continue;\n }\n\n const resourceType: string = hotswappableChangeCandidate.newValue.Type;\n if (resourceType in RESOURCE_DETECTORS) {\n // run detector functions lazily to prevent unhandled promise rejections\n promises.push(() =>\n RESOURCE_DETECTORS[resourceType](logicalId, hotswappableChangeCandidate, evaluateCfnTemplate, hotswapPropertyOverrides),\n );\n } else {\n nonHotswappableResources.push(nonHotswappableResource(hotswappableChangeCandidate));\n }\n }\n\n // resolve all detector results\n const changesDetectionResults: Array<HotswapChange[]> = [];\n for (const detectorResultPromises of promises) {\n // Constant set of promises per resource\n // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism\n const hotswapDetectionResults = await Promise.all(await detectorResultPromises());\n changesDetectionResults.push(hotswapDetectionResults);\n }\n\n for (const resourceDetectionResults of changesDetectionResults) {\n for (const propertyResult of resourceDetectionResults) {\n propertyResult.hotswappable\n ? hotswappableResources.push(propertyResult)\n : nonHotswappableResources.push(propertyResult);\n }\n }\n\n return {\n hotswappable: hotswappableResources,\n nonHotswappable: nonHotswappableResources,\n };\n}\n\n/**\n * Returns all changes to resources in the given Stack.\n *\n * @param stackChanges the collection of all changes to a given Stack\n */\nfunction getStackResourceDifferences(stackChanges: cfn_diff.TemplateDiff): {\n [logicalId: string]: cfn_diff.ResourceDifference;\n} {\n // we need to collapse logical ID rename changes into one change,\n // as they are represented in stackChanges as a pair of two changes: one addition and one removal\n const allResourceChanges: { [logId: string]: cfn_diff.ResourceDifference } = stackChanges.resources.changes;\n const allRemovalChanges = filterDict(allResourceChanges, (resChange) => resChange.isRemoval);\n const allNonRemovalChanges = filterDict(allResourceChanges, (resChange) => !resChange.isRemoval);\n for (const [logId, nonRemovalChange] of Object.entries(allNonRemovalChanges)) {\n if (nonRemovalChange.isAddition) {\n const addChange = nonRemovalChange;\n // search for an identical removal change\n const identicalRemovalChange = Object.entries(allRemovalChanges).find(([_, remChange]) => {\n return changesAreForSameResource(remChange, addChange);\n });\n // if we found one, then this means this is a rename change\n if (identicalRemovalChange) {\n const [removedLogId, removedResourceChange] = identicalRemovalChange;\n allNonRemovalChanges[logId] = makeRenameDifference(removedResourceChange, addChange);\n // delete the removal change that forms the rename pair\n delete allRemovalChanges[removedLogId];\n }\n }\n }\n // the final result are all of the remaining removal changes,\n // plus all of the non-removal changes\n // (we saved the rename changes in that object already)\n return {\n ...allRemovalChanges,\n ...allNonRemovalChanges,\n };\n}\n\n/** Filters an object with string keys based on whether the callback returns 'true' for the given value in the object. */\nfunction filterDict<T>(dict: { [key: string]: T }, func: (t: T) => boolean): { [key: string]: T } {\n return Object.entries(dict).reduce(\n (acc, [key, t]) => {\n if (func(t)) {\n acc[key] = t;\n }\n return acc;\n },\n {} as { [key: string]: T },\n );\n}\n\n/** Finds any hotswappable changes in all nested stacks. */\nasync function findNestedHotswappableChanges(\n logicalId: string,\n change: cfn_diff.ResourceDifference,\n nestedStackTemplates: { [nestedStackName: string]: NestedStackTemplates },\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n sdk: SDK,\n hotswapPropertyOverrides: HotswapPropertyOverrides,\n): Promise<ClassifiedChanges> {\n const nestedStack = nestedStackTemplates[logicalId];\n if (!nestedStack.physicalName) {\n return {\n hotswappable: [],\n nonHotswappable: [\n {\n hotswappable: false,\n change: {\n reason: NonHotswappableReason.NESTED_STACK_CREATION,\n description: 'newly created nested stacks cannot be hotswapped',\n subject: {\n type: 'Resource',\n logicalId,\n resourceType: 'AWS::CloudFormation::Stack',\n metadata: evaluateCfnTemplate.metadataFor(logicalId),\n },\n },\n },\n ],\n };\n }\n\n const evaluateNestedCfnTemplate = await evaluateCfnTemplate.createNestedEvaluateCloudFormationTemplate(\n nestedStack.physicalName,\n nestedStack.generatedTemplate,\n change.newValue?.Properties?.Parameters,\n );\n\n const nestedDiff = cfn_diff.fullDiff(\n nestedStackTemplates[logicalId].deployedTemplate,\n nestedStackTemplates[logicalId].generatedTemplate,\n );\n\n return classifyResourceChanges(\n nestedDiff,\n evaluateNestedCfnTemplate,\n sdk,\n nestedStackTemplates[logicalId].nestedStackTemplates,\n hotswapPropertyOverrides,\n );\n}\n\n/** Returns 'true' if a pair of changes is for the same resource. */\nfunction changesAreForSameResource(\n oldChange: cfn_diff.ResourceDifference,\n newChange: cfn_diff.ResourceDifference,\n): boolean {\n return (\n oldChange.oldResourceType === newChange.newResourceType &&\n // this isn't great, but I don't want to bring in something like underscore just for this comparison\n JSON.stringify(oldChange.oldProperties) === JSON.stringify(newChange.newProperties)\n );\n}\n\nfunction makeRenameDifference(\n remChange: cfn_diff.ResourceDifference,\n addChange: cfn_diff.ResourceDifference,\n): cfn_diff.ResourceDifference {\n return new cfn_diff.ResourceDifference(\n // we have to fill in the old value, because otherwise this will be classified as a non-hotswappable change\n remChange.oldValue,\n addChange.newValue,\n {\n resourceType: {\n oldType: remChange.oldResourceType,\n newType: addChange.newResourceType,\n },\n propertyDiffs: (addChange as any).propertyDiffs,\n otherDiffs: (addChange as any).otherDiffs,\n },\n );\n}\n\n/**\n * Returns a `HotswappableChangeCandidate` if the change is hotswappable\n * Returns an empty `HotswappableChange` if the change is to CDK::Metadata\n * Returns a `NonHotswappableChange` if the change is not hotswappable\n */\nfunction isCandidateForHotswapping(\n logicalId: string,\n change: cfn_diff.ResourceDifference,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): RejectedChange | ResourceChange {\n // a resource has been removed OR a resource has been added; we can't short-circuit that change\n if (!change.oldValue) {\n return {\n hotswappable: false,\n change: {\n reason: NonHotswappableReason.RESOURCE_CREATION,\n description: `resource '${logicalId}' was created by this deployment`,\n subject: {\n type: 'Resource',\n logicalId,\n resourceType: change.newValue!.Type,\n metadata: evaluateCfnTemplate.metadataFor(logicalId),\n },\n },\n };\n } else if (!change.newValue) {\n return {\n hotswappable: false,\n logicalId,\n change: {\n reason: NonHotswappableReason.RESOURCE_DELETION,\n description: `resource '${logicalId}' was destroyed by this deployment`,\n subject: {\n type: 'Resource',\n logicalId,\n resourceType: change.oldValue.Type,\n metadata: evaluateCfnTemplate.metadataFor(logicalId),\n },\n },\n };\n }\n\n // a resource has had its type changed\n if (change.newValue.Type !== change.oldValue.Type) {\n return {\n hotswappable: false,\n change: {\n reason: NonHotswappableReason.RESOURCE_TYPE_CHANGED,\n description: `resource '${logicalId}' had its type changed from '${change.oldValue?.Type}' to '${change.newValue?.Type}'`,\n subject: {\n type: 'Resource',\n logicalId,\n resourceType: change.newValue.Type,\n metadata: evaluateCfnTemplate.metadataFor(logicalId),\n },\n },\n };\n }\n\n return {\n logicalId,\n oldValue: change.oldValue,\n newValue: change.newValue,\n propertyUpdates: change.propertyUpdates,\n metadata: evaluateCfnTemplate.metadataFor(logicalId),\n };\n}\n\nasync function applyAllHotswapOperations(sdk: SDK, ioSpan: IMessageSpan<any>, hotswappableChanges: HotswapOperation[]): Promise<void[]> {\n if (hotswappableChanges.length === 0) {\n return Promise.resolve([]);\n }\n\n await ioSpan.notify(IO.DEFAULT_TOOLKIT_INFO.msg(`\\n${ICON} hotswapping resources:`));\n const limit = pLimit(10);\n // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism\n return Promise.all(hotswappableChanges.map(hotswapOperation => limit(() => {\n return applyHotswapOperation(sdk, ioSpan, hotswapOperation);\n })));\n}\n\nasync function applyHotswapOperation(sdk: SDK, ioSpan: IMessageSpan<any>, hotswapOperation: HotswapOperation): Promise<void> {\n // note the type of service that was successfully hotswapped in the User-Agent\n const customUserAgent = `cdk-hotswap/success-${hotswapOperation.service}`;\n sdk.appendCustomUserAgent(customUserAgent);\n const resourceText = (r: AffectedResource) => r.description ?? `${r.resourceType} '${r.physicalName ?? r.logicalId}'`;\n\n await ioSpan.notify(IO.CDK_TOOLKIT_I5402.msg(\n hotswapOperation.change.resources.map(r => format(` ${ICON} %s`, chalk.bold(resourceText(r)))).join('\\n'),\n hotswapOperation.change,\n ));\n\n // if the SDK call fails, an error will be thrown by the SDK\n // and will prevent the green 'hotswapped!' text from being displayed\n try {\n await hotswapOperation.apply(sdk);\n } catch (e: any) {\n if (e.name === 'TimeoutError' || e.name === 'AbortError') {\n const result: WaiterResult = JSON.parse(formatErrorMessage(e));\n const error = new ToolkitError(formatWaiterErrorResult(result));\n error.name = e.name;\n throw error;\n }\n throw e;\n }\n\n await ioSpan.notify(IO.CDK_TOOLKIT_I5403.msg(\n hotswapOperation.change.resources.map(r => format(` ${ICON} %s %s`, chalk.bold(resourceText(r)), chalk.green('hotswapped!'))).join('\\n'),\n hotswapOperation.change,\n ));\n\n sdk.removeCustomUserAgent(customUserAgent);\n}\n\nfunction formatWaiterErrorResult(result: WaiterResult) {\n const main = [\n `Resource is not in the expected state due to waiter status: ${result.state}`,\n result.reason ? `${result.reason}.` : '',\n ].join('. ');\n\n if (result.observedResponses != null) {\n const observedResponses = Object\n .entries(result.observedResponses)\n .map(([msg, count]) => ` - ${msg} (${count})`)\n .join('\\n');\n\n return `${main} Observed responses:\\n${observedResponses}`;\n }\n\n return main;\n}\n\nasync function logRejectedChanges(\n ioSpan: IMessageSpan<any>,\n rejectedChanges: RejectedChange[],\n hotswapMode: HotswapMode,\n): Promise<void> {\n if (rejectedChanges.length === 0) {\n return;\n }\n /**\n * EKS Services can have a task definition that doesn't refer to the task definition being updated.\n * We have to log this as a non-hotswappable change to the task definition, but when we do,\n * we wind up hotswapping the task definition and logging it as a non-hotswappable change.\n *\n * This logic prevents us from logging that change as non-hotswappable when we hotswap it.\n */\n if (hotswapMode === 'hotswap-only') {\n rejectedChanges = rejectedChanges.filter((change) => change.hotswapOnlyVisible === true);\n\n if (rejectedChanges.length === 0) {\n return;\n }\n }\n\n const messages = ['']; // start with empty line\n\n if (hotswapMode === 'hotswap-only') {\n messages.push(format('%s %s', chalk.red('\u26A0\uFE0F'), chalk.red('The following non-hotswappable changes were found. To reconcile these using CloudFormation, specify --hotswap-fallback')));\n } else {\n messages.push(format('%s %s', chalk.red('\u26A0\uFE0F'), chalk.red('The following non-hotswappable changes were found:')));\n }\n\n for (const { change } of rejectedChanges) {\n messages.push(' ' + nonHotswappableChangeMessage(change));\n }\n messages.push(''); // newline\n\n await ioSpan.notify(IO.DEFAULT_TOOLKIT_INFO.msg(messages.join('\\n')));\n}\n\n/**\n * Formats a NonHotswappableChange\n */\nfunction nonHotswappableChangeMessage(change: NonHotswappableChange): string {\n const subject = change.subject;\n const reason = change.description ?? change.reason;\n\n switch (subject.type) {\n case 'Output':\n return format(\n 'output: %s, reason: %s',\n chalk.bold(subject.logicalId),\n chalk.red(reason),\n );\n case 'Resource':\n return nonHotswappableResourceMessage(subject, reason);\n }\n}\n\n/**\n * Formats a non-hotswappable resource subject\n */\nfunction nonHotswappableResourceMessage(subject: ResourceSubject, reason: string): string {\n if (subject.rejectedProperties?.length) {\n return format(\n 'resource: %s, type: %s, rejected changes: %s, reason: %s',\n chalk.bold(subject.logicalId),\n chalk.bold(subject.resourceType),\n chalk.bold(subject.rejectedProperties),\n chalk.red(reason),\n );\n }\n\n return format(\n 'resource: %s, type: %s, reason: %s',\n chalk.bold(subject.logicalId),\n chalk.bold(subject.resourceType),\n chalk.red(reason),\n );\n}\n", "import { ToolkitError } from '../toolkit-error';\n\nexport type DeployStackResult =\n | SuccessfulDeployStackResult\n | NeedRollbackFirstDeployStackResult\n | ReplacementRequiresRollbackStackResult\n ;\n\n/** Successfully deployed a stack */\nexport interface SuccessfulDeployStackResult {\n readonly type: 'did-deploy-stack';\n readonly noOp: boolean;\n readonly outputs: { [name: string]: string };\n readonly stackArn: string;\n}\n\n/** The stack is currently in a failpaused state, and needs to be rolled back before the deployment */\nexport interface NeedRollbackFirstDeployStackResult {\n readonly type: 'failpaused-need-rollback-first';\n readonly reason: 'not-norollback' | 'replacement';\n readonly status: string;\n}\n\n/** The upcoming change has a replacement, which requires deploying with --rollback */\nexport interface ReplacementRequiresRollbackStackResult {\n readonly type: 'replacement-requires-rollback';\n}\n\nexport function assertIsSuccessfulDeployStackResult(x: DeployStackResult): asserts x is SuccessfulDeployStackResult {\n if (x.type !== 'did-deploy-stack') {\n throw new ToolkitError(`Unexpected deployStack result. This should not happen: ${JSON.stringify(x)}. If you are seeing this error, please report it at https://github.com/aws/aws-cdk/issues/new/choose.`);\n }\n}\n", "import type {\n GetSchemaCreationStatusCommandOutput,\n GetSchemaCreationStatusCommandInput,\n} from '@aws-sdk/client-appsync';\nimport {\n type HotswapChange,\n classifyChanges,\n} from './common';\nimport type { ResourceChange } from '../../payloads/hotswap';\nimport { lowerCaseFirstCharacter, transformObjectKeys } from '../../util';\nimport type { SDK } from '../aws-auth';\n\nimport type { EvaluateCloudFormationTemplate } from '../cloudformation';\nimport { ToolkitError } from '../toolkit-error';\n\nexport async function isHotswappableAppSyncChange(\n logicalId: string,\n change: ResourceChange,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): Promise<HotswapChange[]> {\n const isResolver = change.newValue.Type === 'AWS::AppSync::Resolver';\n const isFunction = change.newValue.Type === 'AWS::AppSync::FunctionConfiguration';\n const isGraphQLSchema = change.newValue.Type === 'AWS::AppSync::GraphQLSchema';\n const isAPIKey = change.newValue.Type === 'AWS::AppSync::ApiKey';\n if (!isResolver && !isFunction && !isGraphQLSchema && !isAPIKey) {\n return [];\n }\n\n const ret: HotswapChange[] = [];\n\n const classifiedChanges = classifyChanges(change, [\n 'RequestMappingTemplate',\n 'RequestMappingTemplateS3Location',\n 'ResponseMappingTemplate',\n 'ResponseMappingTemplateS3Location',\n 'Code',\n 'CodeS3Location',\n 'Definition',\n 'DefinitionS3Location',\n 'Expires',\n ]);\n classifiedChanges.reportNonHotswappablePropertyChanges(ret);\n\n const namesOfHotswappableChanges = Object.keys(classifiedChanges.hotswappableProps);\n if (namesOfHotswappableChanges.length > 0) {\n let physicalName: string | undefined = undefined;\n const arn = await evaluateCfnTemplate.establishResourcePhysicalName(\n logicalId,\n isFunction ? change.newValue.Properties?.Name : undefined,\n );\n if (isResolver) {\n const arnParts = arn?.split('/');\n physicalName = arnParts ? `${arnParts[3]}.${arnParts[5]}` : undefined;\n } else {\n physicalName = arn;\n }\n\n // nothing do here\n if (!physicalName) {\n return ret;\n }\n\n ret.push({\n change: {\n cause: change,\n resources: [{\n logicalId,\n resourceType: change.newValue.Type,\n physicalName,\n metadata: evaluateCfnTemplate.metadataFor(logicalId),\n }],\n },\n hotswappable: true,\n service: 'appsync',\n apply: async (sdk: SDK) => {\n const sdkProperties: { [name: string]: any } = {\n ...change.oldValue.Properties,\n Definition: change.newValue.Properties?.Definition,\n DefinitionS3Location: change.newValue.Properties?.DefinitionS3Location,\n requestMappingTemplate: change.newValue.Properties?.RequestMappingTemplate,\n requestMappingTemplateS3Location: change.newValue.Properties?.RequestMappingTemplateS3Location,\n responseMappingTemplate: change.newValue.Properties?.ResponseMappingTemplate,\n responseMappingTemplateS3Location: change.newValue.Properties?.ResponseMappingTemplateS3Location,\n code: change.newValue.Properties?.Code,\n codeS3Location: change.newValue.Properties?.CodeS3Location,\n expires: change.newValue.Properties?.Expires,\n };\n const evaluatedResourceProperties = await evaluateCfnTemplate.evaluateCfnExpression(sdkProperties);\n const sdkRequestObject = transformObjectKeys(evaluatedResourceProperties, lowerCaseFirstCharacter);\n\n // resolve s3 location files as SDK doesn't take in s3 location but inline code\n if (sdkRequestObject.requestMappingTemplateS3Location) {\n sdkRequestObject.requestMappingTemplate = await fetchFileFromS3(\n sdkRequestObject.requestMappingTemplateS3Location,\n sdk,\n );\n delete sdkRequestObject.requestMappingTemplateS3Location;\n }\n if (sdkRequestObject.responseMappingTemplateS3Location) {\n sdkRequestObject.responseMappingTemplate = await fetchFileFromS3(\n sdkRequestObject.responseMappingTemplateS3Location,\n sdk,\n );\n delete sdkRequestObject.responseMappingTemplateS3Location;\n }\n if (sdkRequestObject.definitionS3Location) {\n sdkRequestObject.definition = await fetchFileFromS3(sdkRequestObject.definitionS3Location, sdk);\n delete sdkRequestObject.definitionS3Location;\n }\n if (sdkRequestObject.codeS3Location) {\n sdkRequestObject.code = await fetchFileFromS3(sdkRequestObject.codeS3Location, sdk);\n delete sdkRequestObject.codeS3Location;\n }\n\n if (isResolver) {\n await sdk.appsync().updateResolver(sdkRequestObject);\n } else if (isFunction) {\n // Function version is only applicable when using VTL and mapping templates\n // Runtime only applicable when using code (JS mapping templates)\n if (sdkRequestObject.code) {\n delete sdkRequestObject.functionVersion;\n } else {\n delete sdkRequestObject.runtime;\n }\n\n const functions = await sdk.appsync().listFunctions({ apiId: sdkRequestObject.apiId });\n const { functionId } = functions.find((fn) => fn.name === physicalName) ?? {};\n // Updating multiple functions at the same time or along with graphql schema results in `ConcurrentModificationException`\n await exponentialBackOffRetry(\n () =>\n sdk.appsync().updateFunction({\n ...sdkRequestObject,\n functionId: functionId,\n }),\n 6,\n 1000,\n 'ConcurrentModificationException',\n );\n } else if (isGraphQLSchema) {\n let schemaCreationResponse: GetSchemaCreationStatusCommandOutput = await sdk\n .appsync()\n .startSchemaCreation(sdkRequestObject);\n while (\n schemaCreationResponse.status &&\n ['PROCESSING', 'DELETING'].some((status) => status === schemaCreationResponse.status)\n ) {\n await sleep(1000); // poll every second\n const getSchemaCreationStatusRequest: GetSchemaCreationStatusCommandInput = {\n apiId: sdkRequestObject.apiId,\n };\n schemaCreationResponse = await sdk.appsync().getSchemaCreationStatus(getSchemaCreationStatusRequest);\n }\n if (schemaCreationResponse.status === 'FAILED') {\n throw new ToolkitError(schemaCreationResponse.details ?? 'Schema creation has failed.');\n }\n } else {\n // isApiKey\n if (!sdkRequestObject.id) {\n // ApiKeyId is optional in CFN but required in SDK. Grab the KeyId from physicalArn if not available as part of CFN template\n const arnParts = physicalName?.split('/');\n if (arnParts && arnParts.length === 4) {\n sdkRequestObject.id = arnParts[3];\n }\n }\n await sdk.appsync().updateApiKey(sdkRequestObject);\n }\n },\n });\n }\n\n return ret;\n}\n\nasync function fetchFileFromS3(s3Url: string, sdk: SDK) {\n const s3PathParts = s3Url.split('/');\n const s3Bucket = s3PathParts[2]; // first two are \"s3:\" and \"\" due to s3://\n const s3Key = s3PathParts.splice(3).join('/'); // after removing first three we reconstruct the key\n return (await sdk.s3().getObject({ Bucket: s3Bucket, Key: s3Key })).Body?.transformToString();\n}\n\nasync function exponentialBackOffRetry(fn: () => Promise<any>, numOfRetries: number, backOff: number, errorCodeToRetry: string) {\n try {\n await fn();\n } catch (error: any) {\n if (error && error.name === errorCodeToRetry && numOfRetries > 0) {\n await sleep(backOff); // time to wait doubles everytime function fails, starts at 1 second\n await exponentialBackOffRetry(fn, numOfRetries - 1, backOff * 2, errorCodeToRetry);\n } else {\n throw error;\n }\n }\n}\n\nasync function sleep(ms: number) {\n return new Promise((ok) => setTimeout(ok, ms));\n}\n", "import type { UpdateProjectCommandInput } from '@aws-sdk/client-codebuild';\nimport {\n type HotswapChange,\n classifyChanges,\n} from './common';\nimport type { ResourceChange } from '../../payloads/hotswap';\nimport { lowerCaseFirstCharacter, transformObjectKeys } from '../../util';\nimport type { SDK } from '../aws-auth';\nimport type { EvaluateCloudFormationTemplate } from '../cloudformation';\n\nexport async function isHotswappableCodeBuildProjectChange(\n logicalId: string,\n change: ResourceChange,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): Promise<HotswapChange[]> {\n if (change.newValue.Type !== 'AWS::CodeBuild::Project') {\n return [];\n }\n\n const ret: HotswapChange[] = [];\n\n const classifiedChanges = classifyChanges(change, ['Source', 'Environment', 'SourceVersion']);\n classifiedChanges.reportNonHotswappablePropertyChanges(ret);\n if (classifiedChanges.namesOfHotswappableProps.length > 0) {\n const updateProjectInput: UpdateProjectCommandInput = {\n name: '',\n };\n const projectName = await evaluateCfnTemplate.establishResourcePhysicalName(\n logicalId,\n change.newValue.Properties?.Name,\n );\n\n // nothing to do jere\n if (!projectName) {\n return ret;\n }\n\n ret.push({\n change: {\n cause: change,\n resources: [{\n logicalId: logicalId,\n resourceType: change.newValue.Type,\n physicalName: projectName,\n metadata: evaluateCfnTemplate.metadataFor(logicalId),\n }],\n },\n hotswappable: true,\n service: 'codebuild',\n apply: async (sdk: SDK) => {\n updateProjectInput.name = projectName;\n\n for (const updatedPropName in change.propertyUpdates) {\n const updatedProp = change.propertyUpdates[updatedPropName];\n switch (updatedPropName) {\n case 'Source':\n updateProjectInput.source = transformObjectKeys(\n await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue),\n convertSourceCloudformationKeyToSdkKey,\n );\n break;\n case 'Environment':\n updateProjectInput.environment = await transformObjectKeys(\n await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue),\n lowerCaseFirstCharacter,\n );\n break;\n case 'SourceVersion':\n updateProjectInput.sourceVersion = await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue);\n break;\n }\n }\n\n await sdk.codeBuild().updateProject(updateProjectInput);\n },\n });\n }\n\n return ret;\n}\n\nfunction convertSourceCloudformationKeyToSdkKey(key: string): string {\n if (key.toLowerCase() === 'buildspec') {\n return key.toLowerCase();\n }\n return lowerCaseFirstCharacter(key);\n}\n", "import type {\n HotswapPropertyOverrides,\n HotswapChange,\n} from './common';\nimport {\n classifyChanges,\n nonHotswappableChange,\n} from './common';\nimport { NonHotswappableReason, type ResourceChange } from '../../payloads/hotswap';\nimport { lowerCaseFirstCharacter, transformObjectKeys } from '../../util';\nimport type { SDK } from '../aws-auth';\nimport type { EvaluateCloudFormationTemplate } from '../cloudformation';\n\nconst ECS_SERVICE_RESOURCE_TYPE = 'AWS::ECS::Service';\n\nexport async function isHotswappableEcsServiceChange(\n logicalId: string,\n change: ResourceChange,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n hotswapPropertyOverrides: HotswapPropertyOverrides,\n): Promise<HotswapChange[]> {\n // the only resource change we can evaluate here is an ECS TaskDefinition\n if (change.newValue.Type !== 'AWS::ECS::TaskDefinition') {\n return [];\n }\n\n const ret: HotswapChange[] = [];\n\n // We only allow a change in the ContainerDefinitions of the TaskDefinition for now -\n // it contains the image and environment variables, so seems like a safe bet for now.\n // We might revisit this decision in the future though!\n const classifiedChanges = classifyChanges(change, ['ContainerDefinitions']);\n classifiedChanges.reportNonHotswappablePropertyChanges(ret);\n\n // find all ECS Services that reference the TaskDefinition that changed\n const resourcesReferencingTaskDef = evaluateCfnTemplate.findReferencesTo(logicalId);\n const ecsServiceResourcesReferencingTaskDef = resourcesReferencingTaskDef.filter(\n (r) => r.Type === ECS_SERVICE_RESOURCE_TYPE,\n );\n const ecsServicesReferencingTaskDef = new Array<EcsService>();\n for (const ecsServiceResource of ecsServiceResourcesReferencingTaskDef) {\n const serviceArn = await evaluateCfnTemplate.findPhysicalNameFor(ecsServiceResource.LogicalId);\n if (serviceArn) {\n ecsServicesReferencingTaskDef.push({\n logicalId: ecsServiceResource.LogicalId,\n serviceArn,\n });\n }\n }\n if (ecsServicesReferencingTaskDef.length === 0) {\n /**\n * ECS Services can have a task definition that doesn't refer to the task definition being updated.\n * We have to log this as a non-hotswappable change to the task definition, but when we do,\n * we wind up hotswapping the task definition and logging it as a non-hotswappable change.\n *\n * This logic prevents us from logging that change as non-hotswappable when we hotswap it.\n */\n ret.push(nonHotswappableChange(\n change,\n NonHotswappableReason.DEPENDENCY_UNSUPPORTED,\n 'No ECS services reference the changed task definition',\n undefined,\n false,\n ));\n }\n if (resourcesReferencingTaskDef.length > ecsServicesReferencingTaskDef.length) {\n // if something besides an ECS Service is referencing the TaskDefinition,\n // hotswap is not possible in FALL_BACK mode\n const nonEcsServiceTaskDefRefs = resourcesReferencingTaskDef.filter((r) => r.Type !== ECS_SERVICE_RESOURCE_TYPE);\n for (const taskRef of nonEcsServiceTaskDefRefs) {\n ret.push(nonHotswappableChange(\n change,\n NonHotswappableReason.DEPENDENCY_UNSUPPORTED,\n `A resource '${taskRef.LogicalId}' with Type '${taskRef.Type}' that is not an ECS Service was found referencing the changed TaskDefinition '${logicalId}'`,\n ));\n }\n }\n\n const namesOfHotswappableChanges = Object.keys(classifiedChanges.hotswappableProps);\n if (namesOfHotswappableChanges.length > 0) {\n const taskDefinitionResource = await prepareTaskDefinitionChange(evaluateCfnTemplate, logicalId, change);\n ret.push({\n change: {\n cause: change,\n resources: [\n {\n logicalId,\n resourceType: change.newValue.Type,\n physicalName: await taskDefinitionResource.Family,\n metadata: evaluateCfnTemplate.metadataFor(logicalId),\n },\n ...ecsServicesReferencingTaskDef.map((ecsService) => ({\n resourceType: ECS_SERVICE_RESOURCE_TYPE,\n physicalName: ecsService.serviceArn.split('/')[2],\n logicalId: ecsService.logicalId,\n metadata: evaluateCfnTemplate.metadataFor(ecsService.logicalId),\n })),\n ],\n },\n hotswappable: true,\n service: 'ecs-service',\n apply: async (sdk: SDK) => {\n // Step 1 - update the changed TaskDefinition, creating a new TaskDefinition Revision\n // we need to lowercase the evaluated TaskDef from CloudFormation,\n // as the AWS SDK uses lowercase property names for these\n\n // The SDK requires more properties here than its worth doing explicit typing for\n // instead, just use all the old values in the diff to fill them in implicitly\n const lowercasedTaskDef = transformObjectKeys(taskDefinitionResource, lowerCaseFirstCharacter, {\n // All the properties that take arbitrary string as keys i.e. { \"string\" : \"string\" }\n // https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_RegisterTaskDefinition.html#API_RegisterTaskDefinition_RequestSyntax\n ContainerDefinitions: {\n DockerLabels: true,\n FirelensConfiguration: {\n Options: true,\n },\n LogConfiguration: {\n Options: true,\n },\n },\n Volumes: {\n DockerVolumeConfiguration: {\n DriverOpts: true,\n Labels: true,\n },\n },\n });\n const registerTaskDefResponse = await sdk.ecs().registerTaskDefinition(lowercasedTaskDef);\n const taskDefRevArn = registerTaskDefResponse.taskDefinition?.taskDefinitionArn;\n\n let ecsHotswapProperties = hotswapPropertyOverrides.ecsHotswapProperties;\n let minimumHealthyPercent = ecsHotswapProperties?.minimumHealthyPercent;\n let maximumHealthyPercent = ecsHotswapProperties?.maximumHealthyPercent;\n\n // Step 2 - update the services using that TaskDefinition to point to the new TaskDefinition Revision\n // Forcing New Deployment and setting Minimum Healthy Percent to 0.\n // As CDK HotSwap is development only, this seems the most efficient way to ensure all tasks are replaced immediately, regardless of original amount\n // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism\n await Promise.all(\n ecsServicesReferencingTaskDef.map(async (service) => {\n const cluster = service.serviceArn.split('/')[1];\n const update = await sdk.ecs().updateService({\n service: service.serviceArn,\n taskDefinition: taskDefRevArn,\n cluster,\n forceNewDeployment: true,\n deploymentConfiguration: {\n minimumHealthyPercent: minimumHealthyPercent !== undefined ? minimumHealthyPercent : 0,\n maximumPercent: maximumHealthyPercent !== undefined ? maximumHealthyPercent : undefined,\n },\n });\n\n await sdk.ecs().waitUntilServicesStable({\n cluster: update.service?.clusterArn,\n services: [service.serviceArn],\n });\n }),\n );\n },\n });\n }\n\n return ret;\n}\n\ninterface EcsService {\n readonly logicalId: string;\n readonly serviceArn: string;\n}\n\nasync function prepareTaskDefinitionChange(\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n logicalId: string,\n change: ResourceChange,\n) {\n const taskDefinitionResource: { [name: string]: any } = {\n ...change.oldValue.Properties,\n ContainerDefinitions: change.newValue.Properties?.ContainerDefinitions,\n };\n // first, let's get the name of the family\n const familyNameOrArn = await evaluateCfnTemplate.establishResourcePhysicalName(\n logicalId,\n taskDefinitionResource?.Family,\n );\n if (!familyNameOrArn) {\n // if the Family property has not been provided, and we can't find it in the current Stack,\n // this means hotswapping is not possible\n return;\n }\n // the physical name of the Task Definition in CloudFormation includes its current revision number at the end,\n // remove it if needed\n const familyNameOrArnParts = familyNameOrArn.split(':');\n const family =\n familyNameOrArnParts.length > 1\n ? // familyNameOrArn is actually an ARN, of the format 'arn:aws:ecs:region:account:task-definition/<family-name>:<revision-nr>'\n // so, take the 6th element, at index 5, and split it on '/'\n familyNameOrArnParts[5].split('/')[1]\n : // otherwise, familyNameOrArn is just the simple name evaluated from the CloudFormation template\n familyNameOrArn;\n // then, let's evaluate the body of the remainder of the TaskDef (without the Family property)\n return {\n ...(await evaluateCfnTemplate.evaluateCfnExpression({\n ...(taskDefinitionResource ?? {}),\n Family: undefined,\n })),\n Family: family,\n };\n}\n", "import { Writable } from 'stream';\nimport type { PropertyDifference } from '@aws-cdk/cloudformation-diff';\nimport type { FunctionConfiguration, UpdateFunctionConfigurationCommandInput } from '@aws-sdk/client-lambda';\nimport type { HotswapChange } from './common';\nimport { classifyChanges } from './common';\nimport type { AffectedResource, ResourceChange } from '../../payloads/hotswap';\nimport { flatMap } from '../../util';\nimport type { ILambdaClient, SDK } from '../aws-auth';\nimport { CfnEvaluationException, type EvaluateCloudFormationTemplate } from '../cloudformation';\nimport { ToolkitError } from '../toolkit-error';\n\n// namespace object imports won't work in the bundle for function exports\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nconst archiver = require('archiver');\n\nexport async function isHotswappableLambdaFunctionChange(\n logicalId: string,\n change: ResourceChange,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): Promise<HotswapChange[]> {\n // if the change is for a Lambda Version, we just ignore it\n // we will publish a new version when we get to hotswapping the actual Function this Version points to\n // (Versions can't be changed in CloudFormation anyway, they're immutable)\n if (change.newValue.Type === 'AWS::Lambda::Version') {\n return [];\n }\n\n // we handle Aliases specially too\n // the actual alias update will happen if we change the function\n if (change.newValue.Type === 'AWS::Lambda::Alias') {\n return classifyAliasChanges(change);\n }\n\n if (change.newValue.Type !== 'AWS::Lambda::Function') {\n return [];\n }\n\n const ret: HotswapChange[] = [];\n const classifiedChanges = classifyChanges(change, ['Code', 'Environment', 'Description']);\n classifiedChanges.reportNonHotswappablePropertyChanges(ret);\n\n const functionName = await evaluateCfnTemplate.establishResourcePhysicalName(\n logicalId,\n change.newValue.Properties?.FunctionName,\n );\n const namesOfHotswappableChanges = Object.keys(classifiedChanges.hotswappableProps);\n if (functionName && namesOfHotswappableChanges.length > 0) {\n const lambdaCodeChange = await evaluateLambdaFunctionProps(\n classifiedChanges.hotswappableProps,\n change.newValue.Properties?.Runtime,\n evaluateCfnTemplate,\n );\n\n // nothing to do here\n if (lambdaCodeChange === undefined) {\n return ret;\n }\n\n const dependencies = await dependantResources(logicalId, functionName, evaluateCfnTemplate);\n\n ret.push({\n change: {\n cause: change,\n resources: [\n {\n logicalId,\n resourceType: change.newValue.Type,\n physicalName: functionName,\n metadata: evaluateCfnTemplate.metadataFor(logicalId),\n },\n ...dependencies,\n ],\n },\n hotswappable: true,\n service: 'lambda',\n apply: async (sdk: SDK) => {\n const lambda = sdk.lambda();\n const operations: Promise<any>[] = [];\n\n if (lambdaCodeChange.code !== undefined || lambdaCodeChange.configurations !== undefined) {\n if (lambdaCodeChange.code !== undefined) {\n const updateFunctionCodeResponse = await lambda.updateFunctionCode({\n FunctionName: functionName,\n S3Bucket: lambdaCodeChange.code.s3Bucket,\n S3Key: lambdaCodeChange.code.s3Key,\n ImageUri: lambdaCodeChange.code.imageUri,\n ZipFile: lambdaCodeChange.code.functionCodeZip,\n S3ObjectVersion: lambdaCodeChange.code.s3ObjectVersion,\n });\n\n await waitForLambdasPropertiesUpdateToFinish(updateFunctionCodeResponse, lambda, functionName);\n }\n\n if (lambdaCodeChange.configurations !== undefined) {\n const updateRequest: UpdateFunctionConfigurationCommandInput = {\n FunctionName: functionName,\n };\n if (lambdaCodeChange.configurations.description !== undefined) {\n updateRequest.Description = lambdaCodeChange.configurations.description;\n }\n if (lambdaCodeChange.configurations.environment !== undefined) {\n updateRequest.Environment = lambdaCodeChange.configurations.environment;\n }\n const updateFunctionCodeResponse = await lambda.updateFunctionConfiguration(updateRequest);\n await waitForLambdasPropertiesUpdateToFinish(updateFunctionCodeResponse, lambda, functionName);\n }\n\n // only if the code changed is there any point in publishing a new Version\n const versions = dependencies.filter((d) => d.resourceType === 'AWS::Lambda::Version');\n if (versions.length) {\n const publishVersionPromise = lambda.publishVersion({\n FunctionName: functionName,\n });\n\n const aliases = dependencies.filter((d) => d.resourceType === 'AWS::Lambda::Alias');\n if (aliases.length) {\n // we need to wait for the Version to finish publishing\n const versionUpdate = await publishVersionPromise;\n for (const alias of aliases) {\n operations.push(\n lambda.updateAlias({\n FunctionName: functionName,\n Name: alias.physicalName,\n FunctionVersion: versionUpdate.Version,\n }),\n );\n }\n } else {\n operations.push(publishVersionPromise);\n }\n }\n }\n\n // run all of our updates in parallel\n // Limited set of updates per function\n // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism\n await Promise.all(operations);\n },\n });\n }\n\n return ret;\n}\n\n/**\n * Determines which changes to this Alias are hotswappable or not\n */\nfunction classifyAliasChanges(change: ResourceChange): HotswapChange[] {\n const ret: HotswapChange[] = [];\n const classifiedChanges = classifyChanges(change, ['FunctionVersion']);\n classifiedChanges.reportNonHotswappablePropertyChanges(ret);\n\n // we only want to report not hotswappable changes to aliases\n // the actual alias update will happen if we change the function\n\n return ret;\n}\n\n/**\n * Evaluates the hotswappable properties of an AWS::Lambda::Function and\n * Returns a `LambdaFunctionChange` if the change is hotswappable.\n * Returns `undefined` if the change is not hotswappable.\n */\nasync function evaluateLambdaFunctionProps(\n hotswappablePropChanges: Record<string, PropertyDifference<any>>,\n runtime: string,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): Promise<LambdaFunctionChange | undefined> {\n /*\n * At first glance, we would want to initialize these using the \"previous\" values (change.oldValue),\n * in case only one of them changed, like the key, and the Bucket stayed the same.\n * However, that actually fails for old-style synthesis, which uses CFN Parameters!\n * Because the names of the Parameters depend on the hash of the Asset,\n * the Parameters used for the \"old\" values no longer exist in `assetParams` at this point,\n * which means we don't have the correct values available to evaluate the CFN expression with.\n * Fortunately, the diff will always include both the s3Bucket and s3Key parts of the Lambda's Code property,\n * even if only one of them was actually changed,\n * which means we don't need the \"old\" values at all, and we can safely initialize these with just `''`.\n */\n let code: LambdaFunctionCode | undefined = undefined;\n let description: string | undefined = undefined;\n let environment: { [key: string]: string } | undefined = undefined;\n\n for (const updatedPropName in hotswappablePropChanges) {\n const updatedProp = hotswappablePropChanges[updatedPropName];\n\n switch (updatedPropName) {\n case 'Code':\n let s3Bucket, s3Key, s3ObjectVersion, imageUri, functionCodeZip;\n\n for (const newPropName in updatedProp.newValue) {\n switch (newPropName) {\n case 'S3Bucket':\n s3Bucket = await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue[newPropName]);\n break;\n case 'S3Key':\n s3Key = await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue[newPropName]);\n break;\n case 'S3ObjectVersion':\n s3ObjectVersion = await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue[newPropName]);\n break;\n case 'ImageUri':\n imageUri = await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue[newPropName]);\n break;\n case 'ZipFile':\n // We must create a zip package containing a file with the inline code\n const functionCode = await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue[newPropName]);\n const functionRuntime = await evaluateCfnTemplate.evaluateCfnExpression(runtime);\n if (!functionRuntime) {\n return undefined;\n }\n // file extension must be chosen depending on the runtime\n const codeFileExt = determineCodeFileExtFromRuntime(functionRuntime);\n functionCodeZip = await zipString(`index.${codeFileExt}`, functionCode);\n break;\n }\n }\n code = {\n s3Bucket,\n s3Key,\n s3ObjectVersion,\n imageUri,\n functionCodeZip,\n };\n break;\n case 'Description':\n description = await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue);\n break;\n case 'Environment':\n environment = await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue);\n break;\n default:\n // we will never get here, but just in case we do throw an error\n throw new ToolkitError(\n 'while apply()ing, found a property that cannot be hotswapped. Please report this at github.com/aws/aws-cdk/issues/new/choose',\n );\n }\n }\n\n const configurations = description || environment ? { description, environment } : undefined;\n return code || configurations ? { code, configurations } : undefined;\n}\n\ninterface LambdaFunctionCode {\n readonly s3Bucket?: string;\n readonly s3Key?: string;\n readonly s3ObjectVersion?: string;\n readonly imageUri?: string;\n readonly functionCodeZip?: Buffer;\n}\n\ninterface LambdaFunctionConfigurations {\n readonly description?: string;\n readonly environment?: { [key: string]: string };\n}\n\ninterface LambdaFunctionChange {\n readonly code?: LambdaFunctionCode;\n readonly configurations?: LambdaFunctionConfigurations;\n}\n\n/**\n * Compress a string as a file, returning a promise for the zip buffer\n * https://github.com/archiverjs/node-archiver/issues/342\n */\nfunction zipString(fileName: string, rawString: string): Promise<Buffer> {\n return new Promise((resolve, reject) => {\n const buffers: Buffer[] = [];\n\n const converter = new Writable();\n\n converter._write = (chunk: Buffer, _: string, callback: () => void) => {\n buffers.push(chunk);\n process.nextTick(callback);\n };\n\n converter.on('finish', () => {\n resolve(Buffer.concat(buffers));\n });\n\n const archive = archiver('zip');\n\n archive.on('error', (err: any) => {\n reject(err);\n });\n\n archive.pipe(converter);\n\n archive.append(rawString, {\n name: fileName,\n date: new Date('1980-01-01T00:00:00.000Z'), // Add date to make resulting zip file deterministic\n });\n\n void archive.finalize();\n });\n}\n\n/**\n * After a Lambda Function is updated, it cannot be updated again until the\n * `State=Active` and the `LastUpdateStatus=Successful`.\n *\n * Depending on the configuration of the Lambda Function this could happen relatively quickly\n * or very slowly. For example, Zip based functions _not_ in a VPC can take ~1 second whereas VPC\n * or Container functions can take ~25 seconds (and 'idle' VPC functions can take minutes).\n */\nasync function waitForLambdasPropertiesUpdateToFinish(\n currentFunctionConfiguration: FunctionConfiguration,\n lambda: ILambdaClient,\n functionName: string,\n): Promise<void> {\n const functionIsInVpcOrUsesDockerForCode =\n currentFunctionConfiguration.VpcConfig?.VpcId || currentFunctionConfiguration.PackageType === 'Image';\n\n // if the function is deployed in a VPC or if it is a container image function\n // then the update will take much longer and we can wait longer between checks\n // otherwise, the update will be quick, so a 1-second delay is fine\n const delaySeconds = functionIsInVpcOrUsesDockerForCode ? 5 : 1;\n\n await lambda.waitUntilFunctionUpdated(delaySeconds, {\n FunctionName: functionName,\n });\n}\n\n/**\n * Get file extension from Lambda runtime string.\n * We use this extension to create a deployment package from Lambda inline code.\n */\nfunction determineCodeFileExtFromRuntime(runtime: string): string {\n if (runtime.startsWith('node')) {\n return 'js';\n }\n if (runtime.startsWith('python')) {\n return 'py';\n }\n // Currently inline code only supports Node.js and Python, ignoring other runtimes.\n // https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-code.html#aws-properties-lambda-function-code-properties\n throw new CfnEvaluationException(\n `runtime ${runtime} is unsupported, only node.js and python runtimes are currently supported.`,\n );\n}\n\n/**\n * Finds all Versions that reference an AWS::Lambda::Function with logical ID `logicalId`\n * and Aliases that reference those Versions.\n */\nasync function versionsAndAliases(logicalId: string, evaluateCfnTemplate: EvaluateCloudFormationTemplate) {\n // find all Lambda Versions that reference this Function\n const versionsReferencingFunction = evaluateCfnTemplate\n .findReferencesTo(logicalId)\n .filter((r) => r.Type === 'AWS::Lambda::Version');\n // find all Lambda Aliases that reference the above Versions\n const aliasesReferencingVersions = flatMap(versionsReferencingFunction, v =>\n evaluateCfnTemplate.findReferencesTo(v.LogicalId));\n\n return { versionsReferencingFunction, aliasesReferencingVersions };\n}\n\nasync function dependantResources(\n logicalId: string,\n functionName: string,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): Promise<Array<AffectedResource>> {\n const candidates = await versionsAndAliases(logicalId, evaluateCfnTemplate);\n\n // Limited set of updates per function\n // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism\n const aliases = await Promise.all(candidates.aliasesReferencingVersions.map(async (a) => {\n const name = await evaluateCfnTemplate.evaluateCfnExpression(a.Properties?.Name);\n return {\n logicalId: a.LogicalId,\n resourceType: a.Type,\n physicalName: name,\n description: `${a.Type} '${name}' for AWS::Lambda::Function '${functionName}'`,\n metadata: evaluateCfnTemplate.metadataFor(a.LogicalId),\n };\n }));\n\n const versions = candidates.versionsReferencingFunction.map((v) => (\n {\n logicalId: v.LogicalId,\n resourceType: v.Type,\n description: `${v.Type} for AWS::Lambda::Function '${functionName}'`,\n metadata: evaluateCfnTemplate.metadataFor(v.LogicalId),\n }\n ));\n\n return [\n ...versions,\n ...aliases,\n ];\n}\n", "import type { HotswapChange } from './common';\nimport type { ResourceChange } from '../../payloads/hotswap';\nimport type { SDK } from '../aws-auth';\nimport type { EvaluateCloudFormationTemplate } from '../cloudformation';\n\n/**\n * This means that the value is required to exist by CloudFormation's Custom Resource API (or our S3 Bucket Deployment Lambda's API)\n * but the actual value specified is irrelevant\n */\nconst REQUIRED_BY_CFN = 'required-to-be-present-by-cfn';\n\nconst CDK_BUCKET_DEPLOYMENT_CFN_TYPE = 'Custom::CDKBucketDeployment';\n\nexport async function isHotswappableS3BucketDeploymentChange(\n logicalId: string,\n change: ResourceChange,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): Promise<HotswapChange[]> {\n // In old-style synthesis, the policy used by the lambda to copy assets Ref's the assets directly,\n // meaning that the changes made to the Policy are artifacts that can be safely ignored\n const ret: HotswapChange[] = [];\n\n if (change.newValue.Type !== CDK_BUCKET_DEPLOYMENT_CFN_TYPE) {\n return [];\n }\n\n // no classification to be done here; all the properties of this custom resource thing are hotswappable\n const customResourceProperties = await evaluateCfnTemplate.evaluateCfnExpression({\n ...change.newValue.Properties,\n ServiceToken: undefined,\n });\n\n // note that this gives the ARN of the lambda, not the name. This is fine though, the invoke() sdk call will take either\n const functionName = await evaluateCfnTemplate.evaluateCfnExpression(change.newValue.Properties?.ServiceToken);\n if (!functionName) {\n return ret;\n }\n\n ret.push({\n change: {\n cause: change,\n resources: [{\n logicalId,\n physicalName: customResourceProperties.DestinationBucketName,\n resourceType: CDK_BUCKET_DEPLOYMENT_CFN_TYPE,\n description: `Contents of AWS::S3::Bucket '${customResourceProperties.DestinationBucketName}'`,\n metadata: evaluateCfnTemplate.metadataFor(logicalId),\n }],\n },\n hotswappable: true,\n service: 'custom-s3-deployment',\n apply: async (sdk: SDK) => {\n await sdk.lambda().invokeCommand({\n FunctionName: functionName,\n // Lambda refuses to take a direct JSON object and requires it to be stringify()'d\n Payload: JSON.stringify({\n RequestType: 'Update',\n ResponseURL: REQUIRED_BY_CFN,\n PhysicalResourceId: REQUIRED_BY_CFN,\n StackId: REQUIRED_BY_CFN,\n RequestId: REQUIRED_BY_CFN,\n LogicalResourceId: REQUIRED_BY_CFN,\n ResourceProperties: stringifyObject(customResourceProperties), // JSON.stringify() doesn't turn the actual objects to strings, but the lambda expects strings\n }),\n });\n },\n });\n\n return ret;\n}\n\nexport async function skipChangeForS3DeployCustomResourcePolicy(\n iamPolicyLogicalId: string,\n change: ResourceChange,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): Promise<boolean> {\n if (change.newValue.Type !== 'AWS::IAM::Policy') {\n return false;\n }\n const roles: string[] = change.newValue.Properties?.Roles;\n\n // If no roles are referenced, the policy is definitely not used for a S3Deployment\n if (!roles || !roles.length) {\n return false;\n }\n\n // Check if every role this policy is referenced by is only used for a S3Deployment\n for (const role of roles) {\n const roleArn = await evaluateCfnTemplate.evaluateCfnExpression(role);\n const roleLogicalId = await evaluateCfnTemplate.findLogicalIdForPhysicalName(roleArn);\n\n // We must assume this role is used for something else, because we can't check it\n if (!roleLogicalId) {\n return false;\n }\n\n // Find all interesting reference to the role\n const roleRefs = evaluateCfnTemplate\n .findReferencesTo(roleLogicalId)\n // we are not interested in the reference from the original policy - it always exists\n .filter((roleRef) => !(roleRef.Type == 'AWS::IAM::Policy' && roleRef.LogicalId === iamPolicyLogicalId));\n\n // Check if the role is only used for S3Deployment\n // We know this is the case, if S3Deployment -> Lambda -> Role is satisfied for every reference\n // And we have at least one reference.\n const isRoleOnlyForS3Deployment =\n roleRefs.length >= 1 &&\n roleRefs.every((roleRef) => {\n if (roleRef.Type === 'AWS::Lambda::Function') {\n const lambdaRefs = evaluateCfnTemplate.findReferencesTo(roleRef.LogicalId);\n // Every reference must be to the custom resource and at least one reference must be present\n return (\n lambdaRefs.length >= 1 && lambdaRefs.every((lambdaRef) => lambdaRef.Type === 'Custom::CDKBucketDeployment')\n );\n }\n return false;\n });\n\n // We have determined this role is used for something else, so we can't skip the change\n if (!isRoleOnlyForS3Deployment) {\n return false;\n }\n }\n\n // We have checked that any use of this policy is only for S3Deployment and we can safely skip it\n return true;\n}\n\nfunction stringifyObject(obj: any): any {\n if (obj == null) {\n return obj;\n }\n if (Array.isArray(obj)) {\n return obj.map(stringifyObject);\n }\n if (typeof obj !== 'object') {\n return obj.toString();\n }\n\n const ret: { [k: string]: any } = {};\n for (const [k, v] of Object.entries(obj)) {\n ret[k] = stringifyObject(v);\n }\n return ret;\n}\n", "import { type HotswapChange, classifyChanges } from './common';\nimport type { ResourceChange } from '../../payloads/hotswap';\nimport type { SDK } from '../aws-auth';\nimport type { EvaluateCloudFormationTemplate } from '../cloudformation';\n\nexport async function isHotswappableStateMachineChange(\n logicalId: string,\n change: ResourceChange,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): Promise<HotswapChange[]> {\n if (change.newValue.Type !== 'AWS::StepFunctions::StateMachine') {\n return [];\n }\n const ret: HotswapChange[] = [];\n const classifiedChanges = classifyChanges(change, ['DefinitionString']);\n classifiedChanges.reportNonHotswappablePropertyChanges(ret);\n\n const namesOfHotswappableChanges = Object.keys(classifiedChanges.hotswappableProps);\n if (namesOfHotswappableChanges.length > 0) {\n const stateMachineNameInCfnTemplate = change.newValue?.Properties?.StateMachineName;\n const stateMachineArn = stateMachineNameInCfnTemplate\n ? await evaluateCfnTemplate.evaluateCfnExpression({\n 'Fn::Sub':\n 'arn:${AWS::Partition}:states:${AWS::Region}:${AWS::AccountId}:stateMachine:' +\n stateMachineNameInCfnTemplate,\n })\n : await evaluateCfnTemplate.findPhysicalNameFor(logicalId);\n\n // nothing to do\n if (!stateMachineArn) {\n return ret;\n }\n\n ret.push({\n change: {\n cause: change,\n resources: [{\n logicalId,\n resourceType: change.newValue.Type,\n physicalName: stateMachineArn?.split(':')[6],\n metadata: evaluateCfnTemplate.metadataFor(logicalId),\n }],\n },\n hotswappable: true,\n service: 'stepfunctions-service',\n apply: async (sdk: SDK) => {\n // not passing the optional properties leaves them unchanged\n await sdk.stepFunctions().updateStateMachine({\n stateMachineArn,\n definition: await evaluateCfnTemplate.evaluateCfnExpression(change.propertyUpdates.DefinitionString.newValue),\n });\n },\n });\n }\n\n return ret;\n}\n", "import type { ClientRequest } from 'http';\nimport type { RequestOptions } from 'https';\nimport * as https from 'node:https';\nimport * as path from 'path';\nimport type { Environment } from '@aws-cdk/cx-api';\nimport * as fs from 'fs-extra';\nimport * as semver from 'semver';\nimport { ProxyAgentProvider } from './aws-auth';\nimport type { SdkHttpOptions } from './aws-auth';\nimport type { Context } from './context';\nimport type { IIoHost } from './io';\nimport type { IoHelper } from './io/private';\nimport { IO, asIoHelper, IoDefaultMessages } from './io/private';\nimport { ToolkitError } from './toolkit-error';\nimport { loadTreeFromDir } from './tree';\nimport type { ConstructTreeNode } from './tree';\nimport { cdkCacheDir, formatErrorMessage } from '../util';\n\nconst CACHE_FILE_PATH = path.join(cdkCacheDir(), 'notices.json');\n\nexport interface NoticesProps {\n /**\n * CDK context\n */\n readonly context: Context;\n\n /**\n * Include notices that have already been acknowledged.\n *\n * @default false\n */\n readonly includeAcknowledged?: boolean;\n\n /**\n * Global CLI option for output directory for synthesized cloud assembly\n *\n * @default 'cdk.out'\n */\n readonly output?: string;\n\n /**\n * Options for the HTTP request\n */\n readonly httpOptions?: SdkHttpOptions;\n\n /**\n * Where messages are going to be sent\n */\n readonly ioHost: IIoHost;\n\n /**\n * The version of the CLI\n */\n readonly cliVersion: string;\n}\n\nexport interface NoticesPrintOptions {\n\n /**\n * Whether to append the total number of unacknowledged notices to the display.\n *\n * @default false\n */\n readonly showTotal?: boolean;\n}\n\nexport interface NoticesRefreshOptions {\n /**\n * Whether to force a cache refresh regardless of expiration time.\n *\n * @default false\n */\n readonly force?: boolean;\n\n /**\n * Data source for fetch notices from.\n *\n * @default - WebsiteNoticeDataSource\n */\n readonly dataSource?: NoticeDataSource;\n}\n\nexport interface NoticesFilterFilterOptions {\n readonly data: Notice[];\n readonly cliVersion: string;\n readonly outDir: string;\n readonly bootstrappedEnvironments: BootstrappedEnvironment[];\n}\n\nexport class NoticesFilter {\n constructor(private readonly ioMessages: IoDefaultMessages) {\n }\n\n public filter(options: NoticesFilterFilterOptions): FilteredNotice[] {\n const components = [\n ...this.constructTreeComponents(options.outDir),\n ...this.otherComponents(options),\n ];\n\n return this.findForNamedComponents(options.data, components);\n }\n\n /**\n * From a set of input options, return the notices components we are searching for\n */\n private otherComponents(options: NoticesFilterFilterOptions): ActualComponent[] {\n return [\n // CLI\n {\n name: 'cli',\n version: options.cliVersion,\n },\n\n // Node version\n {\n name: 'node',\n version: process.version.replace(/^v/, ''), // remove the 'v' prefix.\n dynamicName: 'node',\n },\n\n // Bootstrap environments\n ...options.bootstrappedEnvironments.flatMap(env => {\n const semverBootstrapVersion = semver.coerce(env.bootstrapStackVersion);\n if (!semverBootstrapVersion) {\n // we don't throw because notices should never crash the cli.\n this.ioMessages.warning(`While filtering notices, could not coerce bootstrap version '${env.bootstrapStackVersion}' into semver`);\n return [];\n }\n\n return [{\n name: 'bootstrap',\n version: `${semverBootstrapVersion}`,\n dynamicName: 'ENVIRONMENTS',\n dynamicValue: env.environment.name,\n }];\n }),\n ];\n }\n\n /**\n * Based on a set of component names, find all notices that match one of the given components\n */\n private findForNamedComponents(data: Notice[], actualComponents: ActualComponent[]): FilteredNotice[] {\n return data.flatMap(notice => {\n const ors = this.resolveAliases(normalizeComponents(notice.components));\n\n // Find the first set of the disjunctions of which all components match against the actual components.\n // Return the actual components we found so that we can inject their dynamic values. A single filter\n // component can match more than one actual component\n for (const ands of ors) {\n const matched = ands.map(affected => actualComponents.filter(actual =>\n this.componentNameMatches(affected, actual) && semver.satisfies(actual.version, affected.version, { includePrerelease: true })));\n\n // For every clause in the filter we matched one or more components\n if (matched.every(xs => xs.length > 0)) {\n const ret = new FilteredNotice(notice);\n this.addDynamicValues(matched.flatMap(x => x), ret);\n return [ret];\n }\n }\n\n return [];\n });\n }\n\n /**\n * Whether the given \"affected component\" name applies to the given actual component name.\n *\n * The name matches if the name is exactly the same, or the name in the notice\n * is a prefix of the node name when the query ends in '.'.\n */\n private componentNameMatches(pattern: Component, actual: ActualComponent): boolean {\n return pattern.name.endsWith('.') ? actual.name.startsWith(pattern.name) : pattern.name === actual.name;\n }\n\n /**\n * Adds dynamic values from the given ActualComponents\n *\n * If there are multiple components with the same dynamic name, they are joined\n * by a comma.\n */\n private addDynamicValues(comps: ActualComponent[], notice: FilteredNotice) {\n const dynamicValues: Record<string, string[]> = {};\n for (const comp of comps) {\n if (comp.dynamicName) {\n dynamicValues[comp.dynamicName] = dynamicValues[comp.dynamicName] ?? [];\n dynamicValues[comp.dynamicName].push(comp.dynamicValue ?? comp.version);\n }\n }\n for (const [key, values] of Object.entries(dynamicValues)) {\n notice.addDynamicValue(key, values.join(','));\n }\n }\n\n /**\n * Treat 'framework' as an alias for either `aws-cdk-lib.` or `@aws-cdk/core.`.\n *\n * Because it's EITHER `aws-cdk-lib` or `@aws-cdk/core`, we need to add multiple\n * arrays at the top level.\n */\n private resolveAliases(ors: Component[][]): Component[][] {\n return ors.flatMap(ands => {\n const hasFramework = ands.find(c => c.name === 'framework');\n if (!hasFramework) {\n return [ands];\n }\n\n return [\n ands.map(c => c.name === 'framework' ? { ...c, name: '@aws-cdk/core.' } : c),\n ands.map(c => c.name === 'framework' ? { ...c, name: 'aws-cdk-lib.' } : c),\n ];\n });\n }\n\n /**\n * Load the construct tree from the given directory and return its components\n */\n private constructTreeComponents(manifestDir: string): ActualComponent[] {\n const tree = loadTreeFromDir(manifestDir, (msg: string) => void this.ioMessages.notify(IO.DEFAULT_ASSEMBLY_TRACE.msg(msg)));\n if (!tree) {\n return [];\n }\n\n const ret: ActualComponent[] = [];\n recurse(tree);\n return ret;\n\n function recurse(x: ConstructTreeNode) {\n if (x.constructInfo?.fqn && x.constructInfo?.version) {\n ret.push({\n name: x.constructInfo?.fqn,\n version: x.constructInfo?.version,\n });\n }\n\n for (const child of Object.values(x.children ?? {})) {\n recurse(child);\n }\n }\n }\n}\n\ninterface ActualComponent {\n /**\n * Name of the component\n */\n readonly name: string;\n\n /**\n * Version of the component\n */\n readonly version: string;\n\n /**\n * If matched, under what name should it be added to the set of dynamic values\n *\n * These will be used to substitute placeholders in the message string, where\n * placeholders look like `{resolve:XYZ}`.\n *\n * If there is more than one component with the same dynamic name, they are\n * joined by ','.\n *\n * @default - Don't add to the set of dynamic values.\n */\n readonly dynamicName?: string;\n\n /**\n * If matched, what we should put in the set of dynamic values insstead of the version.\n *\n * Only used if `dynamicName` is set; by default we will add the actual version\n * of the component.\n *\n * @default - The version.\n */\n readonly dynamicValue?: string;\n}\n\n/**\n * Information about a bootstrapped environment.\n */\nexport interface BootstrappedEnvironment {\n readonly bootstrapStackVersion: number;\n readonly environment: Environment;\n}\n\n/**\n * Provides access to notices the CLI can display.\n */\nexport class Notices {\n /**\n * Create an instance. Note that this replaces the singleton.\n */\n public static create(props: NoticesProps): Notices {\n this._instance = new Notices(props);\n return this._instance;\n }\n\n /**\n * Get the singleton instance. May return `undefined` if `create` has not been called.\n */\n public static get(): Notices | undefined {\n return this._instance;\n }\n\n private static _instance: Notices | undefined;\n\n private readonly context: Context;\n private readonly output: string;\n private readonly acknowledgedIssueNumbers: Set<Number>;\n private readonly includeAcknowlegded: boolean;\n private readonly httpOptions: SdkHttpOptions;\n private readonly ioHelper: IoHelper;\n private readonly ioMessages: IoDefaultMessages;\n private readonly cliVersion: string;\n\n private data: Set<Notice> = new Set();\n\n // sets don't deduplicate interfaces, so we use a map.\n private readonly bootstrappedEnvironments: Map<string, BootstrappedEnvironment> = new Map();\n\n private constructor(props: NoticesProps) {\n this.context = props.context;\n this.acknowledgedIssueNumbers = new Set(this.context.get('acknowledged-issue-numbers') ?? []);\n this.includeAcknowlegded = props.includeAcknowledged ?? false;\n this.output = props.output ?? 'cdk.out';\n this.httpOptions = props.httpOptions ?? {};\n this.ioHelper = asIoHelper(props.ioHost, 'notices' as any /* forcing a CliAction to a ToolkitAction */);\n this.ioMessages = new IoDefaultMessages(this.ioHelper);\n this.cliVersion = props.cliVersion;\n }\n\n /**\n * Add a bootstrap information to filter on. Can have multiple values\n * in case of multi-environment deployments.\n */\n public addBootstrappedEnvironment(bootstrapped: BootstrappedEnvironment) {\n const key = [\n bootstrapped.bootstrapStackVersion,\n bootstrapped.environment.account,\n bootstrapped.environment.region,\n bootstrapped.environment.name,\n ].join(':');\n this.bootstrappedEnvironments.set(key, bootstrapped);\n }\n\n /**\n * Refresh the list of notices this instance is aware of.\n * To make sure this never crashes the CLI process, all failures are caught and\n * silently logged.\n *\n * If context is configured to not display notices, this will no-op.\n */\n public async refresh(options: NoticesRefreshOptions = {}) {\n try {\n const underlyingDataSource = options.dataSource ?? new WebsiteNoticeDataSource(this.ioHelper, this.httpOptions);\n const dataSource = new CachedDataSource(this.ioMessages, CACHE_FILE_PATH, underlyingDataSource, options.force ?? false);\n const notices = await dataSource.fetch();\n this.data = new Set(this.includeAcknowlegded ? notices : notices.filter(n => !this.acknowledgedIssueNumbers.has(n.issueNumber)));\n } catch (e: any) {\n this.ioMessages.debug(`Could not refresh notices: ${e}`);\n }\n }\n\n /**\n * Display the relevant notices (unless context dictates we shouldn't).\n */\n public display(options: NoticesPrintOptions = {}) {\n const filteredNotices = new NoticesFilter(this.ioMessages).filter({\n data: Array.from(this.data),\n cliVersion: this.cliVersion,\n outDir: this.output,\n bootstrappedEnvironments: Array.from(this.bootstrappedEnvironments.values()),\n });\n\n if (filteredNotices.length > 0) {\n void this.ioMessages.notify(IO.CDK_TOOLKIT_I0100.msg([\n '',\n 'NOTICES (What\\'s this? https://github.com/aws/aws-cdk/wiki/CLI-Notices)',\n '',\n ].join('\\n')));\n for (const filtered of filteredNotices) {\n const formatted = filtered.format() + '\\n';\n switch (filtered.notice.severity) {\n case 'warning':\n void this.ioMessages.notify(IO.CDK_TOOLKIT_W0101.msg(formatted));\n break;\n case 'error':\n void this.ioMessages.notify(IO.CDK_TOOLKIT_E0101.msg(formatted));\n break;\n default:\n void this.ioMessages.notify(IO.CDK_TOOLKIT_I0101.msg(formatted));\n break;\n }\n }\n void this.ioMessages.notify(IO.CDK_TOOLKIT_I0100.msg(\n `If you don\u2019t want to see a notice anymore, use \"cdk acknowledge <id>\". For example, \"cdk acknowledge ${filteredNotices[0].notice.issueNumber}\".`,\n ));\n }\n\n if (options.showTotal ?? false) {\n void this.ioMessages.notify(IO.CDK_TOOLKIT_I0100.msg(\n `\\nThere are ${filteredNotices.length} unacknowledged notice(s).`,\n ));\n }\n }\n}\n\nexport interface Component {\n name: string;\n\n /**\n * The range of affected versions\n */\n version: string;\n}\n\nexport interface Notice {\n title: string;\n issueNumber: number;\n overview: string;\n /**\n * A set of affected components\n *\n * The canonical form of a list of components is in Disjunctive Normal Form\n * (i.e., an OR of ANDs). This is the form when the list of components is a\n * doubly nested array: the notice matches if all components of at least one\n * of the top-level array matches.\n *\n * If the `components` is a single-level array, it is evaluated as an OR; it\n * matches if any of the components matches.\n */\n components: Array<Component | Component[]>;\n schemaVersion: string;\n severity?: string;\n}\n\n/**\n * Normalizes the given components structure into DNF form\n */\nfunction normalizeComponents(xs: Array<Component | Component[]>): Component[][] {\n return xs.map(x => Array.isArray(x) ? x : [x]);\n}\n\nfunction renderConjunction(xs: Component[]): string {\n return xs.map(c => `${c.name}: ${c.version}`).join(' AND ');\n}\n\n/**\n * Notice after passing the filter. A filter can augment a notice with\n * dynamic values as it has access to the dynamic matching data.\n */\nexport class FilteredNotice {\n private readonly dynamicValues: { [key: string]: string } = {};\n\n public constructor(public readonly notice: Notice) {\n }\n\n public addDynamicValue(key: string, value: string) {\n this.dynamicValues[`{resolve:${key}}`] = value;\n }\n\n public format(): string {\n const componentsValue = normalizeComponents(this.notice.components).map(renderConjunction).join(', ');\n return this.resolveDynamicValues([\n `${this.notice.issueNumber}\\t${this.notice.title}`,\n this.formatOverview(),\n `\\tAffected versions: ${componentsValue}`,\n `\\tMore information at: https://github.com/aws/aws-cdk/issues/${this.notice.issueNumber}`,\n ].join('\\n\\n') + '\\n');\n }\n\n private formatOverview() {\n const wrap = (s: string) => s.replace(/(?![^\\n]{1,60}$)([^\\n]{1,60})\\s/g, '$1\\n');\n\n const heading = 'Overview: ';\n const separator = `\\n\\t${' '.repeat(heading.length)}`;\n const content = wrap(this.notice.overview)\n .split('\\n')\n .join(separator);\n\n return '\\t' + heading + content;\n }\n\n private resolveDynamicValues(input: string): string {\n const pattern = new RegExp(Object.keys(this.dynamicValues).join('|'), 'g');\n return input.replace(pattern, (matched) => this.dynamicValues[matched] ?? matched);\n }\n}\n\nexport interface NoticeDataSource {\n fetch(): Promise<Notice[]>;\n}\n\nexport class WebsiteNoticeDataSource implements NoticeDataSource {\n private readonly options: SdkHttpOptions;\n\n constructor(private readonly ioHelper: IoHelper, options: SdkHttpOptions = {}) {\n this.options = options;\n }\n\n async fetch(): Promise<Notice[]> {\n const timeout = 3000;\n\n const options: RequestOptions = {\n agent: await new ProxyAgentProvider(this.ioHelper).create(this.options),\n };\n\n const notices = await new Promise<Notice[]>((resolve, reject) => {\n let req: ClientRequest | undefined;\n\n let timer = setTimeout(() => {\n if (req) {\n req.destroy(new ToolkitError('Request timed out'));\n }\n }, timeout);\n\n timer.unref();\n\n try {\n req = https.get('https://cli.cdk.dev-tools.aws.dev/notices.json',\n options,\n res => {\n if (res.statusCode === 200) {\n res.setEncoding('utf8');\n let rawData = '';\n res.on('data', (chunk) => {\n rawData += chunk;\n });\n res.on('end', () => {\n try {\n const data = JSON.parse(rawData).notices as Notice[];\n if (!data) {\n throw new ToolkitError(\"'notices' key is missing\");\n }\n resolve(data ?? []);\n } catch (e: any) {\n reject(new ToolkitError(`Failed to parse notices: ${formatErrorMessage(e)}`));\n }\n });\n res.on('error', e => {\n reject(new ToolkitError(`Failed to fetch notices: ${formatErrorMessage(e)}`));\n });\n } else {\n reject(new ToolkitError(`Failed to fetch notices. Status code: ${res.statusCode}`));\n }\n });\n req.on('error', reject);\n } catch (e: any) {\n reject(new ToolkitError(`HTTPS 'get' call threw an error: ${formatErrorMessage(e)}`));\n }\n });\n\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg('Notices refreshed'));\n return notices;\n }\n}\n\ninterface CachedNotices {\n expiration: number;\n notices: Notice[];\n}\n\nconst TIME_TO_LIVE_SUCCESS = 60 * 60 * 1000; // 1 hour\nconst TIME_TO_LIVE_ERROR = 1 * 60 * 1000; // 1 minute\n\nexport class CachedDataSource implements NoticeDataSource {\n constructor(\n private readonly ioMessages: IoDefaultMessages,\n private readonly fileName: string,\n private readonly dataSource: NoticeDataSource,\n private readonly skipCache?: boolean) {\n }\n\n async fetch(): Promise<Notice[]> {\n const cachedData = await this.load();\n const data = cachedData.notices;\n const expiration = cachedData.expiration ?? 0;\n\n if (Date.now() > expiration || this.skipCache) {\n const freshData = await this.fetchInner();\n await this.save(freshData);\n return freshData.notices;\n } else {\n this.ioMessages.debug(`Reading cached notices from ${this.fileName}`);\n return data;\n }\n }\n\n private async fetchInner(): Promise<CachedNotices> {\n try {\n return {\n expiration: Date.now() + TIME_TO_LIVE_SUCCESS,\n notices: await this.dataSource.fetch(),\n };\n } catch (e) {\n this.ioMessages.debug(`Could not refresh notices: ${e}`);\n return {\n expiration: Date.now() + TIME_TO_LIVE_ERROR,\n notices: [],\n };\n }\n }\n\n private async load(): Promise<CachedNotices> {\n const defaultValue = {\n expiration: 0,\n notices: [],\n };\n\n try {\n return fs.existsSync(this.fileName)\n ? await fs.readJSON(this.fileName) as CachedNotices\n : defaultValue;\n } catch (e) {\n this.ioMessages.debug(`Failed to load notices from cache: ${e}`);\n return defaultValue;\n }\n }\n\n private async save(cached: CachedNotices): Promise<void> {\n try {\n await fs.writeJSON(this.fileName, cached);\n } catch (e) {\n this.ioMessages.debug(`Failed to store notices in the cache: ${e}`);\n }\n }\n}\n", "import * as path from 'node:path';\nimport type { CloudAssembly } from '@aws-cdk/cx-api';\nimport * as fs from 'fs-extra';\n\n/**\n * Source information on a construct (class fqn and version)\n */\nexport interface ConstructInfo {\n readonly fqn: string;\n readonly version: string;\n}\n\n/**\n * A node in the construct tree.\n */\nexport interface ConstructTreeNode {\n readonly id: string;\n readonly path: string;\n readonly children?: { [key: string]: ConstructTreeNode };\n readonly attributes?: { [key: string]: any };\n\n /**\n * Information on the construct class that led to this node, if available\n */\n readonly constructInfo?: ConstructInfo;\n}\n\n/**\n * Whether the provided predicate is true for at least one element in the construct (sub-)tree.\n */\nexport function some(node: ConstructTreeNode | undefined, predicate: (n: ConstructTreeNode) => boolean): boolean {\n return node != null && (predicate(node) || findInChildren());\n\n function findInChildren(): boolean {\n return Object.values(node?.children ?? {}).some(child => some(child, predicate));\n }\n}\n\nexport async function loadTree(assembly: CloudAssembly, trace: (msg: string) => Promise<void>): Promise<ConstructTreeNode | undefined > {\n try {\n const outdir = assembly.directory;\n const fileName = assembly.tree()?.file;\n return fileName ? fs.readJSONSync(path.join(outdir, fileName)).tree : ({} as ConstructTreeNode);\n } catch (e) {\n await trace(`Failed to get tree.json file: ${e}. Proceeding with empty tree.`);\n return undefined;\n }\n}\n\nexport function loadTreeFromDir(outdir: string, trace: (msg: string) => void): ConstructTreeNode | undefined {\n try {\n return fs.readJSONSync(path.join(outdir, 'tree.json')).tree;\n } catch (e) {\n trace(`Failed to get tree.json file: ${e}. Proceeding with empty tree.`);\n return undefined;\n }\n}\n", "import { format } from 'util';\nimport type * as cxapi from '@aws-cdk/cx-api';\nimport * as chalk from 'chalk';\nimport type { SDK } from './aws-auth';\nimport {\n BOOTSTRAP_VARIANT_PARAMETER,\n BOOTSTRAP_VERSION_OUTPUT,\n BUCKET_DOMAIN_NAME_OUTPUT,\n BUCKET_NAME_OUTPUT,\n DEFAULT_BOOTSTRAP_VARIANT,\n REPOSITORY_NAME_OUTPUT,\n} from './bootstrap/bootstrap-props';\nimport type { CloudFormationStack } from './cloudformation';\nimport { stabilizeStack } from './deployments/cfn-api';\nimport { IO, type IoHelper } from './io/private';\nimport { ToolkitError } from './toolkit-error';\n\nexport const DEFAULT_TOOLKIT_STACK_NAME = 'CDKToolkit';\n\n/**\n * Information on the Bootstrap stack of the environment we're deploying to.\n *\n * This class serves to:\n *\n * - Inspect the bootstrap stack, and return various properties of it for successful\n * asset deployment (in case of legacy-synthesized stacks).\n * - Validate the version of the target environment, and nothing else (in case of\n * default-synthesized stacks).\n *\n * An object of this type might represent a bootstrap stack that could not be found.\n * This is not an issue unless any members are used that require the bootstrap stack\n * to have been found, in which case an error is thrown (default-synthesized stacks\n * should never run into this as they don't need information from the bootstrap\n * stack, all information is already encoded into the Cloud Assembly Manifest).\n *\n * Nevertheless, an instance of this class exists to serve as a cache for SSM\n * parameter lookups (otherwise, the \"bootstrap stack version\" parameter would\n * need to be read repeatedly).\n *\n * Called \"ToolkitInfo\" for historical reasons.\n *\n */\nexport abstract class ToolkitInfo {\n public static determineName(overrideName?: string) {\n return overrideName ?? DEFAULT_TOOLKIT_STACK_NAME;\n }\n\n public static async lookup(\n environment: cxapi.Environment,\n sdk: SDK,\n ioHelper: IoHelper,\n stackName: string | undefined,\n ): Promise<ToolkitInfo> {\n const cfn = sdk.cloudFormation();\n stackName = ToolkitInfo.determineName(stackName);\n try {\n const stack = await stabilizeStack(cfn, ioHelper, stackName);\n if (!stack) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(\n format(\n \"The environment %s doesn't have the CDK toolkit stack (%s) installed. Use %s to setup your environment for use with the toolkit.\",\n environment.name,\n stackName,\n chalk.blue(`cdk bootstrap \"${environment.name}\"`),\n ),\n ));\n return ToolkitInfo.bootstrapStackNotFoundInfo(stackName);\n }\n if (stack.stackStatus.isCreationFailure) {\n // Treat a \"failed to create\" bootstrap stack as an absent one.\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(\n format(\n 'The environment %s has a CDK toolkit stack (%s) that failed to create. Use %s to try provisioning it again.',\n environment.name,\n stackName,\n chalk.blue(`cdk bootstrap \"${environment.name}\"`),\n ),\n ));\n return ToolkitInfo.bootstrapStackNotFoundInfo(stackName);\n }\n\n return new ExistingToolkitInfo(stack);\n } catch (e: any) {\n return ToolkitInfo.bootstrapStackLookupError(stackName, e);\n }\n }\n\n public static fromStack(stack: CloudFormationStack): ToolkitInfo {\n return new ExistingToolkitInfo(stack);\n }\n\n public static bootstrapStackNotFoundInfo(stackName: string): ToolkitInfo {\n return new BootstrapStackNotFoundInfo(\n stackName,\n \"This deployment requires a bootstrap stack with a known name; pass '--toolkit-stack-name' or switch to using the 'DefaultStackSynthesizer' (see https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html)\",\n );\n }\n\n public static bootstrapStackLookupError(stackName: string, e: Error): ToolkitInfo {\n return new BootstrapStackNotFoundInfo(\n stackName,\n `This deployment requires a bootstrap stack with a known name, but during its lookup the following error occurred: ${e}; pass \\'--toolkit-stack-name\\' or switch to using the \\'DefaultStackSynthesizer\\' (see https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html)`,\n );\n }\n\n public abstract readonly found: boolean;\n public abstract readonly bucketUrl: string;\n public abstract readonly bucketName: string;\n public abstract readonly repositoryName: string;\n public abstract readonly version: number;\n public abstract readonly variant: string;\n public abstract readonly bootstrapStack: CloudFormationStack;\n public abstract readonly stackName: string;\n\n constructor() {\n }\n}\n\n/**\n * Returned when a bootstrap stack is found\n */\nclass ExistingToolkitInfo extends ToolkitInfo {\n public readonly found = true;\n\n constructor(public readonly bootstrapStack: CloudFormationStack) {\n super();\n }\n\n public get bucketUrl() {\n return `https://${this.requireOutput(BUCKET_DOMAIN_NAME_OUTPUT)}`;\n }\n\n public get bucketName() {\n return this.requireOutput(BUCKET_NAME_OUTPUT);\n }\n\n public get repositoryName() {\n return this.requireOutput(REPOSITORY_NAME_OUTPUT);\n }\n\n public get version() {\n return parseInt(this.bootstrapStack.outputs[BOOTSTRAP_VERSION_OUTPUT] ?? '0', 10);\n }\n\n public get variant() {\n return this.bootstrapStack.parameters[BOOTSTRAP_VARIANT_PARAMETER] ?? DEFAULT_BOOTSTRAP_VARIANT;\n }\n\n public get parameters(): Record<string, string> {\n return this.bootstrapStack.parameters ?? {};\n }\n\n public get terminationProtection(): boolean {\n return this.bootstrapStack.terminationProtection ?? false;\n }\n\n public get stackName(): string {\n return this.bootstrapStack.stackName;\n }\n\n /**\n * Prepare an ECR repository for uploading to using Docker\n *\n */\n private requireOutput(output: string): string {\n if (!(output in this.bootstrapStack.outputs)) {\n throw new ToolkitError(\n `The CDK toolkit stack (${this.bootstrapStack.stackName}) does not have an output named ${output}. Use 'cdk bootstrap' to correct this.`,\n );\n }\n return this.bootstrapStack.outputs[output];\n }\n}\n\n/**\n * Returned when a bootstrap stack could not be found\n *\n * This is not an error in principle, UNTIL one of the members is called that requires\n * the bootstrap stack to have been found, in which case the lookup error is still thrown\n * belatedly.\n *\n * The errors below serve as a last stop-gap message--normally calling code should have\n * checked `toolkit.found` and produced an appropriate error message.\n */\nclass BootstrapStackNotFoundInfo extends ToolkitInfo {\n public readonly found = false;\n\n constructor(\n public readonly stackName: string,\n private readonly errorMessage: string,\n ) {\n super();\n }\n\n public get bootstrapStack(): CloudFormationStack {\n throw new ToolkitError(this.errorMessage);\n }\n\n public get bucketUrl(): string {\n throw new ToolkitError(this.errorMessage);\n }\n\n public get bucketName(): string {\n throw new ToolkitError(this.errorMessage);\n }\n\n public get repositoryName(): string {\n throw new ToolkitError(this.errorMessage);\n }\n\n public get version(): number {\n throw new ToolkitError(this.errorMessage);\n }\n\n public get variant(): string {\n throw new ToolkitError(this.errorMessage);\n }\n\n public prepareEcrRepository(): Promise<EcrRepositoryInfo> {\n throw new ToolkitError(this.errorMessage);\n }\n}\n\nexport interface EcrRepositoryInfo {\n repositoryUri: string;\n}\n\nexport interface EcrCredentials {\n username: string;\n password: string;\n endpoint: string;\n}\n", "import type { Environment } from '@aws-cdk/cx-api';\nimport { formatErrorMessage } from '../../util';\nimport type { SDK } from '../aws-auth';\nimport { IO, type IoHelper } from '../io/private';\nimport { Notices } from '../notices';\nimport { ToolkitError } from '../toolkit-error';\nimport { type EcrRepositoryInfo, ToolkitInfo } from '../toolkit-info';\n\n/**\n * Registry class for `EnvironmentResources`.\n *\n * The state management of this class is a bit non-standard. We want to cache\n * data related to toolkit stacks and SSM parameters, but we are not in charge\n * of ensuring caching of SDKs. Since `EnvironmentResources` needs an SDK to\n * function, we treat it as an ephemeral class, and store the actual cached data\n * in `EnvironmentResourcesRegistry`.\n */\nexport class EnvironmentResourcesRegistry {\n private readonly cache = new Map<string, EnvironmentCache>();\n\n constructor(private readonly toolkitStackName?: string) {\n }\n\n public for(resolvedEnvironment: Environment, sdk: SDK, ioHelper: IoHelper) {\n const key = `${resolvedEnvironment.account}:${resolvedEnvironment.region}`;\n let envCache = this.cache.get(key);\n if (!envCache) {\n envCache = emptyCache();\n this.cache.set(key, envCache);\n }\n return new EnvironmentResources(resolvedEnvironment, sdk, ioHelper, envCache, this.toolkitStackName);\n }\n}\n\n/**\n * Interface with the account and region we're deploying into\n *\n * Manages lookups for bootstrapped resources, falling back to the legacy \"CDK Toolkit\"\n * original bootstrap stack if necessary.\n *\n * The state management of this class is a bit non-standard. We want to cache\n * data related to toolkit stacks and SSM parameters, but we are not in charge\n * of ensuring caching of SDKs. Since `EnvironmentResources` needs an SDK to\n * function, we treat it as an ephemeral class, and store the actual cached data\n * in `EnvironmentResourcesRegistry`.\n */\nexport class EnvironmentResources {\n constructor(\n public readonly environment: Environment,\n private readonly sdk: SDK,\n private readonly ioHelper: IoHelper,\n private readonly cache: EnvironmentCache,\n private readonly toolkitStackName?: string,\n ) {\n }\n\n /**\n * Look up the toolkit for a given environment, using a given SDK\n */\n public async lookupToolkit() {\n if (!this.cache.toolkitInfo) {\n this.cache.toolkitInfo = await ToolkitInfo.lookup(this.environment, this.sdk, this.ioHelper, this.toolkitStackName);\n }\n return this.cache.toolkitInfo;\n }\n\n /**\n * Validate that the bootstrap stack version matches or exceeds the expected version\n *\n * Use the SSM parameter name to read the version number if given, otherwise use the version\n * discovered on the bootstrap stack.\n *\n * Pass in the SSM parameter name so we can cache the lookups an don't need to do the same\n * lookup again and again for every artifact.\n */\n public async validateVersion(expectedVersion: number | undefined, ssmParameterName: string | undefined) {\n if (expectedVersion === undefined) {\n // No requirement\n return;\n }\n const defExpectedVersion = expectedVersion;\n\n if (ssmParameterName !== undefined) {\n try {\n doValidate(await this.versionFromSsmParameter(ssmParameterName), this.environment);\n return;\n } catch (e: any) {\n if (e.name !== 'AccessDeniedException') {\n throw e;\n }\n\n // This is a fallback! The bootstrap template that goes along with this change introduces\n // a new 'ssm:GetParameter' permission, but when run using the previous bootstrap template we\n // won't have the permissions yet to read the version, so we won't be able to show the\n // message telling the user they need to update! When we see an AccessDeniedException, fall\n // back to the version we read from Stack Outputs; but ONLY if the version we discovered via\n // outputs is legitimately an old version. If it's newer than that, something else must be broken,\n // so let it fail as it would if we didn't have this fallback.\n const bootstrapStack = await this.lookupToolkit();\n if (bootstrapStack.found && bootstrapStack.version < BOOTSTRAP_TEMPLATE_VERSION_INTRODUCING_GETPARAMETER) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_WARN.msg(\n `Could not read SSM parameter ${ssmParameterName}: ${formatErrorMessage(e)}, falling back to version from ${bootstrapStack}`,\n ));\n doValidate(bootstrapStack.version, this.environment);\n return;\n }\n\n throw new ToolkitError(\n `This CDK deployment requires bootstrap stack version '${expectedVersion}', but during the confirmation via SSM parameter ${ssmParameterName} the following error occurred: ${e}`,\n );\n }\n }\n\n // No SSM parameter\n const bootstrapStack = await this.lookupToolkit();\n doValidate(bootstrapStack.version, this.environment);\n\n function doValidate(version: number, environment: Environment) {\n const notices = Notices.get();\n if (notices) {\n // if `Notices` hasn't been initialized there is probably a good\n // reason for it. handle gracefully.\n notices.addBootstrappedEnvironment({ bootstrapStackVersion: version, environment });\n }\n if (defExpectedVersion > version) {\n throw new ToolkitError(\n `This CDK deployment requires bootstrap stack version '${expectedVersion}', found '${version}'. Please run 'cdk bootstrap'.`,\n );\n }\n }\n }\n\n /**\n * Read a version from an SSM parameter, cached\n */\n public async versionFromSsmParameter(parameterName: string): Promise<number> {\n const existing = this.cache.ssmParameters.get(parameterName);\n if (existing !== undefined) {\n return existing;\n }\n\n const ssm = this.sdk.ssm();\n\n try {\n const result = await ssm.getParameter({ Name: parameterName });\n\n const asNumber = parseInt(`${result.Parameter?.Value}`, 10);\n if (isNaN(asNumber)) {\n throw new ToolkitError(`SSM parameter ${parameterName} not a number: ${result.Parameter?.Value}`);\n }\n\n this.cache.ssmParameters.set(parameterName, asNumber);\n return asNumber;\n } catch (e: any) {\n if (e.name === 'ParameterNotFound') {\n throw new ToolkitError(\n `SSM parameter ${parameterName} not found. Has the environment been bootstrapped? Please run \\'cdk bootstrap\\' (see https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html)`,\n );\n }\n throw e;\n }\n }\n\n public async prepareEcrRepository(repositoryName: string): Promise<EcrRepositoryInfo> {\n if (!this.sdk) {\n throw new ToolkitError('ToolkitInfo needs to have been initialized with an sdk to call prepareEcrRepository');\n }\n const ecr = this.sdk.ecr();\n\n // check if repo already exists\n try {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${repositoryName}: checking if ECR repository already exists`));\n const describeResponse = await ecr.describeRepositories({\n repositoryNames: [repositoryName],\n });\n const existingRepositoryUri = describeResponse.repositories![0]?.repositoryUri;\n if (existingRepositoryUri) {\n return { repositoryUri: existingRepositoryUri };\n }\n } catch (e: any) {\n if (e.name !== 'RepositoryNotFoundException') {\n throw e;\n }\n }\n\n // create the repo (tag it so it will be easier to garbage collect in the future)\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${repositoryName}: creating ECR repository`));\n const assetTag = { Key: 'awscdk:asset', Value: 'true' };\n const response = await ecr.createRepository({\n repositoryName,\n tags: [assetTag],\n });\n const repositoryUri = response.repository?.repositoryUri;\n if (!repositoryUri) {\n throw new ToolkitError(`CreateRepository did not return a repository URI for ${repositoryUri}`);\n }\n\n // configure image scanning on push (helps in identifying software vulnerabilities, no additional charge)\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${repositoryName}: enable image scanning`));\n await ecr.putImageScanningConfiguration({\n repositoryName,\n imageScanningConfiguration: { scanOnPush: true },\n });\n\n return { repositoryUri };\n }\n}\n\nexport class NoBootstrapStackEnvironmentResources extends EnvironmentResources {\n constructor(environment: Environment, sdk: SDK, ioHelper: IoHelper) {\n super(environment, sdk, ioHelper, emptyCache());\n }\n\n /**\n * Look up the toolkit for a given environment, using a given SDK\n */\n public async lookupToolkit(): Promise<ToolkitInfo> {\n throw new ToolkitError(\n 'Trying to perform an operation that requires a bootstrap stack; you should not see this error, this is a bug in the CDK CLI.',\n );\n }\n}\n\n/**\n * Data that is cached on a per-environment level\n *\n * This cache may be shared between different instances of the `EnvironmentResources` class.\n */\ninterface EnvironmentCache {\n readonly ssmParameters: Map<string, number>;\n toolkitInfo?: ToolkitInfo;\n}\n\nfunction emptyCache(): EnvironmentCache {\n return {\n ssmParameters: new Map(),\n toolkitInfo: undefined,\n };\n}\n\n/**\n * The bootstrap template version that introduced ssm:GetParameter\n */\nconst BOOTSTRAP_TEMPLATE_VERSION_INTRODUCING_GETPARAMETER = 5;\n", "import { type Environment, EnvironmentPlaceholders } from '@aws-cdk/cx-api';\nimport type { Branded } from '../../util';\nimport type { SdkProvider } from '../aws-auth';\nimport { Mode } from '../plugin';\n\n/**\n * Replace the {ACCOUNT} and {REGION} placeholders in all strings found in a complex object.\n */\nexport async function replaceEnvPlaceholders<A extends Record<string, string | undefined>>(\n object: A,\n env: Environment,\n sdkProvider: SdkProvider,\n): Promise<{[k in keyof A]: StringWithoutPlaceholders | undefined}> {\n return EnvironmentPlaceholders.replaceAsync(object, {\n accountId: () => Promise.resolve(env.account),\n region: () => Promise.resolve(env.region),\n partition: async () => {\n // There's no good way to get the partition!\n // We should have had it already, except we don't.\n //\n // Best we can do is ask the \"base credentials\" for this environment for their partition. Cross-partition\n // AssumeRole'ing will never work anyway, so this answer won't be wrong (it will just be slow!)\n return (await sdkProvider.baseCredentialsPartition(env, Mode.ForReading)) ?? 'aws';\n },\n });\n}\n\nexport type StringWithoutPlaceholders = Branded<string, 'NoPlaceholders'>;\n", "import type * as cxapi from '@aws-cdk/cx-api';\nimport { ToolkitError } from '../toolkit-error';\nimport type { EnvironmentResources } from './environment-resources';\nimport { EnvironmentResourcesRegistry } from './environment-resources';\nimport type { StringWithoutPlaceholders } from './placeholders';\nimport { replaceEnvPlaceholders } from './placeholders';\nimport { formatErrorMessage } from '../../util';\nimport type { SDK, CredentialsOptions, SdkForEnvironment, SdkProvider } from '../aws-auth';\nimport { IO, type IoHelper } from '../io/private';\nimport { Mode } from '../plugin';\n\n/**\n * Access particular AWS resources, based on information from the CX manifest\n *\n * It is not possible to grab direct access to AWS credentials; 9 times out of 10\n * we have to allow for role assumption, and role assumption can only work if\n * there is a CX Manifest that contains a role ARN.\n *\n * This class exists so new code isn't tempted to go and get SDK credentials directly.\n */\nexport class EnvironmentAccess {\n private readonly sdkCache = new Map<string, SdkForEnvironment>();\n private readonly environmentResources: EnvironmentResourcesRegistry;\n private readonly ioHelper: IoHelper;\n\n constructor(private readonly sdkProvider: SdkProvider, toolkitStackName: string, ioHelper: IoHelper) {\n this.environmentResources = new EnvironmentResourcesRegistry(toolkitStackName);\n this.ioHelper = ioHelper;\n }\n\n /**\n * Resolves the environment for a stack.\n */\n public async resolveStackEnvironment(stack: cxapi.CloudFormationStackArtifact): Promise<cxapi.Environment> {\n return this.sdkProvider.resolveEnvironment(stack.environment);\n }\n\n /**\n * Get an SDK to access the given stack's environment for stack operations\n *\n * Will ask plugins for readonly credentials if available, use the default\n * AWS credentials if not.\n *\n * Will assume the deploy role if configured on the stack. Check the default `deploy-role`\n * policies to see what you can do with this role.\n */\n public async accessStackForReadOnlyStackOperations(stack: cxapi.CloudFormationStackArtifact): Promise<TargetEnvironment> {\n return this.accessStackForStackOperations(stack, Mode.ForReading);\n }\n\n /**\n * Get an SDK to access the given stack's environment for stack operations\n *\n * Will ask plugins for mutating credentials if available, use the default AWS\n * credentials if not. The `mode` parameter is only used for querying\n * plugins.\n *\n * Will assume the deploy role if configured on the stack. Check the default `deploy-role`\n * policies to see what you can do with this role.\n */\n public async accessStackForMutableStackOperations(stack: cxapi.CloudFormationStackArtifact): Promise<TargetEnvironment> {\n return this.accessStackForStackOperations(stack, Mode.ForWriting);\n }\n\n /**\n * Get an SDK to access the given stack's environment for environmental lookups\n *\n * Will use a plugin if available, use the default AWS credentials if not.\n * The `mode` parameter is only used for querying plugins.\n *\n * Will assume the lookup role if configured on the stack. Check the default `lookup-role`\n * policies to see what you can do with this role. It can generally read everything\n * in the account that does not require KMS access.\n *\n * ---\n *\n * For backwards compatibility reasons, there are some scenarios that are handled here:\n *\n * 1. The lookup role may not exist (it was added in bootstrap stack version 7). If so:\n * a. Return the default credentials if the default credentials are for the stack account\n * (you will notice this as `isFallbackCredentials=true`).\n * b. Throw an error if the default credentials are not for the stack account.\n *\n * 2. The lookup role may not have the correct permissions (for example, ReadOnlyAccess was added in\n * bootstrap stack version 8); the stack will have a minimum version number on it.\n * a. If it does not we throw an error which should be handled in the calling\n * function (and fallback to use a different role, etc)\n *\n * Upon success, caller will have an SDK for the right account, which may or may not have\n * the right permissions.\n */\n public async accessStackForLookup(stack: cxapi.CloudFormationStackArtifact): Promise<TargetEnvironment> {\n if (!stack.environment) {\n throw new ToolkitError(`The stack ${stack.displayName} does not have an environment`);\n }\n\n const lookupEnv = await this.prepareSdk({\n environment: stack.environment,\n mode: Mode.ForReading,\n assumeRoleArn: stack.lookupRole?.arn,\n assumeRoleExternalId: stack.lookupRole?.assumeRoleExternalId,\n assumeRoleAdditionalOptions: stack.lookupRole?.assumeRoleAdditionalOptions,\n });\n\n // if we succeed in assuming the lookup role, make sure we have the correct bootstrap stack version\n if (lookupEnv.didAssumeRole && stack.lookupRole?.bootstrapStackVersionSsmParameter && stack.lookupRole.requiresBootstrapStackVersion) {\n const version = await lookupEnv.resources.versionFromSsmParameter(stack.lookupRole.bootstrapStackVersionSsmParameter);\n if (version < stack.lookupRole.requiresBootstrapStackVersion) {\n throw new ToolkitError(`Bootstrap stack version '${stack.lookupRole.requiresBootstrapStackVersion}' is required, found version '${version}'. To get rid of this error, please upgrade to bootstrap version >= ${stack.lookupRole.requiresBootstrapStackVersion}`);\n }\n }\n if (lookupEnv.isFallbackCredentials) {\n const arn = await lookupEnv.replacePlaceholders(stack.lookupRole?.arn);\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_WARN.msg(`Lookup role ${arn} was not assumed. Proceeding with default credentials.`));\n }\n return lookupEnv;\n }\n\n /**\n * Get an SDK to access the given stack's environment for reading stack attributes\n *\n * Will use a plugin if available, use the default AWS credentials if not.\n * The `mode` parameter is only used for querying plugins.\n *\n * Will try to assume the lookup role if given, will use the regular stack operations\n * access (deploy-role) otherwise. When calling this, you should assume that you will get\n * the least privileged role, so don't try to use it for anything the `deploy-role`\n * wouldn't be able to do. Also you cannot rely on being able to read encrypted anything.\n */\n public async accessStackForLookupBestEffort(stack: cxapi.CloudFormationStackArtifact): Promise<TargetEnvironment> {\n if (!stack.environment) {\n throw new ToolkitError(`The stack ${stack.displayName} does not have an environment`);\n }\n\n try {\n return await this.accessStackForLookup(stack);\n } catch (e: any) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_WARN.msg(`${formatErrorMessage(e)}`));\n }\n return this.accessStackForStackOperations(stack, Mode.ForReading);\n }\n\n /**\n * Get an SDK to access the given stack's environment for stack operations\n *\n * Will use a plugin if available, use the default AWS credentials if not.\n * The `mode` parameter is only used for querying plugins.\n *\n * Will assume the deploy role if configured on the stack. Check the default `deploy-role`\n * policies to see what you can do with this role.\n */\n private async accessStackForStackOperations(stack: cxapi.CloudFormationStackArtifact, mode: Mode): Promise<TargetEnvironment> {\n if (!stack.environment) {\n throw new ToolkitError(`The stack ${stack.displayName} does not have an environment`);\n }\n\n return this.prepareSdk({\n environment: stack.environment,\n mode,\n assumeRoleArn: stack.assumeRoleArn,\n assumeRoleExternalId: stack.assumeRoleExternalId,\n assumeRoleAdditionalOptions: stack.assumeRoleAdditionalOptions,\n });\n }\n\n /**\n * Prepare an SDK for use in the given environment and optionally with a role assumed.\n */\n private async prepareSdk(\n options: PrepareSdkRoleOptions,\n ): Promise<TargetEnvironment> {\n const resolvedEnvironment = await this.sdkProvider.resolveEnvironment(options.environment);\n\n // Substitute any placeholders with information about the current environment\n const { assumeRoleArn } = await replaceEnvPlaceholders({\n assumeRoleArn: options.assumeRoleArn,\n }, resolvedEnvironment, this.sdkProvider);\n\n const stackSdk = await this.cachedSdkForEnvironment(resolvedEnvironment, options.mode, {\n assumeRoleArn,\n assumeRoleExternalId: options.assumeRoleExternalId,\n assumeRoleAdditionalOptions: options.assumeRoleAdditionalOptions,\n });\n\n return {\n sdk: stackSdk.sdk,\n resolvedEnvironment,\n resources: this.environmentResources.for(resolvedEnvironment, stackSdk.sdk, this.ioHelper),\n // If we asked for a role, did not successfully assume it, and yet got here without an exception: that\n // means we must have fallback credentials.\n isFallbackCredentials: !stackSdk.didAssumeRole && !!assumeRoleArn,\n didAssumeRole: stackSdk.didAssumeRole,\n replacePlaceholders: async <A extends string | undefined>(str: A) => {\n const ret = await replaceEnvPlaceholders({ str }, resolvedEnvironment, this.sdkProvider);\n return ret.str;\n },\n };\n }\n\n private async cachedSdkForEnvironment(\n environment: cxapi.Environment,\n mode: Mode,\n options?: CredentialsOptions,\n ) {\n const cacheKeyElements = [\n environment.account,\n environment.region,\n `${mode}`,\n options?.assumeRoleArn ?? '',\n options?.assumeRoleExternalId ?? '',\n ];\n\n if (options?.assumeRoleAdditionalOptions) {\n cacheKeyElements.push(JSON.stringify(options.assumeRoleAdditionalOptions));\n }\n\n const cacheKey = cacheKeyElements.join(':');\n const existing = this.sdkCache.get(cacheKey);\n if (existing) {\n return existing;\n }\n const ret = await this.sdkProvider.forEnvironment(environment, mode, options);\n this.sdkCache.set(cacheKey, ret);\n return ret;\n }\n}\n\n/**\n * SDK obtained by assuming the deploy role\n * for a given environment\n */\nexport interface TargetEnvironment {\n /**\n * The SDK for the given environment\n */\n readonly sdk: SDK;\n\n /**\n * The resolved environment for the stack\n * (no more 'unknown-account/unknown-region')\n */\n readonly resolvedEnvironment: cxapi.Environment;\n\n /**\n * Access class for environmental resources to help the deployment\n */\n readonly resources: EnvironmentResources;\n\n /**\n * Whether or not we assumed a role in the process of getting these credentials\n */\n readonly didAssumeRole: boolean;\n\n /**\n * Whether or not these are fallback credentials\n *\n * Fallback credentials means that assuming the intended role failed, but the\n * base credentials happen to be for the right account so we just picked those\n * and hope the future SDK calls succeed.\n *\n * This is a backwards compatibility mechanism from around the time we introduced\n * deployment roles.\n */\n readonly isFallbackCredentials: boolean;\n\n /**\n * Replace environment placeholders according to the current environment\n */\n replacePlaceholders(x: string | undefined): Promise<StringWithoutPlaceholders | undefined>;\n}\n\ninterface PrepareSdkRoleOptions {\n readonly environment: cxapi.Environment;\n readonly mode: Mode;\n readonly assumeRoleArn?: string;\n readonly assumeRoleExternalId?: string;\n readonly assumeRoleAdditionalOptions?: { [key: string]: any };\n}\n", "import type { BootstrappingParameters } from './bootstrap-props';\nimport { BUCKET_DOMAIN_NAME_OUTPUT, BUCKET_NAME_OUTPUT } from './bootstrap-props';\n\nexport function legacyBootstrapTemplate(params: BootstrappingParameters): any {\n return {\n Description: 'The CDK Toolkit Stack. It was created by `cdk bootstrap` and manages resources necessary for managing your Cloud Applications with AWS CDK.',\n Conditions: {\n UsePublicAccessBlockConfiguration: {\n 'Fn::Equals': [\n params.publicAccessBlockConfiguration || params.publicAccessBlockConfiguration === undefined ? 'true' : 'false',\n 'true',\n ],\n },\n },\n Resources: {\n StagingBucket: {\n Type: 'AWS::S3::Bucket',\n Properties: {\n BucketName: params.bucketName,\n AccessControl: 'Private',\n BucketEncryption: {\n ServerSideEncryptionConfiguration: [{\n ServerSideEncryptionByDefault: {\n SSEAlgorithm: 'aws:kms',\n KMSMasterKeyID: params.kmsKeyId,\n },\n }],\n },\n PublicAccessBlockConfiguration: {\n 'Fn::If': [\n 'UsePublicAccessBlockConfiguration',\n {\n BlockPublicAcls: true,\n BlockPublicPolicy: true,\n IgnorePublicAcls: true,\n RestrictPublicBuckets: true,\n },\n { Ref: 'AWS::NoValue' },\n ],\n },\n },\n },\n StagingBucketPolicy: {\n Type: 'AWS::S3::BucketPolicy',\n Properties: {\n Bucket: { Ref: 'StagingBucket' },\n PolicyDocument: {\n Id: 'AccessControl',\n Version: '2012-10-17',\n Statement: [\n {\n Sid: 'AllowSSLRequestsOnly',\n Action: 's3:*',\n Effect: 'Deny',\n Resource: [\n { 'Fn::Sub': '${StagingBucket.Arn}' },\n { 'Fn::Sub': '${StagingBucket.Arn}/*' },\n ],\n Condition: {\n Bool: { 'aws:SecureTransport': 'false' },\n },\n Principal: '*',\n },\n ],\n },\n },\n },\n },\n Outputs: {\n [BUCKET_NAME_OUTPUT]: {\n Description: 'The name of the S3 bucket owned by the CDK toolkit stack',\n Value: { Ref: 'StagingBucket' },\n },\n [BUCKET_DOMAIN_NAME_OUTPUT]: {\n Description: 'The domain name of the S3 bucket owned by the CDK toolkit stack',\n Value: { 'Fn::GetAtt': ['StagingBucket', 'RegionalDomainName'] },\n },\n },\n };\n}\n", "import * as path from 'path';\nimport { format } from 'util';\nimport * as cxapi from '@aws-cdk/cx-api';\nimport * as fs from 'fs-extra';\nimport type { SdkProvider } from '../aws-auth';\nimport type { Settings } from '../settings';\n\n/**\n * If we don't have region/account defined in context, we fall back to the default SDK behavior\n * where region is retrieved from ~/.aws/config and account is based on default credentials provider\n * chain and then STS is queried.\n *\n * This is done opportunistically: for example, if we can't access STS for some reason or the region\n * is not configured, the context value will be 'null' and there could failures down the line. In\n * some cases, synthesis does not require region/account information at all, so that might be perfectly\n * fine in certain scenarios.\n *\n * @param context The context key/value bash.\n */\nexport async function prepareDefaultEnvironment(\n aws: SdkProvider,\n debugFn: (msg: string) => Promise<void>,\n): Promise<{ [key: string]: string }> {\n const env: { [key: string]: string } = { };\n\n env[cxapi.DEFAULT_REGION_ENV] = aws.defaultRegion;\n await debugFn(`Setting \"${cxapi.DEFAULT_REGION_ENV}\" environment variable to ${env[cxapi.DEFAULT_REGION_ENV]}`);\n\n const accountId = (await aws.defaultAccount())?.accountId;\n if (accountId) {\n env[cxapi.DEFAULT_ACCOUNT_ENV] = accountId;\n await debugFn(`Setting \"${cxapi.DEFAULT_ACCOUNT_ENV}\" environment variable to ${env[cxapi.DEFAULT_ACCOUNT_ENV]}`);\n }\n\n return env;\n}\n\n/**\n * Settings related to synthesis are read from context.\n * The merging of various configuration sources like cli args or cdk.json has already happened.\n * We now need to set the final values to the context.\n */\nexport async function prepareContext(\n settings: Settings,\n context: {[key: string]: any},\n env: { [key: string]: string | undefined},\n debugFn: (msg: string) => Promise<void>,\n) {\n const debugMode: boolean = settings.get(['debug']) ?? true;\n if (debugMode) {\n env.CDK_DEBUG = 'true';\n }\n\n const pathMetadata: boolean = settings.get(['pathMetadata']) ?? true;\n if (pathMetadata) {\n context[cxapi.PATH_METADATA_ENABLE_CONTEXT] = true;\n }\n\n const assetMetadata: boolean = settings.get(['assetMetadata']) ?? true;\n if (assetMetadata) {\n context[cxapi.ASSET_RESOURCE_METADATA_ENABLED_CONTEXT] = true;\n }\n\n const versionReporting: boolean = settings.get(['versionReporting']) ?? true;\n if (versionReporting) {\n context[cxapi.ANALYTICS_REPORTING_ENABLED_CONTEXT] = true;\n }\n // We need to keep on doing this for framework version from before this flag was deprecated.\n if (!versionReporting) {\n context['aws:cdk:disable-version-reporting'] = true;\n }\n\n const stagingEnabled = settings.get(['staging']) ?? true;\n if (!stagingEnabled) {\n context[cxapi.DISABLE_ASSET_STAGING_CONTEXT] = true;\n }\n\n const bundlingStacks = settings.get(['bundlingStacks']) ?? ['**'];\n context[cxapi.BUNDLING_STACKS] = bundlingStacks;\n\n await debugFn(format('context:', context));\n\n return context;\n}\n\nexport function spaceAvailableForContext(env: { [key: string]: string }, limit: number) {\n const size = (value: string) => value != null ? Buffer.byteLength(value) : 0;\n\n const usedSpace = Object.entries(env)\n .map(([k, v]) => k === cxapi.CONTEXT_ENV ? size(k) : size(k) + size(v))\n .reduce((a, b) => a + b, 0);\n\n return Math.max(0, limit - usedSpace);\n}\n\n/**\n * Guess the executable from the command-line argument\n *\n * Only do this if the file is NOT marked as executable. If it is,\n * we'll defer to the shebang inside the file itself.\n *\n * If we're on Windows, we ALWAYS take the handler, since it's hard to\n * verify if registry associations have or have not been set up for this\n * file type, so we'll assume the worst and take control.\n */\nexport async function guessExecutable(app: string, debugFn: (msg: string) => Promise<void>) {\n const commandLine = appToArray(app);\n if (commandLine.length === 1) {\n let fstat;\n\n try {\n fstat = await fs.stat(commandLine[0]);\n } catch {\n await debugFn(`Not a file: '${commandLine[0]}'. Using '${commandLine}' as command-line`);\n return commandLine;\n }\n\n // eslint-disable-next-line no-bitwise\n const isExecutable = (fstat.mode & fs.constants.X_OK) !== 0;\n const isWindows = process.platform === 'win32';\n\n const handler = EXTENSION_MAP.get(path.extname(commandLine[0]));\n if (handler && (!isExecutable || isWindows)) {\n return handler(commandLine[0]);\n }\n }\n return commandLine;\n}\n\n/**\n * Mapping of extensions to command-line generators\n */\nconst EXTENSION_MAP = new Map<string, CommandGenerator>([\n ['.js', executeNode],\n]);\n\ntype CommandGenerator = (file: string) => string[];\n\n/**\n * Execute the given file with the same 'node' process as is running the current process\n */\nfunction executeNode(scriptFile: string): string[] {\n return [process.execPath, scriptFile];\n}\n\n/**\n * Make sure the 'app' is an array\n *\n * If it's a string, split on spaces as a trivial way of tokenizing the command line.\n */\nfunction appToArray(app: any) {\n return typeof app === 'string' ? app.split(' ') : app;\n}\n", "import type * as cxapi from '@aws-cdk/cx-api';\nimport * as chalk from 'chalk';\nimport { minimatch } from 'minimatch';\nimport { StackCollection } from './stack-collection';\nimport { flatten } from '../../util';\nimport { IO } from '../io/private';\nimport type { IoHelper } from '../io/private/io-helper';\n\nexport interface IStackAssembly {\n /**\n * The directory this CloudAssembly was read from\n */\n directory: string;\n\n /**\n * Select a single stack by its ID\n */\n stackById(stackId: string): StackCollection;\n}\n\n/**\n * When selecting stacks, what other stacks to include because of dependencies\n */\nexport enum ExtendedStackSelection {\n /**\n * Don't select any extra stacks\n */\n None,\n\n /**\n * Include stacks that this stack depends on\n */\n Upstream,\n\n /**\n * Include stacks that depend on this stack\n */\n Downstream,\n}\n\n/**\n * A single Cloud Assembly and the operations we do on it to deploy the artifacts inside\n */\nexport abstract class BaseStackAssembly implements IStackAssembly {\n /**\n * Sanitize a list of stack match patterns\n */\n protected static sanitizePatterns(patterns: string[]): string[] {\n let sanitized = patterns.filter(s => s != null); // filter null/undefined\n sanitized = [...new Set(sanitized)]; // make them unique\n return sanitized;\n }\n\n /**\n * The directory this CloudAssembly was read from\n */\n public readonly directory: string;\n\n /**\n * The IoHelper used for messaging\n */\n protected readonly ioHelper: IoHelper;\n\n constructor(public readonly assembly: cxapi.CloudAssembly, ioHelper: IoHelper) {\n this.directory = assembly.directory;\n this.ioHelper = ioHelper;\n }\n\n /**\n * Select a single stack by its ID\n */\n public stackById(stackId: string) {\n return new StackCollection(this, [this.assembly.getStackArtifact(stackId)]);\n }\n\n protected async selectMatchingStacks(\n stacks: cxapi.CloudFormationStackArtifact[],\n patterns: string[],\n extend: ExtendedStackSelection = ExtendedStackSelection.None,\n ): Promise<StackCollection> {\n const matchingPattern = (pattern: string) => (stack: cxapi.CloudFormationStackArtifact) => minimatch(stack.hierarchicalId, pattern);\n const matchedStacks = flatten(patterns.map(pattern => stacks.filter(matchingPattern(pattern))));\n\n return this.extendStacks(matchedStacks, stacks, extend);\n }\n\n protected async extendStacks(\n matched: cxapi.CloudFormationStackArtifact[],\n all: cxapi.CloudFormationStackArtifact[],\n extend: ExtendedStackSelection = ExtendedStackSelection.None,\n ) {\n const allStacks = new Map<string, cxapi.CloudFormationStackArtifact>();\n for (const stack of all) {\n allStacks.set(stack.hierarchicalId, stack);\n }\n\n const index = indexByHierarchicalId(matched);\n\n switch (extend) {\n case ExtendedStackSelection.Downstream:\n await includeDownstreamStacks(this.ioHelper, index, allStacks);\n break;\n case ExtendedStackSelection.Upstream:\n await includeUpstreamStacks(this.ioHelper, index, allStacks);\n break;\n }\n\n // Filter original array because it is in the right order\n const selectedList = all.filter(s => index.has(s.hierarchicalId));\n\n return new StackCollection(this, selectedList);\n }\n}\n\nfunction indexByHierarchicalId(stacks: cxapi.CloudFormationStackArtifact[]): Map<string, cxapi.CloudFormationStackArtifact> {\n const result = new Map<string, cxapi.CloudFormationStackArtifact>();\n\n for (const stack of stacks) {\n result.set(stack.hierarchicalId, stack);\n }\n\n return result;\n}\n\n/**\n * Calculate the transitive closure of stack dependents.\n *\n * Modifies `selectedStacks` in-place.\n */\nasync function includeDownstreamStacks(\n ioHelper: IoHelper,\n selectedStacks: Map<string, cxapi.CloudFormationStackArtifact>,\n allStacks: Map<string, cxapi.CloudFormationStackArtifact>,\n) {\n const added = new Array<string>();\n\n let madeProgress;\n do {\n madeProgress = false;\n\n for (const [id, stack] of allStacks) {\n // Select this stack if it's not selected yet AND it depends on a stack that's in the selected set\n if (!selectedStacks.has(id) && (stack.dependencies || []).some(dep => selectedStacks.has(dep.id))) {\n selectedStacks.set(id, stack);\n added.push(id);\n madeProgress = true;\n }\n }\n } while (madeProgress);\n\n if (added.length > 0) {\n await ioHelper.notify(IO.DEFAULT_ASSEMBLY_INFO.msg(`Including depending stacks: ${chalk.bold(added.join(', '))}`));\n }\n}\n\n/**\n * Calculate the transitive closure of stack dependencies.\n *\n * Modifies `selectedStacks` in-place.\n */\nasync function includeUpstreamStacks(\n ioHelper: IoHelper,\n selectedStacks: Map<string, cxapi.CloudFormationStackArtifact>,\n allStacks: Map<string, cxapi.CloudFormationStackArtifact>,\n) {\n const added = new Array<string>();\n let madeProgress = true;\n while (madeProgress) {\n madeProgress = false;\n\n for (const stack of selectedStacks.values()) {\n // Select an additional stack if it's not selected yet and a dependency of a selected stack (and exists, obviously)\n for (const dependencyId of stack.dependencies.map(x => x.manifest.displayName ?? x.id)) {\n if (!selectedStacks.has(dependencyId) && allStacks.has(dependencyId)) {\n added.push(dependencyId);\n selectedStacks.set(dependencyId, allStacks.get(dependencyId)!);\n madeProgress = true;\n }\n }\n }\n }\n\n if (added.length > 0) {\n await ioHelper.notify(IO.DEFAULT_ASSEMBLY_INFO.msg(`Including dependency stacks: ${chalk.bold(added.join(', '))}`));\n }\n}\n", "import type * as cxapi from '@aws-cdk/cx-api';\nimport { SynthesisMessageLevel } from '@aws-cdk/cx-api';\nimport { AssemblyError, ToolkitError } from '../toolkit-error';\nimport type { IStackAssembly } from './stack-assembly';\nimport { type StackDetails } from '../../payloads/stack-details';\n\n/**\n * A collection of stacks and related artifacts\n *\n * In practice, not all artifacts in the CloudAssembly are created equal;\n * stacks can be selected independently, but other artifacts such as asset\n * bundles cannot.\n */\nexport class StackCollection {\n constructor(public readonly assembly: IStackAssembly, public readonly stackArtifacts: cxapi.CloudFormationStackArtifact[]) {\n }\n\n public get stackCount() {\n return this.stackArtifacts.length;\n }\n\n public get firstStack() {\n if (this.stackCount < 1) {\n throw new ToolkitError('StackCollection contains no stack artifacts (trying to access the first one)');\n }\n return this.stackArtifacts[0];\n }\n\n public get stackIds(): string[] {\n return this.stackArtifacts.map(s => s.id);\n }\n\n public get hierarchicalIds(): string[] {\n return this.stackArtifacts.map(s => s.hierarchicalId);\n }\n\n public withDependencies(): StackDetails[] {\n const allData: StackDetails[] = [];\n\n for (const stack of this.stackArtifacts) {\n const data: StackDetails = {\n id: stack.displayName ?? stack.id,\n name: stack.stackName,\n environment: stack.environment,\n dependencies: [],\n };\n\n for (const dependencyId of stack.dependencies.map(x => x.id)) {\n if (dependencyId.includes('.assets')) {\n continue;\n }\n\n const depStack = this.assembly.stackById(dependencyId);\n\n if (depStack.firstStack.dependencies.filter((dep) => !(dep.id).includes('.assets')).length > 0) {\n for (const stackDetail of depStack.withDependencies()) {\n data.dependencies.push({\n id: stackDetail.id,\n dependencies: stackDetail.dependencies,\n });\n }\n } else {\n data.dependencies.push({\n id: depStack.firstStack.displayName ?? depStack.firstStack.id,\n dependencies: [],\n });\n }\n }\n\n allData.push(data);\n }\n\n return allData;\n }\n\n public reversed() {\n const arts = [...this.stackArtifacts];\n arts.reverse();\n return new StackCollection(this.assembly, arts);\n }\n\n public filter(predicate: (art: cxapi.CloudFormationStackArtifact) => boolean): StackCollection {\n return new StackCollection(this.assembly, this.stackArtifacts.filter(predicate));\n }\n\n public concat(...others: StackCollection[]): StackCollection {\n return new StackCollection(this.assembly, this.stackArtifacts.concat(...others.map(o => o.stackArtifacts)));\n }\n\n /**\n * Extracts 'aws:cdk:warning|info|error' metadata entries from the stack synthesis\n */\n public async validateMetadata(\n failAt: 'warn' | 'error' | 'none' = 'error',\n logger: (level: 'info' | 'error' | 'warn', msg: cxapi.SynthesisMessage) => Promise<void> = async () => {\n },\n ) {\n let warnings = false;\n let errors = false;\n\n for (const stack of this.stackArtifacts) {\n for (const message of stack.messages) {\n switch (message.level) {\n case SynthesisMessageLevel.WARNING:\n warnings = true;\n await logger('warn', message);\n break;\n case SynthesisMessageLevel.ERROR:\n errors = true;\n await logger('error', message);\n break;\n case SynthesisMessageLevel.INFO:\n await logger('info', message);\n break;\n }\n }\n }\n\n if (errors && failAt != 'none') {\n throw AssemblyError.withStacks('Found errors', this.stackArtifacts);\n }\n\n if (warnings && failAt === 'warn') {\n throw AssemblyError.withStacks('Found warnings (--strict mode)', this.stackArtifacts);\n }\n }\n}\n", "/**\n * Which stacks should be selected from a cloud assembly\n */\nexport enum StackSelectionStrategy {\n /**\n * Returns all stacks in the app regardless of patterns,\n * including stacks inside nested assemblies.\n */\n ALL_STACKS = 'all-stacks',\n\n /**\n * Returns all stacks in the main (top level) assembly only.\n */\n MAIN_ASSEMBLY = 'main-assembly',\n\n /**\n * If the assembly includes a single stack, returns it.\n * Otherwise throws an exception.\n */\n ONLY_SINGLE = 'only-single',\n\n /**\n * Return stacks matched by patterns.\n * If no stacks are found, execution is halted successfully.\n * Most likely you don't want to use this but `StackSelectionStrategy.MUST_MATCH_PATTERN`\n */\n PATTERN_MATCH = 'pattern-match',\n\n /**\n * Return stacks matched by patterns.\n * Throws an exception if the patterns don't match at least one stack in the assembly.\n */\n PATTERN_MUST_MATCH = 'pattern-must-match',\n\n /**\n * Returns if exactly one stack is matched by the pattern(s).\n * Throws an exception if no stack, or more than exactly one stack are matched.\n */\n PATTERN_MUST_MATCH_SINGLE = 'pattern-must-match-single',\n}\n\n/**\n * When selecting stacks, what other stacks to include because of dependencies\n */\nexport enum ExpandStackSelection {\n /**\n * Don't select any extra stacks\n */\n NONE = 'none',\n\n /**\n * Include stacks that this stack depends on\n */\n UPSTREAM = 'upstream',\n\n /**\n * Include stacks that depend on this stack\n */\n DOWNSTREAM = 'downstream',\n\n /**\n * @TODO\n * Include both directions.\n * I.e. stacks that this stack depends on, and stacks that depend on this stack.\n */\n // FULL = 'full',\n}\n\n/**\n * A specification of which stacks should be selected\n */\nexport interface StackSelector {\n /**\n * The behavior if if no selectors are provided.\n */\n strategy: StackSelectionStrategy;\n\n /**\n * A list of patterns to match the stack hierarchical ids\n * Only used with `PATTERN_*` selection strategies.\n */\n patterns?: string[];\n\n /**\n * Expand the selection to upstream/downstream stacks.\n * @default ExpandStackSelection.None only select the specified/matched stacks\n */\n expand?: ExpandStackSelection;\n\n /**\n * By default, we throw an exception if the assembly contains no stacks.\n * Set to `false`, to halt execution for empty assemblies without error.\n *\n * Note that actions can still throw if a stack selection result is empty,\n * but the assembly contains stacks in principle.\n *\n * @default true\n */\n failOnEmpty?: boolean;\n}\n", "import * as os from 'os';\nimport * as fs_path from 'path';\nimport * as fs from 'fs-extra';\nimport { ToolkitError } from './toolkit-error';\nimport * as util from '../util';\n\nexport type SettingsMap = { [key: string]: any };\n\n/**\n * If a context value is an object with this key set to a truthy value, it won't be saved to cdk.context.json\n */\nexport const TRANSIENT_CONTEXT_KEY = '$dontSaveContext';\n\n/**\n * A single bag of settings\n */\nexport class Settings {\n public static mergeAll(...settings: Settings[]): Settings {\n let ret = new Settings();\n for (const setting of settings) {\n ret = ret.merge(setting);\n }\n return ret;\n }\n\n constructor(\n private settings: SettingsMap = {},\n public readonly readOnly = false,\n ) {\n }\n\n public async save(fileName: string): Promise<this> {\n const expanded = expandHomeDir(fileName);\n await fs.writeJson(expanded, stripTransientValues(this.settings), {\n spaces: 2,\n });\n return this;\n }\n\n public get all(): any {\n return this.get([]);\n }\n\n public merge(other: Settings): Settings {\n return new Settings(util.deepMerge(this.settings, other.settings));\n }\n\n public subSettings(keyPrefix: string[]) {\n return new Settings(this.get(keyPrefix) || {}, false);\n }\n\n public makeReadOnly(): Settings {\n return new Settings(this.settings, true);\n }\n\n public clear() {\n if (this.readOnly) {\n throw new ToolkitError('Cannot clear(): settings are readonly');\n }\n this.settings = {};\n }\n\n public get empty(): boolean {\n return Object.keys(this.settings).length === 0;\n }\n\n public get(path: string[]): any {\n return util.deepClone(util.deepGet(this.settings, path));\n }\n\n public set(path: string[], value: any): Settings {\n if (this.readOnly) {\n throw new ToolkitError(`Can't set ${path}: settings object is readonly`);\n }\n if (path.length === 0) {\n // deepSet can't handle this case\n this.settings = value;\n } else {\n util.deepSet(this.settings, path, value);\n }\n return this;\n }\n\n public unset(path: string[]) {\n this.set(path, undefined);\n }\n}\n\nfunction expandHomeDir(x: string) {\n if (x.startsWith('~')) {\n return fs_path.join(os.homedir(), x.slice(1));\n }\n return x;\n}\n\n/**\n * Return all context value that are not transient context values\n */\nfunction stripTransientValues(obj: { [key: string]: any }) {\n const ret: any = {};\n for (const [key, value] of Object.entries(obj)) {\n if (!isTransientValue(value)) {\n ret[key] = value;\n }\n }\n return ret;\n}\n\n/**\n * Return whether the given value is a transient context value\n *\n * Values that are objects with a magic key set to a truthy value are considered transient.\n */\nfunction isTransientValue(value: any) {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as any)[TRANSIENT_CONTEXT_KEY]\n );\n}\n", "import { Settings } from './settings';\nimport { ToolkitError } from './toolkit-error';\n\nexport { TRANSIENT_CONTEXT_KEY } from './settings';\nexport const PROJECT_CONTEXT = 'cdk.context.json';\n\ninterface ContextBag {\n /**\n * The file name of the context. Will be used to potentially\n * save new context back to the original file.\n */\n fileName?: string;\n\n /**\n * The context values.\n */\n bag: Settings;\n}\n\n/**\n * Class that supports overlaying property bags\n *\n * Reads come from the first property bag that can has the given key,\n * writes go to the first property bag that is not readonly. A write\n * will remove the value from all property bags after the first\n * writable one.\n */\nexport class Context {\n private readonly bags: Settings[];\n private readonly fileNames: (string | undefined)[];\n\n constructor(...bags: ContextBag[]) {\n this.bags = bags.length > 0 ? bags.map((b) => b.bag) : [new Settings()];\n this.fileNames =\n bags.length > 0 ? bags.map((b) => b.fileName) : ['default'];\n }\n\n public get keys(): string[] {\n return Object.keys(this.all);\n }\n\n public has(key: string) {\n return this.keys.indexOf(key) > -1;\n }\n\n public get all(): { [key: string]: any } {\n let ret = new Settings();\n\n // In reverse order so keys to the left overwrite keys to the right of them\n for (const bag of [...this.bags].reverse()) {\n ret = ret.merge(bag);\n }\n\n return ret.all;\n }\n\n public get(key: string): any {\n for (const bag of this.bags) {\n const v = bag.get([key]);\n if (v !== undefined) {\n return v;\n }\n }\n return undefined;\n }\n\n public set(key: string, value: any) {\n for (const bag of this.bags) {\n if (bag.readOnly) {\n continue;\n }\n\n // All bags past the first one have the value erased\n bag.set([key], value);\n value = undefined;\n }\n }\n\n public unset(key: string) {\n this.set(key, undefined);\n }\n\n public clear() {\n for (const key of this.keys) {\n this.unset(key);\n }\n }\n\n /**\n * Save a specific context file\n */\n public async save(fileName: string): Promise<this> {\n const index = this.fileNames.indexOf(fileName);\n\n // File not found, don't do anything in this scenario\n if (index === -1) {\n return this;\n }\n\n const bag = this.bags[index];\n if (bag.readOnly) {\n throw new ToolkitError(`Context file ${fileName} is read only!`);\n }\n\n await bag.save(fileName);\n return this;\n }\n}\n", "import { format } from 'node:util';\nimport * as cxschema from '@aws-cdk/cloud-assembly-schema';\nimport {\n formatDifferences,\n formatSecurityChanges,\n fullDiff,\n mangleLikeCloudFormation,\n type TemplateDiff,\n} from '@aws-cdk/cloudformation-diff';\nimport type * as cxapi from '@aws-cdk/cx-api';\nimport * as chalk from 'chalk';\nimport type { NestedStackTemplates } from '../cloudformation';\nimport type { IoHelper } from '../io/private';\nimport { IoDefaultMessages } from '../io/private';\nimport { RequireApproval } from '../require-approval';\nimport { StringWriteStream } from '../streams';\nimport { ToolkitError } from '../toolkit-error';\n\n/**\n * Output of formatSecurityDiff\n */\ninterface FormatSecurityDiffOutput {\n /**\n * Complete formatted security diff, if it is prompt-worthy\n */\n readonly formattedDiff?: string;\n}\n\n/**\n * Output of formatStackDiff\n */\ninterface FormatStackDiffOutput {\n /**\n * Number of stacks with diff changes\n */\n readonly numStacksWithChanges: number;\n\n /**\n * Complete formatted diff\n */\n readonly formattedDiff: string;\n}\n\n/**\n * Props for the Diff Formatter\n */\ninterface DiffFormatterProps {\n /**\n * Helper for the IoHost class\n */\n readonly ioHelper: IoHelper;\n\n /**\n * The relevant information for the Template that is being diffed.\n * Includes the old/current state of the stack as well as the new state.\n */\n readonly templateInfo: TemplateInfo;\n}\n\n/**\n * Properties specific to formatting the security diff\n */\ninterface FormatSecurityDiffOptions {\n /**\n * The approval level of the security diff\n */\n readonly requireApproval: RequireApproval;\n}\n\n/**\n * PRoperties specific to formatting the stack diff\n */\ninterface FormatStackDiffOptions {\n /**\n * do not filter out AWS::CDK::Metadata or Rules\n *\n * @default false\n */\n readonly strict?: boolean;\n\n /**\n * lines of context to use in arbitrary JSON diff\n *\n * @default 3\n */\n readonly context?: number;\n\n /**\n * silences \\'There were no differences\\' messages\n *\n * @default false\n */\n readonly quiet?: boolean;\n}\n\ninterface ReusableStackDiffOptions extends FormatStackDiffOptions {\n readonly ioDefaultHelper: IoDefaultMessages;\n}\n\n/**\n * Information on a template's old/new state\n * that is used for diff.\n */\nexport interface TemplateInfo {\n /**\n * The old/existing template\n */\n readonly oldTemplate: any;\n\n /**\n * The new template\n */\n readonly newTemplate: cxapi.CloudFormationStackArtifact;\n\n /**\n * A CloudFormation ChangeSet to help the diff operation.\n * Probably created via `createDiffChangeSet`.\n *\n * @default undefined\n */\n readonly changeSet?: any;\n\n /**\n * Whether or not there are any imported resources\n *\n * @default false\n */\n readonly isImport?: boolean;\n\n /**\n * Any nested stacks included in the template\n *\n * @default {}\n */\n readonly nestedStacks?: {\n [nestedStackLogicalId: string]: NestedStackTemplates;\n };\n}\n\n/**\n * Class for formatting the diff output\n */\nexport class DiffFormatter {\n private readonly ioHelper: IoHelper;\n private readonly oldTemplate: any;\n private readonly newTemplate: cxapi.CloudFormationStackArtifact;\n private readonly stackName: string;\n private readonly changeSet?: any;\n private readonly nestedStacks: { [nestedStackLogicalId: string]: NestedStackTemplates } | undefined;\n private readonly isImport: boolean;\n\n /**\n * Stores the TemplateDiffs that get calculated in this DiffFormatter,\n * indexed by the stack name.\n */\n private _diffs: { [name: string]: TemplateDiff } = {};\n\n constructor(props: DiffFormatterProps) {\n this.ioHelper = props.ioHelper;\n this.oldTemplate = props.templateInfo.oldTemplate;\n this.newTemplate = props.templateInfo.newTemplate;\n this.stackName = props.templateInfo.newTemplate.stackName;\n this.changeSet = props.templateInfo.changeSet;\n this.nestedStacks = props.templateInfo.nestedStacks;\n this.isImport = props.templateInfo.isImport ?? false;\n }\n\n public get diffs() {\n return this._diffs;\n }\n\n /**\n * Format the stack diff\n */\n public formatStackDiff(options: FormatStackDiffOptions = {}): FormatStackDiffOutput {\n const ioDefaultHelper = new IoDefaultMessages(this.ioHelper);\n return this.formatStackDiffHelper(\n this.oldTemplate,\n this.stackName,\n this.nestedStacks,\n {\n ...options,\n ioDefaultHelper,\n },\n );\n }\n\n private formatStackDiffHelper(\n oldTemplate: any,\n stackName: string,\n nestedStackTemplates: { [nestedStackLogicalId: string]: NestedStackTemplates } | undefined,\n options: ReusableStackDiffOptions,\n ) {\n let diff = fullDiff(oldTemplate, this.newTemplate.template, this.changeSet, this.isImport);\n this._diffs[stackName] = diff;\n\n // The stack diff is formatted via `Formatter`, which takes in a stream\n // and sends its output directly to that stream. To faciliate use of the\n // global CliIoHost, we create our own stream to capture the output of\n // `Formatter` and return the output as a string for the consumer of\n // `formatStackDiff` to decide what to do with it.\n const stream = new StringWriteStream();\n\n let numStacksWithChanges = 0;\n let formattedDiff = '';\n let filteredChangesCount = 0;\n try {\n // must output the stack name if there are differences, even if quiet\n if (stackName && (!options.quiet || !diff.isEmpty)) {\n stream.write(format(`Stack ${chalk.bold(stackName)}\\n`));\n }\n\n if (!options.quiet && this.isImport) {\n stream.write('Parameters and rules created during migration do not affect resource configuration.\\n');\n }\n\n // detect and filter out mangled characters from the diff\n if (diff.differenceCount && !options.strict) {\n const mangledNewTemplate = JSON.parse(mangleLikeCloudFormation(JSON.stringify(this.newTemplate.template)));\n const mangledDiff = fullDiff(this.oldTemplate, mangledNewTemplate, this.changeSet);\n filteredChangesCount = Math.max(0, diff.differenceCount - mangledDiff.differenceCount);\n if (filteredChangesCount > 0) {\n diff = mangledDiff;\n }\n }\n\n // filter out 'AWS::CDK::Metadata' resources from the template\n // filter out 'CheckBootstrapVersion' rules from the template\n if (!options.strict) {\n obscureDiff(diff);\n }\n\n if (!diff.isEmpty) {\n numStacksWithChanges++;\n\n // formatDifferences updates the stream with the formatted stack diff\n formatDifferences(stream, diff, {\n ...logicalIdMapFromTemplate(this.oldTemplate),\n ...buildLogicalToPathMap(this.newTemplate),\n }, options.context);\n } else if (!options.quiet) {\n stream.write(chalk.green('There were no differences\\n'));\n }\n\n if (filteredChangesCount > 0) {\n stream.write(chalk.yellow(`Omitted ${filteredChangesCount} changes because they are likely mangled non-ASCII characters. Use --strict to print them.\\n`));\n }\n } finally {\n // store the stream containing a formatted stack diff\n formattedDiff = stream.toString();\n stream.end();\n }\n\n for (const nestedStackLogicalId of Object.keys(nestedStackTemplates ?? {})) {\n if (!nestedStackTemplates) {\n break;\n }\n const nestedStack = nestedStackTemplates[nestedStackLogicalId];\n\n (this.newTemplate as any)._template = nestedStack.generatedTemplate;\n const nextDiff = this.formatStackDiffHelper(\n nestedStack.deployedTemplate,\n nestedStack.physicalName ?? nestedStackLogicalId,\n nestedStack.nestedStackTemplates,\n options,\n );\n numStacksWithChanges += nextDiff.numStacksWithChanges;\n formattedDiff += nextDiff.formattedDiff;\n }\n\n return {\n numStacksWithChanges,\n formattedDiff,\n };\n }\n\n /**\n * Format the security diff\n */\n public formatSecurityDiff(options: FormatSecurityDiffOptions): FormatSecurityDiffOutput {\n const ioDefaultHelper = new IoDefaultMessages(this.ioHelper);\n\n const diff = fullDiff(this.oldTemplate, this.newTemplate.template, this.changeSet);\n this._diffs[this.stackName] = diff;\n\n if (diffRequiresApproval(diff, options.requireApproval)) {\n // The security diff is formatted via `Formatter`, which takes in a stream\n // and sends its output directly to that stream. To faciliate use of the\n // global CliIoHost, we create our own stream to capture the output of\n // `Formatter` and return the output as a string for the consumer of\n // `formatSecurityDiff` to decide what to do with it.\n const stream = new StringWriteStream();\n\n stream.write(format(`Stack ${chalk.bold(this.stackName)}\\n`));\n\n // eslint-disable-next-line max-len\n ioDefaultHelper.warning(`This deployment will make potentially sensitive changes according to your current security approval level (--require-approval ${options.requireApproval}).`);\n ioDefaultHelper.warning('Please confirm you intend to make the following modifications:\\n');\n try {\n // formatSecurityChanges updates the stream with the formatted security diff\n formatSecurityChanges(stream, diff, buildLogicalToPathMap(this.newTemplate));\n } finally {\n stream.end();\n }\n // store the stream containing a formatted stack diff\n const formattedDiff = stream.toString();\n return { formattedDiff };\n }\n return {};\n }\n}\n\n/**\n * Return whether the diff has security-impacting changes that need confirmation\n *\n * TODO: Filter the security impact determination based off of an enum that allows\n * us to pick minimum \"severities\" to alert on.\n */\nfunction diffRequiresApproval(diff: TemplateDiff, requireApproval: RequireApproval) {\n switch (requireApproval) {\n case RequireApproval.NEVER: return false;\n case RequireApproval.ANY_CHANGE: return diff.permissionsAnyChanges;\n case RequireApproval.BROADENING: return diff.permissionsBroadened;\n default: throw new ToolkitError(`Unrecognized approval level: ${requireApproval}`);\n }\n}\n\nfunction buildLogicalToPathMap(stack: cxapi.CloudFormationStackArtifact) {\n const map: { [id: string]: string } = {};\n for (const md of stack.findMetadataByType(cxschema.ArtifactMetadataEntryType.LOGICAL_ID)) {\n map[md.data as string] = md.path;\n }\n return map;\n}\n\nfunction logicalIdMapFromTemplate(template: any) {\n const ret: Record<string, string> = {};\n\n for (const [logicalId, resource] of Object.entries(template.Resources ?? {})) {\n const path = (resource as any)?.Metadata?.['aws:cdk:path'];\n if (path) {\n ret[logicalId] = path;\n }\n }\n return ret;\n}\n\n/**\n * Remove any template elements that we don't want to show users.\n * This is currently:\n * - AWS::CDK::Metadata resource\n * - CheckBootstrapVersion Rule\n */\nfunction obscureDiff(diff: TemplateDiff) {\n if (diff.unknown) {\n // see https://github.com/aws/aws-cdk/issues/17942\n diff.unknown = diff.unknown.filter(change => {\n if (!change) {\n return true;\n }\n if (change.newValue?.CheckBootstrapVersion) {\n return false;\n }\n if (change.oldValue?.CheckBootstrapVersion) {\n return false;\n }\n return true;\n });\n }\n\n if (diff.resources) {\n diff.resources = diff.resources.filter(change => {\n if (!change) {\n return true;\n }\n if (change.newResourceType === 'AWS::CDK::Metadata') {\n return false;\n }\n if (change.oldResourceType === 'AWS::CDK::Metadata') {\n return false;\n }\n return true;\n });\n }\n}\n", "/**\n * @deprecated\n */\nexport enum RequireApproval {\n /**\n * Never require any security approvals\n */\n NEVER = 'never',\n /**\n * Any security changes require an approval\n */\n ANY_CHANGE = 'any-change',\n /**\n * Require approval only for changes that are access broadening\n */\n BROADENING = 'broadening',\n}\n", "import { Writable } from 'node:stream';\n\n/*\n * Custom writable stream that collects text into a string buffer.\n * Used on classes that take in and directly write to a stream, but\n * we intend to capture the output rather than print.\n */\nexport class StringWriteStream extends Writable {\n private buffer: string[] = [];\n\n constructor() {\n super();\n }\n\n _write(chunk: any, _encoding: string, callback: (error?: Error | null) => void): void {\n this.buffer.push(chunk.toString());\n callback();\n }\n\n toString(): string {\n return this.buffer.join('');\n }\n}\n", "import type * as cxapi from '@aws-cdk/cx-api';\nimport type { ImageIdentifier } from '@aws-sdk/client-ecr';\nimport type { Tag } from '@aws-sdk/client-s3';\nimport * as chalk from 'chalk';\nimport * as promptly from 'promptly';\nimport type { IECRClient, IS3Client, SDK, SdkProvider } from '../aws-auth';\nimport { DEFAULT_TOOLKIT_STACK_NAME, ToolkitInfo } from '../toolkit-info';\nimport { ProgressPrinter } from './progress-printer';\nimport { ActiveAssetCache, BackgroundStackRefresh, refreshStacks } from './stack-refresh';\nimport { IO, type IoHelper } from '../io/private';\nimport { Mode } from '../plugin';\nimport { ToolkitError } from '../toolkit-error';\n\n// Must use a require() otherwise esbuild complains\n// eslint-disable-next-line @typescript-eslint/no-require-imports,@typescript-eslint/consistent-type-imports\nconst pLimit: typeof import('p-limit') = require('p-limit');\n\nexport const S3_ISOLATED_TAG = 'aws-cdk:isolated';\nexport const ECR_ISOLATED_TAG = 'aws-cdk.isolated'; // ':' is not valid in ECR tags\nconst P_LIMIT = 50;\nconst DAY = 24 * 60 * 60 * 1000; // Number of milliseconds in a day\n\nexport type GcAsset = ImageAsset | ObjectAsset;\n\n/**\n * An image asset that lives in the bootstrapped ECR Repository\n */\nexport class ImageAsset {\n public constructor(\n public readonly digest: string,\n public readonly size: number,\n public readonly tags: string[],\n public readonly manifest: string,\n ) {\n }\n\n private getTag(tag: string) {\n return this.tags.find(t => t.includes(tag));\n }\n\n private hasTag(tag: string) {\n return this.tags.some(t => t.includes(tag));\n }\n\n public hasIsolatedTag() {\n return this.hasTag(ECR_ISOLATED_TAG);\n }\n\n public getIsolatedTag() {\n return this.getTag(ECR_ISOLATED_TAG);\n }\n\n public isolatedTagBefore(date: Date) {\n const dateIsolated = this.dateIsolated();\n if (!dateIsolated || dateIsolated == '') {\n return false;\n }\n return new Date(dateIsolated) < date;\n }\n\n public buildImageTag(inc: number) {\n // isolatedTag will look like \"X-aws-cdk.isolated-YYYYY\"\n return `${inc}-${ECR_ISOLATED_TAG}-${String(Date.now())}`;\n }\n\n public dateIsolated() {\n // isolatedTag will look like \"X-aws-cdk.isolated-YYYYY\"\n return this.getIsolatedTag()?.split('-')[3];\n }\n}\n\n/**\n * An object asset that lives in the bootstrapped S3 Bucket\n */\nexport class ObjectAsset {\n private cached_tags: Tag[] | undefined = undefined;\n\n public constructor(private readonly bucket: string, public readonly key: string, public readonly size: number) {\n }\n\n public fileName(): string {\n return this.key.split('.')[0];\n }\n\n public async allTags(s3: IS3Client) {\n if (this.cached_tags) {\n return this.cached_tags;\n }\n\n const response = await s3.getObjectTagging({ Bucket: this.bucket, Key: this.key });\n this.cached_tags = response.TagSet;\n return this.cached_tags;\n }\n\n private getTag(tag: string) {\n if (!this.cached_tags) {\n throw new ToolkitError('Cannot call getTag before allTags');\n }\n return this.cached_tags.find((t: any) => t.Key === tag)?.Value;\n }\n\n private hasTag(tag: string) {\n if (!this.cached_tags) {\n throw new ToolkitError('Cannot call hasTag before allTags');\n }\n return this.cached_tags.some((t: any) => t.Key === tag);\n }\n\n public hasIsolatedTag() {\n return this.hasTag(S3_ISOLATED_TAG);\n }\n\n public isolatedTagBefore(date: Date) {\n const tagValue = this.getTag(S3_ISOLATED_TAG);\n if (!tagValue || tagValue == '') {\n return false;\n }\n return new Date(tagValue) < date;\n }\n}\n\n/**\n * Props for the Garbage Collector\n */\ninterface GarbageCollectorProps {\n /**\n * The action to perform. Specify this if you want to perform a truncated set\n * of actions available.\n */\n readonly action: 'print' | 'tag' | 'delete-tagged' | 'full';\n\n /**\n * The type of asset to garbage collect.\n */\n readonly type: 's3' | 'ecr' | 'all';\n\n /**\n * The days an asset must be in isolation before being actually deleted.\n */\n readonly rollbackBufferDays: number;\n\n /**\n * Refuse deletion of any assets younger than this number of days.\n */\n readonly createdBufferDays: number;\n\n /**\n * The environment to deploy this stack in\n *\n * The environment on the stack artifact may be unresolved, this one\n * must be resolved.\n */\n readonly resolvedEnvironment: cxapi.Environment;\n\n /**\n * SDK provider (seeded with default credentials)\n *\n * Will be used to make SDK calls to CloudFormation, S3, and ECR.\n */\n readonly sdkProvider: SdkProvider;\n\n /**\n * Used to send messages.\n */\n readonly ioHelper: IoHelper;\n\n /**\n * The name of the bootstrap stack to look for.\n *\n * @default DEFAULT_TOOLKIT_STACK_NAME\n */\n readonly bootstrapStackName?: string;\n\n /**\n * Confirm with the user before actual deletion happens\n *\n * @default true\n */\n readonly confirm?: boolean;\n}\n\n/**\n * A class to facilitate Garbage Collection of S3 and ECR assets\n */\nexport class GarbageCollector {\n private garbageCollectS3Assets: boolean;\n private garbageCollectEcrAssets: boolean;\n private permissionToDelete: boolean;\n private permissionToTag: boolean;\n private bootstrapStackName: string;\n private confirm: boolean;\n private ioHelper: IoHelper;\n\n public constructor(readonly props: GarbageCollectorProps) {\n this.ioHelper = props.ioHelper;\n\n this.garbageCollectS3Assets = ['s3', 'all'].includes(props.type);\n this.garbageCollectEcrAssets = ['ecr', 'all'].includes(props.type);\n\n this.permissionToDelete = ['delete-tagged', 'full'].includes(props.action);\n this.permissionToTag = ['tag', 'full'].includes(props.action);\n this.confirm = props.confirm ?? true;\n\n this.bootstrapStackName = props.bootstrapStackName ?? DEFAULT_TOOLKIT_STACK_NAME;\n }\n\n /**\n * Perform garbage collection on the resolved environment.\n */\n public async garbageCollect() {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${this.garbageCollectS3Assets} ${this.garbageCollectEcrAssets}`));\n\n // SDKs\n const sdk = (await this.props.sdkProvider.forEnvironment(this.props.resolvedEnvironment, Mode.ForWriting)).sdk;\n const cfn = sdk.cloudFormation();\n\n const qualifier = await this.bootstrapQualifier(sdk, this.bootstrapStackName);\n const activeAssets = new ActiveAssetCache();\n\n // Grab stack templates first\n await refreshStacks(cfn, this.ioHelper, activeAssets, qualifier);\n // Start the background refresh\n const backgroundStackRefresh = new BackgroundStackRefresh({\n cfn,\n ioHelper: this.ioHelper,\n activeAssets,\n qualifier,\n });\n backgroundStackRefresh.start();\n\n try {\n if (this.garbageCollectS3Assets) {\n await this.garbageCollectS3(sdk, activeAssets, backgroundStackRefresh);\n }\n\n if (this.garbageCollectEcrAssets) {\n await this.garbageCollectEcr(sdk, activeAssets, backgroundStackRefresh);\n }\n } catch (err: any) {\n throw new ToolkitError(err);\n } finally {\n backgroundStackRefresh.stop();\n }\n }\n\n /**\n * Perform garbage collection on ECR assets\n */\n public async garbageCollectEcr(sdk: SDK, activeAssets: ActiveAssetCache, backgroundStackRefresh: BackgroundStackRefresh) {\n const ecr = sdk.ecr();\n const repo = await this.bootstrapRepositoryName(sdk, this.bootstrapStackName);\n const numImages = await this.numImagesInRepo(ecr, repo);\n const printer = new ProgressPrinter(this.ioHelper, numImages, 1000);\n\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Found bootstrap repo ${repo} with ${numImages} images`));\n\n try {\n // const batches = 1;\n const batchSize = 1000;\n const currentTime = Date.now();\n const graceDays = this.props.rollbackBufferDays;\n\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Parsing through ${numImages} images in batches`));\n\n printer.start();\n\n for await (const batch of this.readRepoInBatches(ecr, repo, batchSize, currentTime)) {\n await backgroundStackRefresh.noOlderThan(600_000); // 10 mins\n\n const { included: isolated, excluded: notIsolated } = partition(batch, asset => !asset.tags.some(t => activeAssets.contains(t)));\n\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${isolated.length} isolated images`));\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${notIsolated.length} not isolated images`));\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${batch.length} images total`));\n\n let deletables: ImageAsset[] = isolated;\n let taggables: ImageAsset[] = [];\n let untaggables: ImageAsset[] = [];\n\n if (graceDays > 0) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg('Filtering out images that are not old enough to delete'));\n\n // We delete images that are not referenced in ActiveAssets and have the Isolated Tag with a date\n // earlier than the current time - grace period.\n deletables = isolated.filter(img => img.isolatedTagBefore(new Date(currentTime - (graceDays * DAY))));\n\n // We tag images that are not referenced in ActiveAssets and do not have the Isolated Tag.\n taggables = isolated.filter(img => !img.hasIsolatedTag());\n\n // We untag images that are referenced in ActiveAssets and currently have the Isolated Tag.\n untaggables = notIsolated.filter(img => img.hasIsolatedTag());\n }\n\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${deletables.length} deletable assets`));\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${taggables.length} taggable assets`));\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${untaggables.length} assets to untag`));\n\n if (this.permissionToDelete && deletables.length > 0) {\n await this.confirmationPrompt(printer, deletables, 'image');\n await this.parallelDeleteEcr(ecr, repo, deletables, printer);\n }\n\n if (this.permissionToTag && taggables.length > 0) {\n await this.parallelTagEcr(ecr, repo, taggables, printer);\n }\n\n if (this.permissionToTag && untaggables.length > 0) {\n await this.parallelUntagEcr(ecr, repo, untaggables);\n }\n\n printer.reportScannedAsset(batch.length);\n }\n } catch (err: any) {\n throw new ToolkitError(err);\n } finally {\n printer.stop();\n }\n }\n\n /**\n * Perform garbage collection on S3 assets\n */\n public async garbageCollectS3(sdk: SDK, activeAssets: ActiveAssetCache, backgroundStackRefresh: BackgroundStackRefresh) {\n const s3 = sdk.s3();\n const bucket = await this.bootstrapBucketName(sdk, this.bootstrapStackName);\n const numObjects = await this.numObjectsInBucket(s3, bucket);\n const printer = new ProgressPrinter(this.ioHelper, numObjects, 1000);\n\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Found bootstrap bucket ${bucket} with ${numObjects} objects`));\n\n try {\n const batchSize = 1000;\n const currentTime = Date.now();\n const graceDays = this.props.rollbackBufferDays;\n\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Parsing through ${numObjects} objects in batches`));\n\n printer.start();\n\n // Process objects in batches of 1000\n // This is the batch limit of s3.DeleteObject and we intend to optimize for the \"worst case\" scenario\n // where gc is run for the first time on a long-standing bucket where ~100% of objects are isolated.\n for await (const batch of this.readBucketInBatches(s3, bucket, batchSize, currentTime)) {\n await backgroundStackRefresh.noOlderThan(600_000); // 10 mins\n\n const { included: isolated, excluded: notIsolated } = partition(batch, asset => !activeAssets.contains(asset.fileName()));\n\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${isolated.length} isolated assets`));\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${notIsolated.length} not isolated assets`));\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${batch.length} objects total`));\n\n let deletables: ObjectAsset[] = isolated;\n let taggables: ObjectAsset[] = [];\n let untaggables: ObjectAsset[] = [];\n\n if (graceDays > 0) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg('Filtering out assets that are not old enough to delete'));\n await this.parallelReadAllTags(s3, batch);\n\n // We delete objects that are not referenced in ActiveAssets and have the Isolated Tag with a date\n // earlier than the current time - grace period.\n deletables = isolated.filter(obj => obj.isolatedTagBefore(new Date(currentTime - (graceDays * DAY))));\n\n // We tag objects that are not referenced in ActiveAssets and do not have the Isolated Tag.\n taggables = isolated.filter(obj => !obj.hasIsolatedTag());\n\n // We untag objects that are referenced in ActiveAssets and currently have the Isolated Tag.\n untaggables = notIsolated.filter(obj => obj.hasIsolatedTag());\n }\n\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${deletables.length} deletable assets`));\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${taggables.length} taggable assets`));\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${untaggables.length} assets to untag`));\n\n if (this.permissionToDelete && deletables.length > 0) {\n await this.confirmationPrompt(printer, deletables, 'object');\n await this.parallelDeleteS3(s3, bucket, deletables, printer);\n }\n\n if (this.permissionToTag && taggables.length > 0) {\n await this.parallelTagS3(s3, bucket, taggables, currentTime, printer);\n }\n\n if (this.permissionToTag && untaggables.length > 0) {\n await this.parallelUntagS3(s3, bucket, untaggables);\n }\n\n printer.reportScannedAsset(batch.length);\n }\n } catch (err: any) {\n throw new ToolkitError(err);\n } finally {\n printer.stop();\n }\n }\n\n private async parallelReadAllTags(s3: IS3Client, objects: ObjectAsset[]) {\n const limit = pLimit(P_LIMIT);\n\n for (const obj of objects) {\n await limit(() => obj.allTags(s3));\n }\n }\n\n /**\n * Untag assets that were previously tagged, but now currently referenced.\n * Since this is treated as an implementation detail, we do not print the results in the printer.\n */\n private async parallelUntagEcr(ecr: IECRClient, repo: string, untaggables: ImageAsset[]) {\n const limit = pLimit(P_LIMIT);\n\n for (const img of untaggables) {\n const tag = img.getIsolatedTag();\n await limit(() =>\n ecr.batchDeleteImage({\n repositoryName: repo,\n imageIds: [{\n imageTag: tag,\n }],\n }),\n );\n }\n\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Untagged ${untaggables.length} assets`));\n }\n\n /**\n * Untag assets that were previously tagged, but now currently referenced.\n * Since this is treated as an implementation detail, we do not print the results in the printer.\n */\n private async parallelUntagS3(s3: IS3Client, bucket: string, untaggables: ObjectAsset[]) {\n const limit = pLimit(P_LIMIT);\n\n for (const obj of untaggables) {\n const tags = await obj.allTags(s3) ?? [];\n const updatedTags = tags.filter((tag: Tag) => tag.Key !== S3_ISOLATED_TAG);\n await limit(() =>\n s3.deleteObjectTagging({\n Bucket: bucket,\n Key: obj.key,\n\n }),\n );\n await limit(() =>\n s3.putObjectTagging({\n Bucket: bucket,\n Key: obj.key,\n Tagging: {\n TagSet: updatedTags,\n },\n }),\n );\n }\n\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Untagged ${untaggables.length} assets`));\n }\n\n /**\n * Tag images in parallel using p-limit\n */\n private async parallelTagEcr(ecr: IECRClient, repo: string, taggables: ImageAsset[], printer: ProgressPrinter) {\n const limit = pLimit(P_LIMIT);\n\n for (let i = 0; i < taggables.length; i++) {\n const img = taggables[i];\n const tagEcr = async () => {\n try {\n await ecr.putImage({\n repositoryName: repo,\n imageDigest: img.digest,\n imageManifest: img.manifest,\n imageTag: img.buildImageTag(i),\n });\n } catch (error) {\n // This is a false negative -- an isolated asset is untagged\n // likely due to an imageTag collision. We can safely ignore,\n // and the isolated asset will be tagged next time.\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Warning: unable to tag image ${JSON.stringify(img.tags)} with ${img.buildImageTag(i)} due to the following error: ${error}`));\n }\n };\n await limit(() => tagEcr());\n }\n\n printer.reportTaggedAsset(taggables);\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Tagged ${taggables.length} assets`));\n }\n\n /**\n * Tag objects in parallel using p-limit. The putObjectTagging API does not\n * support batch tagging so we must handle the parallelism client-side.\n */\n private async parallelTagS3(s3: IS3Client, bucket: string, taggables: ObjectAsset[], date: number, printer: ProgressPrinter) {\n const limit = pLimit(P_LIMIT);\n\n for (const obj of taggables) {\n await limit(() =>\n s3.putObjectTagging({\n Bucket: bucket,\n Key: obj.key,\n Tagging: {\n TagSet: [\n {\n Key: S3_ISOLATED_TAG,\n Value: String(date),\n },\n ],\n },\n }),\n );\n }\n\n printer.reportTaggedAsset(taggables);\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Tagged ${taggables.length} assets`));\n }\n\n /**\n * Delete images in parallel. The deleteImage API supports batches of 100.\n */\n private async parallelDeleteEcr(ecr: IECRClient, repo: string, deletables: ImageAsset[], printer: ProgressPrinter) {\n const batchSize = 100;\n const imagesToDelete = deletables.map(img => ({\n imageDigest: img.digest,\n }));\n\n try {\n const batches = [];\n for (let i = 0; i < imagesToDelete.length; i += batchSize) {\n batches.push(imagesToDelete.slice(i, i + batchSize));\n }\n // Delete images in batches\n for (const batch of batches) {\n await ecr.batchDeleteImage({\n imageIds: batch,\n repositoryName: repo,\n });\n\n const deletedCount = batch.length;\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Deleted ${deletedCount} assets`));\n printer.reportDeletedAsset(deletables.slice(0, deletedCount));\n }\n } catch (err) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_ERROR.msg(`Error deleting images: ${err}`));\n }\n }\n\n /**\n * Delete objects in parallel. The deleteObjects API supports batches of 1000.\n */\n private async parallelDeleteS3(s3: IS3Client, bucket: string, deletables: ObjectAsset[], printer: ProgressPrinter) {\n const batchSize = 1000;\n const objectsToDelete = deletables.map(asset => ({\n Key: asset.key,\n }));\n\n try {\n const batches = [];\n for (let i = 0; i < objectsToDelete.length; i += batchSize) {\n batches.push(objectsToDelete.slice(i, i + batchSize));\n }\n // Delete objects in batches\n for (const batch of batches) {\n await s3.deleteObjects({\n Bucket: bucket,\n Delete: {\n Objects: batch,\n Quiet: true,\n },\n });\n\n const deletedCount = batch.length;\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Deleted ${deletedCount} assets`));\n printer.reportDeletedAsset(deletables.slice(0, deletedCount));\n }\n } catch (err) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(chalk.red(`Error deleting objects: ${err}`)));\n }\n }\n\n private async bootstrapBucketName(sdk: SDK, bootstrapStackName: string): Promise<string> {\n const toolkitInfo = await ToolkitInfo.lookup(this.props.resolvedEnvironment, sdk, this.ioHelper, bootstrapStackName);\n return toolkitInfo.bucketName;\n }\n\n private async bootstrapRepositoryName(sdk: SDK, bootstrapStackName: string): Promise<string> {\n const toolkitInfo = await ToolkitInfo.lookup(this.props.resolvedEnvironment, sdk, this.ioHelper, bootstrapStackName);\n return toolkitInfo.repositoryName;\n }\n\n private async bootstrapQualifier(sdk: SDK, bootstrapStackName: string): Promise<string | undefined> {\n const toolkitInfo = await ToolkitInfo.lookup(this.props.resolvedEnvironment, sdk, this.ioHelper, bootstrapStackName);\n return toolkitInfo.bootstrapStack.parameters.Qualifier;\n }\n\n private async numObjectsInBucket(s3: IS3Client, bucket: string): Promise<number> {\n let totalCount = 0;\n let continuationToken: string | undefined;\n\n do {\n const response = await s3.listObjectsV2({\n Bucket: bucket,\n ContinuationToken: continuationToken,\n });\n\n totalCount += response.KeyCount ?? 0;\n continuationToken = response.NextContinuationToken;\n } while (continuationToken);\n\n return totalCount;\n }\n\n private async numImagesInRepo(ecr: IECRClient, repo: string): Promise<number> {\n let totalCount = 0;\n let nextToken: string | undefined;\n\n do {\n const response = await ecr.listImages({\n repositoryName: repo,\n nextToken: nextToken,\n });\n\n totalCount += response.imageIds?.length ?? 0;\n nextToken = response.nextToken;\n } while (nextToken);\n\n return totalCount;\n }\n\n private async *readRepoInBatches(ecr: IECRClient, repo: string, batchSize: number = 1000, currentTime: number): AsyncGenerator<ImageAsset[]> {\n let continuationToken: string | undefined;\n\n do {\n const batch: ImageAsset[] = [];\n\n while (batch.length < batchSize) {\n const response = await ecr.listImages({\n repositoryName: repo,\n nextToken: continuationToken,\n });\n\n // No images in the repository\n if (!response.imageIds || response.imageIds.length === 0) {\n break;\n }\n\n // map unique image digest to (possibly multiple) tags\n const images = imageMap(response.imageIds ?? []);\n\n const imageIds = Object.keys(images).map(key => ({\n imageDigest: key,\n }));\n\n const describeImageInfo = await ecr.describeImages({\n repositoryName: repo,\n imageIds: imageIds,\n });\n\n const getImageInfo = await ecr.batchGetImage({\n repositoryName: repo,\n imageIds: imageIds,\n });\n\n const combinedImageInfo = describeImageInfo.imageDetails?.map(imageDetail => {\n const matchingImage = getImageInfo.images?.find(\n img => img.imageId?.imageDigest === imageDetail.imageDigest,\n );\n\n return {\n ...imageDetail,\n manifest: matchingImage?.imageManifest,\n };\n });\n\n for (const image of combinedImageInfo ?? []) {\n const lastModified = image.imagePushedAt ?? new Date(currentTime);\n // Store the image if it was pushed earlier than today - createdBufferDays\n if (image.imageDigest && lastModified < new Date(currentTime - (this.props.createdBufferDays * DAY))) {\n batch.push(new ImageAsset(image.imageDigest, image.imageSizeInBytes ?? 0, image.imageTags ?? [], image.manifest ?? ''));\n }\n }\n\n continuationToken = response.nextToken;\n\n if (!continuationToken) break; // No more images to fetch\n }\n\n if (batch.length > 0) {\n yield batch;\n }\n } while (continuationToken);\n }\n\n /**\n * Generator function that reads objects from the S3 Bucket in batches.\n */\n private async *readBucketInBatches(s3: IS3Client, bucket: string, batchSize: number = 1000, currentTime: number): AsyncGenerator<ObjectAsset[]> {\n let continuationToken: string | undefined;\n\n do {\n const batch: ObjectAsset[] = [];\n\n while (batch.length < batchSize) {\n const response = await s3.listObjectsV2({\n Bucket: bucket,\n ContinuationToken: continuationToken,\n });\n\n response.Contents?.forEach((obj: any) => {\n const key = obj.Key ?? '';\n const size = obj.Size ?? 0;\n const lastModified = obj.LastModified ?? new Date(currentTime);\n // Store the object if it has a Key and\n // if it has not been modified since today - createdBufferDays\n if (key && lastModified < new Date(currentTime - (this.props.createdBufferDays * DAY))) {\n batch.push(new ObjectAsset(bucket, key, size));\n }\n });\n\n continuationToken = response.NextContinuationToken;\n\n if (!continuationToken) break; // No more objects to fetch\n }\n\n if (batch.length > 0) {\n yield batch;\n }\n } while (continuationToken);\n }\n\n private async confirmationPrompt(printer: ProgressPrinter, deletables: GcAsset[], type: string) {\n const pluralize = (name: string, count: number): string => {\n return count === 1 ? name : `${name}s`;\n };\n\n if (this.confirm) {\n const message = [\n `Found ${deletables.length} ${pluralize(type, deletables.length)} to delete based off of the following criteria:`,\n `- ${type}s have been isolated for > ${this.props.rollbackBufferDays} days`,\n `- ${type}s were created > ${this.props.createdBufferDays} days ago`,\n '',\n 'Delete this batch (yes/no/delete-all)?',\n ].join('\\n');\n printer.pause();\n const response = await promptly.prompt(message,\n { trim: true },\n );\n\n // Anything other than yes/y/delete-all is treated as no\n if (!response || !['yes', 'y', 'delete-all'].includes(response.toLowerCase())) {\n throw new ToolkitError('Deletion aborted by user');\n } else if (response.toLowerCase() == 'delete-all') {\n this.confirm = false;\n }\n }\n printer.resume();\n }\n}\n\nfunction partition<A>(xs: Iterable<A>, pred: (x: A) => boolean): { included: A[]; excluded: A[] } {\n const result = {\n included: [] as A[],\n excluded: [] as A[],\n };\n\n for (const x of xs) {\n if (pred(x)) {\n result.included.push(x);\n } else {\n result.excluded.push(x);\n }\n }\n\n return result;\n}\n\nfunction imageMap(imageIds: ImageIdentifier[]) {\n const images: Record<string, string[]> = {};\n for (const image of imageIds ?? []) {\n if (!image.imageDigest || !image.imageTag) {\n continue;\n }\n if (!images[image.imageDigest]) {\n images[image.imageDigest] = [];\n }\n images[image.imageDigest].push(image.imageTag);\n }\n return images;\n}\n", "import * as chalk from 'chalk';\nimport type { GcAsset as GCAsset } from './garbage-collector';\nimport { IO, type IoHelper } from '../io/private';\nimport { ToolkitError } from '../toolkit-error';\n\nexport class ProgressPrinter {\n private ioHelper: IoHelper;\n private totalAssets: number;\n private assetsScanned: number;\n private taggedAsset: number;\n private taggedAssetsSizeMb: number;\n private deletedAssets: number;\n private deletedAssetsSizeMb: number;\n private interval: number;\n private setInterval?: ReturnType<typeof setTimeout>;\n private isPaused: boolean;\n\n constructor(ioHelper: IoHelper, totalAssets: number, interval?: number) {\n this.ioHelper = ioHelper;\n this.totalAssets = totalAssets;\n this.assetsScanned = 0;\n this.taggedAsset = 0;\n this.taggedAssetsSizeMb = 0;\n this.deletedAssets = 0;\n this.deletedAssetsSizeMb = 0;\n this.interval = interval ?? 10_000;\n this.isPaused = false;\n }\n\n public reportScannedAsset(amt: number) {\n this.assetsScanned += amt;\n }\n\n public reportTaggedAsset(assets: GCAsset[]) {\n this.taggedAsset += assets.length;\n const sizeInBytes = assets.reduce((total, asset) => total + asset.size, 0);\n this.taggedAssetsSizeMb += sizeInBytes / 1_048_576;\n }\n\n public reportDeletedAsset(assets: GCAsset[]) {\n this.deletedAssets += assets.length;\n const sizeInBytes = assets.reduce((total, asset) => total + asset.size, 0);\n this.deletedAssetsSizeMb += sizeInBytes / 1_048_576;\n }\n\n public start() {\n // If there is already a running setInterval, throw an error.\n // This is because if this.setInterval is reassigned to another setInterval,\n // the original setInterval remains and can no longer be cleared.\n if (this.setInterval) {\n throw new ToolkitError('ProgressPrinter is already running. Stop it first using the stop() method before starting it again.');\n }\n\n this.setInterval = setInterval(() => {\n if (!this.isPaused) {\n this.print();\n }\n }, this.interval);\n }\n\n public pause() {\n this.isPaused = true;\n }\n\n public resume() {\n this.isPaused = false;\n }\n\n public stop() {\n clearInterval(this.setInterval);\n // print one last time if not paused\n if (!this.isPaused) {\n this.print();\n }\n }\n\n private print() {\n const percentage = ((this.assetsScanned / this.totalAssets) * 100).toFixed(2);\n // print in MiB until we hit at least 1 GiB of data tagged/deleted\n if (Math.max(this.taggedAssetsSizeMb, this.deletedAssetsSizeMb) >= 1000) {\n void this.ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(chalk.green(`[${percentage}%] ${this.assetsScanned} files scanned: ${this.taggedAsset} assets (${(this.taggedAssetsSizeMb / 1000).toFixed(2)} GiB) tagged, ${this.deletedAssets} assets (${(this.deletedAssetsSizeMb / 1000).toFixed(2)} GiB) deleted.`)));\n } else {\n void this.ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(chalk.green(`[${percentage}%] ${this.assetsScanned} files scanned: ${this.taggedAsset} assets (${this.taggedAssetsSizeMb.toFixed(2)} MiB) tagged, ${this.deletedAssets} assets (${this.deletedAssetsSizeMb.toFixed(2)} MiB) deleted.`)));\n }\n }\n}\n", "import type { ParameterDeclaration } from '@aws-sdk/client-cloudformation';\nimport type { ICloudFormationClient } from '../aws-auth';\nimport { IO, type IoHelper } from '../io/private';\nimport { ToolkitError } from '../toolkit-error';\n\nexport class ActiveAssetCache {\n private readonly stacks: Set<string> = new Set();\n\n public rememberStack(stackTemplate: string) {\n this.stacks.add(stackTemplate);\n }\n\n public contains(asset: string): boolean {\n for (const stack of this.stacks) {\n if (stack.includes(asset)) {\n return true;\n }\n }\n return false;\n }\n}\n\nasync function paginateSdkCall(cb: (nextToken?: string) => Promise<string | undefined>) {\n let finished = false;\n let nextToken: string | undefined;\n while (!finished) {\n nextToken = await cb(nextToken);\n if (nextToken === undefined) {\n finished = true;\n }\n }\n}\n\n/**\n * Fetches all relevant stack templates from CloudFormation. It ignores the following stacks:\n * - stacks in DELETE_COMPLETE or DELETE_IN_PROGRESS stage\n * - stacks that are using a different bootstrap qualifier\n */\nasync function fetchAllStackTemplates(cfn: ICloudFormationClient, ioHelper: IoHelper, qualifier?: string) {\n const stackNames: string[] = [];\n await paginateSdkCall(async (nextToken) => {\n const stacks = await cfn.listStacks({ NextToken: nextToken });\n\n // We ignore stacks with these statuses because their assets are no longer live\n const ignoredStatues = ['CREATE_FAILED', 'DELETE_COMPLETE', 'DELETE_IN_PROGRESS', 'DELETE_FAILED', 'REVIEW_IN_PROGRESS'];\n stackNames.push(\n ...(stacks.StackSummaries ?? [])\n .filter((s: any) => !ignoredStatues.includes(s.StackStatus))\n .map((s: any) => s.StackId ?? s.StackName),\n );\n\n return stacks.NextToken;\n });\n\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Parsing through ${stackNames.length} stacks`));\n\n const templates: string[] = [];\n for (const stack of stackNames) {\n let summary;\n summary = await cfn.getTemplateSummary({\n StackName: stack,\n });\n\n if (bootstrapFilter(summary.Parameters, qualifier)) {\n // This stack is definitely bootstrapped to a different qualifier so we can safely ignore it\n continue;\n } else {\n const template = await cfn.getTemplate({\n StackName: stack,\n });\n\n templates.push((template.TemplateBody ?? '') + JSON.stringify(summary?.Parameters));\n }\n }\n\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg('Done parsing through stacks'));\n\n return templates;\n}\n\n/**\n * Filter out stacks that we KNOW are using a different bootstrap qualifier\n * This is mostly necessary for the integration tests that can run the same app (with the same assets)\n * under different qualifiers.\n * This is necessary because a stack under a different bootstrap could coincidentally reference the same hash\n * and cause a false negative (cause an asset to be preserved when its isolated)\n * This is intentionally done in a way where we ONLY filter out stacks that are meant for a different qualifier\n * because we are okay with false positives.\n */\nfunction bootstrapFilter(parameters?: ParameterDeclaration[], qualifier?: string) {\n const bootstrapVersion = parameters?.find((p) => p.ParameterKey === 'BootstrapVersion');\n const splitBootstrapVersion = bootstrapVersion?.DefaultValue?.split('/');\n // We find the qualifier in a specific part of the bootstrap version parameter\n return (qualifier &&\n splitBootstrapVersion &&\n splitBootstrapVersion.length == 4 &&\n splitBootstrapVersion[2] != qualifier);\n}\n\nexport async function refreshStacks(cfn: ICloudFormationClient, ioHelper: IoHelper, activeAssets: ActiveAssetCache, qualifier?: string) {\n try {\n const stacks = await fetchAllStackTemplates(cfn, ioHelper, qualifier);\n for (const stack of stacks) {\n activeAssets.rememberStack(stack);\n }\n } catch (err) {\n throw new ToolkitError(`Error refreshing stacks: ${err}`);\n }\n}\n\n/**\n * Background Stack Refresh properties\n */\nexport interface BackgroundStackRefreshProps {\n /**\n * The CFN SDK handler\n */\n readonly cfn: ICloudFormationClient;\n\n /**\n * Used to send messages.\n */\n readonly ioHelper: IoHelper;\n\n /**\n * Active Asset storage\n */\n readonly activeAssets: ActiveAssetCache;\n\n /**\n * Stack bootstrap qualifier\n */\n readonly qualifier?: string;\n}\n\n/**\n * Class that controls scheduling of the background stack refresh\n */\nexport class BackgroundStackRefresh {\n private timeout?: NodeJS.Timeout;\n private lastRefreshTime: number;\n private queuedPromises: Array<(value: unknown) => void> = [];\n\n constructor(private readonly props: BackgroundStackRefreshProps) {\n this.lastRefreshTime = Date.now();\n }\n\n public start() {\n // Since start is going to be called right after the first invocation of refreshStacks,\n // lets wait some time before beginning the background refresh.\n this.timeout = setTimeout(() => this.refresh(), 300_000); // 5 minutes\n }\n\n private async refresh() {\n const startTime = Date.now();\n\n await refreshStacks(this.props.cfn, this.props.ioHelper, this.props.activeAssets, this.props.qualifier);\n this.justRefreshedStacks();\n\n // If the last invocation of refreshStacks takes <5 minutes, the next invocation starts 5 minutes after the last one started.\n // If the last invocation of refreshStacks takes >5 minutes, the next invocation starts immediately.\n this.timeout = setTimeout(() => this.refresh(), Math.max(startTime + 300_000 - Date.now(), 0));\n }\n\n private justRefreshedStacks() {\n this.lastRefreshTime = Date.now();\n for (const p of this.queuedPromises.splice(0, this.queuedPromises.length)) {\n p(undefined);\n }\n }\n\n /**\n * Checks if the last successful background refresh happened within the specified time frame.\n * If the last refresh is older than the specified time frame, it returns a Promise that resolves\n * when the next background refresh completes or rejects if the refresh takes too long.\n */\n public noOlderThan(ms: number) {\n const horizon = Date.now() - ms;\n\n // The last refresh happened within the time frame\n if (this.lastRefreshTime >= horizon) {\n return Promise.resolve();\n }\n\n // The last refresh happened earlier than the time frame\n // We will wait for the latest refresh to land or reject if it takes too long\n return Promise.race([\n new Promise(resolve => this.queuedPromises.push(resolve)),\n new Promise((_, reject) => setTimeout(() => reject(new ToolkitError('refreshStacks took too long; the background thread likely threw an error')), ms)),\n ]);\n }\n\n public stop() {\n clearTimeout(this.timeout);\n }\n}\n", "import * as util from 'util';\nimport type * as cxapi from '@aws-cdk/cx-api';\nimport * as chalk from 'chalk';\nimport * as uuid from 'uuid';\nimport type { CloudWatchLogEvent } from '../../payloads/logs-monitor';\nimport { flatten } from '../../util';\nimport type { SDK } from '../aws-auth';\nimport { IO } from '../io/private';\nimport type { IoHelper } from '../io/private';\n\n/**\n * Configuration tracking information on the log groups that are\n * being monitored\n */\ninterface LogGroupsAccessSettings {\n /**\n * The SDK for a given environment (account/region)\n */\n readonly sdk: SDK;\n\n /**\n * A map of log groups and associated startTime in a given account.\n *\n * The monitor will read events from the log group starting at the\n * associated startTime\n */\n readonly logGroupsStartTimes: { [logGroupName: string]: number };\n}\n\nexport interface CloudWatchLogEventMonitorProps {\n /**\n * The IoHost used for messaging\n */\n readonly ioHelper: IoHelper;\n\n /**\n * The time from which we start reading log messages\n *\n * @default - now\n */\n readonly startTime?: Date;\n}\n\nexport class CloudWatchLogEventMonitor {\n /**\n * Determines which events not to display\n */\n private startTime: number;\n\n /**\n * Map of environment (account:region) to LogGroupsAccessSettings\n */\n private readonly envsLogGroupsAccessSettings = new Map<string, LogGroupsAccessSettings>();\n\n /**\n * After reading events from all CloudWatch log groups\n * how long should we wait to read more events.\n *\n * If there is some error with reading events (i.e. Throttle)\n * then this is also how long we wait until we try again\n */\n private readonly pollingInterval: number = 2_000;\n\n public monitorId?: string;\n private readonly ioHelper: IoHelper;\n\n constructor(props: CloudWatchLogEventMonitorProps) {\n this.startTime = props.startTime?.getTime() ?? Date.now();\n this.ioHelper = props.ioHelper;\n }\n\n /**\n * resume reading/printing events\n */\n public async activate(): Promise<void> {\n this.monitorId = uuid.v4();\n\n await this.ioHelper.notify(IO.CDK_TOOLKIT_I5032.msg('Start monitoring log groups', {\n monitor: this.monitorId,\n logGroupNames: this.logGroupNames(),\n }));\n\n await this.tick();\n this.scheduleNextTick();\n }\n\n /**\n * deactivates the monitor so no new events are read\n * use case for this is when we are in the middle of performing a deployment\n * and don't want to interweave all the logs together with the CFN\n * deployment logs\n *\n * Also resets the start time to be when the new deployment was triggered\n * and clears the list of tracked log groups\n */\n public async deactivate(): Promise<void> {\n const oldMonitorId = this.monitorId!;\n this.monitorId = undefined;\n this.startTime = Date.now();\n\n await this.ioHelper.notify(IO.CDK_TOOLKIT_I5034.msg('Stopped monitoring log groups', {\n monitor: oldMonitorId,\n logGroupNames: this.logGroupNames(),\n }));\n\n this.envsLogGroupsAccessSettings.clear();\n }\n\n /**\n * Adds CloudWatch log groups to read log events from.\n * Since we could be watching multiple stacks that deploy to\n * multiple environments (account+region), we need to store a list of log groups\n * per env along with the SDK object that has access to read from\n * that environment.\n */\n public addLogGroups(env: cxapi.Environment, sdk: SDK, logGroupNames: string[]): void {\n const awsEnv = `${env.account}:${env.region}`;\n const logGroupsStartTimes = logGroupNames.reduce(\n (acc, groupName) => {\n acc[groupName] = this.startTime;\n return acc;\n },\n {} as { [logGroupName: string]: number },\n );\n this.envsLogGroupsAccessSettings.set(awsEnv, {\n sdk,\n logGroupsStartTimes: {\n ...this.envsLogGroupsAccessSettings.get(awsEnv)?.logGroupsStartTimes,\n ...logGroupsStartTimes,\n },\n });\n }\n\n private logGroupNames(): string[] {\n return Array.from(this.envsLogGroupsAccessSettings.values()).flatMap((settings) => Object.keys(settings.logGroupsStartTimes));\n }\n\n private scheduleNextTick(): void {\n if (!this.monitorId) {\n return;\n }\n\n setTimeout(() => void this.tick(), this.pollingInterval);\n }\n\n private async tick(): Promise<void> {\n // excluding from codecoverage because this\n // doesn't always run (depends on timing)\n /* c8 ignore start */\n if (!this.monitorId) {\n return;\n }\n /* c8 ignore stop */\n\n try {\n const events = flatten(await this.readNewEvents());\n for (const event of events) {\n await this.print(event);\n }\n\n // We might have been stop()ped while the network call was in progress.\n if (!this.monitorId) {\n return;\n }\n } catch (e: any) {\n await this.ioHelper.notify(IO.CDK_TOOLKIT_E5035.msg('Error occurred while monitoring logs: %s', { error: e }));\n }\n\n this.scheduleNextTick();\n }\n\n /**\n * Reads all new log events from a set of CloudWatch Log Groups\n * in parallel\n */\n private async readNewEvents(): Promise<Array<Array<CloudWatchLogEvent>>> {\n const promises: Array<Promise<Array<CloudWatchLogEvent>>> = [];\n for (const settings of this.envsLogGroupsAccessSettings.values()) {\n for (const group of Object.keys(settings.logGroupsStartTimes)) {\n promises.push(this.readEventsFromLogGroup(settings, group));\n }\n }\n // Limited set of log groups\n // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism\n return Promise.all(promises);\n }\n\n /**\n * Print out a cloudwatch event\n */\n private async print(event: CloudWatchLogEvent): Promise<void> {\n await this.ioHelper.notify(IO.CDK_TOOLKIT_I5033.msg(\n util.format(\n '[%s] %s %s',\n chalk.blue(event.logGroupName),\n chalk.yellow(event.timestamp.toLocaleTimeString()),\n event.message.trim(),\n ),\n event,\n ));\n }\n\n /**\n * Reads all new log events from a CloudWatch Log Group\n * starting at either the time the hotswap was triggered or\n * when the last event was read on the previous tick\n */\n private async readEventsFromLogGroup(\n logGroupsAccessSettings: LogGroupsAccessSettings,\n logGroupName: string,\n ): Promise<Array<CloudWatchLogEvent>> {\n const events: CloudWatchLogEvent[] = [];\n\n // log events from some service are ingested faster than others\n // so we need to track the start/end time for each log group individually\n // to make sure that we process all events from each log group\n const startTime = logGroupsAccessSettings.logGroupsStartTimes[logGroupName] ?? this.startTime;\n let endTime = startTime;\n try {\n const response = await logGroupsAccessSettings.sdk.cloudWatchLogs().filterLogEvents({\n logGroupName: logGroupName,\n limit: 100,\n startTime: startTime,\n });\n const filteredEvents = response.events ?? [];\n\n for (const event of filteredEvents) {\n if (event.message) {\n events.push({\n message: event.message,\n logGroupName,\n timestamp: event.timestamp ? new Date(event.timestamp) : new Date(),\n });\n\n if (event.timestamp && endTime < event.timestamp) {\n endTime = event.timestamp;\n }\n }\n }\n // As long as there are _any_ events in the log group `filterLogEvents` will return a nextToken.\n // This is true even if these events are before `startTime`. So if we have 100 events and a nextToken\n // then assume that we have hit the limit and let the user know some messages have been suppressed.\n // We are essentially showing them a sampling (10000 events printed out is not very useful)\n if (filteredEvents.length === 100 && response.nextToken) {\n events.push({\n message: '>>> `watch` shows only the first 100 log messages - the rest have been truncated...',\n logGroupName,\n timestamp: new Date(endTime),\n });\n }\n } catch (e: any) {\n // with Lambda functions the CloudWatch is not created\n // until something is logged, so just keep polling until\n // there is somthing to find\n if (e.name === 'ResourceNotFoundException') {\n return [];\n }\n throw e;\n }\n logGroupsAccessSettings.logGroupsStartTimes[logGroupName] = endTime + 1;\n return events;\n }\n}\n", "import type { CloudFormationStackArtifact, Environment } from '@aws-cdk/cx-api';\nimport type { StackResourceSummary } from '@aws-sdk/client-cloudformation';\nimport { formatErrorMessage } from '../../util';\nimport type { SDK, SdkProvider } from '../aws-auth';\nimport { EvaluateCloudFormationTemplate, LazyListStackResources } from '../cloudformation';\nimport { EnvironmentAccess } from '../environment';\nimport { IO } from '../io/private';\nimport type { IoHelper } from '../io/private';\nimport { Mode } from '../plugin';\nimport { DEFAULT_TOOLKIT_STACK_NAME } from '../toolkit-info';\n\n// resource types that have associated CloudWatch Log Groups that should _not_ be monitored\nconst IGNORE_LOGS_RESOURCE_TYPES = ['AWS::EC2::FlowLog', 'AWS::CloudTrail::Trail', 'AWS::CodeBuild::Project'];\n\n/**\n * Configuration needed to monitor CloudWatch Log Groups\n * found in a given CloudFormation Stack\n */\nexport interface FoundLogGroupsResult {\n /**\n * The resolved environment (account/region) that the log\n * groups are deployed in\n */\n readonly env: Environment;\n\n /**\n * The SDK that can be used to read events from the CloudWatch\n * Log Groups in the given environment\n */\n readonly sdk: SDK;\n\n /**\n * The names of the relevant CloudWatch Log Groups\n * in the given CloudFormation template\n */\n readonly logGroupNames: string[];\n}\n\nexport async function findCloudWatchLogGroups(\n sdkProvider: SdkProvider,\n ioHelper: IoHelper,\n stackArtifact: CloudFormationStackArtifact,\n): Promise<FoundLogGroupsResult> {\n let sdk: SDK;\n const resolvedEnv = await sdkProvider.resolveEnvironment(stackArtifact.environment);\n // try to assume the lookup role and fallback to the default credentials\n try {\n sdk = (await new EnvironmentAccess(sdkProvider, DEFAULT_TOOLKIT_STACK_NAME, ioHelper).accessStackForLookup(stackArtifact)).sdk;\n } catch (e: any) {\n await ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`Failed to access SDK environment: ${formatErrorMessage(e)}`));\n sdk = (await sdkProvider.forEnvironment(resolvedEnv, Mode.ForReading)).sdk;\n }\n\n const listStackResources = new LazyListStackResources(sdk, stackArtifact.stackName);\n const evaluateCfnTemplate = new EvaluateCloudFormationTemplate({\n stackArtifact,\n parameters: {},\n account: resolvedEnv.account,\n region: resolvedEnv.region,\n partition: (await sdk.currentAccount()).partition,\n sdk,\n });\n\n const stackResources = await listStackResources.listStackResources();\n const logGroupNames = findAllLogGroupNames(stackResources, evaluateCfnTemplate);\n\n return {\n env: resolvedEnv,\n sdk,\n logGroupNames,\n };\n}\n\n/**\n * Determine if a CloudWatch Log Group is associated\n * with an ignored resource\n */\nfunction isReferencedFromIgnoredResource(\n logGroupResource: StackResourceSummary,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): boolean {\n const resourcesReferencingLogGroup = evaluateCfnTemplate.findReferencesTo(logGroupResource.LogicalResourceId!);\n return resourcesReferencingLogGroup.some((reference) => {\n return IGNORE_LOGS_RESOURCE_TYPES.includes(reference.Type);\n });\n}\n\ntype CloudWatchLogsResolver = (\n resource: StackResourceSummary,\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n) => string | undefined;\n\nconst cloudWatchLogsResolvers: Record<string, CloudWatchLogsResolver> = {\n 'AWS::Logs::LogGroup': (resource, evaluateCfnTemplate) => {\n if (isReferencedFromIgnoredResource(resource, evaluateCfnTemplate)) {\n return undefined;\n }\n return resource.PhysicalResourceId?.toString();\n },\n\n // Resource types that will create a CloudWatch log group with a specific name if one is not provided.\n // The keys are CFN resource types, and the values are the name of the physical name property of that resource\n // and the service name that is used in the automatically created CloudWatch log group.\n 'AWS::Lambda::Function': (resource, evaluateCfnTemplate) => {\n const loggingConfig = evaluateCfnTemplate.getResourceProperty(resource.LogicalResourceId!, 'LoggingConfig');\n if (loggingConfig?.LogGroup) {\n // if LogGroup is a string then use it as the LogGroupName as it is referred by LogGroup.fromLogGroupArn in CDK\n if (typeof loggingConfig.LogGroup === 'string') {\n return loggingConfig.LogGroup;\n }\n\n // if { Ref: '...' } is used then try to resolve the LogGroupName from the referenced resource in the template\n if (typeof loggingConfig.LogGroup === 'object') {\n if (loggingConfig.LogGroup.Ref) {\n return evaluateCfnTemplate.getResourceProperty(loggingConfig.LogGroup.Ref, 'LogGroupName');\n }\n }\n }\n\n return `/aws/lambda/${resource.PhysicalResourceId}`;\n },\n};\n\n/**\n * Find all CloudWatch Log Groups in the deployed template.\n * This will find both explicitly created Log Groups (excluding those associated with ignored resources)\n * and Log Groups created implicitly (i.e. Lambda Functions)\n */\nfunction findAllLogGroupNames(\n stackResources: StackResourceSummary[],\n evaluateCfnTemplate: EvaluateCloudFormationTemplate,\n): string[] {\n const logGroupNames: string[] = [];\n\n for (const resource of stackResources) {\n const logGroupResolver = cloudWatchLogsResolvers[resource.ResourceType!];\n if (logGroupResolver) {\n const logGroupName = logGroupResolver(resource, evaluateCfnTemplate);\n if (logGroupName) {\n logGroupNames.push(logGroupName);\n }\n }\n }\n\n return logGroupNames;\n}\n", "import type { TypedMapping } from '@aws-cdk/cloudformation-diff';\nimport {\n formatAmbiguousMappings as fmtAmbiguousMappings,\n formatTypedMappings as fmtTypedMappings,\n} from '@aws-cdk/cloudformation-diff';\nimport type * as cxapi from '@aws-cdk/cx-api';\nimport type { StackSummary } from '@aws-sdk/client-cloudformation';\nimport { deserializeStructure } from '../../util';\nimport type { SdkProvider } from '../aws-auth';\nimport { Mode } from '../plugin';\nimport { StringWriteStream } from '../streams';\nimport type { CloudFormationStack } from './cloudformation';\nimport { computeResourceDigests, hashObject } from './digest';\n\n/**\n * Represents a set of possible movements of a resource from one location\n * to another. In the ideal case, there is only one source and only one\n * destination.\n */\nexport type ResourceMovement = [ResourceLocation[], ResourceLocation[]];\n\nexport class AmbiguityError extends Error {\n constructor(public readonly movements: ResourceMovement[]) {\n super('Ambiguous resource mappings');\n }\n\n public paths(): [string[], string[]][] {\n return this.movements.map(([a, b]) => [convert(a), convert(b)]);\n\n function convert(locations: ResourceLocation[]): string[] {\n return locations.map((l) => l.toPath());\n }\n }\n}\n\n/**\n * This class mirrors the `ResourceLocation` interface from CloudFormation,\n * but is richer, since it has a reference to the stack object, rather than\n * merely the stack name.\n */\nexport class ResourceLocation {\n constructor(readonly stack: CloudFormationStack, readonly logicalResourceId: string) {\n }\n\n public toPath(): string {\n const stack = this.stack;\n const resource = stack.template.Resources?.[this.logicalResourceId];\n const result = resource?.Metadata?.['aws:cdk:path'];\n\n if (result != null) {\n return result;\n }\n\n // If the path is not available, we can use stack name and logical ID\n return `${stack.stackName}.${this.logicalResourceId}`;\n }\n\n public getType(): string {\n const resource = this.stack.template.Resources?.[this.logicalResourceId ?? ''];\n return resource?.Type ?? 'Unknown';\n }\n\n public equalTo(other: ResourceLocation): boolean {\n return this.logicalResourceId === other.logicalResourceId && this.stack.stackName === other.stack.stackName;\n }\n}\n\n/**\n * A mapping between a source and a destination location.\n */\nexport class ResourceMapping {\n constructor(public readonly source: ResourceLocation, public readonly destination: ResourceLocation) {\n }\n\n public toTypedMapping(): TypedMapping {\n return {\n // the type is the same in both source and destination,\n // so we can use either one\n type: this.source.getType(),\n sourcePath: this.source.toPath(),\n destinationPath: this.destination.toPath(),\n };\n }\n}\n\nfunction groupByKey<A>(entries: [string, A][]): Record<string, A[]> {\n const result: Record<string, A[]> = {};\n\n for (const [hash, location] of entries) {\n if (hash in result) {\n result[hash].push(location);\n } else {\n result[hash] = [location];\n }\n }\n\n return result;\n}\n\nexport function resourceMovements(before: CloudFormationStack[], after: CloudFormationStack[]): ResourceMovement[] {\n return Object.values(\n removeUnmovedResources(\n zip(groupByKey(before.flatMap(resourceDigests)), groupByKey(after.flatMap(resourceDigests))),\n ),\n );\n}\n\nexport function ambiguousMovements(movements: ResourceMovement[]) {\n // A movement is considered ambiguous if these two conditions are met:\n // 1. Both sides have at least one element (otherwise, it's just addition or deletion)\n // 2. At least one side has more than one element\n return movements\n .filter(([pre, post]) => pre.length > 0 && post.length > 0)\n .filter(([pre, post]) => pre.length > 1 || post.length > 1);\n}\n\n/**\n * Converts a list of unambiguous resource movements into a list of resource mappings.\n *\n */\nexport function resourceMappings(movements: ResourceMovement[]): ResourceMapping[] {\n return movements\n .filter(([pre, post]) => pre.length === 1 && post.length === 1 && !pre[0].equalTo(post[0]))\n .map(([pre, post]) => new ResourceMapping(pre[0], post[0]));\n}\n\nfunction removeUnmovedResources(\n m: Record<string, ResourceMovement>,\n): Record<string, ResourceMovement> {\n const result: Record<string, ResourceMovement> = {};\n for (const [hash, [before, after]] of Object.entries(m)) {\n const common = before.filter((b) => after.some((a) => a.equalTo(b)));\n result[hash] = [\n before.filter((b) => !common.some((c) => b.equalTo(c))),\n after.filter((a) => !common.some((c) => a.equalTo(c))),\n ];\n }\n\n return result;\n}\n\n/**\n * For each hash, identifying a single resource, zip the two lists of locations,\n * producing a resource movement\n */\nfunction zip(\n m1: Record<string, ResourceLocation[]>,\n m2: Record<string, ResourceLocation[]>,\n): Record<string, ResourceMovement> {\n const result: Record<string, ResourceMovement> = {};\n\n for (const [hash, locations] of Object.entries(m1)) {\n if (hash in m2) {\n result[hash] = [locations, m2[hash]];\n } else {\n result[hash] = [locations, []];\n }\n }\n\n for (const [hash, locations] of Object.entries(m2)) {\n if (!(hash in m1)) {\n result[hash] = [[], locations];\n }\n }\n\n return result;\n}\n\n/**\n * Computes a list of pairs [digest, location] for each resource in the stack.\n */\nfunction resourceDigests(stack: CloudFormationStack): [string, ResourceLocation][] {\n const digests = computeResourceDigests(stack.template);\n\n return Object.entries(digests).map(([logicalId, digest]) => {\n const location: ResourceLocation = new ResourceLocation(stack, logicalId);\n return [digest, location];\n });\n}\n\n/**\n * Compares the deployed state to the cloud assembly state, and finds all resources\n * that were moved from one location (stack + logical ID) to another. The comparison\n * is done per environment.\n */\nexport async function findResourceMovements(\n stacks: CloudFormationStack[],\n sdkProvider: SdkProvider,\n): Promise<ResourceMovement[]> {\n const stackGroups: Map<string, [CloudFormationStack[], CloudFormationStack[]]> = new Map();\n\n // Group stacks by environment\n for (const stack of stacks) {\n const environment = stack.environment;\n const key = hashObject(environment);\n if (stackGroups.has(key)) {\n stackGroups.get(key)![1].push(stack);\n } else {\n // The first time we see an environment, we need to fetch all stacks deployed to it.\n const before = await getDeployedStacks(sdkProvider, environment);\n stackGroups.set(key, [before, [stack]]);\n }\n }\n\n const result: ResourceMovement[] = [];\n for (const [_, [before, after]] of stackGroups) {\n result.push(...resourceMovements(before, after));\n }\n return result;\n}\n\nasync function getDeployedStacks(\n sdkProvider: SdkProvider,\n environment: cxapi.Environment,\n): Promise<CloudFormationStack[]> {\n const cfn = (await sdkProvider.forEnvironment(environment, Mode.ForReading)).sdk.cloudFormation();\n\n const summaries = await cfn.paginatedListStacks({\n StackStatusFilter: [\n 'CREATE_COMPLETE',\n 'UPDATE_COMPLETE',\n 'UPDATE_ROLLBACK_COMPLETE',\n 'IMPORT_COMPLETE',\n 'ROLLBACK_COMPLETE',\n ],\n });\n\n const normalize = async (summary: StackSummary) => {\n const templateCommandOutput = await cfn.getTemplate({ StackName: summary.StackName! });\n const template = deserializeStructure(templateCommandOutput.TemplateBody ?? '{}');\n return {\n environment,\n stackName: summary.StackName!,\n template,\n };\n };\n\n // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism\n return Promise.all(summaries.map(normalize));\n}\n\nexport function formatTypedMappings(mappings: TypedMapping[]): string {\n const stream = new StringWriteStream();\n fmtTypedMappings(stream, mappings);\n return stream.toString();\n}\n\nexport function formatAmbiguousMappings(paths: [string[], string[]][]): string {\n const stream = new StringWriteStream();\n fmtAmbiguousMappings(stream, paths);\n return stream.toString();\n}\n", "import * as crypto from 'node:crypto';\nimport { loadResourceModel } from '@aws-cdk/cloudformation-diff/lib/diff/util';\nimport type { CloudFormationTemplate } from './cloudformation';\n\n/**\n * Computes the digest for each resource in the template.\n *\n * Conceptually, the digest is computed as:\n *\n * d(resource) = hash(type + physicalId) , if physicalId is defined\n * = hash(type + properties + dependencies.map(d)) , otherwise\n *\n * where `hash` is a cryptographic hash function. In other words, if a resource has\n * a physical ID, we use the physical ID plus its type to uniquely identify\n * that resource. In this case, the digest can be computed from these two fields\n * alone. A corollary is that such resources can be renamed and have their\n * properties updated at the same time, and still be considered equivalent.\n *\n * Otherwise, the digest is computed from its type, its own properties (that is,\n * excluding properties that refer to other resources), and the digests of each of\n * its dependencies.\n *\n * The digest of a resource, defined recursively this way, remains stable even if\n * one or more of its dependencies gets renamed. Since the resources in a\n * CloudFormation template form a directed acyclic graph, this function is\n * well-defined.\n */\nexport function computeResourceDigests(template: CloudFormationTemplate): Record<string, string> {\n const resources = template.Resources || {};\n const graph: Record<string, Set<string>> = {};\n const reverseGraph: Record<string, Set<string>> = {};\n\n // 1. Build adjacency lists\n for (const id of Object.keys(resources)) {\n graph[id] = new Set();\n reverseGraph[id] = new Set();\n }\n\n // 2. Detect dependencies by searching for Ref/Fn::GetAtt\n const findDependencies = (value: any): string[] => {\n if (!value || typeof value !== 'object') return [];\n if (Array.isArray(value)) {\n return value.flatMap(findDependencies);\n }\n if ('Ref' in value) {\n return [value.Ref];\n }\n if ('Fn::GetAtt' in value) {\n const refTarget = Array.isArray(value['Fn::GetAtt']) ? value['Fn::GetAtt'][0] : value['Fn::GetAtt'].split('.')[0];\n return [refTarget];\n }\n if ('DependsOn' in value) {\n return [value.DependsOn];\n }\n return Object.values(value).flatMap(findDependencies);\n };\n\n for (const [id, res] of Object.entries(resources)) {\n const deps = findDependencies(res || {});\n for (const dep of deps) {\n if (dep in resources && dep !== id) {\n graph[id].add(dep);\n reverseGraph[dep].add(id);\n }\n }\n }\n\n // 3. Topological sort\n const outDegree = Object.keys(graph).reduce((acc, k) => {\n acc[k] = graph[k].size;\n return acc;\n }, {} as Record<string, number>);\n\n const queue = Object.keys(outDegree).filter((k) => outDegree[k] === 0);\n const order: string[] = [];\n\n while (queue.length > 0) {\n const node = queue.shift()!;\n order.push(node);\n for (const nxt of reverseGraph[node]) {\n outDegree[nxt]--;\n if (outDegree[nxt] === 0) {\n queue.push(nxt);\n }\n }\n }\n\n // 4. Compute digests in sorted order\n const result: Record<string, string> = {};\n for (const id of order) {\n const resource = resources[id];\n const resourceProperties = resource.Properties ?? {};\n const model = loadResourceModel(resource.Type);\n const identifier = intersection(Object.keys(resourceProperties), model?.primaryIdentifier ?? []);\n let toHash: string;\n\n if (identifier.length === model?.primaryIdentifier?.length) {\n // The resource has a physical ID defined, so we can\n // use the ID and the type as the identity of the resource.\n toHash =\n resource.Type +\n identifier\n .sort()\n .map((attr) => JSON.stringify(resourceProperties[attr]))\n .join('');\n } else {\n // The resource does not have a physical ID defined, so we need to\n // compute the digest based on its properties and dependencies.\n const depDigests = Array.from(graph[id]).map((d) => result[d]);\n const propertiesHash = hashObject(stripReferences(stripConstructPath(resource)));\n toHash = resource.Type + propertiesHash + depDigests.join('');\n }\n\n result[id] = crypto.createHash('sha256').update(toHash).digest('hex');\n }\n\n return result;\n}\n\nexport function hashObject(obj: any): string {\n const hash = crypto.createHash('sha256');\n\n function addToHash(value: any) {\n if (value == null) {\n addToHash('null');\n } else if (typeof value === 'object') {\n if (Array.isArray(value)) {\n value.forEach(addToHash);\n } else {\n Object.keys(value)\n .sort()\n .forEach((key) => {\n hash.update(key);\n addToHash(value[key]);\n });\n }\n } else {\n hash.update(typeof value + value.toString());\n }\n }\n\n addToHash(obj);\n return hash.digest('hex');\n}\n\n/**\n * Removes sub-properties containing Ref or Fn::GetAtt to avoid hashing\n * references themselves but keeps the property structure.\n */\nfunction stripReferences(value: any): any {\n if (!value || typeof value !== 'object') return value;\n if (Array.isArray(value)) {\n return value.map(stripReferences);\n }\n if ('Ref' in value) {\n return { __cloud_ref__: 'Ref' };\n }\n if ('Fn::GetAtt' in value) {\n return { __cloud_ref__: 'Fn::GetAtt' };\n }\n if ('DependsOn' in value) {\n return { __cloud_ref__: 'DependsOn' };\n }\n const result: any = {};\n for (const [k, v] of Object.entries(value)) {\n result[k] = stripReferences(v);\n }\n return result;\n}\n\nfunction stripConstructPath(resource: any): any {\n if (resource?.Metadata?.['aws:cdk:path'] == null) {\n return resource;\n }\n\n const copy = JSON.parse(JSON.stringify(resource));\n delete copy.Metadata['aws:cdk:path'];\n return copy;\n}\n\nfunction intersection<T>(a: T[], b: T[]): T[] {\n return a.filter((value) => b.includes(value));\n}\n", "import { format } from 'util';\nimport * as cfnDiff from '@aws-cdk/cloudformation-diff';\nimport type { ResourceDifference } from '@aws-cdk/cloudformation-diff';\nimport type * as cxapi from '@aws-cdk/cx-api';\nimport type { ResourceIdentifierSummary, ResourceToImport } from '@aws-sdk/client-cloudformation';\nimport * as chalk from 'chalk';\nimport * as fs from 'fs-extra';\nimport * as promptly from 'promptly';\nimport type { DeploymentMethod, Deployments } from '../deployments';\nimport { assertIsSuccessfulDeployStackResult } from '../deployments';\nimport { IO, type IoHelper } from '../io/private';\nimport type { Tag } from '../tags';\nimport { ToolkitError } from '../toolkit-error';\n\nexport type ResourcesToImport = ResourceToImport[];\nexport type ResourceIdentifierSummaries = ResourceIdentifierSummary[];\n\nexport interface ResourceImporterProps {\n deployments: Deployments;\n ioHelper: IoHelper;\n}\n\nexport interface ImportDeploymentOptions {\n /**\n * Role to pass to CloudFormation for deployment\n *\n * @default - Default stack role\n */\n readonly roleArn?: string;\n\n /**\n * Deployment method\n *\n * @default - Change set with default options\n */\n readonly deploymentMethod?: DeploymentMethod;\n\n /**\n * Stack tags (pass through to CloudFormation)\n *\n * @default - No tags\n */\n readonly tags?: Tag[];\n\n /**\n * Use previous values for unspecified parameters\n *\n * If not set, all parameters must be specified for every deployment.\n *\n * @default true\n */\n readonly usePreviousParameters?: boolean;\n\n /**\n * Rollback failed deployments\n *\n * @default true\n */\n readonly rollback?: boolean;\n}\n\n/**\n * Set of parameters that uniquely identify a physical resource of a given type\n * for the import operation, example:\n *\n * ```\n * {\n * \"AWS::S3::Bucket\": [[\"BucketName\"]],\n * \"AWS::DynamoDB::GlobalTable\": [[\"TableName\"], [\"TableArn\"], [\"TableStreamArn\"]],\n * \"AWS::Route53::KeySigningKey\": [[\"HostedZoneId\", \"Name\"]],\n * }\n * ```\n */\nexport type ResourceIdentifiers = { [resourceType: string]: string[][] };\n\ntype ResourceIdentifierProperties = Record<string, string>;\n\n/**\n * Mapping of CDK resources (L1 constructs) to physical resources to be imported\n * in their place, example:\n *\n * ```\n * {\n * \"MyStack/MyS3Bucket/Resource\": {\n * \"BucketName\": \"my-manually-created-s3-bucket\"\n * },\n * \"MyStack/MyVpc/Resource\": {\n * \"VpcId\": \"vpc-123456789\"\n * }\n * }\n * ```\n */\ntype ResourceMap = { [logicalResource: string]: ResourceIdentifierProperties };\n\n/**\n * Resource importing utility class\n *\n * - Determines the resources added to a template (compared to the deployed version)\n * - Look up the identification information\n * - Load them from a file, or\n * - Ask the user, based on information supplied to us by CloudFormation's GetTemplateSummary\n * - Translate the input to a structure expected by CloudFormation, update the template to add the\n * importable resources, then run an IMPORT changeset.\n */\nexport class ResourceImporter {\n private _currentTemplate: any;\n\n private readonly stack: cxapi.CloudFormationStackArtifact;\n private readonly cfn: Deployments;\n private readonly ioHelper: IoHelper;\n\n constructor(\n stack: cxapi.CloudFormationStackArtifact,\n props: ResourceImporterProps,\n ) {\n this.stack = stack;\n this.cfn = props.deployments;\n this.ioHelper = props.ioHelper;\n }\n\n /**\n * Ask the user for resources to import\n */\n public async askForResourceIdentifiers(available: ImportableResource[]): Promise<ImportMap> {\n const ret: ImportMap = { importResources: [], resourceMap: {} };\n const resourceIdentifiers = await this.resourceIdentifiers();\n\n for (const resource of available) {\n const identifier = await this.askForResourceIdentifier(resourceIdentifiers, resource);\n if (!identifier) {\n continue;\n }\n\n ret.importResources.push(resource);\n ret.resourceMap[resource.logicalId] = identifier;\n }\n\n return ret;\n }\n\n /**\n * Load the resources to import from a file\n */\n public async loadResourceIdentifiers(available: ImportableResource[], filename: string): Promise<ImportMap> {\n const contents = await fs.readJson(filename);\n\n const ret: ImportMap = { importResources: [], resourceMap: {} };\n for (const resource of available) {\n const descr = this.describeResource(resource.logicalId);\n const idProps = contents[resource.logicalId];\n if (idProps) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(format('%s: importing using %s', chalk.blue(descr), chalk.blue(fmtdict(idProps)))));\n\n ret.importResources.push(resource);\n ret.resourceMap[resource.logicalId] = idProps;\n delete contents[resource.logicalId];\n } else {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(format('%s: skipping', chalk.blue(descr))));\n }\n }\n\n const unknown = Object.keys(contents);\n if (unknown.length > 0) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_WARN.msg(`Unrecognized resource identifiers in mapping file: ${unknown.join(', ')}`));\n }\n\n return ret;\n }\n\n /**\n * Based on the provided resource mapping, prepare CFN structures for import (template,\n * ResourcesToImport structure) and perform the import operation (CloudFormation deployment)\n *\n * @param importMap Mapping from CDK construct tree path to physical resource import identifiers\n * @param options Options to pass to CloudFormation deploy operation\n */\n public async importResourcesFromMap(importMap: ImportMap, options: ImportDeploymentOptions = {}) {\n const resourcesToImport: ResourcesToImport = await this.makeResourcesToImport(importMap);\n const updatedTemplate = await this.currentTemplateWithAdditions(importMap.importResources);\n\n await this.importResources(updatedTemplate, resourcesToImport, options);\n }\n\n /**\n * Based on the app and resources file generated by cdk migrate. Removes all items from the template that\n * cannot be included in an import change-set for new stacks and performs the import operation,\n * creating the new stack.\n *\n * @param resourcesToImport The mapping created by cdk migrate\n * @param options Options to pass to CloudFormation deploy operation\n */\n public async importResourcesFromMigrate(resourcesToImport: ResourcesToImport, options: ImportDeploymentOptions = {}) {\n const updatedTemplate = this.removeNonImportResources();\n\n await this.importResources(updatedTemplate, resourcesToImport, options);\n }\n\n private async importResources(overrideTemplate: any, resourcesToImport: ResourcesToImport, options: ImportDeploymentOptions) {\n try {\n const result = await this.cfn.deployStack({\n stack: this.stack,\n deployName: this.stack.stackName,\n ...options,\n overrideTemplate,\n resourcesToImport,\n });\n\n assertIsSuccessfulDeployStackResult(result);\n\n const message = result.noOp\n ? ' \u2705 %s (no changes)'\n : ' \u2705 %s';\n\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg('\\n' + chalk.green(format(message, this.stack.displayName))));\n } catch (e) {\n await this.ioHelper.notify(IO.CDK_TOOLKIT_E3900.msg(format('\\n \u274C %s failed: %s', chalk.bold(this.stack.displayName), e), { error: e as any }));\n throw e;\n }\n }\n\n /**\n * Perform a diff between the currently running and the new template, ensure that it is valid\n * for importing and return a list of resources that are being added in the new version\n *\n * @return mapping logicalResourceId -> resourceDifference\n */\n public async discoverImportableResources(allowNonAdditions = false): Promise<DiscoverImportableResourcesResult> {\n const currentTemplate = await this.currentTemplate();\n\n const diff = cfnDiff.fullDiff(currentTemplate, this.stack.template);\n\n // Ignore changes to CDKMetadata\n const resourceChanges = Object.entries(diff.resources.changes)\n .filter(([logicalId, _]) => logicalId !== 'CDKMetadata');\n\n // Split the changes into additions and non-additions. Imports only make sense\n // for newly-added resources.\n const nonAdditions = resourceChanges.filter(([_, dif]) => !dif.isAddition);\n const additions = resourceChanges.filter(([_, dif]) => dif.isAddition);\n\n if (nonAdditions.length) {\n const offendingResources = nonAdditions.map(([logId, _]) => this.describeResource(logId));\n\n if (allowNonAdditions) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_WARN.msg(`Ignoring updated/deleted resources (--force): ${offendingResources.join(', ')}`));\n } else {\n throw new ToolkitError('No resource updates or deletes are allowed on import operation. Make sure to resolve pending changes ' +\n `to existing resources, before attempting an import. Updated/deleted resources: ${offendingResources.join(', ')} (--force to override)`);\n }\n }\n\n // Resources in the new template, that are not present in the current template, are a potential import candidates\n return {\n additions: additions.map(([logicalId, resourceDiff]) => ({\n logicalId,\n resourceDiff,\n resourceDefinition: addDefaultDeletionPolicy(this.stack.template?.Resources?.[logicalId] ?? {}),\n })),\n hasNonAdditions: nonAdditions.length > 0,\n };\n }\n\n /**\n * Resolves the environment of a stack.\n */\n public async resolveEnvironment(): Promise<cxapi.Environment> {\n return this.cfn.resolveEnvironment(this.stack);\n }\n\n /**\n * Get currently deployed template of the given stack (SINGLETON)\n *\n * @returns Currently deployed CloudFormation template\n */\n private async currentTemplate(): Promise<any> {\n if (!this._currentTemplate) {\n this._currentTemplate = await this.cfn.readCurrentTemplate(this.stack);\n }\n return this._currentTemplate;\n }\n\n /**\n * Return the current template, with the given resources added to it\n */\n private async currentTemplateWithAdditions(additions: ImportableResource[]): Promise<any> {\n const template = await this.currentTemplate();\n if (!template.Resources) {\n template.Resources = {};\n }\n\n for (const add of additions) {\n template.Resources[add.logicalId] = add.resourceDefinition;\n }\n\n return template;\n }\n\n /**\n * Get a list of import identifiers for all resource types used in the given\n * template that do support the import operation (SINGLETON)\n *\n * @returns a mapping from a resource type to a list of property names that together identify the resource for import\n */\n private async resourceIdentifiers(): Promise<ResourceIdentifiers> {\n const ret: ResourceIdentifiers = {};\n const resourceIdentifierSummaries = await this.cfn.resourceIdentifierSummaries(this.stack);\n for (const summary of resourceIdentifierSummaries) {\n if ('ResourceType' in summary && summary.ResourceType && 'ResourceIdentifiers' in summary && summary.ResourceIdentifiers) {\n ret[summary.ResourceType] = (summary.ResourceIdentifiers ?? [])?.map(x => x.split(','));\n }\n }\n return ret;\n }\n\n /**\n * Ask for the importable identifier for the given resource\n *\n * There may be more than one identifier under which a resource can be imported. The `import`\n * operation needs exactly one of them.\n *\n * - If we can get one from the template, we will use one.\n * - Otherwise, we will ask the user for one of them.\n */\n private async askForResourceIdentifier(\n resourceIdentifiers: ResourceIdentifiers,\n chg: ImportableResource,\n ): Promise<ResourceIdentifierProperties | undefined> {\n const resourceName = this.describeResource(chg.logicalId);\n\n // Skip resources that do not support importing\n const resourceType = chg.resourceDiff.newResourceType;\n if (resourceType === undefined || !(resourceType in resourceIdentifiers)) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_WARN.msg(`${resourceName}: unsupported resource type ${resourceType}, skipping import.`));\n return undefined;\n }\n\n const idPropSets = resourceIdentifiers[resourceType];\n\n // Retain only literal strings: strip potential CFN intrinsics\n const resourceProps = Object.fromEntries(Object.entries(chg.resourceDefinition.Properties ?? {})\n .filter(([_, v]) => typeof v === 'string')) as Record<string, string>;\n\n // Find property sets that are fully satisfied in the template, ask the user to confirm them\n const satisfiedPropSets = idPropSets.filter(ps => ps.every(p => resourceProps[p]));\n for (const satisfiedPropSet of satisfiedPropSets) {\n const candidateProps = Object.fromEntries(satisfiedPropSet.map(p => [p, resourceProps[p]]));\n const displayCandidateProps = fmtdict(candidateProps);\n\n if (await promptly.confirm(\n `${chalk.blue(resourceName)} (${resourceType}): import with ${chalk.yellow(displayCandidateProps)} (yes/no) [default: yes]? `,\n { default: 'yes' },\n )) {\n return candidateProps;\n }\n }\n\n // If we got here and the user rejected any available identifiers, then apparently they don't want the resource at all\n if (satisfiedPropSets.length > 0) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(chalk.grey(`Skipping import of ${resourceName}`)));\n return undefined;\n }\n\n // We cannot auto-import this, ask the user for one of the props\n // The only difference between these cases is what we print: for multiple properties, we print a preamble\n const prefix = `${chalk.blue(resourceName)} (${resourceType})`;\n let preamble;\n let promptPattern;\n if (idPropSets.length > 1) {\n preamble = `${prefix}: enter one of ${idPropSets.map(x => chalk.blue(x.join('+'))).join(', ')} to import (all empty to skip)`;\n promptPattern = `${prefix}: enter %`;\n } else {\n promptPattern = `${prefix}: enter %`;\n }\n\n // Do the input loop here\n if (preamble) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(preamble));\n }\n for (const idProps of idPropSets) {\n const input: Record<string, string> = {};\n for (const idProp of idProps) {\n // If we have a value from the template, use it as default. This will only be a partial\n // identifier if present, otherwise we would have done the import already above.\n const defaultValue = resourceProps[idProp] ?? '';\n\n const prompt = [\n promptPattern.replace(/%/g, chalk.blue(idProp)),\n defaultValue\n ? `[${defaultValue}]`\n : '(empty to skip)',\n ].join(' ') + ':';\n const response = await promptly.prompt(prompt,\n { default: defaultValue, trim: true },\n );\n\n if (!response) {\n break;\n }\n\n input[idProp] = response;\n // Also stick this property into 'resourceProps', so that it may be reused by a subsequent question\n // (for a different compound identifier that involves the same property). Just a small UX enhancement.\n resourceProps[idProp] = response;\n }\n\n // If the user gave inputs for all values, we are complete\n if (Object.keys(input).length === idProps.length) {\n return input;\n }\n }\n\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(chalk.grey(`Skipping import of ${resourceName}`)));\n return undefined;\n }\n\n /**\n * Convert the internal \"resource mapping\" structure to CloudFormation accepted \"ResourcesToImport\" structure\n */\n private async makeResourcesToImport(resourceMap: ImportMap): Promise<ResourcesToImport> {\n return resourceMap.importResources.map(res => ({\n LogicalResourceId: res.logicalId,\n ResourceType: res.resourceDiff.newResourceType!,\n ResourceIdentifier: resourceMap.resourceMap[res.logicalId],\n }));\n }\n\n /**\n * Convert CloudFormation logical resource ID to CDK construct tree path\n *\n * @param logicalId CloudFormation logical ID of the resource (the key in the template's Resources section)\n * @returns Forward-slash separated path of the resource in CDK construct tree, e.g. MyStack/MyBucket/Resource\n */\n private describeResource(logicalId: string): string {\n return this.stack.template?.Resources?.[logicalId]?.Metadata?.['aws:cdk:path'] ?? logicalId;\n }\n\n /**\n * Removes CDKMetadata and Outputs in the template so that only resources for importing are left.\n * @returns template with import resources only\n */\n private removeNonImportResources() {\n return removeNonImportResources(this.stack);\n }\n}\n\n/**\n * Information about a resource in the template that is importable\n */\nexport interface ImportableResource {\n /**\n * The logical ID of the resource\n */\n readonly logicalId: string;\n\n /**\n * The resource definition in the new template\n */\n readonly resourceDefinition: any;\n\n /**\n * The diff as reported by `cloudformation-diff`.\n */\n readonly resourceDiff: ResourceDifference;\n}\n\n/**\n * The information necessary to execute an import operation\n */\nexport interface ImportMap {\n /**\n * Mapping logical IDs to physical names\n */\n readonly resourceMap: ResourceMap;\n\n /**\n * The selection of resources we are actually importing\n *\n * For each of the resources in this list, there is a corresponding entry in\n * the `resourceMap` map.\n */\n readonly importResources: ImportableResource[];\n}\n\nfunction fmtdict<A>(xs: Record<string, A>) {\n return Object.entries(xs).map(([k, v]) => `${k}=${v}`).join(', ');\n}\n\n/**\n * Add a default `DeletionPolicy` policy.\n * The default value is set to 'Retain', to lower risk of unintentionally\n * deleting stateful resources in the process of importing to CDK.\n */\nfunction addDefaultDeletionPolicy(resource: any): any {\n if (resource.DeletionPolicy) {\n return resource;\n }\n\n return {\n ...resource,\n DeletionPolicy: 'Retain',\n };\n}\n\nexport interface DiscoverImportableResourcesResult {\n readonly additions: ImportableResource[];\n readonly hasNonAdditions: boolean;\n}\n\nexport function removeNonImportResources(stack:cxapi.CloudFormationStackArtifact) {\n const template = stack.template;\n delete template.Resources.CDKMetadata;\n delete template.Outputs;\n return template;\n}\n", "import type * as cxapi from '@aws-cdk/cx-api';\nimport * as chalk from 'chalk';\nimport * as fs from 'fs-extra';\nimport type { ImportDeploymentOptions, ResourcesToImport } from './importer';\nimport { ResourceImporter } from './importer';\nimport { formatTime } from '../../util';\nimport type { StackCollection } from '../cloud-assembly';\nimport type { Deployments } from '../deployments';\nimport { IO, type IoHelper } from '../io/private';\n\nexport interface ResourceMigratorProps {\n deployments: Deployments;\n ioHelper: IoHelper;\n}\n\nexport class ResourceMigrator {\n private readonly props: ResourceMigratorProps;\n private readonly ioHelper: IoHelper;\n\n public constructor(props: ResourceMigratorProps) {\n this.props = props;\n this.ioHelper = props.ioHelper;\n }\n\n /**\n * Checks to see if a migrate.json file exists. If it does and the source is either `filepath` or\n * is in the same environment as the stack deployment, a new stack is created and the resources are\n * migrated to the stack using an IMPORT changeset. The normal deployment will resume after this is complete\n * to add back in any outputs and the CDKMetadata.\n */\n public async tryMigrateResources(stacks: StackCollection, options: ImportDeploymentOptions): Promise<void> {\n const stack = stacks.stackArtifacts[0];\n const migrateDeployment = new ResourceImporter(stack, {\n deployments: this.props.deployments,\n ioHelper: this.ioHelper,\n });\n const resourcesToImport = await this.tryGetResources(await migrateDeployment.resolveEnvironment());\n\n if (resourcesToImport) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(`${chalk.bold(stack.displayName)}: creating stack for resource migration...`));\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(`${chalk.bold(stack.displayName)}: importing resources into stack...`));\n\n await this.performResourceMigration(migrateDeployment, resourcesToImport, options);\n\n fs.rmSync('migrate.json');\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_INFO.msg(`${chalk.bold(stack.displayName)}: applying CDKMetadata and Outputs to stack (if applicable)...`));\n }\n }\n\n /**\n * Creates a new stack with just the resources to be migrated\n */\n private async performResourceMigration(\n migrateDeployment: ResourceImporter,\n resourcesToImport: ResourcesToImport,\n options: ImportDeploymentOptions,\n ) {\n const startDeployTime = new Date().getTime();\n let elapsedDeployTime = 0;\n\n // Initial Deployment\n await migrateDeployment.importResourcesFromMigrate(resourcesToImport, {\n roleArn: options.roleArn,\n deploymentMethod: options.deploymentMethod,\n usePreviousParameters: true,\n rollback: options.rollback,\n });\n\n elapsedDeployTime = new Date().getTime() - startDeployTime;\n await this.ioHelper.notify(IO.CDK_TOOLKIT_I5002.msg(`'\\n\u2728 Resource migration time: ${formatTime(elapsedDeployTime)}s\\n'`, {\n duration: elapsedDeployTime,\n }));\n }\n\n public async tryGetResources(environment: cxapi.Environment): Promise<ResourcesToImport | undefined> {\n try {\n const migrateFile = fs.readJsonSync('migrate.json', {\n encoding: 'utf-8',\n });\n const sourceEnv = (migrateFile.Source as string).split(':');\n if (\n sourceEnv[0] === 'localfile' ||\n (sourceEnv[4] === environment.account && sourceEnv[3] === environment.region)\n ) {\n return migrateFile.Resources;\n }\n } catch (e) {\n // Nothing to do\n }\n\n return undefined;\n }\n}\n\n", "import { promises as fs } from 'fs';\nimport * as path from 'path';\nimport { ToolkitError } from './toolkit-error';\n\n/**\n * A single-writer/multi-reader lock on a directory\n *\n * It uses marker files with PIDs in them as a locking marker; the PIDs will be\n * checked for liveness, so that if the process exits without cleaning up the\n * files the lock is implicitly released.\n *\n * This class is not 100% race safe, but in practice it should be a lot\n * better than the 0 protection we have today.\n */\n/* c8 ignore start */ // code paths are unpredictable\nexport class RWLock {\n private readonly pidString: string;\n private readonly writerFile: string;\n private readCounter = 0;\n\n constructor(public readonly directory: string) {\n this.pidString = `${process.pid}`;\n\n this.writerFile = path.join(this.directory, 'synth.lock');\n }\n\n /**\n * Acquire a writer lock.\n *\n * No other readers or writers must exist for the given directory.\n */\n public async acquireWrite(): Promise<IWriteLock> {\n await this.assertNoOtherWriters();\n\n const readers = await this._currentReaders();\n if (readers.length > 0) {\n throw new ToolkitError(`Other CLIs (PID=${readers}) are currently reading from ${this.directory}. Invoke the CLI in sequence, or use '--output' to synth into different directories.`);\n }\n\n await writeFileAtomic(this.writerFile, this.pidString);\n\n let released = false;\n return {\n release: async () => {\n // Releasing needs a flag, otherwise we might delete a file that some other lock has created in the mean time.\n if (!released) {\n await deleteFile(this.writerFile);\n released = true;\n }\n },\n convertToReaderLock: async () => {\n // Acquire the read lock before releasing the write lock. Slightly less\n // chance of racing!\n const ret = await this.doAcquireRead();\n await deleteFile(this.writerFile);\n return ret;\n },\n };\n }\n\n /**\n * Acquire a read lock\n *\n * Will fail if there are any writers.\n */\n public async acquireRead(): Promise<IReadLock> {\n await this.assertNoOtherWriters();\n return this.doAcquireRead();\n }\n\n /**\n * Obtains the name fo a (new) `readerFile` to use. This includes a counter so\n * that if multiple threads of the same PID attempt to concurrently acquire\n * the same lock, they're guaranteed to use a different reader file name (only\n * one thread will ever execute JS code at once, guaranteeing the readCounter\n * is incremented \"atomically\" from the point of view of this PID.).\n */\n private readerFile(): string {\n return path.join(this.directory, `read.${this.pidString}.${++this.readCounter}.lock`);\n }\n\n /**\n * Do the actual acquiring of a read lock.\n */\n private async doAcquireRead(): Promise<IReadLock> {\n const readerFile = this.readerFile();\n await writeFileAtomic(readerFile, this.pidString);\n\n let released = false;\n return {\n release: async () => {\n // Releasing needs a flag, otherwise we might delete a file that some other lock has created in the mean time.\n if (!released) {\n await deleteFile(readerFile);\n released = true;\n }\n },\n };\n }\n\n private async assertNoOtherWriters() {\n const writer = await this._currentWriter();\n if (writer) {\n throw new ToolkitError(`Another CLI (PID=${writer}) is currently synthing to ${this.directory}. Invoke the CLI in sequence, or use '--output' to synth into different directories.`);\n }\n }\n\n /**\n * Check the current writer (if any)\n *\n * Publicly accessible for testing purposes. Do not use.\n *\n * @internal\n */\n public async _currentWriter(): Promise<number | undefined> {\n const contents = await readFileIfExists(this.writerFile);\n if (!contents) {\n return undefined;\n }\n\n const pid = parseInt(contents, 10);\n if (!processExists(pid)) {\n // Do cleanup of a stray file now\n await deleteFile(this.writerFile);\n return undefined;\n }\n\n return pid;\n }\n\n /**\n * Check the current readers (if any)\n *\n * Publicly accessible for testing purposes. Do not use.\n *\n * @internal\n */\n public async _currentReaders(): Promise<number[]> {\n const re = /^read\\.([^.]+)\\.[^.]+\\.lock$/;\n const ret = new Array<number>();\n\n let children;\n try {\n children = await fs.readdir(this.directory, { encoding: 'utf-8' });\n } catch (e: any) {\n // Can't be locked if the directory doesn't exist\n if (e.code === 'ENOENT') {\n return [];\n }\n throw e;\n }\n\n for (const fname of children) {\n const m = fname.match(re);\n if (m) {\n const pid = parseInt(m[1], 10);\n if (processExists(pid)) {\n ret.push(pid);\n } else {\n // Do cleanup of a stray file now\n await deleteFile(path.join(this.directory, fname));\n }\n }\n }\n return ret;\n }\n}\n/* c8 ignore stop */\n\n/**\n * An acquired lock\n */\nexport interface IReadLock {\n /**\n * Release the lock. Can be called more than once.\n */\n release(): Promise<void>;\n}\n\n/**\n * An acquired writer lock\n */\nexport interface IWriteLock extends IReadLock {\n /**\n * Convert the writer lock to a reader lock\n */\n convertToReaderLock(): Promise<IReadLock>;\n}\n\n/* c8 ignore start */ // code paths are unpredictable\nasync function readFileIfExists(filename: string): Promise<string | undefined> {\n try {\n return await fs.readFile(filename, { encoding: 'utf-8' });\n } catch (e: any) {\n if (e.code === 'ENOENT') {\n return undefined;\n }\n throw e;\n }\n}\n/* c8 ignore stop */\n\nlet tmpCounter = 0;\n/* c8 ignore start */ // code paths are unpredictable\nasync function writeFileAtomic(filename: string, contents: string): Promise<void> {\n await fs.mkdir(path.dirname(filename), { recursive: true });\n const tmpFile = `${filename}.${process.pid}_${++tmpCounter}`;\n await fs.writeFile(tmpFile, contents, { encoding: 'utf-8' });\n await fs.rename(tmpFile, filename);\n}\n/* c8 ignore stop */\n\n/* c8 ignore start */ // code paths are unpredictable\nasync function deleteFile(filename: string) {\n try {\n await fs.unlink(filename);\n } catch (e: any) {\n if (e.code === 'ENOENT') {\n return;\n }\n throw e;\n }\n}\n/* c8 ignore stop */\n\n/* c8 ignore start */ // code paths are unpredictable\nfunction processExists(pid: number) {\n try {\n process.kill(pid, 0);\n return true;\n } catch (e) {\n return false;\n }\n}\n/* c8 ignore stop */\n", "import type * as cxapi from '@aws-cdk/cx-api';\nimport type { AssetManifest, IManifestEntry } from 'cdk-assets';\n\nexport enum DeploymentState {\n PENDING = 'pending',\n QUEUED = 'queued',\n DEPLOYING = 'deploying',\n COMPLETED = 'completed',\n FAILED = 'failed',\n SKIPPED = 'skipped',\n}\n\nexport type WorkNode = StackNode | AssetBuildNode | AssetPublishNode;\n\nexport interface WorkNodeCommon {\n readonly id: string;\n readonly dependencies: Set<string>;\n deploymentState: DeploymentState;\n /** Some readable information to attach to the id, which may be unreadable */\n readonly note?: string;\n}\n\nexport interface StackNode extends WorkNodeCommon {\n readonly type: 'stack';\n readonly stack: cxapi.CloudFormationStackArtifact;\n /** Sort by priority when picking up work, higher is earlier */\n readonly priority?: number;\n}\n\nexport interface AssetBuildNode extends WorkNodeCommon {\n readonly type: 'asset-build';\n /** The asset manifest this asset resides in (artifact) */\n readonly assetManifestArtifact: cxapi.AssetManifestArtifact;\n /** The asset manifest this asset resides in */\n readonly assetManifest: AssetManifest;\n /** The stack this asset was defined in (used for environment settings) */\n readonly parentStack: cxapi.CloudFormationStackArtifact;\n /** The asset that needs to be built */\n readonly asset: IManifestEntry;\n /** Sort by priority when picking up work, higher is earlier */\n readonly priority?: number;\n}\n\nexport interface AssetPublishNode extends WorkNodeCommon {\n readonly type: 'asset-publish';\n /** The asset manifest this asset resides in (artifact) */\n readonly assetManifestArtifact: cxapi.AssetManifestArtifact;\n /** The asset manifest this asset resides in */\n readonly assetManifest: AssetManifest;\n /** The stack this asset was defined in (used for environment settings) */\n readonly parentStack: cxapi.CloudFormationStackArtifact;\n /** The asset that needs to be published */\n readonly asset: IManifestEntry;\n /** Sort by priority when picking up work, higher is earlier */\n readonly priority?: number;\n}\n", "import type { WorkNode, StackNode, AssetBuildNode, AssetPublishNode } from './work-graph-types';\nimport { DeploymentState } from './work-graph-types';\nimport { parallelPromises } from '../../util';\nimport { IO, type IoHelper } from '../io/private';\nimport { ToolkitError } from '../toolkit-error';\nexport type Concurrency = number | Record<WorkNode['type'], number>;\n\nexport class WorkGraph {\n public readonly nodes: Record<string, WorkNode>;\n private readonly readyPool: Array<WorkNode> = [];\n private readonly lazyDependencies = new Map<string, string[]>();\n private readonly ioHelper: IoHelper;\n\n public error?: Error;\n\n public constructor(nodes: Record<string, WorkNode>, ioHelper: IoHelper) {\n this.nodes = { ...nodes };\n this.ioHelper = ioHelper;\n }\n\n public addNodes(...nodes: WorkNode[]) {\n for (const node of nodes) {\n if (this.nodes[node.id]) {\n throw new ToolkitError(`Duplicate use of node id: ${node.id}`);\n }\n\n const ld = this.lazyDependencies.get(node.id);\n if (ld) {\n for (const x of ld) {\n node.dependencies.add(x);\n }\n this.lazyDependencies.delete(node.id);\n }\n\n this.nodes[node.id] = node;\n }\n }\n\n public removeNode(nodeId: string | WorkNode) {\n const id = typeof nodeId === 'string' ? nodeId : nodeId.id;\n const removedNode = this.nodes[id];\n\n this.lazyDependencies.delete(id);\n delete this.nodes[id];\n\n if (removedNode) {\n for (const node of Object.values(this.nodes)) {\n node.dependencies.delete(removedNode.id);\n }\n }\n }\n\n /**\n * Return all nodes of a given type\n */\n public nodesOfType<T extends WorkNode['type']>(type: T): Extract<WorkNode, { type: T }>[] {\n return Object.values(this.nodes).filter(n => n.type === type) as any;\n }\n\n /**\n * Return all nodes that depend on a given node\n */\n public dependees(nodeId: string | WorkNode) {\n const id = typeof nodeId === 'string' ? nodeId : nodeId.id;\n return Object.values(this.nodes).filter(n => n.dependencies.has(id));\n }\n\n /**\n * Add a dependency, that may come before or after the nodes involved\n */\n public addDependency(fromId: string, toId: string) {\n const node = this.nodes[fromId];\n if (node) {\n node.dependencies.add(toId);\n return;\n }\n let lazyDeps = this.lazyDependencies.get(fromId);\n if (!lazyDeps) {\n lazyDeps = [];\n this.lazyDependencies.set(fromId, lazyDeps);\n }\n lazyDeps.push(toId);\n }\n\n public tryGetNode(id: string): WorkNode | undefined {\n return this.nodes[id];\n }\n\n public node(id: string) {\n const ret = this.nodes[id];\n if (!ret) {\n throw new ToolkitError(`No node with id ${id} among ${Object.keys(this.nodes)}`);\n }\n return ret;\n }\n\n public absorb(graph: WorkGraph) {\n this.addNodes(...Object.values(graph.nodes));\n }\n\n private hasFailed(): boolean {\n return Object.values(this.nodes).some((n) => n.deploymentState === DeploymentState.FAILED);\n }\n\n public doParallel(concurrency: Concurrency, actions: WorkGraphActions) {\n return this.forAllArtifacts(concurrency, async (x: WorkNode) => {\n switch (x.type) {\n case 'stack':\n await actions.deployStack(x);\n break;\n case 'asset-build':\n await actions.buildAsset(x);\n break;\n case 'asset-publish':\n await actions.publishAsset(x);\n break;\n }\n });\n }\n\n /**\n * Return the set of unblocked nodes\n */\n public async ready(): Promise<ReadonlyArray<WorkNode>> {\n await this.updateReadyPool();\n return this.readyPool;\n }\n\n private forAllArtifacts(n: Concurrency, fn: (x: WorkNode) => Promise<void>): Promise<void> {\n const graph = this;\n\n // If 'n' is a number, we limit all concurrency equally (effectively we will be using totalMax)\n // If 'n' is a record, we limit each job independently (effectively we will be using max)\n const max: Record<WorkNode['type'], number> = typeof n === 'number' ?\n {\n 'asset-build': n,\n 'asset-publish': n,\n 'stack': n,\n } : n;\n const totalMax = typeof n === 'number' ? n : sum(Object.values(n));\n\n return new Promise((ok, fail) => {\n let active: Record<WorkNode['type'], number> = {\n 'asset-build': 0,\n 'asset-publish': 0,\n 'stack': 0,\n };\n function totalActive() {\n return sum(Object.values(active));\n }\n\n start();\n\n function start() {\n graph.updateReadyPool().then(() => {\n for (let i = 0; i < graph.readyPool.length; ) {\n const node = graph.readyPool[i];\n\n if (active[node.type] < max[node.type] && totalActive() < totalMax) {\n graph.readyPool.splice(i, 1);\n startOne(node);\n } else {\n i += 1;\n }\n }\n\n if (totalActive() === 0) {\n if (graph.done()) {\n ok();\n }\n // wait for other active deploys to finish before failing\n if (graph.hasFailed()) {\n fail(graph.error);\n }\n }\n }).catch((e) => {\n fail(e);\n });\n }\n\n function startOne(x: WorkNode) {\n x.deploymentState = DeploymentState.DEPLOYING;\n active[x.type]++;\n void fn(x)\n .finally(() => {\n active[x.type]--;\n })\n .then(() => {\n graph.deployed(x);\n start();\n }).catch((err) => {\n // By recording the failure immediately as the queued task exits, we prevent the next\n // queued task from starting.\n graph.failed(x, err);\n start();\n });\n }\n });\n }\n\n private done(): boolean {\n return Object.values(this.nodes).every((n) => DeploymentState.COMPLETED === n.deploymentState);\n }\n\n private deployed(node: WorkNode) {\n node.deploymentState = DeploymentState.COMPLETED;\n }\n\n private failed(node: WorkNode, error?: Error) {\n this.error = error;\n node.deploymentState = DeploymentState.FAILED;\n this.skipRest();\n this.readyPool.splice(0);\n }\n\n public toString() {\n return [\n 'digraph D {',\n ...Object.entries(this.nodes).flatMap(([id, node]) => renderNode(id, node)),\n '}',\n ].join('\\n');\n\n function renderNode(id: string, node: WorkNode): string[] {\n const ret = [];\n if (node.deploymentState === DeploymentState.COMPLETED) {\n ret.push(` ${gv(id, { style: 'filled', fillcolor: 'yellow', comment: node.note })};`);\n } else {\n ret.push(` ${gv(id, { comment: node.note })};`);\n }\n for (const dep of node.dependencies) {\n ret.push(` ${gv(id)} -> ${gv(dep)};`);\n }\n return ret;\n }\n }\n\n /**\n * Ensure all dependencies actually exist. This protects against scenarios such as the following:\n * StackA depends on StackB, but StackB is not selected to deploy. The dependency is redundant\n * and will be dropped.\n * This assumes the manifest comes uncorrupted so we will not fail if a dependency is not found.\n */\n public removeUnavailableDependencies() {\n for (const node of Object.values(this.nodes)) {\n const removeDeps = Array.from(node.dependencies).filter((dep) => this.nodes[dep] === undefined);\n\n removeDeps.forEach((d) => {\n node.dependencies.delete(d);\n });\n }\n }\n\n /**\n * Remove all asset publishing steps for assets that are already published, and then build\n * that aren't used anymore.\n *\n * Do this in parallel, because there may be a lot of assets in an application (seen in practice: >100 assets)\n */\n public async removeUnnecessaryAssets(isUnnecessary: (x: AssetPublishNode) => Promise<boolean>) {\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg('Checking for previously published assets'));\n\n const publishes = this.nodesOfType('asset-publish');\n\n const classifiedNodes = await parallelPromises(\n 8,\n publishes.map((assetNode) => async() => [assetNode, await isUnnecessary(assetNode)] as const));\n\n const alreadyPublished = classifiedNodes.filter(([_, unnecessary]) => unnecessary).map(([assetNode, _]) => assetNode);\n for (const assetNode of alreadyPublished) {\n this.removeNode(assetNode);\n }\n\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_DEBUG.msg(`${publishes.length} total assets, ${publishes.length - alreadyPublished.length} still need to be published`));\n\n // Now also remove any asset build steps that don't have any dependencies on them anymore\n const unusedBuilds = this.nodesOfType('asset-build').filter(build => this.dependees(build).length === 0);\n for (const unusedBuild of unusedBuilds) {\n this.removeNode(unusedBuild);\n }\n }\n\n private async updateReadyPool() {\n const activeCount = Object.values(this.nodes).filter((x) => x.deploymentState === DeploymentState.DEPLOYING).length;\n const pendingCount = Object.values(this.nodes).filter((x) => x.deploymentState === DeploymentState.PENDING).length;\n\n const newlyReady = Object.values(this.nodes).filter((x) =>\n x.deploymentState === DeploymentState.PENDING &&\n Array.from(x.dependencies).every((id) => this.node(id).deploymentState === DeploymentState.COMPLETED));\n\n // Add newly available nodes to the ready pool\n for (const node of newlyReady) {\n node.deploymentState = DeploymentState.QUEUED;\n this.readyPool.push(node);\n }\n\n // Remove nodes from the ready pool that have already started deploying\n retainOnly(this.readyPool, (node) => node.deploymentState === DeploymentState.QUEUED);\n\n // Sort by reverse priority\n this.readyPool.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));\n\n if (this.readyPool.length === 0 && activeCount === 0 && pendingCount > 0) {\n const cycle = this.findCycle() ?? ['No cycle found!'];\n await this.ioHelper.notify(IO.DEFAULT_TOOLKIT_TRACE.msg(`Cycle ${cycle.join(' -> ')} in graph ${this}`));\n throw new ToolkitError(`Unable to make progress anymore, dependency cycle between remaining artifacts: ${cycle.join(' -> ')} (run with -vv for full graph)`);\n }\n }\n\n private skipRest() {\n for (const node of Object.values(this.nodes)) {\n if ([DeploymentState.QUEUED, DeploymentState.PENDING].includes(node.deploymentState)) {\n node.deploymentState = DeploymentState.SKIPPED;\n }\n }\n }\n\n /**\n * Find cycles in a graph\n *\n * Not the fastest, but effective and should be rare\n */\n public findCycle(): string[] | undefined {\n const seen = new Set<string>();\n const self = this;\n for (const nodeId of Object.keys(this.nodes)) {\n const cycle = recurse(nodeId, [nodeId]);\n if (cycle) {\n return cycle;\n }\n }\n return undefined;\n\n function recurse(nodeId: string, path: string[]): string[] | undefined {\n if (seen.has(nodeId)) {\n return undefined;\n }\n try {\n for (const dep of self.nodes[nodeId].dependencies ?? []) {\n const index = path.indexOf(dep);\n if (index > -1) {\n return [...path.slice(index), dep];\n }\n\n const cycle = recurse(dep, [...path, dep]);\n if (cycle) {\n return cycle;\n }\n }\n\n return undefined;\n } finally {\n seen.add(nodeId);\n }\n }\n }\n\n /**\n * Whether the `end` node is reachable from the `start` node, following the dependency arrows\n */\n public reachable(start: string, end: string): boolean {\n const seen = new Set<string>();\n const self = this;\n return recurse(start);\n\n function recurse(current: string) {\n if (seen.has(current)) {\n return false;\n }\n seen.add(current);\n\n if (current === end) {\n return true;\n }\n for (const dep of self.nodes[current].dependencies) {\n if (recurse(dep)) {\n return true;\n }\n }\n return false;\n }\n }\n}\n\nexport interface WorkGraphActions {\n deployStack: (stackNode: StackNode) => Promise<void>;\n buildAsset: (assetNode: AssetBuildNode) => Promise<void>;\n publishAsset: (assetNode: AssetPublishNode) => Promise<void>;\n}\n\nfunction sum(xs: number[]) {\n let ret = 0;\n for (const x of xs) {\n ret += x;\n }\n return ret;\n}\n\nfunction retainOnly<A>(xs: A[], pred: (x: A) => boolean) {\n xs.splice(0, xs.length, ...xs.filter(pred));\n}\n\nfunction gv(id: string, attrs?: Record<string, string | undefined>) {\n const attrString = Object.entries(attrs ?? {}).flatMap(([k, v]) => v !== undefined ? [`${k}=\"${v}\"`] : []).join(',');\n\n return attrString ? `\"${simplifyId(id)}\" [${attrString}]` : `\"${simplifyId(id)}\"`;\n}\n\nfunction simplifyId(id: string) {\n return id.replace(/([0-9a-f]{6})[0-9a-f]{6,}/g, '$1');\n}\n", "import * as cxapi from '@aws-cdk/cx-api';\nimport { AssetManifest, type IManifestEntry } from 'cdk-assets';\nimport { WorkGraph } from './work-graph';\nimport type { AssetBuildNode, WorkNode } from './work-graph-types';\nimport { DeploymentState } from './work-graph-types';\nimport { contentHashAny } from '../../util';\nimport type { IoHelper } from '../io/private';\nimport { ToolkitError } from '../toolkit-error';\n\nexport class WorkGraphBuilder {\n /**\n * Default priorities for nodes\n *\n * Assets builds have higher priority than the other two operations, to make good on our promise that\n * '--prebuild-assets' will actually do assets before stacks (if it can). Unfortunately it is the\n * default :(\n *\n * But between stack dependencies and publish dependencies, stack dependencies go first\n */\n public static PRIORITIES: Record<WorkNode['type'], number> = {\n 'asset-build': 10,\n 'asset-publish': 0,\n 'stack': 5,\n };\n private readonly graph: WorkGraph;\n private readonly ioHelper: IoHelper;\n\n constructor(\n ioHelper: IoHelper,\n private readonly prebuildAssets: boolean,\n private readonly idPrefix = '',\n ) {\n this.graph = new WorkGraph({}, ioHelper);\n this.ioHelper = ioHelper;\n }\n\n private addStack(artifact: cxapi.CloudFormationStackArtifact) {\n this.graph.addNodes({\n type: 'stack',\n id: `${this.idPrefix}${artifact.id}`,\n dependencies: new Set(this.stackArtifactIds(onlyStacks(artifact.dependencies))),\n stack: artifact,\n deploymentState: DeploymentState.PENDING,\n priority: WorkGraphBuilder.PRIORITIES.stack,\n });\n }\n\n /**\n * Oof, see this parameter list\n */\n // eslint-disable-next-line max-len\n private addAsset(parentStack: cxapi.CloudFormationStackArtifact, assetManifestArtifact: cxapi.AssetManifestArtifact, assetManifest: AssetManifest, asset: IManifestEntry) {\n // Just the artifact identifier\n const assetId = asset.id.assetId;\n\n const buildId = `build-${assetId}-${contentHashAny([assetId, asset.genericSource]).substring(0, 10)}`;\n const publishId = `publish-${assetId}-${contentHashAny([assetId, asset.genericDestination]).substring(0, 10)}`;\n\n // Build node only gets added once because they are all the same\n if (!this.graph.tryGetNode(buildId)) {\n const node: AssetBuildNode = {\n type: 'asset-build',\n id: buildId,\n note: asset.displayName(false),\n dependencies: new Set([\n ...this.stackArtifactIds(assetManifestArtifact.dependencies),\n // If we disable prebuild, then assets inherit (stack) dependencies from their parent stack\n ...!this.prebuildAssets ? this.stackArtifactIds(onlyStacks(parentStack.dependencies)) : [],\n ]),\n parentStack: parentStack,\n assetManifestArtifact,\n assetManifest,\n asset,\n deploymentState: DeploymentState.PENDING,\n priority: WorkGraphBuilder.PRIORITIES['asset-build'],\n };\n this.graph.addNodes(node);\n }\n\n const publishNode = this.graph.tryGetNode(publishId);\n if (!publishNode) {\n this.graph.addNodes({\n type: 'asset-publish',\n id: publishId,\n note: asset.displayName(true),\n dependencies: new Set([\n buildId,\n ]),\n parentStack,\n assetManifestArtifact,\n assetManifest,\n asset,\n deploymentState: DeploymentState.PENDING,\n priority: WorkGraphBuilder.PRIORITIES['asset-publish'],\n });\n }\n\n for (const inheritedDep of this.stackArtifactIds(onlyStacks(parentStack.dependencies))) {\n // The asset publish step also depends on the stacks that the parent depends on.\n // This is purely cosmetic: if we don't do this, the progress printing of asset publishing\n // is going to interfere with the progress bar of the stack deployment. We could remove this\n // for overall faster deployments if we ever have a better method of progress displaying.\n // Note: this may introduce a cycle if one of the parent's dependencies is another stack that\n // depends on this asset. To workaround this we remove these cycles once all nodes have\n // been added to the graph.\n this.graph.addDependency(publishId, inheritedDep);\n }\n\n // This will work whether the stack node has been added yet or not\n this.graph.addDependency(`${this.idPrefix}${parentStack.id}`, publishId);\n }\n\n public build(artifacts: cxapi.CloudArtifact[]): WorkGraph {\n const parentStacks = stacksFromAssets(artifacts);\n\n for (const artifact of artifacts) {\n if (cxapi.CloudFormationStackArtifact.isCloudFormationStackArtifact(artifact)) {\n this.addStack(artifact);\n } else if (cxapi.AssetManifestArtifact.isAssetManifestArtifact(artifact)) {\n const manifest = AssetManifest.fromFile(artifact.file);\n\n for (const entry of manifest.entries) {\n const parentStack = parentStacks.get(artifact);\n if (parentStack === undefined) {\n throw new ToolkitError('Found an asset manifest that is not associated with a stack');\n }\n this.addAsset(parentStack, artifact, manifest, entry);\n }\n } else if (cxapi.NestedCloudAssemblyArtifact.isNestedCloudAssemblyArtifact(artifact)) {\n const assembly = new cxapi.CloudAssembly(artifact.fullPath, { topoSort: false });\n const nestedGraph = new WorkGraphBuilder(\n this.ioHelper,\n this.prebuildAssets,\n `${this.idPrefix}${artifact.id}.`,\n ).build(assembly.artifacts);\n this.graph.absorb(nestedGraph);\n } else {\n // Ignore whatever else\n }\n }\n\n this.graph.removeUnavailableDependencies();\n\n // Remove any potentially introduced cycles between asset publishing and the stacks that depend on them.\n this.removeStackPublishCycles();\n\n return this.graph;\n }\n\n private stackArtifactIds(deps: cxapi.CloudArtifact[]): string[] {\n return deps.flatMap((d) => cxapi.CloudFormationStackArtifact.isCloudFormationStackArtifact(d) ? [this.stackArtifactId(d)] : []);\n }\n\n private stackArtifactId(artifact: cxapi.CloudArtifact): string {\n if (!cxapi.CloudFormationStackArtifact.isCloudFormationStackArtifact(artifact)) {\n throw new ToolkitError(`Can only call this on CloudFormationStackArtifact, got: ${artifact.constructor.name}`);\n }\n return `${this.idPrefix}${artifact.id}`;\n }\n\n /**\n * We may have accidentally introduced cycles in an attempt to make the messages printed to the\n * console not interfere with each other too much. Remove them again.\n */\n private removeStackPublishCycles() {\n const publishSteps = this.graph.nodesOfType('asset-publish');\n for (const publishStep of publishSteps) {\n for (const dep of publishStep.dependencies) {\n if (this.graph.reachable(dep, publishStep.id)) {\n publishStep.dependencies.delete(dep);\n }\n }\n }\n }\n}\n\nfunction stacksFromAssets(artifacts: cxapi.CloudArtifact[]) {\n const ret = new Map<cxapi.AssetManifestArtifact, cxapi.CloudFormationStackArtifact>();\n for (const stack of artifacts.filter(x => cxapi.CloudFormationStackArtifact.isCloudFormationStackArtifact(x))) {\n const assetArtifacts = stack.dependencies.filter((x) => cxapi.AssetManifestArtifact.isAssetManifestArtifact(x));\n for (const art of assetArtifacts) {\n ret.set(art, stack);\n }\n }\n\n return ret;\n}\n\nfunction onlyStacks(artifacts: cxapi.CloudArtifact[]) {\n return artifacts.filter(x => cxapi.CloudFormationStackArtifact.isCloudFormationStackArtifact(x));\n}\n", "import type * as cxapi from '@aws-cdk/cx-api';\n\n/**\n * @returns an array with the tags available in the stack metadata.\n */\nexport function tagsForStack(stack: cxapi.CloudFormationStackArtifact): Tag[] {\n return Object.entries(stack.tags).map(([Key, Value]) => ({ Key, Value }));\n}\n\nexport interface Tag {\n readonly Key: string;\n readonly Value: string;\n}\n", "import * as cxschema from '@aws-cdk/cloud-assembly-schema';\nimport * as cxapi from '@aws-cdk/cx-api';\nimport { AmiContextProviderPlugin } from './ami';\nimport { AZContextProviderPlugin } from './availability-zones';\nimport { CcApiContextProviderPlugin } from './cc-api-provider';\nimport { EndpointServiceAZContextProviderPlugin } from './endpoint-service-availability-zones';\nimport { HostedZoneContextProviderPlugin } from './hosted-zones';\nimport { KeyContextProviderPlugin } from './keys';\nimport { LoadBalancerContextProviderPlugin, LoadBalancerListenerContextProviderPlugin } from './load-balancers';\nimport { SecurityGroupContextProviderPlugin } from './security-groups';\nimport { SSMContextProviderPlugin } from './ssm-parameters';\nimport { VpcNetworkContextProviderPlugin } from './vpcs';\nimport type { SdkProvider } from '../api/aws-auth';\nimport type { Context } from '../api/context';\nimport { TRANSIENT_CONTEXT_KEY } from '../api/context';\nimport { replaceEnvPlaceholders } from '../api/environment';\nimport { IO } from '../api/io/private';\nimport type { IoHelper } from '../api/io/private';\nimport { PluginHost } from '../api/plugin';\nimport type { ContextProviderPlugin } from '../api/plugin';\nimport { ContextProviderError } from '../api/toolkit-error';\nimport { formatErrorMessage } from '../util';\n\ntype ContextProviderFactory = ((sdk: SdkProvider, io: IContextProviderMessages) => ContextProviderPlugin);\ntype ProviderMap = {[name: string]: ContextProviderFactory};\n\nconst PLUGIN_PROVIDER_PREFIX = 'plugin';\n\nexport interface IContextProviderMessages {\n /**\n * A message that is presented to users in normal mode of operation.\n *\n * Should be used sparingly. The Context Provider framework already provides useful output by default.\n * This can be uses in exceptionally situations, e.g. if a lookup call is expected to take a long time.\n */\n info(message: string): Promise<void>;\n\n /**\n * A message that helps users debugging the context provider.\n *\n * Should be used in most cases to note on current action.\n */\n debug(message: string): Promise<void>;\n}\n\nclass ContextProviderMessages implements IContextProviderMessages {\n private readonly ioHelper: IoHelper;\n private readonly providerName: string;\n\n public constructor(ioHelper: IoHelper, providerName: string) {\n this.ioHelper = ioHelper;\n this.providerName = providerName;\n }\n\n public async info(message: string): Promise<void> {\n return this.ioHelper.notify(IO.CDK_ASSEMBLY_I0300.msg(message, {\n provider: this.providerName,\n }));\n }\n\n public async debug(message: string): Promise<void> {\n return this.ioHelper.notify(IO.CDK_ASSEMBLY_I0301.msg(message, {\n provider: this.providerName,\n }));\n }\n}\n\n/**\n * Iterate over the list of missing context values and invoke the appropriate providers from the map to retrieve them\n */\nexport async function provideContextValues(\n missingValues: cxschema.MissingContext[],\n context: Context,\n sdk: SdkProvider,\n ioHelper: IoHelper,\n) {\n for (const missingContext of missingValues) {\n const key = missingContext.key;\n\n const providerName = missingContext.provider === cxschema.ContextProvider.PLUGIN\n ? `${PLUGIN_PROVIDER_PREFIX}:${(missingContext.props as cxschema.PluginContextQuery).pluginName}`\n : missingContext.provider;\n\n let factory;\n if (providerName.startsWith(`${PLUGIN_PROVIDER_PREFIX}:`)) {\n const plugin = PluginHost.instance.contextProviderPlugins[providerName.substring(PLUGIN_PROVIDER_PREFIX.length + 1)];\n if (!plugin) {\n // eslint-disable-next-line max-len\n throw new ContextProviderError(`Unrecognized plugin context provider name: ${missingContext.provider}.`);\n }\n factory = () => plugin;\n } else {\n factory = availableContextProviders[providerName];\n if (!factory) {\n // eslint-disable-next-line max-len\n throw new ContextProviderError(`Unrecognized context provider name: ${missingContext.provider}. You might need to update the toolkit to match the version of the construct library.`);\n }\n }\n\n const provider = factory(sdk, new ContextProviderMessages(ioHelper, providerName));\n\n let value;\n try {\n const environment = missingContext.props.account && missingContext.props.region\n ? cxapi.EnvironmentUtils.make(missingContext.props.account, missingContext.props.region)\n : undefined;\n\n const resolvedEnvironment: cxapi.Environment = environment\n ? await sdk.resolveEnvironment(environment)\n : { account: '?', region: '?', name: '?' };\n\n const arns = await replaceEnvPlaceholders({\n lookupRoleArn: missingContext.props.lookupRoleArn,\n }, resolvedEnvironment, sdk);\n\n value = await provider.getValue({ ...missingContext.props, lookupRoleArn: arns.lookupRoleArn });\n } catch (e: any) {\n // Set a specially formatted provider value which will be interpreted\n // as a lookup failure in the toolkit.\n value = { [cxapi.PROVIDER_ERROR_KEY]: formatErrorMessage(e), [TRANSIENT_CONTEXT_KEY]: true };\n }\n context.set(key, value);\n await ioHelper.notify(IO.DEFAULT_ASSEMBLY_DEBUG.msg(`Setting \"${key}\" context to ${JSON.stringify(value)}`));\n }\n}\n\n/**\n * Register a context provider\n *\n * A context provider cannot reuse the SDKs authentication mechanisms.\n */\nexport function registerContextProvider(name: string, provider: ContextProviderPlugin) {\n availableContextProviders[name] = () => provider;\n}\n\n/**\n * Register a plugin context provider\n *\n * A plugin provider cannot reuse the SDKs authentication mechanisms.\n */\nexport function registerPluginContextProvider(name: string, provider: ContextProviderPlugin) {\n registerContextProvider(`${PLUGIN_PROVIDER_PREFIX}:${name}`, provider);\n}\n\n/**\n * Register a context provider factory\n *\n * A context provider factory takes an SdkProvider and returns the context provider plugin.\n */\nexport function registerContextProviderFactory(name: string, provider: ContextProviderFactory) {\n availableContextProviders[name] = provider;\n}\n\nconst availableContextProviders: ProviderMap = {\n [cxschema.ContextProvider.AVAILABILITY_ZONE_PROVIDER]: (s, io) => new AZContextProviderPlugin(s, io),\n [cxschema.ContextProvider.SSM_PARAMETER_PROVIDER]: (s, io) => new SSMContextProviderPlugin(s, io),\n [cxschema.ContextProvider.HOSTED_ZONE_PROVIDER]: (s, io) => new HostedZoneContextProviderPlugin(s, io),\n [cxschema.ContextProvider.VPC_PROVIDER]: (s, io) => new VpcNetworkContextProviderPlugin(s, io),\n [cxschema.ContextProvider.AMI_PROVIDER]: (s, io) => new AmiContextProviderPlugin(s, io),\n [cxschema.ContextProvider.ENDPOINT_SERVICE_AVAILABILITY_ZONE_PROVIDER]: (s, io) => new EndpointServiceAZContextProviderPlugin(s, io),\n [cxschema.ContextProvider.SECURITY_GROUP_PROVIDER]: (s) => new SecurityGroupContextProviderPlugin(s),\n [cxschema.ContextProvider.LOAD_BALANCER_PROVIDER]: (s) => new LoadBalancerContextProviderPlugin(s),\n [cxschema.ContextProvider.LOAD_BALANCER_LISTENER_PROVIDER]: (s) => new LoadBalancerListenerContextProviderPlugin(s),\n [cxschema.ContextProvider.KEY_PROVIDER]: (s, io) => new KeyContextProviderPlugin(s, io),\n [cxschema.ContextProvider.CC_API_PROVIDER]: (s) => new CcApiContextProviderPlugin(s),\n};\n", "import type { AmiContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport type { IContextProviderMessages } from '.';\nimport { type SdkProvider, initContextProviderSdk } from '../api/aws-auth';\nimport type { ContextProviderPlugin } from '../api/plugin';\nimport { ContextProviderError } from '../api/toolkit-error';\n\n/**\n * Plugin to search AMIs for the current account\n */\nexport class AmiContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider, private readonly io: IContextProviderMessages) {\n }\n\n public async getValue(args: AmiContextQuery) {\n const region = args.region;\n const account = args.account;\n\n // Normally we'd do this only as 'debug', but searching AMIs typically takes dozens\n // of seconds, so be little more verbose about it so users know what is going on.\n await this.io.info(`Searching for AMI in ${account}:${region}`);\n await this.io.debug(`AMI search parameters: ${JSON.stringify(args)}`);\n\n const ec2 = (await initContextProviderSdk(this.aws, args)).ec2();\n const response = await ec2.describeImages({\n Owners: args.owners,\n Filters: Object.entries(args.filters).map(([key, values]) => ({\n Name: key,\n Values: values,\n })),\n });\n\n const images = [...(response.Images || [])].filter((i) => i.ImageId !== undefined);\n\n if (images.length === 0) {\n throw new ContextProviderError('No AMI found that matched the search criteria');\n }\n\n // Return the most recent one\n // Note: Date.parse() is not going to respect the timezone of the string,\n // but since we only care about the relative values that is okay.\n images.sort(descending((i) => Date.parse(i.CreationDate || '1970')));\n\n await this.io.debug(`Selected image '${images[0].ImageId}' created at '${images[0].CreationDate}'`);\n return images[0].ImageId!;\n }\n}\n\n/**\n * Make a comparator that sorts in descending order given a sort key extractor\n */\nfunction descending<A>(valueOf: (x: A) => number) {\n return (a: A, b: A) => {\n return valueOf(b) - valueOf(a);\n };\n}\n", "import type { AvailabilityZonesContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport type { AvailabilityZone } from '@aws-sdk/client-ec2';\nimport type { IContextProviderMessages } from '.';\nimport { type SdkProvider, initContextProviderSdk } from '../api/aws-auth';\nimport type { ContextProviderPlugin } from '../api/plugin';\n\n/**\n * Plugin to retrieve the Availability Zones for the current account\n */\nexport class AZContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider, private readonly io: IContextProviderMessages) {\n }\n\n public async getValue(args: AvailabilityZonesContextQuery) {\n const region = args.region;\n const account = args.account;\n await this.io.debug(`Reading AZs for ${account}:${region}`);\n const ec2 = (await initContextProviderSdk(this.aws, args)).ec2();\n const response = await ec2.describeAvailabilityZones({});\n if (!response.AvailabilityZones) {\n return [];\n }\n const azs = response.AvailabilityZones.filter((zone: AvailabilityZone) => zone.State === 'available').map(\n (zone: AvailabilityZone) => zone.ZoneName,\n );\n return azs;\n }\n}\n", "import type { CcApiContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport type { ResourceDescription } from '@aws-sdk/client-cloudcontrol';\nimport { ResourceNotFoundException } from '@aws-sdk/client-cloudcontrol';\nimport type { ICloudControlClient, SdkProvider } from '../api/aws-auth';\nimport { initContextProviderSdk } from '../api/aws-auth';\nimport type { ContextProviderPlugin } from '../api/plugin';\nimport { ContextProviderError } from '../api/toolkit-error';\nimport { findJsonValue, getResultObj } from '../util';\n\nexport class CcApiContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider) {\n }\n\n /**\n * This returns a data object with the value from CloudControl API result.\n *\n * See the documentation in the Cloud Assembly Schema for the semantics of\n * each query parameter.\n */\n public async getValue(args: CcApiContextQuery) {\n // Validate input\n if (args.exactIdentifier && args.propertyMatch) {\n throw new ContextProviderError(`Provider protocol error: specify either exactIdentifier or propertyMatch, but not both (got ${JSON.stringify(args)})`);\n }\n if (args.ignoreErrorOnMissingContext && args.dummyValue === undefined) {\n throw new ContextProviderError(`Provider protocol error: if ignoreErrorOnMissingContext is set, a dummyValue must be supplied (got ${JSON.stringify(args)})`);\n }\n if (args.dummyValue !== undefined && (!Array.isArray(args.dummyValue) || !args.dummyValue.every(isObject))) {\n throw new ContextProviderError(`Provider protocol error: dummyValue must be an array of objects (got ${JSON.stringify(args.dummyValue)})`);\n }\n\n // Do the lookup\n const cloudControl = (await initContextProviderSdk(this.aws, args)).cloudControl();\n\n try {\n let resources: FoundResource[];\n if (args.exactIdentifier) {\n // use getResource to get the exact indentifier\n resources = await this.getResource(cloudControl, args.typeName, args.exactIdentifier);\n } else if (args.propertyMatch) {\n // use listResource\n resources = await this.listResources(cloudControl, args.typeName, args.propertyMatch, args.expectedMatchCount);\n } else {\n throw new ContextProviderError(`Provider protocol error: neither exactIdentifier nor propertyMatch is specified in ${JSON.stringify(args)}.`);\n }\n\n return resources.map((r) => getResultObj(r.properties, r.identifier, args.propertiesToReturn));\n } catch (err) {\n if (err instanceof ZeroResourcesFoundError && args.ignoreErrorOnMissingContext) {\n // We've already type-checked dummyValue.\n return args.dummyValue;\n }\n throw err;\n }\n }\n\n /**\n * Calls getResource from CC API to get the resource.\n * See https://docs.aws.amazon.com/cli/latest/reference/cloudcontrol/get-resource.html\n *\n * Will always return exactly one resource, or fail.\n */\n private async getResource(\n cc: ICloudControlClient,\n typeName: string,\n exactIdentifier: string,\n ): Promise<FoundResource[]> {\n try {\n const result = await cc.getResource({\n TypeName: typeName,\n Identifier: exactIdentifier,\n });\n if (!result.ResourceDescription) {\n throw new ContextProviderError('Unexpected CloudControl API behavior: returned empty response');\n }\n\n return [foundResourceFromCcApi(result.ResourceDescription)];\n } catch (err: any) {\n if (err instanceof ResourceNotFoundException || (err as any).name === 'ResourceNotFoundException') {\n throw new ZeroResourcesFoundError(`No resource of type ${typeName} with identifier: ${exactIdentifier}`);\n }\n if (!(err instanceof ContextProviderError)) {\n throw new ContextProviderError(`Encountered CC API error while getting ${typeName} resource ${exactIdentifier}: ${err.message}`);\n }\n throw err;\n }\n }\n\n /**\n * Calls listResources from CC API to get the resources and apply args.propertyMatch to find the resources.\n * See https://docs.aws.amazon.com/cli/latest/reference/cloudcontrol/list-resources.html\n *\n * Will return 0 or more resources.\n *\n * Does not currently paginate through more than one result page.\n */\n private async listResources(\n cc: ICloudControlClient,\n typeName: string,\n propertyMatch: Record<string, unknown>,\n expectedMatchCount?: CcApiContextQuery['expectedMatchCount'],\n ): Promise<FoundResource[]> {\n try {\n const result = await cc.listResources({\n TypeName: typeName,\n\n });\n const found = (result.ResourceDescriptions ?? [])\n .map(foundResourceFromCcApi)\n .filter((r) => {\n return Object.entries(propertyMatch).every(([propPath, expected]) => {\n const actual = findJsonValue(r.properties, propPath);\n return propertyMatchesFilter(actual, expected);\n });\n });\n\n if ((expectedMatchCount === 'at-least-one' || expectedMatchCount === 'exactly-one') && found.length === 0) {\n throw new ZeroResourcesFoundError(`Could not find any resources matching ${JSON.stringify(propertyMatch)}`);\n }\n if ((expectedMatchCount === 'at-most-one' || expectedMatchCount === 'exactly-one') && found.length > 1) {\n throw new ContextProviderError(`Found ${found.length} resources matching ${JSON.stringify(propertyMatch)}; please narrow the search criteria`);\n }\n\n return found;\n } catch (err: any) {\n if (!(err instanceof ContextProviderError) && !(err instanceof ZeroResourcesFoundError)) {\n throw new ContextProviderError(`Encountered CC API error while listing ${typeName} resources matching ${JSON.stringify(propertyMatch)}: ${err.message}`);\n }\n throw err;\n }\n }\n}\n\n/**\n * Convert a CC API response object into a nicer object (parse the JSON)\n */\nfunction foundResourceFromCcApi(desc: ResourceDescription): FoundResource {\n return {\n identifier: desc.Identifier ?? '*MISSING*',\n properties: JSON.parse(desc.Properties ?? '{}'),\n };\n}\n\n/**\n * Whether the given property value matches the given filter\n *\n * For now we just check for strict equality, but we can implement pattern matching and fuzzy matching here later\n */\nfunction propertyMatchesFilter(actual: unknown, expected: unknown) {\n return expected === actual;\n}\n\nfunction isObject(x: unknown): x is {[key: string]: unknown} {\n return typeof x === 'object' && x !== null && !Array.isArray(x);\n}\n\n/**\n * A parsed version of the return value from CCAPI\n */\ninterface FoundResource {\n readonly identifier: string;\n readonly properties: Record<string, unknown>;\n}\n\n/**\n * A specific lookup failure indicating 0 resources found that can be recovered\n */\nclass ZeroResourcesFoundError extends Error {\n}\n", "import type { EndpointServiceAvailabilityZonesContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport type { IContextProviderMessages } from '.';\nimport { type SdkProvider, initContextProviderSdk } from '../api/aws-auth';\nimport type { ContextProviderPlugin } from '../api/plugin';\n\n/**\n * Plugin to retrieve the Availability Zones for an endpoint service\n */\nexport class EndpointServiceAZContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider, private readonly io: IContextProviderMessages) {\n }\n\n public async getValue(args: EndpointServiceAvailabilityZonesContextQuery) {\n const region = args.region;\n const account = args.account;\n const serviceName = args.serviceName;\n await this.io.debug(`Reading AZs for ${account}:${region}:${serviceName}`);\n const ec2 = (await initContextProviderSdk(this.aws, args)).ec2();\n const response = await ec2.describeVpcEndpointServices({\n ServiceNames: [serviceName],\n });\n\n // expect a service in the response\n if (!response.ServiceDetails || response.ServiceDetails.length === 0) {\n await this.io.debug(`Could not retrieve service details for ${account}:${region}:${serviceName}`);\n return [];\n }\n const azs = response.ServiceDetails[0].AvailabilityZones;\n await this.io.debug(`Endpoint service ${account}:${region}:${serviceName} is available in availability zones ${azs}`);\n return azs;\n }\n}\n", "import type { HostedZoneContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport type { HostedZone } from '@aws-sdk/client-route-53';\nimport type { IContextProviderMessages } from '.';\nimport type { IRoute53Client, SdkProvider } from '../api/aws-auth';\nimport { initContextProviderSdk } from '../api/aws-auth';\nimport type { ContextProviderPlugin } from '../api/plugin';\nimport { ContextProviderError } from '../api/toolkit-error';\n\nexport class HostedZoneContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider, private readonly io: IContextProviderMessages) {\n }\n\n public async getValue(args: HostedZoneContextQuery): Promise<object> {\n const account = args.account;\n const region = args.region;\n if (!this.isHostedZoneQuery(args)) {\n throw new ContextProviderError(`HostedZoneProvider requires domainName property to be set in ${args}`);\n }\n const domainName = args.domainName;\n await this.io.debug(`Reading hosted zone ${account}:${region}:${domainName}`);\n const r53 = (await initContextProviderSdk(this.aws, args)).route53();\n const response = await r53.listHostedZonesByName({ DNSName: domainName });\n if (!response.HostedZones) {\n throw new ContextProviderError(`Hosted Zone not found in account ${account}, region ${region}: ${domainName}`);\n }\n const candidateZones = await this.filterZones(r53, response.HostedZones, args);\n if (candidateZones.length !== 1) {\n const filteProps = `dns:${domainName}, privateZone:${args.privateZone}, vpcId:${args.vpcId}`;\n throw new ContextProviderError(`Found zones: ${JSON.stringify(candidateZones)} for ${filteProps}, but wanted exactly 1 zone`);\n }\n\n return {\n Id: candidateZones[0].Id,\n Name: candidateZones[0].Name,\n };\n }\n\n private async filterZones(\n r53: IRoute53Client,\n zones: HostedZone[],\n props: HostedZoneContextQuery,\n ): Promise<HostedZone[]> {\n let candidates: HostedZone[] = [];\n const domainName = props.domainName.endsWith('.') ? props.domainName : `${props.domainName}.`;\n await this.io.debug(`Found the following zones ${JSON.stringify(zones)}`);\n candidates = zones.filter((zone) => zone.Name === domainName);\n await this.io.debug(`Found the following matched name zones ${JSON.stringify(candidates)}`);\n if (props.privateZone) {\n candidates = candidates.filter((zone) => zone.Config && zone.Config.PrivateZone);\n } else {\n candidates = candidates.filter((zone) => !zone.Config || !zone.Config.PrivateZone);\n }\n if (props.vpcId) {\n const vpcZones: HostedZone[] = [];\n for (const zone of candidates) {\n const data = await r53.getHostedZone({ Id: zone.Id });\n if (!data.VPCs) {\n await this.io.debug(`Expected VPC for private zone but no VPC found ${zone.Id}`);\n continue;\n }\n if (data.VPCs.map((vpc) => vpc.VPCId).includes(props.vpcId)) {\n vpcZones.push(zone);\n }\n }\n return vpcZones;\n }\n return candidates;\n }\n\n private isHostedZoneQuery(props: HostedZoneContextQuery | any): props is HostedZoneContextQuery {\n return (props as HostedZoneContextQuery).domainName !== undefined;\n }\n}\n", "import type { KeyContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport type { KeyContextResponse } from '@aws-cdk/cx-api';\nimport type { AliasListEntry, ListAliasesCommandOutput } from '@aws-sdk/client-kms';\nimport type { IContextProviderMessages } from '.';\nimport type { IKMSClient, SdkProvider } from '../api/aws-auth';\nimport { initContextProviderSdk } from '../api/aws-auth';\nimport type { ContextProviderPlugin } from '../api/plugin';\nimport { ContextProviderError } from '../api/toolkit-error';\n\nexport class KeyContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider, private readonly io: IContextProviderMessages) {\n }\n\n public async getValue(args: KeyContextQuery) {\n const kms = (await initContextProviderSdk(this.aws, args)).kms();\n\n const aliasListEntry = await this.findKey(kms, args);\n\n return this.readKeyProps(aliasListEntry, args);\n }\n\n // TODO: use paginator function\n private async findKey(kms: IKMSClient, args: KeyContextQuery): Promise<AliasListEntry> {\n await this.io.debug(`Listing keys in ${args.account}:${args.region}`);\n\n let response: ListAliasesCommandOutput;\n let nextMarker: string | undefined;\n do {\n response = await kms.listAliases({\n Marker: nextMarker,\n });\n\n const aliases = response.Aliases || [];\n for (const alias of aliases) {\n if (alias.AliasName == args.aliasName) {\n return alias;\n }\n }\n\n nextMarker = response.NextMarker;\n } while (nextMarker);\n\n const suppressError = 'ignoreErrorOnMissingContext' in args && args.ignoreErrorOnMissingContext as boolean;\n const hasDummyKeyId = 'dummyValue' in args && typeof args.dummyValue === 'object' && args.dummyValue !== null && 'keyId' in args.dummyValue;\n if (suppressError && hasDummyKeyId) {\n const keyId = (args.dummyValue as { keyId: string }).keyId;\n return { TargetKeyId: keyId };\n }\n throw new ContextProviderError(`Could not find any key with alias named ${args.aliasName}`);\n }\n\n private async readKeyProps(alias: AliasListEntry, args: KeyContextQuery): Promise<KeyContextResponse> {\n if (!alias.TargetKeyId) {\n throw new ContextProviderError(`Could not find any key with alias named ${args.aliasName}`);\n }\n\n await this.io.debug(`Key found ${alias.TargetKeyId}`);\n\n return {\n keyId: alias.TargetKeyId,\n };\n }\n}\n", "import type { LoadBalancerContextQuery, LoadBalancerListenerContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport type {\n LoadBalancerContextResponse,\n LoadBalancerListenerContextResponse,\n} from '@aws-cdk/cx-api';\nimport {\n LoadBalancerIpAddressType,\n} from '@aws-cdk/cx-api';\nimport type { LoadBalancer, Listener, TagDescription } from '@aws-sdk/client-elastic-load-balancing-v2';\nimport type { IElasticLoadBalancingV2Client, SdkProvider } from '../api/aws-auth';\nimport { initContextProviderSdk } from '../api/aws-auth';\nimport type { ContextProviderPlugin } from '../api/plugin';\nimport { ContextProviderError } from '../api/toolkit-error';\n\n/**\n * Provides load balancer context information.\n */\nexport class LoadBalancerContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider) {\n }\n\n async getValue(query: LoadBalancerContextQuery): Promise<LoadBalancerContextResponse> {\n if (!query.loadBalancerArn && !query.loadBalancerTags) {\n throw new ContextProviderError('The load balancer lookup query must specify either `loadBalancerArn` or `loadBalancerTags`');\n }\n\n const loadBalancer = await (await LoadBalancerProvider.getClient(this.aws, query)).getLoadBalancer();\n\n const ipAddressType =\n loadBalancer.IpAddressType === 'ipv4' ? LoadBalancerIpAddressType.IPV4 : LoadBalancerIpAddressType.DUAL_STACK;\n\n return {\n loadBalancerArn: loadBalancer.LoadBalancerArn!,\n loadBalancerCanonicalHostedZoneId: loadBalancer.CanonicalHostedZoneId!,\n loadBalancerDnsName: loadBalancer.DNSName!,\n vpcId: loadBalancer.VpcId!,\n securityGroupIds: loadBalancer.SecurityGroups ?? [],\n ipAddressType: ipAddressType,\n };\n }\n}\n\n/**\n * Provides load balancer listener context information\n */\nexport class LoadBalancerListenerContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider) {\n }\n\n async getValue(query: LoadBalancerListenerContextQuery): Promise<LoadBalancerListenerContextResponse> {\n if (!query.listenerArn && !query.loadBalancerArn && !query.loadBalancerTags) {\n throw new ContextProviderError(\n 'The load balancer listener query must specify at least one of: `listenerArn`, `loadBalancerArn` or `loadBalancerTags`',\n );\n }\n\n return (await LoadBalancerProvider.getClient(this.aws, query)).getListener();\n }\n}\n\nclass LoadBalancerProvider {\n public static async getClient(\n aws: SdkProvider,\n query: LoadBalancerListenerContextQuery,\n ): Promise<LoadBalancerProvider> {\n const client = (await initContextProviderSdk(aws, query)).elbv2();\n\n try {\n const listener = query.listenerArn\n ? // Assert we're sure there's at least one so it throws if not\n (await client.describeListeners({ ListenerArns: [query.listenerArn] })).Listeners![0]!\n : undefined;\n return new LoadBalancerProvider(\n client,\n { ...query, loadBalancerArn: listener?.LoadBalancerArn || query.loadBalancerArn },\n listener,\n );\n } catch (err) {\n throw new ContextProviderError(`No load balancer listeners found matching arn ${query.listenerArn}`);\n }\n }\n\n constructor(\n private readonly client: IElasticLoadBalancingV2Client,\n private readonly filter: LoadBalancerListenerContextQuery,\n private readonly listener?: Listener,\n ) {\n }\n\n public async getLoadBalancer(): Promise<LoadBalancer> {\n const loadBalancers = await this.getLoadBalancers();\n\n if (loadBalancers.length === 0) {\n throw new ContextProviderError(`No load balancers found matching ${JSON.stringify(this.filter)}`);\n }\n\n if (loadBalancers.length > 1) {\n throw new ContextProviderError(\n `Multiple load balancers found matching ${JSON.stringify(this.filter)} - please provide more specific criteria`,\n );\n }\n\n return loadBalancers[0];\n }\n\n public async getListener(): Promise<LoadBalancerListenerContextResponse> {\n if (this.listener) {\n try {\n const loadBalancer = await this.getLoadBalancer();\n return {\n listenerArn: this.listener.ListenerArn!,\n listenerPort: this.listener.Port!,\n securityGroupIds: loadBalancer.SecurityGroups || [],\n };\n } catch (err) {\n throw new ContextProviderError(`No associated load balancer found for listener arn ${this.filter.listenerArn}`);\n }\n }\n\n const loadBalancers = await this.getLoadBalancers();\n if (loadBalancers.length === 0) {\n throw new ContextProviderError(\n `No associated load balancers found for load balancer listener query ${JSON.stringify(this.filter)}`,\n );\n }\n\n const listeners = (await this.getListenersForLoadBalancers(loadBalancers)).filter((listener) => {\n return (\n (!this.filter.listenerPort || listener.Port === this.filter.listenerPort) &&\n (!this.filter.listenerProtocol || listener.Protocol === this.filter.listenerProtocol)\n );\n });\n\n if (listeners.length === 0) {\n throw new ContextProviderError(`No load balancer listeners found matching ${JSON.stringify(this.filter)}`);\n }\n\n if (listeners.length > 1) {\n throw new ContextProviderError(\n `Multiple load balancer listeners found matching ${JSON.stringify(this.filter)} - please provide more specific criteria`,\n );\n }\n\n return {\n listenerArn: listeners[0].ListenerArn!,\n listenerPort: listeners[0].Port!,\n securityGroupIds:\n loadBalancers.find((lb) => listeners[0].LoadBalancerArn === lb.LoadBalancerArn)?.SecurityGroups || [],\n };\n }\n\n private async getLoadBalancers() {\n const loadBalancerArns = this.filter.loadBalancerArn ? [this.filter.loadBalancerArn] : undefined;\n const loadBalancers = (\n await this.client.paginateDescribeLoadBalancers({\n LoadBalancerArns: loadBalancerArns,\n })\n ).filter((lb) => lb.Type === this.filter.loadBalancerType);\n\n return this.filterByTags(loadBalancers);\n }\n\n private async filterByTags(loadBalancers: LoadBalancer[]): Promise<LoadBalancer[]> {\n if (!this.filter.loadBalancerTags) {\n return loadBalancers;\n }\n return (await this.describeTags(loadBalancers.map((lb) => lb.LoadBalancerArn!)))\n .filter((tagDescription) => {\n // For every tag in the filter, there is some tag in the LB that matches it.\n // In other words, the set of tags in the filter is a subset of the set of tags in the LB.\n return this.filter.loadBalancerTags!.every((filter) => {\n return tagDescription.Tags?.some((tag) =>\n filter.key === tag.Key && filter.value === tag.Value);\n });\n })\n .flatMap((tag) => loadBalancers.filter((loadBalancer) => tag.ResourceArn === loadBalancer.LoadBalancerArn));\n }\n\n /**\n * Returns tag descriptions associated with the resources. The API doesn't support\n * pagination, so this function breaks the resource list into chunks and issues\n * the appropriate requests.\n */\n private async describeTags(resourceArns: string[]): Promise<TagDescription[]> {\n // Max of 20 resource arns per request.\n const chunkSize = 20;\n const tags = Array<TagDescription>();\n for (let i = 0; i < resourceArns.length; i += chunkSize) {\n const chunk = resourceArns.slice(i, Math.min(i + chunkSize, resourceArns.length));\n const chunkTags = await this.client.describeTags({\n ResourceArns: chunk,\n });\n\n tags.push(...(chunkTags.TagDescriptions || []));\n }\n return tags;\n }\n\n private async getListenersForLoadBalancers(loadBalancers: LoadBalancer[]): Promise<Listener[]> {\n const listeners: Listener[] = [];\n for (const loadBalancer of loadBalancers.map((lb) => lb.LoadBalancerArn)) {\n listeners.push(...(await this.client.paginateDescribeListeners({ LoadBalancerArn: loadBalancer })));\n }\n return listeners;\n }\n}\n", "import type { SecurityGroupContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport type { SecurityGroupContextResponse } from '@aws-cdk/cx-api';\nimport type { Filter, SecurityGroup } from '@aws-sdk/client-ec2';\nimport { type SdkProvider, initContextProviderSdk } from '../api/aws-auth';\nimport type { ContextProviderPlugin } from '../api/plugin';\nimport { ContextProviderError } from '../api/toolkit-error';\n\nexport class SecurityGroupContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider) {\n }\n\n async getValue(args: SecurityGroupContextQuery): Promise<SecurityGroupContextResponse> {\n if (args.securityGroupId && args.securityGroupName) {\n throw new ContextProviderError(\n \"'securityGroupId' and 'securityGroupName' can not be specified both when looking up a security group\",\n );\n }\n\n if (!args.securityGroupId && !args.securityGroupName) {\n throw new ContextProviderError(\"'securityGroupId' or 'securityGroupName' must be specified to look up a security group\");\n }\n\n const ec2 = (await initContextProviderSdk(this.aws, args)).ec2();\n\n const filters: Filter[] = [];\n if (args.vpcId) {\n filters.push({\n Name: 'vpc-id',\n Values: [args.vpcId],\n });\n }\n if (args.securityGroupName) {\n filters.push({\n Name: 'group-name',\n Values: [args.securityGroupName],\n });\n }\n\n const response = await ec2.describeSecurityGroups({\n GroupIds: args.securityGroupId ? [args.securityGroupId] : undefined,\n Filters: filters.length > 0 ? filters : undefined,\n });\n\n const securityGroups = response.SecurityGroups ?? [];\n if (securityGroups.length === 0) {\n throw new ContextProviderError(`No security groups found matching ${JSON.stringify(args)}`);\n }\n\n if (securityGroups.length > 1) {\n throw new ContextProviderError(`More than one security groups found matching ${JSON.stringify(args)}`);\n }\n\n const [securityGroup] = securityGroups;\n\n return {\n securityGroupId: securityGroup.GroupId!,\n allowAllOutbound: hasAllTrafficEgress(securityGroup),\n };\n }\n}\n\n/**\n * @internal\n */\nexport function hasAllTrafficEgress(securityGroup: SecurityGroup) {\n let hasAllTrafficCidrV4 = false;\n let hasAllTrafficCidrV6 = false;\n\n for (const ipPermission of securityGroup.IpPermissionsEgress ?? []) {\n const isAllProtocols = ipPermission.IpProtocol === '-1';\n\n if (isAllProtocols && ipPermission.IpRanges?.some((m) => m.CidrIp === '0.0.0.0/0')) {\n hasAllTrafficCidrV4 = true;\n }\n\n if (isAllProtocols && ipPermission.Ipv6Ranges?.some((m) => m.CidrIpv6 === '::/0')) {\n hasAllTrafficCidrV6 = true;\n }\n }\n\n return hasAllTrafficCidrV4 && hasAllTrafficCidrV6;\n}\n", "import type { SSMParameterContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport type { GetParameterCommandOutput } from '@aws-sdk/client-ssm';\nimport type { IContextProviderMessages } from '.';\nimport { type SdkProvider, initContextProviderSdk } from '../api/aws-auth';\nimport type { ContextProviderPlugin } from '../api/plugin';\nimport { ContextProviderError } from '../api/toolkit-error';\n\n/**\n * Plugin to read arbitrary SSM parameter names\n */\nexport class SSMContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider, private readonly io: IContextProviderMessages) {\n }\n\n public async getValue(args: SSMParameterContextQuery) {\n const region = args.region;\n const account = args.account;\n\n if (!('parameterName' in args)) {\n throw new ContextProviderError('parameterName must be provided in props for SSMContextProviderPlugin');\n }\n const parameterName = args.parameterName;\n await this.io.debug(`Reading SSM parameter ${account}:${region}:${parameterName}`);\n\n const response = await this.getSsmParameterValue(args);\n const parameterNotFound: boolean = !response.Parameter || response.Parameter.Value === undefined;\n const suppressError = 'ignoreErrorOnMissingContext' in args && (args.ignoreErrorOnMissingContext as boolean);\n if (parameterNotFound && suppressError && 'dummyValue' in args) {\n return args.dummyValue;\n }\n if (parameterNotFound) {\n throw new ContextProviderError(`SSM parameter not available in account ${account}, region ${region}: ${parameterName}`);\n }\n // will not be undefined because we've handled undefined cases above\n return response.Parameter!.Value;\n }\n\n /**\n * Gets the value of an SSM Parameter, while not throwin if the parameter does not exist.\n * @param account the account in which the SSM Parameter is expected to be.\n * @param region the region in which the SSM Parameter is expected to be.\n * @param parameterName the name of the SSM Parameter\n * @param lookupRoleArn the ARN of the lookup role.\n *\n * @returns the result of the ``GetParameter`` operation.\n *\n * @throws Error if a service error (other than ``ParameterNotFound``) occurs.\n */\n private async getSsmParameterValue(args: SSMParameterContextQuery): Promise<GetParameterCommandOutput> {\n const ssm = (await initContextProviderSdk(this.aws, args)).ssm();\n try {\n return await ssm.getParameter({ Name: args.parameterName });\n } catch (e: any) {\n if (e.name === 'ParameterNotFound') {\n return { $metadata: {} };\n }\n throw e;\n }\n }\n}\n", "import type { VpcContextQuery } from '@aws-cdk/cloud-assembly-schema';\nimport { type VpcContextResponse, type VpcSubnetGroup, VpcSubnetGroupType } from '@aws-cdk/cx-api';\nimport type { Filter, RouteTable, Tag, Vpc } from '@aws-sdk/client-ec2';\nimport type { IContextProviderMessages } from '.';\nimport type { IEC2Client, SdkProvider } from '../api/aws-auth';\nimport { initContextProviderSdk } from '../api/aws-auth';\nimport type { ContextProviderPlugin } from '../api/plugin';\nimport { ContextProviderError } from '../api/toolkit-error';\n\nexport class VpcNetworkContextProviderPlugin implements ContextProviderPlugin {\n constructor(private readonly aws: SdkProvider, private readonly io: IContextProviderMessages) {\n }\n\n public async getValue(args: VpcContextQuery) {\n const ec2 = (await initContextProviderSdk(this.aws, args)).ec2();\n\n const vpcId = await this.findVpc(ec2, args);\n\n return this.readVpcProps(ec2, vpcId, args);\n }\n\n private async findVpc(ec2: IEC2Client, args: VpcContextQuery): Promise<Vpc> {\n // Build request filter (map { Name -> Value } to list of [{ Name, Values }])\n const filters: Filter[] = Object.entries(args.filter).map(([tag, value]) => ({ Name: tag, Values: [value] }));\n\n await this.io.debug(`Listing VPCs in ${args.account}:${args.region}`);\n const response = await ec2.describeVpcs({ Filters: filters });\n\n const vpcs = response.Vpcs || [];\n if (vpcs.length === 0) {\n throw new ContextProviderError(`Could not find any VPCs matching ${JSON.stringify(args)}`);\n }\n if (vpcs.length > 1) {\n throw new ContextProviderError(`Found ${vpcs.length} VPCs matching ${JSON.stringify(args)}; please narrow the search criteria`);\n }\n\n return vpcs[0];\n }\n\n private async readVpcProps(ec2: IEC2Client, vpc: Vpc, args: VpcContextQuery): Promise<VpcContextResponse> {\n const vpcId = vpc.VpcId!;\n\n await this.io.debug(`Describing VPC ${vpcId}`);\n\n const filters = { Filters: [{ Name: 'vpc-id', Values: [vpcId] }] };\n\n const subnetsResponse = await ec2.describeSubnets(filters);\n const listedSubnets = subnetsResponse.Subnets || [];\n\n const routeTablesResponse = await ec2.describeRouteTables(filters);\n const routeTables = new RouteTables(routeTablesResponse.RouteTables || []);\n\n // Now comes our job to separate these subnets out into AZs and subnet groups (Public, Private, Isolated)\n // We have the following attributes to go on:\n // - Type tag, we tag subnets with their type. In absence of this tag, we\n // determine the subnet must be Public if either:\n // a) it has the property MapPublicIpOnLaunch\n // b) it has a route to an Internet Gateway\n // If both of the above is false but the subnet has a route to a NAT Gateway\n // and the destination CIDR block is \"0.0.0.0/0\", we assume it to be a Private subnet.\n // Anything else is considered Isolated.\n // - Name tag, we tag subnets with their subnet group name. In absence of this tag,\n // we use the type as the name.\n\n const azs = Array.from(new Set<string>(listedSubnets.map((s) => s.AvailabilityZone!)));\n azs.sort();\n\n const subnets: Subnet[] = listedSubnets.map((subnet) => {\n let type = getTag('aws-cdk:subnet-type', subnet.Tags);\n if (type === undefined && subnet.MapPublicIpOnLaunch) {\n type = SubnetType.Public;\n }\n if (type === undefined && routeTables.hasRouteToIgw(subnet.SubnetId)) {\n type = SubnetType.Public;\n }\n if (type === undefined && routeTables.hasRouteToNatGateway(subnet.SubnetId)) {\n type = SubnetType.Private;\n }\n if (type === undefined && routeTables.hasRouteToTransitGateway(subnet.SubnetId)) {\n type = SubnetType.Private;\n }\n if (type === undefined) {\n type = SubnetType.Isolated;\n }\n\n if (!isValidSubnetType(type)) {\n // eslint-disable-next-line max-len\n throw new ContextProviderError(\n `Subnet ${subnet.SubnetArn} has invalid subnet type ${type} (must be ${SubnetType.Public}, ${SubnetType.Private} or ${SubnetType.Isolated})`,\n );\n }\n\n if (args.subnetGroupNameTag && !getTag(args.subnetGroupNameTag, subnet.Tags)) {\n throw new ContextProviderError(\n `Invalid subnetGroupNameTag: Subnet ${subnet.SubnetArn} does not have an associated tag with Key='${args.subnetGroupNameTag}'`,\n );\n }\n\n const name = getTag(args.subnetGroupNameTag || 'aws-cdk:subnet-name', subnet.Tags) || type;\n const routeTableId = routeTables.routeTableIdForSubnetId(subnet.SubnetId);\n\n if (!routeTableId) {\n throw new ContextProviderError(\n `Subnet ${subnet.SubnetArn} does not have an associated route table (and there is no \"main\" table)`,\n );\n }\n\n return {\n az: subnet.AvailabilityZone!,\n cidr: subnet.CidrBlock!,\n type,\n name,\n subnetId: subnet.SubnetId!,\n routeTableId,\n };\n });\n\n let grouped: SubnetGroups;\n let assymetricSubnetGroups: VpcSubnetGroup[] | undefined;\n if (args.returnAsymmetricSubnets) {\n grouped = { azs: [], groups: [] };\n assymetricSubnetGroups = groupAsymmetricSubnets(subnets);\n } else {\n grouped = groupSubnets(subnets);\n assymetricSubnetGroups = undefined;\n }\n\n // Find attached+available VPN gateway for this VPC\n const vpnGatewayResponse =\n (args.returnVpnGateways ?? true)\n ? await ec2.describeVpnGateways({\n Filters: [\n {\n Name: 'attachment.vpc-id',\n Values: [vpcId],\n },\n {\n Name: 'attachment.state',\n Values: ['attached'],\n },\n {\n Name: 'state',\n Values: ['available'],\n },\n ],\n })\n : undefined;\n const vpnGatewayId =\n vpnGatewayResponse?.VpnGateways?.length === 1 ? vpnGatewayResponse.VpnGateways[0].VpnGatewayId : undefined;\n\n return {\n vpcId,\n vpcCidrBlock: vpc.CidrBlock!,\n ownerAccountId: vpc.OwnerId,\n availabilityZones: grouped.azs,\n isolatedSubnetIds: collapse(\n flatMap(findGroups(SubnetType.Isolated, grouped), (group) => group.subnets.map((s) => s.subnetId)),\n ),\n isolatedSubnetNames: collapse(\n flatMap(findGroups(SubnetType.Isolated, grouped), (group) => (group.name ? [group.name] : [])),\n ),\n isolatedSubnetRouteTableIds: collapse(\n flatMap(findGroups(SubnetType.Isolated, grouped), (group) => group.subnets.map((s) => s.routeTableId)),\n ),\n privateSubnetIds: collapse(\n flatMap(findGroups(SubnetType.Private, grouped), (group) => group.subnets.map((s) => s.subnetId)),\n ),\n privateSubnetNames: collapse(\n flatMap(findGroups(SubnetType.Private, grouped), (group) => (group.name ? [group.name] : [])),\n ),\n privateSubnetRouteTableIds: collapse(\n flatMap(findGroups(SubnetType.Private, grouped), (group) => group.subnets.map((s) => s.routeTableId)),\n ),\n publicSubnetIds: collapse(\n flatMap(findGroups(SubnetType.Public, grouped), (group) => group.subnets.map((s) => s.subnetId)),\n ),\n publicSubnetNames: collapse(\n flatMap(findGroups(SubnetType.Public, grouped), (group) => (group.name ? [group.name] : [])),\n ),\n publicSubnetRouteTableIds: collapse(\n flatMap(findGroups(SubnetType.Public, grouped), (group) => group.subnets.map((s) => s.routeTableId)),\n ),\n vpnGatewayId,\n subnetGroups: assymetricSubnetGroups,\n };\n }\n}\n\nclass RouteTables {\n public readonly mainRouteTable?: RouteTable;\n\n constructor(private readonly tables: RouteTable[]) {\n this.mainRouteTable = this.tables.find(\n (table) => !!table.Associations && table.Associations.some((assoc) => !!assoc.Main),\n );\n }\n\n public routeTableIdForSubnetId(subnetId: string | undefined): string | undefined {\n const table = this.tableForSubnet(subnetId);\n return (table && table.RouteTableId) || (this.mainRouteTable && this.mainRouteTable.RouteTableId);\n }\n\n /**\n * Whether the given subnet has a route to a NAT Gateway\n */\n public hasRouteToNatGateway(subnetId: string | undefined): boolean {\n const table = this.tableForSubnet(subnetId) || this.mainRouteTable;\n\n return (\n !!table &&\n !!table.Routes &&\n table.Routes.some((route) => !!route.NatGatewayId && route.DestinationCidrBlock === '0.0.0.0/0')\n );\n }\n\n /**\n * Whether the given subnet has a route to a Transit Gateway\n */\n public hasRouteToTransitGateway(subnetId: string | undefined): boolean {\n const table = this.tableForSubnet(subnetId) || this.mainRouteTable;\n\n return (\n !!table &&\n !!table.Routes &&\n table.Routes.some((route) => !!route.TransitGatewayId && route.DestinationCidrBlock === '0.0.0.0/0')\n );\n }\n\n /**\n * Whether the given subnet has a route to an IGW\n */\n public hasRouteToIgw(subnetId: string | undefined): boolean {\n const table = this.tableForSubnet(subnetId) || this.mainRouteTable;\n\n return (\n !!table && !!table.Routes && table.Routes.some((route) => !!route.GatewayId && route.GatewayId.startsWith('igw-'))\n );\n }\n\n public tableForSubnet(subnetId: string | undefined) {\n return this.tables.find(\n (table) => !!table.Associations && table.Associations.some((assoc) => assoc.SubnetId === subnetId),\n );\n }\n}\n\n/**\n * Return the value of a tag from a set of tags\n */\nfunction getTag(name: string, tags?: Tag[]): string | undefined {\n for (const tag of tags || []) {\n if (tag.Key === name) {\n return tag.Value;\n }\n }\n return undefined;\n}\n\n/**\n * Group subnets of the same type together, and order by AZ\n */\nfunction groupSubnets(subnets: Subnet[]): SubnetGroups {\n const grouping: { [key: string]: Subnet[] } = {};\n for (const subnet of subnets) {\n const key = [subnet.type, subnet.name].toString();\n if (!(key in grouping)) {\n grouping[key] = [];\n }\n grouping[key].push(subnet);\n }\n\n const groups = Object.values(grouping).map((sns) => {\n sns.sort((a: Subnet, b: Subnet) => a.az.localeCompare(b.az));\n return {\n type: sns[0].type,\n name: sns[0].name,\n subnets: sns,\n };\n });\n\n const azs = groups[0].subnets.map((s) => s.az);\n\n for (const group of groups) {\n const groupAZs = group.subnets.map((s) => s.az);\n if (!arraysEqual(groupAZs, azs)) {\n throw new ContextProviderError(`Not all subnets in VPC have the same AZs: ${groupAZs} vs ${azs}`);\n }\n }\n\n return { azs, groups };\n}\n\nfunction groupAsymmetricSubnets(subnets: Subnet[]): VpcSubnetGroup[] {\n const grouping: { [key: string]: Subnet[] } = {};\n for (const subnet of subnets) {\n const key = [subnet.type, subnet.name].toString();\n if (!(key in grouping)) {\n grouping[key] = [];\n }\n grouping[key].push(subnet);\n }\n\n return Object.values(grouping).map((subnetArray) => {\n subnetArray.sort((subnet1: Subnet, subnet2: Subnet) => subnet1.az.localeCompare(subnet2.az));\n\n return {\n name: subnetArray[0].name,\n type: subnetTypeToVpcSubnetType(subnetArray[0].type),\n subnets: subnetArray.map((subnet) => ({\n subnetId: subnet.subnetId,\n cidr: subnet.cidr,\n availabilityZone: subnet.az,\n routeTableId: subnet.routeTableId,\n })),\n };\n });\n}\n\nfunction subnetTypeToVpcSubnetType(type: SubnetType): VpcSubnetGroupType {\n switch (type) {\n case SubnetType.Isolated:\n return VpcSubnetGroupType.ISOLATED;\n case SubnetType.Private:\n return VpcSubnetGroupType.PRIVATE;\n case SubnetType.Public:\n return VpcSubnetGroupType.PUBLIC;\n }\n}\n\nenum SubnetType {\n Public = 'Public',\n Private = 'Private',\n Isolated = 'Isolated',\n}\n\nfunction isValidSubnetType(val: string): val is SubnetType {\n return val === SubnetType.Public || val === SubnetType.Private || val === SubnetType.Isolated;\n}\n\ninterface Subnet {\n az: string;\n cidr: string;\n type: SubnetType;\n name: string;\n routeTableId: string;\n subnetId: string;\n}\n\ninterface SubnetGroup {\n type: SubnetType;\n name: string;\n subnets: Subnet[];\n}\n\ninterface SubnetGroups {\n azs: string[];\n groups: SubnetGroup[];\n}\n\nfunction arraysEqual(as: string[], bs: string[]): boolean {\n if (as.length !== bs.length) {\n return false;\n }\n\n for (let i = 0; i < as.length; i++) {\n if (as[i] !== bs[i]) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction findGroups(type: SubnetType, groups: SubnetGroups): SubnetGroup[] {\n return groups.groups.filter((g) => g.type === type);\n}\n\nfunction flatMap<T, U>(xs: T[], fn: (x: T) => U[]): U[] {\n const ret = new Array<U>();\n for (const x of xs) {\n ret.push(...fn(x));\n }\n return ret;\n}\n\nfunction collapse<T>(xs: T[]): T[] | undefined {\n if (xs.length > 0) {\n return xs;\n }\n return undefined;\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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", "util", "util", "chalk", "trace", "fs", "path", "path", "fs", "cached", "path", "fs", "ECRDescribeImagesCommand", "result", "partition", "os", "import_credential_providers", "import_util", "import_util", "Mode", "import_util", "path", "os", "path", "import_cloud_assembly_schema", "import_cx_api", "fs", "chalk", "import_cx_api", "import_cdk_assets", "import_util", "import_cx_api", "import_client_cloudformation", "import_cdk_assets", "path", "fs", "path", "util", "import_cx_api", "import_client_s3", "import_middleware_endpoint", "chalk", "path", "fs", "util", "uuid", "util", "import_client_cloudformation", "_StackStatus", "RollbackChoice", "result", "result", "import_util", "chalk", "uuid", "path", "cxschema", "cxapi", "chalk", "HotswapMode", "import_util", "chalk", "error", "archiver", "resolve", "result", "error", "path", "fs", "semver", "path", "fs", "trace", "resolve", "cached", "import_util", "chalk", "bootstrapStack", "result", "import_cx_api", "suffixWithErrors", "partition", "request", "path", "import_util", "cxapi", "fs", "chalk", "import_cx_api", "message", "ExtendedStackSelection", "result", "StackSelectionStrategy", "ExpandStackSelection", "os", "fs", "path", "import_node_util", "cxschema", "chalk", "RequireApproval", "path", "chalk", "promptly", "chalk", "resolve", "pLimit", "error", "message", "result", "util", "chalk", "uuid", "import_cloudformation_diff", "crypto", "import_util", "result", "intersection", "result", "fmtTypedMappings", "fmtAmbiguousMappings", "import_util", "chalk", "fs", "promptly", "result", "message", "prompt", "chalk", "fs", "path", "fs", "DeploymentState", "error", "path", "cxapi", "import_cdk_assets", "cxschema", "cxapi", "import_client_cloudcontrol", "isObject", "result", "import_cx_api", "import_cx_api", "flatMap", "flatMap", "message"]
7
7
  }