@stacksjs/ts-cloud 0.5.18 → 0.5.19
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.
- package/dist/bin/cli.js +3 -3
- package/dist/deploy/dashboard-data.d.ts +1 -1
- package/dist/deploy/management-dashboard.d.ts +4 -4
- package/dist/index.js +2 -2
- package/dist/ui/index.html +205 -68
- package/dist/ui/server/backups.html +205 -68
- package/dist/ui/server/deployments.html +205 -68
- package/dist/ui/server/metrics.html +205 -68
- package/dist/ui/server/services.html +205 -68
- package/dist/ui/server/sites.html +205 -68
- package/dist/ui/server/ssh-keys.html +205 -68
- package/dist/ui/server/workers.html +205 -68
- package/dist/ui/serverless/assets.html +205 -68
- package/dist/ui/serverless/cost.html +205 -68
- package/dist/ui/serverless/data.html +205 -68
- package/dist/ui/serverless/deployments.html +205 -68
- package/dist/ui/serverless/firewall.html +205 -68
- package/dist/ui/serverless/functions.html +205 -68
- package/dist/ui/serverless/metrics.html +205 -68
- package/dist/ui/serverless/queues.html +205 -68
- package/dist/ui/serverless/scheduler.html +205 -68
- package/dist/ui/serverless/secrets.html +205 -68
- package/dist/ui/serverless.html +205 -68
- package/package.json +3 -3
package/dist/bin/cli.js
CHANGED
|
@@ -254,7 +254,7 @@ rpm -U ./amazon-cloudwatch-agent.rpm || true
|
|
|
254
254
|
# Install Node.js or PHP/Python based on app needs
|
|
255
255
|
# Configure application server (PM2, Nginx, Apache)
|
|
256
256
|
# Mount EFS for shared file storage
|
|
257
|
-
`}},storage:{uploads:{type:"efs",performanceMode:"generalPurpose",throughputMode:"bursting",encrypted:!0,lifecyclePolicy:{transitionToIA:30}},backups:{public:!1,versioning:!0,encryption:!0,lifecycleRules:[{id:"ArchiveOldBackups",enabled:!0,transitions:[{days:90,storageClass:"GLACIER"}]}]},static:{public:!0,versioning:!1,encryption:!1,cors:[{allowedOrigins:[Q||"*"],allowedMethods:["GET","HEAD"]}]}},cdn:{enabled:!0,origins:[{originId:"static-assets",domainName:`${Y}-static.s3.amazonaws.com`,pathPattern:"/static/*"}],customDomain:Q?{domain:Q,certificateArn:"TO_BE_GENERATED"}:void 0,cachePolicy:{minTTL:0,defaultTTL:86400,maxTTL:31536000},compress:!0,http3:!0},databases:U==="mysql"?{mysql:{engine:"mysql",version:"8.0",instanceClass:"db.t3.medium",allocatedStorage:100,maxAllocatedStorage:500,multiAZ:!0,backupRetentionDays:14,preferredBackupWindow:"03:00-04:00",preferredMaintenanceWindow:"sun:04:00-sun:05:00",enablePerformanceInsights:!0,performanceInsightsRetention:7,deletionProtection:!0,parameters:{max_connections:"500",innodb_buffer_pool_size:"{DBInstanceClassMemory*3/4}",slow_query_log:"1",long_query_time:"2"}}}:{postgres:{engine:"postgres",version:"15",instanceClass:"db.t3.medium",allocatedStorage:100,maxAllocatedStorage:500,multiAZ:!0,backupRetentionDays:14,preferredBackupWindow:"03:00-04:00",preferredMaintenanceWindow:"sun:04:00-sun:05:00",enablePerformanceInsights:!0,performanceInsightsRetention:7,deletionProtection:!0,parameters:{max_connections:"500",shared_buffers:"{DBInstanceClassMemory/4}",log_min_duration_statement:"2000"}}},cache:z==="redis"?{redis:{nodeType:"cache.t3.medium",numCacheNodes:2,engine:"redis",engineVersion:"7.0",port:6379,parameterGroup:{maxmemoryPolicy:"allkeys-lru",timeout:"300"},snapshotRetentionLimit:5,snapshotWindow:"03:00-05:00",automaticFailoverEnabled:!0}}:void 0,queues:{jobs:{fifo:!1,visibilityTimeout:900,messageRetentionPeriod:345600,receiveMessageWaitTime:20,deadLetterQueue:!0,maxReceiveCount:3},emails:{fifo:!1,visibilityTimeout:300,messageRetentionPeriod:86400,deadLetterQueue:!0}},functions:{"job-worker":{runtime:"nodejs20.x",handler:"dist/workers/jobs.handler",memory:2048,timeout:900,events:[{type:"sqs",queueName:`${Y}-jobs`,batchSize:10}]},"email-sender":{runtime:"nodejs20.x",handler:"dist/workers/email.handler",memory:512,timeout:60,events:[{type:"sqs",queueName:`${Y}-emails`,batchSize:10}]},cleanup:{runtime:"nodejs20.x",handler:"dist/tasks/cleanup.handler",memory:512,timeout:300,events:[{type:"schedule",expression:"cron(0 2 * * ? *)"}]}},monitoring:{dashboard:{name:`${Y}-web-app`,widgets:[{type:"metric",metrics:["EC2CPUUtilization","ALBRequestCount","ALBTargetResponseTime","RDSCPUUtilization","RDSDatabaseConnections","RDSReadLatency","RDSWriteLatency"]}]},alarms:[{metric:"EC2CPUUtilization",threshold:80,evaluationPeriods:2},{metric:"RDSCPUUtilization",threshold:80,evaluationPeriods:2},{metric:"RDSDatabaseConnections",threshold:400,evaluationPeriods:1},{metric:"ALBTargetResponseTime",threshold:2000,evaluationPeriods:2},{metric:"ALBUnhealthyHostCount",threshold:1,evaluationPeriods:1}],logs:{retention:14,groups:[`${Y}-app`,`${Y}-nginx`,`${Y}-workers`]}},security:{certificate:Q?{domain:Q,validationMethod:"DNS"}:void 0,waf:{enabled:!0,rules:["rateLimit","sqlInjection","xss","knownBadInputs"]},securityGroups:{alb:{ingress:[{port:80,protocol:"tcp",cidr:"0.0.0.0/0"},{port:443,protocol:"tcp",cidr:"0.0.0.0/0"}]},app:{ingress:[{port:3000,protocol:"tcp",source:"alb-sg"}]},database:{ingress:[{port:U==="mysql"?3306:5432,protocol:"tcp",source:"app-sg"}]},...z==="redis"&&{cache:{ingress:[{port:6379,protocol:"tcp",source:"app-sg"}]}}}}}}}function uT($){let{name:J,slug:Y,domain:Q,repository:G,phpVersion:Z="8.3",size:W="small",database:U=Y.replace(/-/g,"_"),databasePassword:z,sslEmail:H,deployStrategy:_="push",provider:X="hetzner"}=$;return{project:{name:J,slug:Y,region:"us-east-1"},mode:"server",cloud:{provider:X},environments:{production:{type:"production",domain:Q}},infrastructure:{compute:{mode:"server",size:W,runtime:"php",webServer:"nginx",php:{versions:[Z],default:Z},managedServices:{mysql:!0,redis:!0},firewall:{enabled:!0},autoUpdates:!0,monitoring:!0,backups:{enabled:!0,schedule:"0 2 * * *",retentionCount:7}},appDatabase:{engine:"mysql",name:U,username:U,password:z}},sites:{main:{root:".",type:"laravel",domain:Q,phpVersion:Z,repository:{...G,strategy:_},scheduler:!0,queues:[{connection:"redis",queue:"default",processes:1}],ssl:{provider:"letsencrypt",email:H}}}}}function dT($){let{name:J,slug:Y,domain:Q,layers:G,phpVersion:Z="8.3",architecture:W="x86_64",memory:U=1024,build:z,deploy:H=["migrate --force"],cache:_="dynamodb",scheduler:X="on",region:F="us-east-1"}=$;return{project:{name:J,slug:Y,region:F},mode:"serverless",environments:{production:{type:"production",domain:Q,app:{kind:"php",runtime:"provided.al2023",phpVersion:Z,architecture:W,layers:G,memory:U,build:z,deploy:H,assets:"public",queues:!0,scheduler:X,cache:{driver:_},domain:Q}}}}}function cT($){return{root:$.root??"ui/dist",deploy:"server",type:"static",domain:$.domain,build:$.build??"cd ui && bun install && bun run build",ssl:{provider:"letsencrypt"},auth:{username:$.username??"admin",password:$.password}}}function lT($){let J=$.split(".").filter(Boolean);return J.length<=2?$:J.slice(-2).join(".")}function j_($,J,Y){if(Y)return Y;let Q=[];for(let W of Object.values($.sites??{})){let U=W?.domain;if(typeof U==="string")Q.push(U);else if(Array.isArray(U))Q.push(...U.filter((z)=>typeof z==="string"))}if(J&&$.environments?.[J]?.domain)Q.push($.environments[J].domain);let G=$.infrastructure?.dns?.domain;if(G)Q.push(G);let Z=Q.find((W)=>W&&!W.startsWith("dashboard."));if(!Z)return null;return`dashboard.${lT(Z)}`}function q_($){return Object.entries($.sites??{}).some(([J,Y])=>{if(!Y)return!1;let Q=Y.root??"";return J==="dashboard"||Q==="ui/dist"||Q.endsWith("/ui/dist")||Q.endsWith("/dist/ui")})}function mT($,J,Y){if(q_($))return null;let Q=j_($,J,Y.domain);if(!Q)return null;return{name:"dashboard",site:{root:Y.uiRoot,deploy:"server",type:"static",domain:Q,ssl:{provider:"letsencrypt"},...Y.build===!1||Y.build===void 0?{}:{build:Y.build},...Y.password?{auth:{username:Y.username||"admin",password:Y.password,realm:Y.realm}}:{}}}}function vG($,J){let Y={...$};for(let Q in J){let G=J[Q],Z=Y[Q];if(G===void 0)continue;if(Array.isArray(G)&&Array.isArray(Z))Y[Q]=[...Z,...G];else if(typeof G==="object"&&G!==null&&!Array.isArray(G)&&typeof Z==="object"&&Z!==null&&!Array.isArray(Z))Y[Q]=vG(Z,G);else Y[Q]=G}return Y}function RG($,J){return vG($,J)}function pT(...$){return $.reduce((J,Y)=>vG(J,Y),{})}function rT($,J){return(Y)=>{let Q=$(Y);if(typeof J==="function")return RG(Q,J(Q,Y));return RG(Q,J)}}function e2($){return{infrastructure:$}}function nT($){return e2({monitoring:$})}function iT($){return e2({security:$})}function tT($){return e2({databases:$})}function aT($){return e2({cache:$})}function oT($){return e2({cdn:$})}function sT($){return e2({queues:$})}function R_(){let $=process.env.AWS_ACCESS_KEY_ID,J=process.env.AWS_SECRET_ACCESS_KEY;if(!$||!J)return null;return{accessKeyId:$,secretAccessKey:J,sessionToken:process.env.AWS_SESSION_TOKEN}}function D_($){let J=$?.profile||process.env.AWS_PROFILE||"default",Y=$?.credentialsFile||w_(T_(),".aws","credentials");if(!M_(Y))return null;try{let Q=fG(Y,"utf-8");return eT(Q,J)}catch{return null}}function eT($,J){let Y=$.split(`
|
|
257
|
+
`}},storage:{uploads:{type:"efs",performanceMode:"generalPurpose",throughputMode:"bursting",encrypted:!0,lifecyclePolicy:{transitionToIA:30}},backups:{public:!1,versioning:!0,encryption:!0,lifecycleRules:[{id:"ArchiveOldBackups",enabled:!0,transitions:[{days:90,storageClass:"GLACIER"}]}]},static:{public:!0,versioning:!1,encryption:!1,cors:[{allowedOrigins:[Q||"*"],allowedMethods:["GET","HEAD"]}]}},cdn:{enabled:!0,origins:[{originId:"static-assets",domainName:`${Y}-static.s3.amazonaws.com`,pathPattern:"/static/*"}],customDomain:Q?{domain:Q,certificateArn:"TO_BE_GENERATED"}:void 0,cachePolicy:{minTTL:0,defaultTTL:86400,maxTTL:31536000},compress:!0,http3:!0},databases:U==="mysql"?{mysql:{engine:"mysql",version:"8.0",instanceClass:"db.t3.medium",allocatedStorage:100,maxAllocatedStorage:500,multiAZ:!0,backupRetentionDays:14,preferredBackupWindow:"03:00-04:00",preferredMaintenanceWindow:"sun:04:00-sun:05:00",enablePerformanceInsights:!0,performanceInsightsRetention:7,deletionProtection:!0,parameters:{max_connections:"500",innodb_buffer_pool_size:"{DBInstanceClassMemory*3/4}",slow_query_log:"1",long_query_time:"2"}}}:{postgres:{engine:"postgres",version:"15",instanceClass:"db.t3.medium",allocatedStorage:100,maxAllocatedStorage:500,multiAZ:!0,backupRetentionDays:14,preferredBackupWindow:"03:00-04:00",preferredMaintenanceWindow:"sun:04:00-sun:05:00",enablePerformanceInsights:!0,performanceInsightsRetention:7,deletionProtection:!0,parameters:{max_connections:"500",shared_buffers:"{DBInstanceClassMemory/4}",log_min_duration_statement:"2000"}}},cache:z==="redis"?{redis:{nodeType:"cache.t3.medium",numCacheNodes:2,engine:"redis",engineVersion:"7.0",port:6379,parameterGroup:{maxmemoryPolicy:"allkeys-lru",timeout:"300"},snapshotRetentionLimit:5,snapshotWindow:"03:00-05:00",automaticFailoverEnabled:!0}}:void 0,queues:{jobs:{fifo:!1,visibilityTimeout:900,messageRetentionPeriod:345600,receiveMessageWaitTime:20,deadLetterQueue:!0,maxReceiveCount:3},emails:{fifo:!1,visibilityTimeout:300,messageRetentionPeriod:86400,deadLetterQueue:!0}},functions:{"job-worker":{runtime:"nodejs20.x",handler:"dist/workers/jobs.handler",memory:2048,timeout:900,events:[{type:"sqs",queueName:`${Y}-jobs`,batchSize:10}]},"email-sender":{runtime:"nodejs20.x",handler:"dist/workers/email.handler",memory:512,timeout:60,events:[{type:"sqs",queueName:`${Y}-emails`,batchSize:10}]},cleanup:{runtime:"nodejs20.x",handler:"dist/tasks/cleanup.handler",memory:512,timeout:300,events:[{type:"schedule",expression:"cron(0 2 * * ? *)"}]}},monitoring:{dashboard:{name:`${Y}-web-app`,widgets:[{type:"metric",metrics:["EC2CPUUtilization","ALBRequestCount","ALBTargetResponseTime","RDSCPUUtilization","RDSDatabaseConnections","RDSReadLatency","RDSWriteLatency"]}]},alarms:[{metric:"EC2CPUUtilization",threshold:80,evaluationPeriods:2},{metric:"RDSCPUUtilization",threshold:80,evaluationPeriods:2},{metric:"RDSDatabaseConnections",threshold:400,evaluationPeriods:1},{metric:"ALBTargetResponseTime",threshold:2000,evaluationPeriods:2},{metric:"ALBUnhealthyHostCount",threshold:1,evaluationPeriods:1}],logs:{retention:14,groups:[`${Y}-app`,`${Y}-nginx`,`${Y}-workers`]}},security:{certificate:Q?{domain:Q,validationMethod:"DNS"}:void 0,waf:{enabled:!0,rules:["rateLimit","sqlInjection","xss","knownBadInputs"]},securityGroups:{alb:{ingress:[{port:80,protocol:"tcp",cidr:"0.0.0.0/0"},{port:443,protocol:"tcp",cidr:"0.0.0.0/0"}]},app:{ingress:[{port:3000,protocol:"tcp",source:"alb-sg"}]},database:{ingress:[{port:U==="mysql"?3306:5432,protocol:"tcp",source:"app-sg"}]},...z==="redis"&&{cache:{ingress:[{port:6379,protocol:"tcp",source:"app-sg"}]}}}}}}}function uT($){let{name:J,slug:Y,domain:Q,repository:G,phpVersion:Z="8.3",size:W="small",database:U=Y.replace(/-/g,"_"),databasePassword:z,sslEmail:H,deployStrategy:_="push",provider:X="hetzner"}=$;return{project:{name:J,slug:Y,region:"us-east-1"},mode:"server",cloud:{provider:X},environments:{production:{type:"production",domain:Q}},infrastructure:{compute:{mode:"server",size:W,runtime:"php",webServer:"nginx",php:{versions:[Z],default:Z},managedServices:{mysql:!0,redis:!0},firewall:{enabled:!0},autoUpdates:!0,monitoring:!0,backups:{enabled:!0,schedule:"0 2 * * *",retentionCount:7}},appDatabase:{engine:"mysql",name:U,username:U,password:z}},sites:{main:{root:".",type:"laravel",domain:Q,phpVersion:Z,repository:{...G,strategy:_},scheduler:!0,queues:[{connection:"redis",queue:"default",processes:1}],ssl:{provider:"letsencrypt",email:H}}}}}function dT($){let{name:J,slug:Y,domain:Q,layers:G,phpVersion:Z="8.3",architecture:W="x86_64",memory:U=1024,build:z,deploy:H=["migrate --force"],cache:_="dynamodb",scheduler:X="on",region:F="us-east-1"}=$;return{project:{name:J,slug:Y,region:F},mode:"serverless",environments:{production:{type:"production",domain:Q,app:{kind:"php",runtime:"provided.al2023",phpVersion:Z,architecture:W,layers:G,memory:U,build:z,deploy:H,assets:"public",queues:!0,scheduler:X,cache:{driver:_},domain:Q}}}}}function cT($){return{root:$.root??"packages/ui/dist",deploy:"server",type:"static",domain:$.domain,build:$.build??"cd packages/ui && bun install && bun run build",ssl:{provider:"letsencrypt"},auth:{username:$.username??"admin",password:$.password}}}function lT($){let J=$.split(".").filter(Boolean);return J.length<=2?$:J.slice(-2).join(".")}function j_($,J,Y){if(Y)return Y;let Q=[];for(let W of Object.values($.sites??{})){let U=W?.domain;if(typeof U==="string")Q.push(U);else if(Array.isArray(U))Q.push(...U.filter((z)=>typeof z==="string"))}if(J&&$.environments?.[J]?.domain)Q.push($.environments[J].domain);let G=$.infrastructure?.dns?.domain;if(G)Q.push(G);let Z=Q.find((W)=>W&&!W.startsWith("dashboard."));if(!Z)return null;return`dashboard.${lT(Z)}`}function q_($){return Object.entries($.sites??{}).some(([J,Y])=>{if(!Y)return!1;let Q=Y.root??"";return J==="dashboard"||Q==="ui/dist"||Q.endsWith("/ui/dist")||Q.endsWith("/dist/ui")})}function mT($,J,Y){if(q_($))return null;let Q=j_($,J,Y.domain);if(!Q)return null;return{name:"dashboard",site:{root:Y.uiRoot,deploy:"server",type:"static",domain:Q,ssl:{provider:"letsencrypt"},...Y.build===!1||Y.build===void 0?{}:{build:Y.build},...Y.password?{auth:{username:Y.username||"admin",password:Y.password,realm:Y.realm}}:{}}}}function vG($,J){let Y={...$};for(let Q in J){let G=J[Q],Z=Y[Q];if(G===void 0)continue;if(Array.isArray(G)&&Array.isArray(Z))Y[Q]=[...Z,...G];else if(typeof G==="object"&&G!==null&&!Array.isArray(G)&&typeof Z==="object"&&Z!==null&&!Array.isArray(Z))Y[Q]=vG(Z,G);else Y[Q]=G}return Y}function RG($,J){return vG($,J)}function pT(...$){return $.reduce((J,Y)=>vG(J,Y),{})}function rT($,J){return(Y)=>{let Q=$(Y);if(typeof J==="function")return RG(Q,J(Q,Y));return RG(Q,J)}}function e2($){return{infrastructure:$}}function nT($){return e2({monitoring:$})}function iT($){return e2({security:$})}function tT($){return e2({databases:$})}function aT($){return e2({cache:$})}function oT($){return e2({cdn:$})}function sT($){return e2({queues:$})}function R_(){let $=process.env.AWS_ACCESS_KEY_ID,J=process.env.AWS_SECRET_ACCESS_KEY;if(!$||!J)return null;return{accessKeyId:$,secretAccessKey:J,sessionToken:process.env.AWS_SESSION_TOKEN}}function D_($){let J=$?.profile||process.env.AWS_PROFILE||"default",Y=$?.credentialsFile||w_(T_(),".aws","credentials");if(!M_(Y))return null;try{let Q=fG(Y,"utf-8");return eT(Q,J)}catch{return null}}function eT($,J){let Y=$.split(`
|
|
258
258
|
`),Q=null,G,Z,W;for(let U of Y){let z=U.trim();if(!z||z.startsWith("#")||z.startsWith(";"))continue;let H=z.match(/^\[([^\]]+)\]$/);if(H){if(Q===J&&G&&Z)return{accessKeyId:G,secretAccessKey:Z,sessionToken:W};Q=H[1],G=void 0,Z=void 0,W=void 0;continue}if(Q===J){let[_,...X]=z.split("="),F=X.join("=").trim();switch(_.trim().toLowerCase()){case"aws_access_key_id":G=F;break;case"aws_secret_access_key":Z=F;break;case"aws_session_token":W=F;break}}}if(Q===J&&G&&Z)return{accessKeyId:G,secretAccessKey:Z,sessionToken:W};return null}async function N_($){let J=$?.timeout??1000,Y="http://169.254.169.254";try{let Q=await I9("http://169.254.169.254/latest/api/token",{method:"PUT",headers:{"X-aws-ec2-metadata-token-ttl-seconds":"21600"}},J);if(!Q.ok)return null;let G=await Q.text(),Z=await I9("http://169.254.169.254/latest/meta-data/iam/security-credentials/",{headers:{"X-aws-ec2-metadata-token":G}},J);if(!Z.ok)return null;let W=(await Z.text()).trim(),U=await I9(`http://169.254.169.254/latest/meta-data/iam/security-credentials/${W}`,{headers:{"X-aws-ec2-metadata-token":G}},J);if(!U.ok)return null;let z=await U.json();return{accessKeyId:z.AccessKeyId,secretAccessKey:z.SecretAccessKey,sessionToken:z.Token,expiration:new Date(z.Expiration)}}catch{return null}}async function S_($){let J=$?.timeout??1000,Y=process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI,Q=process.env.AWS_CONTAINER_CREDENTIALS_FULL_URI,G=null;if(Y)G=`http://169.254.170.2${Y}`;else if(Q)G=Q;if(!G)return null;try{let Z={},W=process.env.AWS_CONTAINER_AUTHORIZATION_TOKEN;if(W)Z.Authorization=W;let U=await I9(G,{headers:Z},J);if(!U.ok)return null;let z=await U.json();return{accessKeyId:z.AccessKeyId,secretAccessKey:z.SecretAccessKey,sessionToken:z.Token,expiration:new Date(z.Expiration)}}catch{return null}}async function P_($){let J=$?.timeout??5000,Y=process.env.AWS_WEB_IDENTITY_TOKEN_FILE,Q=process.env.AWS_ROLE_ARN,G=process.env.AWS_ROLE_SESSION_NAME||"ts-cloud-session";if(!Y||!Q)return null;try{let Z=fG(Y,"utf-8").trim(),W=process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||"us-east-1",U=W.startsWith("us-gov")?`https://sts.${W}.amazonaws.com`:W==="us-east-1"?"https://sts.amazonaws.com":`https://sts.${W}.amazonaws.com`,z=new URLSearchParams({Action:"AssumeRoleWithWebIdentity",Version:"2011-06-15",RoleArn:Q,RoleSessionName:G,WebIdentityToken:Z}),H=await I9(`${U}/?${z.toString()}`,{method:"POST"},J);if(!H.ok)return null;let _=await H.text(),X=N9(_,"AccessKeyId"),F=N9(_,"SecretAccessKey"),B=N9(_,"SessionToken"),V=N9(_,"Expiration");if(!X||!F)return null;return{accessKeyId:X,secretAccessKey:F,sessionToken:B??void 0,expiration:V?new Date(V):void 0}}catch{return null}}async function d9($){let J=R_();if(J)return J;let Y=D_($);if(Y)return Y;let Q=await P_($);if(Q)return Q;let G=await S_($);if(G)return G;let Z=await N_($);if(Z)return Z;throw Error("Could not find AWS credentials. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables, or configure ~/.aws/credentials, or run on an EC2 instance with an IAM role.")}function $w($){let J=null,Y=null;return async()=>{if(J){if(!J.expiration)return J;let Q=300000;if(J.expiration.getTime()-Date.now()>Q)return J}if(Y)return Y;return Y=d9($).then((Q)=>{return J=Q,Y=null,Q}).catch((Q)=>{throw Y=null,Q}),Y}}async function I9($,J,Y){let Q=new AbortController,G=setTimeout(()=>Q.abort(),Y);try{let Z=await fetch($,{...J,signal:Q.signal});return clearTimeout(G),Z}catch(Z){throw clearTimeout(G),Z}}function N9($,J){let Y=new RegExp(`<${J}>([^<]+)</${J}>`),Q=$.match(Y);return Q?Q[1]:null}async function J6($){return d9({profile:$})}function C_($){let J=process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION;if(J)return J;let Y=w_(T_(),".aws","config");if(M_(Y))try{let Q=fG(Y,"utf-8"),G=$||process.env.AWS_PROFILE||"default",Z=G==="default"?"[default]":`[profile ${G}]`,W=Q.split(`
|
|
259
259
|
`),U=!1;for(let z of W){let H=z.trim();if(H.startsWith("[")){U=H===Z;continue}if(U&&H.startsWith("region")){let[,_]=H.split("=");if(_)return _.trim()}}}catch{}return"us-east-1"}async function I_($){let J=$||await d9(),Y=C_(),{signRequest:Q}=await f9().then(()=>aH),G=Y.startsWith("us-gov")?`https://sts.${Y}.amazonaws.com`:Y==="us-east-1"?"https://sts.amazonaws.com":`https://sts.${Y}.amazonaws.com`,Z="Action=GetCallerIdentity&Version=2011-06-15",W=Q({method:"POST",url:G,body:"Action=GetCallerIdentity&Version=2011-06-15",headers:{"Content-Type":"application/x-www-form-urlencoded"},...J,service:"sts",region:Y}),U=await fetch(W.url,{method:W.method,headers:W.headers,body:W.body});if(!U.ok)throw Error(`Failed to get account ID: ${await U.text()}`);let z=await U.text(),H=N9(z,"Account");if(!H)throw Error("Failed to parse account ID from response");return H}class x_{profile;credentials=null;region;constructor($="us-east-1",J="default"){this.profile=J,this.region=$}async init(){if(this.credentials=await J6(this.profile),this.credentials.region)this.region=this.credentials.region}async ensureCredentials(){if(!this.credentials)await this.init();return this.credentials}async request($,J){let Y=await this.ensureCredentials(),Q={Action:$,Version:"2010-05-15",...DG(J)},G=new URLSearchParams(Q).toString(),W=await(await t2({method:"POST",url:`https://cloudformation.${this.region}.amazonaws.com/`,service:"cloudformation",region:this.region,headers:{"Content-Type":"application/x-www-form-urlencoded"},body:G,accessKeyId:Y.accessKeyId,secretAccessKey:Y.secretAccessKey,sessionToken:Y.sessionToken})).text();return Jw(W)}async createStack($){let J={StackName:$.stackName};if($.templateBody)J.TemplateBody=$.templateBody;else if($.templateURL)J.TemplateURL=$.templateURL;else throw Error("Either templateBody or templateURL must be provided");if($.parameters)for(let[G,[Z,W]]of Object.entries($.parameters).entries())J[`Parameters.member.${G+1}.ParameterKey`]=Z,J[`Parameters.member.${G+1}.ParameterValue`]=W;if($.capabilities)for(let[G,Z]of $.capabilities.entries())J[`Capabilities.member.${G+1}`]=Z;if($.tags)for(let[G,[Z,W]]of Object.entries($.tags).entries())J[`Tags.member.${G+1}.Key`]=Z,J[`Tags.member.${G+1}.Value`]=W;if($.timeoutInMinutes)J.TimeoutInMinutes=$.timeoutInMinutes;if($.onFailure)J.OnFailure=$.onFailure;let Y=await this.request("CreateStack",J);return(Y?.CreateStackResult||Y?.CreateStackResponse?.CreateStackResult||Y)?.StackId}async updateStack($){let J={StackName:$.stackName};if($.templateBody)J.TemplateBody=$.templateBody;else if($.templateURL)J.TemplateURL=$.templateURL;if($.parameters)for(let[G,[Z,W]]of Object.entries($.parameters).entries())J[`Parameters.member.${G+1}.ParameterKey`]=Z,J[`Parameters.member.${G+1}.ParameterValue`]=W;if($.capabilities)for(let[G,Z]of $.capabilities.entries())J[`Capabilities.member.${G+1}`]=Z;if($.tags)for(let[G,[Z,W]]of Object.entries($.tags).entries())J[`Tags.member.${G+1}.Key`]=Z,J[`Tags.member.${G+1}.Value`]=W;let Y=await this.request("UpdateStack",J);return(Y?.UpdateStackResult||Y?.UpdateStackResponse?.UpdateStackResult||Y)?.StackId}async deleteStack($){await this.request("DeleteStack",{StackName:$})}async describeStack($){let J=await this.request("DescribeStacks",{StackName:$}),Q=(J?.DescribeStacksResult||J?.DescribeStacksResponse?.DescribeStacksResult||J)?.Stacks?.member,G=Array.isArray(Q)?Q[0]:Q;if(!G)throw Error(`Stack ${$} not found`);return Yw(G)}async listStacks($){let J={};if($)for(let[Q,G]of $.entries())J[`StackStatusFilter.member.${Q+1}`]=G;let Y=await this.request("ListStacks",J);return Qw(Y)}async describeStackEvents($){let J=await this.request("DescribeStackEvents",{StackName:$});return Gw(J)}async waitForStack($,J,Y){let Z=0,W=null;while(Z<360){Z++;let U=await this.describeStack($);if(Y)try{let z=await this.describeStackEvents($),H=[];if(W){for(let _ of z){if(_.EventId===W)break;H.push(_)}H.reverse()}else if(z.length>0)H=[z[0]];for(let _ of H)Y(_);if(z.length>0)W=z[0].EventId}catch{}if(U.StackStatus&&J.includes(U.StackStatus))return U;if(U.StackStatus?.includes("FAILED")||U.StackStatus?.includes("ROLLBACK"))throw Error(`Stack reached failed state: ${U.StackStatus}
|
|
260
260
|
Reason: ${U.StackStatusReason||"Unknown"}`);await new Promise((z)=>setTimeout(z,5000))}throw Error(`Timeout waiting for stack ${$} to complete`)}async waitForStackWithProgress($,J,Y){let G={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]}[J];if(!G)throw Error(`Unknown waiter: ${J}`);return this.waitForStack($,G,Y)}async createChangeSet($){let J={StackName:$.stackName,ChangeSetName:$.changeSetName,ChangeSetType:"UPDATE"};if($.templateBody)J.TemplateBody=$.templateBody;else if($.templateURL)J.TemplateURL=$.templateURL;if($.parameters)for(let[Q,[G,Z]]of Object.entries($.parameters).entries())J[`Parameters.member.${Q+1}.ParameterKey`]=G,J[`Parameters.member.${Q+1}.ParameterValue`]=Z;if($.capabilities)for(let[Q,G]of $.capabilities.entries())J[`Capabilities.member.${Q+1}`]=G;return(await this.request("CreateChangeSet",J)).ChangeSetId}async executeChangeSet($,J){await this.request("ExecuteChangeSet",{ChangeSetName:$,StackName:J})}async describeStacks($){let J=typeof $==="string"?$:$.stackName;try{return{Stacks:[await this.describeStack(J)]}}catch{return{Stacks:[]}}}async getStackOutputs($){let J=await this.request("DescribeStacks",{StackName:$}),Q=(J?.DescribeStacksResult||J?.DescribeStacksResponse?.DescribeStacksResult||J)?.Stacks?.member,G=Array.isArray(Q)?Q[0]:Q;if(!G)return{};let Z={},W=G.Outputs?.member;if(W){let U=Array.isArray(W)?W:[W];for(let z of U)if(z.OutputKey&&z.OutputValue)Z[z.OutputKey]=z.OutputValue}return Z}}function DG($,J=""){let Y={};for(let[Q,G]of Object.entries($)){let Z=J?`${J}.${Q}`:Q;if(Array.isArray(G))G.forEach((W,U)=>{if(typeof W==="object")Object.assign(Y,DG(W,`${Z}.${U+1}`));else Y[`${Z}.${U+1}`]=String(W)});else if(typeof G==="object"&&G!==null)Object.assign(Y,DG(G,Z));else if(G!==void 0&&G!==null)Y[Z]=String(G)}return Y}function Jw($){$=$.replace(/<\?xml[^?]*\?>\s*/,"").trim();function J(G,Z,W){let U=1,z=W,H=`<${Z}`,_=`</${Z}>`;while(z<G.length&&U>0){let X=G.indexOf(H,z),F=G.indexOf(_,z);if(F===-1)return-1;if(X!==-1&&X<F){let B=G[X+H.length];if(B===">"||B===" "||B==="/"){let V=G.indexOf(">",X);if(V!==-1&&G[V-1]==="/")z=V+1;else U++,z=V+1}else z=X+H.length}else{if(U--,U===0)return F;z=F+_.length}}return-1}function Y(G,Z){while(Z<G.length&&/\s/.test(G[Z]))Z++;if(Z>=G.length||G[Z]!=="<"){let K=G.indexOf("<",Z);if(K===-1)return{value:G.slice(Z).trim(),end:G.length};return{value:G.slice(Z,K).trim(),end:K}}if(G[Z+1]==="/")return{value:void 0,end:Z};let W=G.slice(Z).match(/^<(\w+)([^>]*?)\/?>/);if(!W)return{value:void 0,end:Z+1};let U=W[1];if(W[0].endsWith("/>"))return{value:"",end:Z+W[0].length};let H=Z+W[0].length,_=`</${U}>`,X=J(G,U,H);if(X===-1)return{value:void 0,end:Z+W[0].length};let F=G.slice(H,X).trim();if(!F.includes("<"))return{value:F,end:X+_.length};let B={},V=H;while(V<X){while(V<X&&/\s/.test(G[V]))V++;if(V>=X)break;if(G[V]!=="<"||G[V+1]==="/")break;let K=G.slice(V).match(/^<(\w+)/);if(!K)break;let L=K[1],E=Y(G,V);if(E.value===void 0){V++;continue}if(L==="member"||B[L]!==void 0){if(!Array.isArray(B[L]))B[L]=B[L]!==void 0?[B[L]]:[];B[L].push(E.value)}else B[L]=E.value;V=E.end}return{value:B,end:X+_.length}}return Y($,0).value||{}}function Yw($){return{StackName:$.StackName||"",StackId:$.StackId,StackStatus:$.StackStatus,CreationTime:$.CreationTime,LastUpdatedTime:$.LastUpdatedTime,StackStatusReason:$.StackStatusReason,Description:$.Description}}function Qw($){let Y=($?.ListStacksResult||$?.ListStacksResponse?.ListStacksResult||$)?.StackSummaries?.member;if(!Y)return[];return(Array.isArray(Y)?Y:[Y]).map((G)=>({StackName:G.StackName||"",StackId:G.StackId,StackStatus:G.StackStatus,CreationTime:G.CreationTime,LastUpdatedTime:G.LastUpdatedTime,StackStatusReason:G.StackStatusReason,Description:G.Description}))}function Gw($){let Y=($?.DescribeStackEventsResult||$?.DescribeStackEventsResponse?.DescribeStackEventsResult||$)?.StackEvents?.member;if(!Y)return[];return(Array.isArray(Y)?Y:[Y]).map((G)=>({StackId:G.StackId||"",EventId:G.EventId||"",StackName:G.StackName||"",LogicalResourceId:G.LogicalResourceId||"",PhysicalResourceId:G.PhysicalResourceId,ResourceType:G.ResourceType||"",Timestamp:G.Timestamp||"",ResourceStatus:G.ResourceStatus||"",ResourceStatusReason:G.ResourceStatusReason}))}class gG{region;endpoint;forcePathStyle;credentials;credentialOptions;retryOptions;constructor($={}){this.region=$.region||process.env.AWS_REGION||"us-east-1",this.endpoint=$.endpoint||`https://s3.${this.region}.amazonaws.com`,this.forcePathStyle=$.forcePathStyle||!1,this.credentials=$.credentials,this.credentialOptions=$.credentialOptions,this.retryOptions=$.retryOptions||{}}async getCredentials(){if(this.credentials)return this.credentials;return d9(this.credentialOptions)}buildUrl($,J){let Y=J?encodeURIComponent(J).replace(/%2F/g,"/"):"";if(this.forcePathStyle)return J?`${this.endpoint}/${$}/${Y}`:`${this.endpoint}/${$}`;let Q=new URL(this.endpoint);return Q.hostname=`${$}.${Q.hostname}`,J?`${Q.origin}/${Y}`:Q.origin}async get($,J,Y={}){let Q=await this.getCredentials(),G=this.buildUrl($,J),Z={};if(Y.range)Z.Range=Y.range;if(Y.ifModifiedSince)Z["If-Modified-Since"]=Y.ifModifiedSince.toUTCString();if(Y.ifMatch)Z["If-Match"]=Y.ifMatch;if(Y.ifNoneMatch)Z["If-None-Match"]=Y.ifNoneMatch;let W=new URL(G);if(Y.responseContentType)W.searchParams.set("response-content-type",Y.responseContentType);if(Y.responseContentDisposition)W.searchParams.set("response-content-disposition",Y.responseContentDisposition);let U=q1({method:"GET",url:W.toString(),headers:Z,...Q,service:"s3",region:this.region}),z=await fetch(U.url,{method:U.method,headers:U.headers});if(!z.ok&&z.status!==304){let H=await z.text();throw new y1(`Failed to get object: ${H}`,z.status,$,J)}return z}async getText($,J,Y={}){return(await this.get($,J,Y)).text()}async getJSON($,J,Y={}){return(await this.get($,J,Y)).json()}async getBuffer($,J,Y={}){return(await this.get($,J,Y)).arrayBuffer()}async put($,J,Y,Q={}){let G,Z;if(typeof Y==="string")G=new TextEncoder().encode(Y).length,Z=Y;else if(Y instanceof ArrayBuffer)G=Y.byteLength,Z=Y;else if(Y instanceof Uint8Array)G=Y.byteLength,Z=Y;else if(Y instanceof Blob)G=Y.size,Z=Y;else return this.uploadMultipart($,J,Y,{...Q,partSize:jG});if(G>Ww){let W=Hw(Z).stream();return this.uploadMultipart($,J,W,{...Q,partSize:jG})}return this.putSimple($,J,Z,G,Q)}async putSimple($,J,Y,Q,G){let Z=await this.getCredentials(),W=this.buildUrl($,J),U={"Content-Length":String(Q),"Content-Type":G.contentType||pH(J)};if(G.contentEncoding)U["Content-Encoding"]=G.contentEncoding;if(G.cacheControl)U["Cache-Control"]=G.cacheControl;if(G.contentDisposition)U["Content-Disposition"]=G.contentDisposition;if(G.storageClass)U["x-amz-storage-class"]=G.storageClass;if(G.serverSideEncryption)U["x-amz-server-side-encryption"]=G.serverSideEncryption;if(G.acl)U["x-amz-acl"]=G.acl;if(G.tagging)U["x-amz-tagging"]=G.tagging;if(G.metadata)for(let[F,B]of Object.entries(G.metadata))U[`x-amz-meta-${F.toLowerCase()}`]=B;let z;if(typeof Y==="string")z=Y;else if(Y instanceof Blob)z=await Y.text();else z=new TextDecoder().decode(Y instanceof ArrayBuffer?new Uint8Array(Y):Y);let H=q1({method:"PUT",url:W,headers:U,body:z,...Z,service:"s3",region:this.region}),_=await fetch(H.url,{method:H.method,headers:H.headers,body:Y});if(!_.ok){let F=await _.text();throw new y1(`Failed to put object: ${F}`,_.status,$,J)}return{etag:(_.headers.get("ETag")||"").replace(/"/g,"")}}async delete($,J){let Y=await this.getCredentials(),Q=this.buildUrl($,J),G=q1({method:"DELETE",url:Q,...Y,service:"s3",region:this.region}),Z=await fetch(G.url,{method:G.method,headers:G.headers});if(!Z.ok&&Z.status!==204){let W=await Z.text();throw new y1(`Failed to delete object: ${W}`,Z.status,$,J)}}async deleteMany($,J){let Y=await this.getCredentials(),Q=`${this.buildUrl($)}?delete`,Z=`<?xml version="1.0" encoding="UTF-8"?><Delete><Quiet>false</Quiet>${J.map((V)=>`<Object><Key>${zw(V)}</Key></Object>`).join("")}</Delete>`,W=q1({method:"POST",url:Q,headers:{"Content-Type":"application/xml"},body:Z,...Y,service:"s3",region:this.region}),U=await fetch(W.url,{method:W.method,headers:W.headers,body:Z});if(!U.ok){let V=await U.text();throw new y1(`Failed to delete objects: ${V}`,U.status,$)}let z=await U.text(),H=[],_=[],X=/<Deleted><Key>([^<]+)<\/Key>/g,F;while((F=X.exec(z))!==null)H.push(F[1]);let B=/<Error><Key>([^<]+)<\/Key><Code>([^<]+)<\/Code><Message>([^<]+)<\/Message>/g;while((F=B.exec(z))!==null)_.push({key:F[1],error:`${F[2]}: ${F[3]}`});return{deleted:H,errors:_}}async list($,J={}){let Y=await this.getCredentials(),Q=new URL(this.buildUrl($));if(Q.searchParams.set("list-type","2"),J.prefix)Q.searchParams.set("prefix",J.prefix);if(J.delimiter)Q.searchParams.set("delimiter",J.delimiter);if(J.maxKeys)Q.searchParams.set("max-keys",String(J.maxKeys));if(J.continuationToken)Q.searchParams.set("continuation-token",J.continuationToken);if(J.startAfter)Q.searchParams.set("start-after",J.startAfter);let G=q1({method:"GET",url:Q.toString(),...Y,service:"s3",region:this.region}),Z=await fetch(G.url,{method:G.method,headers:G.headers});if(!Z.ok){let U=await Z.text();throw new y1(`Failed to list objects: ${U}`,Z.status,$)}let W=await Z.text();return Uw(W)}async*listAll($,J={}){let Y;do{let Q=await this.list($,{...J,continuationToken:Y});for(let G of Q.contents)yield G;Y=Q.nextContinuationToken}while(Y)}async head($,J){let Y=await this.getCredentials(),Q=this.buildUrl($,J),G=q1({method:"HEAD",url:Q,...Y,service:"s3",region:this.region}),Z=await fetch(G.url,{method:G.method,headers:G.headers});if(Z.status===404)return null;if(!Z.ok){let U=await Z.text();throw new y1(`Failed to head object: ${U}`,Z.status,$,J)}let W={};return Z.headers.forEach((U,z)=>{if(z.toLowerCase().startsWith("x-amz-meta-"))W[z.slice(11)]=U}),{contentLength:Number(Z.headers.get("Content-Length")||0),contentType:Z.headers.get("Content-Type")||"application/octet-stream",etag:(Z.headers.get("ETag")||"").replace(/"/g,""),lastModified:new Date(Z.headers.get("Last-Modified")||0),metadata:W,storageClass:Z.headers.get("x-amz-storage-class")||void 0,serverSideEncryption:Z.headers.get("x-amz-server-side-encryption")||void 0}}async exists($,J){return await this.head($,J)!==null}async copy($,J,Y,Q,G={}){let Z=await this.getCredentials(),W=this.buildUrl(Y,Q),U={"x-amz-copy-source":`/${$}/${encodeURIComponent(J)}`};if(G.metadataDirective)U["x-amz-metadata-directive"]=G.metadataDirective;if(G.contentType)U["Content-Type"]=G.contentType;if(G.storageClass)U["x-amz-storage-class"]=G.storageClass;if(G.acl)U["x-amz-acl"]=G.acl;if(G.metadata)for(let[B,V]of Object.entries(G.metadata))U[`x-amz-meta-${B.toLowerCase()}`]=V;let z=q1({method:"PUT",url:W,headers:U,...Z,service:"s3",region:this.region}),H=await fetch(z.url,{method:z.method,headers:z.headers});if(!H.ok){let B=await H.text();throw new y1(`Failed to copy object: ${B}`,H.status,Y,Q)}let X=(await H.text()).match(/<ETag>"?([^"<]+)"?<\/ETag>/);return{etag:X?X[1]:""}}async getPresignedUrl($,J,Y={}){let Q=await this.getCredentials(),G=this.buildUrl($,J);return SG({url:G,method:Y.method||"GET",expiresIn:Y.expiresIn||3600,...Q,service:"s3",region:this.region})}async uploadMultipart($,J,Y,Q={}){let G=await this.getCredentials(),Z=Math.max(Q.partSize||jG,Zw),W,U;if(Y instanceof ReadableStream)W=Y;else if(Y instanceof Blob)W=Y.stream(),U=Y.size;else{let _=new Blob([Y]);W=_.stream(),U=_.size}let{uploadId:z,baseUrl:H}=await this.initiateMultipartUpload($,J,Q);try{let _=await this.uploadParts($,J,H,z,W,Z,G,U,Q.concurrency||4,Q.onProgress);return await this.completeMultipartUpload($,J,H,z,_)}catch(_){throw await this.abortMultipartUpload($,J,z,H).catch(()=>{}),_}}async initiateMultipartUpload($,J,Y){let Q=await this.getCredentials(),G=this.buildUrl($,J),Z=`${G}?uploads`,W={"Content-Type":Y.contentType||pH(J)};if(Y.storageClass)W["x-amz-storage-class"]=Y.storageClass;if(Y.serverSideEncryption)W["x-amz-server-side-encryption"]=Y.serverSideEncryption;if(Y.acl)W["x-amz-acl"]=Y.acl;if(Y.metadata)for(let[F,B]of Object.entries(Y.metadata))W[`x-amz-meta-${F.toLowerCase()}`]=B;let U=q1({method:"POST",url:Z,headers:W,...Q,service:"s3",region:this.region}),z=await fetch(U.url,{method:U.method,headers:U.headers});if(!z.ok){let F=await z.text();throw new y1(`Failed to initiate multipart upload: ${F}`,z.status,$,J)}let _=(await z.text()).match(/<UploadId>([^<]+)<\/UploadId>/);if(!_)throw new y1("Failed to parse upload ID from response",0,$,J);let X=G;if(z.url)try{let F=new URL(z.url);F.search="",X=F.toString()}catch{}return{uploadId:_[1],baseUrl:X}}async uploadParts($,J,Y,Q,G,Z,W,U,z,H){let _=[],X=G.getReader(),F=1,B=new Uint8Array(0),V=0,K=U?Math.ceil(U/Z):void 0,L=new Map,E=async(j,q)=>{let M=`${Y}?partNumber=${q}&uploadId=${encodeURIComponent(Q)}`,w={"Content-Length":String(j.byteLength),"x-amz-content-sha256":"UNSIGNED-PAYLOAD"},R=q1({method:"PUT",url:M,headers:w,...W,service:"s3",region:this.region}),S=await fetch(R.url,{method:R.method,headers:R.headers,body:j,redirect:"error"});if(!S.ok){let C=await S.text();throw new y1(`Failed to upload part ${q}: ${C}`,S.status,$,J)}let N=(S.headers.get("ETag")||"").replace(/"/g,"");if(!N)throw new y1(`Missing ETag for part ${q}`,S.status,$,J);return{partNumber:q,etag:N}},A=async()=>{let j=await Promise.race(L.values());L.delete(j.partNumber),_.push(j)};while(!0){let{done:j,value:q}=await X.read();if(q){let M=new Uint8Array(B.length+q.length);M.set(B),M.set(q,B.length),B=M}while(B.length>=Z||j&&B.length>0){let M=B.slice(0,Z);B=B.slice(Z);let w=F++;if(L.size>=z)await A();if(L.set(w,E(M,w)),V+=M.byteLength,H)H({loaded:V,total:U||V,part:w,totalParts:K||w})}if(j)break}while(L.size>0)await A();return _.sort((j,q)=>j.partNumber-q.partNumber),_}async completeMultipartUpload($,J,Y,Q,G){let Z=await this.getCredentials(),W=`${Y}?uploadId=${encodeURIComponent(Q)}`,z=`<?xml version="1.0" encoding="UTF-8"?><CompleteMultipartUpload>${G.map((V)=>`<Part><PartNumber>${V.partNumber}</PartNumber><ETag>"${V.etag}"</ETag></Part>`).join("")}</CompleteMultipartUpload>`,H=q1({method:"POST",url:W,headers:{"Content-Type":"application/xml"},body:z,...Z,service:"s3",region:this.region}),_=await fetch(H.url,{method:H.method,headers:H.headers,body:z});if(!_.ok){let V=await _.text();throw new y1(`Failed to complete multipart upload: ${V}`,_.status,$,J)}let F=(await _.text()).match(/<ETag>"?([^"<]+)"?<\/ETag>/);return{etag:F?F[1]:""}}async abortMultipartUpload($,J,Y,Q){let G=await this.getCredentials(),Z=`${Q??this.buildUrl($,J)}?uploadId=${encodeURIComponent(Y)}`,W=q1({method:"DELETE",url:Z,...G,service:"s3",region:this.region});await fetch(W.url,{method:W.method,headers:W.headers})}async emptyAndDeleteBucket($){let Y=[];for await(let W of this.listAll($,{}))if(Y.push(W.key),Y.length>=1000)await this.deleteMany($,Y),Y=[];if(Y.length>0)await this.deleteMany($,Y);let Q=await this.getCredentials(),G=this.buildUrl($),Z=q1({method:"DELETE",url:G,...Q,service:"s3",region:this.region});await fetch(Z.url,{method:Z.method,headers:Z.headers})}}function Uw($){let J=[],Y=[],Q=/<Contents>([\s\S]*?)<\/Contents>/g,G;while((G=Q.exec($))!==null){let W=G[1];J.push({key:W$(W,"Key")||"",lastModified:new Date(W$(W,"LastModified")||0),etag:(W$(W,"ETag")||"").replace(/"/g,""),size:Number(W$(W,"Size")||0),storageClass:W$(W,"StorageClass")||"STANDARD"})}let Z=/<CommonPrefixes><Prefix>([^<]+)<\/Prefix><\/CommonPrefixes>/g;while((G=Z.exec($))!==null)Y.push(G[1]);return{contents:J,commonPrefixes:Y,isTruncated:W$($,"IsTruncated")==="true",continuationToken:W$($,"ContinuationToken")||void 0,nextContinuationToken:W$($,"NextContinuationToken")||void 0,keyCount:Number(W$($,"KeyCount")||0),maxKeys:Number(W$($,"MaxKeys")||1000),prefix:W$($,"Prefix")||void 0,delimiter:W$($,"Delimiter")||void 0}}function W$($,J){let Y=new RegExp(`<${J}>([^<]*)</${J}>`),Q=$.match(Y);return Q?Q[1]:null}function zw($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function pH($){let J=$.split(".").pop()?.toLowerCase();return{html:"text/html",htm:"text/html",css:"text/css",js:"application/javascript",mjs:"application/javascript",json:"application/json",xml:"application/xml",txt:"text/plain",md:"text/markdown",csv:"text/csv",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",ico:"image/x-icon",avif:"image/avif",mp4:"video/mp4",webm:"video/webm",mov:"video/quicktime",avi:"video/x-msvideo",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",zip:"application/zip",gz:"application/gzip",tar:"application/x-tar",rar:"application/vnd.rar","7z":"application/x-7z-compressed",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",otf:"font/otf",eot:"application/vnd.ms-fontobject",wasm:"application/wasm"}[J||""]||"application/octet-stream"}function Hw($){if($ instanceof Blob)return $;if(typeof $==="string")return new Blob([$],{type:"text/plain"});return new Blob([$])}function _w($){return new gG($)}class k_{profile;credentials=null;constructor($="default"){this.profile=$}async init(){this.credentials=await J6(this.profile)}async ensureCredentials(){if(!this.credentials)await this.init();return this.credentials}async createInvalidation($){let J=await this.ensureCredentials(),Y=$.callerReference||`invalidation-${Date.now()}`,Q=`<?xml version="1.0" encoding="UTF-8"?>
|
|
@@ -13638,7 +13638,7 @@ async function sendFallbackSms(to, message) {
|
|
|
13638
13638
|
</ChangeBatch>
|
|
13639
13639
|
</ChangeResourceRecordSetsRequest>`;let G=await this.client.request({service:"route53",region:this.region,method:"POST",path:`/2013-04-01/hostedzone/${Y}/rrset`,headers:{"content-type":"application/xml"},body:Q});return this.parseChangeResourceRecordSetsResponse(G)}escapeXml(J){return J.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}parseCreateHostedZoneResponse(J){let Y=J.CreateHostedZoneResponse||J;return{HostedZone:this.parseHostedZone(Y.HostedZone),ChangeInfo:{Id:Y.ChangeInfo?.Id||"",Status:Y.ChangeInfo?.Status||"",SubmittedAt:Y.ChangeInfo?.SubmittedAt||""},DelegationSet:this.parseDelegationSet(Y.DelegationSet),Location:Y.Location||""}}parseListHostedZonesResponse(J){let Y=J.ListHostedZonesResponse||J.ListHostedZonesByNameResponse||J,Q=Y.HostedZones?.HostedZone||Y.HostedZones||[];if(!Array.isArray(Q))Q=Q?[Q]:[];return{HostedZones:Q.map((G)=>this.parseHostedZone(G)),IsTruncated:Y.IsTruncated==="true"||Y.IsTruncated===!0,MaxItems:Y.MaxItems||"100",Marker:Y.Marker,NextMarker:Y.NextMarker}}parseGetHostedZoneResponse(J){let Y=J.GetHostedZoneResponse||J;return{HostedZone:this.parseHostedZone(Y.HostedZone),DelegationSet:this.parseDelegationSet(Y.DelegationSet),VPCs:Y.VPCs?.VPC?Array.isArray(Y.VPCs.VPC)?Y.VPCs.VPC:[Y.VPCs.VPC]:void 0}}parseListResourceRecordSetsResponse(J){let Y=J.ListResourceRecordSetsResponse||J,Q=Y.ResourceRecordSets?.ResourceRecordSet||Y.ResourceRecordSets||[];if(!Array.isArray(Q))Q=Q?[Q]:[];return{ResourceRecordSets:Q.map((G)=>this.parseResourceRecordSet(G)),IsTruncated:Y.IsTruncated==="true"||Y.IsTruncated===!0,MaxItems:Y.MaxItems||"100",NextRecordName:Y.NextRecordName,NextRecordType:Y.NextRecordType,NextRecordIdentifier:Y.NextRecordIdentifier}}parseChangeResourceRecordSetsResponse(J){let Y=J.ChangeResourceRecordSetsResponse||J;return{ChangeInfo:{Id:Y.ChangeInfo?.Id||"",Status:Y.ChangeInfo?.Status||"",SubmittedAt:Y.ChangeInfo?.SubmittedAt||"",Comment:Y.ChangeInfo?.Comment}}}parseHostedZone(J){if(!J)return{Id:"",Name:""};return{Id:J.Id||"",Name:J.Name||"",CallerReference:J.CallerReference,Config:J.Config?{Comment:J.Config.Comment,PrivateZone:J.Config.PrivateZone==="true"||J.Config.PrivateZone===!0}:void 0,ResourceRecordSetCount:J.ResourceRecordSetCount?Number(J.ResourceRecordSetCount):void 0}}parseDelegationSet(J){if(!J)return{NameServers:[]};let Y=J.NameServers?.NameServer||J.NameServers||[];if(!Array.isArray(Y))Y=Y?[Y]:[];return{Id:J.Id,CallerReference:J.CallerReference,NameServers:Y}}parseResourceRecordSet(J){if(!J)return{Name:"",Type:""};let Y=J.ResourceRecords?.ResourceRecord||J.ResourceRecords||[];if(!Array.isArray(Y))Y=Y?[Y]:[];return{Name:J.Name||"",Type:J.Type||"",TTL:J.TTL?Number(J.TTL):void 0,ResourceRecords:Y.map((Q)=>({Value:Q.Value||Q})),AliasTarget:J.AliasTarget?{HostedZoneId:J.AliasTarget.HostedZoneId,DNSName:J.AliasTarget.DNSName,EvaluateTargetHealth:J.AliasTarget.EvaluateTargetHealth==="true"||J.AliasTarget.EvaluateTargetHealth===!0}:void 0,SetIdentifier:J.SetIdentifier,Weight:J.Weight?Number(J.Weight):void 0,Region:J.Region,GeoLocation:J.GeoLocation,Failover:J.Failover,HealthCheckId:J.HealthCheckId}}async findHostedZoneByName(J){let Y=J.endsWith(".")?J:`${J}.`;return(await this.listHostedZonesByName({DNSName:Y})).HostedZones.find((Z)=>Z.Name===Y)||null}async createARecord(J){let Y=Array.isArray(J.Value)?J.Value:[J.Value];return this.changeResourceRecordSets({HostedZoneId:J.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:J.Name,Type:"A",TTL:J.TTL||300,ResourceRecords:Y.map((Q)=>({Value:Q}))}}]}})}async createCnameRecord(J){return this.changeResourceRecordSets({HostedZoneId:J.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:J.Name,Type:"CNAME",TTL:J.TTL||300,ResourceRecords:[{Value:J.Value}]}}]}})}async createAliasRecord(J){return this.changeResourceRecordSets({HostedZoneId:J.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:J.Name,Type:J.Type||"A",AliasTarget:{HostedZoneId:J.TargetHostedZoneId,DNSName:J.TargetDNSName,EvaluateTargetHealth:J.EvaluateTargetHealth??!1}}}]}})}async createTxtRecord(J){let Q=(Array.isArray(J.Value)?J.Value:[J.Value]).map((G)=>{if(!G.startsWith('"'))return`"${G}"`;return G});return this.changeResourceRecordSets({HostedZoneId:J.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:J.Name,Type:"TXT",TTL:J.TTL||300,ResourceRecords:Q.map((G)=>({Value:G}))}}]}})}async createMxRecord(J){return this.changeResourceRecordSets({HostedZoneId:J.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:J.Name,Type:"MX",TTL:J.TTL||300,ResourceRecords:J.Values.map((Y)=>({Value:`${Y.priority} ${Y.mailServer}`}))}}]}})}async deleteRecord(J){return this.changeResourceRecordSets({HostedZoneId:J.HostedZoneId,ChangeBatch:{Changes:[{Action:"DELETE",ResourceRecordSet:J.RecordSet}]}})}async waitForChange(J,Y=60,Q=5000){let G=J.replace("/change/","");for(let Z=0;Z<Y;Z++){let W=await this.client.request({service:"route53",region:this.region,method:"GET",path:`/2013-04-01/change/${G}`});if((W.GetChangeResponse?.ChangeInfo?.Status||W.ChangeInfo?.Status)==="INSYNC")return!0;await new Promise((z)=>setTimeout(z,Q))}return!1}async findOrCreateHostedZone(J){let Y=J.domainName.endsWith(".")?J.domainName:`${J.domainName}.`,Q=await this.findHostedZoneByName(Y);if(Q){let Z=await this.getHostedZone({Id:Q.Id});return{hostedZone:Q,nameServers:Z.DelegationSet.NameServers,isNew:!1}}let G=await this.createHostedZone({Name:Y,HostedZoneConfig:{Comment:J.comment||`Hosted zone for ${J.domainName}`,PrivateZone:J.privateZone},VPC:J.vpc});return{hostedZone:G.HostedZone,nameServers:G.DelegationSet.NameServers,isNew:!0}}static getRootDomain(J){let Y=J.replace(/\.$/,"").split(".");if(Y.length<=2)return J;return Y.slice(-2).join(".")}async findHostedZoneForDomain(J){let Q=J.replace(/\.$/,"").split(".");for(let G=0;G<Q.length-1;G++){let Z=Q.slice(G).join("."),W=await this.findHostedZoneByName(Z);if(W)return W}return null}async ensureHostedZone(J){let Y=await this.findOrCreateHostedZone({domainName:J.domainName,comment:J.comment});return{hostedZoneId:Y.hostedZone.Id.replace("/hostedzone/",""),nameServers:Y.nameServers,isNew:Y.isNew,action:Y.isNew?"created":"found"}}async setupDomainDns(J){let{domain:Y,createIfNotExists:Q=!0}=J,G=await this.findHostedZoneByName(Y);if(G){let W=await this.getHostedZone({Id:G.Id});return{success:!0,hostedZoneId:G.Id.replace("/hostedzone/",""),nameServers:W.DelegationSet.NameServers,isNew:!1,message:`Found existing hosted zone for ${Y}`}}if(!Q)return{success:!1,hostedZoneId:null,nameServers:[],isNew:!1,message:`No hosted zone found for ${Y} and createIfNotExists is false`};let Z=await this.createHostedZone({Name:Y,HostedZoneConfig:{Comment:`Created automatically by ts-cloud for ${Y}`}});return{success:!0,hostedZoneId:Z.HostedZone.Id.replace("/hostedzone/",""),nameServers:Z.DelegationSet.NameServers,isNew:!0,message:`Created new hosted zone for ${Y}. Please update your domain registrar with these name servers: ${Z.DelegationSet.NameServers.join(", ")}`}}static CloudFrontHostedZoneId="Z2FDTNDATAQYW2";static S3WebsiteHostedZoneIds={"us-east-1":"Z3AQBSTGFYJSTF","us-east-2":"Z2O1EMRO9K5GLX","us-west-1":"Z2F56UZL2M1ACD","us-west-2":"Z3BJ6K6RIION7M","ap-east-1":"ZNB98KWMFR0R6","ap-south-1":"Z11RGJOFQNVJUP","ap-northeast-1":"Z2M4EHUR26P7ZW","ap-northeast-2":"Z3W03O7B5YMIYP","ap-northeast-3":"Z2YQB5RD63NC85","ap-southeast-1":"Z3O0J2DXBE1FTB","ap-southeast-2":"Z1WCIGYICN2BYD","ca-central-1":"Z1QDHH18159H29","eu-central-1":"Z21DNDUVLTQW6Q","eu-west-1":"Z1BKCTXD74EZPE","eu-west-2":"Z3GKZC51ZF0DB4","eu-west-3":"Z3R1K369G5AVDG","eu-north-1":"Z3BAZG2TWCNX0D","sa-east-1":"Z7KQH4QJS55SO"};static ALBHostedZoneIds={"us-east-1":"Z35SXDOTRQ7X7K","us-east-2":"Z3AADJGX6KTTL2","us-west-1":"Z368ELLRRE2KJ0","us-west-2":"Z1H1FL5HABSF5","ap-east-1":"Z3DQVH9N71FHZ0","ap-south-1":"ZP97RAFLXTNZK","ap-northeast-1":"Z14GRHDCWA56QT","ap-northeast-2":"ZWKZPGTI48KDX","ap-northeast-3":"Z5LXEBD8Y73MNV","ap-southeast-1":"Z1LMS91P8CMLE5","ap-southeast-2":"Z1GM3OXH4ZPM65","ca-central-1":"ZQSVJUPU6J1EY","eu-central-1":"Z215JYRZR1TBD5","eu-west-1":"Z32O12XQLNTSW2","eu-west-2":"ZHURV8PSTC4K8","eu-west-3":"Z3Q77PNBQS71R4","eu-north-1":"Z23TAZ6LKFMNIO","sa-east-1":"Z2P70J7HTTTPLU"};static APIGatewayHostedZoneIds={"us-east-1":"Z1UJRXOUMOOFQ8","us-east-2":"ZOJJZC49E0EPZ","us-west-1":"Z2MUQ32089INYE","us-west-2":"Z2OJLYMUO9EFXC","ap-east-1":"Z3FD1VL90ND7K5","ap-south-1":"Z3VO1THU9YC4UR","ap-northeast-1":"Z1YSHQZHG15GKL","ap-northeast-2":"Z20JF4UZKIW1U8","ap-northeast-3":"Z2YQB5RD63NC85","ap-southeast-1":"ZL327KTPIQFUL","ap-southeast-2":"Z2RPCDW04V8134","ca-central-1":"Z19DQILCV0OWEC","eu-central-1":"Z1U9ULNL0V5AJ3","eu-west-1":"ZLY8HYME6SFDD","eu-west-2":"ZJ5UAJN8Y3Z2Q","eu-west-3":"Z3KY65QIEKYHQQ","eu-north-1":"Z3UWIKFBOOGXPP","sa-east-1":"ZCMLWB8V5SYIT"}}});Lz=a0(()=>{Z9()});uV=a0(()=>{tQ(),W9()});W9=a0(()=>{Lz(),uV(),Lz(),bx=new dV});tQ=a0(()=>{F0(),Z9(),W9()});mV=a0(()=>{F0()});sz=a0(()=>{F0()});nV=a0(()=>{F0()}),yx={};rQ(yx,{email:()=>iV,EmailClient:()=>ez});vx=a0(()=>{sz(),a1(),nV(),Z9(),iV=new ez}),fx=a0(()=>{F0()});$4=a0(()=>{G9(),a1(),az(),tQ(),W9(),Lz(),uV()}),dx={};rQ(dx,{uploadStaticFiles:()=>oV,invalidateCache:()=>sV,generateStaticSiteTemplate:()=>tV,deployStaticSiteFull:()=>lx,deployStaticSite:()=>aV,deleteStaticSite:()=>cx});mx=a0(()=>{G9(),a1(),az(),Z9(),tQ(),$4()});eV=a0(()=>{Az={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m"},rx=!!(process.env.CI||process.env.GITHUB_ACTIONS||process.env.BUILDKITE||process.env.CIRCLECI||process.env.GITLAB_CI)}),nx={};rQ(nx,{buildAndPushServerlessImage:()=>sx});ex=a0(async()=>{mV(),eV(),await X2()});bQ=new YL,J4=new QL,dk=Object.defineProperty;GL={};mk(GL,{withErrorRecovery:()=>UL,tryLoadConfig:()=>Bb,loadConfigWithResult:()=>Fb,loadConfig:()=>FL,isRetryableError:()=>Wb,isConfigNotFoundError:()=>Zb,isBunfigError:()=>zL,globalPerformanceMonitor:()=>vJ,globalCache:()=>Y9,getEnvOrDefault:()=>Ub,generateConfigTypes:()=>Kb,defaultGeneratedDir:()=>jL,defaultConfigDir:()=>EL,deepMergeWithArrayStrategy:()=>W4,deepMerge:()=>HL,createLibraryConfig:()=>Vb,config:()=>Ob,bunfigPlugin:()=>Lb,applyEnvVarsToConfig:()=>PJ,TypeGenerationError:()=>Sz,SchemaValidationError:()=>bJ,PluginError:()=>Cz,PerformanceMonitor:()=>Q4,FileSystemError:()=>Nz,ErrorFactory:()=>v2,EnvVarError:()=>uQ,EnvProcessor:()=>oQ,ConfigValidator:()=>U4,ConfigValidationError:()=>Rz,ConfigNotFoundError:()=>gQ,ConfigMergeError:()=>Dz,ConfigLoader:()=>z4,ConfigLoadError:()=>kJ,ConfigFileLoader:()=>sQ,ConfigCache:()=>Y4,CacheUtils:()=>BL,BunfigError:()=>t1,BrowserConfigError:()=>Pz,ArrayMergeStrategies:()=>LL});pb=pk(async()=>{OL=import.meta.require,Y9=new Y4,vJ=new Q4,BL={createKey:rk,isEquivalent:nk,estimateMemoryUsage:ik},Ab=xQ(qz.cwd(),"config"),Eb=xQ(qz.cwd(),"src/generated"),PB=IQ.env.CLARITY_LOG_DIR||Uk(ok(),"logs"),jQ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:PB,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Tz=await sk(),E1={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},v0=E1,jb=E1.red,CB=E1.green,qb=E1.yellow,IB=E1.blue,Mb=E1.magenta,Tb=E1.cyan,$z=E1.white,wb=E1.gray,xB=E1.bgRed,kB=E1.bgYellow,Jz=E1.bold,Rb=E1.dim,Db=E1.italic,Nb=E1.underline,Sb=E1.reset,qQ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},KL={debug:"\uD83D\uDD0D",info:IB("ℹ"),success:CB("✓"),warning:kB($z(Jz(" WARN "))),error:xB($z(Jz(" ERROR ")))},Pb=new yQ("stacks"),j1=new yQ("bunfig",{showTags:!0}),Cb=S1(xJ.cwd(),"config"),Ib=S1(xJ.cwd(),"src/generated"),bB=CQ.env.CLARITY_LOG_DIR||Zk(Yb(),"logs"),MQ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:bB,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},wz=await Qb(),Z1={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},D0=Z1,xb=Z1.red,hB=Z1.green,kb=Z1.yellow,yB=Z1.blue,bb=Z1.magenta,hb=Z1.cyan,Yz=Z1.white,yb=Z1.gray,vB=Z1.bgRed,fB=Z1.bgYellow,vb=Z1.bgGray,Qz=Z1.bold,fb=Z1.dim,gb=Z1.italic,ub=Z1.underline,db=Z1.strikethrough,cb=Z1.reset,TQ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},VL={debug:"\uD83D\uDD0D",info:yB("ℹ"),success:hB("✓"),warning:fB(Yz(Qz(" WARN "))),error:vB(Yz(Qz(" ERROR ")))},lb=new fQ("stacks"),t1=class extends Error{timestamp;context;constructor(J,Y={}){super(J);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Y,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let J=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Y,Q])=>`${Y}: ${Q}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${J}`}},gQ=class extends t1{code="CONFIG_NOT_FOUND";constructor(J,Y,Q){let G=Q?` or alias "${Q}"`:"";super(`Configuration "${J}"${G} not found`,{configName:J,alias:Q,searchPaths:Y,searchPathCount:Y.length})}},kJ=class extends t1{code="CONFIG_LOAD_ERROR";constructor(J,Y,Q){super(`Failed to load configuration from "${J}": ${Y.message}`,{configPath:J,configName:Q,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},Rz=class extends t1{code="CONFIG_VALIDATION_ERROR";constructor(J,Y,Q){super(`Configuration validation failed for "${J}"`,{configPath:J,configName:Q,validationErrors:Y,errorCount:Y.length})}},Dz=class extends t1{code="CONFIG_MERGE_ERROR";constructor(J,Y,Q,G){super(`Failed to merge configuration from "${J}" with "${Y}": ${Q.message}`,{sourcePath:J,targetPath:Y,configName:G,originalError:Q.name,originalMessage:Q.message});this.cause=Q}},uQ=class extends t1{code="ENV_VAR_ERROR";constructor(J,Y,Q,G){super(`Failed to parse environment variable "${J}" with value "${Y}" as ${Q}`,{envKey:J,envValue:Y,expectedType:Q,configName:G})}},Nz=class extends t1{code="FILE_SYSTEM_ERROR";constructor(J,Y,Q){super(`File system ${J} failed for "${Y}": ${Q.message}`,{operation:J,path:Y,originalError:Q.name,originalMessage:Q.message});this.cause=Q}},Sz=class extends t1{code="TYPE_GENERATION_ERROR";constructor(J,Y,Q){super(`Failed to generate types from "${J}" to "${Y}": ${Q.message}`,{configDir:J,outputPath:Y,originalError:Q.name,originalMessage:Q.message});this.cause=Q}},bJ=class extends t1{code="SCHEMA_VALIDATION_ERROR";constructor(J,Y,Q){super(`Schema validation failed${Q?` for config "${Q}"`:""}`,{schemaPath:J,configName:Q,validationErrors:Y,errorCount:Y.length})}},Pz=class extends t1{code="BROWSER_CONFIG_ERROR";constructor(J,Y,Q,G){super(`Failed to fetch configuration from "${J}": ${Y} ${Q}`,{endpoint:J,status:Y,statusText:Q,configName:G})}},Cz=class extends t1{code="PLUGIN_ERROR";constructor(J,Y,Q){super(`Plugin "${J}" failed during ${Y}: ${Q.message}`,{pluginName:J,operation:Y,originalError:Q.name,originalMessage:Q.message});this.cause=Q}},v2={configNotFound($,J,Y){return new gQ($,J,Y)},configLoad($,J,Y){return new kJ($,J,Y)},configValidation($,J,Y){return new Rz($,J,Y)},configMerge($,J,Y,Q){return new Dz($,J,Y,Q)},envVar($,J,Y,Q){return new uQ($,J,Y,Q)},fileSystem($,J,Y){return new Nz($,J,Y)},typeGeneration($,J,Y){return new Sz($,J,Y)},schemaValidation($,J,Y){return new bJ($,J,Y)},browserConfig($,J,Y,Q){return new Pz($,J,Y,Q)},plugin($,J,Y){return new Cz($,J,Y)}},LL={replace:"replace",concat:"concat",smart:"smart"},AL=/^https?:\/\//,w$=new fQ("bunfig",{showTags:!0}),H2=new z4,EL=P1(H8.cwd(),"config"),jL=P1(H8.cwd(),"src/generated")});nb=kQ.env.CLARITY_LOG_DIR||Pk(rb(),"logs"),qL={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:nb,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},dQ={...qL},Cn=(async()=>{try{let{loadConfig:$}=await pb().then(()=>GL),J=await $({name:"clarity",alias:"logging",defaultConfig:qL,cwd:kQ.cwd()});if(J)Object.assign(dQ,J)}catch{}return dQ})();H1={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},P0=H1,In=H1.red,tb=H1.green,xn=H1.yellow,ab=H1.blue,kn=H1.magenta,bn=H1.cyan,gB=H1.white,hn=H1.gray,ob=H1.bgRed,sb=H1.bgYellow,yn=H1.bgGray,uB=H1.bold,vn=H1.dim,fn=H1.italic,gn=H1.underline,un=H1.strikethrough,dn=H1.reset,Gz={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},eb={debug:"\uD83D\uDD0D",info:ab("ℹ"),success:tb("✓"),warning:sb(gB(uB(" WARN "))),error:ob(gB(uB(" ERROR ")))};cn=new eQ("stacks");D$=class D$ extends Error{timestamp;context;constructor($,J={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=J,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([J,Y])=>`${J}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}};TL=class TL extends D${code="CONFIG_NOT_FOUND";constructor($,J,Y){let Q=Y===void 0?[]:Array.isArray(Y)?Y.filter(Boolean):[Y],G="";if(Q.length===1)G=` or alias "${Q[0]}"`;else if(Q.length>1)G=` or aliases ${Q.map((Z)=>`"${Z}"`).join(", ")}`;super(`Configuration "${$}"${G} not found`,{configName:$,alias:Y,searchPaths:J,searchPathCount:J.length})}};cQ=class cQ extends D${code="CONFIG_LOAD_ERROR";constructor($,J,Y){super(`Failed to load configuration from "${$}": ${J.message}`,{configPath:$,configName:Y,originalError:J.name,originalMessage:J.message});this.cause=J}};wL=class wL extends D${code="CONFIG_VALIDATION_ERROR";constructor($,J,Y){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:Y,validationErrors:J,errorCount:J.length})}};RL=class RL extends D${code="CONFIG_MERGE_ERROR";constructor($,J,Y,Q){super(`Failed to merge configuration from "${$}" with "${J}": ${Y.message}`,{sourcePath:$,targetPath:J,configName:Q,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};H4=class H4 extends D${code="ENV_VAR_ERROR";constructor($,J,Y,Q){super(`Failed to parse environment variable "${$}" with value "${J}" as ${Y}`,{envKey:$,envValue:J,expectedType:Y,configName:Q})}};DL=class DL extends D${code="FILE_SYSTEM_ERROR";constructor($,J,Y){super(`File system ${$} failed for "${J}": ${Y.message}`,{operation:$,path:J,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};NL=class NL extends D${code="TYPE_GENERATION_ERROR";constructor($,J,Y){super(`Failed to generate types from "${$}" to "${J}": ${Y.message}`,{configDir:$,outputPath:J,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};lQ=class lQ extends D${code="SCHEMA_VALIDATION_ERROR";constructor($,J,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:$,configName:Y,validationErrors:J,errorCount:J.length})}};SL=class SL extends D${code="BROWSER_CONFIG_ERROR";constructor($,J,Y,Q){super(`Failed to fetch configuration from "${$}": ${J} ${Y}`,{endpoint:$,status:J,statusText:Y,configName:Q})}};PL=class PL extends D${code="PLUGIN_ERROR";constructor($,J,Y){super(`Plugin "${$}" failed during ${J}: ${Y.message}`,{pluginName:$,operation:J,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};Q9={configNotFound($,J,Y){return new TL($,J,Y)},configLoad($,J,Y){return new cQ($,J,Y)},configValidation($,J,Y){return new wL($,J,Y)},configMerge($,J,Y,Q){return new RL($,J,Y,Q)},envVar($,J,Y,Q){return new H4($,J,Y,Q)},fileSystem($,J,Y){return new DL($,J,Y)},typeGeneration($,J,Y){return new NL($,J,Y)},schemaValidation($,J,Y){return new lQ($,J,Y)},browserConfig($,J,Y,Q){return new SL($,J,Y,Q)},plugin($,J,Y){return new PL($,J,Y)}};Wh=/^https?:\/\//;G2=new eQ("bunfig",{showTags:!0});ln=new hL;mn=H$(aQ.cwd(),"config"),pn=H$(aQ.cwd(),"src/generated");await X2();F0();a1();G9();F0();Hh=24*zh,rn=30*Hh;F0();a1();az();Z9();F0();tQ();mV();F0();F0();F0();F0();sz();vx();F0();F0();F0();F0();F0();F0();fx();F0();F0();F0();F0();F0();F0();F0();F0();F0();F0();F0();F0();F0();F0();nV();F0();a1();sz();a1();a1();a1();F0();a1();F0();F0();W9();W9();Z9();_h=new Set(["laravel","php","statamic","wordpress"]);mx();$4();$4();G9();await X2();a1();eV();await ex();G9();await X2();F0();a1();F0();await X2();G9();await X2();a1();Bh={php:"php.net",nginx:"nginx.org",composer:"getcomposer.org",mysql:"mysql.com",mariadb:"mariadb.com/server",postgres:"postgresql.org",redis:"redis.io",memcached:"memcached.org",meilisearch:"meilisearch.com",git:"git-scm.com",certbot:"certbot.eff.org",bun:"bun.sh",node:"nodejs.org",deno:"deno.land"};Lh={"opcache.enable":"1","opcache.enable_cli":"1","opcache.memory_consumption":"256","opcache.interned_strings_buffer":"16","opcache.max_accelerated_files":"20000","opcache.validate_timestamps":"0","opcache.revalidate_freq":"0","opcache.save_comments":"1","opcache.fast_shutdown":"1",realpath_cache_size:"4096K",realpath_cache_ttl:"600"};Mh=[80,443];cB=[["nginx",80],["phpFpm",9074],["mysql",3306],["postgres",5432],["redis",6379],["meilisearch",7700]];await X2();Xz={micro:"cpx11",small:"cx23",medium:"cx33",large:"cx43",xlarge:"cx53","2xlarge":"ccx33"};pQ=class pQ{name="hetzner";usesCloudFormation=!1;client;sshPrivateKeyPath;sshPublicKeyPath;sshUser;location;waitForBoot;bootWait;constructor($={}){this.client=$.client??new rL({apiToken:lh($.apiToken)}),this.sshPrivateKeyPath=oB($.sshPrivateKeyPath||process.env.HCLOUD_SSH_KEY||"~/.ssh/id_ed25519"),this.sshPublicKeyPath=oB($.sshPublicKeyPath||process.env.HCLOUD_SSH_PUBLIC_KEY||`${this.sshPrivateKeyPath}.pub`),this.sshUser=$.sshUser||process.env.HCLOUD_SSH_USER||"root",this.location=$.location||process.env.HCLOUD_LOCATION||"fsn1",this.waitForBoot=$.waitForBoot??!0,this.bootWait={sshIntervalMs:$.bootWait?.sshIntervalMs??5000,sshTimeoutMs:$.bootWait?.sshTimeoutMs??300000,cloudInitIntervalMs:$.bootWait?.cloudInitIntervalMs??5000,cloudInitTimeoutMs:$.bootWait?.cloudInitTimeoutMs??600000}}async provisionComputeInfrastructure($){let{config:J,environment:Y}=$,Q=J.project.slug,G=J.infrastructure?.compute;if(!G)throw Error("infrastructure.compute is required to provision Hetzner compute");let Z=SJ(J,Y),W=`${Q}-${Y}-app`,U=oh(G);if(U.dedicatedServices||U.appServers>1)return this.provisionFleet($,U);let z=await KQ(Z);if(z?.serverId){let k=await this.tryGetServer(z.serverId);if(k&&k.status!=="off")return this.outputsFromState(z,k)}let H=x2(Q,Y,"app"),_=await this.findExistingServer(Q,Y,W);if(_&&_.status!=="off"){let k={provider:"hetzner",stackName:Z,serverId:_.id,serverName:_.name,publicIp:_.public_net.ipv4?.ip,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await VQ(Z,k),this.outputsFromState(k,_)}let X=J.sites||{},F=this.collectUpstreamPorts(X),B=G.proxy?.engine==="rpx"?ah({proxy:G.proxy,config:nh(X,{proxy:G.proxy}),bunBin:G.runtime==="node"||G.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,V=mL(J),K=G.bakedImage===!0,L=RQ({runtime:V.runtime,runtimeVersion:V.runtimeVersion,systemPackages:G.systemPackages,database:J.infrastructure?.database,phpProvision:V.phpProvision,servicesProvision:V.servicesProvision,rpxProvision:B,baked:K}),E=Hz(L),A=Fz(G.size),j=G.image||J.hetzner?.image||"ubuntu-24.04",q=`${Q}-${Y}-app-fw`,{firewall:M}=await this.ensureFirewall(q,H,aB({allowSsh:G.allowSsh!==!1,sitePorts:F})),w=await this.ensureSshKey(Q,Y,H),{server:R,action:S}=await this.client.createServer({name:W,serverType:A,image:j,location:J.hetzner?.location||this.location,userData:E,labels:H,sshKeys:w?[w]:void 0,firewalls:[{firewall:M.id}]});await this.client.waitForAction(S.id);let N=await this.client.waitForServerRunning(R.id),C={provider:"hetzner",stackName:Z,serverId:N.id,serverName:N.name,firewallId:M.id,publicIp:N.public_net.ipv4?.ip,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};await VQ(Z,C);let x=N.public_net.ipv4?.ip;if(x&&this.waitForBoot)await this.waitForSshReady(x),await this.waitForCloudInit(x);return this.outputsFromState(C,N)}async provisionFleet($,J){let{config:Y,environment:Q}=$,G=Y.project.slug,Z=Y.infrastructure.compute,W=SJ(Y,Q),U=Fz(Z.size),z=Z.image||Y.hetzner?.image||"ubuntu-24.04",H=Y.hetzner?.location||this.location,_=Z.bakedImage===!0,X=await KQ(W);if(X?.loadBalancerId){let s=(await this.client.listLoadBalancers().catch(()=>[])).find((Y0)=>Y0.id===X.loadBalancerId);if(s)return{appPublicIp:s.public_net?.ipv4?.ip,loadBalancerIp:s.public_net?.ipv4?.ip,servicesPrivateIp:X.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}let F=await this.ensureSshKey(G,Q,x2(G,Q,"app")),B=`${G}-${Q}-net`,K=(await this.client.listNetworks().catch(()=>[])).find((a)=>a.name===B)??await this.client.createNetwork({name:B,labels:x2(G,Q,"app")}),{firewall:L}=await this.ensureFirewall(`${G}-${Q}-app-fw`,x2(G,Q,"app"),aB({allowSsh:!0,sitePorts:[]})),{firewall:E}=await this.ensureFirewall(`${G}-${Q}-services-fw`,x2(G,Q,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[K.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[K.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[K.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[K.ip_range]}]),A=[...gL(Z.managedServices??{mysql:!0,redis:!0},{bindPrivate:!0}),...uL(Y.infrastructure?.appDatabase,Z.managedServices??{mysql:!0}),...bz(!0),...hz(!0),...yz(Z.sshKeys)],j=Hz(RQ({runtime:"php",servicesProvision:A,baked:_})),q=await this.client.listServers().catch(()=>[]),M=[],w=q.find((a)=>e8(a.labels,G,Q,"services"));if(!w){let{server:a,action:s}=await this.client.createServer({name:`${G}-${Q}-services`,serverType:Fz(typeof Z.servicesServer==="object"?Z.servicesServer.size:Z.size),image:z,location:H,userData:j,labels:x2(G,Q,"services"),sshKeys:F?[F]:void 0,firewalls:[{firewall:E.id}],networks:[K.id]});await this.client.waitForAction(s.id),w=await this.client.waitForServerRunning(a.id),M.push(a.id)}let R=w.id,S=w.private_net?.[0]?.ip??(await this.client.getServer(R)).private_net?.[0]?.ip,N=[...bz(!0),...hz(!0),...yz(Z.sshKeys),...cL(Y.notifications)],C=dL({versions:Z.php?.versions,default:Z.php?.default,extensions:Z.php?.extensions,installNginx:Z.webServer!=="rpx",optimizeForProduction:Z.php?.optimizeForProduction,ini:Z.php?.ini}),x=Hz(RQ({runtime:"php",phpProvision:C,servicesProvision:N,baked:_})),k=q.filter((a)=>e8(a.labels,G,Q,"app")),b=k.map((a)=>a.id);if(k.length>J.appServers)for(let a of k.slice(J.appServers))await this.client.deleteServer(a.id).catch(()=>{}),b.splice(b.indexOf(a.id),1);for(let a=k.length;a<J.appServers;a++){let{server:s,action:Y0}=await this.client.createServer({name:`${G}-${Q}-app-${a+1}`,serverType:U,image:z,location:H,userData:x,labels:x2(G,Q,"app"),sshKeys:F?[F]:void 0,firewalls:[{firewall:L.id}],networks:[K.id]});await this.client.waitForAction(Y0.id),b.push(s.id),M.push(s.id)}if(this.waitForBoot&&M.length>0)await Promise.all(M.map(async(a)=>{let Y0=(await this.client.waitForServerRunning(a)).public_net.ipv4?.ip;if(Y0)await this.waitForSshReady(Y0),await this.waitForCloudInit(Y0)}));let m=`${G}-${Q}-lb`,h,u;if(J.loadBalancer){let s=(await this.client.listLoadBalancers().catch(()=>[])).find((Y0)=>Y0.name===m)??await this.client.createLoadBalancer({name:m,location:H,network:K.id,labels:x2(G,Q,"lb"),labelSelector:`ts-cloud/project=${G},ts-cloud/environment=${Q},ts-cloud/role=app`,services:[{listenPort:80,destinationPort:80},{listenPort:443,destinationPort:443}]});u=s.id,h=s.public_net?.ipv4?.ip}let $0=h??(await this.client.getServer(b[0]).catch(()=>{return}))?.public_net.ipv4?.ip,J0={provider:"hetzner",stackName:W,networkId:K.id,loadBalancerId:u,servicesServerId:R,servicesPrivateIp:S,publicIp:$0,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await VQ(W,J0),{appPublicIp:$0,loadBalancerIp:h,servicesPrivateIp:S,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async destroyCompute($){let{config:J,environment:Y}=$,Q=J.project.slug,G=SJ(J,Y),Z=await KQ(G),W=[],U=`${Q}-${Y}-lb`,H=(await this.client.listLoadBalancers().catch(()=>[])).find((L)=>L.name===U);if(H)try{await this.client.deleteLoadBalancer(H.id),W.push(`load balancer ${U}`)}catch{}let _=await this.client.listServers().catch(()=>[]),X=new Set;for(let L of _)if(e8(L.labels,Q,Y,"app")||e8(L.labels,Q,Y,"services"))X.add(L.id);if(Z?.serverId)X.add(Z.serverId);if(Z?.servicesServerId)X.add(Z.servicesServerId);for(let L of X)try{await this.client.deleteServer(L),W.push(`server ${L}`)}catch{}let F=await this.client.listFirewalls().catch(()=>[]);for(let L of[`${Q}-${Y}-app-fw`,`${Q}-${Y}-services-fw`]){let E=F.find((A)=>A.name===L);if(!E)continue;for(let A=0;A<12;A++)try{await this.client.deleteFirewall(E.id),W.push(`firewall ${L}`);break}catch{await this.sleep(3000)}}let B=`${Q}-${Y}-net`,K=(await this.client.listNetworks().catch(()=>[])).find((L)=>L.name===B);if(K)for(let L=0;L<12;L++)try{await this.client.deleteNetwork(K.id),W.push(`network ${B}`);break}catch{await this.sleep(3000)}return await VQ(G,{provider:"hetzner",stackName:G}).catch(()=>{}),{destroyed:W}}async getComputeOutputs($){let J=SJ($.config,$.environment),Y=await KQ(J);if(Y?.serverId){let Z=await this.client.getServer(Y.serverId);return this.outputsFromState(Y,Z)}if(Y?.loadBalancerId||Y?.servicesPrivateIp)return this.outputsFromState(Y);let G=(await this.findComputeTargets({slug:$.config.project.slug,environment:$.environment,role:"app"}))[0];return{deployStoragePath:"/var/ts-cloud/staging",appInstanceId:G?.id,appPublicIp:G?.publicIp,sshUser:this.sshUser}}async uploadRelease($){let J=$.targets?.length?$.targets:await this.findComputeTargets({slug:$.config.project.slug,environment:$.environment,role:"app"});if(J.length===0)throw Error("No Hetzner compute targets found for release upload");let Y=`/var/ts-cloud/staging/${$.remoteKey.split("/").pop()}`;for(let Q of J){if(!Q.publicIp)throw Error(`Target ${Q.id} has no public IP for SCP upload`);this.scpToHost(Q.publicIp,$.localPath,Y)}return{artifactRef:Y}}async findComputeTargets($){return(await this.client.listServers()).filter((Y)=>e8(Y.labels,$.slug,$.environment,$.role||"app")).map((Y)=>({id:String(Y.id),name:Y.name,publicIp:Y.public_net.ipv4?.ip,privateIp:Y.private_net?.[0]?.ip,status:Y.status}))}async runRemoteDeploy($){if($.targets.length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets provided"};let J=$.commands.join(`
|
|
13640
13640
|
`),Y=[];for(let G of $.targets){if(!G.publicIp){Y.push({instanceId:G.id,status:"Failed",error:"Missing public IP"});continue}try{let Z=this.sshExec(G.publicIp,J);Y.push({instanceId:G.id,status:"Success",output:Z})}catch(Z){Y.push({instanceId:G.id,status:"Failed",error:Z.message})}}let Q=Y.every((G)=>G.status==="Success");return{success:Q,instanceCount:$.targets.length,perInstance:Y,error:Q?void 0:"One or more SSH deploy commands failed"}}async ensureSshKey($,J,Y){if(!fh(this.sshPublicKeyPath))throw Error(`SSH public key not found at ${this.sshPublicKeyPath}. ts-cloud deploys to Hetzner over SSH and needs a public key to authorize on the server. Generate one (\`ssh-keygen -t ed25519\`) or set hetzner.sshPrivateKeyPath / HCLOUD_SSH_PUBLIC_KEY.`);let Q=gh(this.sshPublicKeyPath,"utf8").trim(),G=nB(Q),W=(await this.client.listSshKeys()).find((z)=>nB(z.public_key)===G);if(W)return W.id;return(await this.client.createSshKey({name:`${$}-${J}-deploy`,publicKey:Q,labels:Y})).id}async tryGetServer($){try{return await this.client.getServer($)}catch{return null}}async findExistingServer($,J,Y){return(await this.client.listServers()).find((G)=>e8(G.labels,$,J,"app")||G.name===Y)}async ensureFirewall($,J,Y){let G=(await this.client.listFirewalls()).find((W)=>W.name===$);if(G)return await this.client.setFirewallRules(G.id,Y),{firewall:G};let{firewall:Z}=await this.client.createFirewall({name:$,labels:J,rules:Y});return{firewall:Z}}collectUpstreamPorts($){let J=new Set;for(let Y of Object.values($))if(typeof Y.port==="number")J.add(Y.port);return[...J].filter((Y)=>![80,443].includes(Y))}async sleep($){await new Promise((J)=>setTimeout(J,$))}async waitForSshReady($){let{sshIntervalMs:J,sshTimeoutMs:Y}=this.bootWait,Q=Date.now(),G;while(Date.now()-Q<Y)try{zz(`ssh ${this.sshBaseArgs($,["-o","ConnectTimeout=5"]).map((Z)=>`"${Z.replace(/"/g,"\\\"")}"`).join(" ")} true`,{stdio:"pipe",maxBuffer:Oz});return}catch(Z){G=Z,await this.sleep(J)}throw Error(`Timed out waiting for SSH on ${$} after ${Y}ms: ${G?.message??"unknown error"}`)}async waitForCloudInit($){let{cloudInitIntervalMs:J,cloudInitTimeoutMs:Y}=this.bootWait,Q=Date.now();while(Date.now()-Q<Y){try{let G=this.sshExec($,"cloud-init status --long 2>/dev/null || cloud-init status 2>/dev/null || echo status:\\ done");if(/status:\s*done/.test(G))return;if(/status:\s*error/.test(G))throw Error(`cloud-init reported an error on ${$}:
|
|
13641
|
-
${G}`)}catch(G){if(G instanceof Error&&/cloud-init reported an error/.test(G.message))throw G}await this.sleep(J)}throw Error(`Timed out waiting for cloud-init to finish on ${$} after ${Y}ms`)}outputsFromState($,J){return{deployStoragePath:$.deployStoragePath||"/var/ts-cloud/staging",appInstanceId:$.serverId?String($.serverId):void 0,appPublicIp:J?.public_net.ipv4?.ip||$.publicIp,sshUser:$.sshUser||this.sshUser,servicesPrivateIp:$.servicesPrivateIp}}static SSH_HOST_KEY_OPTS=["-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR"];sshBaseArgs($,J=[]){return["-i",this.sshPrivateKeyPath,...pQ.SSH_HOST_KEY_OPTS,"-o","BatchMode=yes",...J,`${this.sshUser}@${$}`]}scpToHost($,J,Y){zz(["scp","-i",this.sshPrivateKeyPath,...pQ.SSH_HOST_KEY_OPTS,"-o","BatchMode=yes",J,`${this.sshUser}@${$}:${Y}`].map((Q)=>`"${Q.replace(/"/g,"\\\"")}"`).join(" "),{stdio:"pipe",maxBuffer:Oz})}sshExec($,J){let Y=J.replace(/'/g,"'\\''");return zz(`ssh ${this.sshBaseArgs($).map((Q)=>`"${Q.replace(/"/g,"\\\"")}"`).join(" ")} '${Y}'`,{encoding:"utf8",stdio:["pipe","pipe","pipe"],maxBuffer:Oz})}};Ji=new aL;await X2();Yi=`eval "$(cd ${_8} && pantry env 2>/dev/null)"`;W9();X2()});var eL={};n0(eL,{resolveUiSource:()=>sL,ensureManagementDashboard:()=>Wy});import{existsSync as $5}from"node:fs";import{dirname as Yy,join as f2}from"node:path";import{fileURLToPath as Qy}from"node:url";function Zy($){return $!=null&&$!==""&&$!=="0"&&$.toLowerCase()!=="false"}function sL($){if($5(f2($,"ui","pages"))||$5(f2($,"ui","package.json")))return{uiRoot:"ui/dist",build:"cd ui && bun install && bun run build"};let J=Yy(Qy(import.meta.url)),Y=[f2(J,"ui"),f2(J,"..","ui"),f2(J,"..","..","ui"),f2(J,"..","dist","ui")];for(let Q of Y)if($5(f2(Q,"index.html"))||$5(f2(Q,"serverless.html")))return{uiRoot:Q,build:!1};return null}function Wy($,J={}){let Y=J.logger??Gy,Q=J.cwd??process.cwd();if(Zy(process.env.TS_CLOUD_UI_DISABLE))return Y.info("Management dashboard: skipped (TS_CLOUD_UI_DISABLE set)."),$;if(uz($))return $;let G=sL(Q);if(!G)return Y.info("Management dashboard: UI not found (no local ui/ or packaged dist/ui) — skipping auto-deploy."),$;let Z=process.env.TS_CLOUD_UI_PASSWORD?.trim()||void 0,W=$.environments&&Object.keys($.environments)[0],U=_K($,W??"production",{uiRoot:G.uiRoot,build:G.build,domain:process.env.TS_CLOUD_UI_DOMAIN?.trim()||void 0,username:process.env.TS_CLOUD_UI_USERNAME?.trim()||void 0,password:Z,realm:process.env.TS_CLOUD_UI_REALM?.trim()||void 0});if(!U)return Y.info("Management dashboard: no domain resolved (set TS_CLOUD_UI_DOMAIN or configure a site domain) — skipping."),$;return $.sites={...$.sites??{},[U.name]:U.site},Y.info(`Management dashboard → https://${U.site.domain} (${Z?"htpasswd-protected":"NO AUTH — set TS_CLOUD_UI_PASSWORD"})`),$}var Gy;var $A=Z0(async()=>{await oL();Gy={info:()=>{},warn:()=>{}}});function Uy($){return`'${$.split("'").join("'\\''")}'`}function JA($){let J=$.user||"root",Y=$.script.join(`
|
|
13641
|
+
${G}`)}catch(G){if(G instanceof Error&&/cloud-init reported an error/.test(G.message))throw G}await this.sleep(J)}throw Error(`Timed out waiting for cloud-init to finish on ${$} after ${Y}ms`)}outputsFromState($,J){return{deployStoragePath:$.deployStoragePath||"/var/ts-cloud/staging",appInstanceId:$.serverId?String($.serverId):void 0,appPublicIp:J?.public_net.ipv4?.ip||$.publicIp,sshUser:$.sshUser||this.sshUser,servicesPrivateIp:$.servicesPrivateIp}}static SSH_HOST_KEY_OPTS=["-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR"];sshBaseArgs($,J=[]){return["-i",this.sshPrivateKeyPath,...pQ.SSH_HOST_KEY_OPTS,"-o","BatchMode=yes",...J,`${this.sshUser}@${$}`]}scpToHost($,J,Y){zz(["scp","-i",this.sshPrivateKeyPath,...pQ.SSH_HOST_KEY_OPTS,"-o","BatchMode=yes",J,`${this.sshUser}@${$}:${Y}`].map((Q)=>`"${Q.replace(/"/g,"\\\"")}"`).join(" "),{stdio:"pipe",maxBuffer:Oz})}sshExec($,J){let Y=J.replace(/'/g,"'\\''");return zz(`ssh ${this.sshBaseArgs($).map((Q)=>`"${Q.replace(/"/g,"\\\"")}"`).join(" ")} '${Y}'`,{encoding:"utf8",stdio:["pipe","pipe","pipe"],maxBuffer:Oz})}};Ji=new aL;await X2();Yi=`eval "$(cd ${_8} && pantry env 2>/dev/null)"`;W9();X2()});var eL={};n0(eL,{resolveUiSource:()=>sL,ensureManagementDashboard:()=>Wy});import{existsSync as $5}from"node:fs";import{dirname as Yy,join as f2}from"node:path";import{fileURLToPath as Qy}from"node:url";function Zy($){return $!=null&&$!==""&&$!=="0"&&$.toLowerCase()!=="false"}function sL($){if($5(f2($,"packages","ui","pages"))||$5(f2($,"packages","ui","package.json")))return{uiRoot:"packages/ui/dist",build:"cd packages/ui && bun install && bun run build"};let J=Yy(Qy(import.meta.url)),Y=[f2(J,"ui"),f2(J,"..","ui"),f2(J,"..","..","ui"),f2(J,"..","dist","ui")];for(let Q of Y)if($5(f2(Q,"index.html"))||$5(f2(Q,"serverless.html")))return{uiRoot:Q,build:!1};return null}function Wy($,J={}){let Y=J.logger??Gy,Q=J.cwd??process.cwd();if(Zy(process.env.TS_CLOUD_UI_DISABLE))return Y.info("Management dashboard: skipped (TS_CLOUD_UI_DISABLE set)."),$;if(uz($))return $;let G=sL(Q);if(!G)return Y.info("Management dashboard: UI not found (no local ui/ or packaged dist/ui) — skipping auto-deploy."),$;let Z=process.env.TS_CLOUD_UI_PASSWORD?.trim()||void 0,W=$.environments&&Object.keys($.environments)[0],U=_K($,W??"production",{uiRoot:G.uiRoot,build:G.build,domain:process.env.TS_CLOUD_UI_DOMAIN?.trim()||void 0,username:process.env.TS_CLOUD_UI_USERNAME?.trim()||void 0,password:Z,realm:process.env.TS_CLOUD_UI_REALM?.trim()||void 0});if(!U)return Y.info("Management dashboard: no domain resolved (set TS_CLOUD_UI_DOMAIN or configure a site domain) — skipping."),$;return $.sites={...$.sites??{},[U.name]:U.site},Y.info(`Management dashboard → https://${U.site.domain} (${Z?"htpasswd-protected":"NO AUTH — set TS_CLOUD_UI_PASSWORD"})`),$}var Gy;var $A=Z0(async()=>{await oL();Gy={info:()=>{},warn:()=>{}}});function Uy($){return`'${$.split("'").join("'\\''")}'`}function JA($){let J=$.user||"root",Y=$.script.join(`
|
|
13642
13642
|
`),Q=J==="root"?'bash -l "$TS_CLOUD_RECIPE"':`runuser -l ${Uy(J)} -c "bash $TS_CLOUD_RECIPE"`;return["set -uo pipefail",`echo "__TS_CLOUD_RECIPE_BEGIN__ ${$.name} (user=${J})"`,"TS_CLOUD_RECIPE=$(mktemp)",`cat > "$TS_CLOUD_RECIPE" <<'TS_CLOUD_RECIPE_EOF'`,Y,"TS_CLOUD_RECIPE_EOF",'chmod +r "$TS_CLOUD_RECIPE"',Q,"TS_CLOUD_RC=$?",'rm -f "$TS_CLOUD_RECIPE"',`echo "__TS_CLOUD_RECIPE_END__ ${$.name} exit=$TS_CLOUD_RC"`,"exit $TS_CLOUD_RC"]}var fJ={};n0(fJ,{runComputeRecipe:()=>_y,rollbackComputeSite:()=>zy,restoreDatabaseBackup:()=>Xy,getComputeDeployHistory:()=>Hy});async function J5($){return await $.driver.findComputeTargets({slug:$.slug,environment:$.environment,role:$.role||"app"})}async function zy($,J){let Y=$.logger||X4,Q=await J5($);if(Q.length===0)return{success:!1,error:`No '${$.role||"app"}' servers found for ${$.slug}/${$.environment}.`};let G=`/var/www/${J.siteName}`,Z=i6(G,J.to||"unused"),W=["set -uo pipefail",...sF(Z,J.to?{to:J.to}:{}),`(cd ${M$} && pantry restart php-fpm) 2>/dev/null || true`,`(cd ${Z.current} && eval "$(cd ${M$} && pantry env 2>/dev/null)" && php artisan queue:restart) 2>/dev/null || true`];Y.step(`Rolling back ${J.siteName}${J.to?` to ${J.to}`:" to the previous release"} on ${Q.length} server(s)...`);let U=await $.driver.runRemoteDeploy({targets:Q,commands:W,comment:`ts-cloud rollback ${$.slug}/${J.siteName}`,tags:{Project:$.slug,Environment:$.environment,Role:$.role||"app"}});if(!U.success)Y.error(`Rollback failed: ${U.error||"unknown error"}`);else Y.success(`Rolled back ${J.siteName}.`);return{success:U.success,error:U.error,perInstance:U.perInstance}}async function Hy($,J){let Y=await J5($);if(Y.length===0)return{success:!1,error:`No '${$.role||"app"}' servers found for ${$.slug}/${$.environment}.`};let Q=PU(`/var/www/${J.siteName}`),G=Math.max(1,J.limit??20),Z=[`[ -f ${Q} ] && tail -n ${G} ${Q} || echo "no deploy history for ${J.siteName}"`],W=await $.driver.runRemoteDeploy({targets:Y,commands:Z,comment:`ts-cloud deploy:history ${$.slug}/${J.siteName}`,tags:{Project:$.slug,Environment:$.environment,Role:$.role||"app"}});return{success:W.success,error:W.error,perInstance:W.perInstance}}async function _y($,J){let Y=$.logger||X4,Q=await J5($);if(Q.length===0)return{success:!1,error:`No '${$.role||"app"}' servers found for ${$.slug}/${$.environment}.`};Y.step(`Running recipe '${J.name}' as ${J.user||"root"} on ${Q.length} server(s)...`);let G=await $.driver.runRemoteDeploy({targets:Q,commands:JA({name:J.name,script:J.script,user:J.user}),comment:`ts-cloud recipe ${J.name}`,tags:{Project:$.slug,Environment:$.environment,Role:$.role||"app"}});if(!G.success)Y.error(`Recipe '${J.name}' failed: ${G.error||"unknown error"}`);else Y.success(`Recipe '${J.name}' completed.`);return{success:G.success,error:G.error,perInstance:G.perInstance}}async function Xy($,J){let Y=$.logger||X4;if(!J.database?.name)return{success:!1,error:"No appDatabase configured to restore."};let Q=await J5($);if(Q.length===0)return{success:!1,error:`No '${$.role||"app"}' servers found for ${$.slug}/${$.environment}.`};Y.step(`Restoring database '${J.database.name}'${J.from?` from ${J.from}`:" from the latest backup"} on ${Q.length} server(s)...`);let G=await $.driver.runRemoteDeploy({targets:Q,commands:qF(J.database,{from:J.from}),comment:`ts-cloud db:restore ${$.slug}/${J.database.name}`,tags:{Project:$.slug,Environment:$.environment,Role:$.role||"app"}});if(!G.success)Y.error(`Restore failed: ${G.error||"unknown error"}`);else Y.success(`Restored ${J.database.name}.`);return{success:G.success,error:G.error,perInstance:G.perInstance}}var X4;var gJ=Z0(()=>{P2();CU();X4={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}}});var YA={};n0(YA,{buildQuickDeployCi:()=>Oy});function Fy($){let J=$.sites||{};for(let Y of Object.values(J))if(Y?.repository?.url)return{provider:Y.repository.provider,branch:Y.repository.branch};return}function Oy($,J="production"){let Y=Fy($),Q=Y?.provider;if(Q!=="github"&&Q!=="gitlab"&&Q!=="bitbucket")return null;let G=Y?.branch||"main",Z=`bunx --bun ts-cloud deploy ${J}`;if(Q==="github")return{provider:Q,branch:G,path:".github/workflows/deploy.yml",content:`name: Deploy
|
|
13643
13643
|
on:
|
|
13644
13644
|
push:
|
|
@@ -13716,7 +13716,7 @@ Run \`${this.name??"cli"} --help\` for usage.`;O2.stderr.write(`${Z}${G}${W}
|
|
|
13716
13716
|
`).length-1;this.output.write(d$.move(-999,$*-1))}render(){let $=o4(this._render(this)??"",a4.stdout.columns,{hard:!0,trim:!1});if($===this._prevFrame)return;if(this.state==="initial")this.output.write(d$.hide);else{let J=OE(this._prevFrame,$);if(this.restoreCursor(),J&&J?.length===1){let Y=J[0];this.output.write(d$.move(0,Y)),this.output.write(H5.lines(1));let Q=$.split(`
|
|
13717
13717
|
`);this.output.write(Q[Y]),this._prevFrame=$,this.output.write(d$.move(0,Q.length-Y-1));return}if(J&&J?.length>1){let Y=J[0];this.output.write(d$.move(0,Y)),this.output.write(H5.down());let G=$.split(`
|
|
13718
13718
|
`).slice(Y);this.output.write(G.join(`
|
|
13719
|
-
`)),this._prevFrame=$;return}this.output.write(H5.down())}if(this.output.write($),this.state==="initial")this.state="active";this._prevFrame=$}}function EE($,J){if($===void 0)return 0;if(J.length===0)return 0;let Q=J.findIndex((G)=>G.value===$);return Q!==-1?Q:0}function jE($,J){return(J.label??String(J.value)).toLowerCase().includes($.toLowerCase())}function qE($,J){if(!J)return;if($)return J;return J[0]}class ME extends K5{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#Y="";#Q;#J;get cursor(){return this.#$}get userInputWithCursor(){if(!this.userInput)return tJ.inverse(tJ.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let $=this.userInput.slice(0,this._cursor),[J,...Y]=this.userInput.slice(this._cursor);return`${$}${tJ.inverse(J)}${Y.join("")}`}get options(){if(typeof this.#J==="function")return this.#J();return this.#J}constructor($){super($);this.#J=$.options;let J=this.options;this.filteredOptions=[...J],this.multiple=$.multiple===!0,this.#Q=$.filter??jE;let Y;if($.initialValue&&Array.isArray($.initialValue))if(this.multiple)Y=$.initialValue;else Y=$.initialValue.slice(0,1);else if(!this.multiple&&this.options.length>0)Y=[this.options[0].value];if(Y)for(let Q of Y){let G=J.findIndex((Z)=>Z.value===Q);if(G!==-1)this.toggleSelected(Q),this.#$=G}this.focusedValue=this.options[this.#$]?.value,this.on("key",(Q,G)=>this.#G(Q,G)),this.on("userInput",(Q)=>this.#Z(Q))}_isActionKey($,J){return $==="\t"||this.multiple&&this.isNavigating&&J.name==="space"&&$!==void 0&&$!==""}#G($,J){let Y=J.name==="up",Q=J.name==="down",G=J.name==="return";if(Y||Q){if(this.#$=Math.max(0,Math.min(this.#$+(Y?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if(G)this.value=qE(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&(J.name==="tab"||this.isNavigating&&J.name==="space"))this.toggleSelected(this.focusedValue);else this.isNavigating=!1;else{if(this.focusedValue)this.selectedValues=[this.focusedValue];this.isNavigating=!1}}deselectAll(){this.selectedValues=[]}toggleSelected($){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes($))this.selectedValues=this.selectedValues.filter((J)=>J!==$);else this.selectedValues=[...this.selectedValues,$];else this.selectedValues=[$]}#Z($){if($!==this.#Y){this.#Y=$;let J=this.options;if($)this.filteredOptions=J.filter((Y)=>this.#Q($,Y));else this.filteredOptions=[...J];if(this.#$=EE(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class TE extends K5{options;cursor=0;#$;getGroupItems($){return this.options.filter((J)=>J.group===$)}isGroupSelected($){let J=this.getGroupItems($),Y=this.value;if(Y===void 0)return!1;return J.every((Q)=>Y.includes(Q.value))}toggleValue(){let $=this.options[this.cursor];if(this.value===void 0)this.value=[];if($.group===!0){let J=$.value,Y=this.getGroupItems(J);if(this.isGroupSelected(J))this.value=this.value.filter((Q)=>Y.findIndex((G)=>G.value===Q)===-1);else this.value=[...this.value,...Y.map((Q)=>Q.value)];this.value=Array.from(new Set(this.value))}else{let J=this.value.includes($.value);this.value=J?this.value.filter((Y)=>Y!==$.value):[...this.value,$.value]}}constructor($){super($,!1);let{options:J}=$;this.#$=$.selectableGroups!==!1,this.options=Object.entries(J).flatMap(([Y,Q])=>[{value:Y,group:!0,label:Y},...Q.map((G)=>({...G,group:Y}))]),this.value=[...$.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:Y})=>Y===$.cursorAt),this.#$?0:1),this.on("cursor",(Y)=>{switch(Y){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let Q=this.options[this.cursor]?.group===!0;if(!this.#$&&Q)this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let Q=this.options[this.cursor]?.group===!0;if(!this.#$&&Q)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var wE=xA();var f0=($,J)=>wE?$:J,Vv=f0("◆","*"),Lv=f0("■","x"),Av=f0("▲","x"),Ev=f0("◇","o"),jv=f0("┌","T"),RE=f0("│","|"),qv=f0("└","—"),Mv=f0("●",">"),Tv=f0("○"," "),wv=f0("◻","[•]"),Rv=f0("◼","[+]"),Dv=f0("◻","[ ]"),Nv=f0("▪","•"),Sv=f0("─","-"),Pv=f0("╮","+"),Cv=f0("├","+"),Iv=f0("╯","+"),xv=f0("●","•"),kv=f0("◆","*"),bv=f0("▲","!"),hv=f0("■","x");var yv={light:f0("─","-"),heavy:f0("━","="),block:f0("█","#")};function DE(){return`${tJ.gray(RE)} `}var vv=DE();var V5="0.5.
|
|
13719
|
+
`)),this._prevFrame=$;return}this.output.write(H5.down())}if(this.output.write($),this.state==="initial")this.state="active";this._prevFrame=$}}function EE($,J){if($===void 0)return 0;if(J.length===0)return 0;let Q=J.findIndex((G)=>G.value===$);return Q!==-1?Q:0}function jE($,J){return(J.label??String(J.value)).toLowerCase().includes($.toLowerCase())}function qE($,J){if(!J)return;if($)return J;return J[0]}class ME extends K5{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#Y="";#Q;#J;get cursor(){return this.#$}get userInputWithCursor(){if(!this.userInput)return tJ.inverse(tJ.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let $=this.userInput.slice(0,this._cursor),[J,...Y]=this.userInput.slice(this._cursor);return`${$}${tJ.inverse(J)}${Y.join("")}`}get options(){if(typeof this.#J==="function")return this.#J();return this.#J}constructor($){super($);this.#J=$.options;let J=this.options;this.filteredOptions=[...J],this.multiple=$.multiple===!0,this.#Q=$.filter??jE;let Y;if($.initialValue&&Array.isArray($.initialValue))if(this.multiple)Y=$.initialValue;else Y=$.initialValue.slice(0,1);else if(!this.multiple&&this.options.length>0)Y=[this.options[0].value];if(Y)for(let Q of Y){let G=J.findIndex((Z)=>Z.value===Q);if(G!==-1)this.toggleSelected(Q),this.#$=G}this.focusedValue=this.options[this.#$]?.value,this.on("key",(Q,G)=>this.#G(Q,G)),this.on("userInput",(Q)=>this.#Z(Q))}_isActionKey($,J){return $==="\t"||this.multiple&&this.isNavigating&&J.name==="space"&&$!==void 0&&$!==""}#G($,J){let Y=J.name==="up",Q=J.name==="down",G=J.name==="return";if(Y||Q){if(this.#$=Math.max(0,Math.min(this.#$+(Y?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if(G)this.value=qE(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&(J.name==="tab"||this.isNavigating&&J.name==="space"))this.toggleSelected(this.focusedValue);else this.isNavigating=!1;else{if(this.focusedValue)this.selectedValues=[this.focusedValue];this.isNavigating=!1}}deselectAll(){this.selectedValues=[]}toggleSelected($){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes($))this.selectedValues=this.selectedValues.filter((J)=>J!==$);else this.selectedValues=[...this.selectedValues,$];else this.selectedValues=[$]}#Z($){if($!==this.#Y){this.#Y=$;let J=this.options;if($)this.filteredOptions=J.filter((Y)=>this.#Q($,Y));else this.filteredOptions=[...J];if(this.#$=EE(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class TE extends K5{options;cursor=0;#$;getGroupItems($){return this.options.filter((J)=>J.group===$)}isGroupSelected($){let J=this.getGroupItems($),Y=this.value;if(Y===void 0)return!1;return J.every((Q)=>Y.includes(Q.value))}toggleValue(){let $=this.options[this.cursor];if(this.value===void 0)this.value=[];if($.group===!0){let J=$.value,Y=this.getGroupItems(J);if(this.isGroupSelected(J))this.value=this.value.filter((Q)=>Y.findIndex((G)=>G.value===Q)===-1);else this.value=[...this.value,...Y.map((Q)=>Q.value)];this.value=Array.from(new Set(this.value))}else{let J=this.value.includes($.value);this.value=J?this.value.filter((Y)=>Y!==$.value):[...this.value,$.value]}}constructor($){super($,!1);let{options:J}=$;this.#$=$.selectableGroups!==!1,this.options=Object.entries(J).flatMap(([Y,Q])=>[{value:Y,group:!0,label:Y},...Q.map((G)=>({...G,group:Y}))]),this.value=[...$.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:Y})=>Y===$.cursorAt),this.#$?0:1),this.on("cursor",(Y)=>{switch(Y){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let Q=this.options[this.cursor]?.group===!0;if(!this.#$&&Q)this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let Q=this.options[this.cursor]?.group===!0;if(!this.#$&&Q)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var wE=xA();var f0=($,J)=>wE?$:J,Vv=f0("◆","*"),Lv=f0("■","x"),Av=f0("▲","x"),Ev=f0("◇","o"),jv=f0("┌","T"),RE=f0("│","|"),qv=f0("└","—"),Mv=f0("●",">"),Tv=f0("○"," "),wv=f0("◻","[•]"),Rv=f0("◼","[+]"),Dv=f0("◻","[ ]"),Nv=f0("▪","•"),Sv=f0("─","-"),Pv=f0("╮","+"),Cv=f0("├","+"),Iv=f0("╯","+"),xv=f0("●","•"),kv=f0("◆","*"),bv=f0("▲","!"),hv=f0("■","x");var yv={light:f0("─","-"),heavy:f0("━","="),block:f0("█","#")};function DE(){return`${tJ.gray(RE)} `}var vv=DE();var V5="0.5.19";B0();import{existsSync as D5}from"node:fs";import{mkdir as vE,writeFile as K7}from"node:fs/promises";function N5($){$.command("init","Initialize a new ts-cloud project").option("--mode <mode>","Deployment mode: server, serverless, or hybrid").option("--name <name>","Project name").option("--region <region>","AWS Region").action(async(J)=>{if(P("Initializing ts-cloud Project"),D5("cloud.config.ts")){if(!await p("cloud.config.ts already exists. Overwrite?",!1)){O("Initialization cancelled");return}}let Y=J?.name||await k0("Project name","my-app"),Q=J?.mode||await sJ("Select deployment mode",["serverless","server","hybrid"]),G=J?.region||await sJ("Select AWS region",["us-east-1","us-west-2","eu-west-1","eu-central-1","ap-southeast-1"]),Z=new I("Creating configuration file...");Z.start();let W=`import { defineConfig } from '@ts-cloud/core'
|
|
13720
13720
|
|
|
13721
13721
|
export default defineConfig({
|
|
13722
13722
|
project: {
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* this to `TSCLOUD_DASHBOARD_DATA` and the pages' `<script server>` blocks read
|
|
5
5
|
* it at build time (falling back to representative sample data per-field/per-page
|
|
6
6
|
* when a value isn't present). Every gather is wrapped so one failing source only
|
|
7
|
-
* drops its own slice — the rest still render live. See `ui/pages/*`.
|
|
7
|
+
* drops its own slice — the rest still render live. See `packages/ui/pages/*`.
|
|
8
8
|
*/
|
|
9
9
|
import type { CloudConfig, EnvironmentType } from '@ts-cloud/core';
|
|
10
10
|
/** A loosely-typed bag — the pages read named slices, missing ones fall back. */
|
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
* Auto-deploy of the ts-cloud management dashboard (the `@ts-cloud/ui` stx app)
|
|
3
3
|
* on every server provision/deploy.
|
|
4
4
|
*
|
|
5
|
-
* Resolves the UI directory (the repo's local `ui/`, else the prebuilt
|
|
6
|
-
* ships inside the installed package at `dist/ui`), derives a `dashboard.<apex>`
|
|
5
|
+
* Resolves the UI directory (the repo's local `packages/ui/`, else the prebuilt
|
|
6
|
+
* UI that ships inside the installed package at `dist/ui`), derives a `dashboard.<apex>`
|
|
7
7
|
* host, and injects it into `config.sites` as a server-static site. It is served
|
|
8
8
|
* behind htpasswd ONLY when `TS_CLOUD_UI_PASSWORD` is set; when it is not, the
|
|
9
9
|
* dashboard is served without auth (no password is invented).
|
|
@@ -21,8 +21,8 @@ export interface EnsureDashboardLogger {
|
|
|
21
21
|
warn: (msg: string) => void;
|
|
22
22
|
}
|
|
23
23
|
/**
|
|
24
|
-
* Resolve the UI source to ship. Prefers the repo's local `ui/` (built
|
|
25
|
-
* deploy machine), then the prebuilt UI bundled in the installed package.
|
|
24
|
+
* Resolve the UI source to ship. Prefers the repo's local `packages/ui/` (built
|
|
25
|
+
* on the deploy machine), then the prebuilt UI bundled in the installed package.
|
|
26
26
|
* Returns `{ uiRoot, build }` or null when no UI is available.
|
|
27
27
|
*/
|
|
28
28
|
export declare function resolveUiSource(cwd: string): {
|
package/dist/index.js
CHANGED
|
@@ -7642,11 +7642,11 @@ function createServerlessLaravelPreset(options) {
|
|
|
7642
7642
|
}
|
|
7643
7643
|
function createDashboardSite(options) {
|
|
7644
7644
|
return {
|
|
7645
|
-
root: options.root ?? "ui/dist",
|
|
7645
|
+
root: options.root ?? "packages/ui/dist",
|
|
7646
7646
|
deploy: "server",
|
|
7647
7647
|
type: "static",
|
|
7648
7648
|
domain: options.domain,
|
|
7649
|
-
build: options.build ?? "cd ui && bun install && bun run build",
|
|
7649
|
+
build: options.build ?? "cd packages/ui && bun install && bun run build",
|
|
7650
7650
|
ssl: { provider: "letsencrypt" },
|
|
7651
7651
|
auth: {
|
|
7652
7652
|
username: options.username ?? "admin",
|