fjall 29.0.0 → 30.0.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.
@@ -296,7 +296,7 @@ ${n_}
296
296
  `)}
297
297
  `}Ai(CR,"renderUpdateEnvelope");var Xm,qm=!1;function eW(e){Xm=e,qm=!1}Ai(eW,"armUpdateEnvelope");function tW(){Xm=void 0,qm=!1}Ai(tW,"disarmUpdateEnvelope");function IR(){if(!(qm||Xm===void 0)){qm=!0;try{return Xm()}catch(e){Ei.debug("UpdateEnvelope","Envelope source failed",{error:le(e instanceof Error?e.message:String(e))});return}}}Ai(IR,"takeUpdateEnvelope");function Qo(){let e=IR();return e===void 0?"":CR(e)}Ai(Qo,"takeUpdateEnvelopeTail");var rW=Object.defineProperty,sa=(e,t)=>rW(e,"name",{value:t,configurable:!0}),N={success:sa(e=>e.outcome==="success","success"),error:sa(e=>e.outcome==="error","error"),empty:sa(e=>e.outcome==="empty","empty"),unsupported:sa(e=>e.outcome==="unsupported","unsupported"),successDryRun:sa(e=>e.outcome==="success"&&e.dryRun==="true","successDryRun"),successOffline:sa(e=>e.outcome==="success"&&e.offline==="true","successOffline"),errorWithCode:sa(e=>t=>t.outcome==="error"&&t.errorCode===e,"errorWithCode")};var nW=Object.defineProperty,iW=(e,t)=>nW(e,"name",{value:t,configurable:!0}),aW=["account deploy","add","agent install-skill","agent session-context","apps create","apps describe","apps detect","apps list","assets compliance","assets list","assets show","assets summary","aws exec","build","ci run","ci setup","ci status","ci token create","ci token list","ci token revoke","ci verify","compliance fix","compliance fix --execute","connect","connect status","costs show","create account","create app","create domain","create org","deploy","deploy diff","deploy logs","deployments cancel","deployments force-release","deployments list","destroy","dev down","dev list","dev substrate down","dev up","domain","domain create","domain delegate","domain deploy","domain destroy","domain eject","domain export","domain import","domain list","domain records list","domain sync","domain verify","drift detect","drift repair","drift resume","fjall","history","home","import","list","login","metrics show","migrate identity","modify","org bind","org deploy","org get","org identity setup-google","platform deploy","remove","restore","secrets delete","secrets exec","secrets export","secrets get","secrets import","secrets list","secrets set","services","status","target get","target list","target set","token create","token list","token revoke","token show","tunnel","undo","unlock bucket","user add","user list","user rebind","user remove","validate"],oW=new Set(aW);function Ym(e){return typeof e=="string"&&oW.has(e)}iW(Ym,"isAgentWriterSurface");var bl="fjall";var sW=Object.defineProperty,cW=(e,t)=>sW(e,"name",{value:t,configurable:!0}),DR=[{command:bl,match:N.error,templates:["Run `fjall --help` to list the available commands"]},{command:"home",match:N.success,templates:["Run `fjall apps describe <name>` to see app details","Run `fjall deploy <name>` to deploy","Run `fjall status <name>` to check a specific app"]},{command:"home",match:N.empty,templates:[`Run \`${te.createApplicationAgent} --name "<name>"\` to create your first app`,`Run \`${te.connect}\` to connect an AWS account`]},{command:"apps list",match:N.success,templates:["Run `fjall apps describe <name>` to see app details","Run `fjall deploy <name>` to deploy",`Run \`${te.createApplicationAgent} --name "<name>"\` to create a new app`]},{command:"apps list",match:N.empty,templates:[`Run \`${te.createApplicationAgent} --name "<name>"\` to create your first app`,`Run \`${te.connect}\` to connect an AWS account first`]},{command:"apps describe",match:N.success,templates:["Run `fjall deploy <app>` to deploy","Run `fjall secrets list --app <app>` to list secrets","Run `fjall status <app>` to check health"]},{command:"apps detect",match:N.empty,templates:["Run `fjall apps detect <path> --agent` against the directory holding the application, if this was the repository root","Pass `--pattern staticsite` with `--source`, `--build-command` and `--output-dir` explicitly if the app has no recognised framework dependency"]},{command:"apps detect",match:N.success,templates:[`Run \`${te.createApplicationAgent} --name <name> --pattern <pattern>\` using the \`pattern\` column \u2014 never the \`framework\` column`,"Skip any row whose `role` is `library` \u2014 those are not deployable applications","Confirm `outputDir` exists after building: it is a framework convention, not a verified path"]},{command:"apps create",match:N.successOffline,templates:["Run `npm install` in the app directory \u2014 `--offline` skipped it",`Re-run \`${te.createApplicationAgent}\` without \`--offline\` once you have credentials, to register the app`,"Run `fjall deploy <app>` only after both of the above"]},{command:"apps create",match:N.success,templates:["Run `fjall deploy <app>` to deploy your new app","Run `fjall secrets set --app <app> DB_URL=<url>` to configure secrets"]},{command:"status",match:N.success,templates:["Run `fjall deploy <app>` to deploy","Run `fjall apps describe <app>` for details"]},{command:"deploy",match:N.success,templates:["Run `fjall status <app>` to check health","Run `fjall apps describe <app>` for full details"]},{command:"deploy",match:N.error,templates:["Run `fjall deploy <app>` to retry","Run `fjall status <app>` to check current state"]},{command:"destroy",match:N.success,templates:["Run `fjall list` to see remaining resources","Run `fjall apps list` to see remaining apps"]},{command:"destroy",match:N.error,templates:["Run `fjall destroy <app> --skip-confirmation` to force destroy","Run `fjall status <app>` to check current state"]},{command:"build",match:N.success,templates:["Run `fjall deploy <app> --image-tag <tag>` with a tag from `artefacts` to roll out this build","Run `fjall status <app>` to check health"]},{command:"connect",match:cW(e=>e.outcome==="success"&&e.pending==="true","match"),templates:["Run `fjall connect status --external-id <externalId> --wait` to block until the stack completes"]},{command:"connect",match:N.success,templates:[`Run \`${te.accountDeploy}\` or \`${te.organisationDeploy}\` to deploy infrastructure`,`Run \`${te.createApplicationAgent} --name "<name>"\` to create an app`]},{command:"connect status",match:N.success,templates:["Run `fjall connect status --external-id <id> --wait` to block until a pending stack completes",`Run \`${te.accountDeploy}\` or \`${te.organisationDeploy}\` to deploy infrastructure`]},{command:"connect status",match:N.empty,templates:[`Run \`${te.connect}\` to connect an AWS account`]},{command:"login",match:N.success,templates:["Run `fjall apps list` to see your applications",`Run \`${te.connect}\` to connect an AWS account`]},{command:"list",match:N.success,templates:["Run `fjall apps describe <name>` for app details","Run `fjall deploy <name>` to deploy"]},{command:"add",match:N.success,templates:["Run `fjall deploy <app>` to deploy the change","Run `fjall apps describe <app>` to see updated resources"]},{command:"modify",match:N.success,templates:["Run `fjall validate --deep --app <app>` to typecheck the edited infrastructure.ts","Run `fjall deploy <app>` to deploy the change","Run `fjall undo --app <app>` to restore the .bak sidecar if the edit was wrong"]},{command:"remove",match:N.success,templates:["Run `fjall validate --deep --app <app>` to confirm nothing still references the removed resource","Run `fjall deploy <app>` to deploy the change","Run `fjall undo --app <app>` to restore the .bak sidecar if the removal was wrong"]},{command:"validate",match:N.success,templates:["Run `fjall deploy <app>` to deploy the validated infrastructure"]},{command:"validate",match:N.error,templates:["Run `fjall undo --app <app>` to restore the most recent .bak sidecar","Run `fjall history --app <app>` to list older snapshots to restore from"]},{command:"undo",match:N.success,templates:["Run `fjall validate --deep --app <app>` to confirm the restored infrastructure.ts typechecks","Run `fjall history --app <app>` to restore an older snapshot instead"]},{command:"history",match:N.success,templates:["Run `fjall history --restore <timestamp> --app <app>` to restore a specific snapshot","Run `fjall undo --app <app>` to restore the most recent .bak sidecar instead"]},{command:"history",match:N.empty,templates:["No snapshots yet \u2014 `fjall add`, `fjall modify` and `fjall remove` each write one before editing infrastructure.ts"]},{command:"tunnel",match:N.success,templates:["Run `fjall tunnel <app> --background` to run in the background"]}];var NR=[{command:"secrets list",match:N.success,templates:["Run `fjall secrets set --app <app> KEY=VALUE` to set a secret","Run `fjall rollout <app>` to restart running services with the latest values"]},{command:"secrets list",match:N.empty,templates:["Run `fjall secrets set --app <app> KEY=VALUE` to add a secret","Run `fjall secrets import --app <app> <file>` to bulk import"]},{command:"secrets get",match:N.success,templates:["Run `fjall secrets set --app <app> KEY=VALUE` to update","Run `fjall secrets list --app <app>` to see all secrets"]},{command:"secrets set",match:N.success,templates:["Run `fjall rollout <app>` to restart running services with the new value","New key? Run a full `fjall deploy <app>` so the task definition gains the reference","Run `fjall secrets list --app <app>` to verify"]},{command:"secrets delete",match:N.success,templates:["Declared for a service? Re-run with `--remove-declaration` (or edit infrastructure.ts ssmSecrets), then `fjall deploy <app>` \u2014 a stale declaration breaks task launches","Not declared anywhere? Run `fjall rollout <app>` so running services drop the previous value","Run `fjall secrets list --app <app>` to verify"]},{command:"secrets import",match:N.success,templates:["Run `fjall rollout <app>` to restart running services with the imported values","New keys? Run a full `fjall deploy <app>` so task definitions gain the references","Run `fjall secrets list --app <app>` to verify"]},{command:"secrets export",match:N.success,templates:["Run `fjall secrets list --app <app>` to see all secret names","Run `fjall secrets import --app <app> <file>` to restore"]},{command:"secrets exec",match:N.success,templates:["Run `fjall secrets list --app <app>` to see available secrets"]}];var lW=Object.defineProperty,uW=(e,t)=>lW(e,"name",{value:t,configurable:!0});var kR="identity-only organisation deploys typically take 2-5 minutes",S_=`Run \`${te.organisationDeploy}\` to apply the change (${kR}).`,aoe=`Deploy the organisation now to apply this change? (${kR})`,dW="Groups have no members",es="fjall user add <email> --group <group>",pW=es,ooe=`${dW} \u2014 run \`${pW}\` to declare access.`;function mW(e,t){return`Declared identity (source "${e}"): ${String(t)} user${t===1?"":"s"}`}uW(mW,"formatUserListHeading");var soe=`No users or memberships declared. Run \`${es}\` to add one.`;var wR=[{command:"user list",match:N.success,templates:[`Run \`${es}\` to grant access`,`Run \`${te.organisationDeploy}\` to apply declared changes`]},{command:"user list",match:N.empty,templates:[`Run \`${es}\` to declare the first membership`]},{command:"user add",match:N.success,templates:[S_,"Run `fjall user list` to review the declared users"]},{command:"user remove",match:N.success,templates:[S_,"Run `fjall user list` to see the remaining users"]},{command:"user rebind",match:N.success,templates:[`Run \`${te.organisationDeploy}\` to re-resolve external users against the identity store`]},{command:"org identity setup-google",match:N.success,templates:[`Run \`${es} --live\` to declare access for a synced user`,"Run `fjall user list --live` to compare declared memberships against the identity store"]},{command:"token create",match:N.success,templates:["Run `fjall token list` to see all tokens","Save the token now \u2014 it cannot be retrieved again"]},{command:"token list",match:N.success,templates:["Run `fjall token create --name <name> --scope <scope> --expires <duration>` to create a token","Run `fjall token revoke <id>` to revoke a token"]},{command:"token show",match:N.success,templates:["Run `fjall token revoke <id>` to revoke this token","Run `fjall token list` to see all tokens"]},{command:"token revoke",match:N.success,templates:["Run `fjall token list` to see remaining tokens"]},{command:"target list",match:N.success,templates:["Run `fjall target set <name>` to change active target","Run `fjall deploy <app>` to deploy to the active target","Run `fjall apps list` to see applications"]},{command:"target list",match:N.empty,templates:[`Run \`${te.connect}\` to connect an AWS account`,`Run \`${te.login}\` to authenticate if not logged in`]},{command:"org bind",match:N.success,templates:["Run `fjall org get` to confirm the organisation's regions and accounts","Commit fjall-config.json so every checkout of this project carries the binding"]},{command:"org get",match:N.success,templates:["Run `fjall target list` to see which account/region pairs are deployable","Run `fjall accounts list` to see application-hosting accounts only"]},{command:"target get",match:N.success,templates:["Run `fjall target set <name>` to change active target","Run `fjall target list` to see all targets"]},{command:"target get",match:N.empty,templates:["Run `fjall target set <name>` to set a target","Run `fjall target list` to see available targets"]},{command:"target set",match:N.success,templates:["Run `fjall deploy <app>` to deploy to this target","Run `fjall target get` to verify the active target"]},{command:"target set",match:N.errorWithCode("NOT_FOUND"),templates:["Run `fjall target list` to see available targets",`Run \`${te.connect}\` to connect an AWS account if none available`]}];import{platform as MW,arch as LW}from"os";import*as Oe from"fs";import*as kt from"path";var fW=Object.defineProperty,Qm=(e,t)=>fW(e,"name",{value:t,configurable:!0});function hW(e){return e.success===!0}Qm(hW,"isSuccess");function gW(e){return e.success===!1}Qm(gW,"isFailure");function ca(e){return{success:!0,data:e}}Qm(ca,"success");function nn(e){return{success:!1,error:e}}Qm(nn,"failure");var yW=Object.defineProperty,ef=(e,t)=>yW(e,"name",{value:t,configurable:!0}),vW=ef(e=>{try{return JSON.stringify(e)}catch{return"[unserializable]"}},"safeStringify"),PR=ef((e,t,r,i)=>{let n=new Date().toISOString(),a=e.toUpperCase(),o=i?` ${vW(i)}`:"";process.stderr.write(`[${n}] [${a}] [${t}] ${r}${o}
298
298
  `)},"defaultWriter"),la=PR;function SW(e){la=e}ef(SW,"configureLogWriter");function bW(){la=PR}ef(bW,"resetLogWriter");var ua={info(e,t,r){la("info",e,t,r)},warn(e,t,r){la("warn",e,t,r)},error(e,t,r){la("error",e,t,r)},debug(e,t,r){process.env.FJALL_DEBUG==="true"&&la("debug",e,t,r)},trace(e,t,r){process.env.FJALL_TRACE==="true"&&la("trace",e,t,r)},isDebugEnabled(){return process.env.FJALL_DEBUG==="true"}};var EW=Object.defineProperty,b_=(e,t)=>EW(e,"name",{value:t,configurable:!0}),E_=c.object({name:c.string(),type:c.enum(["apex","delegated"]),parentDomain:c.string().optional(),account:c.string().optional(),region:c.string().optional()}).strict(),A_=c.object({id:c.string().min(1),name:c.string().min(1).optional()}).strict(),tf=c.object({activeTarget:c.string().optional(),domains:c.array(E_).optional(),capacityIdentity:dm.optional(),organisation:A_.optional()}).strict(),El=c.object({activeTarget:c.string().optional(),domains:c.array(E_).optional(),capacityIdentity:dm.optional(),organisation:A_.optional()});function da(e={}){return JSON.stringify(e,null,2)}b_(da,"serialiseRootConfig");var rf=tf.keyof().options;function __(e,t,r){let i=t[r];i!==void 0&&(e[r]=i)}b_(__,"copyDefinedKey");function nf(e,t){if(t===void 0)return!1;let r=new Set([...Object.keys(e),...Object.keys(t)]);for(let i of r)if(e[i]!==t[i])return!1;return!0}b_(nf,"domainEntriesEqual");var AW=Object.defineProperty,ts=(e,t)=>AW(e,"name",{value:t,configurable:!0});function Al(e){if(e===void 0||e==="")return{kind:"absent"};let t;try{t=JSON.parse(e)}catch(a){return{kind:"unmergeable",reason:`the existing file could not be read or parsed as JSON (${le(ze(a))})`}}if(typeof t!="object"||t===null||Array.isArray(t))return{kind:"unmergeable",reason:"it does not contain a JSON object"};let r=El.safeParse(t);if(!r.success){let a=r.error.issues.map(o=>`${o.path.join(".")}: ${o.message}`).join("; ");return{kind:"unmergeable",reason:`a recognised key in the existing file is malformed (${le(a)})`}}let i={},n=rf;for(let[a,o]of Object.entries(t))n.includes(a)||(i[a]=o);return{kind:"ok",disk:{known:r.data,foreign:i}}}ts(Al,"readRootConfigForMerge");function RR(e,t,r){return JSON.stringify(e[r])!==JSON.stringify(t[r])}ts(RR,"sessionChangedKey");function OR(e,t,r){let i=t.domains,n=r.domains??[];if(i===void 0&&n.length===0)return e;let a=ts(h=>h.toLowerCase(),"norm"),o=i??[],s=new Map(n.map(h=>[a(h.name),h])),l=new Map(o.map(h=>[a(h.name),h])),m=[],d=new Set;for(let h of e??[]){let g=a(h.name);d.add(g);let u=l.get(g),p=s.get(g);if(u!==void 0&&!nf(u,p)){m.push(u);continue}u===void 0&&p!==void 0||m.push(h)}for(let h of o){let g=a(h.name);d.has(g)||nf(h,s.get(g))||m.push(h)}return m}ts(OR,"mergeDomains");function _l(e,t,r){let i={...e.foreign,...e.known};for(let a of rf)a!=="domains"&&RR(t,r,a)&&(t[a]===void 0?delete i[a]:__(i,t,a));let n=OR(e.known.domains,t,r);return n!==void 0?i.domains=n:delete i.domains,i}ts(_l,"mergeRootConfig");function $R(e,t,r={}){let i=Al(e);return i.kind==="unmergeable"?{kind:"unmergeable",reason:i.reason}:i.kind==="absent"?{kind:"ok",content:da(t)}:{kind:"ok",content:da(_l(i.disk,t,r))}}ts($R,"mergeRootConfigContent");var _W=Object.defineProperty,xW=(e,t)=>_W(e,"name",{value:t,configurable:!0}),TW=10;var CW=c.object({activeTarget:c.string().optional()}),af=class e{static{xW(this,"Config")}rootConfig;configPath=null;loadFailed=!1;parseDegraded=!1;loadedSnapshot={};searchStartDir;constructor(t,r){this.rootConfig=t??{},this.configPath=r??null}static findConfigDirectory(t){let r=t!==void 0&&t!==""?t:process.cwd();for(let i=0;i<TW;i++){let n=kt.join(r,"fjall"),a=kt.join(n,On);if(Oe.existsSync(a))return n;let o=kt.join(r,On);if(Oe.existsSync(o))return r;let s=kt.dirname(r);if(s===r)break;r=s}return null}static loadConfigFile(t){try{return Oe.accessSync(t,Oe.constants.R_OK),Oe.readFileSync(t,{encoding:"utf8"})}catch(r){return ua.warn("Config",`Config file at ${t} could not be read; using defaults`,{file:t,error:le(ze(r))}),null}}static loadConfig(t){let r=e.findConfigDirectory(t);if(!r){let l=new e;return l.searchStartDir=t,l}let i=kt.join(r,On),n=e.loadConfigFile(i);if(n===null){let l=new e(void 0,i);return l.searchStartDir=t,l.loadFailed=!0,l}let a,o=!1;if(n!==""){let l;try{l=JSON.parse(n)}catch(d){throw e.formatZodError(d,On)}let m=tf.safeParse(l);if(m.success)a=m.data;else{let d=El.safeParse(l);a=d.success?d.data:{},o=!d.success,d.success?ua.warn("Config","fjall-config.json contains keys this version does not recognise (only activeTarget, domains, capacityIdentity and organisation are read). They were most likely written by a newer fjall version \u2014 leave them in place; saves preserve them verbatim.",{file:i}):ua.warn("Config","fjall-config.json has a malformed activeTarget, domains or capacityIdentity value, so its contents were ignored for this run \u2014 any capacity-identity pins it holds will NOT apply (a pinned stack deploys unpinned and is blocked by the rename gate). Fix the file by hand; do NOT regenerate it, which would discard the pins.",{file:i})}}let s=new e(a,i);return s.searchStartDir=t,s.parseDegraded=o,s.loadedSnapshot=structuredClone(s.rootConfig),s}static formatZodError(t,r){if(t instanceof c.ZodError&&t.issues.length>0){let n=t.issues.map(a=>`${a.path.join(".")}: ${a.message}`).join("; ");return new Error(`Failed to parse ${r}: ${n}`)}let i=(t instanceof Error?t.message:String(t)).replace(/\n/g," ").substring(0,500);return new Error(`Failed to parse ${r}: ${i}`)}saveConfig(){let t=kt.join(this.resolveProjectDirectory()??kt.join(this.searchStartDir??process.cwd(),"fjall"),On);if(this.loadFailed)return nn(new Error(`Refusing to save ${t}: the file exists but could not be read when this config loaded, so saving would replace its contents with state that never included them. Fix the file permissions (e.g. chmod u+rw ${t}) and retry.`));let r=kt.dirname(t);try{Oe.mkdirSync(r,{recursive:!0})}catch(s){return nn(new Error(`Cannot create config directory ${r}: ${le(ze(s))}`))}let i=e.assertWritable(t,r);if(!i.success)return i;let n=this.mergeWithDisk(t);if(!n.success)return n;let a=da(n.data),o=`${t}.tmp-${process.pid}`;try{Oe.writeFileSync(o,a,{mode:384}),Oe.renameSync(o,t)}catch(s){return nn(new Error(`Failed to save ${t}: ${le(ze(s))}`))}return this.configPath=t,ca(void 0)}static assertWritable(t,r){if(Oe.existsSync(t))try{Oe.accessSync(t,Oe.constants.W_OK)}catch{return nn(new Error(`Cannot save ${t}: the file is read-only. Make it writable (e.g. chmod u+w ${t}) and retry.`))}try{Oe.accessSync(r,Oe.constants.W_OK)}catch{return nn(new Error(`Cannot save ${t}: the directory ${r} is not writable. Make it writable (e.g. chmod u+w ${r}) and retry.`))}return ca(void 0)}mergeWithDisk(t){let r=e.readDiskConfigForMerge(t);return r.kind==="unmergeable"?nn(new Error(`Refusing to save ${t}: ${r.reason}. Writing now would keep only this session's state and drop everything else the file carries (including keys written by other fjall versions). Fix or remove the file and retry.`)):r.kind==="absent"?ca(this.rootConfig):ca(_l(r.disk,this.rootConfig,this.loadedSnapshot))}static readDiskConfigForMerge(t){if(!Oe.existsSync(t))return{kind:"absent"};let r;try{r=Oe.readFileSync(t,{encoding:"utf8"})}catch(i){return{kind:"unmergeable",reason:`the existing file could not be read or parsed as JSON (${le(ze(i))})`}}return Al(r)}static getConfigDirectory(t){return e.findConfigDirectory(t)}getConfigPath(){return this.configPath}isContentUnavailable(){return this.loadFailed||this.parseDegraded}static warnedLegacyActiveTarget=!1;localConfigCache;resolveProjectDirectory(){return this.configPath!==null?kt.dirname(this.configPath):e.findConfigDirectory(this.searchStartDir)}localConfigFile(){let t=this.resolveProjectDirectory();return t===null?null:kt.join(t,bi,sl)}loadLocalConfig(){if(this.localConfigCache===void 0){let t=this.localConfigFile();if(t===null)return this.localConfigCache={};try{let r=Oe.readFileSync(t,{encoding:"utf8"}),i=CW.safeParse(JSON.parse(r));this.localConfigCache=i.success?i.data:{}}catch{this.localConfigCache={}}}return this.localConfigCache}writeLocalConfig(t){let r=this.localConfigFile();if(r===null)return nn(new Error("Cannot persist local state: no fjall-config.json was found from this directory, so there is no project to anchor `.fjall/local.json` to. Run this from inside a fjall project, or run `fjall create account` / `fjall create app` first."));try{Oe.mkdirSync(kt.dirname(r),{recursive:!0});let i=`${r}.tmp-${process.pid}`;Oe.writeFileSync(i,JSON.stringify(t,null,2)+`
299
- `,{encoding:"utf8"}),Oe.renameSync(i,r),Um(kt.dirname(kt.dirname(r)),[Lm,...cl],{header:JA,marker:JP})}catch(i){return nn(new Error(`Failed to write ${r}: ${le(ze(i))}`))}return this.localConfigCache=t,ca(void 0)}static warnLegacyActiveTargetOnce(){e.warnedLegacyActiveTarget||(e.warnedLegacyActiveTarget=!0,ua.warn("Config","`activeTarget` in fjall-config.json is deprecated and ignored: a committed target must never re-aim a deploy or CI pipeline. Run `fjall target set <name>` to store it locally in .fjall/local.json, then remove `activeTarget` from the committed fjall-config.json."))}getActiveTarget(){let t=this.loadLocalConfig().activeTarget;if(t!==void 0)return t;this.rootConfig.activeTarget!==void 0&&e.warnLegacyActiveTargetOnce()}setActiveTarget(t){let r=this.loadLocalConfig();return r.activeTarget=t,this.writeLocalConfig(r)}clearActiveTarget(){let t=this.loadLocalConfig();return delete t.activeTarget,this.writeLocalConfig(t)}getDomains(){return this.rootConfig.domains??[]}setDomains(t){this.rootConfig.domains=t}addDomain(t){this.rootConfig.domains||(this.rootConfig.domains=[]),this.rootConfig.domains.push(t)}getDomain(t){return this.rootConfig.domains?.find(r=>r.name.toLowerCase()===t.toLowerCase())}removeDomain(t){if(!this.rootConfig.domains)return!1;let r=this.rootConfig.domains.findIndex(i=>i.name.toLowerCase()===t.toLowerCase());return r===-1?!1:(this.rootConfig.domains.splice(r,1),!0)}getOrganisation(){return this.rootConfig.organisation}setOrganisation(t){this.rootConfig.organisation=t}clearOrganisation(){delete this.rootConfig.organisation}};var IW=Object.defineProperty,_i=(e,t)=>IW(e,"name",{value:t,configurable:!0});function x_(e){let t;try{t=af.loadConfig(e)}catch(i){return{kind:"unreadable",reason:le(ze(i))}}if(t.isContentUnavailable())return{kind:"unreadable",reason:"fjall-config.json exists but its contents could not be loaded (the preceding warning names the problem)"};let r=t.getOrganisation();return r!==void 0?{kind:"bound",bound:r}:t.getConfigPath()===null?{kind:"no_project"}:{kind:"unbound"}}_i(x_,"readProjectBinding");function T_(e,t,r){switch(e.kind){case"unreadable":return e;case"no_project":return{kind:"unbound",projectFound:!1,identity:t};case"unbound":return{kind:"unbound",projectFound:!0,identity:t};case"bound":return t===null?{kind:"unverifiable",bound:e.bound,reason:r??"the organisation could not be resolved"}:e.bound.id===t.id?{kind:"matched",bound:e.bound}:{kind:"mismatched",bound:e.bound,actual:t}}}_i(T_,"resolveBindingVerdict");function jR(e,t={}){return T_(x_(t.startDir),e,t.unresolvedReason)}_i(jR,"checkProjectOrganisation");function pa(e){return e.name!==void 0&&e.name!==""?`${e.name} (${e.id})`:e.id}_i(pa,"describeOrganisation");function MR(e,t,r){return`Refusing to ${e}: this project's fjall-config.json records organisation ${pa(t)} as its home, but the credential in use belongs to ${pa(r)}. Nothing was created, synthesised or deployed. Cure: authenticate as ${pa(t)} ('fjall login', or set FJALL_API_KEY to a key for that organisation), or \u2014 if this project really is moving \u2014 run 'fjall org bind --org ${r.id} --force' to re-bind it.`}_i(MR,"buildWrongOrganisationMessage");function LR(e,t){return`Refusing to ${e}: ${t}, so this project's organisation binding cannot be checked. Nothing was created, synthesised or deployed. Cure: fix fjall-config.json (permissions or contents), then re-run.`}_i(LR,"buildUnreadableConfigMessage");function FR(e,t){return`Could not confirm which organisation your credential belongs to (${t}). Proceeding \u2014 this project is bound to ${pa(e)}, and a mismatch would not have been caught.`}_i(FR,"buildUnverifiableNotice");function UR(e){return`This project is not bound to an organisation. Run 'fjall org bind' to pin it to ${pa(e)} \u2014 afterwards, any command run here with another organisation's credential is refused instead of silently landing there.`}_i(UR,"buildUnboundNotice");import{createHash as kW}from"node:crypto";var DW=Object.defineProperty,NW=(e,t)=>DW(e,"name",{value:t,configurable:!0});function zR(e,t){return kW("sha256").update(`${e}${t}`).digest("hex")}NW(zR,"credentialFingerprint");import*as sf from"node:fs";var wW=Object.defineProperty,of=(e,t)=>wW(e,"name",{value:t,configurable:!0}),BR="org-config-cache.json";function C_(){return Go(BR)}of(C_,"orgConfigCachePath");function I_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}of(I_,"isObject");function D_(e){return I_(e)&&typeof e.organisationId=="string"&&e.organisationId!==""&&typeof e.organisationName=="string"}of(D_,"isCachedCredentialIdentity");function GR(e){try{let t=C_();if(!sf.existsSync(t))return null;let r=JSON.parse(sf.readFileSync(t,"utf-8"));return!I_(r)||r.credentialFingerprint!==e?null:D_(r.identity)?r.identity:null}catch(t){return ua.debug("cachedCredentialIdentity","Cache read failed, treating as a miss",{error:le(ze(t))}),null}}of(GR,"readCachedCredentialIdentity");var PW=Object.defineProperty,RW=(e,t)=>PW(e,"name",{value:t,configurable:!0}),VR="https://fjall.io";function cf(){let e=process.env.FJALL_API_URL;return e!==void 0&&e!==""?e:VR}RW(cf,"resolveApiBaseUrl");var WR={name:"@fjall/cli",version:"29.0.0",repository:{type:"git",url:"git+https://github.com/fjall-tech/fjall.git",directory:"cli"},description:"Fjall CLI helper",private:!0,type:"module",bin:{fjall:"dist/src/cli.js"},files:["dist/"],scripts:{clean:"rm -rf ./dist ./dist.next ./sourcemaps","clean:node":"rm -rf ./node_modules","copy-files":'DEST="${DEST:-dist}"; find generators -type d -name files | while read dir; do mkdir -p "$DEST/$dir" && cp -R "$dir/." "$DEST/$dir/"; done && cp -R src/proto "./$DEST/src/proto"',build:"rm -rf ./dist.next ./sourcemaps && npx tsc --outDir dist.next && DEST=dist.next npm run copy-files && node ../scripts/minify-dist.mjs dist.next && chmod +x ./dist.next/src/cli.js && rm -rf ./dist && mv ./dist.next ./dist && node ../scripts/stamp-build.mjs",watch:"npm run build && npx tsc-watch","watch:only":'npx tsc-watch --onSuccess "npm run copy-files"',"fjall-cli":"node ./dist/src/cli.js",version:"npx tsx scripts/updateTemplateVersions.ts && node ../scripts/sync-ci-plugin-major.mjs",format:'prettier --write "src/**/*.{ts,tsx,js,jsx,json}" "generators/**/*.{ts,tsx,js,jsx,json}"',"format:check":'prettier --check "src/**/*.{ts,tsx,js,jsx,json}" "generators/**/*.{ts,tsx,js,jsx,json}"',lint:"eslint src/ generators/","lint:fix":"eslint src/ generators/ --fix",typecheck:"tsc --noEmit","typecheck:tests":"tsc --noEmit --project tsconfig.test.json","typecheck:scripts":"tsc --noEmit --project tsconfig.scripts.json","typecheck:all":"npm run typecheck && npm run typecheck:tests && npm run typecheck:scripts",test:"vitest run","test:watch":"vitest","test:coverage":"vitest run --coverage","test:integration":"vitest run --config vitest.config.integration.ts","test:integration:watch":"vitest --config vitest.config.integration.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","test:all":"npm run test && npm run test:integration && npm run test:e2e","test:setup":"node scripts/setupTestFixtures.mjs","test:payload-compat":"npx tsx scripts/testPayloadCompatibility.ts","test:payload-compat:e2e":"npx tsx scripts/testPayloadCompatibility.ts --e2e"},engines:{node:">=22.0.0"},author:"",license:"SEE LICENSE IN LICENSE",devDependencies:{"@eslint/js":"^10.0.1","@playwright/test":"^1.62.0","@testing-library/dom":"^10.4.1","@testing-library/react":"^16.3.2","@types/ejs":"^3.1.5","@types/prompts":"^2.4.9","@types/proper-lockfile":"^4.1.4","@types/react":"^19.2.17","@typescript-eslint/parser":"^8.65.0","@vitest/coverage-v8":"^4.1.10","aws-cdk-lib":"^2.265.0",constructs:"^10.7.2",eslint:"^10.8.0","ink-testing-library":"^4.0.0",jsdom:"^30.0.1",prettier:"^3.9.6","react-dom":"^19.2.8","strip-ansi":"^6.0.1","tsc-watch":"^7.2.1",tsx:"^4.23.1","typescript-eslint":"^8.65.0",vitest:"4.1.10"},dependencies:{"@anthropic-ai/sdk":"^0.115.0","@aws-sdk/client-acm":"^3.1098.0","@aws-sdk/client-auto-scaling":"^3.1098.0","@aws-sdk/client-backup":"^3.1098.0","@aws-sdk/client-cloudformation":"^3.1098.0","@aws-sdk/client-cost-explorer":"^3.1098.0","@aws-sdk/client-ec2":"^3.1098.0","@aws-sdk/client-ecr":"^3.1098.0","@aws-sdk/client-ecs":"^3.1098.0","@aws-sdk/client-elasticache":"^3.1098.0","@aws-sdk/client-iam":"^3.1098.0","@aws-sdk/client-identitystore":"^3.1098.0","@aws-sdk/client-lambda":"^3.1098.0","@aws-sdk/client-organizations":"^3.1098.0","@aws-sdk/client-ram":"^3.1098.0","@aws-sdk/client-rds":"^3.1098.0","@aws-sdk/client-route-53":"^3.1098.0","@aws-sdk/client-s3":"^3.1098.0","@aws-sdk/client-secrets-manager":"^3.1098.0","@aws-sdk/client-ssm":"^3.1098.0","@aws-sdk/client-sso":"^3.1098.0","@aws-sdk/client-sso-admin":"^3.1098.0","@aws-sdk/client-sso-oidc":"^3.1098.0","@aws-sdk/client-sts":"^3.1098.0","@fjall/deploy-core":"^29.0.0","@fjall/generator":"^29.0.0","@fjall/util":"^29.0.0","@nx/devkit":"^23.1.0","@opennextjs/aws":"^4.1.0","@smithy/node-http-handler":"^4.9.13","@toon-format/toon":"^4.1.0","aws-cdk":"^2.1134.0",axios:"^1.19.0",chalk:"^6.0.0","cli-cursor":"^5.0.0",commander:"^15.0.0",ejs:"^6.0.1",ink:"^7.1.1","js-yaml":"^5.2.2",open:"^11.0.0",ora:"^9.4.1",prompts:"^2.4.2","proper-lockfile":"^4.1.2",protobufjs:"^8.7.1",react:"^19.2.8",typescript:"^6.0.3","update-check":"^1.5.4",zod:"^4.4.3"}};var $W=Object.defineProperty,jW=(e,t)=>$W(e,"name",{value:t,configurable:!0}),ase=`fjall-cli/${WR.version} node/${process.versions.node} ${MW()}/${LW()}`;var KR=cf(),ose=c.looseObject({deviceCode:c.string(),userCode:c.string(),verificationUri:c.string(),expiresIn:c.number(),interval:c.number()}),sse=c.looseObject({status:c.string(),apiKey:c.string().optional(),organisationId:c.string().optional(),organisationName:c.string().optional(),email:c.string().optional()}),cse=c.looseObject({application:c.looseObject({id:c.string()})}),N_=c.looseObject({id:c.string(),name:c.string(),vpcCidr:c.string().nullable(),connectedAwsAccountId:c.string().nullable()}),lse=c.looseObject({applications:c.array(N_),nextCursor:c.string().optional()}),use=c.looseObject({application:N_}),dse=c.looseObject({applications:c.array(N_)}),pse=c.looseObject({application:c.looseObject({id:c.string(),name:c.string()})}),mse=c.looseObject({primaryRegion:c.string().nullish(),secondaryRegions:c.array(c.string()).optional(),disasterRecoveryRegion:c.string().nullish(),providerAccounts:c.custom(e=>Array.isArray(e)),ssoSessions:c.record(c.string(),c.looseObject({ssoRegion:c.string(),ssoStartUrl:c.string()})).optional(),rootOidcRoleArn:c.string().nullish(),allowCodemodLlmFallback:c.boolean().optional(),rootAccessManagement:c.custom(e=>typeof e=="string").optional(),requireTrackedDeploys:c.boolean().optional().catch(void 0)}),fse=c.looseObject({id:c.string(),token:c.string(),tokenPrefix:c.string(),name:c.string(),scopes:c.array(c.string())}),FW=c.looseObject({id:c.string(),name:c.string(),tokenPrefix:c.string(),scopes:c.array(c.string()),resourceConstraints:c.record(c.string(),c.unknown()),sourceTag:c.string().nullable(),expiresAt:c.string(),createdAt:c.string(),revokedAt:c.string().nullable(),revokedReason:c.string().nullable(),lastUsedAt:c.string().nullable(),usageCount:c.number(),deniedCount:c.number()}),hse=c.looseObject({tokens:c.array(FW)}),gse=c.looseObject({scopes:c.array(c.string()),expiresAt:c.string().optional()}),UW=c.looseObject({id:c.string(),awsAccountId:c.string(),accountName:c.string().nullable(),environment:c.string().nullable()}),yse=c.looseObject({accounts:c.array(UW)}),zW=c.looseObject({id:c.string(),assetIdentifier:c.string(),name:c.string(),type:c.string(),status:c.string(),region:c.string().nullish(),_count:c.looseObject({complianceIssues:c.number()}).optional()}),BW=c.looseObject({id:c.string(),name:c.string(),assetIdentifier:c.string(),provider:c.string(),type:c.string(),status:c.string(),region:c.string().nullish(),iacStatus:c.string().nullish(),accountId:c.string().nullish(),estimatedMonthlyCost:c.string().nullish(),lastSeenAt:c.string().nullish(),createdAt:c.string().nullish(),updatedAt:c.string().nullish()}),vse=c.looseObject({assets:c.array(zW),nextCursor:c.string().optional()}),Sse=c.looseObject({asset:BW}),GW=c.looseObject({id:c.string(),ruleId:c.string(),title:c.string(),severity:c.string(),status:c.string()}),bse=c.looseObject({issues:c.array(GW)}),Ese=c.record(c.string(),c.unknown()),Ase=c.union([c.array(c.record(c.string(),c.unknown())),c.record(c.string(),c.unknown())]),_se=c.record(c.string(),c.unknown()),xse=c.record(c.string(),c.unknown()),Tse=c.record(c.string(),c.unknown()),Cse=c.record(c.string(),c.unknown()),Ise=c.looseObject({deployment:c.looseObject({id:c.string()}),minCliVersion:c.string().optional()});var VW=c.object({id:c.string(),releaseNumber:c.number().int(),status:c.string(),commitSha:c.string().nullable(),branch:c.string().nullable(),createdAt:c.string(),assemblyDigest:c.string().nullable(),createdByDeploymentId:c.string().nullable(),rollbackOfReleaseId:c.string().nullable(),services:c.array(Rm.strip())}),Dse=c.object({releases:c.array(VW),currentReleaseId:c.string().nullable(),nextCursor:c.number().int().optional()}),WW=c.object({id:c.string(),status:c.string(),target:c.string().nullish(),applicationId:c.string().nullish(),applicationName:c.string().nullish(),connectedAwsAccountId:c.string().nullish(),source:c.string().nullish(),startedAt:c.string().nullish(),triggeredByName:c.string().nullish(),machineLabel:c.string().nullish()}),Nse=c.object({deployments:c.array(WW)}),kse=c.object({cancelled:c.boolean(),message:c.string().nullish(),declined:c.boolean().nullish()}),wse=c.object({released:c.literal(!0),id:c.string().nullish()}),Pse=c.looseObject({organisationId:c.string(),organisationName:c.string(),organisationSlug:c.string().min(1).optional()}),Rse=c.looseObject({status:c.string(),roleArn:c.string().optional(),accountId:c.string().optional(),phase:c.string().optional(),reason:c.string().optional()}),Ose=c.looseObject({token:c.string()}),KW=c.looseObject({quickCreateUrl:c.string(),externalId:c.string()}),ZW=c.looseObject({alreadyConnected:c.literal(!0),account:c.looseObject({awsAccountId:c.string(),accountName:c.string().nullable(),status:c.string()})}),$se=c.union([ZW,KW]);function HW(e){return"alreadyConnected"in e&&e.alreadyConnected===!0}jW(HW,"isAlreadyConnected");var jse=c.looseObject({registered:c.boolean(),repository:c.looseObject({id:c.string()}).optional()});var JW=Object.defineProperty,XW=(e,t)=>JW(e,"name",{value:t,configurable:!0});function xl(e=KR){return`Deploy tokens are minted from a signed-in browser session by an owner or admin: open ${e}/settings/ci (Settings \u2192 CI/CD Tokens).`}XW(xl,"deployTokenMintGuidance");var ZR=[{command:"ci status",match:N.success,templates:["Run `fjall ci verify` to check the rest of the wiring \u2014 an active deploy token is necessary, not sufficient","Run `fjall ci token list` to see which applications, environments and accounts each active token may deploy to"]},{command:"ci status",match:N.empty,templates:[xl(),"Run `fjall ci setup --plan --app <app>` to learn where the workflow file will go and which secret name it will read (`workflowPath`, `secretName`) \u2014 the two things needed to stage the secret before minting. `--plan` mints nothing and writes nothing, and the workflow BODY is printed on the human surface only: it is not a field of the agent payload"]},{command:"ci token list",match:N.success,templates:["Run `fjall token show <id>` to inspect one token's stored constraints","Run `fjall ci token revoke <id> --reason <text>` to revoke a listed token"]},{command:"ci token list",match:N.empty,templates:[xl(),"Run `fjall ci status` to re-check readiness once a token exists"]},{command:"ci token revoke",match:N.success,templates:["Run `fjall ci token list` to confirm the token now lists as revoked \u2014 a revoked token stays listed, it does not disappear",`Any CI job still holding this token now fails to authenticate. ${xl()}`]}];var lf="Do not retry or vary flags: `supported: false` is the server's capability verdict, not an input error \u2014 every invocation answers the same until the Fjall server is updated to a version that ships this API (the `message` field names the upgrade)",HR=[{command:"deployments list",match:N.unsupported,templates:[lf]},{command:"deployments cancel",match:N.unsupported,templates:[lf]},{command:"deployments force-release",match:N.unsupported,templates:[lf]},{command:"dev list",match:N.unsupported,templates:[lf]},{command:"deployments list",match:N.success,templates:["Run `fjall deployments cancel <id>` to request co-operative cancellation of a listed deployment","Run `fjall deploy logs --deployment-id <id>` to read one deployment's logs"]},{command:"deployments cancel",match:N.success,templates:["Run `fjall deployments list` to confirm whether the slot is free, and read `cancelled` and `declined` before assuming it is: `cancelled: false` means the request was refused, `declined: true` is an already-terminal reject, and a plain granted cancel is co-operative \u2014 the deployment has to acknowledge it","Run `fjall deployments force-release <id> --confirm <id>` to clear a slot that stays occupied (organisation admin, audited \u2014 retype the id in `--confirm`)"]},{command:"deployments force-release",match:N.success,templates:["Run `fjall deployments list` to confirm the slot is free","Run `fjall deploy <app>` to retry the deployment the wedged slot was blocking"]},{command:"dev up",match:N.success,templates:["Run `fjall dev list <app>` to see every slot for this app with its `host` \u2014 rows carry `host`, not a full URL, and it is empty until the slot leaves `creating`","Run `fjall dev down <app> --branch <branch>` to tear this slot down"]},{command:"dev list",match:N.success,templates:["Run `fjall dev down <app> --branch <branch>` to tear one listed slot down \u2014 every row carries the `branch` to name here","Run `fjall dev up <app> --branch <branch>` to bring another branch up"]},{command:"dev down",match:N.success,templates:["Run `fjall dev list <app>` to see which slots remain","Run `fjall dev up <app> --branch <branch>` to bring the branch back up"]},{command:"dev substrate down",match:N.success,templates:["Run `fjall dev list <app>` to confirm no slot survives \u2014 the substrate will not tear down under live slots, and `--force` takes them with it","Any `residuals` row survives the teardown and can still cost: its `cleanupHint` names the manual step"]}];var JR=["Run `fjall domain deploy <name>` to deploy the domain","Run `fjall domain verify <name>` to check DNS delegation once it is deployed","Run `fjall domain export <name>` to export the live zone records"],XR=[{command:"org deploy",match:N.success,templates:["Run `fjall org get` to review the deployed organisation topology and accounts",`Run \`${te.accountDeploy}\` to deploy the account tier if you passed \`--no-cascade\``,`Run \`${te.createApplicationAgent} --name "<name>"\` to create an application to deploy into it`]},{command:"org deploy",match:N.error,templates:["Run `fjall org get` to see which tier of the cascade is already deployed",`Run \`${te.organisationDeploy} --no-cascade\` to retry the organisation stack alone`]},{command:"platform deploy",match:N.success,templates:[`Run \`${te.accountDeploy}\` to deploy the account tier on top of it`]},{command:"platform deploy",match:N.error,templates:["Run `fjall org get` to check the organisation tier is deployed first"]},{command:"account deploy",match:N.success,templates:["Run `fjall apps list` to see which applications are registered","Run `fjall deploy <application>` to deploy one into this account"]},{command:"account deploy",match:N.error,templates:["Run `fjall org get` to confirm the account is registered in the organisation",`Run \`${te.accountDeploy} --target <target>\` to select a specific member account`]},{command:"domain list",match:N.success,templates:["Run `fjall domain verify <name>` to check DNS delegation","Run `fjall domain export <name>` to export zone file","Run `fjall create domain --name <name>` to create a new domain"]},{command:"domain list",match:N.empty,templates:['Run `fjall create domain --name "<name>"` to create a domain',"Run `fjall domain import <name>` to import from Route53"]},{command:"domain verify",match:N.success,templates:["Run `fjall domain export <name>` to export zone file","Run `fjall domain deploy <name>` to deploy domain infrastructure"]},{command:"domain verify",match:N.error,templates:["Run `fjall domain verify <name>` to retry","Run `fjall domain list` to see existing domains"]},{command:"domain export",match:N.success,templates:["Run `fjall domain verify <name>` to check delegation","Run `fjall domain import <name>` to re-import from Route53"]},{command:"domain import",match:N.success,templates:["Run `fjall domain verify <name>` to check delegation","Run `fjall domain export <name>` to see the zone file","Run `fjall domain deploy <name>` to deploy domain infrastructure"]},{command:"domain import",match:N.error,templates:["Run `fjall domain import --hosted-zone-id <id>` to import by zone ID","Run `fjall domain list` to see existing domains"]},{command:"domain records list",match:N.success,templates:["Run `fjall domain sync <domain>` for the full zone-hygiene report","Run `fjall domain sync <domain> --fix` to remediate residue records via the destruction ceremony"]},{command:"domain records list",match:N.empty,templates:["Run `fjall domain deploy <domain>` to deploy the domain's declared records","Run `fjall domain list` to see existing domains"]},{command:"domain records list",match:N.error,templates:["Run `fjall domain records list <domain> --hosted-zone-id <id>` when the zone is not resolvable by name",`Run \`${te.connect}\` if AWS credentials are missing`]},{command:"domain sync",match:N.success,templates:["Run `fjall domain sync <domain> --fix` to remediate residue records (ceremony-gated)","Run `fjall domain records list <domain>` to see every record with its owner"]},{command:"domain sync",match:N.error,templates:["Run `fjall domain sync <domain> --hosted-zone-id <id>` when the zone is not resolvable by name","Run `fjall domain list` to see existing domains"]},{command:"domain delegate",match:N.success,templates:["Run `fjall domain verify <domain>` to confirm public DNS resolution","Run `fjall domain deploy <domain>` to continue a two-phase deploy after delegation"]},{command:"domain delegate",match:N.error,templates:["Run `fjall domain deploy <parent-domain>` so the parent publishes its DelegationRole","Run `fjall domain verify <domain> --show-delegation` for registrar instructions"]},{command:"domain destroy",match:N.success,templates:["Run `fjall domain list` to see remaining domains","Run `fjall domain sync <parent-domain>` to confirm no delegation residue remains"]},{command:"domain destroy",match:N.error,templates:["Run `fjall domain destroy <domain> --remediate '<name>'=recreate` with the exact consent the ticket names","Run `fjall domain list` to see existing domains"]},{command:"domain deploy",match:N.success,templates:["Run `fjall domain verify <domain>` to check DNS propagation","Run `fjall domain delegate <domain>` to write the NS delegation for a delegated child"]},{command:"domain deploy",match:N.error,templates:["Run `fjall domain deploy <domain>` to resume \u2014 the zone phase is retained and skipped on re-run","Run `fjall domain verify <domain> --show-delegation` for registrar delegation instructions"]},{command:"domain eject",match:N.success,templates:["Review the ejected infrastructure.ts \u2014 it is now vanilla CDK owned by you","Run `fjall domain list` to see remaining managed domains"]},{command:"create domain",match:N.success,templates:JR},{command:"domain create",match:N.success,templates:JR},{command:"create domain",match:N.error,templates:["Run `fjall domain list` to see existing domains",'Run `fjall create domain --name "<name>"` to retry with a different name']},{command:"create account",match:N.success,templates:[`Run \`${te.connect} --environment production\` to link your AWS account`,`Run \`${te.accountDeploy}\` to deploy account infrastructure (after connecting)`]},{command:"create account",match:N.error,templates:[`Run \`${te.createAccount} --primary-region <region>\` to retry`,`Run \`${te.createAccount} --help\` for usage information`]},{command:"create org",match:N.success,templates:[`Run \`${te.connect} --name "<account-name>" --region <region>\` to link the AWS Organizations management account \u2014 omit \`--environment\` so it registers at the organisation tier`,`Run \`${te.organisationDeploy}\` to deploy all infrastructure (after connecting)`]},{command:"create org",match:N.error,templates:[`Run \`${te.createOrganisation} --email "<email>"\` to retry (add \`--name "<name>"\` only for a brand-new organisation)`,`Run \`${te.createOrganisation} --help\` for all options`]},{command:"restore",match:N.successDryRun,templates:["Run `fjall restore <resourceType> --recovery-point <recoveryPointArn> --yes` to initiate restore","Run `fjall apps list` to see existing applications"]},{command:"restore",match:N.success,templates:["Open the AWS Console URL above to monitor restore progress","Run `fjall import` to import the restored resource after completion"]},{command:"restore",match:N.errorWithCode("NOT_FOUND"),templates:["Verify the recovery point ARN is correct and exists in the current region","Run `fjall restore <resourceType> --recovery-point <arn>` to retry"]},{command:"restore",match:N.errorWithCode("FORBIDDEN"),templates:["Ensure the IAM role has backup:StartRestoreJob and iam:PassRole permissions","Run `fjall restore` interactively to configure with guided setup"]},{command:"import",match:N.successDryRun,templates:["Run `fjall import --app <app> --resource-id <resourceId> --yes` to import a specific resource","Run `fjall import --app <app> --yes` to import all discovered resources"]},{command:"import",match:N.success,templates:["Run `fjall deploy <app>` to deploy with the imported resource","Run `fjall apps describe <app>` to see updated resources"]},{command:"import",match:N.errorWithCode("NOT_FOUND"),templates:[`Run \`${te.createApplicationAgent} --name "<app>"\` to create the application`,"Run `fjall apps list` to see existing applications"]},{command:"import",match:N.errorWithCode("VALIDATION_ERROR"),templates:["Run `fjall import --app <app> --resource-id <resourceId>` to import a specific resource","Run `fjall import --app <app> --resource-id <resourceId> --yes` to import immediately"]},{command:"aws exec",match:N.success,templates:["Run `fjall aws exec -- <command...>` to run another AWS CLI command","Run `fjall status` to check application health"]},{command:"aws exec",match:N.error,templates:["Retry the command \u2014 OIDC token mints can fail transiently",`Run \`${te.login}\` if the retry also fails with an authentication error`]},{command:"unlock bucket",match:N.success,templates:["Re-put sane bucket policy statements (enforceSSL deny, access grants) \u2014 the unlock deleted the ENTIRE policy","Run `fjall destroy <app>` to retry the blocked stack cleanup"]},{command:"unlock bucket",match:N.error,templates:["Ensure your credentials belong to the organisation's management account \u2014 STS AssumeRoot is rejected elsewhere","Run `fjall unlock bucket <name> --account <id> --acknowledge-root-session` to retry"]}];var qW=Object.defineProperty,eO=(e,t)=>qW(e,"name",{value:t,configurable:!0}),qR="Run `fjall connect status` to check that an AWS account is connected: asset discovery only inventories connected accounts, so an organisation with none has nothing to inventory",YR=["Run `fjall assets show <asset>` to read one asset in full \u2014 pass its `assetIdentifier`","Run `fjall assets compliance <asset>` to list an asset's recorded posture issues \u2014 pass its `assetIdentifier`, the address every server version accepts"],QR=eO(e=>e.outcome==="success"&&e.nextCursor!==void 0,"isTruncatedPage"),tO=[{command:"assets list",match:eO(e=>QR(e)&&e.fields!==void 0&&e.fields!=="","match"),templates:["This window is truncated \u2014 more assets exist beyond these rows. Run `fjall assets list --cursor <nextCursor> --fields <fields>` to fetch the next page with the same projection; `total` counts this window only, and `fjall assets summary` reports the estate-wide tally, split active/deleted",...YR]},{command:"assets list",match:QR,templates:["This window is truncated \u2014 more assets exist beyond these rows. Run `fjall assets list --cursor <nextCursor>` to fetch the next page; `total` counts this window only, and `fjall assets summary` reports the estate-wide tally, split active/deleted",...YR]},{command:"assets list",match:N.success,templates:["The `total` aggregate counts the rows in this response, not the estate: `--take` bounds the window (default 50). No `nextCursor` aggregate here means the estate ends with these rows; `fjall assets summary` reports the estate-wide tally, split active/deleted","Run `fjall assets show <asset>` to read one asset in full","Run `fjall assets compliance <asset>` to list an asset's recorded posture issues \u2014 pass its `assetIdentifier`, the address every server version accepts (row `id`s are only accepted by newer servers)"]},{command:"assets list",match:N.empty,templates:["Run `fjall assets list --status deleted` to include assets discovery has since marked deleted \u2014 the default listing hides them",qR]},{command:"assets show",match:N.success,templates:["Run `fjall assets compliance <asset>` to list the posture issues recorded against this asset","Run `fjall assets show <asset> --fields id,accountId,iacStatus,estimatedMonthlyCost,lastSeenAt` to read the fields the default projection omits"]},{command:"assets compliance",match:N.success,templates:["Read the `status` column before acting: this listing returns every issue recorded against the asset, `resolved` and `suppressed` included, where the `openIssues` count on `fjall assets list` counts only the open ones","Run `fjall compliance fix --domain compliance --issue-id <issueId>` to read this issue in full alongside the organisation's other open issues. `--domain` is the producer's category \u2014 one of `compliance`, `cost`, `performance` \u2014 not a framework name, and the response is context to reason from, not a remediation step: use `--execute` to run one","Run `fjall assets show <asset>` to read the asset these issues were raised against"]},{command:"assets compliance",match:N.empty,templates:["No issue of ANY status has been recorded against this asset \u2014 an empty listing here is not the same as issues that were resolved, which would still appear with `status: resolved`","Run `fjall assets list --fields name,assetIdentifier,openIssues` to find the assets that do carry open issues"]},{command:"assets summary",match:N.success,templates:["Run `fjall assets list --fields name,assetIdentifier,openIssues` to see which assets sit behind `withIssues` \u2014 `withIssues` counts the assets carrying at least one open issue, `openIssues` counts those issues per asset","Run `fjall assets list --take <n>` to read the rows behind these totals \u2014 page onwards with `--cursor` when the listing reports a `nextCursor`, and pass `--status deleted` to include the `deleted` rows in the listing (interleaved with active \u2014 read the `status` column). These totals are estate-wide (the summary pages the listing to exhaustion, deleted assets included): `total` counts the whole estate, `active` and `deleted` split it"]},{command:"assets summary",match:N.empty,templates:[qR]},{command:"costs show",match:N.success,templates:["Run `fjall costs --mode forecast` to see forecasted spend","Run `fjall costs --mode breakdown` to see service-level breakdown"]},{command:"costs show",match:N.error,templates:["Run `fjall costs --app <app>` to filter by application","Run `fjall costs --help` for usage information"]},{command:"metrics show",match:N.success,templates:["Run `fjall metrics --mode latency` to see latency percentiles","Run `fjall metrics --mode errors` to see error trends"]},{command:"metrics show",match:N.error,templates:["Run `fjall metrics --app <app>` to filter by application","Run `fjall metrics --help` for usage information"]},{command:"compliance fix",match:N.success,templates:["Run `fjall compliance fix --domain <domain> --issue-id <id>` to narrow the suggestions to one issue","Run `fjall deploy <app>` to apply remediation changes"]},{command:"compliance fix",match:N.error,templates:["Run `fjall compliance fix --domain <domain>` to name the compliance domain","Run `fjall compliance --help` for usage information"]},{command:"compliance fix --execute",match:N.success,templates:["Read the result's `kind` before treating the issue as fixed: `auto-pr` opened a pull request that still has to be merged, `imperative` rewrote the live policy, and `manual-hint` changed nothing \u2014 its `awsCliHint` carries the manual step, and that field is absent for rules that supply no hint (`message` is a fixed string either way)","Do not re-read the issue to confirm the cure: nothing on the remediation path writes to the issue record, so `status` stays `open` until the next discovery scan re-evaluates the asset. Verify at the thing that changed \u2014 the pull request, or the live resource","Run `fjall deploy <app>` to roll out an `auto-pr` remediation once its pull request is merged"]},{command:"deploy diff",match:N.success,templates:["Run `fjall deploy logs --deployment-id <id>` to analyse deployment logs","Run `fjall status <app>` to check current deployment health"]},{command:"deploy diff",match:N.error,templates:["Run `fjall list deployments` to see recent deployment IDs","Run `fjall deploy diff --help` for usage information"]},{command:"deploy logs",match:N.success,templates:["Run `fjall deploy diff <idA> <idB>` to compare two deployments","Run `fjall status <app>` to check current deployment health"]},{command:"deploy logs",match:N.error,templates:["Run `fjall deploy logs --deployment-id <id>` with a valid deployment ID","Run `fjall list deployments` to find a deployment ID"]}];var YW={command:"*",match:N.error,templates:["Run `fjall <command> --help` for usage information"]},rO=[...DR,...NR,...wR,...ZR,...HR,...XR,...tO,YW];var QW=Object.defineProperty,eK=(e,t)=>QW(e,"name",{value:t,configurable:!0}),nO=["app","environment","region","profile","target","cluster","service","lambda","status","type"],ma=["app","cluster","service","lambda"],tK=["status","type","region"],k_={deploy:["environment","region","target"],"deploy diff":[],"deploy logs":[],destroy:["target"],"org deploy":["target"],"org destroy":["target"],"platform deploy":["target"],"platform destroy":["target"],"account deploy":["target"],"account destroy":["target"],status:[],rollout:[],list:["app"],apps:["target"],connect:["environment","region"],"connect status":[],import:["app","region"],costs:["app"],metrics:["app"],compliance:["app"],"token create":["app","environment"],"unlock bucket":["region"],"aws exec":["app","region","target"],"secrets set":ma,"secrets get":ma,"secrets list":ma,"secrets delete":ma,"secrets export":ma,"secrets import":ma,"secrets exec":ma,"assets list":tK},rK=Math.max(...Object.keys(k_).map(e=>e.split(" ").length));function w_(e){let t=e.trim().split(/\s+/).slice(1);for(let r=rK;r>=1;r--){let i=t.slice(0,r).join(" ");if(Object.hasOwn(k_,i))return k_[i]}return[]}eK(w_,"resolvePreservableFlags");var nK=Object.defineProperty,df=(e,t)=>nK(e,"name",{value:t,configurable:!0});function P_(e){let t=e.replace(/[\u0000-\u001f\u007f`]/g,"");return/[^\w@%+=:,./-]/.test(t)?`'${t.replace(/'/g,"'\\''")}'`:t}df(P_,"shellEscape");function iO(e,t,r){let i=new Set,n=e.replace(/<(\w+)>/g,(a,o)=>{let s=t[o];return s===void 0||s===""?`<${o}>`:(i.add(o),o==="command"?s:P_(s))});return aO(n,r,i)}df(iO,"interpolateTemplate");var uf=class{static{df(this,"SuggestionResolver")}command;flags;constructor(t,r){this.command=t,this.flags=r}resolve(t){let r=rO.find(i=>(i.command===this.command||i.command==="*")&&i.match(t));return r===void 0?[]:r.templates.map(i=>iO(i,t,this.flags))}};function aO(e,t,r=new Set){let i=/`(fjall[^`]*)`/.exec(e),n=i?.[1];if(i===null||n===void 0)return e;let a=w_(n),o=[];for(let d of nO){if(!a.includes(d))continue;let h=t[d];h!==void 0&&h!==""&&!r.has(d)&&!n.includes(`--${d}`)&&o.push(`--${d} ${P_(h)}`)}if(o.length===0)return e;let s=` ${o.join(" ")}`,l=n.indexOf(" -- "),m=l===-1?`${n}${s}`:`${n.slice(0,l)}${s}${n.slice(l)}`;return e.slice(0,i.index)+`\`${m}\``+e.slice(i.index+i[0].length)}df(aO,"applyPreservedFlags");var iK=Object.defineProperty,Un=(e,t)=>iK(e,"name",{value:t,configurable:!0});function Gr(e,t){if(t!==void 0&&rs(e)){let i={};for(let[n,a]of Object.entries(e))i[n]=t.has(n)?a:Gr(a);return i}if(typeof e=="string")return le(e);if(e==null||typeof e!="object")return e;if(Array.isArray(e))return e.map(i=>Gr(i));if(e instanceof Date||e instanceof RegExp)return e;let r={};for(let[i,n]of Object.entries(e))r[i]=Gr(n);return r}Un(Gr,"maskTree");function pf(e){if(Array.isArray(e))return e.map(pf);if(!rs(e))return e;let t={};for(let[r,i]of Object.entries(e))i!==void 0&&(t[r]=pf(i));return t}Un(pf,"stripAbsent");function rs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof Date)&&!(e instanceof RegExp)}Un(rs,"isPlainRecord");function oO(e){let t=e?.verbatimFields;return t!==void 0&&t.length>0?new Set(t):void 0}Un(oO,"toVerbatimKeys");function sO(e,t){return t===void 0||!rs(e)?!1:Object.keys(e).some(r=>t.has(r))}Un(sO,"carriesVerbatimField");function cO(e,t){let r=e;for(let i of t.split(".")){if(!rs(r))return;r=r[i]}return r}Un(cO,"resolveDotPath");function lO(e,t,r){let i=e.project(t),n={};for(let a of r)a in i&&(n[a]=i[a]);return n}Un(lO,"projectSelectedFields");var Tl=class{static{Un(this,"AgentOutputWriter")}write;hasWrittenBlock=!1;resolver;flags;full;budget;requestedFields;constructor(t){this.write=t.writeFn??(r=>{process.stdout.write(r)}),this.resolver=new uf(t.command,t.flags),this.flags=t.flags,this.full=t.full??!1,this.budget=t.budget,this.requestedFields=t.fields??[]}get isFullOutput(){return this.full}writeBlock(t){t!==""&&(this.hasWrittenBlock&&this.write(n_+`
299
+ `,{encoding:"utf8"}),Oe.renameSync(i,r),Um(kt.dirname(kt.dirname(r)),[Lm,...cl],{header:JA,marker:JP})}catch(i){return nn(new Error(`Failed to write ${r}: ${le(ze(i))}`))}return this.localConfigCache=t,ca(void 0)}static warnLegacyActiveTargetOnce(){e.warnedLegacyActiveTarget||(e.warnedLegacyActiveTarget=!0,ua.warn("Config","`activeTarget` in fjall-config.json is deprecated and ignored: a committed target must never re-aim a deploy or CI pipeline. Run `fjall target set <name>` to store it locally in .fjall/local.json, then remove `activeTarget` from the committed fjall-config.json."))}getActiveTarget(){let t=this.loadLocalConfig().activeTarget;if(t!==void 0)return t;this.rootConfig.activeTarget!==void 0&&e.warnLegacyActiveTargetOnce()}setActiveTarget(t){let r=this.loadLocalConfig();return r.activeTarget=t,this.writeLocalConfig(r)}clearActiveTarget(){let t=this.loadLocalConfig();return delete t.activeTarget,this.writeLocalConfig(t)}getDomains(){return this.rootConfig.domains??[]}setDomains(t){this.rootConfig.domains=t}addDomain(t){this.rootConfig.domains||(this.rootConfig.domains=[]),this.rootConfig.domains.push(t)}getDomain(t){return this.rootConfig.domains?.find(r=>r.name.toLowerCase()===t.toLowerCase())}removeDomain(t){if(!this.rootConfig.domains)return!1;let r=this.rootConfig.domains.findIndex(i=>i.name.toLowerCase()===t.toLowerCase());return r===-1?!1:(this.rootConfig.domains.splice(r,1),!0)}getOrganisation(){return this.rootConfig.organisation}setOrganisation(t){this.rootConfig.organisation=t}clearOrganisation(){delete this.rootConfig.organisation}};var IW=Object.defineProperty,_i=(e,t)=>IW(e,"name",{value:t,configurable:!0});function x_(e){let t;try{t=af.loadConfig(e)}catch(i){return{kind:"unreadable",reason:le(ze(i))}}if(t.isContentUnavailable())return{kind:"unreadable",reason:"fjall-config.json exists but its contents could not be loaded (the preceding warning names the problem)"};let r=t.getOrganisation();return r!==void 0?{kind:"bound",bound:r}:t.getConfigPath()===null?{kind:"no_project"}:{kind:"unbound"}}_i(x_,"readProjectBinding");function T_(e,t,r){switch(e.kind){case"unreadable":return e;case"no_project":return{kind:"unbound",projectFound:!1,identity:t};case"unbound":return{kind:"unbound",projectFound:!0,identity:t};case"bound":return t===null?{kind:"unverifiable",bound:e.bound,reason:r??"the organisation could not be resolved"}:e.bound.id===t.id?{kind:"matched",bound:e.bound}:{kind:"mismatched",bound:e.bound,actual:t}}}_i(T_,"resolveBindingVerdict");function jR(e,t={}){return T_(x_(t.startDir),e,t.unresolvedReason)}_i(jR,"checkProjectOrganisation");function pa(e){return e.name!==void 0&&e.name!==""?`${e.name} (${e.id})`:e.id}_i(pa,"describeOrganisation");function MR(e,t,r){return`Refusing to ${e}: this project's fjall-config.json records organisation ${pa(t)} as its home, but the credential in use belongs to ${pa(r)}. Nothing was created, synthesised or deployed. Cure: authenticate as ${pa(t)} ('fjall login', or set FJALL_API_KEY to a key for that organisation), or \u2014 if this project really is moving \u2014 run 'fjall org bind --org ${r.id} --force' to re-bind it.`}_i(MR,"buildWrongOrganisationMessage");function LR(e,t){return`Refusing to ${e}: ${t}, so this project's organisation binding cannot be checked. Nothing was created, synthesised or deployed. Cure: fix fjall-config.json (permissions or contents), then re-run.`}_i(LR,"buildUnreadableConfigMessage");function FR(e,t){return`Could not confirm which organisation your credential belongs to (${t}). Proceeding \u2014 this project is bound to ${pa(e)}, and a mismatch would not have been caught.`}_i(FR,"buildUnverifiableNotice");function UR(e){return`This project is not bound to an organisation. Run 'fjall org bind' to pin it to ${pa(e)} \u2014 afterwards, any command run here with another organisation's credential is refused instead of silently landing there.`}_i(UR,"buildUnboundNotice");import{createHash as kW}from"node:crypto";var DW=Object.defineProperty,NW=(e,t)=>DW(e,"name",{value:t,configurable:!0});function zR(e,t){return kW("sha256").update(`${e}${t}`).digest("hex")}NW(zR,"credentialFingerprint");import*as sf from"node:fs";var wW=Object.defineProperty,of=(e,t)=>wW(e,"name",{value:t,configurable:!0}),BR="org-config-cache.json";function C_(){return Go(BR)}of(C_,"orgConfigCachePath");function I_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}of(I_,"isObject");function D_(e){return I_(e)&&typeof e.organisationId=="string"&&e.organisationId!==""&&typeof e.organisationName=="string"}of(D_,"isCachedCredentialIdentity");function GR(e){try{let t=C_();if(!sf.existsSync(t))return null;let r=JSON.parse(sf.readFileSync(t,"utf-8"));return!I_(r)||r.credentialFingerprint!==e?null:D_(r.identity)?r.identity:null}catch(t){return ua.debug("cachedCredentialIdentity","Cache read failed, treating as a miss",{error:le(ze(t))}),null}}of(GR,"readCachedCredentialIdentity");var PW=Object.defineProperty,RW=(e,t)=>PW(e,"name",{value:t,configurable:!0}),VR="https://fjall.io";function cf(){let e=process.env.FJALL_API_URL;return e!==void 0&&e!==""?e:VR}RW(cf,"resolveApiBaseUrl");var WR={name:"@fjall/cli",version:"30.0.0",repository:{type:"git",url:"git+https://github.com/fjall-tech/fjall.git",directory:"cli"},description:"Fjall CLI helper",private:!0,type:"module",bin:{fjall:"dist/src/cli.js"},files:["dist/"],scripts:{clean:"rm -rf ./dist ./dist.next ./sourcemaps","clean:node":"rm -rf ./node_modules","copy-files":'DEST="${DEST:-dist}"; find generators -type d -name files | while read dir; do mkdir -p "$DEST/$dir" && cp -R "$dir/." "$DEST/$dir/"; done && cp -R src/proto "./$DEST/src/proto"',build:"rm -rf ./dist.next ./sourcemaps && npx tsc --outDir dist.next && DEST=dist.next npm run copy-files && node ../scripts/minify-dist.mjs dist.next && chmod +x ./dist.next/src/cli.js && rm -rf ./dist && mv ./dist.next ./dist && node ../scripts/stamp-build.mjs",watch:"npm run build && npx tsc-watch","watch:only":'npx tsc-watch --onSuccess "npm run copy-files"',"fjall-cli":"node ./dist/src/cli.js",version:"npx tsx scripts/updateTemplateVersions.ts && node ../scripts/sync-ci-plugin-major.mjs",format:'prettier --write "src/**/*.{ts,tsx,js,jsx,json}" "generators/**/*.{ts,tsx,js,jsx,json}"',"format:check":'prettier --check "src/**/*.{ts,tsx,js,jsx,json}" "generators/**/*.{ts,tsx,js,jsx,json}"',lint:"eslint src/ generators/","lint:fix":"eslint src/ generators/ --fix",typecheck:"tsc --noEmit","typecheck:tests":"tsc --noEmit --project tsconfig.test.json","typecheck:scripts":"tsc --noEmit --project tsconfig.scripts.json","typecheck:all":"npm run typecheck && npm run typecheck:tests && npm run typecheck:scripts",test:"vitest run","test:watch":"vitest","test:coverage":"vitest run --coverage","test:integration":"vitest run --config vitest.config.integration.ts","test:integration:watch":"vitest --config vitest.config.integration.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","test:all":"npm run test && npm run test:integration && npm run test:e2e","test:setup":"node scripts/setupTestFixtures.mjs","test:payload-compat":"npx tsx scripts/testPayloadCompatibility.ts","test:payload-compat:e2e":"npx tsx scripts/testPayloadCompatibility.ts --e2e"},engines:{node:">=22.0.0"},author:"",license:"SEE LICENSE IN LICENSE",devDependencies:{"@eslint/js":"^10.0.1","@playwright/test":"^1.62.0","@testing-library/dom":"^10.4.1","@testing-library/react":"^16.3.2","@types/ejs":"^3.1.5","@types/prompts":"^2.4.9","@types/proper-lockfile":"^4.1.4","@types/react":"^19.2.17","@typescript-eslint/parser":"^8.65.0","@vitest/coverage-v8":"^4.1.10","aws-cdk-lib":"^2.265.0",constructs:"^10.7.2",eslint:"^10.8.0","ink-testing-library":"^4.0.0",jsdom:"^30.0.1",prettier:"^3.9.6","react-dom":"^19.2.8","strip-ansi":"^6.0.1","tsc-watch":"^7.2.1",tsx:"^4.23.1","typescript-eslint":"^8.65.0",vitest:"4.1.10"},dependencies:{"@anthropic-ai/sdk":"^0.115.0","@aws-sdk/client-acm":"^3.1098.0","@aws-sdk/client-auto-scaling":"^3.1098.0","@aws-sdk/client-backup":"^3.1098.0","@aws-sdk/client-cloudformation":"^3.1098.0","@aws-sdk/client-cost-explorer":"^3.1098.0","@aws-sdk/client-ec2":"^3.1098.0","@aws-sdk/client-ecr":"^3.1098.0","@aws-sdk/client-ecs":"^3.1098.0","@aws-sdk/client-elasticache":"^3.1098.0","@aws-sdk/client-iam":"^3.1098.0","@aws-sdk/client-identitystore":"^3.1098.0","@aws-sdk/client-lambda":"^3.1098.0","@aws-sdk/client-organizations":"^3.1098.0","@aws-sdk/client-ram":"^3.1098.0","@aws-sdk/client-rds":"^3.1098.0","@aws-sdk/client-route-53":"^3.1098.0","@aws-sdk/client-s3":"^3.1098.0","@aws-sdk/client-secrets-manager":"^3.1098.0","@aws-sdk/client-ssm":"^3.1098.0","@aws-sdk/client-sso":"^3.1098.0","@aws-sdk/client-sso-admin":"^3.1098.0","@aws-sdk/client-sso-oidc":"^3.1098.0","@aws-sdk/client-sts":"^3.1098.0","@fjall/deploy-core":"^30.0.0","@fjall/generator":"^30.0.0","@fjall/util":"^30.0.0","@nx/devkit":"^23.1.0","@opennextjs/aws":"^4.1.0","@smithy/node-http-handler":"^4.9.13","@toon-format/toon":"^4.1.0","aws-cdk":"^2.1134.0",axios:"^1.19.0",chalk:"^6.0.0","cli-cursor":"^5.0.0",commander:"^15.0.0",ejs:"^6.0.1",ink:"^7.1.1","js-yaml":"^5.2.2",open:"^11.0.0",ora:"^9.4.1",prompts:"^2.4.2","proper-lockfile":"^4.1.2",protobufjs:"^8.7.1",react:"^19.2.8",typescript:"^6.0.3","update-check":"^1.5.4",zod:"^4.4.3"}};var $W=Object.defineProperty,jW=(e,t)=>$W(e,"name",{value:t,configurable:!0}),ase=`fjall-cli/${WR.version} node/${process.versions.node} ${MW()}/${LW()}`;var KR=cf(),ose=c.looseObject({deviceCode:c.string(),userCode:c.string(),verificationUri:c.string(),expiresIn:c.number(),interval:c.number()}),sse=c.looseObject({status:c.string(),apiKey:c.string().optional(),organisationId:c.string().optional(),organisationName:c.string().optional(),email:c.string().optional()}),cse=c.looseObject({application:c.looseObject({id:c.string()})}),N_=c.looseObject({id:c.string(),name:c.string(),vpcCidr:c.string().nullable(),connectedAwsAccountId:c.string().nullable()}),lse=c.looseObject({applications:c.array(N_),nextCursor:c.string().optional()}),use=c.looseObject({application:N_}),dse=c.looseObject({applications:c.array(N_)}),pse=c.looseObject({application:c.looseObject({id:c.string(),name:c.string()})}),mse=c.looseObject({primaryRegion:c.string().nullish(),secondaryRegions:c.array(c.string()).optional(),disasterRecoveryRegion:c.string().nullish(),providerAccounts:c.custom(e=>Array.isArray(e)),ssoSessions:c.record(c.string(),c.looseObject({ssoRegion:c.string(),ssoStartUrl:c.string()})).optional(),rootOidcRoleArn:c.string().nullish(),allowCodemodLlmFallback:c.boolean().optional(),rootAccessManagement:c.custom(e=>typeof e=="string").optional(),requireTrackedDeploys:c.boolean().optional().catch(void 0)}),fse=c.looseObject({id:c.string(),token:c.string(),tokenPrefix:c.string(),name:c.string(),scopes:c.array(c.string())}),FW=c.looseObject({id:c.string(),name:c.string(),tokenPrefix:c.string(),scopes:c.array(c.string()),resourceConstraints:c.record(c.string(),c.unknown()),sourceTag:c.string().nullable(),expiresAt:c.string(),createdAt:c.string(),revokedAt:c.string().nullable(),revokedReason:c.string().nullable(),lastUsedAt:c.string().nullable(),usageCount:c.number(),deniedCount:c.number()}),hse=c.looseObject({tokens:c.array(FW)}),gse=c.looseObject({scopes:c.array(c.string()),expiresAt:c.string().optional()}),UW=c.looseObject({id:c.string(),awsAccountId:c.string(),accountName:c.string().nullable(),environment:c.string().nullable()}),yse=c.looseObject({accounts:c.array(UW)}),zW=c.looseObject({id:c.string(),assetIdentifier:c.string(),name:c.string(),type:c.string(),status:c.string(),region:c.string().nullish(),_count:c.looseObject({complianceIssues:c.number()}).optional()}),BW=c.looseObject({id:c.string(),name:c.string(),assetIdentifier:c.string(),provider:c.string(),type:c.string(),status:c.string(),region:c.string().nullish(),iacStatus:c.string().nullish(),accountId:c.string().nullish(),estimatedMonthlyCost:c.string().nullish(),lastSeenAt:c.string().nullish(),createdAt:c.string().nullish(),updatedAt:c.string().nullish()}),vse=c.looseObject({assets:c.array(zW),nextCursor:c.string().optional()}),Sse=c.looseObject({asset:BW}),GW=c.looseObject({id:c.string(),ruleId:c.string(),title:c.string(),severity:c.string(),status:c.string()}),bse=c.looseObject({issues:c.array(GW)}),Ese=c.record(c.string(),c.unknown()),Ase=c.union([c.array(c.record(c.string(),c.unknown())),c.record(c.string(),c.unknown())]),_se=c.record(c.string(),c.unknown()),xse=c.record(c.string(),c.unknown()),Tse=c.record(c.string(),c.unknown()),Cse=c.record(c.string(),c.unknown()),Ise=c.looseObject({deployment:c.looseObject({id:c.string()}),minCliVersion:c.string().optional()});var VW=c.object({id:c.string(),releaseNumber:c.number().int(),status:c.string(),commitSha:c.string().nullable(),branch:c.string().nullable(),createdAt:c.string(),assemblyDigest:c.string().nullable(),createdByDeploymentId:c.string().nullable(),rollbackOfReleaseId:c.string().nullable(),services:c.array(Rm.strip())}),Dse=c.object({releases:c.array(VW),currentReleaseId:c.string().nullable(),nextCursor:c.number().int().optional()}),WW=c.object({id:c.string(),status:c.string(),target:c.string().nullish(),applicationId:c.string().nullish(),applicationName:c.string().nullish(),connectedAwsAccountId:c.string().nullish(),source:c.string().nullish(),startedAt:c.string().nullish(),triggeredByName:c.string().nullish(),machineLabel:c.string().nullish()}),Nse=c.object({deployments:c.array(WW)}),kse=c.object({cancelled:c.boolean(),message:c.string().nullish(),declined:c.boolean().nullish()}),wse=c.object({released:c.literal(!0),id:c.string().nullish()}),Pse=c.looseObject({organisationId:c.string(),organisationName:c.string(),organisationSlug:c.string().min(1).optional()}),Rse=c.looseObject({status:c.string(),roleArn:c.string().optional(),accountId:c.string().optional(),phase:c.string().optional(),reason:c.string().optional()}),Ose=c.looseObject({token:c.string()}),KW=c.looseObject({quickCreateUrl:c.string(),externalId:c.string()}),ZW=c.looseObject({alreadyConnected:c.literal(!0),account:c.looseObject({awsAccountId:c.string(),accountName:c.string().nullable(),status:c.string()})}),$se=c.union([ZW,KW]);function HW(e){return"alreadyConnected"in e&&e.alreadyConnected===!0}jW(HW,"isAlreadyConnected");var jse=c.looseObject({registered:c.boolean(),repository:c.looseObject({id:c.string()}).optional()});var JW=Object.defineProperty,XW=(e,t)=>JW(e,"name",{value:t,configurable:!0});function xl(e=KR){return`Deploy tokens are minted from a signed-in browser session by an owner or admin: open ${e}/settings/ci (Settings \u2192 CI/CD Tokens).`}XW(xl,"deployTokenMintGuidance");var ZR=[{command:"ci status",match:N.success,templates:["Run `fjall ci verify` to check the rest of the wiring \u2014 an active deploy token is necessary, not sufficient","Run `fjall ci token list` to see which applications, environments and accounts each active token may deploy to"]},{command:"ci status",match:N.empty,templates:[xl(),"Run `fjall ci setup --plan --app <app>` to learn where the workflow file will go and which secret name it will read (`workflowPath`, `secretName`) \u2014 the two things needed to stage the secret before minting. `--plan` mints nothing and writes nothing, and the workflow BODY is printed on the human surface only: it is not a field of the agent payload"]},{command:"ci token list",match:N.success,templates:["Run `fjall token show <id>` to inspect one token's stored constraints","Run `fjall ci token revoke <id> --reason <text>` to revoke a listed token"]},{command:"ci token list",match:N.empty,templates:[xl(),"Run `fjall ci status` to re-check readiness once a token exists"]},{command:"ci token revoke",match:N.success,templates:["Run `fjall ci token list` to confirm the token now lists as revoked \u2014 a revoked token stays listed, it does not disappear",`Any CI job still holding this token now fails to authenticate. ${xl()}`]}];var lf="Do not retry or vary flags: `supported: false` is the server's capability verdict, not an input error \u2014 every invocation answers the same until the Fjall server is updated to a version that ships this API (the `message` field names the upgrade)",HR=[{command:"deployments list",match:N.unsupported,templates:[lf]},{command:"deployments cancel",match:N.unsupported,templates:[lf]},{command:"deployments force-release",match:N.unsupported,templates:[lf]},{command:"dev list",match:N.unsupported,templates:[lf]},{command:"deployments list",match:N.success,templates:["Run `fjall deployments cancel <id>` to request co-operative cancellation of a listed deployment","Run `fjall deploy logs --deployment-id <id>` to read one deployment's logs"]},{command:"deployments cancel",match:N.success,templates:["Run `fjall deployments list` to confirm whether the slot is free, and read `cancelled` and `declined` before assuming it is: `cancelled: false` means the request was refused, `declined: true` is an already-terminal reject, and a plain granted cancel is co-operative \u2014 the deployment has to acknowledge it","Run `fjall deployments force-release <id> --confirm <id>` to clear a slot that stays occupied (organisation admin, audited \u2014 retype the id in `--confirm`)"]},{command:"deployments force-release",match:N.success,templates:["Run `fjall deployments list` to confirm the slot is free","Run `fjall deploy <app>` to retry the deployment the wedged slot was blocking"]},{command:"dev up",match:N.success,templates:["Run `fjall dev list <app>` to see every slot for this app with its `host` \u2014 rows carry `host`, not a full URL, and it is empty until the slot leaves `creating`","Run `fjall dev down <app> --branch <branch>` to tear this slot down"]},{command:"dev list",match:N.success,templates:["Run `fjall dev down <app> --branch <branch>` to tear one listed slot down \u2014 every row carries the `branch` to name here","Run `fjall dev up <app> --branch <branch>` to bring another branch up"]},{command:"dev down",match:N.success,templates:["Run `fjall dev list <app>` to see which slots remain","Run `fjall dev up <app> --branch <branch>` to bring the branch back up"]},{command:"dev substrate down",match:N.success,templates:["Run `fjall dev list <app>` to confirm no slot survives \u2014 the substrate will not tear down under live slots, and `--force` takes them with it","Any `residuals` row survives the teardown and can still cost: its `cleanupHint` names the manual step"]}];var JR=["Run `fjall domain deploy <name>` to deploy the domain","Run `fjall domain verify <name>` to check DNS delegation once it is deployed","Run `fjall domain export <name>` to export the live zone records"],XR=[{command:"org deploy",match:N.success,templates:["Run `fjall org get` to review the deployed organisation topology and accounts",`Run \`${te.accountDeploy}\` to deploy the account tier if you passed \`--no-cascade\``,`Run \`${te.createApplicationAgent} --name "<name>"\` to create an application to deploy into it`]},{command:"org deploy",match:N.error,templates:["Run `fjall org get` to see which tier of the cascade is already deployed",`Run \`${te.organisationDeploy} --no-cascade\` to retry the organisation stack alone`]},{command:"platform deploy",match:N.success,templates:[`Run \`${te.accountDeploy}\` to deploy the account tier on top of it`]},{command:"platform deploy",match:N.error,templates:["Run `fjall org get` to check the organisation tier is deployed first"]},{command:"account deploy",match:N.success,templates:["Run `fjall apps list` to see which applications are registered","Run `fjall deploy <application>` to deploy one into this account"]},{command:"account deploy",match:N.error,templates:["Run `fjall org get` to confirm the account is registered in the organisation",`Run \`${te.accountDeploy} --target <target>\` to select a specific member account`]},{command:"domain list",match:N.success,templates:["Run `fjall domain verify <name>` to check DNS delegation","Run `fjall domain export <name>` to export zone file","Run `fjall create domain --name <name>` to create a new domain"]},{command:"domain list",match:N.empty,templates:['Run `fjall create domain --name "<name>"` to create a domain',"Run `fjall domain import <name>` to import from Route53"]},{command:"domain verify",match:N.success,templates:["Run `fjall domain export <name>` to export zone file","Run `fjall domain deploy <name>` to deploy domain infrastructure"]},{command:"domain verify",match:N.error,templates:["Run `fjall domain verify <name>` to retry","Run `fjall domain list` to see existing domains"]},{command:"domain export",match:N.success,templates:["Run `fjall domain verify <name>` to check delegation","Run `fjall domain import <name>` to re-import from Route53"]},{command:"domain import",match:N.success,templates:["Run `fjall domain verify <name>` to check delegation","Run `fjall domain export <name>` to see the zone file","Run `fjall domain deploy <name>` to deploy domain infrastructure"]},{command:"domain import",match:N.error,templates:["Run `fjall domain import --hosted-zone-id <id>` to import by zone ID","Run `fjall domain list` to see existing domains"]},{command:"domain records list",match:N.success,templates:["Run `fjall domain sync <domain>` for the full zone-hygiene report","Run `fjall domain sync <domain> --fix` to remediate residue records via the destruction ceremony"]},{command:"domain records list",match:N.empty,templates:["Run `fjall domain deploy <domain>` to deploy the domain's declared records","Run `fjall domain list` to see existing domains"]},{command:"domain records list",match:N.error,templates:["Run `fjall domain records list <domain> --hosted-zone-id <id>` when the zone is not resolvable by name",`Run \`${te.connect}\` if AWS credentials are missing`]},{command:"domain sync",match:N.success,templates:["Run `fjall domain sync <domain> --fix` to remediate residue records (ceremony-gated)","Run `fjall domain records list <domain>` to see every record with its owner"]},{command:"domain sync",match:N.error,templates:["Run `fjall domain sync <domain> --hosted-zone-id <id>` when the zone is not resolvable by name","Run `fjall domain list` to see existing domains"]},{command:"domain delegate",match:N.success,templates:["Run `fjall domain verify <domain>` to confirm public DNS resolution","Run `fjall domain deploy <domain>` to continue a two-phase deploy after delegation"]},{command:"domain delegate",match:N.error,templates:["Run `fjall domain deploy <parent-domain>` so the parent publishes its DelegationRole","Run `fjall domain verify <domain> --show-delegation` for registrar instructions"]},{command:"domain destroy",match:N.success,templates:["Run `fjall domain list` to see remaining domains","Run `fjall domain sync <parent-domain>` to confirm no delegation residue remains"]},{command:"domain destroy",match:N.error,templates:["Run `fjall domain destroy <domain> --remediate '<name>'=recreate` with the exact consent the ticket names","Run `fjall domain list` to see existing domains"]},{command:"domain deploy",match:N.success,templates:["Run `fjall domain verify <domain>` to check DNS propagation","Run `fjall domain delegate <domain>` to write the NS delegation for a delegated child"]},{command:"domain deploy",match:N.error,templates:["Run `fjall domain deploy <domain>` to resume \u2014 the zone phase is retained and skipped on re-run","Run `fjall domain verify <domain> --show-delegation` for registrar delegation instructions"]},{command:"domain eject",match:N.success,templates:["Review the ejected infrastructure.ts \u2014 it is now vanilla CDK owned by you","Run `fjall domain list` to see remaining managed domains"]},{command:"create domain",match:N.success,templates:JR},{command:"domain create",match:N.success,templates:JR},{command:"create domain",match:N.error,templates:["Run `fjall domain list` to see existing domains",'Run `fjall create domain --name "<name>"` to retry with a different name']},{command:"create account",match:N.success,templates:[`Run \`${te.connect} --environment production\` to link your AWS account`,`Run \`${te.accountDeploy}\` to deploy account infrastructure (after connecting)`]},{command:"create account",match:N.error,templates:[`Run \`${te.createAccount} --primary-region <region>\` to retry`,`Run \`${te.createAccount} --help\` for usage information`]},{command:"create org",match:N.success,templates:[`Run \`${te.connect} --name "<account-name>" --region <region>\` to link the AWS Organizations management account \u2014 omit \`--environment\` so it registers at the organisation tier`,`Run \`${te.organisationDeploy}\` to deploy all infrastructure (after connecting)`]},{command:"create org",match:N.error,templates:[`Run \`${te.createOrganisation} --email "<email>"\` to retry (add \`--name "<name>"\` only for a brand-new organisation)`,`Run \`${te.createOrganisation} --help\` for all options`]},{command:"restore",match:N.successDryRun,templates:["Run `fjall restore <resourceType> --recovery-point <recoveryPointArn> --yes` to initiate restore","Run `fjall apps list` to see existing applications"]},{command:"restore",match:N.success,templates:["Open the AWS Console URL above to monitor restore progress","Run `fjall import` to import the restored resource after completion"]},{command:"restore",match:N.errorWithCode("NOT_FOUND"),templates:["Verify the recovery point ARN is correct and exists in the current region","Run `fjall restore <resourceType> --recovery-point <arn>` to retry"]},{command:"restore",match:N.errorWithCode("FORBIDDEN"),templates:["Ensure the IAM role has backup:StartRestoreJob and iam:PassRole permissions","Run `fjall restore` interactively to configure with guided setup"]},{command:"import",match:N.successDryRun,templates:["Run `fjall import --app <app> --resource-id <resourceId> --yes` to import a specific resource","Run `fjall import --app <app> --yes` to import all discovered resources"]},{command:"import",match:N.success,templates:["Run `fjall deploy <app>` to deploy with the imported resource","Run `fjall apps describe <app>` to see updated resources"]},{command:"import",match:N.errorWithCode("NOT_FOUND"),templates:[`Run \`${te.createApplicationAgent} --name "<app>"\` to create the application`,"Run `fjall apps list` to see existing applications"]},{command:"import",match:N.errorWithCode("VALIDATION_ERROR"),templates:["Run `fjall import --app <app> --resource-id <resourceId>` to import a specific resource","Run `fjall import --app <app> --resource-id <resourceId> --yes` to import immediately"]},{command:"aws exec",match:N.success,templates:["Run `fjall aws exec -- <command...>` to run another AWS CLI command","Run `fjall status` to check application health"]},{command:"aws exec",match:N.error,templates:["Retry the command \u2014 OIDC token mints can fail transiently",`Run \`${te.login}\` if the retry also fails with an authentication error`]},{command:"unlock bucket",match:N.success,templates:["Re-put sane bucket policy statements (enforceSSL deny, access grants) \u2014 the unlock deleted the ENTIRE policy","Run `fjall destroy <app>` to retry the blocked stack cleanup"]},{command:"unlock bucket",match:N.error,templates:["Ensure your credentials belong to the organisation's management account \u2014 STS AssumeRoot is rejected elsewhere","Run `fjall unlock bucket <name> --account <id> --acknowledge-root-session` to retry"]}];var qW=Object.defineProperty,eO=(e,t)=>qW(e,"name",{value:t,configurable:!0}),qR="Run `fjall connect status` to check that an AWS account is connected: asset discovery only inventories connected accounts, so an organisation with none has nothing to inventory",YR=["Run `fjall assets show <asset>` to read one asset in full \u2014 pass its `assetIdentifier`","Run `fjall assets compliance <asset>` to list an asset's recorded posture issues \u2014 pass its `assetIdentifier`, the address every server version accepts"],QR=eO(e=>e.outcome==="success"&&e.nextCursor!==void 0,"isTruncatedPage"),tO=[{command:"assets list",match:eO(e=>QR(e)&&e.fields!==void 0&&e.fields!=="","match"),templates:["This window is truncated \u2014 more assets exist beyond these rows. Run `fjall assets list --cursor <nextCursor> --fields <fields>` to fetch the next page with the same projection; `total` counts this window only, and `fjall assets summary` reports the estate-wide tally, split active/deleted",...YR]},{command:"assets list",match:QR,templates:["This window is truncated \u2014 more assets exist beyond these rows. Run `fjall assets list --cursor <nextCursor>` to fetch the next page; `total` counts this window only, and `fjall assets summary` reports the estate-wide tally, split active/deleted",...YR]},{command:"assets list",match:N.success,templates:["The `total` aggregate counts the rows in this response, not the estate: `--take` bounds the window (default 50). No `nextCursor` aggregate here means the estate ends with these rows; `fjall assets summary` reports the estate-wide tally, split active/deleted","Run `fjall assets show <asset>` to read one asset in full","Run `fjall assets compliance <asset>` to list an asset's recorded posture issues \u2014 pass its `assetIdentifier`, the address every server version accepts (row `id`s are only accepted by newer servers)"]},{command:"assets list",match:N.empty,templates:["Run `fjall assets list --status deleted` to include assets discovery has since marked deleted \u2014 the default listing hides them",qR]},{command:"assets show",match:N.success,templates:["Run `fjall assets compliance <asset>` to list the posture issues recorded against this asset","Run `fjall assets show <asset> --fields id,accountId,iacStatus,estimatedMonthlyCost,lastSeenAt` to read the fields the default projection omits"]},{command:"assets compliance",match:N.success,templates:["Read the `status` column before acting: this listing returns every issue recorded against the asset, `resolved` and `suppressed` included, where the `openIssues` count on `fjall assets list` counts only the open ones","Run `fjall compliance fix --domain compliance --issue-id <issueId>` to read this issue in full alongside the organisation's other open issues. `--domain` is the producer's category \u2014 one of `compliance`, `cost`, `performance` \u2014 not a framework name, and the response is context to reason from, not a remediation step: use `--execute` to run one","Run `fjall assets show <asset>` to read the asset these issues were raised against"]},{command:"assets compliance",match:N.empty,templates:["No issue of ANY status has been recorded against this asset \u2014 an empty listing here is not the same as issues that were resolved, which would still appear with `status: resolved`","Run `fjall assets list --fields name,assetIdentifier,openIssues` to find the assets that do carry open issues"]},{command:"assets summary",match:N.success,templates:["Run `fjall assets list --fields name,assetIdentifier,openIssues` to see which assets sit behind `withIssues` \u2014 `withIssues` counts the assets carrying at least one open issue, `openIssues` counts those issues per asset","Run `fjall assets list --take <n>` to read the rows behind these totals \u2014 page onwards with `--cursor` when the listing reports a `nextCursor`, and pass `--status deleted` to include the `deleted` rows in the listing (interleaved with active \u2014 read the `status` column). These totals are estate-wide (the summary pages the listing to exhaustion, deleted assets included): `total` counts the whole estate, `active` and `deleted` split it"]},{command:"assets summary",match:N.empty,templates:[qR]},{command:"costs show",match:N.success,templates:["Run `fjall costs --mode forecast` to see forecasted spend","Run `fjall costs --mode breakdown` to see service-level breakdown"]},{command:"costs show",match:N.error,templates:["Run `fjall costs --app <app>` to filter by application","Run `fjall costs --help` for usage information"]},{command:"metrics show",match:N.success,templates:["Run `fjall metrics --mode latency` to see latency percentiles","Run `fjall metrics --mode errors` to see error trends"]},{command:"metrics show",match:N.error,templates:["Run `fjall metrics --app <app>` to filter by application","Run `fjall metrics --help` for usage information"]},{command:"compliance fix",match:N.success,templates:["Run `fjall compliance fix --domain <domain> --issue-id <id>` to narrow the suggestions to one issue","Run `fjall deploy <app>` to apply remediation changes"]},{command:"compliance fix",match:N.error,templates:["Run `fjall compliance fix --domain <domain>` to name the compliance domain","Run `fjall compliance --help` for usage information"]},{command:"compliance fix --execute",match:N.success,templates:["Read the result's `kind` before treating the issue as fixed: `auto-pr` opened a pull request that still has to be merged, `imperative` rewrote the live policy, and `manual-hint` changed nothing \u2014 its `awsCliHint` carries the manual step, and that field is absent for rules that supply no hint (`message` is a fixed string either way)","Do not re-read the issue to confirm the cure: nothing on the remediation path writes to the issue record, so `status` stays `open` until the next discovery scan re-evaluates the asset. Verify at the thing that changed \u2014 the pull request, or the live resource","Run `fjall deploy <app>` to roll out an `auto-pr` remediation once its pull request is merged"]},{command:"deploy diff",match:N.success,templates:["Run `fjall deploy logs --deployment-id <id>` to analyse deployment logs","Run `fjall status <app>` to check current deployment health"]},{command:"deploy diff",match:N.error,templates:["Run `fjall list deployments` to see recent deployment IDs","Run `fjall deploy diff --help` for usage information"]},{command:"deploy logs",match:N.success,templates:["Run `fjall deploy diff <idA> <idB>` to compare two deployments","Run `fjall status <app>` to check current deployment health"]},{command:"deploy logs",match:N.error,templates:["Run `fjall deploy logs --deployment-id <id>` with a valid deployment ID","Run `fjall list deployments` to find a deployment ID"]}];var YW={command:"*",match:N.error,templates:["Run `fjall <command> --help` for usage information"]},rO=[...DR,...NR,...wR,...ZR,...HR,...XR,...tO,YW];var QW=Object.defineProperty,eK=(e,t)=>QW(e,"name",{value:t,configurable:!0}),nO=["app","environment","region","profile","target","cluster","service","lambda","status","type"],ma=["app","cluster","service","lambda"],tK=["status","type","region"],k_={deploy:["environment","region","target"],"deploy diff":[],"deploy logs":[],destroy:["target"],"org deploy":["target"],"org destroy":["target"],"platform deploy":["target"],"platform destroy":["target"],"account deploy":["target"],"account destroy":["target"],status:[],rollout:[],list:["app"],apps:["target"],connect:["environment","region"],"connect status":[],import:["app","region"],costs:["app"],metrics:["app"],compliance:["app"],"token create":["app","environment"],"unlock bucket":["region"],"aws exec":["app","region","target"],"secrets set":ma,"secrets get":ma,"secrets list":ma,"secrets delete":ma,"secrets export":ma,"secrets import":ma,"secrets exec":ma,"assets list":tK},rK=Math.max(...Object.keys(k_).map(e=>e.split(" ").length));function w_(e){let t=e.trim().split(/\s+/).slice(1);for(let r=rK;r>=1;r--){let i=t.slice(0,r).join(" ");if(Object.hasOwn(k_,i))return k_[i]}return[]}eK(w_,"resolvePreservableFlags");var nK=Object.defineProperty,df=(e,t)=>nK(e,"name",{value:t,configurable:!0});function P_(e){let t=e.replace(/[\u0000-\u001f\u007f`]/g,"");return/[^\w@%+=:,./-]/.test(t)?`'${t.replace(/'/g,"'\\''")}'`:t}df(P_,"shellEscape");function iO(e,t,r){let i=new Set,n=e.replace(/<(\w+)>/g,(a,o)=>{let s=t[o];return s===void 0||s===""?`<${o}>`:(i.add(o),o==="command"?s:P_(s))});return aO(n,r,i)}df(iO,"interpolateTemplate");var uf=class{static{df(this,"SuggestionResolver")}command;flags;constructor(t,r){this.command=t,this.flags=r}resolve(t){let r=rO.find(i=>(i.command===this.command||i.command==="*")&&i.match(t));return r===void 0?[]:r.templates.map(i=>iO(i,t,this.flags))}};function aO(e,t,r=new Set){let i=/`(fjall[^`]*)`/.exec(e),n=i?.[1];if(i===null||n===void 0)return e;let a=w_(n),o=[];for(let d of nO){if(!a.includes(d))continue;let h=t[d];h!==void 0&&h!==""&&!r.has(d)&&!n.includes(`--${d}`)&&o.push(`--${d} ${P_(h)}`)}if(o.length===0)return e;let s=` ${o.join(" ")}`,l=n.indexOf(" -- "),m=l===-1?`${n}${s}`:`${n.slice(0,l)}${s}${n.slice(l)}`;return e.slice(0,i.index)+`\`${m}\``+e.slice(i.index+i[0].length)}df(aO,"applyPreservedFlags");var iK=Object.defineProperty,Un=(e,t)=>iK(e,"name",{value:t,configurable:!0});function Gr(e,t){if(t!==void 0&&rs(e)){let i={};for(let[n,a]of Object.entries(e))i[n]=t.has(n)?a:Gr(a);return i}if(typeof e=="string")return le(e);if(e==null||typeof e!="object")return e;if(Array.isArray(e))return e.map(i=>Gr(i));if(e instanceof Date||e instanceof RegExp)return e;let r={};for(let[i,n]of Object.entries(e))r[i]=Gr(n);return r}Un(Gr,"maskTree");function pf(e){if(Array.isArray(e))return e.map(pf);if(!rs(e))return e;let t={};for(let[r,i]of Object.entries(e))i!==void 0&&(t[r]=pf(i));return t}Un(pf,"stripAbsent");function rs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof Date)&&!(e instanceof RegExp)}Un(rs,"isPlainRecord");function oO(e){let t=e?.verbatimFields;return t!==void 0&&t.length>0?new Set(t):void 0}Un(oO,"toVerbatimKeys");function sO(e,t){return t===void 0||!rs(e)?!1:Object.keys(e).some(r=>t.has(r))}Un(sO,"carriesVerbatimField");function cO(e,t){let r=e;for(let i of t.split(".")){if(!rs(r))return;r=r[i]}return r}Un(cO,"resolveDotPath");function lO(e,t,r){let i=e.project(t),n={};for(let a of r)a in i&&(n[a]=i[a]);return n}Un(lO,"projectSelectedFields");var Tl=class{static{Un(this,"AgentOutputWriter")}write;hasWrittenBlock=!1;resolver;flags;full;budget;requestedFields;constructor(t){this.write=t.writeFn??(r=>{process.stdout.write(r)}),this.resolver=new uf(t.command,t.flags),this.flags=t.flags,this.full=t.full??!1,this.budget=t.budget,this.requestedFields=t.fields??[]}get isFullOutput(){return this.full}writeBlock(t){t!==""&&(this.hasWrittenBlock&&this.write(n_+`
300
300
  `),this.hasWrittenBlock=!0,this.write(t))}renderResult(t,r){let i=oO(r?.schema),n=Gr(t,i),a=r?.schema!==void 0&&rs(n)?this.applySchema(n,r.schema):n,o=a_(a),s=this.resolveHelp(r?.suggestionContext),l=o+s+`
301
301
  `;this.writeBlock((sO(a,i)?l:Jm(l,this.budget))+Qo())}renderListResult(t,r,i){let n=t.map(m=>Gr(m)),a=i.fields,o=a!==void 0&&a.length>0?a:r.fields,s=o_(n,{fields:o,project:Un(m=>lO(r,m,o),"project")},{entity:i.entity,aggregates:i.aggregates===void 0?void 0:Gr(i.aggregates)}),l=this.resolveHelp(i.suggestionContext);this.writeBlock(Jm(s+l+`
302
302
  `,this.budget)+Qo())}renderEvent(t){let r=Gr(t),i=l_({...r,value:pf(r.value)});this.writeBlock(i)}renderError(t,r){let i={...t,message:le(t.message),...t.details!==void 0?{details:Gr(t.details)}:{}},n=s_(i),a=this.resolveHelp(r);this.writeBlock(n+a+`
@@ -309,7 +309,7 @@ ${n_}
309
309
  `)}}setDebugEnabled(t){this.debugEnabled=t}write(t,r){this.isClosing||(this.initialised||this.initialise(),this.buffer.push(t),this.debugEnabled&&r&&this.debugBuffer.push(t),this.buffer.length>=this.config.maxBufferSize&&this.flush())}flushBuffer(t,r,i){if(t.length===0||!r)return{buffer:t,stream:r};let n=r;this.fileRotator.needsRotation(i,this.config.maxFileSize)&&(n.end(),this.fileRotator.rotate(i),n=this.openStream(i));for(let a of t)n.write(JSON.stringify(a)+`
310
310
  `);return{buffer:[],stream:n}}flush(){let t=this.flushBuffer(this.buffer,this.mainLogStream,this.mainLogPath);this.buffer=t.buffer,this.mainLogStream=t.stream;let r=this.flushBuffer(this.debugBuffer,this.debugLogStream,this.debugLogPath);this.debugBuffer=r.buffer,this.debugLogStream=r.stream}close(){this.isClosing=!0,this.flush(),this.flushInterval&&(clearInterval(this.flushInterval),this.flushInterval=null),this.mainLogStream&&(this.mainLogStream.end(),this.mainLogStream=null),this.debugLogStream&&(this.debugLogStream.end(),this.debugLogStream=null),this.buffer=[],this.debugBuffer=[],this.initialised=!1,this.isClosing=!1}async closeAndFlush(){this.isClosing=!0,this.flush(),this.flushInterval&&(clearInterval(this.flushInterval),this.flushInterval=null);let t=[];this.mainLogStream&&(t.push(this.mainLogStream),this.mainLogStream=null),this.debugLogStream&&(t.push(this.debugLogStream),this.debugLogStream=null),this.buffer=[],this.debugBuffer=[],this.initialised=!1,await Promise.all(t.map(r=>new Promise(i=>{r.end(()=>i())}))),this.isClosing=!1}};import{createWriteStream as kK,existsSync as wK,mkdirSync as PK,readdirSync as RK,statSync as OK,unlinkSync as $K}from"fs";import{join as B_}from"path";var zn={trace:0,debug:1,info:2,warn:3,error:4},an={MAX_FILE_SIZE:Dl.MAX_FILE_SIZE,MAX_FILES:Dl.MAX_FILES,MAX_BUFFER_SIZE:100,MAX_DEPLOYMENT_LOGS_PER_APP:100,MAX_DEPLOYMENT_LOG_BYTES_PER_APP:256*1024*1024,FLUSH_INTERVAL_MS:500,LOG_FILENAME:"fjall.jsonl",DEBUG_LOG_FILENAME:"fjall-debug.jsonl"};var IK=Object.defineProperty,DK=(e,t)=>IK(e,"name",{value:t,configurable:!0});function os(){return Sm()}DK(os,"getDefaultLogDir");var NK=Object.defineProperty,EO=(e,t)=>NK(e,"name",{value:t,configurable:!0}),jK=/^[a-zA-Z0-9_-]+-\d{4}-\d{2}-\d{2}T[\d-]+Z\.jsonl$/,MK=6e4;function AO(e,t,r){try{let i=Date.now(),n=RK(e).filter(s=>jK.test(s)).map(s=>{let l=B_(e,s);try{let m=OK(l);return{path:l,mtimeMs:m.mtimeMs,size:m.size}}catch{return}}).filter(s=>s!==void 0&&i-s.mtimeMs>=MK);n.sort((s,l)=>l.mtimeMs-s.mtimeMs);let a=0,o=0;for(let s of n){if(a===0||a<t&&o+s.size<=r){a+=1,o+=s.size;continue}try{$K(s.path)}catch{}}}catch{}}EO(AO,"pruneOldDeploymentLogs");var Nl=class{static{EO(this,"DeploymentLoggerImpl")}mainLogger;appName;operationType;logStream=null;logPath;deploymentId;buffer=[];flushInterval=null;isClosing=!1;maxBufferSize=an.MAX_BUFFER_SIZE;constructor(t,r,i){this.mainLogger=t,this.appName=r,this.operationType=i,this.deploymentId=`${i}-${Date.now()}`;let n=os(),a=B_(n,"deployments",r);wK(a)||PK(a,{recursive:!0}),AO(a,an.MAX_DEPLOYMENT_LOGS_PER_APP,an.MAX_DEPLOYMENT_LOG_BYTES_PER_APP);let o=new Date().toISOString().replace(/[:.]/g,"-"),s=`${i}-${o}.jsonl`;this.logPath=B_(a,s);try{this.logStream=kK(this.logPath,{flags:"a"}),this.flushInterval=setInterval(()=>this.flush(),an.FLUSH_INTERVAL_MS),this.info("DeploymentLogger","Deployment logging initialised",{appName:r,operationType:i,deploymentId:this.deploymentId,logPath:this.logPath})}catch{}}log(t,r,i,n,a,o){if(this.isClosing)return;let s={timestamp:new Date().toISOString(),level:t,component:r,message:i,correlationId:this.deploymentId,...n&&Object.keys(n).length>0&&{data:n},...a&&{stackName:a},...o&&{phase:o}};this.buffer.push(s),this.mainLogger.logWithCorrelation(t,r,i,this.deploymentId,n,a,o),this.buffer.length>=this.maxBufferSize&&this.flush()}flush(){if(!(this.buffer.length===0||!this.logStream)){for(let t of this.buffer)this.logStream.write(JSON.stringify(t)+`
311
311
  `);this.buffer=[]}}info(t,r,i){this.log("info",t,r,i)}warn(t,r,i){this.log("warn",t,r,i)}error(t,r,i){this.log("error",t,r,i)}debug(t,r,i){this.log("debug",t,r,i)}stackEvent(t,r,i,n){this.log("info","StackDeployment",i,n,t,r)}dockerEvent(t,r){this.log("info","DockerOperation",t,{percentage:r})}ecsEvent(t,r,i){this.log("info","ECSDeployment",t,{percentage:r,taskCount:i})}close(){this.isClosing=!0,this.flush(),this.flushInterval&&(clearInterval(this.flushInterval),this.flushInterval=null),this.logStream&&(this.logStream.end(),this.logStream=null),this.buffer=[],this.isClosing=!1}getLogPath(){return this.logPath}getDeploymentId(){return this.deploymentId}};var LK=Object.defineProperty,W_=(e,t)=>LK(e,"name",{value:t,configurable:!0});function V_(){let e=L_();return e==="agent"||e==="mcp"}W_(V_,"isStructuredOutputMode");function _O(){return Jo.isUIMode||Jo.isNonInteractive}W_(_O,"surfaceOwnsConsole");var yf=class e{static{W_(this,"Logger")}static instance=null;config;debugEnabled;traceEnabled;minLevel;fileWriter;mainLogPath;debugLogPath;constructor(){let t=os(),r=G_(t,"debug"),{maxFileSize:i,maxFiles:n}=z_();this.config={logDir:t,debugLogDir:r,maxFileSize:i,maxFiles:n,maxBufferSize:an.MAX_BUFFER_SIZE,flushIntervalMs:an.FLUSH_INTERVAL_MS},this.mainLogPath=G_(t,an.LOG_FILENAME),this.debugLogPath=G_(r,an.DEBUG_LOG_FILENAME),this.debugEnabled=process.env.FJALL_DEBUG==="true"||process.env.FJALL_TRACE==="true"||process.argv.includes("--verbose")||process.argv.includes("-v"),this.traceEnabled=process.env.FJALL_TRACE==="true";let a=process.env.FJALL_LOG_LEVEL?.toLowerCase();a&&a in zn?this.minLevel=a:this.traceEnabled?this.minLevel="trace":this.debugEnabled?this.minLevel="debug":this.minLevel="info",this.fileWriter=new gf(this.config,this.mainLogPath,this.debugLogPath,this.debugEnabled)}static getInstance(){return e.instance||(e.instance=new e),e.instance}shouldLog(t){return zn[t]>=zn[this.minLevel]}createEntry(t,r,i,n,a,o,s){return{timestamp:new Date().toISOString(),level:t,component:r,message:i,...a&&{correlationId:a},...n&&Object.keys(n).length>0&&{data:n},...o&&{stackName:o},...s&&{phase:s}}}log(t,r,i,n,a,o,s){if(!this.shouldLog(t))return;let l=this.createEntry(t,r,i,n,a,o,s),m=t==="debug"||t==="trace";this.fileWriter.write(l,m),this.writeConsole(l)}writeConsole(t){if(V_()||_O()){this.debugEnabled&&this.writeStderrLine(t);return}let r=this.getConsolePrefix(t.level),i=`[${t.component}]`,n=`${r} ${i} ${t.message}`;t.level==="error"?console.error(n):t.level==="warn"?console.warn(n):console.log(n)}writeStderrLine(t){let r=this.getConsolePrefix(t.level),i=`[${t.component}]`,n="";if(t.data&&Object.keys(t.data).length>0)try{n=` ${JSON.stringify(t.data)}`}catch{n=" [unserialisable data]"}let a=`${r} ${i} ${t.message}${n}`;process.stderr.write(`${le(a)}
312
- `)}getConsolePrefix(t){switch(t){case"error":return"[ERROR]";case"warn":return"[WARN]";case"info":return"[INFO]";case"debug":return"[DEBUG]";case"trace":return"[TRACE]"}}error(t,r,i){this.log("error",t,r,i)}warn(t,r,i){this.log("warn",t,r,i)}info(t,r,i){this.log("info",t,r,i)}debug(t,r,i){this.log("debug",t,r,i)}trace(t,r,i){this.log("trace",t,r,i)}diagnostic(t,r,i,n){this.log(t,r,i,n),!this.debugEnabled&&V_()&&(zn[t]<zn.info||this.writeStderrLine(this.createEntry(t,r,i,n)))}isDebugEnabled(){return this.debugEnabled}isTraceEnabled(){return this.traceEnabled}enableDebug(){this.debugEnabled=!0,zn[this.minLevel]>zn.debug&&(this.minLevel="debug"),this.fileWriter.setDebugEnabled(!0),this.fileWriter.isInitialised&&this.fileWriter.initialiseDebugStream()}withCorrelation(t){return new is(this,t)}forDeployment(t,r="deploy"){return new Nl(this,t,r)}close(){this.fileWriter.close()}async flushAndClose(){await this.fileWriter.closeAndFlush()}getLogPath(){return this.mainLogPath}getDebugLogPath(){return this.debugLogPath}getLogDir(){return this.config.logDir}logWithCorrelation(t,r,i,n,a,o,s){this.log(t,r,i,a,n,o,s)}static reset(){e.instance&&(e.instance.close(),e.instance=null)}};var Ei=yf.getInstance();var FK=Object.defineProperty,ct=(e,t)=>FK(e,"name",{value:t,configurable:!0}),ss="fjall";function ha(e,t){let r=UK(e);if(r.includes("..")||r.startsWith("/"))throw new Error(`Invalid ${t}: path traversal is not allowed`)}ct(ha,"assertNoTraversal");function zK(){return ss}ct(zK,"getFjallPath");function BK(e){let t=xO(e);return xO(t)||"."}ct(BK,"getProjectRoot");function IO(e){if(!CO(e))throw new Error(`Infrastructure file not found: ${e}`);let t=TO(e,"utf-8"),r=DO(t);if(r===void 0)throw new Error(`Could not find appName in infrastructure file: ${e}. Expected format: const appName = "yourAppName";`);return r}ct(IO,"getAppNameFromInfrastructure");function DO(e){return e.match(/const\s+appName\s*=\s*["']([^"']+)["']/)?.[1]}ct(DO,"parseAppNameFromInfrastructureContent");function GK(e){if(!CO(e))return;let t;try{t=TO(e,"utf-8")}catch(r){Ei.debug("PathHelpers","Could not read organisation infrastructure",{error:le(ze(r))});return}return t.match(/organisationName:\s*(["'])(.+?)\1/)?.[2]}ct(GK,"readOrganisationNameFromInfrastructure");function VK(e){let t=vr(e,H_);return IO(t)}ct(VK,"getAppName");function WK(e){return ha(e,"app name"),vr(ss,e,H_)}ct(WK,"getInfrastructurePath");function vf(e){return ha(e,"app name"),vr(ss,e)}ct(vf,"getAppPath");function NO(e,t){let r=e??process.cwd();return t===void 0?r:(ha(t,"container"),vr(r,t))}ct(NO,"resolveScaffoldRootDir");function KK(e,t,r){return vr(NO(t,r),vf(e))}ct(KK,"resolveAppScaffoldPath");function K_(e){return ha(e,"component name"),vr(ss,e)}ct(K_,"getOrganisationComponentPath");function ZK(e){return ha(e,"deployment type"),vr(ss,e,"logs")}ct(ZK,"getDeploymentLogsPath");function kO(){return vr(ss,"domains")}ct(kO,"getDomainsDir");function Z_(e){return ha(e,"domain name"),vr(kO(),e)}ct(Z_,"getDomainComponentPath");function HK(e){return vr(Z_(e),H_)}ct(HK,"getDomainInfrastructurePath");function JK(e){return vr(Z_(e),XK)}ct(JK,"getDomainZoneFilePath");var H_="infrastructure.ts",XK="zone.bind",qK="cdk.out";function YK(e){return vr(e,qK)}ct(YK,"getCdkOutPath");var QK=Object.defineProperty,eZ=(e,t)=>QK(e,"name",{value:t,configurable:!0}),tZ=import.meta.dirname;function J_(e,t,r,i){let n=wO(tZ,"..","shared","files"),a=t.includes("/")?t:vf(t);yc(e,n,a,r,i),gc(e,wO(a,".gitignore"),ll,i)}eZ(J_,"copySharedCdkFiles");var rZ=Object.defineProperty,cs=(e,t)=>rZ(e,"name",{value:t,configurable:!0});function PO(e){return e.success===!0}cs(PO,"isSuccess");function RO(e){return e.success===!1}cs(RO,"isFailure");function K(e){return{success:!0,data:e}}cs(K,"success");function j(e){return{success:!1,error:e}}cs(j,"failure");async function OO(e){try{let t=await e();return K(t)}catch(t){return j(yi(t))}}cs(OO,"tryAsync");function $O(e){try{let t=e();return K(t)}catch(t){return j(yi(t))}}cs($O,"trySync");var nZ=Object.defineProperty,iZ=(e,t)=>nZ(e,"name",{value:t,configurable:!0}),jO=/^[a-zA-Z][a-zA-Z0-9-]*$/,aZ=rl.source.replace(/^\^|\$$/g,""),he=Object.freeze({IDENTIFIER:jO,NEW_APP_NAME:/^[a-z][a-z0-9-]*$/,RESOURCE_NAME:/^[a-zA-Z][a-zA-Z0-9]*$/,ECS_SERVICE_NAME:jO,BUCKET_NAME:/^[a-z][a-z0-9-]*[a-z0-9]$|^[a-z][a-z0-9]*$/,DATABASE_NAME:/^[a-zA-Z][a-zA-Z0-9_]*$/,RESOURCE_TYPE:/^[a-z]+(:[a-z]+)?$/,SSM_PATH:new RegExp(`^(?:/${aZ})+$`),SECRET_NAME:Im,SSM_COMPONENT:rl,EMAIL:/^[^\s@]+@[^\s@]+\.[^\s@]+$/,DOCKER_IMAGE:/^[a-z0-9][a-z0-9._-]*[a-z0-9](:[a-z0-9._-]+)?$/,DOMAIN:/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/i,HTTP_ORIGIN:/^https?:\/\/[a-z0-9.-]+(:\d+)?$/i,PASCAL_CASE:/^[A-Z][A-Za-z0-9]*$/,AWS_ACCOUNT_ID:/^\d{12}$/,VPC_ID:/^vpc-[a-z0-9]+$/,ROLE_ARN:/^arn:aws[a-zA-Z-]*:iam::\d{12}:role\/.+$/,CIDR:/^((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\/(3[0-2]|[12]?\d)$/,SCHEDULE_EXPRESSION:/^(rate\(1 (?:minute|hour|day)\)|rate\((?:[2-9]|[1-9]\d+) (?:minutes|hours|days)\)|cron\([^\s()]+ [^\s()]+ [^\s()]+ [^\s()]+ [^\s()]+ [^\s()]+\))$/,LAMBDA_RUNTIME_IDENTIFIER:/^[A-Za-z0-9._-]+$/,ENV_VAR_NAME:/^[A-Za-z_][A-Za-z0-9_]*$/});function X_(e){let t=/^rate\((\d+) (minute|minutes|hour|hours|day|days)\)$/.exec(e);if(!t)return;let r=t[1],i=t[2];if(r===void 0||i===void 0)return;let n=parseInt(r,10);if(!Number.isFinite(n)||n<1)return;let a=i==="minute"||i==="hour"||i==="day";if(!(a&&n!==1)&&!(!a&&n===1))return i==="minute"||i==="minutes"?{everyMs:n*6e4}:i==="hour"||i==="hours"?{everyMs:n*60*6e4}:{everyMs:n*24*60*6e4}}iZ(X_,"parseRateExpression");var MO=["t4g.medium","m7g.medium","m8g.medium","r7g.medium","r8g.medium","m7g.large","m8g.large","r7g.large","r8g.large","m7g.xlarge","m8g.xlarge","r7g.xlarge","r8g.xlarge"];var E=Object.freeze({IDENTIFIER:"Must start with a letter, contain only letters, numbers, and hyphens",NEW_APP_NAME:"Must start with a lowercase letter and contain only lowercase letters, numbers, and hyphens",IDENTIFIER_MIN_LENGTH:"Must be at least 2 characters",IDENTIFIER_NO_TRAILING_HYPHEN:"Must not end with a hyphen",IDENTIFIER_NO_CONSECUTIVE_HYPHENS:"Must not contain consecutive hyphens",RESOURCE_NAME:"Must start with a letter and contain only letters and numbers (PascalCase recommended)",ECS_SERVICE_NAME:"Service name must start with a letter and contain only letters, numbers, and hyphens",BUCKET_NAME:"Bucket name must start with a lowercase letter and contain only lowercase letters, numbers, and hyphens",DATABASE_NAME:"Database name must start with a letter and contain only letters, numbers, and underscores",RESOURCE_TYPE:"Resource type must be in format 'category' or 'category:type'",SSM_PATH:"SSM path must start with / and contain valid namespace segments (e.g., /myapp/ApiCluster/service)",SECRET_NAME:gA,SSM_COMPONENT:Dm,EMAIL:"Please enter a valid email address",DOMAIN:"Please enter a valid domain (e.g., cms.example.com)",DOCKER_IMAGE:"Invalid Docker image name format",REQUIRED:{APP_NAME:"Application name is required",RESOURCE_NAME:"Resource name is required",BUCKET_NAME:"Bucket name is required",SERVICE_NAME:"Service name is required",NETWORK_NAME:"Network name is required",DATABASE_NAME:"Database name is required",ORGANISATION_NAME:"Organisation name is required",EMAIL:"Email is required",NAME:"Name is required",USERNAME:"Username is required",CONTAINER_NAME:"Container name is required",GROUP:"Group is required",PATTERN_NAME:"Pattern name is required",SOURCE:"Source directory is required",BUILD_COMMAND:"Build command is required",OUTPUT_DIR:"Output directory is required",FORMS_TO:"Forms recipient address is required",ROUTING_PATH:"Routing path is required",RESOURCE_REFERENCE:"Resource reference is required",RESOURCE_TYPE:"Resource type is required",VARIANT:"Variant is required",SUBTYPE:"Subtype is required",DEPLOY_TARGET:"Deploy target is required",DESTROY_TARGET:"Destroy target is required",CONNECTED_RESOURCE_NAME:"Connected resource names must not be empty"},MAX_LENGTH:{APP_NAME:"Application name must be 50 characters or less",RESOURCE_NAME:"Resource name must be 63 characters or less",BUCKET_NAME:"Bucket name must be 63 characters or less",SERVICE_NAME:"Service name must be 255 characters or less",NETWORK_NAME:"Network name must be 50 characters or less",DATABASE_NAME:"Database name must be 63 characters or less",ORGANISATION_NAME:"Organisation name must be 50 characters or less"},PORT:{INTEGER:"Port must be an integer",MIN:"Port must be at least 1",MAX:"Port cannot exceed 65535"},USERNAME:{MAX_LENGTH:"Username cannot exceed 63 characters"},LAMBDA:{MEMORY:{INTEGER:"Lambda memory must be an integer",MIN:"Memory must be at least 128 MB",MAX:"Memory cannot exceed 10240 MB",MULTIPLE:"Memory must be 128 MB or a multiple of 64 MB"},TIMEOUT:{INTEGER:"Timeout must be an integer",MIN:"Timeout must be at least 1 second",MAX:"Timeout cannot exceed 900 seconds"},RUNTIME:"Lambda runtime must contain only letters, digits, dots, underscores, or dashes (e.g. 'NODEJS_20_X' or 'nodejs20.x')"},ENV_VAR_NAME:"Environment variable names must start with a letter or underscore and contain only letters, digits, and underscores",PRIORITY:{INTEGER:"Priority must be an integer",MIN:"Priority must be at least 1",MAX:"Priority cannot exceed 50000"},CAPACITY:{MIN:{INTEGER:"Minimum capacity must be an integer",MIN_0:"Minimum capacity must be at least 0",MIN_1:"Minimum capacity must be at least 1",MAX:"Minimum capacity cannot exceed 100"},MAX:{INTEGER:"Maximum capacity must be an integer",MIN_0:"Maximum capacity must be at least 0",MIN_1:"Maximum capacity must be at least 1",MAX:"Maximum capacity cannot exceed 100"},DESIRED:{INTEGER:"Desired count must be an integer",MIN:"Desired count must be at least 0",MAX:"Desired count cannot exceed 100"},WARM_POOL_REQUIRED:"minCapacity 0 requires a warmPool \u2014 without it, new tasks wait 60-90s for a cold instance launch",WARM_POOL:{MIN_SIZE:{INTEGER:"Warm pool minSize must be an integer",MIN:"Warm pool minSize must be at least 0",MAX:"Warm pool minSize cannot exceed 100"},MIN_SIZE_EXCEEDS_MAX_CAPACITY:"warmPool.minSize cannot exceed maxCapacity \u2014 the warm pool cannot hold more instances than the ASG allows"}},MEMORY_LIMIT:{INTEGER:"Memory limit must be an integer",MIN_512:"Memory limit must be at least 512 MiB",MIN_128:"Memory limit must be at least 128 MiB",MAX:"Memory limit cannot exceed 30720 MiB"},DATABASE:{PORT:{INTEGER:"Database port must be an integer",MIN:"Database port must be at least 1024",MAX:"Database port cannot exceed 65535"},NAME:{REQUIRED:"Database name is required",MAX_LENGTH:"Database name must be 63 characters or less"}},CLICKHOUSE_STORAGE:{INTEGER:"ClickHouse storage must be a whole number of GiB",MIN:`ClickHouse storage must be at least ${100} GiB`,MAX:`ClickHouse storage cannot exceed ${16384} GiB (the gp3 ceiling)`},CLICKHOUSE_IOPS:{INTEGER:"ClickHouse iops must be a whole number",MIN:`ClickHouse iops must be at least ${3e3} (the gp3 baseline)`,MAX:`ClickHouse iops cannot exceed ${8e4} (the gp3 ceiling)`},CLICKHOUSE_THROUGHPUT:{INTEGER:"ClickHouse throughputMbps must be a whole number of MiB/s",MIN:`ClickHouse throughputMbps must be at least ${125} MiB/s (the gp3 baseline)`,MAX:`ClickHouse throughputMbps cannot exceed ${2e3} MiB/s (the gp3 ceiling)`},BACKUP_RETENTION:{INTEGER:"Backup retention must be an integer",MIN:"Backup retention must be at least 1 day",MAX:"Backup retention cannot exceed 35 days (the RDS automated-backup ceiling)"},CLICKHOUSE_BACKUP_RETENTION:{INTEGER:"ClickHouse backup retention must be an integer number of days",MIN:`ClickHouse backup retention must be at least ${1} day`,MAX:`ClickHouse backup retention cannot exceed ${3650} days`},SQS:{VISIBILITY_TIMEOUT:{INTEGER:"Visibility timeout must be an integer",MIN:"Visibility timeout must be at least 0 seconds",MAX:"Visibility timeout cannot exceed 43200 seconds (12 hours)"},RETENTION_PERIOD:{INTEGER:"Retention period must be an integer",MIN:"Retention period must be at least 60 seconds",MAX:"Retention period cannot exceed 1209600 seconds (14 days)"}},READER:{COUNT:{INTEGER:"Reader count must be an integer",MIN:"Reader count must be at least 0",MAX:"Reader count cannot exceed 15"}},IDENTIFIER_SUFFIX:{REQUIRED:"Identifier suffix is required when specified",MAX_LENGTH:"Identifier suffix cannot exceed 50 characters"},ROTATION:{INTEGER:"Rotation days must be an integer",MIN:"Rotation interval must be at least 1 day",MAX:"Rotation interval cannot exceed 365 days"},MAX_CONNECTIONS:{INTEGER:"Max connections must be an integer",MIN:"Max connections must be at least 1",MAX:"Max connections cannot exceed 100"},MONITORING_INTERVAL:{INTEGER:"Monitoring interval must be an integer",MIN:"Monitoring interval must be at least 0",MAX:"Monitoring interval cannot exceed 60 seconds",VALUES:"Monitoring interval must be 0, 1, 5, 10, 15, 30, or 60 seconds"},RETENTION_DAYS:{INTEGER:"Retention days must be an integer",MIN:"Retention days must be at least 1",MAX:"Retention days cannot exceed 365"},BATCH_SIZE:{INTEGER:"Batch size must be an integer",MIN:"Batch size must be at least 1",MAX:"Batch size cannot exceed 10000"},SERVICE:{UNIQUE_WITHIN_CLUSTER:"Service names must be unique within a cluster",MIN_REQUIRED:"At least one service is required",ROUTING_REQUIRED:"Multiple services with ports require routing config (path or host)"},PROXY_CONFIG:{MAX_IDLE_CONNECTIONS:{INTEGER:"Max idle connections must be an integer",MIN:"Max idle connections must be at least 0",MAX:"Max idle connections cannot exceed 100"},BORROW_TIMEOUT:{INTEGER:"Connection borrow timeout must be an integer",MIN:"Connection borrow timeout must be at least 1 second",MAX:"Connection borrow timeout cannot exceed 3600 seconds"}},MAX_AZS:{INTEGER:"Max AZs must be an integer",MIN:"Max AZs must be at least 1",MAX:"Max AZs cannot exceed 3"},BATCHING_WINDOW:{INTEGER:"Max batching window must be an integer",MIN:"Max batching window must be at least 0",MAX:"Max batching window cannot exceed 300 seconds"},HEALTH_CHECK:{INTERVAL:{INTEGER:"Health check interval must be an integer",MIN:"Health check interval must be at least 5 seconds",MAX:"Health check interval cannot exceed 300 seconds"},TIMEOUT:{INTEGER:"Health check timeout must be an integer",MIN:"Health check timeout must be at least 2 seconds",MAX:"Health check timeout cannot exceed 60 seconds"},RETRIES:{INTEGER:"Health check retries must be an integer",MIN:"Health check retries must be at least 1",MAX:"Health check retries cannot exceed 10"},START_PERIOD:{INTEGER:"Health check start period must be an integer",MIN:"Health check start period must be at least 0 seconds",MAX:"Health check start period cannot exceed 300 seconds"}},EPHEMERAL_STORAGE:{INTEGER:"Ephemeral storage size must be an integer",MIN:"Ephemeral storage size must be at least 512 MB",MAX:"Ephemeral storage size cannot exceed 10240 MB"},MAX_MESSAGE_SIZE:{INTEGER:"Max message size must be an integer",MIN:"Max message size must be at least 1024 bytes",MAX:"Max message size cannot exceed 262144 bytes (256 KB)"},CAPACITY_CONSTRAINT:{MIN_LTE_MAX:"minCapacity must be less than or equal to maxCapacity"},DIRECT_ACCESS:{NO_DOMAIN:"directAccess cannot be used with domain (no ALB for HTTPS)",NO_LOAD_BALANCER:"directAccess cannot be used with loadBalancer (mutually exclusive)"},GLOBAL_AURORA:{PRIMARY_REGION_REQUIRED:"primaryRegion is required for GlobalAurora databases"},NAT_GATEWAY:{INTEGER:"NAT gateway count must be an integer",MIN:"NAT gateway count must be at least 0",MAX:"NAT gateway count cannot exceed 3"},CIDR_MASK:{INTEGER:"CIDR mask must be an integer",MIN:"CIDR mask must be at least 16",MAX:"CIDR mask cannot exceed 28"},CPU:{INTEGER:"CPU must be an integer",MIN:"CPU must be at least 256 units",MAX:"CPU cannot exceed 4096 units"},KMS:{KEY_REQUIRED:"KMS key ARN is required when using KMS encryption"},READER_INSTANCES:{MAX:"Cannot have more than 15 reader instances",COUNT_OR_INSTANCES:"Cannot specify both 'count' and 'instances' - use one or the other"},GENERATOR_CAPACITY:{MIN:{MIN:"Minimum capacity must be at least 1",MAX:"Minimum capacity cannot exceed 1000"},MAX:{MIN:"Maximum capacity must be at least 1",MAX:"Maximum capacity cannot exceed 1000"}},INSTANCE_TYPE:"Unknown instance type. Common types include: t4g.micro, t4g.small, m5.large",ARCHITECTURE_MISMATCH:"Architecture mismatch between instance type and AMI",ALLOCATED_STORAGE:{INTEGER:"Allocated storage must be an integer",MIN:"Allocated storage must be at least 20 GB",MAX:"Allocated storage cannot exceed 65536 GB"},DLQ:{MAX_RECEIVE_COUNT:{INTEGER:"Max receive count must be an integer",MIN:"Max receive count must be at least 1",MAX:"Max receive count cannot exceed 1000"}},ALARM:{PERCENTAGE:{MIN:"Threshold must be at least 1%",MAX:"Threshold must be at most 100%"},FREE_STORAGE_GIB:{MIN:"Free storage threshold must be at least 1 GiB"},RESPONSE_TIME_MS:{MIN:"Response-time threshold must be at least 1 ms"}},REGION:"Invalid AWS region",PASCAL_CASE:"Resource name must start with an uppercase letter and contain only alphanumerics (PascalCase).",IMAGE_DOCKER_MUTEX:"image and docker are mutually exclusive",AWS_ACCOUNT_ID:"AWS account id must be exactly 12 digits (no hyphens)",VPC_ID:"VPC id must look like vpc-abc12345",ROLE_ARN:"Role ARN must have the form arn:aws:iam::<account-id>:role/<name>",CIDR:"CIDR must be in dotted-quad/prefix-length form (e.g. 10.0.0.0/16)",VPC_PEER:{MIN_REQUESTER_ACCOUNTS:"At least one requester account id is required",REGION_REQUIRED:"Peer region is required when specified",ROUTE_TABLE_ID_REQUIRED:"Route table id must not be empty"},SCHEDULE_EXPRESSION:"Schedule expression must be 'rate(N minute|minutes|hour|hours|day|days)' with N>=1, or 'cron(<6-field AWS expression>)'"});var oZ=Object.defineProperty,Sr=(e,t)=>oZ(e,"name",{value:t,configurable:!0}),sZ=["us-east-2","us-west-2","us-east-1","eu-west-1","eu-central-1","ap-southeast-1"],cZ=Object.freeze(sZ.flatMap(e=>{let t=Fo(e);return t?[t]:[]})),ax=Object.freeze(["us-east-2","us-west-2","us-east-1","eu-west-1","ap-southeast-1"]);function Sf(e){return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}Sr(Sf,"parseRegionList");function ox(e){return Rn.includes(e)}Sr(ox,"isValidRegion");function sx(e){return/^[a-z]{2}-[a-z]+-[1-9]$/.test(e)}Sr(sx,"isValidRegionFormat");function cx(e){if(!e)return ax.slice(0,3);let t=e.toLowerCase().split("-"),r=t[0],i=t.length>1?t[1]:"",n=[];return r&&i&&(n=Rn.filter(a=>a.startsWith(`${r}-${i}`))),n.length===0&&r&&(n=Rn.filter(a=>a.startsWith(`${r}-`))),n.length>0?n.slice(0,3):ax.slice(0,3)}Sr(cx,"getSuggestions");function lx(e){if(ox(e))return!0;let t=cx(e);return sx(e)?`Unknown region. Try: ${t.join(", ")}`:`Invalid format. Try: ${t.join(", ")}`}Sr(lx,"validateRegion");function LO(e){if(!e||e.trim()==="")return!0;let t=Sf(e);for(let r of t){let i=lx(r);if(i!==!0)return i}return!0}Sr(LO,"validateRegionList");function ux(e,t){return e.filter(r=>r!==t)}Sr(ux,"filterDuplicateRegions");function dx(e){return{label:e.city,value:e.code,description:e.optIn?`${e.code} \u2014 opt-in required`:e.code}}Sr(dx,"toRegionOption");function FO(){return hr.map(dx)}Sr(FO,"getRegionOptions");function UO(e){return hr.filter(t=>t.code!==e).map(dx)}Sr(UO,"getRegionOptionsExcluding");function zO(e){let t=hr.find(r=>r.code===e);return t?t.city:e}Sr(zO,"getRegionName");function BO(e){return t=>{let r=Sf(t);return ux(r,e)}}Sr(BO,"createRegionFormatter");var bf="29.0.0";var Ef=["Aurora","Instance","GlobalAurora","ClickHouse"],ls=["FARGATE","FARGATE_SPOT","EC2"],Vr=["standard","resilient","enterprise"],Af=["tinkerer","lightweight","standard","resilient","enterprise"],px="custom",kl=[...Af,px];var lZ=Object.defineProperty,uZ=(e,t)=>lZ(e,"name",{value:t,configurable:!0}),zle=Object.freeze({RESOURCE_SUFFIXES:Object.freeze({storage:"Storage",database:"Database",cluster:"Cluster",function:"Function",instance:"Instance",compute:"Compute"})}),wl=["ecs","lambda","ec2"],Pl=Object.freeze({ECS:"ecs",LAMBDA:"lambda",EC2:"ec2"}),_f=["code","container"],xf=Object.freeze({CODE:"code",CONTAINER:"container"}),Tf=["ARM_64","X86_64"],GO="ARM_64",Rl=["NONE","AWS_IAM"],Cf=["public","internal"],If=["CPU","MEMORY"],ga=["messaging","compute"],Df=["ARM","STANDARD"],mx=["Instance","Aurora"],us=["postgresql","mysql"],Ol=["web","worker"],VO=["foundation","compliance","hardened"];var Nf=["t3.nano","t3.micro","t3.small","t3.medium","t3.large","t3.xlarge","t3.2xlarge","t3a.nano","t3a.micro","t3a.small","t3a.medium","t3a.large","t3a.xlarge","t3a.2xlarge","t4g.nano","t4g.micro","t4g.small","t4g.medium","t4g.large","t4g.xlarge","t4g.2xlarge","c5.large","c5.xlarge","c5.2xlarge","c5.4xlarge","c5.9xlarge","c5.12xlarge","c5.18xlarge","c5.24xlarge","c5a.large","c5a.xlarge","c5a.2xlarge","c5a.4xlarge","c5a.8xlarge","c5a.12xlarge","c5a.16xlarge","c5a.24xlarge","c6g.medium","c6g.large","c6g.xlarge","c6g.2xlarge","c6g.4xlarge","c6g.8xlarge","c6g.12xlarge","c6g.16xlarge","r5.large","r5.xlarge","r5.2xlarge","r5.4xlarge","r5.8xlarge","r5.12xlarge","r5.16xlarge","r5.24xlarge","r5a.large","r5a.xlarge","r5a.2xlarge","r5a.4xlarge","r5a.8xlarge","r5a.12xlarge","r5a.16xlarge","r5a.24xlarge","r6g.medium","r6g.large","r6g.xlarge","r6g.2xlarge","r6g.4xlarge","r6g.8xlarge","r6g.12xlarge","r6g.16xlarge","i3.large","i3.xlarge","i3.2xlarge","i3.4xlarge","i3.8xlarge","i3.16xlarge","p3.2xlarge","p3.8xlarge","p3.16xlarge","g4dn.xlarge","g4dn.2xlarge","g4dn.4xlarge","g4dn.8xlarge","g4dn.12xlarge","g4dn.16xlarge","m5.large","m5.xlarge","m5.2xlarge","m5.4xlarge","m5.8xlarge","m5.12xlarge","m5.16xlarge","m5.24xlarge","m5a.large","m5a.xlarge","m5a.2xlarge","m5a.4xlarge","m5a.8xlarge","m5a.12xlarge","m5a.16xlarge","m5a.24xlarge"],WO=[0,1,5,10,15,30,60];function Ft(e,t){return e.includes(t)}uZ(Ft,"constIncludes");var KO=1,ZO=65535,Kle=Object.freeze({postgresql:5432,mysql:3306}),HO=128,JO=10240,kf=1,wf=900,fx=1,hx=1e3,ds=100,XO=100;var qO=3e3;var YO=["GET","POST","PUT","DELETE","HEAD","OPTIONS","PATCH"],QO=["standard","assets","upload","website"],ps=["AES256","KMS"];var dZ=Object.defineProperty,$l=(e,t)=>dZ(e,"name",{value:t,configurable:!0}),Ut=$l(e=>c.union([c.literal(!1),e]),"optionalOrDisabled"),ya={check:$l(e=>e.minCapacity!==void 0&&e.maxCapacity!==void 0?e.minCapacity<=e.maxCapacity:!0,"check"),params:{message:E.CAPACITY_CONSTRAINT.MIN_LTE_MAX,path:["maxCapacity"]}},jl=$l(e=>c.number().int(E.MEMORY_LIMIT.INTEGER).min(e,e===128?E.MEMORY_LIMIT.MIN_128:E.MEMORY_LIMIT.MIN_512).max(30720,E.MEMORY_LIMIT.MAX),"memoryLimitMiBSchema"),Se=c.string().min(1,E.REQUIRED.RESOURCE_NAME).max(63,E.MAX_LENGTH.RESOURCE_NAME).regex(he.RESOURCE_NAME,E.RESOURCE_NAME),t$=c.string().min(1,E.REQUIRED.BUCKET_NAME).max(63,E.MAX_LENGTH.BUCKET_NAME).regex(he.BUCKET_NAME,E.BUCKET_NAME),r$=c.string().min(1,E.REQUIRED.DATABASE_NAME).max(63,E.MAX_LENGTH.DATABASE_NAME).regex(he.DATABASE_NAME,E.DATABASE_NAME);function Pf(e,t=he.IDENTIFIER,r=E.IDENTIFIER){return c.string().min(2,E.IDENTIFIER_MIN_LENGTH).max(50,e).regex(t,r).refine(i=>!i.endsWith("-"),{message:E.IDENTIFIER_NO_TRAILING_HYPHEN}).refine(i=>!i.includes("--"),{message:E.IDENTIFIER_NO_CONSECUTIVE_HYPHENS})}$l(Pf,"identifierSchema");var lt=Pf(E.MAX_LENGTH.APP_NAME),Qle=Pf(E.MAX_LENGTH.APP_NAME,he.NEW_APP_NAME,E.NEW_APP_NAME),va=c.number().int(E.PORT.INTEGER).min(KO,E.PORT.MIN).max(ZO,E.PORT.MAX),St=c.object({key:c.string(),sourceText:c.string()}).strict(),pZ=c.object({__identifier:c.string()}).strict(),mZ=c.object({__expression:c.string()}).strict(),fZ=c.object({__call:c.string()}).strict(),hZ=c.union([pZ,mZ,fZ]),gZ=c.union([c.string(),c.number(),c.boolean(),hZ]),ms=c.record(c.string().regex(he.ENV_VAR_NAME,E.ENV_VAR_NAME),gZ),yZ=c.object({id:c.string(),name:c.string().optional(),arn:c.string().optional(),field:c.string().optional()}).strict().refine(e=>e.name!==void 0!=(e.arn!==void 0),{message:"secretsImport requires exactly one of `name` or `arn`."}),n$=c.record(c.string(),yZ),eue=c.record(c.string(),c.unknown()),gx=c.enum(kl).describe(`Application type must be one of: ${kl.join(", ")}`),yx=c.enum(gr).describe(`OpenNext deployment pattern: ${gr.join(", ")}`),vZ=c.enum(["before-imports","after-imports","after-app-init","after-tags","after-resource","end-of-file"]),SZ=c.enum(["import","app-init","tags","database","compute","storage","network","messaging","cdn","pattern","vpc-peer","vpc-peer-accepter","cross-plan-connection","custom"]),i$=c.object({sourceText:c.string(),position:vZ,afterManagedResource:c.object({type:SZ,name:c.string().optional()}).strict().optional(),originalLine:c.number().int().optional(),leadingComments:c.array(c.string()).optional(),orphaned:c.boolean().optional(),orphanedComment:c.string().optional()}).strict(),a$=c.union([c.object({tier:c.enum(Vr)}).strict(),c.literal(!1)]),o$=c.union([c.object({instanceType:c.string().optional()}).strict(),c.literal(!1)]),bZ=Pf(E.MAX_LENGTH.ORGANISATION_NAME),EZ=c.string().regex(he.EMAIL,E.EMAIL),e$=c.string().refine(e=>Rn.includes(e),{message:E.REGION}),s$=c.object({name:bZ,email:EZ,accountName:c.string().optional(),primaryRegion:e$.optional().default(Lo),secondaryRegions:c.array(e$).optional(),security:c.enum(VO).optional(),force:c.boolean().optional()}).strict();function Ml(e){return e.issues.map(t=>`${t.path.length>0?`${t.path.join(".")}: `:""}${t.message}`).join(`
312
+ `)}getConsolePrefix(t){switch(t){case"error":return"[ERROR]";case"warn":return"[WARN]";case"info":return"[INFO]";case"debug":return"[DEBUG]";case"trace":return"[TRACE]"}}error(t,r,i){this.log("error",t,r,i)}warn(t,r,i){this.log("warn",t,r,i)}info(t,r,i){this.log("info",t,r,i)}debug(t,r,i){this.log("debug",t,r,i)}trace(t,r,i){this.log("trace",t,r,i)}diagnostic(t,r,i,n){this.log(t,r,i,n),!this.debugEnabled&&V_()&&(zn[t]<zn.info||this.writeStderrLine(this.createEntry(t,r,i,n)))}isDebugEnabled(){return this.debugEnabled}isTraceEnabled(){return this.traceEnabled}enableDebug(){this.debugEnabled=!0,zn[this.minLevel]>zn.debug&&(this.minLevel="debug"),this.fileWriter.setDebugEnabled(!0),this.fileWriter.isInitialised&&this.fileWriter.initialiseDebugStream()}withCorrelation(t){return new is(this,t)}forDeployment(t,r="deploy"){return new Nl(this,t,r)}close(){this.fileWriter.close()}async flushAndClose(){await this.fileWriter.closeAndFlush()}getLogPath(){return this.mainLogPath}getDebugLogPath(){return this.debugLogPath}getLogDir(){return this.config.logDir}logWithCorrelation(t,r,i,n,a,o,s){this.log(t,r,i,a,n,o,s)}static reset(){e.instance&&(e.instance.close(),e.instance=null)}};var Ei=yf.getInstance();var FK=Object.defineProperty,ct=(e,t)=>FK(e,"name",{value:t,configurable:!0}),ss="fjall";function ha(e,t){let r=UK(e);if(r.includes("..")||r.startsWith("/"))throw new Error(`Invalid ${t}: path traversal is not allowed`)}ct(ha,"assertNoTraversal");function zK(){return ss}ct(zK,"getFjallPath");function BK(e){let t=xO(e);return xO(t)||"."}ct(BK,"getProjectRoot");function IO(e){if(!CO(e))throw new Error(`Infrastructure file not found: ${e}`);let t=TO(e,"utf-8"),r=DO(t);if(r===void 0)throw new Error(`Could not find appName in infrastructure file: ${e}. Expected format: const appName = "yourAppName";`);return r}ct(IO,"getAppNameFromInfrastructure");function DO(e){return e.match(/const\s+appName\s*=\s*["']([^"']+)["']/)?.[1]}ct(DO,"parseAppNameFromInfrastructureContent");function GK(e){if(!CO(e))return;let t;try{t=TO(e,"utf-8")}catch(r){Ei.debug("PathHelpers","Could not read organisation infrastructure",{error:le(ze(r))});return}return t.match(/organisationName:\s*(["'])(.+?)\1/)?.[2]}ct(GK,"readOrganisationNameFromInfrastructure");function VK(e){let t=vr(e,H_);return IO(t)}ct(VK,"getAppName");function WK(e){return ha(e,"app name"),vr(ss,e,H_)}ct(WK,"getInfrastructurePath");function vf(e){return ha(e,"app name"),vr(ss,e)}ct(vf,"getAppPath");function NO(e,t){let r=e??process.cwd();return t===void 0?r:(ha(t,"container"),vr(r,t))}ct(NO,"resolveScaffoldRootDir");function KK(e,t,r){return vr(NO(t,r),vf(e))}ct(KK,"resolveAppScaffoldPath");function K_(e){return ha(e,"component name"),vr(ss,e)}ct(K_,"getOrganisationComponentPath");function ZK(e){return ha(e,"deployment type"),vr(ss,e,"logs")}ct(ZK,"getDeploymentLogsPath");function kO(){return vr(ss,"domains")}ct(kO,"getDomainsDir");function Z_(e){return ha(e,"domain name"),vr(kO(),e)}ct(Z_,"getDomainComponentPath");function HK(e){return vr(Z_(e),H_)}ct(HK,"getDomainInfrastructurePath");function JK(e){return vr(Z_(e),XK)}ct(JK,"getDomainZoneFilePath");var H_="infrastructure.ts",XK="zone.bind",qK="cdk.out";function YK(e){return vr(e,qK)}ct(YK,"getCdkOutPath");var QK=Object.defineProperty,eZ=(e,t)=>QK(e,"name",{value:t,configurable:!0}),tZ=import.meta.dirname;function J_(e,t,r,i){let n=wO(tZ,"..","shared","files"),a=t.includes("/")?t:vf(t);yc(e,n,a,r,i),gc(e,wO(a,".gitignore"),ll,i)}eZ(J_,"copySharedCdkFiles");var rZ=Object.defineProperty,cs=(e,t)=>rZ(e,"name",{value:t,configurable:!0});function PO(e){return e.success===!0}cs(PO,"isSuccess");function RO(e){return e.success===!1}cs(RO,"isFailure");function K(e){return{success:!0,data:e}}cs(K,"success");function j(e){return{success:!1,error:e}}cs(j,"failure");async function OO(e){try{let t=await e();return K(t)}catch(t){return j(yi(t))}}cs(OO,"tryAsync");function $O(e){try{let t=e();return K(t)}catch(t){return j(yi(t))}}cs($O,"trySync");var nZ=Object.defineProperty,iZ=(e,t)=>nZ(e,"name",{value:t,configurable:!0}),jO=/^[a-zA-Z][a-zA-Z0-9-]*$/,aZ=rl.source.replace(/^\^|\$$/g,""),he=Object.freeze({IDENTIFIER:jO,NEW_APP_NAME:/^[a-z][a-z0-9-]*$/,RESOURCE_NAME:/^[a-zA-Z][a-zA-Z0-9]*$/,ECS_SERVICE_NAME:jO,BUCKET_NAME:/^[a-z][a-z0-9-]*[a-z0-9]$|^[a-z][a-z0-9]*$/,DATABASE_NAME:/^[a-zA-Z][a-zA-Z0-9_]*$/,RESOURCE_TYPE:/^[a-z]+(:[a-z]+)?$/,SSM_PATH:new RegExp(`^(?:/${aZ})+$`),SECRET_NAME:Im,SSM_COMPONENT:rl,EMAIL:/^[^\s@]+@[^\s@]+\.[^\s@]+$/,DOCKER_IMAGE:/^[a-z0-9][a-z0-9._-]*[a-z0-9](:[a-z0-9._-]+)?$/,DOMAIN:/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/i,HTTP_ORIGIN:/^https?:\/\/[a-z0-9.-]+(:\d+)?$/i,PASCAL_CASE:/^[A-Z][A-Za-z0-9]*$/,AWS_ACCOUNT_ID:/^\d{12}$/,VPC_ID:/^vpc-[a-z0-9]+$/,ROLE_ARN:/^arn:aws[a-zA-Z-]*:iam::\d{12}:role\/.+$/,CIDR:/^((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\/(3[0-2]|[12]?\d)$/,SCHEDULE_EXPRESSION:/^(rate\(1 (?:minute|hour|day)\)|rate\((?:[2-9]|[1-9]\d+) (?:minutes|hours|days)\)|cron\([^\s()]+ [^\s()]+ [^\s()]+ [^\s()]+ [^\s()]+ [^\s()]+\))$/,LAMBDA_RUNTIME_IDENTIFIER:/^[A-Za-z0-9._-]+$/,ENV_VAR_NAME:/^[A-Za-z_][A-Za-z0-9_]*$/});function X_(e){let t=/^rate\((\d+) (minute|minutes|hour|hours|day|days)\)$/.exec(e);if(!t)return;let r=t[1],i=t[2];if(r===void 0||i===void 0)return;let n=parseInt(r,10);if(!Number.isFinite(n)||n<1)return;let a=i==="minute"||i==="hour"||i==="day";if(!(a&&n!==1)&&!(!a&&n===1))return i==="minute"||i==="minutes"?{everyMs:n*6e4}:i==="hour"||i==="hours"?{everyMs:n*60*6e4}:{everyMs:n*24*60*6e4}}iZ(X_,"parseRateExpression");var MO=["t4g.medium","m7g.medium","m8g.medium","r7g.medium","r8g.medium","m7g.large","m8g.large","r7g.large","r8g.large","m7g.xlarge","m8g.xlarge","r7g.xlarge","r8g.xlarge"];var E=Object.freeze({IDENTIFIER:"Must start with a letter, contain only letters, numbers, and hyphens",NEW_APP_NAME:"Must start with a lowercase letter and contain only lowercase letters, numbers, and hyphens",IDENTIFIER_MIN_LENGTH:"Must be at least 2 characters",IDENTIFIER_NO_TRAILING_HYPHEN:"Must not end with a hyphen",IDENTIFIER_NO_CONSECUTIVE_HYPHENS:"Must not contain consecutive hyphens",RESOURCE_NAME:"Must start with a letter and contain only letters and numbers (PascalCase recommended)",ECS_SERVICE_NAME:"Service name must start with a letter and contain only letters, numbers, and hyphens",BUCKET_NAME:"Bucket name must start with a lowercase letter and contain only lowercase letters, numbers, and hyphens",DATABASE_NAME:"Database name must start with a letter and contain only letters, numbers, and underscores",RESOURCE_TYPE:"Resource type must be in format 'category' or 'category:type'",SSM_PATH:"SSM path must start with / and contain valid namespace segments (e.g., /myapp/ApiCluster/service)",SECRET_NAME:gA,SSM_COMPONENT:Dm,EMAIL:"Please enter a valid email address",DOMAIN:"Please enter a valid domain (e.g., cms.example.com)",DOCKER_IMAGE:"Invalid Docker image name format",REQUIRED:{APP_NAME:"Application name is required",RESOURCE_NAME:"Resource name is required",BUCKET_NAME:"Bucket name is required",SERVICE_NAME:"Service name is required",NETWORK_NAME:"Network name is required",DATABASE_NAME:"Database name is required",ORGANISATION_NAME:"Organisation name is required",EMAIL:"Email is required",NAME:"Name is required",USERNAME:"Username is required",CONTAINER_NAME:"Container name is required",GROUP:"Group is required",PATTERN_NAME:"Pattern name is required",SOURCE:"Source directory is required",BUILD_COMMAND:"Build command is required",OUTPUT_DIR:"Output directory is required",FORMS_TO:"Forms recipient address is required",ROUTING_PATH:"Routing path is required",RESOURCE_REFERENCE:"Resource reference is required",RESOURCE_TYPE:"Resource type is required",VARIANT:"Variant is required",SUBTYPE:"Subtype is required",DEPLOY_TARGET:"Deploy target is required",DESTROY_TARGET:"Destroy target is required",CONNECTED_RESOURCE_NAME:"Connected resource names must not be empty"},MAX_LENGTH:{APP_NAME:"Application name must be 50 characters or less",RESOURCE_NAME:"Resource name must be 63 characters or less",BUCKET_NAME:"Bucket name must be 63 characters or less",SERVICE_NAME:"Service name must be 255 characters or less",NETWORK_NAME:"Network name must be 50 characters or less",DATABASE_NAME:"Database name must be 63 characters or less",ORGANISATION_NAME:"Organisation name must be 50 characters or less"},PORT:{INTEGER:"Port must be an integer",MIN:"Port must be at least 1",MAX:"Port cannot exceed 65535"},USERNAME:{MAX_LENGTH:"Username cannot exceed 63 characters"},LAMBDA:{MEMORY:{INTEGER:"Lambda memory must be an integer",MIN:"Memory must be at least 128 MB",MAX:"Memory cannot exceed 10240 MB",MULTIPLE:"Memory must be 128 MB or a multiple of 64 MB"},TIMEOUT:{INTEGER:"Timeout must be an integer",MIN:"Timeout must be at least 1 second",MAX:"Timeout cannot exceed 900 seconds"},RUNTIME:"Lambda runtime must contain only letters, digits, dots, underscores, or dashes (e.g. 'NODEJS_20_X' or 'nodejs20.x')"},ENV_VAR_NAME:"Environment variable names must start with a letter or underscore and contain only letters, digits, and underscores",PRIORITY:{INTEGER:"Priority must be an integer",MIN:"Priority must be at least 1",MAX:"Priority cannot exceed 50000"},CAPACITY:{MIN:{INTEGER:"Minimum capacity must be an integer",MIN_0:"Minimum capacity must be at least 0",MIN_1:"Minimum capacity must be at least 1",MAX:"Minimum capacity cannot exceed 100"},MAX:{INTEGER:"Maximum capacity must be an integer",MIN_0:"Maximum capacity must be at least 0",MIN_1:"Maximum capacity must be at least 1",MAX:"Maximum capacity cannot exceed 100"},DESIRED:{INTEGER:"Desired count must be an integer",MIN:"Desired count must be at least 0",MAX:"Desired count cannot exceed 100"},WARM_POOL_REQUIRED:"minCapacity 0 requires a warmPool \u2014 without it, new tasks wait 60-90s for a cold instance launch",WARM_POOL:{MIN_SIZE:{INTEGER:"Warm pool minSize must be an integer",MIN:"Warm pool minSize must be at least 0",MAX:"Warm pool minSize cannot exceed 100"},MIN_SIZE_EXCEEDS_MAX_CAPACITY:"warmPool.minSize cannot exceed maxCapacity \u2014 the warm pool cannot hold more instances than the ASG allows"}},MEMORY_LIMIT:{INTEGER:"Memory limit must be an integer",MIN_512:"Memory limit must be at least 512 MiB",MIN_128:"Memory limit must be at least 128 MiB",MAX:"Memory limit cannot exceed 30720 MiB"},DATABASE:{PORT:{INTEGER:"Database port must be an integer",MIN:"Database port must be at least 1024",MAX:"Database port cannot exceed 65535"},NAME:{REQUIRED:"Database name is required",MAX_LENGTH:"Database name must be 63 characters or less"}},CLICKHOUSE_STORAGE:{INTEGER:"ClickHouse storage must be a whole number of GiB",MIN:`ClickHouse storage must be at least ${100} GiB`,MAX:`ClickHouse storage cannot exceed ${16384} GiB (the gp3 ceiling)`},CLICKHOUSE_IOPS:{INTEGER:"ClickHouse iops must be a whole number",MIN:`ClickHouse iops must be at least ${3e3} (the gp3 baseline)`,MAX:`ClickHouse iops cannot exceed ${8e4} (the gp3 ceiling)`},CLICKHOUSE_THROUGHPUT:{INTEGER:"ClickHouse throughputMbps must be a whole number of MiB/s",MIN:`ClickHouse throughputMbps must be at least ${125} MiB/s (the gp3 baseline)`,MAX:`ClickHouse throughputMbps cannot exceed ${2e3} MiB/s (the gp3 ceiling)`},BACKUP_RETENTION:{INTEGER:"Backup retention must be an integer",MIN:"Backup retention must be at least 1 day",MAX:"Backup retention cannot exceed 35 days (the RDS automated-backup ceiling)"},CLICKHOUSE_BACKUP_RETENTION:{INTEGER:"ClickHouse backup retention must be an integer number of days",MIN:`ClickHouse backup retention must be at least ${1} day`,MAX:`ClickHouse backup retention cannot exceed ${3650} days`},SQS:{VISIBILITY_TIMEOUT:{INTEGER:"Visibility timeout must be an integer",MIN:"Visibility timeout must be at least 0 seconds",MAX:"Visibility timeout cannot exceed 43200 seconds (12 hours)"},RETENTION_PERIOD:{INTEGER:"Retention period must be an integer",MIN:"Retention period must be at least 60 seconds",MAX:"Retention period cannot exceed 1209600 seconds (14 days)"}},READER:{COUNT:{INTEGER:"Reader count must be an integer",MIN:"Reader count must be at least 0",MAX:"Reader count cannot exceed 15"}},IDENTIFIER_SUFFIX:{REQUIRED:"Identifier suffix is required when specified",MAX_LENGTH:"Identifier suffix cannot exceed 50 characters"},ROTATION:{INTEGER:"Rotation days must be an integer",MIN:"Rotation interval must be at least 1 day",MAX:"Rotation interval cannot exceed 365 days"},MAX_CONNECTIONS:{INTEGER:"Max connections must be an integer",MIN:"Max connections must be at least 1",MAX:"Max connections cannot exceed 100"},MONITORING_INTERVAL:{INTEGER:"Monitoring interval must be an integer",MIN:"Monitoring interval must be at least 0",MAX:"Monitoring interval cannot exceed 60 seconds",VALUES:"Monitoring interval must be 0, 1, 5, 10, 15, 30, or 60 seconds"},RETENTION_DAYS:{INTEGER:"Retention days must be an integer",MIN:"Retention days must be at least 1",MAX:"Retention days cannot exceed 365"},BATCH_SIZE:{INTEGER:"Batch size must be an integer",MIN:"Batch size must be at least 1",MAX:"Batch size cannot exceed 10000"},SERVICE:{UNIQUE_WITHIN_CLUSTER:"Service names must be unique within a cluster",MIN_REQUIRED:"At least one service is required",ROUTING_REQUIRED:"Multiple services with ports require routing config (path or host)"},PROXY_CONFIG:{MAX_IDLE_CONNECTIONS:{INTEGER:"Max idle connections must be an integer",MIN:"Max idle connections must be at least 0",MAX:"Max idle connections cannot exceed 100"},BORROW_TIMEOUT:{INTEGER:"Connection borrow timeout must be an integer",MIN:"Connection borrow timeout must be at least 1 second",MAX:"Connection borrow timeout cannot exceed 3600 seconds"}},MAX_AZS:{INTEGER:"Max AZs must be an integer",MIN:"Max AZs must be at least 1",MAX:"Max AZs cannot exceed 3"},BATCHING_WINDOW:{INTEGER:"Max batching window must be an integer",MIN:"Max batching window must be at least 0",MAX:"Max batching window cannot exceed 300 seconds"},HEALTH_CHECK:{INTERVAL:{INTEGER:"Health check interval must be an integer",MIN:"Health check interval must be at least 5 seconds",MAX:"Health check interval cannot exceed 300 seconds"},TIMEOUT:{INTEGER:"Health check timeout must be an integer",MIN:"Health check timeout must be at least 2 seconds",MAX:"Health check timeout cannot exceed 60 seconds"},RETRIES:{INTEGER:"Health check retries must be an integer",MIN:"Health check retries must be at least 1",MAX:"Health check retries cannot exceed 10"},START_PERIOD:{INTEGER:"Health check start period must be an integer",MIN:"Health check start period must be at least 0 seconds",MAX:"Health check start period cannot exceed 300 seconds"}},EPHEMERAL_STORAGE:{INTEGER:"Ephemeral storage size must be an integer",MIN:"Ephemeral storage size must be at least 512 MB",MAX:"Ephemeral storage size cannot exceed 10240 MB"},MAX_MESSAGE_SIZE:{INTEGER:"Max message size must be an integer",MIN:"Max message size must be at least 1024 bytes",MAX:"Max message size cannot exceed 262144 bytes (256 KB)"},CAPACITY_CONSTRAINT:{MIN_LTE_MAX:"minCapacity must be less than or equal to maxCapacity"},DIRECT_ACCESS:{NO_DOMAIN:"directAccess cannot be used with domain (no ALB for HTTPS)",NO_LOAD_BALANCER:"directAccess cannot be used with loadBalancer (mutually exclusive)"},GLOBAL_AURORA:{PRIMARY_REGION_REQUIRED:"primaryRegion is required for GlobalAurora databases"},NAT_GATEWAY:{INTEGER:"NAT gateway count must be an integer",MIN:"NAT gateway count must be at least 0",MAX:"NAT gateway count cannot exceed 3"},CIDR_MASK:{INTEGER:"CIDR mask must be an integer",MIN:"CIDR mask must be at least 16",MAX:"CIDR mask cannot exceed 28"},CPU:{INTEGER:"CPU must be an integer",MIN:"CPU must be at least 256 units",MAX:"CPU cannot exceed 4096 units"},KMS:{KEY_REQUIRED:"KMS key ARN is required when using KMS encryption"},READER_INSTANCES:{MAX:"Cannot have more than 15 reader instances",COUNT_OR_INSTANCES:"Cannot specify both 'count' and 'instances' - use one or the other"},GENERATOR_CAPACITY:{MIN:{MIN:"Minimum capacity must be at least 1",MAX:"Minimum capacity cannot exceed 1000"},MAX:{MIN:"Maximum capacity must be at least 1",MAX:"Maximum capacity cannot exceed 1000"}},INSTANCE_TYPE:"Unknown instance type. Common types include: t4g.micro, t4g.small, m5.large",ARCHITECTURE_MISMATCH:"Architecture mismatch between instance type and AMI",ALLOCATED_STORAGE:{INTEGER:"Allocated storage must be an integer",MIN:"Allocated storage must be at least 20 GB",MAX:"Allocated storage cannot exceed 65536 GB"},DLQ:{MAX_RECEIVE_COUNT:{INTEGER:"Max receive count must be an integer",MIN:"Max receive count must be at least 1",MAX:"Max receive count cannot exceed 1000"}},ALARM:{PERCENTAGE:{MIN:"Threshold must be at least 1%",MAX:"Threshold must be at most 100%"},FREE_STORAGE_GIB:{MIN:"Free storage threshold must be at least 1 GiB"},RESPONSE_TIME_MS:{MIN:"Response-time threshold must be at least 1 ms"}},REGION:"Invalid AWS region",PASCAL_CASE:"Resource name must start with an uppercase letter and contain only alphanumerics (PascalCase).",IMAGE_DOCKER_MUTEX:"image and docker are mutually exclusive",AWS_ACCOUNT_ID:"AWS account id must be exactly 12 digits (no hyphens)",VPC_ID:"VPC id must look like vpc-abc12345",ROLE_ARN:"Role ARN must have the form arn:aws:iam::<account-id>:role/<name>",CIDR:"CIDR must be in dotted-quad/prefix-length form (e.g. 10.0.0.0/16)",VPC_PEER:{MIN_REQUESTER_ACCOUNTS:"At least one requester account id is required",REGION_REQUIRED:"Peer region is required when specified",ROUTE_TABLE_ID_REQUIRED:"Route table id must not be empty"},SCHEDULE_EXPRESSION:"Schedule expression must be 'rate(N minute|minutes|hour|hours|day|days)' with N>=1, or 'cron(<6-field AWS expression>)'"});var oZ=Object.defineProperty,Sr=(e,t)=>oZ(e,"name",{value:t,configurable:!0}),sZ=["us-east-2","us-west-2","us-east-1","eu-west-1","eu-central-1","ap-southeast-1"],cZ=Object.freeze(sZ.flatMap(e=>{let t=Fo(e);return t?[t]:[]})),ax=Object.freeze(["us-east-2","us-west-2","us-east-1","eu-west-1","ap-southeast-1"]);function Sf(e){return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}Sr(Sf,"parseRegionList");function ox(e){return Rn.includes(e)}Sr(ox,"isValidRegion");function sx(e){return/^[a-z]{2}-[a-z]+-[1-9]$/.test(e)}Sr(sx,"isValidRegionFormat");function cx(e){if(!e)return ax.slice(0,3);let t=e.toLowerCase().split("-"),r=t[0],i=t.length>1?t[1]:"",n=[];return r&&i&&(n=Rn.filter(a=>a.startsWith(`${r}-${i}`))),n.length===0&&r&&(n=Rn.filter(a=>a.startsWith(`${r}-`))),n.length>0?n.slice(0,3):ax.slice(0,3)}Sr(cx,"getSuggestions");function lx(e){if(ox(e))return!0;let t=cx(e);return sx(e)?`Unknown region. Try: ${t.join(", ")}`:`Invalid format. Try: ${t.join(", ")}`}Sr(lx,"validateRegion");function LO(e){if(!e||e.trim()==="")return!0;let t=Sf(e);for(let r of t){let i=lx(r);if(i!==!0)return i}return!0}Sr(LO,"validateRegionList");function ux(e,t){return e.filter(r=>r!==t)}Sr(ux,"filterDuplicateRegions");function dx(e){return{label:e.city,value:e.code,description:e.optIn?`${e.code} \u2014 opt-in required`:e.code}}Sr(dx,"toRegionOption");function FO(){return hr.map(dx)}Sr(FO,"getRegionOptions");function UO(e){return hr.filter(t=>t.code!==e).map(dx)}Sr(UO,"getRegionOptionsExcluding");function zO(e){let t=hr.find(r=>r.code===e);return t?t.city:e}Sr(zO,"getRegionName");function BO(e){return t=>{let r=Sf(t);return ux(r,e)}}Sr(BO,"createRegionFormatter");var bf="30.0.0";var Ef=["Aurora","Instance","GlobalAurora","ClickHouse"],ls=["FARGATE","FARGATE_SPOT","EC2"],Vr=["standard","resilient","enterprise"],Af=["tinkerer","lightweight","standard","resilient","enterprise"],px="custom",kl=[...Af,px];var lZ=Object.defineProperty,uZ=(e,t)=>lZ(e,"name",{value:t,configurable:!0}),zle=Object.freeze({RESOURCE_SUFFIXES:Object.freeze({storage:"Storage",database:"Database",cluster:"Cluster",function:"Function",instance:"Instance",compute:"Compute"})}),wl=["ecs","lambda","ec2"],Pl=Object.freeze({ECS:"ecs",LAMBDA:"lambda",EC2:"ec2"}),_f=["code","container"],xf=Object.freeze({CODE:"code",CONTAINER:"container"}),Tf=["ARM_64","X86_64"],GO="ARM_64",Rl=["NONE","AWS_IAM"],Cf=["public","internal"],If=["CPU","MEMORY"],ga=["messaging","compute"],Df=["ARM","STANDARD"],mx=["Instance","Aurora"],us=["postgresql","mysql"],Ol=["web","worker"],VO=["foundation","compliance","hardened"];var Nf=["t3.nano","t3.micro","t3.small","t3.medium","t3.large","t3.xlarge","t3.2xlarge","t3a.nano","t3a.micro","t3a.small","t3a.medium","t3a.large","t3a.xlarge","t3a.2xlarge","t4g.nano","t4g.micro","t4g.small","t4g.medium","t4g.large","t4g.xlarge","t4g.2xlarge","c5.large","c5.xlarge","c5.2xlarge","c5.4xlarge","c5.9xlarge","c5.12xlarge","c5.18xlarge","c5.24xlarge","c5a.large","c5a.xlarge","c5a.2xlarge","c5a.4xlarge","c5a.8xlarge","c5a.12xlarge","c5a.16xlarge","c5a.24xlarge","c6g.medium","c6g.large","c6g.xlarge","c6g.2xlarge","c6g.4xlarge","c6g.8xlarge","c6g.12xlarge","c6g.16xlarge","r5.large","r5.xlarge","r5.2xlarge","r5.4xlarge","r5.8xlarge","r5.12xlarge","r5.16xlarge","r5.24xlarge","r5a.large","r5a.xlarge","r5a.2xlarge","r5a.4xlarge","r5a.8xlarge","r5a.12xlarge","r5a.16xlarge","r5a.24xlarge","r6g.medium","r6g.large","r6g.xlarge","r6g.2xlarge","r6g.4xlarge","r6g.8xlarge","r6g.12xlarge","r6g.16xlarge","i3.large","i3.xlarge","i3.2xlarge","i3.4xlarge","i3.8xlarge","i3.16xlarge","p3.2xlarge","p3.8xlarge","p3.16xlarge","g4dn.xlarge","g4dn.2xlarge","g4dn.4xlarge","g4dn.8xlarge","g4dn.12xlarge","g4dn.16xlarge","m5.large","m5.xlarge","m5.2xlarge","m5.4xlarge","m5.8xlarge","m5.12xlarge","m5.16xlarge","m5.24xlarge","m5a.large","m5a.xlarge","m5a.2xlarge","m5a.4xlarge","m5a.8xlarge","m5a.12xlarge","m5a.16xlarge","m5a.24xlarge"],WO=[0,1,5,10,15,30,60];function Ft(e,t){return e.includes(t)}uZ(Ft,"constIncludes");var KO=1,ZO=65535,Kle=Object.freeze({postgresql:5432,mysql:3306}),HO=128,JO=10240,kf=1,wf=900,fx=1,hx=1e3,ds=100,XO=100;var qO=3e3;var YO=["GET","POST","PUT","DELETE","HEAD","OPTIONS","PATCH"],QO=["standard","assets","upload","website"],ps=["AES256","KMS"];var dZ=Object.defineProperty,$l=(e,t)=>dZ(e,"name",{value:t,configurable:!0}),Ut=$l(e=>c.union([c.literal(!1),e]),"optionalOrDisabled"),ya={check:$l(e=>e.minCapacity!==void 0&&e.maxCapacity!==void 0?e.minCapacity<=e.maxCapacity:!0,"check"),params:{message:E.CAPACITY_CONSTRAINT.MIN_LTE_MAX,path:["maxCapacity"]}},jl=$l(e=>c.number().int(E.MEMORY_LIMIT.INTEGER).min(e,e===128?E.MEMORY_LIMIT.MIN_128:E.MEMORY_LIMIT.MIN_512).max(30720,E.MEMORY_LIMIT.MAX),"memoryLimitMiBSchema"),Se=c.string().min(1,E.REQUIRED.RESOURCE_NAME).max(63,E.MAX_LENGTH.RESOURCE_NAME).regex(he.RESOURCE_NAME,E.RESOURCE_NAME),t$=c.string().min(1,E.REQUIRED.BUCKET_NAME).max(63,E.MAX_LENGTH.BUCKET_NAME).regex(he.BUCKET_NAME,E.BUCKET_NAME),r$=c.string().min(1,E.REQUIRED.DATABASE_NAME).max(63,E.MAX_LENGTH.DATABASE_NAME).regex(he.DATABASE_NAME,E.DATABASE_NAME);function Pf(e,t=he.IDENTIFIER,r=E.IDENTIFIER){return c.string().min(2,E.IDENTIFIER_MIN_LENGTH).max(50,e).regex(t,r).refine(i=>!i.endsWith("-"),{message:E.IDENTIFIER_NO_TRAILING_HYPHEN}).refine(i=>!i.includes("--"),{message:E.IDENTIFIER_NO_CONSECUTIVE_HYPHENS})}$l(Pf,"identifierSchema");var lt=Pf(E.MAX_LENGTH.APP_NAME),Qle=Pf(E.MAX_LENGTH.APP_NAME,he.NEW_APP_NAME,E.NEW_APP_NAME),va=c.number().int(E.PORT.INTEGER).min(KO,E.PORT.MIN).max(ZO,E.PORT.MAX),St=c.object({key:c.string(),sourceText:c.string()}).strict(),pZ=c.object({__identifier:c.string()}).strict(),mZ=c.object({__expression:c.string()}).strict(),fZ=c.object({__call:c.string()}).strict(),hZ=c.union([pZ,mZ,fZ]),gZ=c.union([c.string(),c.number(),c.boolean(),hZ]),ms=c.record(c.string().regex(he.ENV_VAR_NAME,E.ENV_VAR_NAME),gZ),yZ=c.object({id:c.string(),name:c.string().optional(),arn:c.string().optional(),field:c.string().optional()}).strict().refine(e=>e.name!==void 0!=(e.arn!==void 0),{message:"secretsImport requires exactly one of `name` or `arn`."}),n$=c.record(c.string(),yZ),eue=c.record(c.string(),c.unknown()),gx=c.enum(kl).describe(`Application type must be one of: ${kl.join(", ")}`),yx=c.enum(gr).describe(`OpenNext deployment pattern: ${gr.join(", ")}`),vZ=c.enum(["before-imports","after-imports","after-app-init","after-tags","after-resource","end-of-file"]),SZ=c.enum(["import","app-init","tags","database","compute","storage","network","messaging","cdn","pattern","vpc-peer","vpc-peer-accepter","cross-plan-connection","custom"]),i$=c.object({sourceText:c.string(),position:vZ,afterManagedResource:c.object({type:SZ,name:c.string().optional()}).strict().optional(),originalLine:c.number().int().optional(),leadingComments:c.array(c.string()).optional(),orphaned:c.boolean().optional(),orphanedComment:c.string().optional()}).strict(),a$=c.union([c.object({tier:c.enum(Vr)}).strict(),c.literal(!1)]),o$=c.union([c.object({instanceType:c.string().optional()}).strict(),c.literal(!1)]),bZ=Pf(E.MAX_LENGTH.ORGANISATION_NAME),EZ=c.string().regex(he.EMAIL,E.EMAIL),e$=c.string().refine(e=>Rn.includes(e),{message:E.REGION}),s$=c.object({name:bZ,email:EZ,accountName:c.string().optional(),primaryRegion:e$.optional().default(Lo),secondaryRegions:c.array(e$).optional(),security:c.enum(VO).optional(),force:c.boolean().optional()}).strict();function Ml(e){return e.issues.map(t=>`${t.path.length>0?`${t.path.join(".")}: `:""}${t.message}`).join(`
313
313
  `)}$l(Ml,"getZodErrorMessage");var Rf=c.number().min(1,E.ALARM.PERCENTAGE.MIN).max(100,E.ALARM.PERCENTAGE.MAX),vx=c.union([Rf,c.literal(!1)]),AZ=c.union([c.number().min(1,E.ALARM.RESPONSE_TIME_MS.MIN),c.literal(!1)]),_Z=c.number().min(1,E.ALARM.FREE_STORAGE_GIB.MIN),c$=c.union([c.literal(!1),c.object({cpuThreshold:vx.optional(),memoryThreshold:vx.optional(),runningTasksMinimum:c.number().int().min(0).optional(),http5xxThreshold:vx.optional(),p99ResponseTimeThresholdMs:AZ.optional()}).strict()]),l$=c.union([c.literal(!1),c.object({cpuThreshold:Rf.optional(),freeStorageThresholdGiB:_Z.optional(),connectionsThreshold:c.number().int().min(1).optional()}).strict()]),u$=c.union([c.literal(!1),c.object({errorRateThreshold:Rf.optional(),durationThresholdPercent:Rf.optional()}).strict()]);var Sa=c.number().int(E.BACKUP_RETENTION.INTEGER).min(1,E.BACKUP_RETENTION.MIN).max(35,E.BACKUP_RETENTION.MAX),d$=c.number().int(E.CLICKHOUSE_STORAGE.INTEGER).min(100,E.CLICKHOUSE_STORAGE.MIN).max(16384,E.CLICKHOUSE_STORAGE.MAX),p$=c.number().int(E.CLICKHOUSE_IOPS.INTEGER).min(3e3,E.CLICKHOUSE_IOPS.MIN).max(8e4,E.CLICKHOUSE_IOPS.MAX),m$=c.number().int(E.CLICKHOUSE_THROUGHPUT.INTEGER).min(125,E.CLICKHOUSE_THROUGHPUT.MIN).max(2e3,E.CLICKHOUSE_THROUGHPUT.MAX),xZ=c.enum(MO),f$=c.number().int(E.CLICKHOUSE_BACKUP_RETENTION.INTEGER).min(1,E.CLICKHOUSE_BACKUP_RETENTION.MIN).max(3650,E.CLICKHOUSE_BACKUP_RETENTION.MAX),Ll=c.number().int(E.MONITORING_INTERVAL.INTEGER).refine(e=>Ft(WO,e),{message:E.MONITORING_INTERVAL.VALUES}),$f=c.number().int(E.DATABASE.PORT.INTEGER).min(1024,E.DATABASE.PORT.MIN).max(65535,E.DATABASE.PORT.MAX),TZ=c.enum(Ef).describe(`Database type must be one of: ${Ef.join(", ")}`),CZ=c.object({maxConnections:c.number().int(E.MAX_CONNECTIONS.INTEGER).min(1,E.MAX_CONNECTIONS.MIN).max(100,E.MAX_CONNECTIONS.MAX).optional(),maxIdleConnections:c.number().int(E.PROXY_CONFIG.MAX_IDLE_CONNECTIONS.INTEGER).min(0,E.PROXY_CONFIG.MAX_IDLE_CONNECTIONS.MIN).max(100,E.PROXY_CONFIG.MAX_IDLE_CONNECTIONS.MAX).optional(),connectionBorrowTimeout:c.number().int(E.PROXY_CONFIG.BORROW_TIMEOUT.INTEGER).min(1,E.PROXY_CONFIG.BORROW_TIMEOUT.MIN).max(3600,E.PROXY_CONFIG.BORROW_TIMEOUT.MAX).optional(),requireTLS:c.boolean().optional()}).strict().describe("RDS Proxy configuration"),IZ=c.object({instanceType:c.string().optional(),availabilityZone:c.string().optional()}).strict().describe("Read replica configuration"),DZ=c.object({automaticallyAfterDays:c.number().int(E.ROTATION.INTEGER).min(1,E.ROTATION.MIN).max(365,E.ROTATION.MAX).optional()}).strict().describe("Secret rotation configuration"),jf=c.object({username:c.string().min(1,E.REQUIRED.USERNAME).max(63,E.USERNAME.MAX_LENGTH).optional(),secretRotation:DZ.optional()}).strict().describe("Database credentials configuration"),Mf=Ut(CZ),Lf=Ut(IZ),NZ=c.object({scaleWithWriter:c.boolean().optional(),enableDatabaseInsights:c.boolean().optional(),identifierSuffix:c.string().min(1,E.IDENTIFIER_SUFFIX.REQUIRED).max(50,E.IDENTIFIER_SUFFIX.MAX_LENGTH).optional(),availabilityZone:c.string().optional()}).strict().describe("Configuration for a single Aurora reader instance"),Fl=c.object({enableDatabaseInsights:c.boolean().optional(),identifierSuffix:c.string().min(1,E.IDENTIFIER_SUFFIX.REQUIRED).max(50,E.IDENTIFIER_SUFFIX.MAX_LENGTH).optional(),availabilityZone:c.string().optional()}).strict().describe("Configuration for Aurora writer instance"),kZ=c.object({count:c.number().int(E.READER.COUNT.INTEGER).min(0,E.READER.COUNT.MIN).max(15,E.READER.COUNT.MAX).optional(),instances:c.array(NZ).max(15,E.READER_INSTANCES.MAX).optional(),defaultEnableDatabaseInsights:c.boolean().optional()}).strict().refine(e=>!(e.count!==void 0&&e.instances!==void 0),{message:E.READER_INSTANCES.COUNT_OR_INSTANCES,path:["count"]}).describe("Aurora readers configuration"),Ul=Ut(kZ),wZ=c.object({awsManaged:c.literal(!0)}).strict(),PZ=c.object({useCMK:c.literal(!0)}).strict(),h$=c.union([wZ,PZ]),RZ=c.object({mode:c.enum(["standard","advanced"]).optional(),encryptionKey:h$.optional()}).strict().describe("Database Insights configuration"),Ff=Ut(RZ),Uf=c.object({storageKey:h$.optional()}).strict().describe("Encryption configuration (DESTRUCTIVE to change storageKey)"),zl=c.object({name:Se,type:TZ,databaseName:c.string().min(1,E.REQUIRED.DATABASE_NAME),instanceType:c.string().optional(),allocatedStorage:c.number().optional(),multiAz:c.boolean().optional(),publiclyAccessible:c.boolean().optional(),databaseInsights:Ff.optional(),port:$f.optional(),deletionProtection:c.boolean().optional(),proxy:Mf.optional(),credentials:jf.optional(),readReplica:Lf.optional(),encryption:Uf.optional(),writer:Fl.optional(),readers:Ul.optional(),backupRetention:Sa.optional(),preferredMaintenanceWindow:c.string().optional(),monitoringInterval:Ll.optional(),primaryRegion:c.string().optional(),secondaryRegions:c.array(c.string()).optional(),globalClusterIdentifier:c.string().optional(),enableGlobalWriteForwarding:c.boolean().optional(),snapshotIdentifier:c.string().optional(),snapshotUsername:c.string().optional(),databaseEngine:c.enum(us).optional(),engineExpression:c.string().optional(),variableName:c.string().optional(),extraProperties:c.array(St).optional(),alarms:l$.optional()}).strict(),zf=c.object({appName:lt,nameProvidedByFlag:c.boolean().optional(),databaseName:c.string().min(1,E.REQUIRED.DATABASE_NAME).max(63,E.MAX_LENGTH.DATABASE_NAME).regex(he.DATABASE_NAME,E.DATABASE_NAME),resourceName:Se.optional(),connectionConfig:c.object({connectToCompute:c.array(c.string()).optional(),connectToServices:c.array(c.string()).optional()}).strict().optional(),databaseInsights:Ff.optional(),port:$f.optional(),proxy:Mf.optional(),credentials:jf.optional(),encryption:Uf.optional(),deletionProtection:c.boolean().optional()}).strict(),g$={databaseType:c.literal("Instance"),instanceType:c.string().optional(),multiAz:c.boolean().optional(),readReplica:Lf.optional(),publiclyAccessible:c.boolean().optional(),backupRetention:Sa.optional(),allocatedStorage:c.number().optional(),snapshotIdentifier:c.string().optional(),snapshotUsername:c.string().optional()},y$={databaseType:c.literal("Aurora"),writer:Fl.optional(),readers:Ul.optional(),backupRetention:Sa.optional(),preferredMaintenanceWindow:c.string().optional(),monitoringInterval:Ll.optional(),snapshotIdentifier:c.string().optional(),snapshotUsername:c.string().optional()},v$={databaseType:c.literal("GlobalAurora"),primaryRegion:c.string().min(1,E.GLOBAL_AURORA.PRIMARY_REGION_REQUIRED),secondaryRegions:c.array(c.string()).optional(),globalClusterIdentifier:c.string().optional(),enableGlobalWriteForwarding:c.boolean().optional(),writer:Fl.optional(),readers:Ul.optional(),backupRetention:Sa.optional(),preferredMaintenanceWindow:c.string().optional(),monitoringInterval:Ll.optional(),snapshotIdentifier:c.string().optional(),snapshotUsername:c.string().optional()},S$=c.object({appName:lt,nameProvidedByFlag:c.boolean().optional(),databaseName:c.string().min(1,E.REQUIRED.DATABASE_NAME).max(63,E.MAX_LENGTH.DATABASE_NAME).regex(he.DATABASE_NAME,E.DATABASE_NAME),resourceName:Se.optional(),connectionConfig:c.object({connectToCompute:c.array(c.string()).optional(),connectToServices:c.array(c.string()).optional()}).strict().optional()}).strict(),b$={databaseType:c.literal("ClickHouse"),instanceType:xZ.optional(),storageGb:d$.optional(),iops:p$.optional(),throughputMbps:m$.optional(),coldTier:c.union([c.object({mode:c.literal("s3")}).strict(),c.literal(!1)]).optional(),optimiseSchedule:c.union([c.string(),c.literal(!1)]).optional(),backupSchedule:c.union([c.string(),c.literal(!1)]).optional(),backupVerify:c.literal(!1).optional(),backupRetentionDays:f$.optional()},OZ=zf.extend(g$).strict(),$Z=zf.extend(y$).strict(),jZ=zf.extend(v$).strict(),MZ=S$.extend(b$).strict(),due=c.discriminatedUnion("databaseType",[OZ,$Z,jZ,MZ]),Sx=zf.extend({resourceName:Se}).strict(),LZ=Sx.extend(g$).strict(),FZ=Sx.extend(y$).strict(),UZ=Sx.extend(v$).strict(),zZ=S$.extend({resourceName:Se}).strict(),BZ=zZ.extend(b$).strict(),pue=c.discriminatedUnion("databaseType",[LZ,FZ,UZ,BZ]),mue=c.object({appName:lt,databaseName:c.string().min(1,E.REQUIRED.DATABASE_NAME),maxConnections:c.number().int(E.MAX_CONNECTIONS.INTEGER).min(1,E.MAX_CONNECTIONS.MIN).max(100,E.MAX_CONNECTIONS.MAX).optional(),maxIdleConnections:c.number().int(E.PROXY_CONFIG.MAX_IDLE_CONNECTIONS.INTEGER).min(0,E.PROXY_CONFIG.MAX_IDLE_CONNECTIONS.MIN).max(100,E.PROXY_CONFIG.MAX_IDLE_CONNECTIONS.MAX).optional(),connectionBorrowTimeout:c.number().int(E.PROXY_CONFIG.BORROW_TIMEOUT.INTEGER).min(1,E.PROXY_CONFIG.BORROW_TIMEOUT.MIN).max(3600,E.PROXY_CONFIG.BORROW_TIMEOUT.MAX).optional(),requireTLS:c.boolean().optional(),nameProvidedByFlag:c.boolean().optional()}).strict(),GZ=["S","N","B"],Of=c.object({name:c.string(),type:c.enum(GZ)}).strict(),E$=c.object({name:Se,partitionKey:Of,sortKey:Of.optional(),globalSecondaryIndexes:c.array(c.object({indexName:c.string(),partitionKey:Of,sortKey:Of.optional()}).strict()).optional(),ttlAttribute:c.string().optional(),stream:c.boolean().optional(),variableName:c.string().optional(),extraProperties:c.array(St).optional()}).strict(),VZ=c.object({mode:c.literal("s3")}).strict(),A$=c.object({name:Se,type:c.literal("ClickHouse"),databaseName:r$,instanceType:c.string().optional(),storageGb:d$.optional(),iops:p$.optional(),throughputMbps:m$.optional(),coldTier:c.union([VZ,c.literal(!1)]).optional(),optimiseSchedule:c.union([c.string(),c.literal(!1)]).optional(),backupSchedule:c.union([c.string(),c.literal(!1)]).optional(),backupVerify:c.literal(!1).optional(),backupRetentionDays:f$.optional(),variableName:c.string().optional(),extraProperties:c.array(St).optional()}).strict();var WZ=c.object({count:c.number().int(E.NAT_GATEWAY.INTEGER).min(0,E.NAT_GATEWAY.MIN).max(3,E.NAT_GATEWAY.MAX).optional()}).strict().describe("NAT gateway configuration"),_$=Ut(WZ),bx=c.enum(["cloudwatch","s3"]),KZ=c.object({destination:bx.optional(),retentionDays:c.number().int(E.RETENTION_DAYS.INTEGER).min(1,E.RETENTION_DAYS.MIN).max(365,E.RETENTION_DAYS.MAX).optional(),trafficType:c.enum(["ALL","ACCEPT","REJECT"]).optional()}).strict().describe("VPC flow log configuration"),x$=Ut(KZ),ZZ=c.object({s3:c.boolean().optional(),dynamodb:c.boolean().optional()}).strict().describe("Gateway VPC endpoints (FREE)"),HZ=Ut(ZZ),JZ=c.object({ecr:c.boolean().optional(),secretsManager:c.boolean().optional(),kms:c.boolean().optional(),cloudwatchLogs:c.boolean().optional(),ssm:c.boolean().optional(),sts:c.boolean().optional()}).strict().describe("Interface VPC endpoints (cost per hour)"),XZ=Ut(JZ),qZ=c.object({gateway:HZ.optional(),interface:XZ.optional()}).strict().describe("VPC endpoints configuration"),T$=Ut(qZ),ba=c.object({maxAzs:c.number().int(E.MAX_AZS.INTEGER).min(1,E.MAX_AZS.MIN).max(3,E.MAX_AZS.MAX).optional(),natGateways:_$.optional(),flowLogs:x$.optional(),vpcEndpoints:T$.optional(),cidrMask:c.number().int(E.CIDR_MASK.INTEGER).min(16,E.CIDR_MASK.MIN).max(28,E.CIDR_MASK.MAX).optional()}).strict(),C$=c.string().min(1,E.REQUIRED.NETWORK_NAME).max(50,E.MAX_LENGTH.NETWORK_NAME).regex(he.RESOURCE_NAME,E.RESOURCE_NAME),I$=ba.extend({name:C$}).strict(),D$=Ut(ba),vue=c.object({appName:lt,networkName:C$.optional(),maxAzs:c.number().int(E.MAX_AZS.INTEGER).min(1,E.MAX_AZS.MIN).max(3,E.MAX_AZS.MAX).optional(),natGateways:_$.optional(),flowLogs:x$.optional(),vpcEndpoints:T$.optional()}).strict(),YZ=he.CIDR,Ex=c.string().regex(YZ,E.CIDR),QZ=c.object({kind:c.literal("database"),resource:c.string().min(1,E.REQUIRED.RESOURCE_REFERENCE),name:Se,allowedFromCidrs:c.array(Ex),access:c.enum(["read","write","readWrite"]).optional()}).strict(),eH=c.object({kind:c.literal("ecsService"),resource:c.string().min(1,E.REQUIRED.RESOURCE_REFERENCE),serviceName:c.string().min(1,E.REQUIRED.SERVICE_NAME),name:Se,allowedFromCidrs:c.array(Ex),port:va.optional()}).strict(),tH=c.discriminatedUnion("kind",[QZ,eH]),N$=c.object({name:Se,peerAppName:c.string().min(1,E.REQUIRED.APP_NAME),peerAccountId:c.string().regex(he.AWS_ACCOUNT_ID,E.AWS_ACCOUNT_ID),peerRegion:c.string().min(1,E.VPC_PEER.REGION_REQUIRED).optional(),peerVpcId:c.string().regex(he.VPC_ID,E.VPC_ID).optional(),peerVpcCidr:Ex.optional(),peerRoleArn:c.string().regex(he.ROLE_ARN,E.ROLE_ARN).optional(),peerRouteTableIds:c.array(c.string().min(1,E.VPC_PEER.ROUTE_TABLE_ID_REQUIRED)).optional(),localVpcName:c.string().min(1,E.REQUIRED.NETWORK_NAME).optional(),enableDnsResolution:c.boolean().optional()}).strict(),Ax=c.object({name:Se,requesterAccountIds:c.array(c.string().regex(he.AWS_ACCOUNT_ID,E.AWS_ACCOUNT_ID)).min(1,E.VPC_PEER.MIN_REQUESTER_ACCOUNTS),localVpcName:c.string().min(1,E.REQUIRED.NETWORK_NAME).optional(),publishToSsm:c.boolean().optional(),exposedResources:c.array(tH).optional()}).strict();var Bf=["storage","cdn","compute"],rH=c.object({sid:c.string().optional(),effect:c.enum(["Allow","Deny"]),principals:c.array(c.string()),actions:c.array(c.string()),resources:c.array(c.string()).optional(),conditions:c.record(c.string(),c.record(c.string(),c.union([c.string(),c.array(c.string())]))).optional()}).strict(),Bl=c.object({name:Se,bucketName:c.string().optional(),publicReadAccess:c.boolean().optional(),websiteHosting:c.object({indexDocument:c.string(),errorDocument:c.string().optional()}).strict().optional(),backupVaultTier:c.enum(Vr).optional(),versioned:c.boolean().optional(),encryption:c.enum(ps).optional(),kmsKeyArn:c.string().optional(),cors:c.array(c.object({allowedOrigins:c.array(c.string()),allowedMethods:c.array(c.string()),allowedHeaders:c.array(c.string()).optional(),exposedHeaders:c.array(c.string()).optional(),maxAge:c.number().optional()}).strict()).optional(),deployment:c.object({source:c.string(),prune:c.boolean().optional(),cacheControl:c.object({maxAge:c.number().optional(),immutable:c.boolean().optional()}).strict().optional()}).strict().optional(),retain:c.boolean().optional(),resourcePolicyStatements:c.array(rH).optional(),stackPlacement:c.enum(Bf).optional(),variableName:c.string().optional(),extraProperties:c.array(St).optional()}).strict().refine(e=>e.encryption!=="KMS"||!!e.kmsKeyArn,{message:E.KMS.KEY_REQUIRED}),xue=c.object({appName:lt,bucketName:t$,nameProvidedByFlag:c.boolean().optional(),storagePreset:c.enum(QO).optional(),publicReadAccess:c.boolean().optional(),websiteHosting:c.object({indexDocument:c.string(),errorDocument:c.string().optional()}).strict().optional(),backupVaultTier:c.enum(Vr).optional(),versioned:c.boolean().optional(),encryption:c.enum(ps).optional(),kmsKeyArn:c.string().optional(),cors:c.array(c.object({allowedOrigins:c.array(c.string()),allowedMethods:c.array(c.string()),allowedHeaders:c.array(c.string()).optional(),exposedHeaders:c.array(c.string()).optional(),maxAge:c.number().optional()}).strict()).optional(),connectionConfig:c.object({connectToCompute:c.array(c.string()).optional(),connectToServices:c.array(c.string()).optional()}).strict().optional()}).strict().refine(e=>e.encryption!=="KMS"||!!e.kmsKeyArn,{message:E.KMS.KEY_REQUIRED,path:["kmsKeyArn"]});var _x=c.enum(["DESTROY","RETAIN"]),Gl=c.object({name:Se,queueType:c.enum(["standard","fifo"]).default("standard"),visibilityTimeout:c.number().int(E.SQS.VISIBILITY_TIMEOUT.INTEGER).min(0,E.SQS.VISIBILITY_TIMEOUT.MIN).max(43200,E.SQS.VISIBILITY_TIMEOUT.MAX).optional(),retentionPeriod:c.number().int(E.SQS.RETENTION_PERIOD.INTEGER).min(60,E.SQS.RETENTION_PERIOD.MIN).max(1209600,E.SQS.RETENTION_PERIOD.MAX).optional(),contentBasedDeduplication:c.boolean().optional(),removalPolicy:_x.optional(),variableName:c.string().optional(),extraProperties:c.array(St).optional()}).strict();var k$=c.object({type:c.literal("basic-auth"),username:c.string().min(1),password:c.string().min(1)}).strict(),Vl=c.object({name:Se,defaultOriginRef:c.string(),behaviours:c.array(c.object({pathPattern:c.string(),originRef:c.string(),cachePolicy:c.enum(["CACHING_OPTIMIZED","CACHING_DISABLED"]).optional()}).strict()).optional(),customDomain:c.string().optional(),certificateArn:c.string().optional(),domain:c.string().optional(),originHostname:c.string().optional(),accessGate:c.union([c.literal(!1),k$]).optional(),extraProperties:c.array(St).optional()}).strict(),Pue=c.object({appName:c.string(),name:Se.optional(),defaultOriginRef:c.string(),behaviours:c.array(c.object({pathPattern:c.string(),originRef:c.string(),cachePolicy:c.enum(["CACHING_OPTIMIZED","CACHING_DISABLED"]).optional()}).strict()).optional(),customDomain:c.string().optional(),certificateArn:c.string().optional(),domain:c.string().optional(),originHostname:c.string().optional(),accessGate:c.union([c.literal(!1),k$]).optional(),nameProvidedByFlag:c.boolean().optional()}).strict();var nH=Object.defineProperty,xx=(e,t)=>nH(e,"name",{value:t,configurable:!0}),iH=new Set(["t4g","c6g","c6gd","c6gn","c7g","c7gd","c7gn","r6g","r6gd","r7g","r7gd","r8g","r8gd","c8g","c8gd","c8gn","m6g","m6gd","m7g","m7gd","m8g","m8gd","x8g","i8g","a1","x2gd","im4gn","is4gen","i4g","hpc7g"]);function xi(e){let t=e.split(".")[0]??"";return iH.has(t)?"ARM":"STANDARD"}xx(xi,"getArchitectureForInstanceType");function Gf(e,t){let r=xi(e);return r!==t?{valid:!1,message:`Instance type '${e}' requires ${r} architecture, but '${t}' AMI was specified. Use a ${r==="ARM"?"Graviton instance (t4g, c6g, r6g, m6g, etc.)":"Intel/AMD instance (t3, c5, r5, m5, etc.)"} instead.`}:{valid:!0}}xx(Gf,"validateArchitectureMatch");function w$(e,t){return xi(e)===t}xx(w$,"isArchitectureCompatible");var aH=Object.defineProperty,Vf=(e,t)=>aH(e,"name",{value:t,configurable:!0});var oH=1;var sH=/^[A-Za-z0-9_.-]+$/,cH=c.object({id:c.string().min(1,"buildSecret id cannot be empty").regex(sH,"buildSecret id may contain only letters, digits, '_', '.', and '-' (no comma, '=', or whitespace, which would break the buildx --secret argv)"),ssm:c.string().min(1,"ssm parameter name cannot be empty").optional(),secretsManager:c.object({name:c.string().min(1,"secret name cannot be empty").optional(),arn:c.string().min(1,"secret arn cannot be empty").optional(),field:c.string().min(1,"secret field cannot be empty").optional()}).strict().refine(e=>e.name===void 0!=(e.arn===void 0),"secretsManager requires exactly one of name or arn").optional(),env:c.string().min(1,"env variable name cannot be empty").optional()}).strict().superRefine((e,t)=>{[e.ssm,e.secretsManager,e.env].filter(r=>r!==void 0).length!==1&&t.addIssue({code:c.ZodIssueCode.custom,message:"buildSecret requires exactly one source (ssm, secretsManager, or env)"})}),lH=c.union([c.string(),c.object({ssm:c.string().min(1,"ssm parameter name cannot be empty").optional(),secretsManager:c.object({name:c.string().min(1,"secret name cannot be empty").optional(),arn:c.string().min(1,"secret arn cannot be empty").optional(),field:c.string().min(1,"secret field cannot be empty").optional()}).strict().refine(e=>e.name===void 0!=(e.arn===void 0),"secretsManager requires exactly one of name or arn").optional(),env:c.string().min(1,"env variable name cannot be empty").optional(),acknowledgePublic:c.boolean().optional()}).strict().superRefine((e,t)=>{[e.ssm,e.secretsManager,e.env].filter(r=>r!==void 0).length!==1&&t.addIssue({code:c.ZodIssueCode.custom,message:"buildArg value requires exactly one source (ssm, secretsManager, or env)"})})]),on=c.object({path:c.string(),context:c.string().min(1,"context cannot be empty").optional(),target:c.string().min(1,"target cannot be empty").optional(),buildArgs:c.record(c.string(),lH).optional(),buildSecrets:c.array(cH).optional()}).strict(),Mue=on.partial();function uH(e,t){if(t===void 0)return e;let r=t.context??e.context,i=t.target??e.target,n=t.buildArgs??e.buildArgs,a=t.buildSecrets??e.buildSecrets;return{path:t.path??e.path,...r!==void 0&&{context:r},...i!==void 0&&{target:i},...n!==void 0&&{buildArgs:n},...a!==void 0&&{buildSecrets:a}}}Vf(uH,"mergeDockerBuild");function Tx(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}Vf(Tx,"isRecord");function P$(e){if(!Tx(e)||typeof e.path!="string"||e.path.length===0)return;let t=typeof e.context=="string"&&e.context.length>0?e.context:void 0,r=typeof e.target=="string"&&e.target.length>0?e.target:void 0,i=Tx(e.buildArgs)&&Object.keys(e.buildArgs).length>0?e.buildArgs:void 0,n=Array.isArray(e.buildSecrets)&&e.buildSecrets.length>0?e.buildSecrets:void 0,a={path:e.path,...t!==void 0&&{context:t},...r!==void 0&&{target:r},...i!==void 0&&{buildArgs:i},...n!==void 0&&{buildSecrets:n}},o=on.safeParse(a);return o.success?o.data:void 0}Vf(P$,"normaliseDockerBuild");function dH(e){if(e===void 0)return;let t=P$(e);return t===void 0?void 0:JSON.stringify(t)}Vf(dH,"dockerBuildFingerprint");var pH=c.object({name:c.string(),clusterName:c.string().optional(),docker:on.optional(),containerPort:c.number().optional(),secrets:c.array(c.string()).optional(),ssmSecretsPath:c.string().optional(),importedSecretNames:c.array(c.string()).optional(),schemaGateImageTag:c.string().optional()}).strict(),mH=c.object({type:c.enum(gr),name:c.string(),source:c.string()}).strict(),fH=c.object({repositoryName:c.string()}).strict(),hH=["x86_64","arm64"],gH=c.object({name:c.string(),secrets:c.array(c.string()).optional(),ssmSecretsPath:c.string().optional(),importedSecretNames:c.array(c.string()).optional(),docker:on.optional(),imageKey:c.string().optional(),architecture:c.enum(hH).optional()}).strict(),yH=c.object({templateHash:c.string(),synthTimestamp:c.string()}).strict(),vH=c.object({constructPath:c.string().max(512),group:c.string().max(128),resourceType:c.string().max(256)}).strict(),SH=c.object({synthesisedBy:c.string().min(1).max(128),minimumEngineVersion:c.string().min(1).max(32),maximumEngineMajor:c.number().int().min(0).optional(),minimumAwsCdkCli:c.string().min(1).max(32).optional()}).strict(),bH=c.object({appName:c.string().min(1).max(128),slot:c.string().min(1).max(64),clusterName:c.string().min(1).max(128),anchor:c.string().min(1).max(128),pinned:c.boolean(),currentServiceName:c.string().min(1).max(256),legacyKey:c.string().min(1).max(256),legacyAnchor:c.string().min(1).max(256),legacyServiceName:c.string().min(1).max(512),legacyKeyFields:c.array(c.string().max(64)).max(32)}).strict(),EH=c.object({constructPath:c.string().min(1).max(512),resourceType:c.string().min(1).max(256),physicalNameHint:c.string().min(1).max(512),policy:c.enum(["retain","snapshot","adopted"]),destroyDisposition:c.enum(["survives","deleted-on-explicit-destroy"]),reason:c.string().min(1).max(1024),costClass:c.enum(["none","storage","fixed-monthly"]),cleanupHint:c.string().min(1).max(1024)}).strict(),Lue=c.object({version:c.literal(oH),generatedAt:c.string(),appName:c.string(),services:c.array(pH),lambdas:c.array(gH),pattern:mH.optional(),ecr:fH.optional(),stacks:c.record(c.string(),yH),resourceMap:c.record(c.string(),vH).optional(),engineCompat:SH.optional(),identityAliases:c.array(bH).optional(),residuals:c.array(EH).optional()}).strict();var AH=Object.defineProperty,_H=(e,t)=>AH(e,"name",{value:t,configurable:!0});function O$(e){return!(e.image!==void 0&&e.docker!==void 0)}_H(O$,"imageDockerMutexCheck");var $$=c.number().int(E.CAPACITY.MIN.INTEGER).min(fx,E.GENERATOR_CAPACITY.MIN.MIN).max(hx,E.GENERATOR_CAPACITY.MIN.MAX),j$=c.number().int(E.CAPACITY.MAX.INTEGER).min(fx,E.GENERATOR_CAPACITY.MAX.MIN).max(hx,E.GENERATOR_CAPACITY.MAX.MAX),fs=c.number().int(E.LAMBDA.MEMORY.INTEGER).min(HO,E.LAMBDA.MEMORY.MIN).max(JO,E.LAMBDA.MEMORY.MAX).refine(e=>e===128||e%64===0,E.LAMBDA.MEMORY.MULTIPLE),M$=c.string().regex(he.LAMBDA_RUNTIME_IDENTIFIER,E.LAMBDA.RUNTIME),Cx=c.number().int(E.CPU.INTEGER).min(256,E.CPU.MIN).max(4096,E.CPU.MAX),Kf=c.number().int(E.CAPACITY.DESIRED.INTEGER).min(0,E.CAPACITY.DESIRED.MIN).max(ds,E.CAPACITY.DESIRED.MAX),Wl=c.object({connectToDatabase:c.array(c.string()).optional()}).strict(),xH=c.object({minSize:c.number().int(E.CAPACITY.WARM_POOL.MIN_SIZE.INTEGER).min(0,E.CAPACITY.WARM_POOL.MIN_SIZE.MIN).max(XO,E.CAPACITY.WARM_POOL.MIN_SIZE.MAX).optional(),reuseOnScaleIn:c.boolean().optional()}).strict(),Ix=c.object({instanceType:c.string().optional(),amiHardwareType:c.enum(Df).optional(),minCapacity:c.number().int(E.CAPACITY.MIN.INTEGER).min(0,E.CAPACITY.MIN.MIN_0).max(ds,E.CAPACITY.MIN.MAX).optional(),maxCapacity:c.number().int(E.CAPACITY.MAX.INTEGER).min(1,E.CAPACITY.MAX.MIN_1).max(ds,E.CAPACITY.MAX.MAX).optional(),memoryLimitMiB:jl(128).optional(),warmPool:xH.optional(),extraProperties:c.array(St).optional()}).strict().superRefine((e,t)=>{if(!e.instanceType||!e.amiHardwareType)return;let r=Gf(e.instanceType,e.amiHardwareType);r.valid||t.addIssue({code:"custom",message:r.message??E.ARCHITECTURE_MISMATCH,path:["instanceType"]})}).superRefine((e,t)=>{e.minCapacity===0&&!e.warmPool&&t.addIssue({code:"custom",message:E.CAPACITY.WARM_POOL_REQUIRED,path:["minCapacity"]}),e.warmPool?.minSize!==void 0&&e.maxCapacity!==void 0&&e.warmPool.minSize>e.maxCapacity&&t.addIssue({code:"custom",message:E.CAPACITY.WARM_POOL.MIN_SIZE_EXCEEDS_MAX_CAPACITY,path:["warmPool","minSize"]})}),TH=c.enum(wl).describe(`Compute type must be one of: ${wl.join(", ")}`),Dx=c.enum(ls).describe(`ECS capacity provider must be one of: ${ls.join(", ")}`),Nx=c.string().refine(e=>Ft(Nf,e),{message:E.INSTANCE_TYPE}),L$=c.object({sourceType:c.enum(["sqs","dynamodb","eventbridge"]),sourceRef:c.string().describe("Name of the source resource"),batchSize:c.number().int(E.BATCH_SIZE.INTEGER).min(1,E.BATCH_SIZE.MIN).max(1e4,E.BATCH_SIZE.MAX).optional(),startingPosition:c.enum(["TRIM_HORIZON","LATEST"]).optional(),maxBatchingWindow:c.number().int(E.BATCHING_WINDOW.INTEGER).min(0,E.BATCHING_WINDOW.MIN).max(300,E.BATCHING_WINDOW.MAX).optional(),reportBatchItemFailures:c.boolean().optional()}).strict(),CH=c.object({name:c.string().min(1,E.REQUIRED.CONTAINER_NAME).optional(),image:c.string().optional(),port:va.optional(),environment:ms.optional(),secretsImport:n$.optional(),command:c.array(c.string()).optional(),entryPoint:c.array(c.string()).optional(),essential:c.boolean().optional(),healthCheck:c.object({command:c.array(c.string()),interval:c.number().int(E.HEALTH_CHECK.INTERVAL.INTEGER).min(5,E.HEALTH_CHECK.INTERVAL.MIN).max(300,E.HEALTH_CHECK.INTERVAL.MAX).optional(),timeout:c.number().int(E.HEALTH_CHECK.TIMEOUT.INTEGER).min(2,E.HEALTH_CHECK.TIMEOUT.MIN).max(60,E.HEALTH_CHECK.TIMEOUT.MAX).optional(),retries:c.number().int(E.HEALTH_CHECK.RETRIES.INTEGER).min(1,E.HEALTH_CHECK.RETRIES.MIN).max(10,E.HEALTH_CHECK.RETRIES.MAX).optional(),startPeriod:c.number().int(E.HEALTH_CHECK.START_PERIOD.INTEGER).min(0,E.HEALTH_CHECK.START_PERIOD.MIN).max(300,E.HEALTH_CHECK.START_PERIOD.MAX).optional()}).strict().optional(),ssmSecrets:c.array(c.string().regex(he.SECRET_NAME,E.SECRET_NAME)).optional(),extraProperties:c.array(St).optional()}).strict(),F$=c.string().min(1,E.REQUIRED.SERVICE_NAME).max(255,E.MAX_LENGTH.SERVICE_NAME).regex(he.ECS_SERVICE_NAME,E.ECS_SERVICE_NAME),U$=c.object({domain:c.string().optional(),loadBalancer:c.union([c.literal(!1),c.enum(Cf)]).optional(),directAccess:c.boolean().optional(),extraProperties:c.array(St).optional()}).strict().refine(e=>!(e.directAccess&&e.domain),{message:E.DIRECT_ACCESS.NO_DOMAIN,path:["directAccess"]}).refine(e=>!(e.directAccess&&typeof e.loadBalancer=="string"),{message:E.DIRECT_ACCESS.NO_LOAD_BALANCER}).describe("Cluster-level configuration"),Wf=c.object({path:c.string().optional(),host:c.string().optional(),priority:c.number().int(E.PRIORITY.INTEGER).min(1,E.PRIORITY.MIN).max(5e4,E.PRIORITY.MAX).optional(),healthCheckPath:c.string().optional()}).strict().describe("Path/host-based routing configuration"),IH=c.object({desiredCount:Kf.optional(),minCapacity:c.number().int(E.CAPACITY.MIN.INTEGER).min(0,E.CAPACITY.MIN.MIN_0).max(ds,E.CAPACITY.MIN.MAX).optional(),maxCapacity:c.number().int(E.CAPACITY.MAX.INTEGER).min(1,E.CAPACITY.MAX.MIN_1).max(ds,E.CAPACITY.MAX.MAX).optional(),scalingType:c.enum(If).optional()}).strict().refine(ya.check,ya.params).describe("ECS service scaling configuration"),z$=c.object({name:F$,docker:on.optional(),needsDatabaseConnection:c.boolean().optional(),needsStorageConnection:c.boolean().optional(),needsMessagingConnection:c.boolean().optional(),image:c.string().optional(),containers:c.array(CH).optional(),routing:c.union([Wf,c.array(Wf).min(1)]).optional(),serviceType:c.enum(Ol).optional(),cpu:Cx.optional(),memoryLimitMiB:jl(512).optional(),desiredCount:Kf.optional(),scaling:Ut(IH).optional(),capacityProvider:Dx,ec2Config:Ix.optional(),ssmSecretsPath:c.string().regex(he.SSM_PATH,E.SSM_PATH).optional(),extraProperties:c.array(St).optional(),alarms:c$.optional()}).strict().superRefine((e,t)=>{O$(e)||t.addIssue({code:"custom",path:["docker"],message:E.IMAGE_DOCKER_MUTEX})}).describe("Configuration for a service in an ECS cluster"),Kl=c.object({name:Se,type:TH,needsConnection:c.boolean(),connectedDatabase:c.array(c.string().min(1,E.REQUIRED.CONNECTED_RESOURCE_NAME)).optional(),connectedStorage:c.array(c.string().min(1,E.REQUIRED.CONNECTED_RESOURCE_NAME)).optional(),connectedMessaging:c.array(c.string().min(1,E.REQUIRED.CONNECTED_RESOURCE_NAME)).optional(),cluster:U$.optional(),services:c.array(z$).optional(),docker:on.partial().optional(),deployment:c.enum(_f).optional(),codePath:c.string().optional(),timeout:c.number().int(E.LAMBDA.TIMEOUT.INTEGER).min(kf,E.LAMBDA.TIMEOUT.MIN).max(wf,E.LAMBDA.TIMEOUT.MAX).optional(),memory:fs.optional(),handler:c.string().optional(),runtime:M$.optional(),environment:ms.optional(),secrets:ms.optional(),eventSources:c.array(L$).optional(),functionUrl:c.object({authType:c.enum(Rl)}).strict().optional(),description:c.string().optional(),scheduleExpression:c.string().optional(),scheduleStackPlacement:c.enum(ga).optional(),architecture:c.enum(Tf).optional(),ephemeralStorageSize:c.number().int(E.EPHEMERAL_STORAGE.INTEGER).min(512,E.EPHEMERAL_STORAGE.MIN).max(10240,E.EPHEMERAL_STORAGE.MAX).optional(),functionName:c.string().optional(),ssmSecrets:c.array(c.string()).optional(),ssmSecretsPath:c.string().optional(),alarms:u$.optional(),instanceType:Nx.optional(),enableSSH:c.boolean().optional(),keyName:c.string().optional(),userData:c.string().optional(),securityGroups:c.array(c.string()).optional(),variableName:c.string().optional(),extraProperties:c.array(St).optional()}).strict().superRefine((e,t)=>{if(e.type==="ecs"&&e.services)for(let r=0;r<e.services.length;r++){let i=e.services[r];i?.ec2Config?.instanceType&&!i.ec2Config.amiHardwareType&&xi(i.ec2Config.instanceType)!=="ARM"&&t.addIssue({code:"custom",message:`Service '${i.name??r}' uses instance type '${i.ec2Config.instanceType}' (x86), which requires Docker images built for linux/amd64. The default build targets linux/arm64 (Graviton). Use a Graviton instance type (t4g, c6g, r6g, m6g, etc.) or set amiHardwareType: "STANDARD" to acknowledge x86.`,path:["services",r,"ec2Config","instanceType"]})}e.type==="lambda"&&e.deployment==="container"&&e.architecture==="X86_64"&&t.addIssue({code:"custom",message:"Lambda architecture 'X86_64' requires Docker images built for linux/amd64, but the default build targets linux/arm64. Use 'ARM_64' for Graviton Lambdas (recommended) or ensure your build pipeline targets linux/amd64.",path:["architecture"]})}),Zue=c.object({appName:lt,clusterName:Se,containerPort:va,nameProvidedByFlag:c.boolean().optional(),ecrRepository:c.string().optional(),capacityProvider:Dx.optional(),useAppEcr:c.boolean().optional(),desiredCount:Kf.optional(),cpu:Cx.optional(),memoryLimitMiB:jl(512).optional(),minCapacity:$$.optional(),maxCapacity:j$.optional(),ec2Config:Ix.optional(),connectionConfig:Wl.optional()}).strict().refine(ya.check,ya.params),Hue=c.object({appName:lt,functionName:Se,nameProvidedByFlag:c.boolean().optional(),lambdaType:c.enum(["basic","web","custom"]).optional(),ecrRepository:c.string().optional(),timeout:c.number().int(E.LAMBDA.TIMEOUT.INTEGER).min(kf,E.LAMBDA.TIMEOUT.MIN).max(wf,E.LAMBDA.TIMEOUT.MAX).optional(),memory:fs.optional(),enableFunctionUrl:c.boolean().optional(),description:c.string().optional(),enableCors:c.boolean().optional(),corsOrigins:c.string().optional(),corsHeaders:c.string().optional(),corsMethods:c.array(c.enum(YO)).optional(),corsCredentials:c.boolean().optional(),connectionConfig:Wl.optional()}).strict(),Jue=c.object({appName:lt,instanceName:Se,nameProvidedByFlag:c.boolean().optional(),instanceType:Nx.optional(),enableSSH:c.boolean().optional(),minCapacity:$$.optional(),maxCapacity:j$.optional(),connectionConfig:Wl.optional()}).strict().refine(ya.check,ya.params),Xue=c.object({appName:lt,clusterName:Se,serviceName:F$,capacityProvider:Dx,containerPort:va.optional(),cpu:Cx.optional(),memoryLimitMiB:jl(512).optional(),desiredCount:Kf.optional(),ec2Config:Ix.optional(),routing:c.union([Wf,c.array(Wf).min(1)]).optional(),docker:on.partial().optional(),nameProvidedByFlag:c.boolean().optional(),connectionConfig:Wl.optional()}).strict(),kx=c.object({appName:lt,computeName:Se,nameProvidedByFlag:c.boolean().optional(),connectionConfig:Wl.optional()}).strict(),DH=kx.extend({type:c.literal("ecs"),cluster:U$.optional(),services:c.array(z$).min(1,E.SERVICE.MIN_REQUIRED),docker:on.partial().optional()}).strict().refine(e=>{let t=e.services.filter(r=>r.containers?.some(i=>i.port));return t.length>1?t.every(r=>(Array.isArray(r.routing)?r.routing:r.routing?[r.routing]:[]).some(i=>i.path||i.host)):!0},{message:E.SERVICE.ROUTING_REQUIRED}).refine(e=>{let t=e.services.map(r=>r.name);return new Set(t).size===t.length},{message:E.SERVICE.UNIQUE_WITHIN_CLUSTER}),NH=kx.extend({type:c.literal("lambda"),timeout:c.number().int(E.LAMBDA.TIMEOUT.INTEGER).min(kf,E.LAMBDA.TIMEOUT.MIN).max(wf,E.LAMBDA.TIMEOUT.MAX).optional(),memory:fs.optional(),handler:c.string().optional(),runtime:M$.optional(),environment:ms.optional(),secrets:ms.optional(),description:c.string().optional(),functionUrl:c.union([c.object({authType:c.enum(Rl).optional()}).strict(),c.literal(!1)]).optional(),eventSources:c.array(L$).optional()}).strict(),kH=kx.extend({type:c.literal("ec2"),instanceType:Nx.optional(),enableSSH:c.boolean().optional(),keyName:c.string().optional(),userData:c.string().optional(),securityGroups:c.array(c.string()).optional()}).strict(),que=c.discriminatedUnion("type",[DH,NH,kH]),R$=c.object({path:c.string().min(1,E.REQUIRED.ROUTING_PATH),priority:c.number().int(E.PRIORITY.INTEGER).min(1,E.PRIORITY.MIN).max(5e4,E.PRIORITY.MAX).optional()}).strict(),B$=c.object({name:c.string().min(1,E.REQUIRED.SERVICE_NAME).max(255,E.MAX_LENGTH.SERVICE_NAME).regex(he.RESOURCE_NAME,E.RESOURCE_NAME),serviceType:c.enum(Ol).optional(),docker:on.partial().optional(),containerPort:va.optional(),needsDatabaseConnection:c.boolean().optional(),routing:c.union([R$,c.array(R$).min(1)]).optional()}).strict().superRefine((e,t)=>{e.serviceType==="worker"&&(e.containerPort!==void 0&&t.addIssue({code:"custom",path:["containerPort"],message:"Worker services are not reachable inbound; remove containerPort."}),e.routing!==void 0&&t.addIssue({code:"custom",path:["routing"],message:"Worker services have no ALB route; remove routing."}))}),Yue=c.object({appName:lt,instanceType:c.string().optional()}).strict();var wx=c.object({memorySize:fs.optional(),timeout:c.number().int(E.LAMBDA.TIMEOUT.INTEGER).min(1,E.LAMBDA.TIMEOUT.MIN).max(900,E.LAMBDA.TIMEOUT.MAX).optional(),ephemeralStorageSize:c.number().int(E.EPHEMERAL_STORAGE.INTEGER).min(512,E.EPHEMERAL_STORAGE.MIN).max(10240,E.EPHEMERAL_STORAGE.MAX).optional()}).strict(),G$=c.object({type:c.enum(mx).optional(),databaseName:c.string().optional(),databaseEngine:c.enum(us).optional(),deletionProtection:c.boolean().optional(),backupRetention:Sa.optional(),port:$f.optional(),publiclyAccessible:c.boolean().optional(),allowedIpCidr:c.string().optional(),instanceType:c.string().optional(),allocatedStorage:c.number().int(E.ALLOCATED_STORAGE.INTEGER).min(20,E.ALLOCATED_STORAGE.MIN).max(65536,E.ALLOCATED_STORAGE.MAX).optional(),multiAz:c.boolean().optional(),readReplica:Lf.optional(),writer:Fl.optional(),readers:Ul.optional(),allowVpcAccess:c.boolean().optional(),monitoringInterval:Ll.optional(),preferredMaintenanceWindow:c.string().optional(),databaseInsights:Ff.optional(),proxy:Mf.optional(),credentials:jf.optional(),encryption:Uf.optional(),snapshotIdentifier:c.string().optional(),snapshotUsername:c.string().optional()}).strict(),V$=c.object({server:wx.optional(),imageOptimisation:wx.optional(),revalidation:wx.optional()}).strict(),Px=c.object({versioned:c.boolean().optional()}).strict(),W$=c.object({assets:Px.optional(),cache:Px.optional(),media:Px.optional()}).strict(),wH=c.object({visibilityTimeout:c.number().int(E.SQS.VISIBILITY_TIMEOUT.INTEGER).min(0,E.SQS.VISIBILITY_TIMEOUT.MIN).max(43200,E.SQS.VISIBILITY_TIMEOUT.MAX).optional(),messageRetentionPeriod:c.number().int(E.SQS.RETENTION_PERIOD.INTEGER).min(60,E.SQS.RETENTION_PERIOD.MIN).max(1209600,E.SQS.RETENTION_PERIOD.MAX).optional(),maxMessageSize:c.number().int(E.MAX_MESSAGE_SIZE.INTEGER).min(1024,E.MAX_MESSAGE_SIZE.MIN).max(262144,E.MAX_MESSAGE_SIZE.MAX).optional(),deadLetterQueue:c.union([c.literal(!1),c.object({enabled:c.boolean().optional(),maxReceiveCount:c.number().int(E.DLQ.MAX_RECEIVE_COUNT.INTEGER).min(1,E.DLQ.MAX_RECEIVE_COUNT.MIN).max(1e3,E.DLQ.MAX_RECEIVE_COUNT.MAX).optional()}).strict()]).optional()}).strict(),K$=c.object({revalidationQueue:wH.optional()}).strict(),Z$=c.object({domainNames:c.array(c.string()).optional(),certificateArn:c.string().optional()}).strict(),H$=c.record(c.string().regex(he.ENV_VAR_NAME,E.ENV_VAR_NAME),c.string()).optional(),Rx=c.object({type:c.literal("payload"),name:c.string().min(1,E.REQUIRED.PATTERN_NAME),domain:c.string().optional(),database:G$.optional(),compute:V$.optional(),storage:W$.optional(),messaging:K$.optional(),cdn:Z$.optional(),environment:H$}).strict(),Ox=c.object({type:c.literal("nextjs"),name:c.string().min(1,E.REQUIRED.PATTERN_NAME),domain:c.string().optional(),database:G$.optional(),compute:V$.optional(),storage:W$.optional(),messaging:K$.optional(),cdn:Z$.optional(),environment:H$}).strict(),$x=c.enum(al),PH=c.object({command:c.string().min(1,E.REQUIRED.BUILD_COMMAND),outputDir:c.string().min(1,E.REQUIRED.OUTPUT_DIR)}).strict(),RH=c.object({maxAgeDays:c.number().optional(),includeSubdomains:c.boolean().optional(),preload:c.boolean().optional()}).strict(),OH=c.object({headers:c.boolean().optional(),contentSecurityPolicy:c.string().optional(),hsts:c.union([c.literal(!1),RH]).optional()}).strict(),$H=c.object({to:c.string().min(1,E.REQUIRED.FORMS_TO).regex(he.EMAIL,E.EMAIL),from:c.string().regex(he.EMAIL,E.EMAIL).optional(),corsOrigin:c.string().regex(he.HTTP_ORIGIN,"corsOrigin must be an exact origin such as https://example.com (no path, no trailing slash)").optional(),maxConcurrency:c.number().int().min(1).max(100).optional()}).strict(),jH=c.object({behaviours:c.array(c.unknown()).optional(),priceClass:c.enum(ol).optional(),invalidateOnDeploy:c.boolean().optional()}).strict(),MH=c.object({type:c.literal("basic-auth"),username:c.string().min(1,"accessGate.username must not be empty"),password:c.string().min(1,"accessGate.password must not be empty")}).strict(),Zl=c.object({type:c.literal("staticsite"),name:c.string().min(1,E.REQUIRED.PATTERN_NAME),source:c.string().min(1,E.REQUIRED.SOURCE),build:PH,routing:$x.optional(),security:OH.optional(),domain:c.string().optional(),zoneName:c.string().optional(),hostedZoneId:c.string().optional(),forms:$H.optional(),cdn:jH.optional(),accessGate:MH.optional()}).strict().superRefine((e,t)=>{if(e.forms===void 0)return;let r=e.domain;if(r===void 0||r===""){t.addIssue({code:"custom",path:["domain"],message:"A domain is required when forms are enabled: SES sends only from a verified identity, and the site's domain is the identity the pattern verifies"});return}let i=e.forms.from;i!==void 0&&!jm(i,r)&&t.addIssue({code:"custom",path:["forms","from"],message:`forms.from must be an address at ${r} (the verified SES identity) \u2014 for example noreply@${r}. Use forms.to for the recipient.`})}),Hl=c.discriminatedUnion("type",[Rx,Ox,Zl]),J$=c.enum(["lightweight","standard","resilient","custom"]),X$=c.object({type:c.enum(mx),instanceType:c.string().optional(),backupRetention:Sa.optional(),deletionProtection:c.boolean().optional(),encryption:c.union([c.object({useCMK:c.literal(!0)}).strict(),c.literal(!1)]).optional()}).strict(),q$=c.object({memorySize:fs.optional(),timeout:c.number().int(E.LAMBDA.TIMEOUT.INTEGER).min(1,E.LAMBDA.TIMEOUT.MIN).max(900,E.LAMBDA.TIMEOUT.MAX).optional()}).strict();var Y$=c.object({appName:lt,type:gx,pattern:yx.optional(),patternConfig:Hl.optional(),owner:c.string().optional(),tags:c.record(c.string(),c.string()).optional(),vpcId:c.string().optional(),network:ba.optional(),backup:a$.optional(),tunnel:o$.optional(),additionalNetworks:c.array(I$).optional(),database:c.array(zl),s3:c.array(Bl),compute:c.array(Kl),dynamodb:c.array(E$).optional(),clickhouse:c.array(A$).optional(),sqs:c.array(Gl).optional(),cdn:Vl.optional(),customCodeBlocks:c.array(i$).optional(),additionalManagedImports:c.array(c.object({moduleSpecifier:c.string(),namedImports:c.array(c.string()),defaultImport:c.string().optional()}).strict()).optional()}).strict(),vde=c.object({name:lt,type:gx,pattern:yx.optional(),patternTier:J$.optional(),patternDomain:c.string().optional(),source:c.string().min(1,E.REQUIRED.SOURCE).optional(),buildCommand:c.string().min(1,E.REQUIRED.BUILD_COMMAND).optional(),outputDir:c.string().min(1,E.REQUIRED.OUTPUT_DIR).optional(),routing:$x.optional(),formsTo:c.string().min(1,E.REQUIRED.FORMS_TO).regex(he.EMAIL,E.EMAIL).optional(),corsOrigin:c.string().regex(he.HTTP_ORIGIN,"corsOrigin must be an exact origin such as https://example.com (no path, no trailing slash)").optional(),customDatabase:X$.optional(),customCompute:q$.optional(),region:c.string().optional(),owner:c.string().optional(),includeDatabase:c.boolean().optional(),databaseName:c.string().min(1,E.DATABASE.NAME.REQUIRED).max(63,E.DATABASE.NAME.MAX_LENGTH).optional(),vpcId:c.string().optional(),network:D$.optional(),services:c.array(B$).optional(),snapshotIdentifier:c.string().optional(),snapshotUsername:c.string().optional()}).strict().superRefine((e,t)=>{e.formsTo!==void 0&&(e.patternDomain!==void 0&&e.patternDomain!==""||t.addIssue({code:"custom",path:["patternDomain"],message:"A domain is required when forms are enabled: SES sends only from a verified identity, and the site's domain is the identity the pattern verifies"}))}),jx=c.object({name:Se,localResource:c.string().min(1),remoteApp:c.string().min(1),remoteResource:c.string().min(1),permission:c.enum(["read","write","read-write"]),remoteArn:c.string().optional()}).strict();var LH=["fjall-managed","external","external-manual"],_de=c.enum(LH);var Q$=c.object({givenName:c.string().min(1),familyName:c.string().min(1),displayName:c.string().min(1).optional(),expires:c.string().min(1).optional()}).strict(),ej=c.object({name:c.string().min(1),path:c.string().min(1).optional()}).strict(),FH=c.union([c.object({managedPolicyArn:c.string().min(1)}).strict(),c.object({customerManagedPolicy:ej}).strict()]),UH=c.object({managedPolicies:c.array(c.string().min(1)).optional(),inlinePolicy:c.record(c.string(),c.unknown()).optional(),customerManagedPolicies:c.array(ej).optional(),permissionsBoundary:FH.optional(),sessionDuration:c.string().min(1).optional(),description:c.string().optional(),accounts:c.union([c.array(c.string().min(1)),c.literal("all")]).optional(),includeManagementAccount:c.boolean().optional(),groups:c.array(c.string().min(1)).optional()}).strict(),zH=c.object({description:c.string().optional()}).strict(),Zf=c.string().regex(he.EMAIL,E.EMAIL),Mx={groups:c.record(c.string(),zH).optional(),permissionSets:c.record(c.string(),UH).optional(),memberships:c.record(c.string(),c.array(Zf)).optional(),resolutionVersion:c.number().int().min(1).optional(),defaultPermissionSets:c.boolean().optional()},BH=c.discriminatedUnion("source",[c.object({...Mx,source:c.literal("fjall-managed"),users:c.record(Zf,Q$)}).strict(),c.object({...Mx,source:c.literal("external")}).strict(),c.object({...Mx,source:c.literal("external-manual"),users:c.record(Zf,Q$).optional()}).strict()]),Lx=c.object({name:Se,type:c.literal("organisation").optional(),organisationName:c.string().min(1).optional(),orgEmail:Zf.optional(),accounts:c.unknown().optional(),accountIds:c.record(c.string(),c.string()).optional(),identityCentre:c.union([BH,c.literal(!1)]).optional(),allowedRegions:c.array(c.string().min(1)).optional()}).strict();var GH=Object.defineProperty,VH=(e,t)=>GH(e,"name",{value:t,configurable:!0}),WH=[1,3,5,7,14,30,60,90,120,150,180,365,400,545,731,1827,3653],Hf=c.object({buildkiteQueue:c.string().min(1,"buildkiteQueue cannot be empty").max(100).regex(/^[a-zA-Z0-9-_]+$/,"buildkiteQueue must be alphanumeric with hyphens/underscores"),buildkiteOrgSlug:c.string().min(1,"buildkiteOrgSlug cannot be empty").max(100).regex(/^[a-z0-9-]+$/,"buildkiteOrgSlug must be a lowercase Buildkite organisation slug"),agentTokenSsmParameterName:c.string().min(2).regex(/^\//,"agentTokenSsmParameterName must be a full path (leading /)").optional(),agentTokenKmsKeyArn:c.string().min(1).optional(),fjallApiKeySsmParameterName:c.string().min(2).regex(/^\//,"fjallApiKeySsmParameterName must be a full path (leading /)").optional(),instanceType:c.string().min(1).default("c8g.xlarge"),agentVolumeSizeGib:c.number().int().min(20).max(1e3).default(250),agentMinInstances:c.number().int().min(0).default(0),agentMaxInstances:c.number().int().min(1).default(2),agentsPerInstance:c.number().int().min(1).default(1),spotCapacityPercentage:c.number().int().min(0).max(100).default(0),scaleInIdlePeriodSeconds:c.number().int().min(60).default(600),disconnectAfterUptimeSeconds:c.number().int().min(3600).default(86400),maxInstanceLifetimeDays:c.number().int().min(1).max(365).default(7),terminateInstanceAfterJob:c.boolean().default(!1),purgeBuildsOnDiskFull:c.boolean().default(!0),terminateInstanceOnDiskFull:c.boolean().default(!1),logRetentionDays:c.number().int().min(1).default(30),agentLogRetentionDays:c.literal(WH).default(7),buildkiteAgentRelease:c.enum(["stable","beta","edge"]).default("stable"),buildkiteAgentTags:c.string().default(""),buildkiteAgentTimestampLines:c.boolean().default(!1),buildkiteAgentExperiments:c.string().default(""),buildkiteAgentTracingBackend:c.enum(["","datadog","opentelemetry"]).default(""),buildkiteAgentCancelGracePeriodSeconds:c.number().int().min(10).default(60),enableSecretsPlugin:c.boolean().default(!0),enableEcrPlugin:c.boolean().default(!1),enableDockerLoginPlugin:c.boolean().default(!1),enableDockerUserNamespaceRemap:c.boolean().default(!0),enableDockerExperimental:c.boolean().default(!1),dockerNetworkingProtocol:c.enum(["ipv4","dualstack"]).default("ipv4"),enableInstanceStorage:c.boolean().default(!1),mountTmpfsAtTmp:c.boolean().default(!0),buildkiteAgentEnableGitMirrors:c.boolean().default(!1),bootstrapScriptUrl:c.string().default(""),agentEnvFileUrl:c.string().default(""),scalerEventSchedulePeriod:c.string().min(1).default("1 minute"),scalerMinPollInterval:c.string().min(1).default("10s"),scaleOutFactor:c.string().min(1).default("1.0"),scaleOutWaitingForJobs:c.boolean().default(!1),rolePermissionsBoundaryArn:c.string().min(1).optional(),alarmSnsTopicArn:c.string().min(1).optional(),applicationId:c.string().min(1).optional(),costAllocationEnvironment:c.string().min(1).optional(),costAllocationOwner:c.string().min(1).optional()}).strict(),KH=Hf.refine(e=>e.agentMinInstances<=e.agentMaxInstances,{message:"agentMinInstances must be <= agentMaxInstances"});function ZH(e){let t=KH.safeParse(e);if(!t.success){let r=t.error.issues.map(i=>` - ${i.path.join(".")||"(root)"}: ${i.message}`).join(`
314
314
  `);throw new Error(`Buildkite: invalid props:
315
315
  ${r}`)}return t.data}VH(ZH,"validateBuildkiteProps");var HH=Object.defineProperty,JH=(e,t)=>HH(e,"name",{value:t,configurable:!0});function XH(e){return`FjallDeployBoundary${e}`}JH(XH,"deployBoundaryName");var Fx={Sid:"FjallInheritAdministratorAccess",Effect:"Allow",Action:"*",Resource:"*"},tj=[{Sid:"FjallDenyOrgAndAccountEscape",Effect:"Deny",Action:["organizations:LeaveOrganization","account:CloseAccount"],Resource:"*"},{Sid:"FjallDenyDisableAuditLogging",Effect:"Deny",Action:["cloudtrail:StopLogging"],Resource:"*"},{Sid:"FjallDenyBoundarySelfEscape",Effect:"Deny",Action:["iam:DeleteRolePermissionsBoundary"],Resource:"*"},{Sid:"FjallDenyDisableKmsKey",Effect:"Deny",Action:["kms:DisableKey"],Resource:"*"}],rj=[...tj,{Sid:"FjallDenyStandingHumanCredentials",Effect:"Deny",Action:["iam:CreateUser","iam:CreateLoginProfile","iam:CreateAccessKey","iam:CreateAccountAlias"],Resource:"*"},{Sid:"FjallDenyDisableConfigRecorder",Effect:"Deny",Action:["config:StopConfigurationRecorder"],Resource:"*"}],qH=[...rj,{Sid:"FjallDenyAccountPasswordPolicyTamper",Effect:"Deny",Action:["iam:UpdateAccountPasswordPolicy","iam:DeleteAccountPasswordPolicy"],Resource:"*"},{Sid:"FjallDenyDisableDefaultEbsEncryption",Effect:"Deny",Action:["ec2:DisableEbsEncryptionByDefault"],Resource:"*"}],Fde={foundation:[Fx,...tj],compliance:[Fx,...rj],hardened:[Fx,...qH]};var YH=Object.defineProperty,ut=(e,t)=>YH(e,"name",{value:t,configurable:!0});var Bx="sts.amazonaws.com";function QH(e){return`FjallDevDeploy${e}`}ut(QH,"devDeployRoleName");function eJ(e){return`FjallDevProvisioner${e}`}ut(eJ,"devProvisionerRoleName");function tJ(e){return`FjallDevSyncWriter${e}`}ut(tJ,"devSyncWriterRoleName");var rJ="FjallDevBoundary";function nj(e){return`arn:aws:iam::${e}:policy/${rJ}`}ut(nj,"devBoundaryPolicyArn");function ij(e){return`org:${e}:dev-provisioner`}ut(ij,"devProvisionerSubject");function aj(e){return`org:${e}:dev-sync`}ut(aj,"devSyncSubject");function Ux(e,t){return`org:${e}:acct:${t}`}ut(Ux,"deployAccountSubject");function zx(e){return`org:${e}:*`}ut(zx,"genericMachineSubject");var nJ=["discovery","connection","org-setup","dev-substrate-setup"];function oj(e,t){return`org:${e}:${t}`}ut(oj,"serviceSubject");function iJ(e){let{fjallOrgId:t,providerArn:r,issuerDomain:i,accountTier:n,accountId:a}=e,o=e.machineTrustMode??"expanded",s={[`${i}:aud`]:Bx},l;if(o==="account-scoped"){if(n===void 0||!xm(n)||a===void 0)throw new Error(`machineTrustMode "account-scoped" requires a governance accountTier and an accountId (got tier: ${String(n)}, accountId ${a===void 0?"absent":"present"}) \u2014 refusing to fall back to the generic machine subject: a silent fallback would re-widen the trust the \xA74.4a Step-3 contract removes`);l=[Ux(t,a)]}else a!==void 0?l=[zx(t),Ux(t,a)]:l=zx(t);return[{Sid:"FjallMachineSubject",Effect:"Allow",Principal:{Federated:r},Action:"sts:AssumeRoleWithWebIdentity",Condition:{StringEquals:{...s,[`${i}:sub`]:l}}},{Sid:"FjallUserSubjects",Effect:"Allow",Principal:{Federated:r},Action:"sts:AssumeRoleWithWebIdentity",Condition:{StringEquals:s,StringLike:{[`${i}:sub`]:`org:${t}:user:*`}}},{Sid:"FjallServiceSubjects",Effect:"Allow",Principal:{Federated:r},Action:"sts:AssumeRoleWithWebIdentity",Condition:{StringEquals:{...s,[`${i}:sub`]:nJ.map(m=>oj(t,m))}}}]}ut(iJ,"buildNarrowedDeployTrustStatements");function aJ(e){let{fjallOrgId:t,providerArn:r,issuerDomain:i,accountId:n}=e;return[{Sid:"FjallDevSubjectsThisAccount",Effect:"Allow",Principal:{Federated:r},Action:"sts:AssumeRoleWithWebIdentity",Condition:{StringEquals:{[`${i}:aud`]:Bx},StringLike:{[`${i}:sub`]:`org:${t}:dev:${n}:*`}}}]}ut(aJ,"buildDevDeployTrustStatements");function Gx(e){let{providerArn:t,issuerDomain:r,sid:i,subject:n}=e;return[{Sid:i,Effect:"Allow",Principal:{Federated:t},Action:"sts:AssumeRoleWithWebIdentity",Condition:{StringEquals:{[`${r}:aud`]:Bx,[`${r}:sub`]:n}}}]}ut(Gx,"buildServiceSubjectTrustStatements");function oJ(e){return Gx({...e,sid:"FjallDevProvisionerSubject",subject:ij(e.fjallOrgId)})}ut(oJ,"buildDevProvisionerTrustStatements");function sJ(e){return Gx({...e,sid:"FjallDevSyncSubject",subject:aj(e.fjallOrgId)})}ut(sJ,"buildDevSyncWriterTrustStatements");function cJ({accountId:e}){return[{Sid:"FjallDevEcsTaggedMutations",Effect:"Allow",Action:["ecs:UpdateService","ecs:DeleteService","ecs:RunTask","ecs:StopTask"],Resource:`arn:aws:ecs:*:${e}:*`,Condition:{StringEquals:{"aws:ResourceTag/fjall:dev":"true"}}},{Sid:"FjallDevEcsTaggedCreates",Effect:"Allow",Action:["ecs:RegisterTaskDefinition","ecs:CreateService"],Resource:"*",Condition:{StringEquals:{"aws:RequestTag/fjall:dev":"true"}}},{Sid:"FjallDevEcsTagOnCreate",Effect:"Allow",Action:["ecs:TagResource"],Resource:`arn:aws:ecs:*:${e}:*`,Condition:{StringEquals:{"ecs:CreateAction":["RegisterTaskDefinition","CreateService","RunTask"]}}},{Sid:"FjallDevEcsReads",Effect:"Allow",Action:["ecs:Describe*","ecs:List*"],Resource:"*"},{Sid:"FjallDevEcsDeregisterTaskDefinition",Effect:"Allow",Action:["ecs:DeregisterTaskDefinition"],Resource:`arn:aws:ecs:*:${e}:task-definition/fjall-dev-*`},{Sid:"FjallDevElbTaggedMutations",Effect:"Allow",Action:["elasticloadbalancing:ModifyRule","elasticloadbalancing:DeleteRule","elasticloadbalancing:ModifyTargetGroup","elasticloadbalancing:ModifyTargetGroupAttributes","elasticloadbalancing:DeleteTargetGroup","elasticloadbalancing:RegisterTargets","elasticloadbalancing:DeregisterTargets"],Resource:`arn:aws:elasticloadbalancing:*:${e}:*`,Condition:{StringEquals:{"aws:ResourceTag/fjall:dev":"true"}}},{Sid:"FjallDevElbTaggedCreates",Effect:"Allow",Action:["elasticloadbalancing:CreateTargetGroup","elasticloadbalancing:CreateRule"],Resource:`arn:aws:elasticloadbalancing:*:${e}:*`,Condition:{StringEquals:{"aws:RequestTag/fjall:dev":"true"}}},{Sid:"FjallDevElbTagOnCreate",Effect:"Allow",Action:["elasticloadbalancing:AddTags"],Resource:`arn:aws:elasticloadbalancing:*:${e}:*`,Condition:{StringEquals:{"elasticloadbalancing:CreateAction":["CreateTargetGroup","CreateRule"]}}},{Sid:"FjallDevElbReads",Effect:"Allow",Action:["elasticloadbalancing:Describe*"],Resource:"*"},{Sid:"FjallDevSsmDevTree",Effect:"Allow",Action:["ssm:GetParameter*","ssm:PutParameter","ssm:AddTagsToResource"],Resource:`arn:aws:ssm:*:${e}:parameter/fjall/dev/*`},{Sid:"FjallDevLogsMutations",Effect:"Allow",Action:["logs:PutRetentionPolicy","logs:DeleteLogGroup"],Resource:`arn:aws:logs:*:${e}:log-group:/fjall/dev/*`},{Sid:"FjallDevLogsTaggedCreate",Effect:"Allow",Action:["logs:CreateLogGroup","logs:TagResource"],Resource:`arn:aws:logs:*:${e}:log-group:/fjall/dev/*`,Condition:{StringEquals:{"aws:RequestTag/fjall:dev":"true"}}},{Sid:"FjallDevLogsRead",Effect:"Allow",Action:["logs:GetLogEvents","logs:DescribeLogStreams","logs:FilterLogEvents"],Resource:`arn:aws:logs:*:${e}:log-group:/fjall/dev/*`},{Sid:"FjallDevLogsDescribeGroups",Effect:"Allow",Action:["logs:DescribeLogGroups"],Resource:"*"},{Sid:"FjallDevKmsViaDevAlias",Effect:"Allow",Action:["kms:Encrypt","kms:Decrypt","kms:GenerateDataKey"],Resource:`arn:aws:kms:*:${e}:key/*`,Condition:{"ForAnyValue:StringLike":{"kms:ResourceAliases":"alias/fjall-dev-*"}}},{Sid:"FjallDevKmsSsmSecureString",Effect:"Allow",Action:["kms:Encrypt","kms:Decrypt","kms:GenerateDataKey"],Resource:`arn:aws:kms:*:${e}:key/*`,Condition:{StringLike:{"kms:ViaService":"ssm.*.amazonaws.com"}}},{Sid:"FjallDevEcrAuthToken",Effect:"Allow",Action:["ecr:GetAuthorizationToken"],Resource:"*"},{Sid:"FjallDevEcrPushPull",Effect:"Allow",Action:["ecr:PutImage","ecr:InitiateLayerUpload","ecr:UploadLayerPart","ecr:CompleteLayerUpload","ecr:BatchCheckLayerAvailability","ecr:BatchGetImage","ecr:GetDownloadUrlForLayer","ecr:DescribeImages"],Resource:`arn:aws:ecr:*:${e}:repository/*`},{Sid:"FjallDevPassDevPathRoles",Effect:"Allow",Action:["iam:PassRole"],Resource:`arn:aws:iam::${e}:role/fjall/dev/*`}]}ut(cJ,"buildDevDeployPolicyStatements");function lJ({accountId:e}){return[{Sid:"FjallDevProvisionerBoundedRoleWrites",Effect:"Allow",Action:["iam:CreateRole","iam:PutRolePolicy","iam:AttachRolePolicy"],Resource:`arn:aws:iam::${e}:role/fjall/dev/*`,Condition:{StringEquals:{"iam:PermissionsBoundary":nj(e)}}},{Sid:"FjallDevProvisionerPathRoleOps",Effect:"Allow",Action:["iam:DeleteRole","iam:DeleteRolePolicy","iam:DetachRolePolicy","iam:ListRolePolicies","iam:TagRole"],Resource:`arn:aws:iam::${e}:role/fjall/dev/*`},{Sid:"FjallDevProvisionerListRoles",Effect:"Allow",Action:["iam:ListRoles"],Resource:"*"},{Sid:"FjallDevProvisionerDevMasterSecrets",Effect:"Allow",Action:["secretsmanager:GetSecretValue"],Resource:`arn:aws:secretsmanager:*:${e}:secret:fjall-dev-*`},{Sid:"FjallDevProvisionerKmsDecryptViaSecretsManager",Effect:"Allow",Action:["kms:Decrypt"],Resource:`arn:aws:kms:*:${e}:key/*`,Condition:{StringLike:{"kms:ViaService":"secretsmanager.*.amazonaws.com"}}},{Sid:"FjallDevProvisionerDataApi",Effect:"Allow",Action:["rds-data:ExecuteStatement","rds-data:BatchExecuteStatement","rds-data:BeginTransaction","rds-data:CommitTransaction","rds-data:RollbackTransaction"],Resource:`arn:aws:rds:*:${e}:cluster:fjall-dev-*`},{Sid:"FjallDevProvisionerMetrics",Effect:"Allow",Action:["cloudwatch:GetMetricData"],Resource:"*"},{Sid:"FjallDevProvisionerOrphanDiscovery",Effect:"Allow",Action:["tag:GetResources"],Resource:"*"},{Sid:"FjallDevProvisionerSsmTeardown",Effect:"Allow",Action:["ssm:DeleteParameter*"],Resource:`arn:aws:ssm:*:${e}:parameter/fjall/dev/*`},{Sid:"FjallDevProvisionerLogsTeardown",Effect:"Allow",Action:["logs:DeleteLogGroup"],Resource:`arn:aws:logs:*:${e}:log-group:/fjall/dev/*`},{Sid:"FjallDevProvisionerTaggedTeardown",Effect:"Allow",Action:["ecs:UpdateService","ecs:StopTask","ecs:DeleteService","elasticloadbalancing:DeleteRule","elasticloadbalancing:DeleteTargetGroup","elasticloadbalancing:DeregisterTargets"],Resource:[`arn:aws:ecs:*:${e}:*`,`arn:aws:elasticloadbalancing:*:${e}:*`],Condition:{StringEquals:{"aws:ResourceTag/fjall:dev":"true"}}},{Sid:"FjallDevProvisionerTeardownReads",Effect:"Allow",Action:["ecs:Describe*","elasticloadbalancing:Describe*"],Resource:"*"},{Sid:"FjallDevProvisionerImageJanitor",Effect:"Allow",Action:["ecr:ListImages","ecr:DescribeImages","ecr:BatchDeleteImage"],Resource:`arn:aws:ecr:*:${e}:repository/*`},{Sid:"FjallDevProvisionerSsmReadAll",Effect:"Allow",Action:["ssm:GetParameter*"],Resource:`arn:aws:ssm:*:${e}:parameter/*`},{Sid:"FjallDevProvisionerKmsDecryptViaSsm",Effect:"Allow",Action:["kms:Decrypt"],Resource:`arn:aws:kms:*:${e}:key/*`,Condition:{StringLike:{"kms:ViaService":"ssm.*.amazonaws.com"}}}]}ut(lJ,"buildDevProvisionerPolicyStatements");function uJ({accountId:e}){return[{Sid:"FjallDevSyncPrefixReadWrite",Effect:"Allow",Action:["s3:GetObject","s3:PutObject"],Resource:`arn:aws:s3:::fjall-dev-sync-${e}-*/*`,Condition:{StringEquals:{"aws:ResourceAccount":e}}}]}ut(uJ,"buildDevSyncWriterPolicyStatements");function dJ({accountId:e}){return[{Sid:"FjallDevBoundarySsmDevRead",Effect:"Allow",Action:["ssm:GetParameter*"],Resource:`arn:aws:ssm:*:${e}:parameter/fjall/dev/*`},{Sid:"FjallDevBoundaryKmsDecryptDevAlias",Effect:"Allow",Action:["kms:Decrypt"],Resource:`arn:aws:kms:*:${e}:key/*`,Condition:{"ForAnyValue:StringLike":{"kms:ResourceAliases":"alias/fjall-dev-*"}}},{Sid:"FjallDevBoundarySyncPrefixReadWrite",Effect:"Allow",Action:["s3:GetObject","s3:PutObject"],Resource:`arn:aws:s3:::fjall-dev-sync-${e}-*/*`,Condition:{StringEquals:{"aws:ResourceAccount":e}}},{Sid:"FjallDevBoundarySlotLogs",Effect:"Allow",Action:["logs:CreateLogStream","logs:PutLogEvents"],Resource:`arn:aws:logs:*:${e}:log-group:/fjall/dev/*`},{Sid:"FjallDevBoundarySyncQueue",Effect:"Allow",Action:["sqs:ReceiveMessage","sqs:DeleteMessage","sqs:GetQueueUrl"],Resource:`arn:aws:sqs:*:${e}:fjall-dev-sync-${e}-*`}]}ut(dJ,"buildDevBoundaryStatements");var pJ=Object.defineProperty,Yt=(e,t)=>pJ(e,"name",{value:t,configurable:!0});function J(e){return JSON.stringify(e)}Yt(J,"escapeStringLiteral");function Jl(e){return e.map(J).join(", ")}Yt(Jl,"formatStringArray");var mJ="import:SharedAlarmTopicArn";function Ea(e=" "){return`
@@ -552,7 +552,7 @@ app.${xs.appMethod}(
552
552
  accessGate: ${Ae(e.cdn.accessGate," ")}`),r+=rt(e.cdn.extraProperties),r+=`
553
553
  })
554
554
  );
555
- `,r}Dr(Lh,"generateCDNCode");function Ru(e){let t=new Set;if(e.cdn&&(e.cdn.defaultOriginRef&&t.add(e.cdn.defaultOriginRef),e.cdn.behaviours))for(let r of e.cdn.behaviours)t.add(r.originRef);return t}Dr(Ru,"collectCdnReferencedResources");function Rs(e){return e.patternConfig!==void 0}Dr(Rs,"usesPatternApproach");var B5=Object.defineProperty,ja=(e,t)=>B5(e,"name",{value:t,configurable:!0}),Ou="service",dT="cron(0 4 * * ? *)",pT="cron(0 5 * * ? *)",Zn=Object.freeze({tinkerer:{displayName:"Tinkerer",description:"Free tier eligible, minimal cost for experimentation",database:{Instance:{instanceType:"t4g.micro",multiAz:!1,proxy:!1,readReplica:!1,publiclyAccessible:!0},Aurora:null,GlobalAurora:null,ClickHouse:null},compute:{ecs:{services:[{name:Ou,capacityProvider:"EC2",desiredCount:1,minCapacity:1,maxCapacity:1,ec2Config:{instanceType:"t4g.micro",amiHardwareType:"ARM",minCapacity:1,maxCapacity:1,memoryLimitMiB:400}}],cluster:{directAccess:!0}},lambda:{timeout:30,memory:128}},network:{maxAzs:2,natGateways:!1,flowLogs:!1},backup:!1},lightweight:{displayName:"Lightweight",description:"Streamlined single-AZ deployment for cost efficiency",database:{Instance:{instanceType:"t4g.small",multiAz:!1},Aurora:{readers:!1},GlobalAurora:null,ClickHouse:null},compute:{ecs:{services:[{name:Ou,capacityProvider:"FARGATE_SPOT",cpu:256,memoryLimitMiB:512,desiredCount:1,minCapacity:1,maxCapacity:3}]},lambda:{timeout:30,memory:256}},network:{maxAzs:2,natGateways:{count:1},flowLogs:!1},backup:!1},standard:{displayName:"Standard",description:"Production-ready with sensible defaults",database:{Instance:{instanceType:"t4g.large"},Aurora:{readers:{count:1}},GlobalAurora:{readers:{count:1}},ClickHouse:{instanceType:"t4g.medium",coldTier:{mode:"s3"},optimiseSchedule:dT,backupSchedule:pT,backupRetentionDays:14}},compute:{ecs:{services:[{name:Ou,capacityProvider:"FARGATE",cpu:512,memoryLimitMiB:1024,desiredCount:2,minCapacity:2,maxCapacity:5}]},lambda:{timeout:60,memory:256}},network:{maxAzs:3,natGateways:{count:1},flowLogs:{},vpcEndpoints:{interface:{ecr:!0}}},backup:!1},resilient:{displayName:"Resilient",description:"High availability with enhanced monitoring and scaling",database:{Instance:{instanceType:"r7g.large",encryption:{storageKey:{useCMK:!0}},databaseInsights:{mode:"advanced",encryptionKey:{useCMK:!0}},proxy:{requireTLS:!0}},Aurora:{readers:{count:2},encryption:{storageKey:{useCMK:!0}},databaseInsights:{mode:"advanced",encryptionKey:{useCMK:!0}},proxy:{requireTLS:!0},backupRetention:30},GlobalAurora:{readers:{count:2},encryption:{storageKey:{useCMK:!0}},databaseInsights:{mode:"advanced",encryptionKey:{useCMK:!0}},proxy:{requireTLS:!0},backupRetention:30,enableGlobalWriteForwarding:!0},ClickHouse:{instanceType:"m7g.large",coldTier:{mode:"s3"},optimiseSchedule:dT,backupSchedule:pT,backupRetentionDays:14}},compute:{ecs:{services:[{name:Ou,capacityProvider:"FARGATE",cpu:1024,memoryLimitMiB:2048,desiredCount:4,minCapacity:4,maxCapacity:20}]},lambda:{timeout:120,memory:512}},network:{maxAzs:3,natGateways:{count:3},flowLogs:{retentionDays:90},vpcEndpoints:{interface:{ecr:!0,secretsManager:!0}}},backup:{tier:"resilient"}},enterprise:{displayName:"Enterprise",description:"Maximum capability with all features enabled",database:{Instance:{instanceType:"r7g.xlarge",encryption:{storageKey:{useCMK:!0}},databaseInsights:{mode:"advanced",encryptionKey:{useCMK:!0}},proxy:{requireTLS:!0},readReplica:{}},Aurora:{readers:{count:2},encryption:{storageKey:{useCMK:!0}},databaseInsights:{mode:"advanced",encryptionKey:{useCMK:!0}},proxy:{requireTLS:!0},backupRetention:35},GlobalAurora:{readers:{count:2},encryption:{storageKey:{useCMK:!0}},databaseInsights:{mode:"advanced",encryptionKey:{useCMK:!0}},proxy:{requireTLS:!0},backupRetention:35,enableGlobalWriteForwarding:!0},ClickHouse:{instanceType:"m7g.xlarge",coldTier:{mode:"s3"},optimiseSchedule:dT,backupSchedule:pT,backupRetentionDays:30}},compute:{ecs:{services:[{name:Ou,capacityProvider:"FARGATE",cpu:2048,memoryLimitMiB:4096,desiredCount:6,minCapacity:6,maxCapacity:100}]},lambda:{timeout:300,memory:1024}},network:{maxAzs:3,natGateways:{count:3},flowLogs:{destination:"s3",retentionDays:365},vpcEndpoints:{interface:{ecr:!0,secretsManager:!0,kms:!0,cloudwatchLogs:!0}}},backup:{tier:"enterprise"}}});function G5(e,t){return Zn[e].database[t]}ja(G5,"getDatabasePreset");function V5(e){return Zn[e].compute.ecs}ja(V5,"getEcsPreset");function mT(e){return Zn[e].network}ja(mT,"getNetworkPreset");function aL(e){return Af.filter(t=>Zn[t].database[e]!==null)}ja(aL,"getAvailableTiersForDatabase");function W5(e){return aL(e).map(t=>({label:Zn[t].displayName,value:t,description:Zn[t].description}))}ja(W5,"getTierOptionsForDatabase");function fT(e){switch(e){case"tinkerer":case"lightweight":case"standard":return"Instance";case"resilient":case"enterprise":return"Aurora"}}ja(fT,"getDefaultDatabaseTypeForTier");function hT(e,t){let r=Zn[e].compute.ecs,i=r.services[0],n=!r.cluster?.directAccess&&r.cluster?.loadBalancer!==!1,a=t.filter(s=>s.serviceType!=="worker").length,o=t.findIndex(s=>s.serviceType!=="worker");return t.map((s,l)=>{let m=l===o,d=s.serviceType==="worker",h;return n&&!d&&(s.routing?h=s.routing:a>1&&(h={path:m?"/*":`/${s.name.toLowerCase()}/*`,...m?{}:{priority:100+l}})),{name:s.name,capacityProvider:i.capacityProvider,ec2Config:i.ec2Config,cpu:i.cpu,memoryLimitMiB:i.memoryLimitMiB,desiredCount:i.desiredCount,minCapacity:i.minCapacity,maxCapacity:i.maxCapacity,routing:h}})}ja(hT,"applyTierDefaultsToServices");var K5=Object.defineProperty,gT=(e,t)=>K5(e,"name",{value:t,configurable:!0}),$u=["lightweight","standard","resilient"],Z5=[...$u,"custom"],ki=Object.freeze({lightweight:{displayName:"Lightweight",description:"Cost-effective \xB7 Instance DB, minimal Lambda",database:{type:"Instance",instanceType:"t4g.small",backupRetention:7,deletionProtection:!1},compute:{memorySize:512,timeout:30},network:{maxAzs:2,natGateways:{count:1},flowLogs:!1},backup:!1},standard:{displayName:"Standard",description:"Production-ready \xB7 Instance DB, balanced Lambda",database:{type:"Instance",instanceType:"t4g.large",backupRetention:14,deletionProtection:!0},compute:{memorySize:1536,timeout:60},network:{maxAzs:3,natGateways:{count:1},flowLogs:{}},backup:{tier:"standard"}},resilient:{displayName:"Resilient",description:"High-availability \xB7 Aurora V2, KMS encryption",database:{type:"Aurora",backupRetention:30,deletionProtection:!0,encryption:{useCMK:!0}},compute:{memorySize:2048,timeout:120},network:{maxAzs:3,natGateways:{count:3},flowLogs:{retentionDays:90}},backup:{tier:"resilient"}}});function Fh(e){return ki[e]}gT(Fh,"getPatternTierPreset");function oL(){return[{label:ki.standard.displayName,value:"standard",description:ki.standard.description},{label:ki.lightweight.displayName,value:"lightweight",description:ki.lightweight.description},{label:ki.resilient.displayName,value:"resilient",description:ki.resilient.description},{label:"Custom",value:"custom",description:"Full control \xB7 Configure everything"}]}gT(oL,"getPatternTierOptions");var H5=new Set($u);function Uh(e){return H5.has(e)}gT(Uh,"isPatternTierName");var J5=Object.defineProperty,sL=(e,t)=>J5(e,"name",{value:t,configurable:!0}),zh=Object.freeze({standard:{},assets:{versioned:!0,deployment:{source:"./assets"}},upload:{versioned:!0,cors:[{allowedOrigins:["*"],allowedMethods:["GET","PUT","POST"]}]},website:{publicReadAccess:!0,websiteHosting:{indexDocument:"index.html",errorDocument:"error.html"}}});function cL(e){return{...zh[e]}}sL(cL,"getStoragePreset");function lL(){return[{label:"Standard",value:"standard"},{label:"Assets",value:"assets"},{label:"Upload",value:"upload"},{label:"Website Hosting",value:"website"}]}sL(lL,"getStoragePresetOptions");import*as nt from"typescript";import*as ae from"typescript";var X5=Object.defineProperty,Os=(e,t)=>X5(e,"name",{value:t,configurable:!0});function ye(e){let t={};for(let r of e.properties){if(!ae.isPropertyAssignment(r))continue;let i=ae.isIdentifier(r.name)||ae.isStringLiteral(r.name)?r.name.text:void 0;i!==void 0&&(t[i]=wi(r.initializer))}return t}Os(ye,"parseObjectLiteral");function wi(e){if(ae.isStringLiteral(e))return e.text;if(ae.isNumericLiteral(e))return Number(e.text);if(e.kind===ae.SyntaxKind.TrueKeyword)return!0;if(e.kind===ae.SyntaxKind.FalseKeyword)return!1;if(ae.isArrayLiteralExpression(e))return e.elements.map(t=>wi(t));if(ae.isObjectLiteralExpression(e))return ye(e);if(ae.isIdentifier(e))return{__identifier:e.text};if(ae.isPropertyAccessExpression(e))return{__expression:e.getText()};if(ae.isCallExpression(e))return{__call:e.getText()};if(ae.isBinaryExpression(e)&&e.operatorToken.kind===ae.SyntaxKind.BarBarToken){let t=wi(e.left),r=wi(e.right);return typeof r=="string"?r:t}else if(ae.isConditionalExpression(e)){let t=wi(e.whenTrue),r=wi(e.whenFalse);return typeof r=="string"||typeof r=="number"?r:t}else if(ae.isTemplateExpression(e)||ae.isNoSubstitutionTemplateLiteral(e))return{__expression:e.getText()};return{__unknown:e.getText()}}Os(wi,"evaluateExpression");function ju(e,t){return rr(e,r=>{if(ae.isVariableStatement(r)){for(let i of r.declarationList.declarations)if(ae.isIdentifier(i.name)&&i.name.text===t&&i.initializer){if(ae.isStringLiteral(i.initializer))return i.initializer.text;if(ae.isObjectLiteralExpression(i.initializer)){let n=ye(i.initializer);return JSON.stringify(n)}}}})}Os(ju,"findVariableValue");function yT(e,t){return rr(e,r=>{if(ae.isVariableStatement(r)){for(let i of r.declarationList.declarations)if(ae.isIdentifier(i.name)&&i.name.text===t&&i.initializer&&ae.isObjectLiteralExpression(i.initializer))return ye(i.initializer)}})}Os(yT,"findObjectDeclaration");function Mu(e,t){if(!ae.isIdentifier(t.expression))return;let r=yT(e,t.expression.text),i=t.name.text;if(r&&r[i]!==void 0)return String(r[i])}Os(Mu,"evaluatePropertyAccess");function Bh(e,t){let r=t.head.text;for(let i of t.templateSpans){if(ae.isIdentifier(i.expression)){let n=ju(e,i.expression.text);if(n)r+=n;else return t.getText(e).replace(/^`|`$/g,"")}else if(ae.isPropertyAccessExpression(i.expression)){let n=Mu(e,i.expression);if(n)r+=n;else return t.getText(e).replace(/^`|`$/g,"")}else return t.getText(e).replace(/^`|`$/g,"");r+=i.literal.text}return r}Os(Bh,"resolveTemplateLiteral");var q5=Object.defineProperty,Pe=(e,t)=>q5(e,"name",{value:t,configurable:!0});function Nr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}Pe(Nr,"isPlainObject");function Hn(e){return Nr(e)&&"__identifier"in e}Pe(Hn,"isIdentifierRef");function Pi(e){return Nr(e)&&"__expression"in e}Pe(Pi,"isExpressionRef");function Zr(e){return Nr(e)&&"__call"in e}Pe(Zr,"isCallRef");function Z(e){return Nr(e)&&!("__identifier"in e)&&!("__expression"in e)&&!("__call"in e)&&!("__unknown"in e)}Pe(Z,"isParsedObject");function w(e){return typeof e=="string"?e:void 0}Pe(w,"asString");function W(e){return typeof e=="number"?e:void 0}Pe(W,"asNumber");function oe(e){return typeof e=="boolean"?e:void 0}Pe(oe,"asBoolean");function He(e){if(!Array.isArray(e))return;let t=[];for(let r of e){if(typeof r!="string")return;t.push(r)}return t.length>0?t:void 0}Pe(He,"asStringArray");function se(e,t){let r=w(e);if(r!==void 0)return Ft(t,r)?r:void 0}Pe(se,"asStringUnion");function Gt(e){let t={};for(let[r,i]of Object.entries(e))i!==void 0&&(t[r]=i);return t}Pe(Gt,"omitUndefined");function Gh(e){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean")return String(e);if(Array.isArray(e))return`[${e.map(Gh).join(", ")}]`;if(!Nr(e))return String(e);if(Hn(e))return e.__identifier;if(Pi(e))return e.__expression;if(Zr(e))return e.__call;if("__unknown"in e&&typeof e.__unknown=="string")return e.__unknown;let t=Object.entries(e);return t.length===0?"{}":`{ ${t.map(([r,i])=>`${r}: ${Gh(i)}`).join(", ")} }`}Pe(Gh,"parsedValueToSourceText");function Ze(e,t){let r=[];for(let[i,n]of Object.entries(e))t.has(i)||n===void 0||r.push({key:i,sourceText:Gh(n)});return r}Pe(Ze,"captureExtraProperties");function Ri(e,t){return nt.isPropertyAssignment(e)&&nt.isIdentifier(e.name)&&e.name.text===t}Pe(Ri,"isNamedProperty");function fn(e){return nt.isCallExpression(e)&&nt.isPropertyAccessExpression(e.expression)&&e.expression.name.text==="getApp"&&nt.isIdentifier(e.expression.expression)&&e.expression.expression.text==="App"}Pe(fn,"isAppGetAppCall");function ft(e,t){let{expression:r}=e;return nt.isPropertyAccessExpression(r)&&r.name.text===t&&e.arguments.length>0}Pe(ft,"isFactoryMethodCall");function rr(e,t){let r,i=Pe(n=>{r===void 0&&(r=t(n),r===void 0&&nt.forEachChild(n,i))},"visit");return i(e),r}Pe(rr,"findFirstInAst");function bt(e,t){let r=[],i=Pe(n=>{let a=t(n);a!==null&&r.push(a),nt.forEachChild(n,i)},"visit");return i(e),r}Pe(bt,"collectFromAst");function Rt(e,t){return nt.isCallExpression(e)&&nt.isPropertyAccessExpression(e.expression)&&e.expression.name.text==="build"&&nt.isIdentifier(e.expression.expression)&&e.expression.expression.text===t}Pe(Rt,"isFactoryBuildCall");function nr(e){let t=e.parent;if(nt.isVariableDeclaration(t)&&nt.isIdentifier(t.name))return t.name.text}Pe(nr,"extractVariableName");var kr=Pe(()=>e=>e,"typed");function $s(e){if(e!=null){if(e===!1)return!1;if(typeof e=="object"&&!Array.isArray(e))return e}}Pe($s,"asObjectOrFalse");function Hr(e,t){return e===!1?!1:Z(e)?t(e):void 0}Pe(Hr,"parseBooleanOrConfig");function Et(e,t){return Z(e)?t(e):void 0}Pe(Et,"parseOptionalConfig");function ir(e,t,r){let i=e[t];return Z(i)?r(i):void 0}Pe(ir,"extractSubConfig");import*as Te from"typescript";import*as Ms from"typescript";var Y5=Object.defineProperty,ar=(e,t)=>Y5(e,"name",{value:t,configurable:!0});function Lu(e){return e!==void 0&&Nr(e)}ar(Lu,"isEnvironmentRecord");function uL(e){if(!Z(e))return;let t={};for(let[r,i]of Object.entries(e))if(Z(i)){let n=w(i.id),a=w(i.name);n&&a&&(t[r]={id:n,name:a,field:w(i.field)})}return Object.keys(t).length>0?t:void 0}ar(uL,"parseContainerSecretsImport");function dL(e){if(!Z(e))return;let t=He(e.command);if(!(!t||t.length===0))return{command:t,interval:W(e.interval),timeout:W(e.timeout),retries:W(e.retries),startPeriod:W(e.startPeriod)}}ar(dL,"parseContainerHealthCheck");function pL(e){let t=Ze(e,new Set(["name","image","port","environment","essential","command","entryPoint","secretsImport","secrets","healthCheck"]));return{name:w(e.name),image:w(e.image),port:W(e.port),environment:Lu(e.environment)?e.environment:void 0,essential:oe(e.essential),command:He(e.command),entryPoint:He(e.entryPoint),secretsImport:uL(e.secretsImport),ssmSecrets:He(e.secrets),healthCheck:dL(e.healthCheck),extraProperties:t.length>0?t:void 0}}ar(pL,"parseServiceContainer");function mL(e){if(Array.isArray(e))return e.filter(Z).map(t=>({path:w(t.path),host:w(t.host),priority:W(t.priority),healthCheckPath:w(t.healthCheckPath)}));if(Z(e))return{path:w(e.path),host:w(e.host),priority:W(e.priority),healthCheckPath:w(e.healthCheckPath)}}ar(mL,"parseServiceRouting");function fL(e){if(e===!1)return!1;if(Z(e))return{minCapacity:W(e.minCapacity),maxCapacity:W(e.maxCapacity),desiredCount:W(e.desiredCount),scalingType:se(js(e.scalingType,"ScalingType"),If)}}ar(fL,"parseServiceScaling");var Q5=new Set(["instanceType","amiHardwareType","minCapacity","maxCapacity","memoryLimitMiB","warmPool"]);function hL(e){if(!Z(e))return;let t=e.warmPool,r=Z(t)?{minSize:W(t.minSize),reuseOnScaleIn:oe(t.reuseOnScaleIn)}:void 0,i=Ze(e,Q5);return{instanceType:w(e.instanceType),amiHardwareType:se(e.amiHardwareType,Df),minCapacity:W(e.minCapacity),maxCapacity:W(e.maxCapacity),memoryLimitMiB:W(e.memoryLimitMiB),warmPool:r,extraProperties:i.length>0?i:void 0}}ar(hL,"parseServiceEc2Config");var eq=new Set(["domain","loadBalancer","directAccess"]);function vT(e){if(!Z(e))return;let t=e.loadBalancer,r=Ze(e,eq);return{domain:w(e.domain),loadBalancer:t===!1?!1:se(t,Cf),directAccess:oe(e.directAccess),...r.length>0&&{extraProperties:r}}}ar(vT,"extractClusterConfig");function ST(e){let t=e.containers,r=Array.isArray(t)?t.filter(Z).map(pL):void 0,i=Ze(e,new Set(["name","image","docker","ssmSecretsPath","containers","routing","connections","serviceType","cpu","memoryLimitMiB","desiredCount","scaling","capacityProvider","ec2Config"]));return{name:w(e.name)??"",image:w(e.image),docker:gL(e.docker),ssmSecretsPath:w(e.ssmSecretsPath),containers:r,routing:mL(e.routing),serviceType:se(e.serviceType,Ol),cpu:W(e.cpu),memoryLimitMiB:W(e.memoryLimitMiB),desiredCount:W(e.desiredCount),scaling:fL(e.scaling),capacityProvider:se(e.capacityProvider,ls)??"FARGATE",ec2Config:hL(e.ec2Config),...i.length>0&&{extraProperties:i}}}ar(ST,"parseEcsService");function gL(e){if(!Z(e))return;let t=w(e.path);if(t===void 0)return;let r=w(e.context),i=w(e.target);return{path:t,...r!==void 0&&{context:r},...i!==void 0&&{target:i}}}ar(gL,"parseServiceDocker");function js(e,t){let r=w(e);if(r)return r;if(Pi(e)&&e.__expression.startsWith(t+"."))return e.__expression.slice(t.length+1)}ar(js,"extractEnumString");function bT(e){return Zr(e)?e.__call.match(/\(\s*"([^"]+)"\s*\)/)?.[1]:void 0}ar(bT,"extractCallStringArg");function At(e,t,r){r!==void 0&&(e[t]=r)}ar(At,"assignIfDefined");var tq=Object.defineProperty,Vh=(e,t)=>tq(e,"name",{value:t,configurable:!0}),rq=10;function ET(e,t){return Array.isArray(e)?e.filter(Hn).map(r=>t.find(i=>i.variableName===r.__identifier)).filter(r=>r!==void 0).map(r=>r.resourceName):[]}Vh(ET,"resolveConnectedDatabaseNames");function AT(e,t){return Array.isArray(e)?e.filter(Hn).map(r=>t.find(i=>i.variableName===r.__identifier)).filter(r=>r!==void 0).map(r=>r.resourceName):[]}Vh(AT,"resolveConnectedStorageNames");function _T(e,t,r){if(!Array.isArray(t)||t.length===0)return;let i=t[0];if(!Z(i))return;let n=i.containers;if(!Array.isArray(n)||n.length===0)return;let a=n[0];if(!Z(a)||!Z(a.environment))return;let o=a.environment;(o.DATABASE_HOST||o.DATABASE_PORT||o.DATABASE_NAME)&&(e.needsConnection=!0,r.length>0&&(e.connectedDatabase??[]).length===0&&(e.connectedDatabase=[r[0].name]));for(let s=1;s<=rq;s++)(o[`DATABASE_HOST_${s}`]||o[`DATABASE_PORT_${s}`]||o[`DATABASE_NAME_${s}`])&&(e.needsConnection=!0)}Vh(_T,"inferDatabaseConnectionsFromEnv");function xT(e,t,r){if(!Array.isArray(t)||t.length===0)return;let i=t[0];if(!Z(i))return;let n=i.containers;if(!Array.isArray(n)||n.length===0)return;let a=n[0];!Z(a)||!Z(a.environment)||a.environment.BUCKET_NAME&&r.length>0&&(e.connectedStorage??[]).length===0&&(e.connectedStorage=[r[0].name])}Vh(xT,"inferStorageConnectionsFromEnv");var nq=Object.defineProperty,Jn=(e,t)=>nq(e,"name",{value:t,configurable:!0});function yL(e){if(e.arguments.length<2)return null;let t=e.arguments[0],r=e.arguments[1];if(!Ms.isStringLiteral(t)||!Ms.isObjectLiteralExpression(r))return null;let i=t.text,n=ye(r);return{resourceName:i,type:w(n.type)??"ecs",config:n,node:e}}Jn(yL,"extractComputeResource");function Wh(e){return bt(e,t=>{if(!Ms.isCallExpression(t)||!ft(t,"addCompute"))return null;let r=t.arguments[0];if(!Rt(r,"ComputeFactory"))return null;let i=yL(r);if(i){let n=nr(t);n&&(i.variableName=n)}return i})}Jn(Wh,"findComputeResources");function Kh(e,t,r){let i=Ze(e.config,r);i.length>0&&(t.extraProperties=i)}Jn(Kh,"applyExtras");function vL(e,t){let r=e.config.docker;if(Z(r)){let a=w(r.path),o=w(r.context),s=w(r.target);(a!==void 0||o!==void 0||s!==void 0)&&(t.docker={...a!==void 0&&{path:a},...o!==void 0&&{context:o},...s!==void 0&&{target:s}})}let i=e.config.cluster;i!==void 0&&(t.cluster=vT(i));let n=e.config.services;n!==void 0&&Array.isArray(n)&&(t.services=n.filter(a=>Z(a)).map(ST)),Kh(e,t,new Set(["type","ecrRepository","docker","cluster","services","connections"]))}Jn(vL,"convertEcsCompute");function SL(e,t){if(At(t,"deployment",se(e.config.deployment,_f)),At(t,"timeout",W(e.config.timeout)),At(t,"memory",W(e.config.memorySize)??W(e.config.memory)),At(t,"handler",w(e.config.handler)),At(t,"runtime",js(e.config.runtime,"Runtime")),Lu(e.config.environment)&&(t.environment=e.config.environment),Lu(e.config.secrets))t.secrets=e.config.secrets;else{let n=He(e.config.secrets);n&&(t.ssmSecrets=n)}let r=e.config.functionUrl;if(Z(r)){let n=se(js(r.authType,"FunctionUrlAuthType"),Rl);n!==void 0&&(t.functionUrl={authType:n})}let i=e.config.code;if(i!==void 0){let n=bT(i);n&&(t.codePath=n)}At(t,"description",w(e.config.description)??w(e.config.lambdaDescription)),At(t,"architecture",se(js(e.config.architecture,"Architecture"),Tf)),At(t,"ephemeralStorageSize",W(e.config.ephemeralStorageSize)),At(t,"functionName",w(e.config.functionName)),At(t,"ssmSecretsPath",w(e.config.ssmSecretsPath)),Kh(e,t,new Set(["type","deployment","timeout","memorySize","memory","handler","runtime","environment","secrets","functionUrl","code","connections","ecrRepository","containerSecretsImport","secretsImport","lambdaDescription","description","architecture","ephemeralStorageSize","functionName","ssmSecretsPath"]))}Jn(SL,"convertLambdaCompute");function bL(e,t){At(t,"instanceType",se(e.config.instanceType,Nf));let r=e.config.ssh;r===!1?t.enableSSH=!1:r!==void 0&&Z(r)?t.enableSSH=!0:At(t,"enableSSH",oe(e.config.enableSSH)),At(t,"keyName",w(e.config.keyName)),At(t,"userData",w(e.config.userData)),e.config.securityGroups!==void 0&&(t.securityGroups=He(e.config.securityGroups)),Kh(e,t,new Set(["type","instanceType","ssh","enableSSH","keyName","userData","securityGroups","connections"]))}Jn(bL,"convertEc2Compute");function EL(e,t,r,i){let n=t.config.connections;if(!n&&Array.isArray(t.config.services)){let s=t.config.services[0];Z(s)&&(n=s.connections)}if(!n)return;let a=ET(n,r);a.length>0&&(e.needsConnection=!0,e.connectedDatabase=a);let o=AT(n,i);o.length>0&&(e.connectedStorage=o)}Jn(EL,"applyConnectionConfig");function AL(e,t){({ecs:vL,lambda:SL,ec2:bL})[e.type]?.(t,e)}Jn(AL,"applyTypeSpecificConfig");function TT(e,t,r,i){return e.map(n=>{let a=se(n.config.type,wl)??"ecs",o={name:n.resourceName,type:a,needsConnection:!1,connectedDatabase:[],...n.variableName&&{variableName:n.variableName}};return EL(o,n,t,r),AL(o,n),_T(o,n.config.services,i.database),xT(o,n.config.services,i.s3),o})}Jn(TT,"convertComputeResources");import*as wr from"typescript";var iq=Object.defineProperty,aq=(e,t)=>iq(e,"name",{value:t,configurable:!0});function Zh(e){return bt(e,t=>{if(!wr.isCallExpression(t)||!ft(t,"addSchedule")||t.arguments.length<2)return null;let r=t.arguments[0],i=t.arguments[1];if(!wr.isStringLiteral(r)||!wr.isObjectLiteralExpression(i))return null;let n=ye(i),a=w(n.schedule);if(a===void 0)return null;let o=i.properties.find(l=>wr.isPropertyAssignment(l)&&wr.isIdentifier(l.name)&&l.name.text==="target");if(!o||!wr.isPropertyAssignment(o)||!wr.isIdentifier(o.initializer))return null;let s=se(n.stackPlacement,ga);return{id:r.text,schedule:a,targetVariableName:o.initializer.text,...s!==void 0&&{stackPlacement:s}}})}aq(Zh,"findSchedules");import*as $e from"typescript";import*as Ot from"typescript";var oq=Object.defineProperty,Fu=(e,t)=>oq(e,"name",{value:t,configurable:!0}),CT=new Set(["S3Bucket"]);function _L(e,t,r){let i=Ot.isIdentifier(e.name)?e.name.text:"";if(t.arguments&&t.arguments.length>=2){let n=t.arguments[1],a=Ot.isStringLiteral(n)?n.text:"",o=t.arguments.length>=3?t.arguments[2]:void 0,s=o&&Ot.isObjectLiteralExpression(o)?ye(o):{};return{variableName:i,resourceName:a,bucketClass:r,config:s,node:e}}return null}Fu(_L,"extractS3Resource");function xL(e,t){if(t.arguments.length<2)return null;let r=t.arguments[0],i=t.arguments[1];if(!Ot.isStringLiteral(r)||!Ot.isObjectLiteralExpression(i))return null;let n=ye(i);return{variableName:nr(e)??"",resourceName:r.text,bucketClass:"StorageFactory",config:n,node:e}}Fu(xL,"extractS3FactoryResource");function IT(e){return bt(e,t=>{if(!Ot.isVariableDeclaration(t)||!t.initializer||!Ot.isNewExpression(t.initializer))return null;let r=t.initializer;if(!Ot.isIdentifier(r.expression))return null;let i=r.expression.text;return CT.has(i)?_L(t,r,i):null})}Fu(IT,"findS3Resources");function DT(e){return bt(e,t=>{if(!Ot.isCallExpression(t)||!ft(t,"addStorage"))return null;let r=t.arguments[0];return Rt(r,"StorageFactory")?xL(t,r):null})}Fu(DT,"findS3FactoryResources");function NT(e){return e.map(t=>({name:t.resourceName,...w(t.config.bucketName)&&{bucketName:w(t.config.bucketName)},...oe(t.config.publicReadAccess)===!0&&{publicReadAccess:!0},...Z(t.config.websiteHosting)&&(()=>{let r=t.config.websiteHosting;return{websiteHosting:{indexDocument:w(r.indexDocument)??"index.html",...w(r.errorDocument)&&{errorDocument:w(r.errorDocument)}}}})(),...se(t.config.backupVaultTier,Vr)&&{backupVaultTier:se(t.config.backupVaultTier,Vr)},...oe(t.config.versioned)!==void 0&&{versioned:oe(t.config.versioned)},...se(t.config.encryption,ps)&&{encryption:se(t.config.encryption,ps)},...w(t.config.kmsKeyArn)&&{kmsKeyArn:w(t.config.kmsKeyArn)},...Array.isArray(t.config.cors)&&t.config.cors.length>0&&{cors:t.config.cors.filter(Z).map(r=>({allowedOrigins:Array.isArray(r.allowedOrigins)?r.allowedOrigins.filter(i=>typeof i=="string"):[],allowedMethods:Array.isArray(r.allowedMethods)?r.allowedMethods.filter(i=>typeof i=="string"):[]}))},...Z(t.config.deployment)&&(()=>{let r=t.config.deployment;return{deployment:{source:w(r.source)??"",...oe(r.prune)!==void 0&&{prune:oe(r.prune)},...Z(r.cacheControl)&&(()=>{let i=r.cacheControl;return{cacheControl:{...W(i.maxAge)!==void 0&&{maxAge:W(i.maxAge)},...oe(i.immutable)!==void 0&&{immutable:oe(i.immutable)}}}})()}}})(),...se(t.config.stackPlacement,Bf)&&{stackPlacement:se(t.config.stackPlacement,Bf)},...t.variableName&&{variableName:t.variableName},...(()=>{let r=new Set(["bucketName","publicReadAccess","websiteHosting","backupVaultTier","versioned","encryption","kmsKeyArn","cors","deployment","stackPlacement"]),i=Ze(t.config,r);return i.length>0?{extraProperties:i}:{}})()}))}Fu(NT,"convertS3Resources");var sq=Object.defineProperty,Ma=(e,t)=>sq(e,"name",{value:t,configurable:!0}),TL=new Set(["App","Architecture","DatabaseFactory","StorageFactory","ComputeFactory","getConfig","MessagingFactory","CdnFactory","Code","Runtime","FunctionUrlAuthType","NetworkFactory","PatternFactory","CrossPlanConnectionFactory"]);function Hh(e){return!!(e.startsWith("@fjall/")||e==="aws-cdk-lib"||e.startsWith("aws-cdk-lib/")||e==="constructs")}Ma(Hh,"isManagedModuleSpecifier");function Vt(e){let t=[];for(let r of e.statements){let i=r.getFullStart(),n=r.getEnd();if($e.isImportDeclaration(r)){t.push({type:"import",node:r,startPos:i,endPos:n,isManaged:CL(r)});continue}if($e.isVariableStatement(r)){t.push(IL(r,i,n));continue}if($e.isExpressionStatement(r)){t.push(DL(r,i,n));continue}t.push({type:"custom",node:r,startPos:i,endPos:n,isManaged:!1})}return t}Ma(Vt,"classifyStatements");function CL(e){return $e.isStringLiteral(e.moduleSpecifier)?Hh(e.moduleSpecifier.text):!1}Ma(CL,"isManagedImport");function IL(e,t,r){for(let i of e.declarationList.declarations)if(i.initializer){if(fn(i.initializer))return{type:"app-init",node:e,resourceName:$e.isIdentifier(i.name)?i.name.text:void 0,startPos:t,endPos:r,isManaged:!0};if($e.isIdentifier(i.name)&&i.name.text==="appName"&&$e.isStringLiteral(i.initializer))return{type:"app-init",node:e,startPos:t,endPos:r,isManaged:!0};if($e.isNewExpression(i.initializer)){let n=i.initializer;if($e.isIdentifier(n.expression)){let a=n.expression.text;if(CT.has(a)){let o=n.arguments&&n.arguments.length>=2&&$e.isStringLiteral(n.arguments[1])?n.arguments[1].text:void 0;return{type:"storage",node:e,resourceName:o,startPos:t,endPos:r,isManaged:!0}}}}if($e.isCallExpression(i.initializer)){let n=kT(i.initializer,e,t,r);if(n.type!=="custom")return n}}return{type:"custom",node:e,startPos:t,endPos:r,isManaged:!1}}Ma(IL,"classifyVariableStatement");function DL(e,t,r){let i=e.expression;return $e.isCallExpression(i)?kT(i,e,t,r):{type:"custom",node:e,startPos:t,endPos:r,isManaged:!1}}Ma(DL,"classifyExpressionStatement");function kT(e,t,r,i){let n=e.expression;if($e.isPropertyAccessExpression(n)&&$e.isIdentifier(n.expression)){let a=n.name.text;if(a==="addTags")return{type:"tags",node:t,startPos:r,endPos:i,isManaged:!0};let o={addDatabase:{type:"database",factory:"DatabaseFactory"},addCompute:{type:"compute",factory:"ComputeFactory"},addNetwork:{type:"network",factory:"NetworkFactory"},addMessaging:{type:"messaging",factory:"MessagingFactory"},addCdn:{type:"cdn",factory:"CdnFactory"},addPattern:{type:"pattern",factory:"PatternFactory"},addStorage:{type:"storage",factory:"StorageFactory"}}[a];if(o){let s=NL(e,o.factory);return{type:o.type,node:t,resourceName:s,startPos:r,endPos:i,isManaged:!0}}}return{type:"custom",node:t,startPos:r,endPos:i,isManaged:!1}}Ma(kT,"classifyCallExpression");function NL(e,t){if(e.arguments.length===0)return;let r=e.arguments[0];if(!$e.isCallExpression(r))return;let i=r.expression;if(!$e.isPropertyAccessExpression(i)||i.name.text!=="build"||!$e.isIdentifier(i.expression)||i.expression.text!==t||r.arguments.length===0)return;let n=r.arguments[0];if($e.isStringLiteral(n))return n.text}Ma(NL,"extractResourceNameFromFactoryCall");import*as kL from"typescript";var cq=Object.defineProperty,La=(e,t)=>cq(e,"name",{value:t,configurable:!0}),lq={import:"after-imports","app-init":"after-app-init",tags:"after-tags"};function wL(e){if(!e)return{position:"before-imports"};let t=lq[e.type];return t?{position:t}:{position:"after-resource",afterManagedResource:{type:e.type,name:e.resourceName}}}La(wL,"determineCustomBlockPosition");function Uu(e,t){let r=t??Vt(e),i=[],n=e.getFullText(),a=null;for(let o of r)if(o.type==="custom"&&!o.isManaged){let{position:s,afterManagedResource:l}=wL(a),m=PL(n,o.node),d=RL(n,o.node),h=e.getLineAndCharacterOfPosition(o.node.getStart());i.push({sourceText:m,position:s,afterManagedResource:l,originalLine:h.line+1,leadingComments:d.length>0?d:void 0})}else o.isManaged&&(a=o);return i}La(Uu,"extractCustomCodeBlocks");function PL(e,t){let r=t.getFullStart(),i=t.getEnd(),n=e.slice(r,i).split(`
555
+ `,r}Dr(Lh,"generateCDNCode");function Ru(e){let t=new Set;if(e.cdn&&(e.cdn.defaultOriginRef&&t.add(e.cdn.defaultOriginRef),e.cdn.behaviours))for(let r of e.cdn.behaviours)t.add(r.originRef);return t}Dr(Ru,"collectCdnReferencedResources");function Rs(e){return e.patternConfig!==void 0}Dr(Rs,"usesPatternApproach");var B5=Object.defineProperty,ja=(e,t)=>B5(e,"name",{value:t,configurable:!0}),Ou="service",dT="cron(0 4 * * ? *)",pT="cron(0 5 * * ? *)",Zn=Object.freeze({tinkerer:{displayName:"Tinkerer",description:"Free tier eligible, minimal cost for experimentation",database:{Instance:{instanceType:"t4g.micro",multiAz:!1,proxy:!1,readReplica:!1,publiclyAccessible:!0},Aurora:null,GlobalAurora:null,ClickHouse:null},compute:{ecs:{services:[{name:Ou,capacityProvider:"EC2",desiredCount:1,minCapacity:1,maxCapacity:1,ec2Config:{instanceType:"t4g.micro",amiHardwareType:"ARM",minCapacity:1,maxCapacity:1,memoryLimitMiB:400}}],cluster:{directAccess:!0}},lambda:{timeout:30,memory:128}},network:{maxAzs:2,natGateways:!1,flowLogs:!1},backup:!1},lightweight:{displayName:"Lightweight",description:"Streamlined single-AZ deployment for cost efficiency",database:{Instance:{instanceType:"t4g.small",multiAz:!1},Aurora:{readers:!1},GlobalAurora:null,ClickHouse:null},compute:{ecs:{services:[{name:Ou,capacityProvider:"FARGATE_SPOT",cpu:256,memoryLimitMiB:512,desiredCount:1,minCapacity:1,maxCapacity:3}]},lambda:{timeout:30,memory:256}},network:{maxAzs:2,natGateways:{count:1},flowLogs:!1},backup:!1},standard:{displayName:"Standard",description:"Production-ready with sensible defaults",database:{Instance:{instanceType:"t4g.large"},Aurora:{readers:{count:1}},GlobalAurora:{readers:{count:1}},ClickHouse:{instanceType:"t4g.medium",coldTier:{mode:"s3"},optimiseSchedule:dT,backupSchedule:pT,backupRetentionDays:14}},compute:{ecs:{services:[{name:Ou,capacityProvider:"FARGATE",cpu:512,memoryLimitMiB:1024,desiredCount:2,minCapacity:2,maxCapacity:5}]},lambda:{timeout:60,memory:256}},network:{maxAzs:3,natGateways:{count:1},flowLogs:{},vpcEndpoints:{interface:{ecr:!0}}},backup:!1},resilient:{displayName:"Resilient",description:"High availability with enhanced monitoring and scaling",database:{Instance:{instanceType:"r7g.large",encryption:{storageKey:{useCMK:!0}},databaseInsights:{mode:"advanced",encryptionKey:{useCMK:!0}},proxy:{requireTLS:!0}},Aurora:{readers:{count:2},encryption:{storageKey:{useCMK:!0}},databaseInsights:{mode:"advanced",encryptionKey:{useCMK:!0}},proxy:{requireTLS:!0},backupRetention:30},GlobalAurora:{readers:{count:2},encryption:{storageKey:{useCMK:!0}},databaseInsights:{mode:"advanced",encryptionKey:{useCMK:!0}},proxy:{requireTLS:!0},backupRetention:30,enableGlobalWriteForwarding:!0},ClickHouse:{instanceType:"m7g.large",coldTier:{mode:"s3"},optimiseSchedule:dT,backupSchedule:pT,backupRetentionDays:14}},compute:{ecs:{services:[{name:Ou,capacityProvider:"FARGATE",cpu:1024,memoryLimitMiB:2048,desiredCount:4,minCapacity:4,maxCapacity:20}]},lambda:{timeout:120,memory:512}},network:{maxAzs:3,natGateways:{count:3},flowLogs:{retentionDays:90},vpcEndpoints:{interface:{ecr:!0,secretsManager:!0}}},backup:{tier:"resilient"}},enterprise:{displayName:"Enterprise",description:"Maximum capability with all features enabled",database:{Instance:{instanceType:"r7g.xlarge",encryption:{storageKey:{useCMK:!0}},databaseInsights:{mode:"advanced",encryptionKey:{useCMK:!0}},proxy:{requireTLS:!0},readReplica:{}},Aurora:{readers:{count:2},encryption:{storageKey:{useCMK:!0}},databaseInsights:{mode:"advanced",encryptionKey:{useCMK:!0}},proxy:{requireTLS:!0},backupRetention:35},GlobalAurora:{readers:{count:2},encryption:{storageKey:{useCMK:!0}},databaseInsights:{mode:"advanced",encryptionKey:{useCMK:!0}},proxy:{requireTLS:!0},backupRetention:35,enableGlobalWriteForwarding:!0},ClickHouse:{instanceType:"m7g.xlarge",coldTier:{mode:"s3"},optimiseSchedule:dT,backupSchedule:pT,backupRetentionDays:30}},compute:{ecs:{services:[{name:Ou,capacityProvider:"FARGATE",cpu:2048,memoryLimitMiB:4096,desiredCount:6,minCapacity:6,maxCapacity:100}]},lambda:{timeout:300,memory:1024}},network:{maxAzs:3,natGateways:{count:3},flowLogs:{destination:"s3",retentionDays:365},vpcEndpoints:{interface:{ecr:!0,secretsManager:!0,kms:!0,cloudwatchLogs:!0}}},backup:{tier:"enterprise"}}});function G5(e,t){return Zn[e].database[t]}ja(G5,"getDatabasePreset");function V5(e){return Zn[e].compute.ecs}ja(V5,"getEcsPreset");function mT(e){return Zn[e].network}ja(mT,"getNetworkPreset");function aL(e){return Af.filter(t=>Zn[t].database[e]!==null)}ja(aL,"getAvailableTiersForDatabase");function W5(e){return aL(e).map(t=>({label:Zn[t].displayName,value:t,description:Zn[t].description}))}ja(W5,"getTierOptionsForDatabase");function fT(e){switch(e){case"tinkerer":case"lightweight":case"standard":return"Instance";case"resilient":case"enterprise":return"Aurora"}}ja(fT,"getDefaultDatabaseTypeForTier");function hT(e,t){let r=Zn[e].compute.ecs,i=r.services[0],n=!r.cluster?.directAccess&&r.cluster?.loadBalancer!==!1,a=t.filter(s=>s.serviceType!=="worker").length,o=t.findIndex(s=>s.serviceType!=="worker");return t.map((s,l)=>{let m=l===o,d=s.serviceType==="worker",h;return n&&!d&&(s.routing?h=s.routing:a>1&&(h={path:m?"/*":`/${s.name.toLowerCase()}/*`,...m?{}:{priority:100+l}})),{name:s.name,capacityProvider:i.capacityProvider,ec2Config:i.ec2Config,cpu:i.cpu,memoryLimitMiB:i.memoryLimitMiB,desiredCount:i.desiredCount,minCapacity:i.minCapacity,maxCapacity:i.maxCapacity,routing:h}})}ja(hT,"applyTierDefaultsToServices");var K5=Object.defineProperty,gT=(e,t)=>K5(e,"name",{value:t,configurable:!0}),$u=["lightweight","standard","resilient"],Z5=[...$u,"custom"],ki=Object.freeze({lightweight:{displayName:"Lightweight",description:"Cost-effective \xB7 Instance DB, minimal Lambda",database:{type:"Instance",instanceType:"t4g.small",backupRetention:7,deletionProtection:!1},compute:{memorySize:512,timeout:30},network:{maxAzs:2,natGateways:{count:1},flowLogs:!1},backup:!1},standard:{displayName:"Standard",description:"Production-ready \xB7 Instance DB, balanced Lambda",database:{type:"Instance",instanceType:"t4g.large",backupRetention:14,deletionProtection:!0},compute:{memorySize:1536,timeout:60},network:{maxAzs:3,natGateways:{count:1},flowLogs:{}},backup:{tier:"standard"}},resilient:{displayName:"Resilient",description:"High-availability \xB7 Aurora V2, KMS encryption",database:{type:"Aurora",backupRetention:30,deletionProtection:!0,encryption:{useCMK:!0}},compute:{memorySize:2048,timeout:120},network:{maxAzs:3,natGateways:{count:3},flowLogs:{retentionDays:90}},backup:{tier:"resilient"}}});function Fh(e){return ki[e]}gT(Fh,"getPatternTierPreset");function oL(){return[{label:ki.standard.displayName,value:"standard",description:ki.standard.description},{label:ki.lightweight.displayName,value:"lightweight",description:ki.lightweight.description},{label:ki.resilient.displayName,value:"resilient",description:ki.resilient.description},{label:"Custom",value:"custom",description:"Full control \xB7 Configure everything"}]}gT(oL,"getPatternTierOptions");var H5=new Set($u);function Uh(e){return H5.has(e)}gT(Uh,"isPatternTierName");var J5=Object.defineProperty,sL=(e,t)=>J5(e,"name",{value:t,configurable:!0}),zh=Object.freeze({standard:{},assets:{deployment:{source:"./assets"}},upload:{cors:[{allowedOrigins:["*"],allowedMethods:["GET","PUT","POST"]}]},website:{publicReadAccess:!0,websiteHosting:{indexDocument:"index.html",errorDocument:"error.html"}}});function cL(e){return{...zh[e]}}sL(cL,"getStoragePreset");function lL(){return[{label:"Standard",value:"standard"},{label:"Assets",value:"assets"},{label:"Upload",value:"upload"},{label:"Website Hosting",value:"website"}]}sL(lL,"getStoragePresetOptions");import*as nt from"typescript";import*as ae from"typescript";var X5=Object.defineProperty,Os=(e,t)=>X5(e,"name",{value:t,configurable:!0});function ye(e){let t={};for(let r of e.properties){if(!ae.isPropertyAssignment(r))continue;let i=ae.isIdentifier(r.name)||ae.isStringLiteral(r.name)?r.name.text:void 0;i!==void 0&&(t[i]=wi(r.initializer))}return t}Os(ye,"parseObjectLiteral");function wi(e){if(ae.isStringLiteral(e))return e.text;if(ae.isNumericLiteral(e))return Number(e.text);if(e.kind===ae.SyntaxKind.TrueKeyword)return!0;if(e.kind===ae.SyntaxKind.FalseKeyword)return!1;if(ae.isArrayLiteralExpression(e))return e.elements.map(t=>wi(t));if(ae.isObjectLiteralExpression(e))return ye(e);if(ae.isIdentifier(e))return{__identifier:e.text};if(ae.isPropertyAccessExpression(e))return{__expression:e.getText()};if(ae.isCallExpression(e))return{__call:e.getText()};if(ae.isBinaryExpression(e)&&e.operatorToken.kind===ae.SyntaxKind.BarBarToken){let t=wi(e.left),r=wi(e.right);return typeof r=="string"?r:t}else if(ae.isConditionalExpression(e)){let t=wi(e.whenTrue),r=wi(e.whenFalse);return typeof r=="string"||typeof r=="number"?r:t}else if(ae.isTemplateExpression(e)||ae.isNoSubstitutionTemplateLiteral(e))return{__expression:e.getText()};return{__unknown:e.getText()}}Os(wi,"evaluateExpression");function ju(e,t){return rr(e,r=>{if(ae.isVariableStatement(r)){for(let i of r.declarationList.declarations)if(ae.isIdentifier(i.name)&&i.name.text===t&&i.initializer){if(ae.isStringLiteral(i.initializer))return i.initializer.text;if(ae.isObjectLiteralExpression(i.initializer)){let n=ye(i.initializer);return JSON.stringify(n)}}}})}Os(ju,"findVariableValue");function yT(e,t){return rr(e,r=>{if(ae.isVariableStatement(r)){for(let i of r.declarationList.declarations)if(ae.isIdentifier(i.name)&&i.name.text===t&&i.initializer&&ae.isObjectLiteralExpression(i.initializer))return ye(i.initializer)}})}Os(yT,"findObjectDeclaration");function Mu(e,t){if(!ae.isIdentifier(t.expression))return;let r=yT(e,t.expression.text),i=t.name.text;if(r&&r[i]!==void 0)return String(r[i])}Os(Mu,"evaluatePropertyAccess");function Bh(e,t){let r=t.head.text;for(let i of t.templateSpans){if(ae.isIdentifier(i.expression)){let n=ju(e,i.expression.text);if(n)r+=n;else return t.getText(e).replace(/^`|`$/g,"")}else if(ae.isPropertyAccessExpression(i.expression)){let n=Mu(e,i.expression);if(n)r+=n;else return t.getText(e).replace(/^`|`$/g,"")}else return t.getText(e).replace(/^`|`$/g,"");r+=i.literal.text}return r}Os(Bh,"resolveTemplateLiteral");var q5=Object.defineProperty,Pe=(e,t)=>q5(e,"name",{value:t,configurable:!0});function Nr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}Pe(Nr,"isPlainObject");function Hn(e){return Nr(e)&&"__identifier"in e}Pe(Hn,"isIdentifierRef");function Pi(e){return Nr(e)&&"__expression"in e}Pe(Pi,"isExpressionRef");function Zr(e){return Nr(e)&&"__call"in e}Pe(Zr,"isCallRef");function Z(e){return Nr(e)&&!("__identifier"in e)&&!("__expression"in e)&&!("__call"in e)&&!("__unknown"in e)}Pe(Z,"isParsedObject");function w(e){return typeof e=="string"?e:void 0}Pe(w,"asString");function W(e){return typeof e=="number"?e:void 0}Pe(W,"asNumber");function oe(e){return typeof e=="boolean"?e:void 0}Pe(oe,"asBoolean");function He(e){if(!Array.isArray(e))return;let t=[];for(let r of e){if(typeof r!="string")return;t.push(r)}return t.length>0?t:void 0}Pe(He,"asStringArray");function se(e,t){let r=w(e);if(r!==void 0)return Ft(t,r)?r:void 0}Pe(se,"asStringUnion");function Gt(e){let t={};for(let[r,i]of Object.entries(e))i!==void 0&&(t[r]=i);return t}Pe(Gt,"omitUndefined");function Gh(e){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean")return String(e);if(Array.isArray(e))return`[${e.map(Gh).join(", ")}]`;if(!Nr(e))return String(e);if(Hn(e))return e.__identifier;if(Pi(e))return e.__expression;if(Zr(e))return e.__call;if("__unknown"in e&&typeof e.__unknown=="string")return e.__unknown;let t=Object.entries(e);return t.length===0?"{}":`{ ${t.map(([r,i])=>`${r}: ${Gh(i)}`).join(", ")} }`}Pe(Gh,"parsedValueToSourceText");function Ze(e,t){let r=[];for(let[i,n]of Object.entries(e))t.has(i)||n===void 0||r.push({key:i,sourceText:Gh(n)});return r}Pe(Ze,"captureExtraProperties");function Ri(e,t){return nt.isPropertyAssignment(e)&&nt.isIdentifier(e.name)&&e.name.text===t}Pe(Ri,"isNamedProperty");function fn(e){return nt.isCallExpression(e)&&nt.isPropertyAccessExpression(e.expression)&&e.expression.name.text==="getApp"&&nt.isIdentifier(e.expression.expression)&&e.expression.expression.text==="App"}Pe(fn,"isAppGetAppCall");function ft(e,t){let{expression:r}=e;return nt.isPropertyAccessExpression(r)&&r.name.text===t&&e.arguments.length>0}Pe(ft,"isFactoryMethodCall");function rr(e,t){let r,i=Pe(n=>{r===void 0&&(r=t(n),r===void 0&&nt.forEachChild(n,i))},"visit");return i(e),r}Pe(rr,"findFirstInAst");function bt(e,t){let r=[],i=Pe(n=>{let a=t(n);a!==null&&r.push(a),nt.forEachChild(n,i)},"visit");return i(e),r}Pe(bt,"collectFromAst");function Rt(e,t){return nt.isCallExpression(e)&&nt.isPropertyAccessExpression(e.expression)&&e.expression.name.text==="build"&&nt.isIdentifier(e.expression.expression)&&e.expression.expression.text===t}Pe(Rt,"isFactoryBuildCall");function nr(e){let t=e.parent;if(nt.isVariableDeclaration(t)&&nt.isIdentifier(t.name))return t.name.text}Pe(nr,"extractVariableName");var kr=Pe(()=>e=>e,"typed");function $s(e){if(e!=null){if(e===!1)return!1;if(typeof e=="object"&&!Array.isArray(e))return e}}Pe($s,"asObjectOrFalse");function Hr(e,t){return e===!1?!1:Z(e)?t(e):void 0}Pe(Hr,"parseBooleanOrConfig");function Et(e,t){return Z(e)?t(e):void 0}Pe(Et,"parseOptionalConfig");function ir(e,t,r){let i=e[t];return Z(i)?r(i):void 0}Pe(ir,"extractSubConfig");import*as Te from"typescript";import*as Ms from"typescript";var Y5=Object.defineProperty,ar=(e,t)=>Y5(e,"name",{value:t,configurable:!0});function Lu(e){return e!==void 0&&Nr(e)}ar(Lu,"isEnvironmentRecord");function uL(e){if(!Z(e))return;let t={};for(let[r,i]of Object.entries(e))if(Z(i)){let n=w(i.id),a=w(i.name);n&&a&&(t[r]={id:n,name:a,field:w(i.field)})}return Object.keys(t).length>0?t:void 0}ar(uL,"parseContainerSecretsImport");function dL(e){if(!Z(e))return;let t=He(e.command);if(!(!t||t.length===0))return{command:t,interval:W(e.interval),timeout:W(e.timeout),retries:W(e.retries),startPeriod:W(e.startPeriod)}}ar(dL,"parseContainerHealthCheck");function pL(e){let t=Ze(e,new Set(["name","image","port","environment","essential","command","entryPoint","secretsImport","secrets","healthCheck"]));return{name:w(e.name),image:w(e.image),port:W(e.port),environment:Lu(e.environment)?e.environment:void 0,essential:oe(e.essential),command:He(e.command),entryPoint:He(e.entryPoint),secretsImport:uL(e.secretsImport),ssmSecrets:He(e.secrets),healthCheck:dL(e.healthCheck),extraProperties:t.length>0?t:void 0}}ar(pL,"parseServiceContainer");function mL(e){if(Array.isArray(e))return e.filter(Z).map(t=>({path:w(t.path),host:w(t.host),priority:W(t.priority),healthCheckPath:w(t.healthCheckPath)}));if(Z(e))return{path:w(e.path),host:w(e.host),priority:W(e.priority),healthCheckPath:w(e.healthCheckPath)}}ar(mL,"parseServiceRouting");function fL(e){if(e===!1)return!1;if(Z(e))return{minCapacity:W(e.minCapacity),maxCapacity:W(e.maxCapacity),desiredCount:W(e.desiredCount),scalingType:se(js(e.scalingType,"ScalingType"),If)}}ar(fL,"parseServiceScaling");var Q5=new Set(["instanceType","amiHardwareType","minCapacity","maxCapacity","memoryLimitMiB","warmPool"]);function hL(e){if(!Z(e))return;let t=e.warmPool,r=Z(t)?{minSize:W(t.minSize),reuseOnScaleIn:oe(t.reuseOnScaleIn)}:void 0,i=Ze(e,Q5);return{instanceType:w(e.instanceType),amiHardwareType:se(e.amiHardwareType,Df),minCapacity:W(e.minCapacity),maxCapacity:W(e.maxCapacity),memoryLimitMiB:W(e.memoryLimitMiB),warmPool:r,extraProperties:i.length>0?i:void 0}}ar(hL,"parseServiceEc2Config");var eq=new Set(["domain","loadBalancer","directAccess"]);function vT(e){if(!Z(e))return;let t=e.loadBalancer,r=Ze(e,eq);return{domain:w(e.domain),loadBalancer:t===!1?!1:se(t,Cf),directAccess:oe(e.directAccess),...r.length>0&&{extraProperties:r}}}ar(vT,"extractClusterConfig");function ST(e){let t=e.containers,r=Array.isArray(t)?t.filter(Z).map(pL):void 0,i=Ze(e,new Set(["name","image","docker","ssmSecretsPath","containers","routing","connections","serviceType","cpu","memoryLimitMiB","desiredCount","scaling","capacityProvider","ec2Config"]));return{name:w(e.name)??"",image:w(e.image),docker:gL(e.docker),ssmSecretsPath:w(e.ssmSecretsPath),containers:r,routing:mL(e.routing),serviceType:se(e.serviceType,Ol),cpu:W(e.cpu),memoryLimitMiB:W(e.memoryLimitMiB),desiredCount:W(e.desiredCount),scaling:fL(e.scaling),capacityProvider:se(e.capacityProvider,ls)??"FARGATE",ec2Config:hL(e.ec2Config),...i.length>0&&{extraProperties:i}}}ar(ST,"parseEcsService");function gL(e){if(!Z(e))return;let t=w(e.path);if(t===void 0)return;let r=w(e.context),i=w(e.target);return{path:t,...r!==void 0&&{context:r},...i!==void 0&&{target:i}}}ar(gL,"parseServiceDocker");function js(e,t){let r=w(e);if(r)return r;if(Pi(e)&&e.__expression.startsWith(t+"."))return e.__expression.slice(t.length+1)}ar(js,"extractEnumString");function bT(e){return Zr(e)?e.__call.match(/\(\s*"([^"]+)"\s*\)/)?.[1]:void 0}ar(bT,"extractCallStringArg");function At(e,t,r){r!==void 0&&(e[t]=r)}ar(At,"assignIfDefined");var tq=Object.defineProperty,Vh=(e,t)=>tq(e,"name",{value:t,configurable:!0}),rq=10;function ET(e,t){return Array.isArray(e)?e.filter(Hn).map(r=>t.find(i=>i.variableName===r.__identifier)).filter(r=>r!==void 0).map(r=>r.resourceName):[]}Vh(ET,"resolveConnectedDatabaseNames");function AT(e,t){return Array.isArray(e)?e.filter(Hn).map(r=>t.find(i=>i.variableName===r.__identifier)).filter(r=>r!==void 0).map(r=>r.resourceName):[]}Vh(AT,"resolveConnectedStorageNames");function _T(e,t,r){if(!Array.isArray(t)||t.length===0)return;let i=t[0];if(!Z(i))return;let n=i.containers;if(!Array.isArray(n)||n.length===0)return;let a=n[0];if(!Z(a)||!Z(a.environment))return;let o=a.environment;(o.DATABASE_HOST||o.DATABASE_PORT||o.DATABASE_NAME)&&(e.needsConnection=!0,r.length>0&&(e.connectedDatabase??[]).length===0&&(e.connectedDatabase=[r[0].name]));for(let s=1;s<=rq;s++)(o[`DATABASE_HOST_${s}`]||o[`DATABASE_PORT_${s}`]||o[`DATABASE_NAME_${s}`])&&(e.needsConnection=!0)}Vh(_T,"inferDatabaseConnectionsFromEnv");function xT(e,t,r){if(!Array.isArray(t)||t.length===0)return;let i=t[0];if(!Z(i))return;let n=i.containers;if(!Array.isArray(n)||n.length===0)return;let a=n[0];!Z(a)||!Z(a.environment)||a.environment.BUCKET_NAME&&r.length>0&&(e.connectedStorage??[]).length===0&&(e.connectedStorage=[r[0].name])}Vh(xT,"inferStorageConnectionsFromEnv");var nq=Object.defineProperty,Jn=(e,t)=>nq(e,"name",{value:t,configurable:!0});function yL(e){if(e.arguments.length<2)return null;let t=e.arguments[0],r=e.arguments[1];if(!Ms.isStringLiteral(t)||!Ms.isObjectLiteralExpression(r))return null;let i=t.text,n=ye(r);return{resourceName:i,type:w(n.type)??"ecs",config:n,node:e}}Jn(yL,"extractComputeResource");function Wh(e){return bt(e,t=>{if(!Ms.isCallExpression(t)||!ft(t,"addCompute"))return null;let r=t.arguments[0];if(!Rt(r,"ComputeFactory"))return null;let i=yL(r);if(i){let n=nr(t);n&&(i.variableName=n)}return i})}Jn(Wh,"findComputeResources");function Kh(e,t,r){let i=Ze(e.config,r);i.length>0&&(t.extraProperties=i)}Jn(Kh,"applyExtras");function vL(e,t){let r=e.config.docker;if(Z(r)){let a=w(r.path),o=w(r.context),s=w(r.target);(a!==void 0||o!==void 0||s!==void 0)&&(t.docker={...a!==void 0&&{path:a},...o!==void 0&&{context:o},...s!==void 0&&{target:s}})}let i=e.config.cluster;i!==void 0&&(t.cluster=vT(i));let n=e.config.services;n!==void 0&&Array.isArray(n)&&(t.services=n.filter(a=>Z(a)).map(ST)),Kh(e,t,new Set(["type","ecrRepository","docker","cluster","services","connections"]))}Jn(vL,"convertEcsCompute");function SL(e,t){if(At(t,"deployment",se(e.config.deployment,_f)),At(t,"timeout",W(e.config.timeout)),At(t,"memory",W(e.config.memorySize)??W(e.config.memory)),At(t,"handler",w(e.config.handler)),At(t,"runtime",js(e.config.runtime,"Runtime")),Lu(e.config.environment)&&(t.environment=e.config.environment),Lu(e.config.secrets))t.secrets=e.config.secrets;else{let n=He(e.config.secrets);n&&(t.ssmSecrets=n)}let r=e.config.functionUrl;if(Z(r)){let n=se(js(r.authType,"FunctionUrlAuthType"),Rl);n!==void 0&&(t.functionUrl={authType:n})}let i=e.config.code;if(i!==void 0){let n=bT(i);n&&(t.codePath=n)}At(t,"description",w(e.config.description)??w(e.config.lambdaDescription)),At(t,"architecture",se(js(e.config.architecture,"Architecture"),Tf)),At(t,"ephemeralStorageSize",W(e.config.ephemeralStorageSize)),At(t,"functionName",w(e.config.functionName)),At(t,"ssmSecretsPath",w(e.config.ssmSecretsPath)),Kh(e,t,new Set(["type","deployment","timeout","memorySize","memory","handler","runtime","environment","secrets","functionUrl","code","connections","ecrRepository","containerSecretsImport","secretsImport","lambdaDescription","description","architecture","ephemeralStorageSize","functionName","ssmSecretsPath"]))}Jn(SL,"convertLambdaCompute");function bL(e,t){At(t,"instanceType",se(e.config.instanceType,Nf));let r=e.config.ssh;r===!1?t.enableSSH=!1:r!==void 0&&Z(r)?t.enableSSH=!0:At(t,"enableSSH",oe(e.config.enableSSH)),At(t,"keyName",w(e.config.keyName)),At(t,"userData",w(e.config.userData)),e.config.securityGroups!==void 0&&(t.securityGroups=He(e.config.securityGroups)),Kh(e,t,new Set(["type","instanceType","ssh","enableSSH","keyName","userData","securityGroups","connections"]))}Jn(bL,"convertEc2Compute");function EL(e,t,r,i){let n=t.config.connections;if(!n&&Array.isArray(t.config.services)){let s=t.config.services[0];Z(s)&&(n=s.connections)}if(!n)return;let a=ET(n,r);a.length>0&&(e.needsConnection=!0,e.connectedDatabase=a);let o=AT(n,i);o.length>0&&(e.connectedStorage=o)}Jn(EL,"applyConnectionConfig");function AL(e,t){({ecs:vL,lambda:SL,ec2:bL})[e.type]?.(t,e)}Jn(AL,"applyTypeSpecificConfig");function TT(e,t,r,i){return e.map(n=>{let a=se(n.config.type,wl)??"ecs",o={name:n.resourceName,type:a,needsConnection:!1,connectedDatabase:[],...n.variableName&&{variableName:n.variableName}};return EL(o,n,t,r),AL(o,n),_T(o,n.config.services,i.database),xT(o,n.config.services,i.s3),o})}Jn(TT,"convertComputeResources");import*as wr from"typescript";var iq=Object.defineProperty,aq=(e,t)=>iq(e,"name",{value:t,configurable:!0});function Zh(e){return bt(e,t=>{if(!wr.isCallExpression(t)||!ft(t,"addSchedule")||t.arguments.length<2)return null;let r=t.arguments[0],i=t.arguments[1];if(!wr.isStringLiteral(r)||!wr.isObjectLiteralExpression(i))return null;let n=ye(i),a=w(n.schedule);if(a===void 0)return null;let o=i.properties.find(l=>wr.isPropertyAssignment(l)&&wr.isIdentifier(l.name)&&l.name.text==="target");if(!o||!wr.isPropertyAssignment(o)||!wr.isIdentifier(o.initializer))return null;let s=se(n.stackPlacement,ga);return{id:r.text,schedule:a,targetVariableName:o.initializer.text,...s!==void 0&&{stackPlacement:s}}})}aq(Zh,"findSchedules");import*as $e from"typescript";import*as Ot from"typescript";var oq=Object.defineProperty,Fu=(e,t)=>oq(e,"name",{value:t,configurable:!0}),CT=new Set(["S3Bucket"]);function _L(e,t,r){let i=Ot.isIdentifier(e.name)?e.name.text:"";if(t.arguments&&t.arguments.length>=2){let n=t.arguments[1],a=Ot.isStringLiteral(n)?n.text:"",o=t.arguments.length>=3?t.arguments[2]:void 0,s=o&&Ot.isObjectLiteralExpression(o)?ye(o):{};return{variableName:i,resourceName:a,bucketClass:r,config:s,node:e}}return null}Fu(_L,"extractS3Resource");function xL(e,t){if(t.arguments.length<2)return null;let r=t.arguments[0],i=t.arguments[1];if(!Ot.isStringLiteral(r)||!Ot.isObjectLiteralExpression(i))return null;let n=ye(i);return{variableName:nr(e)??"",resourceName:r.text,bucketClass:"StorageFactory",config:n,node:e}}Fu(xL,"extractS3FactoryResource");function IT(e){return bt(e,t=>{if(!Ot.isVariableDeclaration(t)||!t.initializer||!Ot.isNewExpression(t.initializer))return null;let r=t.initializer;if(!Ot.isIdentifier(r.expression))return null;let i=r.expression.text;return CT.has(i)?_L(t,r,i):null})}Fu(IT,"findS3Resources");function DT(e){return bt(e,t=>{if(!Ot.isCallExpression(t)||!ft(t,"addStorage"))return null;let r=t.arguments[0];return Rt(r,"StorageFactory")?xL(t,r):null})}Fu(DT,"findS3FactoryResources");function NT(e){return e.map(t=>({name:t.resourceName,...w(t.config.bucketName)&&{bucketName:w(t.config.bucketName)},...oe(t.config.publicReadAccess)===!0&&{publicReadAccess:!0},...Z(t.config.websiteHosting)&&(()=>{let r=t.config.websiteHosting;return{websiteHosting:{indexDocument:w(r.indexDocument)??"index.html",...w(r.errorDocument)&&{errorDocument:w(r.errorDocument)}}}})(),...se(t.config.backupVaultTier,Vr)&&{backupVaultTier:se(t.config.backupVaultTier,Vr)},...oe(t.config.versioned)!==void 0&&{versioned:oe(t.config.versioned)},...se(t.config.encryption,ps)&&{encryption:se(t.config.encryption,ps)},...w(t.config.kmsKeyArn)&&{kmsKeyArn:w(t.config.kmsKeyArn)},...Array.isArray(t.config.cors)&&t.config.cors.length>0&&{cors:t.config.cors.filter(Z).map(r=>({allowedOrigins:Array.isArray(r.allowedOrigins)?r.allowedOrigins.filter(i=>typeof i=="string"):[],allowedMethods:Array.isArray(r.allowedMethods)?r.allowedMethods.filter(i=>typeof i=="string"):[]}))},...Z(t.config.deployment)&&(()=>{let r=t.config.deployment;return{deployment:{source:w(r.source)??"",...oe(r.prune)!==void 0&&{prune:oe(r.prune)},...Z(r.cacheControl)&&(()=>{let i=r.cacheControl;return{cacheControl:{...W(i.maxAge)!==void 0&&{maxAge:W(i.maxAge)},...oe(i.immutable)!==void 0&&{immutable:oe(i.immutable)}}}})()}}})(),...se(t.config.stackPlacement,Bf)&&{stackPlacement:se(t.config.stackPlacement,Bf)},...t.variableName&&{variableName:t.variableName},...(()=>{let r=new Set(["bucketName","publicReadAccess","websiteHosting","backupVaultTier","versioned","encryption","kmsKeyArn","cors","deployment","stackPlacement"]),i=Ze(t.config,r);return i.length>0?{extraProperties:i}:{}})()}))}Fu(NT,"convertS3Resources");var sq=Object.defineProperty,Ma=(e,t)=>sq(e,"name",{value:t,configurable:!0}),TL=new Set(["App","Architecture","DatabaseFactory","StorageFactory","ComputeFactory","getConfig","MessagingFactory","CdnFactory","Code","Runtime","FunctionUrlAuthType","NetworkFactory","PatternFactory","CrossPlanConnectionFactory"]);function Hh(e){return!!(e.startsWith("@fjall/")||e==="aws-cdk-lib"||e.startsWith("aws-cdk-lib/")||e==="constructs")}Ma(Hh,"isManagedModuleSpecifier");function Vt(e){let t=[];for(let r of e.statements){let i=r.getFullStart(),n=r.getEnd();if($e.isImportDeclaration(r)){t.push({type:"import",node:r,startPos:i,endPos:n,isManaged:CL(r)});continue}if($e.isVariableStatement(r)){t.push(IL(r,i,n));continue}if($e.isExpressionStatement(r)){t.push(DL(r,i,n));continue}t.push({type:"custom",node:r,startPos:i,endPos:n,isManaged:!1})}return t}Ma(Vt,"classifyStatements");function CL(e){return $e.isStringLiteral(e.moduleSpecifier)?Hh(e.moduleSpecifier.text):!1}Ma(CL,"isManagedImport");function IL(e,t,r){for(let i of e.declarationList.declarations)if(i.initializer){if(fn(i.initializer))return{type:"app-init",node:e,resourceName:$e.isIdentifier(i.name)?i.name.text:void 0,startPos:t,endPos:r,isManaged:!0};if($e.isIdentifier(i.name)&&i.name.text==="appName"&&$e.isStringLiteral(i.initializer))return{type:"app-init",node:e,startPos:t,endPos:r,isManaged:!0};if($e.isNewExpression(i.initializer)){let n=i.initializer;if($e.isIdentifier(n.expression)){let a=n.expression.text;if(CT.has(a)){let o=n.arguments&&n.arguments.length>=2&&$e.isStringLiteral(n.arguments[1])?n.arguments[1].text:void 0;return{type:"storage",node:e,resourceName:o,startPos:t,endPos:r,isManaged:!0}}}}if($e.isCallExpression(i.initializer)){let n=kT(i.initializer,e,t,r);if(n.type!=="custom")return n}}return{type:"custom",node:e,startPos:t,endPos:r,isManaged:!1}}Ma(IL,"classifyVariableStatement");function DL(e,t,r){let i=e.expression;return $e.isCallExpression(i)?kT(i,e,t,r):{type:"custom",node:e,startPos:t,endPos:r,isManaged:!1}}Ma(DL,"classifyExpressionStatement");function kT(e,t,r,i){let n=e.expression;if($e.isPropertyAccessExpression(n)&&$e.isIdentifier(n.expression)){let a=n.name.text;if(a==="addTags")return{type:"tags",node:t,startPos:r,endPos:i,isManaged:!0};let o={addDatabase:{type:"database",factory:"DatabaseFactory"},addCompute:{type:"compute",factory:"ComputeFactory"},addNetwork:{type:"network",factory:"NetworkFactory"},addMessaging:{type:"messaging",factory:"MessagingFactory"},addCdn:{type:"cdn",factory:"CdnFactory"},addPattern:{type:"pattern",factory:"PatternFactory"},addStorage:{type:"storage",factory:"StorageFactory"}}[a];if(o){let s=NL(e,o.factory);return{type:o.type,node:t,resourceName:s,startPos:r,endPos:i,isManaged:!0}}}return{type:"custom",node:t,startPos:r,endPos:i,isManaged:!1}}Ma(kT,"classifyCallExpression");function NL(e,t){if(e.arguments.length===0)return;let r=e.arguments[0];if(!$e.isCallExpression(r))return;let i=r.expression;if(!$e.isPropertyAccessExpression(i)||i.name.text!=="build"||!$e.isIdentifier(i.expression)||i.expression.text!==t||r.arguments.length===0)return;let n=r.arguments[0];if($e.isStringLiteral(n))return n.text}Ma(NL,"extractResourceNameFromFactoryCall");import*as kL from"typescript";var cq=Object.defineProperty,La=(e,t)=>cq(e,"name",{value:t,configurable:!0}),lq={import:"after-imports","app-init":"after-app-init",tags:"after-tags"};function wL(e){if(!e)return{position:"before-imports"};let t=lq[e.type];return t?{position:t}:{position:"after-resource",afterManagedResource:{type:e.type,name:e.resourceName}}}La(wL,"determineCustomBlockPosition");function Uu(e,t){let r=t??Vt(e),i=[],n=e.getFullText(),a=null;for(let o of r)if(o.type==="custom"&&!o.isManaged){let{position:s,afterManagedResource:l}=wL(a),m=PL(n,o.node),d=RL(n,o.node),h=e.getLineAndCharacterOfPosition(o.node.getStart());i.push({sourceText:m,position:s,afterManagedResource:l,originalLine:h.line+1,leadingComments:d.length>0?d:void 0})}else o.isManaged&&(a=o);return i}La(Uu,"extractCustomCodeBlocks");function PL(e,t){let r=t.getFullStart(),i=t.getEnd(),n=e.slice(r,i).split(`
556
556
  `),a=n.findIndex(o=>o.trim()!=="");return n.slice(a===-1?0:a).join(`
557
557
  `)}La(PL,"getStatementTextWithComments");function RL(e,t){let r=[],i=kL.getLeadingCommentRanges(e,t.getFullStart());if(i)for(let n of i){let a=e.slice(n.pos,n.end);r.push(a)}return r}La(RL,"extractLeadingComments");function Ls(e,t,r,i){let n=i??Vt(e);for(let a of n)if(a.type===t&&a.resourceName===r)return{startPos:a.startPos,endPos:a.endPos,node:a.node};return null}La(Ls,"findManagedResourcePosition");function wT(e,t,r){let i=r??Vt(e),n=null;for(let a of i)a.type===t&&a.isManaged&&(n=a);return n}La(wT,"getLastManagedStatementOfType");function PT(e,t){let r=t??Vt(e),i={import:[],"app-init":[],tags:[],database:[],compute:[],storage:[],network:[],messaging:[],cdn:[],pattern:[],"vpc-peer":[],"vpc-peer-accepter":[],"cross-plan-connection":[],custom:[]};for(let n of r)i[n.type].push(n);return i}La(PT,"getManagedResourcesByType");import*as Xn from"typescript";import*as Bu from"typescript";var uq=Object.defineProperty,RT=(e,t)=>uq(e,"name",{value:t,configurable:!0}),dq=["S","N","B"];function zu(e){if(!Z(e))return;let t=w(e.name),r=se(e.type,dq);if(!(!t||!r))return{name:t,type:r}}RT(zu,"parseDynamoDBKey");function OT(e){let t=e.node;if(!Bu.isCallExpression(t))return null;let r=t.arguments[0];if(!Bu.isCallExpression(r)||r.arguments.length<2)return null;let i=r.arguments[1];if(!Bu.isObjectLiteralExpression(i))return null;let n=ye(i),a=zu(n.partitionKey);if(!a)return null;let o={resourceName:e.resourceName,partitionKey:a,node:e.node};e.variableName&&(o.variableName=e.variableName);let s=zu(n.sortKey);if(s&&(o.sortKey=s),Array.isArray(n.globalSecondaryIndexes)){let h=n.globalSecondaryIndexes.filter(Z).map(g=>{let u=zu(g.partitionKey);if(!u)return null;let p=w(g.indexName);if(!p)return null;let f={indexName:p,partitionKey:u},y=zu(g.sortKey);return y&&(f.sortKey=y),f}).filter(g=>g!==null);h.length>0&&(o.globalSecondaryIndexes=h)}let l=w(n.ttlAttribute);l&&(o.ttlAttribute=l);let m=oe(n.stream);m!==void 0&&(o.stream=m);let d=Ze(n,new Set(["type","databaseName","partitionKey","sortKey","globalSecondaryIndexes","ttlAttribute","stream"]));return d.length>0&&(o.extraProperties=d),o}RT(OT,"extractDynamoDBFields");function Jh(e){if(e.length!==0)return e.map(t=>({name:t.resourceName,partitionKey:t.partitionKey,...Gt({sortKey:t.sortKey,globalSecondaryIndexes:t.globalSecondaryIndexes,ttlAttribute:t.ttlAttribute,stream:t.stream,variableName:t.variableName,extraProperties:t.extraProperties})}))}RT(Jh,"convertDynamoDBResources");import*as Gu from"typescript";var pq=Object.defineProperty,OL=(e,t)=>pq(e,"name",{value:t,configurable:!0}),mq=new Set(["type","databaseName","instanceType","storageGb","iops","throughputMbps","coldTier","optimiseSchedule","backupSchedule","backupVerify","backupRetentionDays"]);function $T(e){let t=e.node;if(!Gu.isCallExpression(t))return null;let r=t.arguments[0];if(!Gu.isCallExpression(r)||r.arguments.length<2)return null;let i=r.arguments[1];if(!Gu.isObjectLiteralExpression(i))return null;let n=ye(i),a={resourceName:e.resourceName,databaseName:e.databaseName,node:e.node};e.variableName&&(a.variableName=e.variableName);let o=w(n.instanceType);o&&(a.instanceType=o);let s=W(n.storageGb);s!==void 0&&(a.storageGb=s);let l=W(n.iops);l!==void 0&&(a.iops=l);let m=W(n.throughputMbps);m!==void 0&&(a.throughputMbps=m);let d=n.coldTier;d===!1?a.coldTier=!1:Z(d)&&w(d.mode)==="s3"&&(a.coldTier={mode:"s3"});let h=n.optimiseSchedule;if(h===!1)a.optimiseSchedule=!1;else{let f=w(h);f&&(a.optimiseSchedule=f)}let g=n.backupSchedule;if(g===!1)a.backupSchedule=!1;else{let f=w(g);f&&(a.backupSchedule=f)}n.backupVerify===!1&&(a.backupVerify=!1);let u=W(n.backupRetentionDays);u!==void 0&&(a.backupRetentionDays=u);let p=Ze(n,mq);return p.length>0&&(a.extraProperties=p),a}OL($T,"extractClickHouseFields");function Xh(e){if(e.length!==0)return e.map(t=>({name:t.resourceName,type:"ClickHouse",databaseName:t.databaseName,...Gt({instanceType:t.instanceType,storageGb:t.storageGb,iops:t.iops,throughputMbps:t.throughputMbps,coldTier:t.coldTier,optimiseSchedule:t.optimiseSchedule,backupSchedule:t.backupSchedule,backupVerify:t.backupVerify,backupRetentionDays:t.backupRetentionDays,variableName:t.variableName,extraProperties:t.extraProperties})}))}OL(Xh,"convertClickHouseResources");var fq=Object.defineProperty,Fs=(e,t)=>fq(e,"name",{value:t,configurable:!0});function $L(e){let t=w(e.databaseEngine);if(t!==void 0&&Ft(us,t))return t;let r=e.engine;if(Zr(r)){let i=String(r.__call);if(i.includes("postgres")||i.includes("auroraPostgres"))return"postgresql";if(i.includes("mysql")||i.includes("auroraMysql"))return"mysql"}}Fs($L,"extractDatabaseEngine");function jL(e){let t=e.engine;if(Zr(t))return String(t.__call)}Fs(jL,"extractEngineExpression");var hq=new Set(["type","databaseName","databaseEngine","engine","vpc","port","deletionProtection","instanceType","multiAz","publiclyAccessible","enableSecretRotation","encryption","databaseInsights","proxy","readReplica","credentials","writer","readers","backupRetention","preferredMaintenanceWindow","primaryRegion","secondaryRegions","globalClusterIdentifier","enableGlobalWriteForwarding","snapshotIdentifier","allocatedStorage","monitoringInterval","snapshotUsername"]);function ML(e,t,r){if(r.arguments.length<2)return null;let i=r.arguments[0],n=r.arguments[1];if(!Xn.isStringLiteral(i)&&!Xn.isTemplateExpression(i))return null;let a=Xn.isStringLiteral(i)?i.text:Bh(e,i);if(!Xn.isObjectLiteralExpression(n))return null;let o=ye(n),s={resourceName:a,type:w(o.type)??"",databaseName:w(o.databaseName)??"",databaseEngine:$L(o),engineExpression:jL(o),port:W(o.port),deletionProtection:oe(o.deletionProtection),instanceType:w(o.instanceType),multiAz:oe(o.multiAz),publiclyAccessible:oe(o.publiclyAccessible),enableSecretRotation:oe(o.enableSecretRotation),encryption:Et(o.encryption,kr()),databaseInsights:Hr(o.databaseInsights,kr()),proxy:Hr(o.proxy,kr()),readReplica:Hr(o.readReplica,kr()),credentials:Et(o.credentials,kr()),writer:Et(o.writer,kr()),readers:Hr(o.readers,kr()),backupRetention:W(o.backupRetention),preferredMaintenanceWindow:w(o.preferredMaintenanceWindow),primaryRegion:w(o.primaryRegion),secondaryRegions:He(o.secondaryRegions),globalClusterIdentifier:w(o.globalClusterIdentifier),enableGlobalWriteForwarding:oe(o.enableGlobalWriteForwarding),allocatedStorage:W(o.allocatedStorage),monitoringInterval:W(o.monitoringInterval),snapshotIdentifier:w(o.snapshotIdentifier),snapshotUsername:w(o.snapshotUsername),node:t},l=nr(t);l&&(s.variableName=l);let m=Ze(o,hq);return m.length>0&&(s.extraProperties=m),s}Fs(ML,"extractDatabaseResource");function jT(e){return bt(e,t=>{if(!Xn.isCallExpression(t)||!ft(t,"addDatabase"))return null;let r=t.arguments[0];return Rt(r,"DatabaseFactory")?ML(e,t,r):null})}Fs(jT,"findDatabaseResources");function MT(e){let t=[],r=[],i=[];for(let n of e)if(n.type==="DynamoDB"){let a=OT(n);a&&r.push(a)}else if(n.type==="ClickHouse"){let a=$T(n);a&&i.push(a)}else t.push(n);return{databases:t,dynamodb:r,clickhouse:i}}Fs(MT,"splitDatabaseResources");var gq=["Instance","Aurora","GlobalAurora"];function LT(e){return e.filter(t=>t.type!=="DynamoDB").map(t=>({name:t.resourceName,type:Ft(gq,t.type)?t.type:"Instance",databaseName:t.databaseName,...Gt({port:t.port,deletionProtection:t.deletionProtection,instanceType:t.instanceType,multiAz:t.multiAz,publiclyAccessible:t.publiclyAccessible,enableSecretRotation:t.enableSecretRotation,encryption:t.encryption,databaseInsights:t.databaseInsights,proxy:t.proxy,readReplica:t.readReplica,credentials:t.credentials,writer:t.writer,readers:t.readers,backupRetention:t.backupRetention,preferredMaintenanceWindow:t.preferredMaintenanceWindow,primaryRegion:t.primaryRegion,secondaryRegions:t.secondaryRegions,globalClusterIdentifier:t.globalClusterIdentifier,enableGlobalWriteForwarding:t.enableGlobalWriteForwarding,allocatedStorage:t.allocatedStorage,monitoringInterval:t.monitoringInterval,variableName:t.variableName,databaseEngine:t.databaseEngine,engineExpression:t.engineExpression,extraProperties:t.extraProperties})}))}Fs(LT,"convertDatabaseResources");import*as zs from"typescript";var yq=Object.defineProperty,Us=(e,t)=>yq(e,"name",{value:t,configurable:!0});function LL(e,t){if(t.arguments.length<2)return null;let r=t.arguments[0],i=t.arguments[1];if(!zs.isStringLiteral(r)||!zs.isObjectLiteralExpression(i))return null;let n=ye(i),a={resourceName:r.text,queueType:w(n.queueType)??"standard",visibilityTimeout:W(n.visibilityTimeout),retentionPeriod:W(n.messageRetentionPeriod),contentBasedDeduplication:oe(n.contentBasedDeduplication),removalPolicy:w(n.removalPolicy),node:e},o=nr(e);o&&(a.variableName=o);let s=Ze(n,new Set(["type","queueType","visibilityTimeout","messageRetentionPeriod","contentBasedDeduplication","removalPolicy"]));return s.length>0&&(a.extraProperties=s),a}Us(LL,"extractSQSResource");function FT(e){if(e!=null){if(e===!1)return!1;if(Z(e))return Gt({enabled:oe(e.enabled),maxReceiveCount:W(e.maxReceiveCount)})}}Us(FT,"parseDeadLetterQueueConfig");function UT(e){return bt(e,t=>{if(!zs.isCallExpression(t)||!ft(t,"addMessaging"))return null;let r=t.arguments[0];return Rt(r,"MessagingFactory")?LL(t,r):null})}Us(UT,"findSQSResources");function zT(e){if(e.length!==0)return e.map(t=>({name:t.resourceName,queueType:t.queueType==="fifo"?"fifo":"standard",...Gt({visibilityTimeout:t.visibilityTimeout,retentionPeriod:t.retentionPeriod,contentBasedDeduplication:t.contentBasedDeduplication,removalPolicy:UL(t.removalPolicy),variableName:t.variableName,extraProperties:t.extraProperties})}))}Us(zT,"convertSQSResources");var vq=new Set(_x.options);function FL(e){return vq.has(e)}Us(FL,"isSqsRemovalPolicy");function UL(e){return e!==void 0&&FL(e)?e:void 0}Us(UL,"toSqsRemovalPolicy");import*as Bs from"typescript";var Sq=Object.defineProperty,Vu=(e,t)=>Sq(e,"name",{value:t,configurable:!0});function BL(e){if(e.arguments.length<2)return null;let t=e.arguments[0],r=e.arguments[1];return!Bs.isStringLiteral(t)||!Bs.isObjectLiteralExpression(r)?null:{resourceName:t.text,config:ye(r),node:e}}Vu(BL,"extractCDNResource");function GL(e,t,r){let i=t.find(a=>a.variableName===e);if(i)return i.resourceName;let n=r.find(a=>a.variableName===e||a.resourceName.charAt(0).toLowerCase()+a.resourceName.slice(1)===e);return n?n.resourceName:e}Vu(GL,"resolveOriginIdentifier");var zL=["CACHING_OPTIMIZED","CACHING_DISABLED"];function BT(e){return rr(e,t=>{if(!Bs.isCallExpression(t)||!ft(t,"addCdn"))return;let r=t.arguments[0];if(Rt(r,"CdnFactory"))return BL(r)??void 0})}Vu(BT,"findCDNResource");function GT(e,t,r){if(!e)return;let i=e,n=i.config,a=Vu(f=>Hn(f)?GL(f.__identifier,t,r):w(f)??"","resolveOrigin"),o=w(n.originType)==="alb",s;if(o){let f=a(n.loadBalancer),y=r.some(S=>S.resourceName===f),v=w(n.protocolPolicy);if(!y||v!=="HTTP_ONLY")throw new Error(`CDN '${i.resourceName}': only the generated alb lane is plan-mappable \u2014 originType "alb" with loadBalancer referencing a compute declared in this app and protocolPolicy "HTTP_ONLY". Reshape the statement to that form, or manage this CDN outside the generator lane.`);s=f}else s=a(n.origin);let l={name:i.resourceName,defaultOriginRef:s};if(Array.isArray(n.behaviours)){let f=n.behaviours.filter(Z).map(y=>({pathPattern:w(y.pathPattern)??"",originRef:a(y.origin),...se(y.cachePolicy,zL)!==void 0&&{cachePolicy:se(y.cachePolicy,zL)}}));f.length>0&&(l.behaviours=f)}let m=w(n.customDomain);if(m)l.customDomain=m;else{let f=He(n.domainNames);f&&f.length>0&&(l.customDomain=f[0])}let d=w(n.certificateArn);d&&(l.certificateArn=d);let h=w(n.originHostname);h&&(l.originHostname=h);let g=!1;if(Z(n.domainConfig)){let f=n.domainConfig,y=w(f.domainName);y!==void 0&&Object.keys(f).every(v=>v==="domainName"||v==="record")&&(f.record===void 0||w(f.record)==="alias")&&(l.domain=y,g=!0)}if(n.accessGate!==void 0){if(n.accessGate===!1)l.accessGate=!1;else if(Z(n.accessGate)){let f=n.accessGate,y=w(f.type),v=w(f.username),S=w(f.password);y==="basic-auth"&&v&&S&&(l.accessGate={type:"basic-auth",username:v,password:S})}}let u=new Set(["originType","origin","behaviours","customDomain","domainNames","certificateArn","accessGate"]);g&&u.add("domainConfig"),o&&(u.add("loadBalancer"),u.add("protocolPolicy")),h&&u.add("originHostname");let p=Ze(n,u);return p.length>0&&(l.extraProperties=p),l}Vu(GT,"convertCDNResource");import*as qe from"typescript";var bq=Object.defineProperty,or=(e,t)=>bq(e,"name",{value:t,configurable:!0}),Eq=new Set(bx.options);function VL(e){if(e!==void 0)return Eq.has(e)?e:void 0}or(VL,"asFlowLogDestination");function VT(e){return{maxAzs:W(e.maxAzs),natGateways:Hr(e.natGateways,t=>({count:W(t.count)})),flowLogs:Hr(e.flowLogs,t=>({destination:w(t.destination),retentionDays:W(t.retentionDays)})),vpcEndpoints:Z(e.vpcEndpoints)?e.vpcEndpoints:void 0}}or(VT,"parseNetworkConfigFields");function WL(e,t){if(t.arguments.length<2)return null;let r=t.arguments[0],i=t.arguments[1];if(!qe.isStringLiteral(r))return null;let n=r.text,a=qe.isObjectLiteralExpression(i)?ye(i):{},o=VT(a),s={name:n,config:Gt({...o}),node:e},l=nr(e);return l&&(s.variableName=l),s}or(WL,"extractNetworkResource");function WT(e){return rr(e,t=>{if(!fn(t)||t.arguments.length<=1)return;let r=t.arguments[1];if(qe.isObjectLiteralExpression(r)){for(let i of r.properties)if(Ri(i,"network")&&qe.isObjectLiteralExpression(i.initializer)){for(let n of i.initializer.properties)if(Ri(n,"useExisting")&&qe.isStringLiteral(n.initializer))return n.initializer.text}}})}or(WT,"findVpcId");function KT(e){return rr(e,t=>{if(!fn(t)||t.arguments.length<=1)return;let r=t.arguments[1];if(qe.isObjectLiteralExpression(r)){for(let i of r.properties)if(Ri(i,"network")){if(i.initializer.kind===qe.SyntaxKind.FalseKeyword)return;if(qe.isObjectLiteralExpression(i.initializer)&&!i.initializer.properties.some(n=>Ri(n,"useExisting"))){let n=ye(i.initializer);return VT(n)}}}})}or(KT,"findNetworkConfig");function ZT(e){return rr(e,t=>{if(!fn(t)||t.arguments.length<=1)return;let r=t.arguments[1];if(qe.isObjectLiteralExpression(r)){for(let i of r.properties)if(Ri(i,"backup")){if(i.initializer.kind===qe.SyntaxKind.FalseKeyword)return!1;if(qe.isObjectLiteralExpression(i.initializer)){let n=ye(i.initializer),a=w(n.tier);if(a)return{tier:a}}}}})}or(ZT,"findBackupConfig");function HT(e){return rr(e,t=>{if(!fn(t)||t.arguments.length<=1)return;let r=t.arguments[1];if(qe.isObjectLiteralExpression(r)){for(let i of r.properties)if(Ri(i,"tunnel")){if(i.initializer.kind===qe.SyntaxKind.FalseKeyword)return!1;if(i.initializer.kind===qe.SyntaxKind.TrueKeyword)return!0;if(qe.isObjectLiteralExpression(i.initializer)){let n=ye(i.initializer),a=w(n.instanceType);return a?{instanceType:a}:{}}}}})}or(HT,"findTunnelConfig");function JT(e){return bt(e,t=>{if(!qe.isCallExpression(t)||!ft(t,"addNetwork"))return null;let r=t.arguments[0];return Rt(r,"NetworkFactory")?WL(t,r):null})}or(JT,"findNetworkResources");function XT(e){let t=e.flowLogs;return{...Gt({maxAzs:e.maxAzs,natGateways:e.natGateways,vpcEndpoints:e.vpcEndpoints}),...t!==void 0&&{flowLogs:t===!1?!1:Gt({destination:VL(t.destination),retentionDays:t.retentionDays})}}}or(XT,"buildNetworkFields");function qT(e){if(e)return XT(e)}or(qT,"convertNetworkConfig");function YT(e){if(e===void 0)return;if(e===!1)return!1;let t=e.tier;if(Ft(Vr,t))return{tier:t}}or(YT,"convertBackupConfig");function QT(e){if(e===void 0)return;if(e===!1)return!1;if(e===!0)return{};let t={};return e.instanceType&&(t.instanceType=e.instanceType),t}or(QT,"convertTunnelConfig");function eC(e){if(!(!e||e.length===0))return e.map(t=>({name:t.name,...XT(t.config)}))}or(eC,"convertAdditionalNetworks");import*as Gs from"typescript";var Aq=Object.defineProperty,it=(e,t)=>Aq(e,"name",{value:t,configurable:!0}),_q=["Instance","Aurora"],xq=["postgresql","mysql"];function qh(e){if(!Z(e))return;let t={...e.memorySize!==void 0&&{memorySize:W(e.memorySize)},...e.timeout!==void 0&&{timeout:W(e.timeout)},...e.ephemeralStorageSize!==void 0&&{ephemeralStorageSize:W(e.ephemeralStorageSize)}};return Object.keys(t).length>0?t:void 0}it(qh,"parseLambdaConfig");function KL(e){return ir(e,"database",t=>({type:se(t.type,_q),databaseName:w(t.databaseName),databaseEngine:se(t.databaseEngine,xq),deletionProtection:oe(t.deletionProtection),backupRetention:W(t.backupRetention),port:W(t.port),publiclyAccessible:oe(t.publiclyAccessible),allowedIpCidr:w(t.allowedIpCidr),instanceType:w(t.instanceType),allocatedStorage:W(t.allocatedStorage),multiAz:oe(t.multiAz),allowVpcAccess:oe(t.allowVpcAccess),monitoringInterval:W(t.monitoringInterval),preferredMaintenanceWindow:w(t.preferredMaintenanceWindow),snapshotIdentifier:w(t.snapshotIdentifier),snapshotUsername:w(t.snapshotUsername),readReplica:$s(t.readReplica),writer:Et(t.writer,kr()),readers:$s(t.readers),databaseInsights:$s(t.databaseInsights),proxy:$s(t.proxy),credentials:Et(t.credentials,kr()),encryption:Et(t.encryption,kr())}))}it(KL,"extractPatternDatabaseConfig");function ZL(e){return ir(e,"compute",t=>({server:Et(t.server,qh),imageOptimisation:Et(t.imageOptimisation,qh),revalidation:Et(t.revalidation,qh)}))}it(ZL,"extractPatternComputeConfig");function HL(e){let t=it(r=>({versioned:oe(r.versioned)}),"parseVersionedConfig");return ir(e,"storage",r=>({assets:Et(r.assets,t),cache:Et(r.cache,t),media:Et(r.media,t)}))}it(HL,"extractPatternStorageConfig");function JL(e){return ir(e,"messaging",t=>({revalidationQueue:Et(t.revalidationQueue,r=>({visibilityTimeout:W(r.visibilityTimeout),messageRetentionPeriod:W(r.messageRetentionPeriod),maxMessageSize:W(r.maxMessageSize),deadLetterQueue:FT(r.deadLetterQueue)}))}))}it(JL,"extractPatternMessagingConfig");function XL(e){return ir(e,"cdn",t=>({domainNames:He(t.domainNames),certificateArn:w(t.certificateArn)}))}it(XL,"extractPatternCdnConfig");function qL(e){return ir(e,"environment",t=>{let r=Object.fromEntries(Object.entries(t).filter(i=>typeof i[1]=="string"));return Object.keys(r).length>0?r:void 0})}it(qL,"extractPatternEnvironmentConfig");function YL(e,t){let r=QL(e);return{name:t,source:w(e.source),build:ir(e,"build",i=>({command:w(i.command),outputDir:w(i.outputDir)})),routing:se(e.routing,al),security:ir(e,"security",i=>({headers:oe(i.headers),contentSecurityPolicy:w(i.contentSecurityPolicy),hsts:Hr(i.hsts,n=>({maxAgeDays:W(n.maxAgeDays),includeSubdomains:oe(n.includeSubdomains),preload:oe(n.preload)}))})),domain:w(e.domain),zoneName:w(e.zoneName),hostedZoneId:w(e.hostedZoneId),forms:ir(e,"forms",i=>({to:w(i.to),from:w(i.from),corsOrigin:w(i.corsOrigin),maxConcurrency:W(i.maxConcurrency)})),cdn:ir(e,"cdn",i=>({behaviours:Array.isArray(i.behaviours)?i.behaviours:void 0,priceClass:se(i.priceClass,ol),invalidateOnDeploy:oe(i.invalidateOnDeploy)})),accessGate:ir(e,"accessGate",i=>({type:se(i.type,["basic-auth"]),username:w(i.username),password:w(i.password)})),...r.length>0&&{unreadableFields:r}}}it(YL,"extractStaticSiteConfig");function tC(e){return Nr(e)&&("__identifier"in e||"__expression"in e||"__call"in e||"__unknown"in e)}it(tC,"isUnreadableRef");function QL(e){let t=[],r=it((a,o)=>{tC(a)&&t.push(o)},"check");r(e.source,"source"),r(e.routing,"routing"),r(e.domain,"domain"),r(e.zoneName,"zoneName"),r(e.hostedZoneId,"hostedZoneId");let i=[[e.build,"build",["command","outputDir"]],[e.security,"security",["headers","contentSecurityPolicy","hsts"]],[e.forms,"forms",["to","from","corsOrigin","maxConcurrency"]],[e.cdn,"cdn",["behaviours","priceClass","invalidateOnDeploy"]],[e.accessGate,"accessGate",["type","username","password"]]];for(let[a,o,s]of i)if(tC(a))t.push(o);else if(Z(a))for(let l of s)r(a[l],`${o}.${l}`);let n=e.security;if(Z(n)&&Z(n.hsts)){let a=n.hsts;for(let o of["maxAgeDays","includeSubdomains","preload"])r(a[o],`security.hsts.${o}`)}return t}it(QL,"collectUnreadableStaticSiteFields");function hn(e){return e!==void 0&&e!==""}it(hn,"isReadable");function Wu(e,t){return new Error(`Static-site pattern '${e}' in infrastructure.ts: Fjall could not read ${t.join(", ")} as inline literal(s). Fjall reads these fields out of the file and writes them back, so they must be written inline (source: "./site"), not as a variable or an expression.`)}it(Wu,"unreadableStaticSiteFields");function eF(e,t){let r=t.to;if(!hn(r))throw Wu(e,["forms.to"]);return{to:r,...t.from!==void 0&&{from:t.from},...t.corsOrigin!==void 0&&{corsOrigin:t.corsOrigin},...t.maxConcurrency!==void 0&&{maxConcurrency:t.maxConcurrency}}}it(eF,"readStaticSiteForms");function tF(e,t){let r=[];if(t.type!=="basic-auth"&&r.push("accessGate.type"),hn(t.username)||r.push("accessGate.username"),hn(t.password)||r.push("accessGate.password"),r.length>0||t.username===void 0||t.password===void 0)throw Wu(e,r);return{type:"basic-auth",username:t.username,password:t.password}}it(tF,"readStaticSiteAccessGate");function rF(e,t){if(e.arguments.length<2)return null;let r=e.arguments[0],i=e.arguments[1];if(!Gs.isStringLiteral(r)||!Gs.isObjectLiteralExpression(i))return null;let n=r.text,a=ye(i),o=a.type,s=nr(t),l=w(a.name);return l?o==="payload"||o==="nextjs"?{variableName:s,constructId:n,type:o,config:{name:l,domain:w(a.domain),database:KL(a),compute:ZL(a),storage:HL(a),messaging:JL(a),cdn:XL(a),environment:qL(a)},node:e}:o==="staticsite"?{variableName:s,constructId:n,type:"staticsite",config:YL(a,l),node:e}:null:null}it(rF,"extractPatternResource");function rC(e){return bt(e,t=>{if(!Gs.isCallExpression(t)||!ft(t,"addPattern"))return null;let r=t.arguments[0];return Rt(r,"PatternFactory")?rF(r,t):null})}it(rC,"findPatternResources");function nC(e,t){if(!t||t.length===0)return;let r=t[0];if(e.pattern=r.type,r.type==="staticsite"){let{config:n}=r,a=n.source,o=n.build?.command,s=n.build?.outputDir;if(n.unreadableFields!==void 0)throw Wu(n.name,n.unreadableFields);if(!hn(a)||!hn(o)||!hn(s)){let l=[];throw hn(a)||l.push("source"),hn(o)||l.push("build.command"),hn(s)||l.push("build.outputDir"),Wu(n.name,l)}e.patternConfig={type:"staticsite",name:n.name,source:a,build:{command:o,outputDir:s},routing:n.routing,security:n.security,domain:n.domain,zoneName:n.zoneName,hostedZoneId:n.hostedZoneId,...n.forms!==void 0&&{forms:eF(n.name,n.forms)},cdn:n.cdn,...n.accessGate!==void 0&&{accessGate:tF(n.name,n.accessGate)}};return}let{config:i}=r;e.patternConfig={type:r.type,name:i.name,domain:i.domain,database:i.database,compute:i.compute,storage:i.storage,messaging:i.messaging,cdn:i.cdn,environment:i.environment}}it(nC,"applyPatternConfig");var Tq=Object.defineProperty,Yh=(e,t)=>Tq(e,"name",{value:t,configurable:!0});function nF(e,t){for(let r of t){let i=e.compute.find(n=>n.variableName===r.targetVariableName);i!==void 0&&i.type==="lambda"&&(i.scheduleExpression=r.schedule,r.stackPlacement!==void 0&&(i.scheduleStackPlacement=r.stackPlacement))}}Yh(nF,"applyScheduleBackfill");function iF(e,t){Object.keys(t).length>0&&(e.tags={...t}),t[ku]&&(e.owner=t[ku])}Yh(iF,"applyTagsAndOwner");function aF(e){let t=[];for(let r of e)if(Hh(r.moduleSpecifier))if(r.moduleSpecifier==="@fjall/components-infrastructure"||r.moduleSpecifier==="@fjall/infrastructure"){let i=r.namedImports.filter(n=>!TL.has(n));i.length>0&&t.push({moduleSpecifier:r.moduleSpecifier,namedImports:i,defaultImport:r.defaultImport})}else(r.namedImports.length>0||r.defaultImport)&&t.push(r);return t.length>0?t:void 0}Yh(aF,"computeAdditionalManagedImports");function Ku(e,t,r){let i={appName:t,type:"standard",database:[],s3:[],compute:[]};if(nC(i,e.patternResources),e.vpcId&&(i.vpcId=e.vpcId),i.network=qT(e.network),i.backup=YT(e.backup),i.tunnel=QT(e.tunnel),i.additionalNetworks=eC(e.networkResources),iF(i,e.tags),i.database=LT(e.databaseResources),i.dynamodb=Jh(e.dynamodbResources),i.clickhouse=Xh(e.clickhouseResources),i.sqs=zT(e.sqsResources),i.cdn=GT(e.cdnResource,e.s3Resources,e.computeResources),i.s3=NT(e.s3Resources),i.compute=TT(e.computeResources,e.databaseResources,e.s3Resources,i),nF(i,e.schedules),i.additionalManagedImports=aF(e.imports),r?.skipValidation)return i;try{return Y$.parse(i)}catch(n){if(n instanceof c.ZodError){let a=Ml(n);throw new Error(`Invalid infrastructure configuration:
558
558
  ${a}`)}throw n}}Yh(Ku,"convertToResourcePlan");var Cq=Object.defineProperty,Vs=(e,t)=>Cq(e,"name",{value:t,configurable:!0});function Ws(e,t){let r=Te.createSourceFile("infrastructure.ts",e,Te.ScriptTarget.Latest,!0,Te.ScriptKind.TS),i=oF(r),{appVariableName:n,appName:a}=cF(r),o=WT(r),s=KT(r),l=ZT(r),m=HT(r),d=JT(r),h=jT(r),{databases:g,dynamodb:u,clickhouse:p}=MT(h),f=UT(r),y=BT(r),v=[...IT(r),...DT(r)],S=Wh(r),x=Zh(r),A=rC(r),_=lF(r),C={sourceFile:r,imports:i,appVariableName:n,appName:a,vpcId:o,network:s,backup:l,tunnel:m,networkResources:d,databaseResources:g,dynamodbResources:u,clickhouseResources:p,sqsResources:f,cdnResource:y,s3Resources:v,computeResources:S,schedules:x,patternResources:A,tags:_};return t?.extractCustomCode&&(C.customCodeBlocks=Uu(r),C.classifiedStatements=Vt(r)),C}Vs(Ws,"parseInfrastructure");function oF(e){let t=[];return Te.forEachChild(e,r=>{if(Te.isImportDeclaration(r)){if(!Te.isStringLiteral(r.moduleSpecifier))return;let i={moduleSpecifier:r.moduleSpecifier.text,namedImports:[]};r.importClause&&(r.importClause.name&&(i.defaultImport=r.importClause.name.text),r.importClause.namedBindings&&Te.isNamedImports(r.importClause.namedBindings)&&(i.namedImports=r.importClause.namedBindings.elements.map(n=>n.name.text))),t.push(i)}}),t}Vs(oF,"extractImports");function sF(e,t){return Te.isStringLiteral(t)?t.text:Te.isIdentifier(t)?ju(e,t.text)??"":Te.isPropertyAccessExpression(t)?Mu(e,t)??"":""}Vs(sF,"resolveAppName");function cF(e){return rr(e,t=>{if(Te.isVariableStatement(t))for(let r of t.declarationList.declarations){if(!r.initializer||!fn(r.initializer))continue;let i=Te.isIdentifier(r.name)?r.name.text:"",n=r.initializer.arguments.length>0?sF(e,r.initializer.arguments[0]):"";return{appVariableName:i,appName:n}}})??{appVariableName:"",appName:""}}Vs(cF,"findAppVariable");function lF(e){let t={};function r(i){if(Te.isCallExpression(i)&&Te.isPropertyAccessExpression(i.expression)&&i.expression.name.text==="addTags"&&Te.isIdentifier(i.expression.expression)&&i.arguments.length>0){let n=i.arguments[0];if(Te.isObjectLiteralExpression(n)){let a=ye(n);for(let[o,s]of Object.entries(a))typeof s=="string"?t[o]=s:Pi(s)&&(t[o]="default-value")}}Te.forEachChild(i,r)}return Vs(r,"visit"),r(e),t}Vs(lF,"extractTags");import*as Ks from"typescript";var Iq=Object.defineProperty,ht=(e,t)=>Iq(e,"name",{value:t,configurable:!0});function Zs(e,t,r){return e.slice(0,t)+r+e.slice(t)}ht(Zs,"insertAtPosition");function Qh(e,t){return e.find(r=>r.type===t)}ht(Qh,"findClassification");function iC(e,t){return e.filter(r=>r.type===t).pop()}ht(iC,"findLastClassification");function Oi(e){return Ks.createSourceFile("infrastructure.ts",e,Ks.ScriptTarget.Latest,!0,Ks.ScriptKind.TS)}ht(Oi,"parseSourceFile");function eg(e,t){return e.endsWith(`