@stacksjs/buddy 0.70.33 → 0.70.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +14 -14
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  // @bun
2
- var Q8=Object.defineProperty;var J8=(Q)=>Q;function Y8(Q,$){this[Q]=J8.bind(null,$)}var f7=(Q,$)=>{for(var J in $)Q8(Q,J,{get:$[J],enumerable:!0,configurable:!0,set:Y8.bind($,J)})};var p=(Q,$)=>()=>(Q&&($=Q(Q=0)),$);var w=import.meta.require;var j3;var A3=p(()=>{j3={type:"aws",useLoadBalancer:!0,app:{name:"app-server-1",domain:"stacksjs.com",region:"us-east-1",type:"app",size:"t3.micro",diskSize:20,serverOS:"ubuntu-20-lts-x86_64",bunVersion:"1.1.26",database:"sqlite",databaseName:"stacks"},app2:{name:"app-server-2",domain:"stacksjs.com",instanceType:"t3.micro",userData:`#!/bin/bash
2
+ var Q5=Object.defineProperty;var J5=(Q)=>Q;function Y5(Q,$){this[Q]=J5.bind(null,$)}var f7=(Q,$)=>{for(var J in $)Q5(Q,J,{get:$[J],enumerable:!0,configurable:!0,set:Y5.bind($,J)})};var p=(Q,$)=>()=>(Q&&($=Q(Q=0)),$);var w=import.meta.require;var j3;var A3=p(()=>{j3={type:"aws",useLoadBalancer:!0,app:{name:"app-server-1",domain:"stacksjs.com",region:"us-east-1",type:"app",size:"t3.micro",diskSize:20,serverOS:"ubuntu-20-lts-x86_64",bunVersion:"1.1.26",database:"sqlite",databaseName:"stacks"},app2:{name:"app-server-2",domain:"stacksjs.com",instanceType:"t3.micro",userData:`#!/bin/bash
3
3
  echo "Hello World from App Server 2!" > /tmp/test.txt
4
4
  chown ubuntu:ubuntu /tmp/test.txt
5
- `},web:{name:"web-server",domain:"ow3.org",region:"us-east-1",type:"web",size:"t3.micro",diskSize:20,serverOS:"ubuntu-20-lts-x86_64",bunVersion:"1.1.26"},cache:{name:"cache-server",domain:"stacksjs.com",region:"us-east-1",type:"cache",size:"t3.micro",diskSize:20,serverOS:"ubuntu-20-lts-x86_64",bunVersion:"1.1.26"}}});var r$={};f7(r$,{tsCloud:()=>M8,default:()=>I8});import{env as p$}from"@stacksjs/env";var M8,T8,I8;var n$=p(()=>{A3();M8={project:{name:"stacks",slug:"stacks",region:"us-east-1"},mode:"server",environments:{production:{type:"production",region:"us-east-1",variables:{NODE_ENV:"production",LOG_LEVEL:"info"}},staging:{type:"staging",region:"us-east-1",variables:{NODE_ENV:"staging",LOG_LEVEL:"debug"}},development:{type:"development",region:"us-east-1",variables:{NODE_ENV:"development",LOG_LEVEL:"debug"}}},infrastructure:{compute:{instances:1,size:"small",disk:{size:20,type:"ssd",encrypted:!0}},servers:{app:j3.app},containers:{api:{cpu:512,memory:1024,port:3000,healthCheck:"/health",desiredCount:2,autoScaling:{min:1,max:10,targetCpuUtilization:70,targetMemoryUtilization:80}}},loadBalancer:{enabled:!0,type:"application",healthCheck:{path:"/health",interval:30,healthyThreshold:2,unhealthyThreshold:5}},ssl:{enabled:!0,provider:"acm",domains:p$.SSL_DOMAINS?.split(",")||["stacksjs.com","www.stacksjs.com"],redirectHttp:!0,letsEncrypt:{email:p$.LETSENCRYPT_EMAIL||"admin@stacksjs.com",staging:!1,autoRenew:!0}},dns:{domain:p$.APP_DOMAIN||"stacksjs.com",hostedZoneId:p$.AWS_HOSTED_ZONE_ID||"Z01455702Q7952O6RCY37"},storage:{public:{public:!0,encryption:!0,versioning:!0,website:{indexDocument:"index.html",errorDocument:"index.html"}},private:{encryption:!0,versioning:!0},docs:{public:!0,encryption:!0,versioning:!0,path:"/docs",pathRewriteStyle:"flat",website:{indexDocument:"index.html",errorDocument:"404.html"}},blog:{public:!0,encryption:!0,versioning:!0,path:"/blog",website:{indexDocument:"index.html",errorDocument:"404.html"}},logs:{encryption:!0,versioning:!1},backups:{encryption:!0,versioning:!0},email:{public:!1,encryption:!0,versioning:!1}},functions:{},queues:{jobs:{visibilityTimeout:120,deadLetterQueue:!0,maxReceiveCount:3}},databases:{},cdn:{},monitoring:{}},sites:{main:{root:"/var/www/app",path:"/",domain:p$.APP_DOMAIN||"stacksjs.com"}}},T8={},I8=T8});var f3={};f7(f3,{undeployStack:()=>S8,getDeploymentStatus:()=>v8,deployStack:()=>P8,deployFrontend:()=>f8});import P3 from"process";import{log as D7}from"@stacksjs/cli";async function O2(){try{return(await Promise.resolve().then(() => (n$(),r$))).tsCloud||null}catch{return null}}async function b7(){let Q=await O2();return{name:Q?.project?.name||"stacks",region:Q?.project?.region||"us-east-1"}}async function L2(Q){try{let{AWSClient:$}=await import("@stacksjs/ts-cloud"),J=new $,Y=new URLSearchParams({Action:"GetCallerIdentity",Version:"2011-06-15"}),G=await J.request({service:"sts",region:Q,method:"POST",path:"/",body:Y.toString()}),z=String(G).match(/<Account>(\d+)<\/Account>/);if(z&&z[1])return z[1];return P3.env.AWS_ACCOUNT_ID||""}catch($){return P3.env.AWS_ACCOUNT_ID||""}}async function j8(Q){let{environment:$}=Q,J=await O2();if(!J)throw Error("Cloud configuration not found. Ensure config/cloud.ts exports tsCloud.");let{InfrastructureGenerator:Y}=await import("@stacksjs/ts-cloud"),z=new Y({config:J,environment:$}).generate().getBuilder().build();return JSON.stringify(z)}function F2(Q){let $={green:"\x1B[32m",yellow:"\x1B[33m",red:"\x1B[31m",cyan:"\x1B[36m",gray:"\x1B[90m",reset:"\x1B[0m"};if(Q.includes("COMPLETE")&&!Q.includes("ROLLBACK"))return`${$.green}${Q}${$.reset}`;if(Q.includes("IN_PROGRESS"))return`${$.yellow}${Q}${$.reset}`;if(Q.includes("FAILED")||Q.includes("ROLLBACK"))return`${$.red}${Q}${$.reset}`;if(Q.includes("DELETE"))return`${$.gray}${Q}${$.reset}`;return Q}async function A8(Q){let{region:$,domain:J,sslDomains:Y,hostedZoneId:G,albDnsName:z,stackName:W}=Q;console.log(""),console.log("Setting up SSL certificate...");try{let{Route53Client:X,ACMClient:H,AWSClient:q}=await import("@stacksjs/ts-cloud"),Z=new X($),K=new H($),_=new q;console.log(` Requesting SSL certificate for ${J}...`);let U=await K.requestCertificate({DomainName:Y[0]??J,SubjectAlternativeNames:Y.length>1?Y.slice(1):void 0,ValidationMethod:"DNS"});console.log(` Certificate ARN: ${U.CertificateArn}`),await new Promise((F)=>setTimeout(F,5000));let L=await K.describeCertificate({CertificateArn:U.CertificateArn});console.log(" Adding DNS validation records...");for(let F of L.DomainValidationOptions||[])if(F.ResourceRecord)await Z.changeResourceRecordSets({HostedZoneId:G,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:F.ResourceRecord.Name,Type:"CNAME",TTL:300,ResourceRecords:[{Value:F.ResourceRecord.Value}]}}]}});console.log("\u2713 Validation records added"),console.log(" Waiting for certificate validation (this may take 1-5 minutes)...");for(let F=0;F<30;F++){let O=await K.describeCertificate({CertificateArn:U.CertificateArn});if(O.Status==="ISSUED"){console.log("\u2713 Certificate issued!");let{AWSCloudFormationClient:M}=await import("@stacksjs/ts-cloud"),f=await new M($).listStackResources(W),P=f.StackResourceSummaries.find((A)=>A.LogicalResourceId==="ApplicationLoadBalancer")?.PhysicalResourceId,I=f.StackResourceSummaries.find((A)=>A.LogicalResourceId==="ECSTargetGroup")?.PhysicalResourceId||f.StackResourceSummaries.find((A)=>A.LogicalResourceId==="WebTargetGroup")?.PhysicalResourceId;if(P&&I){console.log(" Creating HTTPS listener...");let A=new URLSearchParams({Action:"CreateListener",LoadBalancerArn:P,Protocol:"HTTPS",Port:"443","Certificates.member.1.CertificateArn":U.CertificateArn,"DefaultActions.member.1.Type":"forward","DefaultActions.member.1.TargetGroupArn":I,Version:"2015-12-01"});await _.request({service:"elasticloadbalancing",region:$,method:"POST",path:"/",body:A.toString()}),console.log("\u2713 HTTPS listener created!"),console.log(" Configuring HTTP to HTTPS redirect...");let h=new URLSearchParams({Action:"DescribeListeners",LoadBalancerArn:P,Version:"2015-12-01"}),V=await _.request({service:"elasticloadbalancing",region:$,method:"POST",path:"/",body:h.toString()}),N=V?.DescribeListenersResponse?.DescribeListenersResult?.Listeners?.member||V?.DescribeListenersResult?.Listeners?.member,v=(Array.isArray(N)?N:N?[N]:[]).find((B0)=>B0.Port==="80"||B0.Port===80);if(v){let B0=new URLSearchParams({Action:"ModifyListener",ListenerArn:v.ListenerArn,"DefaultActions.member.1.Type":"redirect","DefaultActions.member.1.RedirectConfig.Protocol":"HTTPS","DefaultActions.member.1.RedirectConfig.Port":"443","DefaultActions.member.1.RedirectConfig.StatusCode":"HTTP_301",Version:"2015-12-01"});await _.request({service:"elasticloadbalancing",region:$,method:"POST",path:"/",body:B0.toString()}),console.log("\u2713 HTTP to HTTPS redirect configured!")}}let j=f.StackResourceSummaries.find((A)=>A.LogicalResourceId==="CloudFrontDistribution")?.PhysicalResourceId;if(j){console.log(" Updating CloudFront distribution with SSL certificate...");let A=await _.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${j}/config`}),h=A._headers?.etag||A._headers?.ETag,V=A.DistributionConfig;if(V&&h){V.Aliases={Quantity:Y.length,Items:Y},V.ViewerCertificate={ACMCertificateArn:U.CertificateArn,SSLSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021",CloudFrontDefaultCertificate:!1};let N=`<?xml version="1.0" encoding="UTF-8"?>
5
+ `},web:{name:"web-server",domain:"ow3.org",region:"us-east-1",type:"web",size:"t3.micro",diskSize:20,serverOS:"ubuntu-20-lts-x86_64",bunVersion:"1.1.26"},cache:{name:"cache-server",domain:"stacksjs.com",region:"us-east-1",type:"cache",size:"t3.micro",diskSize:20,serverOS:"ubuntu-20-lts-x86_64",bunVersion:"1.1.26"}}});var r$={};f7(r$,{tsCloud:()=>M5,default:()=>I5});import{env as p$}from"@stacksjs/env";var M5,T5,I5;var n$=p(()=>{A3();M5={project:{name:"stacks",slug:"stacks",region:"us-east-1"},mode:"server",environments:{production:{type:"production",region:"us-east-1",variables:{NODE_ENV:"production",LOG_LEVEL:"info"}},staging:{type:"staging",region:"us-east-1",variables:{NODE_ENV:"staging",LOG_LEVEL:"debug"}},development:{type:"development",region:"us-east-1",variables:{NODE_ENV:"development",LOG_LEVEL:"debug"}}},infrastructure:{compute:{instances:1,size:"small",disk:{size:20,type:"ssd",encrypted:!0}},servers:{app:j3.app},containers:{api:{cpu:512,memory:1024,port:3000,healthCheck:"/health",desiredCount:2,autoScaling:{min:1,max:10,targetCpuUtilization:70,targetMemoryUtilization:80}}},loadBalancer:{enabled:!0,type:"application",healthCheck:{path:"/health",interval:30,healthyThreshold:2,unhealthyThreshold:5}},ssl:{enabled:!0,provider:"acm",domains:p$.SSL_DOMAINS?.split(",")||["stacksjs.com","www.stacksjs.com"],redirectHttp:!0,letsEncrypt:{email:p$.LETSENCRYPT_EMAIL||"admin@stacksjs.com",staging:!1,autoRenew:!0}},dns:{domain:p$.APP_DOMAIN||"stacksjs.com",hostedZoneId:p$.AWS_HOSTED_ZONE_ID||"Z01455702Q7952O6RCY37"},storage:{public:{public:!0,encryption:!0,versioning:!0,website:{indexDocument:"index.html",errorDocument:"index.html"}},private:{encryption:!0,versioning:!0},docs:{public:!0,encryption:!0,versioning:!0,path:"/docs",pathRewriteStyle:"flat",website:{indexDocument:"index.html",errorDocument:"404.html"}},blog:{public:!0,encryption:!0,versioning:!0,path:"/blog",website:{indexDocument:"index.html",errorDocument:"404.html"}},logs:{encryption:!0,versioning:!1},backups:{encryption:!0,versioning:!0},email:{public:!1,encryption:!0,versioning:!1}},functions:{},queues:{jobs:{visibilityTimeout:120,deadLetterQueue:!0,maxReceiveCount:3}},databases:{},cdn:{},monitoring:{}},sites:{main:{root:"/var/www/app",path:"/",domain:p$.APP_DOMAIN||"stacksjs.com"}}},T5={},I5=T5});var f3={};f7(f3,{undeployStack:()=>S5,getDeploymentStatus:()=>v5,deployStack:()=>P5,deployFrontend:()=>f5});import P3 from"process";import{log as D7}from"@stacksjs/cli";async function O2(){try{return(await Promise.resolve().then(() => (n$(),r$))).tsCloud||null}catch{return null}}async function b7(){let Q=await O2();return{name:Q?.project?.name||"stacks",region:Q?.project?.region||"us-east-1"}}async function L2(Q){try{let{AWSClient:$}=await import("@stacksjs/ts-cloud"),J=new $,Y=new URLSearchParams({Action:"GetCallerIdentity",Version:"2011-06-15"}),G=await J.request({service:"sts",region:Q,method:"POST",path:"/",body:Y.toString()}),z=String(G).match(/<Account>(\d+)<\/Account>/);if(z&&z[1])return z[1];return P3.env.AWS_ACCOUNT_ID||""}catch($){return P3.env.AWS_ACCOUNT_ID||""}}async function j5(Q){let{environment:$}=Q,J=await O2();if(!J)throw Error("Cloud configuration not found. Ensure config/cloud.ts exports tsCloud.");let{InfrastructureGenerator:Y}=await import("@stacksjs/ts-cloud"),z=new Y({config:J,environment:$}).generate().getBuilder().build();return JSON.stringify(z)}function F2(Q){let $={green:"\x1B[32m",yellow:"\x1B[33m",red:"\x1B[31m",cyan:"\x1B[36m",gray:"\x1B[90m",reset:"\x1B[0m"};if(Q.includes("COMPLETE")&&!Q.includes("ROLLBACK"))return`${$.green}${Q}${$.reset}`;if(Q.includes("IN_PROGRESS"))return`${$.yellow}${Q}${$.reset}`;if(Q.includes("FAILED")||Q.includes("ROLLBACK"))return`${$.red}${Q}${$.reset}`;if(Q.includes("DELETE"))return`${$.gray}${Q}${$.reset}`;return Q}async function A5(Q){let{region:$,domain:J,sslDomains:Y,hostedZoneId:G,albDnsName:z,stackName:W}=Q;console.log(""),console.log("Setting up SSL certificate...");try{let{Route53Client:X,ACMClient:H,AWSClient:q}=await import("@stacksjs/ts-cloud"),Z=new X($),K=new H($),_=new q;console.log(` Requesting SSL certificate for ${J}...`);let U=await K.requestCertificate({DomainName:Y[0]??J,SubjectAlternativeNames:Y.length>1?Y.slice(1):void 0,ValidationMethod:"DNS"});console.log(` Certificate ARN: ${U.CertificateArn}`),await new Promise((F)=>setTimeout(F,5000));let L=await K.describeCertificate({CertificateArn:U.CertificateArn});console.log(" Adding DNS validation records...");for(let F of L.DomainValidationOptions||[])if(F.ResourceRecord)await Z.changeResourceRecordSets({HostedZoneId:G,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:F.ResourceRecord.Name,Type:"CNAME",TTL:300,ResourceRecords:[{Value:F.ResourceRecord.Value}]}}]}});console.log("\u2713 Validation records added"),console.log(" Waiting for certificate validation (this may take 1-5 minutes)...");for(let F=0;F<30;F++){let O=await K.describeCertificate({CertificateArn:U.CertificateArn});if(O.Status==="ISSUED"){console.log("\u2713 Certificate issued!");let{AWSCloudFormationClient:M}=await import("@stacksjs/ts-cloud"),f=await new M($).listStackResources(W),P=f.StackResourceSummaries.find((A)=>A.LogicalResourceId==="ApplicationLoadBalancer")?.PhysicalResourceId,I=f.StackResourceSummaries.find((A)=>A.LogicalResourceId==="ECSTargetGroup")?.PhysicalResourceId||f.StackResourceSummaries.find((A)=>A.LogicalResourceId==="WebTargetGroup")?.PhysicalResourceId;if(P&&I){console.log(" Creating HTTPS listener...");let A=new URLSearchParams({Action:"CreateListener",LoadBalancerArn:P,Protocol:"HTTPS",Port:"443","Certificates.member.1.CertificateArn":U.CertificateArn,"DefaultActions.member.1.Type":"forward","DefaultActions.member.1.TargetGroupArn":I,Version:"2015-12-01"});await _.request({service:"elasticloadbalancing",region:$,method:"POST",path:"/",body:A.toString()}),console.log("\u2713 HTTPS listener created!"),console.log(" Configuring HTTP to HTTPS redirect...");let h=new URLSearchParams({Action:"DescribeListeners",LoadBalancerArn:P,Version:"2015-12-01"}),V=await _.request({service:"elasticloadbalancing",region:$,method:"POST",path:"/",body:h.toString()}),N=V?.DescribeListenersResponse?.DescribeListenersResult?.Listeners?.member||V?.DescribeListenersResult?.Listeners?.member,v=(Array.isArray(N)?N:N?[N]:[]).find((B0)=>B0.Port==="80"||B0.Port===80);if(v){let B0=new URLSearchParams({Action:"ModifyListener",ListenerArn:v.ListenerArn,"DefaultActions.member.1.Type":"redirect","DefaultActions.member.1.RedirectConfig.Protocol":"HTTPS","DefaultActions.member.1.RedirectConfig.Port":"443","DefaultActions.member.1.RedirectConfig.StatusCode":"HTTP_301",Version:"2015-12-01"});await _.request({service:"elasticloadbalancing",region:$,method:"POST",path:"/",body:B0.toString()}),console.log("\u2713 HTTP to HTTPS redirect configured!")}}let j=f.StackResourceSummaries.find((A)=>A.LogicalResourceId==="CloudFrontDistribution")?.PhysicalResourceId;if(j){console.log(" Updating CloudFront distribution with SSL certificate...");let A=await _.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${j}/config`}),h=A._headers?.etag||A._headers?.ETag,V=A.DistributionConfig;if(V&&h){V.Aliases={Quantity:Y.length,Items:Y},V.ViewerCertificate={ACMCertificateArn:U.CertificateArn,SSLSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021",CloudFrontDefaultCertificate:!1};let N=`<?xml version="1.0" encoding="UTF-8"?>
6
6
  <DistributionConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
7
7
  <CallerReference>${V.CallerReference}</CallerReference>
8
8
  <Aliases>
@@ -93,9 +93,9 @@ ${(V.CustomErrorResponses?.Items||[]).map((B)=>` <CustomErrorResponse>
93
93
  </ViewerCertificate>
94
94
  <HttpVersion>${V.HttpVersion||"http2and3"}</HttpVersion>
95
95
  <IsIPV6Enabled>${V.IsIPV6Enabled!==!1}</IsIPV6Enabled>
96
- </DistributionConfig>`;await _.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${j}/config`,headers:{"Content-Type":"application/xml","If-Match":h},body:N}),console.log("\u2713 CloudFront distribution updated with SSL certificate!")}}console.log(""),console.log(`\u2713 SSL setup complete! https://${J} should be accessible shortly.`),console.log("");return}if(O.Status==="FAILED"){console.log("\u2717 Certificate validation failed!");return}await new Promise((M)=>setTimeout(M,1e4))}console.log("\u26A0 Certificate validation timed out. Please check AWS Console.")}catch(X){console.log(`\u2717 DNS/SSL setup failed: ${X.message}`),console.log(" You can manually set up DNS and SSL using ./buddy cloud:ssl")}}async function P8(Q){let{environment:$,region:J,waitForCompletion:Y=!0,verbose:G=!1}=Q,W=(await b7()).name,X=`${W}-cloud`;if(G)console.log(`Deploying ${X} to ${J}...`);try{let{AWSCloudFormationClient:H}=await import("@stacksjs/ts-cloud"),q=new H(J),Z=await O2(),K=Z?.infrastructure?.compute?.mode||Z?.mode||"server";if(G)console.log(`Generating CloudFormation template (${K} mode)...`);let _=await j8({environment:$,projectName:W}),U=51200,L;if(Buffer.byteLength(_,"utf-8")>U){if(G)console.log(`Template exceeds inline limit (${Buffer.byteLength(_,"utf-8")} bytes), uploading to S3...`);let{S3Client:I,AWSClient:j}=await import("@stacksjs/ts-cloud"),A=new I(J),h=new j,V=`${W}-cf-templates-${J}`;try{await h.request({service:"s3",region:J,method:"HEAD",path:`/${V}`,bucket:V})}catch{let B=J==="us-east-1"?"":`<CreateBucketConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><LocationConstraint>${J}</LocationConstraint></CreateBucketConfiguration>`;await h.request({service:"s3",region:J,method:"PUT",path:`/${V}`,bucket:V,body:B||void 0})}let N=`${X}/template-${Date.now()}.json`;if(await A.putObject({bucket:V,key:N,body:_,contentType:"application/json"}),L=`https://${V}.s3.${J}.amazonaws.com/${N}`,G)console.log(`Template uploaded to: ${L}`)}let F=L?{templateUrl:L}:{templateBody:_},O=!1,M=!1;try{let I=(await q.describeStacks({stackName:X})).Stacks?.[0];if(I&&I.StackStatus){if(G)console.log(`Current status: ${F2(I.StackStatus)}`);if(O=!0,M=!0,I.StackStatus.endsWith("_IN_PROGRESS")){console.log(`Stack is busy (${I.StackStatus}). Waiting for current operation to finish...`);let j=I.StackStatus.startsWith("DELETE")?"stack-delete-complete":I.StackStatus.startsWith("CREATE")?"stack-create-complete":"stack-update-complete";try{await q.waitForStack(X,j)}catch{}try{let A=(await q.describeStacks({stackName:X})).Stacks?.[0];if(!A||!A.StackStatus)O=!1,M=!1;else{if(G)console.log(`Stack settled to: ${F2(A.StackStatus)}`);I.StackStatus=A.StackStatus}}catch{O=!1,M=!1}}if(I.StackStatus==="UPDATE_ROLLBACK_COMPLETE")console.log("Stack rolled back from a previous update. Re-deploying...");else if(I.StackStatus==="DELETE_COMPLETE")O=!1,M=!1;else if(I.StackStatus==="ROLLBACK_COMPLETE"||I.StackStatus==="ROLLBACK_FAILED"||I.StackStatus==="CREATE_FAILED"){console.log(`Stack is in ${I.StackStatus} state. Deleting before recreating...`),await q.deleteStack(X),await q.waitForStack(X,"stack-delete-complete"),console.log("Cleaning up retained resources...");try{let{S3Client:j}=await import("@stacksjs/ts-cloud"),A=new j(J),h=await L2(J),V=`${W}-${$}-assets-${h}`,N=`${W}-${$}-frontend-${h}`;if(G)console.log(` Checking bucket: ${V}`);try{await A.emptyAndDeleteBucket(V),console.log(`\u2713 Deleted retained bucket: ${V}`)}catch(B){if(!B.message?.includes("NoSuchBucket")&&!B.message?.includes("does not exist"))console.log(`\u26A0 Could not delete assets bucket: ${B.message}`);else if(G)console.log(" No retained assets bucket to clean up")}if(G)console.log(` Checking bucket: ${N}`);try{await A.emptyAndDeleteBucket(N),console.log(`\u2713 Deleted retained bucket: ${N}`)}catch(B){if(!B.message?.includes("NoSuchBucket")&&!B.message?.includes("does not exist"))console.log(`\u26A0 Could not delete frontend bucket: ${B.message}`);else if(G)console.log(" No retained frontend bucket to clean up")}}catch(j){console.log(`\u26A0 Cleanup error: ${j.message}`)}O=!1,M=!1}}}catch{O=!1}if(O){console.log("Updating stack..."),console.log("");try{let I=L?{templateURL:L}:{templateBody:_};if(await q.updateStack({stackName:X,...I,capabilities:["CAPABILITY_IAM","CAPABILITY_NAMED_IAM"],tags:[{Key:"Environment",Value:$},{Key:"Project",Value:W},{Key:"ManagedBy",Value:"stacks"}]}),Y)console.log(` ${"Resource".padEnd(35)} ${"Type".padEnd(30)} Status`),console.log(" "+"\u2500".repeat(85)),await q.waitForStack(X,"stack-update-complete"),console.log("")}catch(I){if(I.message?.includes("No updates are to be performed"))console.log("\u2713 Stack is up to date (no changes)");else throw I}}else{console.log("Checking for retained resources...");try{let{S3Client:A}=await import("@stacksjs/ts-cloud"),h=new A(J),V=await L2(J),N=`${W}-${$}-assets-${V}`,B=`${W}-${$}-frontend-${V}`;if(G)console.log(` Checking bucket: ${N}`);try{await h.emptyAndDeleteBucket(N),console.log(`\u2713 Cleaned up existing bucket: ${N}`)}catch(v){if(!v.message?.includes("NoSuchBucket")&&!v.message?.includes("does not exist"))console.log(`\u26A0 Could not delete assets bucket: ${v.message}`);else if(G)console.log(" No existing assets bucket to clean up")}if(G)console.log(` Checking bucket: ${B}`);try{await h.emptyAndDeleteBucket(B),console.log(`\u2713 Cleaned up existing bucket: ${B}`)}catch(v){if(!v.message?.includes("NoSuchBucket")&&!v.message?.includes("does not exist"))console.log(`\u26A0 Could not delete frontend bucket: ${v.message}`);else if(G)console.log(" No existing frontend bucket to clean up")}}catch(A){console.log(`\u26A0 Pre-deployment cleanup error: ${A.message}`)}console.log("Creating stack..."),console.log("");let I=L?{templateURL:L}:{templateBody:_},j=await q.createStack({stackName:X,...I,capabilities:["CAPABILITY_IAM","CAPABILITY_NAMED_IAM"],tags:[{Key:"Environment",Value:$},{Key:"Project",Value:W},{Key:"ManagedBy",Value:"stacks"}],onFailure:"ROLLBACK",timeoutInMinutes:30});if(G)console.log(`Stack ID: ${j}`);if(Y)console.log(` ${"Resource".padEnd(35)} ${"Type".padEnd(30)} Status`),console.log(" "+"\u2500".repeat(85)),await q.waitForStack(X,"stack-create-complete"),console.log("")}let T=Z?.infrastructure?.dns?.domain||"stacksjs.com",f=Z?.infrastructure?.ssl||{enabled:!0,domains:[]},P=f.domains||[T,`www.${T}`];try{let I=(await q.describeStacks({stackName:X})).Stacks?.[0];if(I&&I.StackStatus){let j={};for(let A of I.Outputs||[])if(A.OutputKey&&A.OutputValue)j[A.OutputKey]=A.OutputValue;if(console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(""),console.log(" \u2713 Infrastructure deployed successfully"),console.log(""),console.log(` Stack: ${X}`),console.log(` Status: ${I.StackStatus}`),console.log(` Domain: https://${T}`),j.LoadBalancerDNS)console.log(` Load Balancer: ${j.LoadBalancerDNS}`);if(j.WebServerPublicIP)console.log(` Server IP: ${j.WebServerPublicIP}`);if(j.AssetsBucketName&&G)console.log(` Assets: ${j.AssetsBucketName}`);if(console.log(""),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(""),f.enabled&&Z?.infrastructure?.dns?.hostedZoneId&&j.LoadBalancerDNS)await A8({region:J,domain:T,sslDomains:P,hostedZoneId:Z.infrastructure.dns.hostedZoneId,albDnsName:j.LoadBalancerDNS,stackName:X});else if(!f.certificateArn&&G)console.log(" Next steps:"),console.log(" 1. DNS records need to be updated to point to the ALB"),console.log(" 2. SSL certificate needs to be requested and attached"),console.log(` Run: ./buddy cloud:ssl to set up SSL for ${T}`),console.log("")}}catch{}}catch(H){throw console.error(`Stack deployment failed: ${H.message}`),H}}async function f8(Q){let{environment:$,region:J,buildDir:Y}=Q,z=(await b7()).name;D7.info(`Deploying frontend from ${Y} to ${$} in ${J}...`);try{let{S3Client:W,AWSCloudFormationClient:X}=await import("@stacksjs/ts-cloud"),H=new W(J),q=new X(J),Z=`${z}-cloud`,_=(await q.describeStacks({stackName:Z})).Stacks?.[0]?.Outputs?.find((U)=>U.OutputKey==="AssetsBucketName")?.OutputValue;if(!_)throw Error("Assets bucket not found in stack outputs");D7.info(`Syncing ${Y} to s3://${_}/...`),await H.sync({source:Y,bucket:_,delete:!0,cacheControl:"max-age=31536000"}),D7.success("Frontend deployment completed!")}catch(W){throw D7.error(`Frontend deployment failed: ${W.message}`),W}}async function v8(Q){let{environment:$,region:J}=Q,z=`${(await b7()).name}-cloud`,{AWSCloudFormationClient:W}=await import("@stacksjs/ts-cloud"),X=new W(J);try{let H=(await X.describeStacks({stackName:z})).Stacks?.[0];if(!H||!H.StackStatus)return{status:"NOT_FOUND",outputs:{}};let q={};for(let Z of H.Outputs||[])if(Z.OutputKey&&Z.OutputValue)q[Z.OutputKey]=Z.OutputValue;return{status:H.StackStatus,outputs:q}}catch{return{status:"NOT_FOUND",outputs:{}}}}async function S8(Q){let{environment:$,region:J,verbose:Y}=Q,G=await b7(),W=`${G.name}-cloud`;console.log(`Undeploying ${W} from ${J}...`),console.log("");try{let{AWSCloudFormationClient:X,AWSClient:H}=await import("@stacksjs/ts-cloud"),q=new X(J),Z=!1;try{let K=(await q.describeStacks({stackName:W})).Stacks?.[0];if(K&&K.StackStatus){if(console.log(`Current status: ${F2(K.StackStatus)}`),Z=!0,K.StackStatus.endsWith("_IN_PROGRESS")){console.log(`Waiting for current operation (${K.StackStatus}) to finish...`);let _=K.StackStatus.startsWith("DELETE")?"stack-delete-complete":K.StackStatus.startsWith("CREATE")?"stack-create-complete":"stack-update-complete";try{await q.waitForStack(W,_)}catch{}try{let U=(await q.describeStacks({stackName:W})).Stacks?.[0];if(!U||!U.StackStatus||U.StackStatus==="DELETE_COMPLETE"){console.log("Stack was already deleted during the in-progress operation.");return}}catch{console.log("Stack was already deleted during the in-progress operation.");return}}if(K.StackStatus==="DELETE_COMPLETE")Z=!1}}catch{Z=!1}if(!Z){console.log(`Stack ${W} does not exist. Nothing to undeploy.`);return}if(Y)console.log("Checking for resources to clean up before deletion...");try{let K=new H,{AWSCloudFormationClient:_}=await import("@stacksjs/ts-cloud"),O=((await new _(J).listStackResources(W)).StackResourceSummaries||[]).find((M)=>M.LogicalResourceId==="ApplicationLoadBalancer");if(O?.PhysicalResourceId){let T={Action:"DescribeListeners",LoadBalancerArn:O.PhysicalResourceId,Version:"2015-12-01"},f=await K.request({service:"elasticloadbalancing",region:J,method:"POST",path:"/",body:new URLSearchParams(T).toString()}),P=f?.DescribeListenersResult?.Listeners?.member||f?.DescribeListenersResponse?.DescribeListenersResult?.Listeners?.member,I=Array.isArray(P)?P:P?[P]:[],j=0;for(let A of I)if(A.Protocol==="HTTPS"){if(Y)console.log(` Removing HTTPS listener on port ${A.Port}...`);let h={Action:"DeleteListener",ListenerArn:A.ListenerArn,Version:"2015-12-01"};await K.request({service:"elasticloadbalancing",region:J,method:"POST",path:"/",body:new URLSearchParams(h).toString()}),j++}if(j>0&&Y)console.log(`\u2713 Cleaned up ${j} HTTPS listener(s)`),await new Promise((A)=>setTimeout(A,2000))}}catch(K){if(Y)console.log(`Warning: ${K.message}`)}console.log("Deleting stack..."),console.log(""),await q.deleteStack(W),console.log(` ${"Resource".padEnd(35)} ${"Type".padEnd(30)} Status`),console.log(" "+"\u2500".repeat(85)),await q.waitForStack(W,"stack-delete-complete");try{let{S3Client:K}=await import("@stacksjs/ts-cloud"),_=new K(J),U=await L2(J),L=`${G.name}-${$}-assets-${U}`,F=`${G.name}-${$}-frontend-${U}`;console.log("Cleaning up retained buckets...");try{await _.emptyAndDeleteBucket(L),console.log("\u2713 Assets bucket deleted successfully")}catch(O){if(!O.message?.includes("NoSuchBucket")&&!O.message?.includes("does not exist"))console.log(`\u26A0 Could not delete assets bucket: ${O.message}`);else console.log("\u2713 No retained assets bucket to clean up")}try{await _.emptyAndDeleteBucket(F),console.log("\u2713 Frontend bucket deleted successfully")}catch(O){if(!O.message?.includes("NoSuchBucket")&&!O.message?.includes("does not exist"))console.log(`\u26A0 Could not delete frontend bucket: ${O.message}`);else console.log("\u2713 No retained frontend bucket to clean up")}}catch(K){console.log(`\u26A0 Cleanup error: ${K.message}`)}console.log(""),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(""),console.log(" \u2713 Infrastructure removed successfully"),console.log(""),console.log(` Stack: ${W}`),console.log(` Environment: ${$}`),console.log(` Region: ${J}`),console.log(""),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log("")}catch(X){let H=String(X.message||X);if(H.includes("does not exist")){console.log(""),console.log("\u2713 Stack already deleted or does not exist.");return}if(X.code==="DELETE_FAILED"||H.includes("DELETE_FAILED")){console.log(""),console.log("Some resources could not be deleted automatically"),console.log("Identifying resources to retain...");let{AWSCloudFormationClient:q}=await import("@stacksjs/ts-cloud"),Z=new q(J);try{let U=((await Z.listStackResources(W)).StackResourceSummaries||[]).filter((L)=>L.ResourceStatus==="DELETE_FAILED").map((L)=>L.LogicalResourceId);if(U.length>0){console.log(`Retaining ${U.length} resource(s):`),U.forEach((O)=>console.log(` - ${O}`)),console.log(""),console.log("Retrying deletion with retained resources..."),await Z.deleteStack(W,void 0,U);let{AWSCloudFormationClient:L}=await import("@stacksjs/ts-cloud");await new L(J).waitForStack(W,"stack-delete-complete"),console.log(""),console.log("\u2713 Stack removed (with retained resources)"),console.log(""),console.log("Note: Some resources were retained and may need manual cleanup."),console.log("Run `./buddy cloud:cleanup` to clean up remaining resources.");return}}catch(K){if(String(K.message||K).includes("does not exist")){console.log(""),console.log("\u2713 Stack deleted successfully!");return}throw K}}throw console.error(`Stack deletion failed: ${X.message}`),X}}var v3=()=>{};var P5={};f7(P5,{setup:()=>R5,optimizePantryDeps:()=>y3,ensurePantryInstalled:()=>T$,ensurePantryDependencies:()=>I$,ensureEnvIsSet:()=>u7,ensureAppKey:()=>g7});import{existsSync as k7,readFileSync as b3,writeFileSync as X5}from"fs";import{join as o$}from"path";import K$ from"process";import{runAction as q5,setupSSL as H5}from"@stacksjs/actions";import{log as o,onUnknownSubcommand as Z5,runCommand as t$}from"@stacksjs/cli";import{Action as K5}from"@stacksjs/enums";import{handleError as e$}from"@stacksjs/error-handling";import{path as x7}from"@stacksjs/path";import{copyFile as _5,storage as U5}from"@stacksjs/storage";import{ExitCode as M$}from"@stacksjs/types";function $7(Q,$){let J=Number(K$.env[Q]);if(Number.isFinite(J)&&J>0)return J;return $}function R5(Q){let $={setup:"This command ensures your project is setup correctly",ssl:"Setup SSL certificates and hosts file for HTTPS development",ohMyZsh:"Enable Oh My Zsh",aws:"Ensures AWS is connected to the project",project:"Target a specific project",verbose:"Enable verbose output",domain:"Custom domain to setup (defaults to APP_URL)",skipHosts:"Skip adding domain to hosts file",skipTrust:"Skip trusting the certificate",skipAws:"Skip AWS configuration during setup",skipKeygen:"Skip generating an application key during setup"};Q.command("setup",$.setup).alias("ensure").option("-p, --project [project]",$.project,{default:!1}).option("--skip-aws",$.skipAws,{default:!1}).option("--skip-keygen",$.skipKeygen,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{o.debug("Running `buddy setup` ...",J),await T$(),await y3(),await I5(J)}),Q.command("setup:ssl",$.ssl).alias("ssl:setup").option("-d, --domain [domain]",$.domain).option("--skip-hosts",$.skipHosts,{default:!1}).option("--skip-trust",$.skipTrust,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{if(o.debug("Running `buddy setup:ssl` ...",J),!await H5({domain:J.domain,skipHosts:J.skipHosts,skipTrust:J.skipTrust,verbose:J.verbose}))o.warn("SSL setup completed with warnings"),o.info("You may need to manually trust certificates or update hosts file")}),Q.command("setup:oh-my-zsh",$.ohMyZsh).alias("upgrade:oh-my-zsh").option("--verbose",$.verbose,{default:!1}).action(async(J)=>{o.debug("Running `buddy setup:oh-my-zsh` ...",J);let Y=await q5(K5.UpgradeShell);if(Y.isErr)o.error(Y.error),K$.exit(M$.FatalError)}),Z5(Q,"setup")}async function w5(){if((await t$("pantry --version",{silent:!0,timeoutMs:L5})).isOk)return!0;return!1}async function M5(){let Q=await t$(x7.frameworkPath("scripts/pantry-install"),{timeoutMs:F5});if(Q.isOk)return;e$(Q.error),K$.exit(M$.FatalError)}async function T$(){if(!await w5())await M5()}async function I$(Q){o.info("Installing Pantry dependencies...");let $=await t$("pantry install",{cwd:Q,timeoutMs:O5});if($.isOk){o.success("Installed Pantry dependencies");return}e$($.error),K$.exit(M$.FatalError)}function T5(Q){let $=o$(Q,".env");if(!k7($))return!1;return/^APP_KEY=.+$/m.test(b3($,"utf-8"))}async function g7(Q){if(T5(Q)){o.success("APP_KEY existed");return}let $=await t$("./buddy key:generate",{cwd:Q,timeoutMs:V5});if($.isErr)e$($.error),K$.exit(M$.FatalError);o.success("Generated application key")}async function I5(Q){let $=Q.cwd||x7.projectPath();if(await I$($),await u7(Q),!Q.skipKeygen)await g7($);if(!Q.skipAws){o.info("Ensuring AWS is connected...");let J=await t$("./buddy configure:aws",{cwd:$,timeoutMs:B5});if(J.isErr)e$(J.error),K$.exit(M$.FatalError);o.success("Configured AWS")}o.success("Project is setup"),o.info("Happy coding! \uD83D\uDC99")}function A5(Q){let $=o$(Q,".env"),J=o$(Q,".env.example"),Y=k7($)?$:k7(J)?J:void 0;if(!Y)return;let z=b3(Y,"utf-8").match(/^DB_CONNECTION=(.+)$/m);if(!z)return;let W=z[1].trim().replace(/['"]/g,"");return j5[W]}async function y3(){let Q=x7.projectPath(),$=o$(Q,"config","deps.ts");if(!k7($)){o.debug("No config/deps.ts found, skipping dependency optimization");return}let J={};try{let W=await import($),X=W.config||W.default;if(X?.dependencies)J={...X.dependencies}}catch(W){o.debug("Could not load config/deps.ts, skipping dependency optimization");return}let Y=A5(Q);if(Y){if(!Object.keys(J).some((X)=>X===Y||X.startsWith(`${Y}/`)))o.info(`Detected DB_CONNECTION requires ${Y}, adding to dependencies`),J[Y]="*"}let G=["# Auto-generated from config/deps.ts and .env sniffing.","# This file is regenerated on each `buddy setup` run.","#","# To learn more, please visit:","# https://stacksjs.com/docs/dependency-management","","dependencies:"];for(let[W,X]of Object.entries(J))G.push(` ${W}: ${X}`);let z=o$(Q,"deps.yaml");X5(z,`${G.join(`
96
+ </DistributionConfig>`;await _.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${j}/config`,headers:{"Content-Type":"application/xml","If-Match":h},body:N}),console.log("\u2713 CloudFront distribution updated with SSL certificate!")}}console.log(""),console.log(`\u2713 SSL setup complete! https://${J} should be accessible shortly.`),console.log("");return}if(O.Status==="FAILED"){console.log("\u2717 Certificate validation failed!");return}await new Promise((M)=>setTimeout(M,1e4))}console.log("\u26A0 Certificate validation timed out. Please check AWS Console.")}catch(X){console.log(`\u2717 DNS/SSL setup failed: ${X.message}`),console.log(" You can manually set up DNS and SSL using ./buddy cloud:ssl")}}async function P5(Q){let{environment:$,region:J,waitForCompletion:Y=!0,verbose:G=!1}=Q,W=(await b7()).name,X=`${W}-cloud`;if(G)console.log(`Deploying ${X} to ${J}...`);try{let{AWSCloudFormationClient:H}=await import("@stacksjs/ts-cloud"),q=new H(J),Z=await O2(),K=Z?.infrastructure?.compute?.mode||Z?.mode||"server";if(G)console.log(`Generating CloudFormation template (${K} mode)...`);let _=await j5({environment:$,projectName:W}),U=51200,L;if(Buffer.byteLength(_,"utf-8")>U){if(G)console.log(`Template exceeds inline limit (${Buffer.byteLength(_,"utf-8")} bytes), uploading to S3...`);let{S3Client:I,AWSClient:j}=await import("@stacksjs/ts-cloud"),A=new I(J),h=new j,V=`${W}-cf-templates-${J}`;try{await h.request({service:"s3",region:J,method:"HEAD",path:`/${V}`,bucket:V})}catch{let B=J==="us-east-1"?"":`<CreateBucketConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><LocationConstraint>${J}</LocationConstraint></CreateBucketConfiguration>`;await h.request({service:"s3",region:J,method:"PUT",path:`/${V}`,bucket:V,body:B||void 0})}let N=`${X}/template-${Date.now()}.json`;if(await A.putObject({bucket:V,key:N,body:_,contentType:"application/json"}),L=`https://${V}.s3.${J}.amazonaws.com/${N}`,G)console.log(`Template uploaded to: ${L}`)}let F=L?{templateUrl:L}:{templateBody:_},O=!1,M=!1;try{let I=(await q.describeStacks({stackName:X})).Stacks?.[0];if(I&&I.StackStatus){if(G)console.log(`Current status: ${F2(I.StackStatus)}`);if(O=!0,M=!0,I.StackStatus.endsWith("_IN_PROGRESS")){console.log(`Stack is busy (${I.StackStatus}). Waiting for current operation to finish...`);let j=I.StackStatus.startsWith("DELETE")?"stack-delete-complete":I.StackStatus.startsWith("CREATE")?"stack-create-complete":"stack-update-complete";try{await q.waitForStack(X,j)}catch{}try{let A=(await q.describeStacks({stackName:X})).Stacks?.[0];if(!A||!A.StackStatus)O=!1,M=!1;else{if(G)console.log(`Stack settled to: ${F2(A.StackStatus)}`);I.StackStatus=A.StackStatus}}catch{O=!1,M=!1}}if(I.StackStatus==="UPDATE_ROLLBACK_COMPLETE")console.log("Stack rolled back from a previous update. Re-deploying...");else if(I.StackStatus==="DELETE_COMPLETE")O=!1,M=!1;else if(I.StackStatus==="ROLLBACK_COMPLETE"||I.StackStatus==="ROLLBACK_FAILED"||I.StackStatus==="CREATE_FAILED"){console.log(`Stack is in ${I.StackStatus} state. Deleting before recreating...`),await q.deleteStack(X),await q.waitForStack(X,"stack-delete-complete"),console.log("Cleaning up retained resources...");try{let{S3Client:j}=await import("@stacksjs/ts-cloud"),A=new j(J),h=await L2(J),V=`${W}-${$}-assets-${h}`,N=`${W}-${$}-frontend-${h}`;if(G)console.log(` Checking bucket: ${V}`);try{await A.emptyAndDeleteBucket(V),console.log(`\u2713 Deleted retained bucket: ${V}`)}catch(B){if(!B.message?.includes("NoSuchBucket")&&!B.message?.includes("does not exist"))console.log(`\u26A0 Could not delete assets bucket: ${B.message}`);else if(G)console.log(" No retained assets bucket to clean up")}if(G)console.log(` Checking bucket: ${N}`);try{await A.emptyAndDeleteBucket(N),console.log(`\u2713 Deleted retained bucket: ${N}`)}catch(B){if(!B.message?.includes("NoSuchBucket")&&!B.message?.includes("does not exist"))console.log(`\u26A0 Could not delete frontend bucket: ${B.message}`);else if(G)console.log(" No retained frontend bucket to clean up")}}catch(j){console.log(`\u26A0 Cleanup error: ${j.message}`)}O=!1,M=!1}}}catch{O=!1}if(O){console.log("Updating stack..."),console.log("");try{let I=L?{templateURL:L}:{templateBody:_};if(await q.updateStack({stackName:X,...I,capabilities:["CAPABILITY_IAM","CAPABILITY_NAMED_IAM"],tags:[{Key:"Environment",Value:$},{Key:"Project",Value:W},{Key:"ManagedBy",Value:"stacks"}]}),Y)console.log(` ${"Resource".padEnd(35)} ${"Type".padEnd(30)} Status`),console.log(" "+"\u2500".repeat(85)),await q.waitForStack(X,"stack-update-complete"),console.log("")}catch(I){if(I.message?.includes("No updates are to be performed"))console.log("\u2713 Stack is up to date (no changes)");else throw I}}else{console.log("Checking for retained resources...");try{let{S3Client:A}=await import("@stacksjs/ts-cloud"),h=new A(J),V=await L2(J),N=`${W}-${$}-assets-${V}`,B=`${W}-${$}-frontend-${V}`;if(G)console.log(` Checking bucket: ${N}`);try{await h.emptyAndDeleteBucket(N),console.log(`\u2713 Cleaned up existing bucket: ${N}`)}catch(v){if(!v.message?.includes("NoSuchBucket")&&!v.message?.includes("does not exist"))console.log(`\u26A0 Could not delete assets bucket: ${v.message}`);else if(G)console.log(" No existing assets bucket to clean up")}if(G)console.log(` Checking bucket: ${B}`);try{await h.emptyAndDeleteBucket(B),console.log(`\u2713 Cleaned up existing bucket: ${B}`)}catch(v){if(!v.message?.includes("NoSuchBucket")&&!v.message?.includes("does not exist"))console.log(`\u26A0 Could not delete frontend bucket: ${v.message}`);else if(G)console.log(" No existing frontend bucket to clean up")}}catch(A){console.log(`\u26A0 Pre-deployment cleanup error: ${A.message}`)}console.log("Creating stack..."),console.log("");let I=L?{templateURL:L}:{templateBody:_},j=await q.createStack({stackName:X,...I,capabilities:["CAPABILITY_IAM","CAPABILITY_NAMED_IAM"],tags:[{Key:"Environment",Value:$},{Key:"Project",Value:W},{Key:"ManagedBy",Value:"stacks"}],onFailure:"ROLLBACK",timeoutInMinutes:30});if(G)console.log(`Stack ID: ${j}`);if(Y)console.log(` ${"Resource".padEnd(35)} ${"Type".padEnd(30)} Status`),console.log(" "+"\u2500".repeat(85)),await q.waitForStack(X,"stack-create-complete"),console.log("")}let T=Z?.infrastructure?.dns?.domain||"stacksjs.com",f=Z?.infrastructure?.ssl||{enabled:!0,domains:[]},P=f.domains||[T,`www.${T}`];try{let I=(await q.describeStacks({stackName:X})).Stacks?.[0];if(I&&I.StackStatus){let j={};for(let A of I.Outputs||[])if(A.OutputKey&&A.OutputValue)j[A.OutputKey]=A.OutputValue;if(console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(""),console.log(" \u2713 Infrastructure deployed successfully"),console.log(""),console.log(` Stack: ${X}`),console.log(` Status: ${I.StackStatus}`),console.log(` Domain: https://${T}`),j.LoadBalancerDNS)console.log(` Load Balancer: ${j.LoadBalancerDNS}`);if(j.WebServerPublicIP)console.log(` Server IP: ${j.WebServerPublicIP}`);if(j.AssetsBucketName&&G)console.log(` Assets: ${j.AssetsBucketName}`);if(console.log(""),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(""),f.enabled&&Z?.infrastructure?.dns?.hostedZoneId&&j.LoadBalancerDNS)await A5({region:J,domain:T,sslDomains:P,hostedZoneId:Z.infrastructure.dns.hostedZoneId,albDnsName:j.LoadBalancerDNS,stackName:X});else if(!f.certificateArn&&G)console.log(" Next steps:"),console.log(" 1. DNS records need to be updated to point to the ALB"),console.log(" 2. SSL certificate needs to be requested and attached"),console.log(` Run: ./buddy cloud:ssl to set up SSL for ${T}`),console.log("")}}catch{}}catch(H){throw console.error(`Stack deployment failed: ${H.message}`),H}}async function f5(Q){let{environment:$,region:J,buildDir:Y}=Q,z=(await b7()).name;D7.info(`Deploying frontend from ${Y} to ${$} in ${J}...`);try{let{S3Client:W,AWSCloudFormationClient:X}=await import("@stacksjs/ts-cloud"),H=new W(J),q=new X(J),Z=`${z}-cloud`,_=(await q.describeStacks({stackName:Z})).Stacks?.[0]?.Outputs?.find((U)=>U.OutputKey==="AssetsBucketName")?.OutputValue;if(!_)throw Error("Assets bucket not found in stack outputs");D7.info(`Syncing ${Y} to s3://${_}/...`),await H.sync({source:Y,bucket:_,delete:!0,cacheControl:"max-age=31536000"}),D7.success("Frontend deployment completed!")}catch(W){throw D7.error(`Frontend deployment failed: ${W.message}`),W}}async function v5(Q){let{environment:$,region:J}=Q,z=`${(await b7()).name}-cloud`,{AWSCloudFormationClient:W}=await import("@stacksjs/ts-cloud"),X=new W(J);try{let H=(await X.describeStacks({stackName:z})).Stacks?.[0];if(!H||!H.StackStatus)return{status:"NOT_FOUND",outputs:{}};let q={};for(let Z of H.Outputs||[])if(Z.OutputKey&&Z.OutputValue)q[Z.OutputKey]=Z.OutputValue;return{status:H.StackStatus,outputs:q}}catch{return{status:"NOT_FOUND",outputs:{}}}}async function S5(Q){let{environment:$,region:J,verbose:Y}=Q,G=await b7(),W=`${G.name}-cloud`;console.log(`Undeploying ${W} from ${J}...`),console.log("");try{let{AWSCloudFormationClient:X,AWSClient:H}=await import("@stacksjs/ts-cloud"),q=new X(J),Z=!1;try{let K=(await q.describeStacks({stackName:W})).Stacks?.[0];if(K&&K.StackStatus){if(console.log(`Current status: ${F2(K.StackStatus)}`),Z=!0,K.StackStatus.endsWith("_IN_PROGRESS")){console.log(`Waiting for current operation (${K.StackStatus}) to finish...`);let _=K.StackStatus.startsWith("DELETE")?"stack-delete-complete":K.StackStatus.startsWith("CREATE")?"stack-create-complete":"stack-update-complete";try{await q.waitForStack(W,_)}catch{}try{let U=(await q.describeStacks({stackName:W})).Stacks?.[0];if(!U||!U.StackStatus||U.StackStatus==="DELETE_COMPLETE"){console.log("Stack was already deleted during the in-progress operation.");return}}catch{console.log("Stack was already deleted during the in-progress operation.");return}}if(K.StackStatus==="DELETE_COMPLETE")Z=!1}}catch{Z=!1}if(!Z){console.log(`Stack ${W} does not exist. Nothing to undeploy.`);return}if(Y)console.log("Checking for resources to clean up before deletion...");try{let K=new H,{AWSCloudFormationClient:_}=await import("@stacksjs/ts-cloud"),O=((await new _(J).listStackResources(W)).StackResourceSummaries||[]).find((M)=>M.LogicalResourceId==="ApplicationLoadBalancer");if(O?.PhysicalResourceId){let T={Action:"DescribeListeners",LoadBalancerArn:O.PhysicalResourceId,Version:"2015-12-01"},f=await K.request({service:"elasticloadbalancing",region:J,method:"POST",path:"/",body:new URLSearchParams(T).toString()}),P=f?.DescribeListenersResult?.Listeners?.member||f?.DescribeListenersResponse?.DescribeListenersResult?.Listeners?.member,I=Array.isArray(P)?P:P?[P]:[],j=0;for(let A of I)if(A.Protocol==="HTTPS"){if(Y)console.log(` Removing HTTPS listener on port ${A.Port}...`);let h={Action:"DeleteListener",ListenerArn:A.ListenerArn,Version:"2015-12-01"};await K.request({service:"elasticloadbalancing",region:J,method:"POST",path:"/",body:new URLSearchParams(h).toString()}),j++}if(j>0&&Y)console.log(`\u2713 Cleaned up ${j} HTTPS listener(s)`),await new Promise((A)=>setTimeout(A,2000))}}catch(K){if(Y)console.log(`Warning: ${K.message}`)}console.log("Deleting stack..."),console.log(""),await q.deleteStack(W),console.log(` ${"Resource".padEnd(35)} ${"Type".padEnd(30)} Status`),console.log(" "+"\u2500".repeat(85)),await q.waitForStack(W,"stack-delete-complete");try{let{S3Client:K}=await import("@stacksjs/ts-cloud"),_=new K(J),U=await L2(J),L=`${G.name}-${$}-assets-${U}`,F=`${G.name}-${$}-frontend-${U}`;console.log("Cleaning up retained buckets...");try{await _.emptyAndDeleteBucket(L),console.log("\u2713 Assets bucket deleted successfully")}catch(O){if(!O.message?.includes("NoSuchBucket")&&!O.message?.includes("does not exist"))console.log(`\u26A0 Could not delete assets bucket: ${O.message}`);else console.log("\u2713 No retained assets bucket to clean up")}try{await _.emptyAndDeleteBucket(F),console.log("\u2713 Frontend bucket deleted successfully")}catch(O){if(!O.message?.includes("NoSuchBucket")&&!O.message?.includes("does not exist"))console.log(`\u26A0 Could not delete frontend bucket: ${O.message}`);else console.log("\u2713 No retained frontend bucket to clean up")}}catch(K){console.log(`\u26A0 Cleanup error: ${K.message}`)}console.log(""),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(""),console.log(" \u2713 Infrastructure removed successfully"),console.log(""),console.log(` Stack: ${W}`),console.log(` Environment: ${$}`),console.log(` Region: ${J}`),console.log(""),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log("")}catch(X){let H=String(X.message||X);if(H.includes("does not exist")){console.log(""),console.log("\u2713 Stack already deleted or does not exist.");return}if(X.code==="DELETE_FAILED"||H.includes("DELETE_FAILED")){console.log(""),console.log("Some resources could not be deleted automatically"),console.log("Identifying resources to retain...");let{AWSCloudFormationClient:q}=await import("@stacksjs/ts-cloud"),Z=new q(J);try{let U=((await Z.listStackResources(W)).StackResourceSummaries||[]).filter((L)=>L.ResourceStatus==="DELETE_FAILED").map((L)=>L.LogicalResourceId);if(U.length>0){console.log(`Retaining ${U.length} resource(s):`),U.forEach((O)=>console.log(` - ${O}`)),console.log(""),console.log("Retrying deletion with retained resources..."),await Z.deleteStack(W,void 0,U);let{AWSCloudFormationClient:L}=await import("@stacksjs/ts-cloud");await new L(J).waitForStack(W,"stack-delete-complete"),console.log(""),console.log("\u2713 Stack removed (with retained resources)"),console.log(""),console.log("Note: Some resources were retained and may need manual cleanup."),console.log("Run `./buddy cloud:cleanup` to clean up remaining resources.");return}}catch(K){if(String(K.message||K).includes("does not exist")){console.log(""),console.log("\u2713 Stack deleted successfully!");return}throw K}}throw console.error(`Stack deletion failed: ${X.message}`),X}}var v3=()=>{};var P8={};f7(P8,{setup:()=>R8,optimizePantryDeps:()=>y3,ensurePantryInstalled:()=>T$,ensurePantryDependencies:()=>I$,ensureEnvIsSet:()=>u7,ensureAppKey:()=>g7});import{existsSync as k7,readFileSync as b3,writeFileSync as X8}from"fs";import{join as o$}from"path";import K$ from"process";import{runAction as q8,setupSSL as H8}from"@stacksjs/actions";import{log as o,onUnknownSubcommand as Z8,runCommand as t$}from"@stacksjs/cli";import{Action as K8}from"@stacksjs/enums";import{handleError as e$}from"@stacksjs/error-handling";import{path as x7}from"@stacksjs/path";import{copyFile as _8,storage as U8}from"@stacksjs/storage";import{ExitCode as M$}from"@stacksjs/types";function $7(Q,$){let J=Number(K$.env[Q]);if(Number.isFinite(J)&&J>0)return J;return $}function R8(Q){let $={setup:"This command ensures your project is setup correctly",ssl:"Setup SSL certificates and hosts file for HTTPS development",ohMyZsh:"Enable Oh My Zsh",aws:"Ensures AWS is connected to the project",project:"Target a specific project",verbose:"Enable verbose output",domain:"Custom domain to setup (defaults to APP_URL)",skipHosts:"Skip adding domain to hosts file",skipTrust:"Skip trusting the certificate",skipAws:"Skip AWS configuration during setup",skipKeygen:"Skip generating an application key during setup"};Q.command("setup",$.setup).alias("ensure").option("-p, --project [project]",$.project,{default:!1}).option("--skip-aws",$.skipAws,{default:!1}).option("--skip-keygen",$.skipKeygen,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{o.debug("Running `buddy setup` ...",J),await T$(),await y3(),await I8(J)}),Q.command("setup:ssl",$.ssl).alias("ssl:setup").option("-d, --domain [domain]",$.domain).option("--skip-hosts",$.skipHosts,{default:!1}).option("--skip-trust",$.skipTrust,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{if(o.debug("Running `buddy setup:ssl` ...",J),!await H8({domain:J.domain,skipHosts:J.skipHosts,skipTrust:J.skipTrust,verbose:J.verbose}))o.warn("SSL setup completed with warnings"),o.info("You may need to manually trust certificates or update hosts file")}),Q.command("setup:oh-my-zsh",$.ohMyZsh).alias("upgrade:oh-my-zsh").option("--verbose",$.verbose,{default:!1}).action(async(J)=>{o.debug("Running `buddy setup:oh-my-zsh` ...",J);let Y=await q8(K8.UpgradeShell);if(Y.isErr)o.error(Y.error),K$.exit(M$.FatalError)}),Z8(Q,"setup")}async function w8(){if((await t$("pantry --version",{silent:!0,timeoutMs:L8})).isOk)return!0;return!1}async function M8(){let Q=await t$(x7.frameworkPath("scripts/pantry-install"),{timeoutMs:F8});if(Q.isOk)return;e$(Q.error),K$.exit(M$.FatalError)}async function T$(){if(!await w8())await M8()}async function I$(Q){o.info("Installing Pantry dependencies...");let $=await t$("pantry install",{cwd:Q,timeoutMs:O8});if($.isOk){o.success("Installed Pantry dependencies");return}e$($.error),K$.exit(M$.FatalError)}function T8(Q){let $=o$(Q,".env");if(!k7($))return!1;return/^APP_KEY=.+$/m.test(b3($,"utf-8"))}async function g7(Q){if(T8(Q)){o.success("APP_KEY existed");return}let $=await t$("./buddy key:generate",{cwd:Q,timeoutMs:V8});if($.isErr)e$($.error),K$.exit(M$.FatalError);o.success("Generated application key")}async function I8(Q){let $=Q.cwd||x7.projectPath();if(await I$($),await u7(Q),!Q.skipKeygen)await g7($);if(!Q.skipAws){o.info("Ensuring AWS is connected...");let J=await t$("./buddy configure:aws",{cwd:$,timeoutMs:B8});if(J.isErr)e$(J.error),K$.exit(M$.FatalError);o.success("Configured AWS")}o.success("Project is setup"),o.info("Happy coding! \uD83D\uDC99")}function A8(Q){let $=o$(Q,".env"),J=o$(Q,".env.example"),Y=k7($)?$:k7(J)?J:void 0;if(!Y)return;let z=b3(Y,"utf-8").match(/^DB_CONNECTION=(.+)$/m);if(!z)return;let W=z[1].trim().replace(/['"]/g,"");return j8[W]}async function y3(){let Q=x7.projectPath(),$=o$(Q,"config","deps.ts");if(!k7($)){o.debug("No config/deps.ts found, skipping dependency optimization");return}let J={};try{let W=await import($),X=W.config||W.default;if(X?.dependencies)J={...X.dependencies}}catch(W){o.debug("Could not load config/deps.ts, skipping dependency optimization");return}let Y=A8(Q);if(Y){if(!Object.keys(J).some((X)=>X===Y||X.startsWith(`${Y}/`)))o.info(`Detected DB_CONNECTION requires ${Y}, adding to dependencies`),J[Y]="*"}let G=["# Auto-generated from config/deps.ts and .env sniffing.","# This file is regenerated on each `buddy setup` run.","#","# To learn more, please visit:","# https://stacksjs.com/docs/dependency-management","","dependencies:"];for(let[W,X]of Object.entries(J))G.push(` ${W}: ${X}`);let z=o$(Q,"deps.yaml");X8(z,`${G.join(`
97
97
  `)}
98
- `),o.success("Generated deps.yaml from config/deps.ts")}async function u7(Q){o.info("Ensuring .env exists...");let $=Q.cwd||x7.projectPath(),J=`${$}/.env`,Y=`${$}/.env.example`;if(U5.doesNotExist(J)){try{_5(Y,J)}catch(G){e$(G),K$.exit(M$.FatalError)}o.success(".env created")}else o.success(".env existed")}var L5,F5,O5,V5,B5,j5;var m7=p(()=>{L5=$7("PANTRY_CHECK_TIMEOUT_MS",15000),F5=$7("PANTRY_INSTALL_TIMEOUT_MS",600000),O5=$7("PANTRY_DEPENDENCIES_TIMEOUT_MS",1200000),V5=$7("KEYGEN_TIMEOUT_MS",120000),B5=$7("AWS_CONFIG_TIMEOUT_MS",900000);j5={postgres:"postgresql.org",mysql:"mysql.com",sqlite:"sqlite.org"}});function i7(Q,$){let J=[],Y=$.exec(Q);while(Y){let G=[];G.startIndex=$.lastIndex-Y[0].length;let z=Y.length;for(let W=0;W<z;W++)G.push(Y[W]);J.push(G),Y=$.exec(Q)}return J}function B1(Q){return typeof Q<"u"}var bQ=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",yQ,kQ,E$=function(Q){let $=kQ.exec(Q);return!($===null||typeof $>"u")},z7,s7;var W7=p(()=>{yQ="[:A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]["+bQ+"]*",kQ=new RegExp("^"+yQ+"$");z7=["hasOwnProperty","toString","valueOf","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"],s7=["__proto__","constructor","prototype"]});function I1(Q,$){$=Object.assign({},xQ,$);let J=[],Y=!1,G=!1;if(Q[0]==="\uFEFF")Q=Q.substr(1);for(let z=0;z<Q.length;z++)if(Q[z]==="<"&&Q[z+1]==="?"){if(z+=2,z=w1(Q,z),z.err)return z}else if(Q[z]==="<"){let W=z;if(z++,Q[z]==="!"){z=M1(Q,z);continue}else{let X=!1;if(Q[z]==="/")X=!0,z++;let H="";for(;z<Q.length&&Q[z]!==">"&&Q[z]!==" "&&Q[z]!=="\t"&&Q[z]!==`
98
+ `),o.success("Generated deps.yaml from config/deps.ts")}async function u7(Q){o.info("Ensuring .env exists...");let $=Q.cwd||x7.projectPath(),J=`${$}/.env`,Y=`${$}/.env.example`;if(U8.doesNotExist(J)){try{_8(Y,J)}catch(G){e$(G),K$.exit(M$.FatalError)}o.success(".env created")}else o.success(".env existed")}var L8,F8,O8,V8,B8,j8;var m7=p(()=>{L8=$7("PANTRY_CHECK_TIMEOUT_MS",15000),F8=$7("PANTRY_INSTALL_TIMEOUT_MS",600000),O8=$7("PANTRY_DEPENDENCIES_TIMEOUT_MS",1200000),V8=$7("KEYGEN_TIMEOUT_MS",120000),B8=$7("AWS_CONFIG_TIMEOUT_MS",900000);j8={postgres:"postgresql.org",mysql:"mysql.com",sqlite:"sqlite.org"}});function i7(Q,$){let J=[],Y=$.exec(Q);while(Y){let G=[];G.startIndex=$.lastIndex-Y[0].length;let z=Y.length;for(let W=0;W<z;W++)G.push(Y[W]);J.push(G),Y=$.exec(Q)}return J}function B1(Q){return typeof Q<"u"}var bQ=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",yQ,kQ,E$=function(Q){let $=kQ.exec(Q);return!($===null||typeof $>"u")},z7,s7;var W7=p(()=>{yQ="[:A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]["+bQ+"]*",kQ=new RegExp("^"+yQ+"$");z7=["hasOwnProperty","toString","valueOf","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"],s7=["__proto__","constructor","prototype"]});function I1(Q,$){$=Object.assign({},xQ,$);let J=[],Y=!1,G=!1;if(Q[0]==="\uFEFF")Q=Q.substr(1);for(let z=0;z<Q.length;z++)if(Q[z]==="<"&&Q[z+1]==="?"){if(z+=2,z=w1(Q,z),z.err)return z}else if(Q[z]==="<"){let W=z;if(z++,Q[z]==="!"){z=M1(Q,z);continue}else{let X=!1;if(Q[z]==="/")X=!0,z++;let H="";for(;z<Q.length&&Q[z]!==">"&&Q[z]!==" "&&Q[z]!=="\t"&&Q[z]!==`
99
99
  `&&Q[z]!=="\r";z++)H+=Q[z];if(H=H.trim(),H[H.length-1]==="/")H=H.substring(0,H.length-1),z--;if(!rQ(H)){let K;if(H.trim().length===0)K="Invalid space after '<'.";else K="Tag '"+H+"' is an invalid name.";return t("InvalidTag",K,_0(Q,z))}let q=mQ(Q,z);if(q===!1)return t("InvalidAttr","Attributes for '"+H+"' have open quote.",_0(Q,z));let Z=q.value;if(z=q.index,Z[Z.length-1]==="/"){let K=z-Z.length;Z=Z.substring(0,Z.length-1);let _=T1(Z,$);if(_===!0)Y=!0;else return t(_.err.code,_.err.msg,_0(Q,K+_.err.line))}else if(X)if(!q.tagClosed)return t("InvalidTag","Closing tag '"+H+"' doesn't have proper closing.",_0(Q,z));else if(Z.trim().length>0)return t("InvalidTag","Closing tag '"+H+"' can't have attributes or invalid starting.",_0(Q,W));else if(J.length===0)return t("InvalidTag","Closing tag '"+H+"' has not been opened.",_0(Q,W));else{let K=J.pop();if(H!==K.tagName){let _=_0(Q,K.tagStartPos);return t("InvalidTag","Expected closing tag '"+K.tagName+"' (opened in line "+_.line+", col "+_.col+") instead of closing tag '"+H+"'.",_0(Q,W))}if(J.length==0)G=!0}else{let K=T1(Z,$);if(K!==!0)return t(K.err.code,K.err.msg,_0(Q,z-Z.length+K.err.line));if(G===!0)return t("InvalidXml","Multiple possible root nodes found.",_0(Q,z));else if($.unpairedTags.indexOf(H)!==-1);else J.push({tagName:H,tagStartPos:W});Y=!0}for(z++;z<Q.length;z++)if(Q[z]==="<")if(Q[z+1]==="!"){z++,z=M1(Q,z);continue}else if(Q[z+1]==="?"){if(z=w1(Q,++z),z.err)return z}else break;else if(Q[z]==="&"){let K=dQ(Q,z);if(K==-1)return t("InvalidChar","char '&' is not expected.",_0(Q,z));z=K}else if(G===!0&&!R1(Q[z]))return t("InvalidXml","Extra text at the end",_0(Q,z));if(Q[z]==="<")z--}}else{if(R1(Q[z]))continue;return t("InvalidChar","char '"+Q[z]+"' is not expected.",_0(Q,z))}if(!Y)return t("InvalidXml","Start tag expected.",1);else if(J.length==1)return t("InvalidTag","Unclosed tag '"+J[0].tagName+"'.",_0(Q,J[0].tagStartPos));else if(J.length>0)return t("InvalidXml","Invalid '"+JSON.stringify(J.map((z)=>z.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1});return!0}function R1(Q){return Q===" "||Q==="\t"||Q===`
100
100
  `||Q==="\r"}function w1(Q,$){let J=$;for(;$<Q.length;$++)if(Q[$]=="?"||Q[$]==" "){let Y=Q.substr(J,$-J);if($>5&&Y==="xml")return t("InvalidXml","XML declaration allowed only at the start of the document.",_0(Q,$));else if(Q[$]=="?"&&Q[$+1]==">"){$++;break}else continue}return $}function M1(Q,$){if(Q.length>$+5&&Q[$+1]==="-"&&Q[$+2]==="-"){for($+=3;$<Q.length;$++)if(Q[$]==="-"&&Q[$+1]==="-"&&Q[$+2]===">"){$+=2;break}}else if(Q.length>$+8&&Q[$+1]==="D"&&Q[$+2]==="O"&&Q[$+3]==="C"&&Q[$+4]==="T"&&Q[$+5]==="Y"&&Q[$+6]==="P"&&Q[$+7]==="E"){let J=1;for($+=8;$<Q.length;$++)if(Q[$]==="<")J++;else if(Q[$]===">"){if(J--,J===0)break}}else if(Q.length>$+9&&Q[$+1]==="["&&Q[$+2]==="C"&&Q[$+3]==="D"&&Q[$+4]==="A"&&Q[$+5]==="T"&&Q[$+6]==="A"&&Q[$+7]==="["){for($+=8;$<Q.length;$++)if(Q[$]==="]"&&Q[$+1]==="]"&&Q[$+2]===">"){$+=2;break}}return $}function mQ(Q,$){let J="",Y="",G=!1;for(;$<Q.length;$++){if(Q[$]===gQ||Q[$]===uQ)if(Y==="")Y=Q[$];else if(Y!==Q[$]);else Y="";else if(Q[$]===">"){if(Y===""){G=!0;break}}J+=Q[$]}if(Y!=="")return!1;return{value:J,index:$,tagClosed:G}}function T1(Q,$){let J=i7(Q,cQ),Y={};for(let G=0;G<J.length;G++){if(J[G][1].length===0)return t("InvalidAttr","Attribute '"+J[G][2]+"' has no space in starting.",X7(J[G]));else if(J[G][3]!==void 0&&J[G][4]===void 0)return t("InvalidAttr","Attribute '"+J[G][2]+"' is without value.",X7(J[G]));else if(J[G][3]===void 0&&!$.allowBooleanAttributes)return t("InvalidAttr","boolean attribute '"+J[G][2]+"' is not allowed.",X7(J[G]));let z=J[G][2];if(!pQ(z))return t("InvalidAttr","Attribute '"+z+"' is an invalid name.",X7(J[G]));if(!Object.prototype.hasOwnProperty.call(Y,z))Y[z]=1;else return t("InvalidAttr","Attribute '"+z+"' is repeated.",X7(J[G]))}return!0}function lQ(Q,$){let J=/\d/;if(Q[$]==="x")$++,J=/[\da-fA-F]/;for(;$<Q.length;$++){if(Q[$]===";")return $;if(!Q[$].match(J))break}return-1}function dQ(Q,$){if($++,Q[$]===";")return-1;if(Q[$]==="#")return $++,lQ(Q,$);let J=0;for(;$<Q.length;$++,J++){if(Q[$].match(/\w/)&&J<20)continue;if(Q[$]===";")break;return-1}return $}function t(Q,$,J){return{err:{code:Q,msg:$,line:J.line||J,col:J.col}}}function pQ(Q){return E$(Q)}function rQ(Q){return E$(Q)}function _0(Q,$){let J=Q.substring(0,$).split(/\r?\n/);return{line:J.length,col:J[J.length-1].length+1}}function X7(Q){return Q.startIndex+Q[1].length}var xQ,gQ='"',uQ="'",cQ;var j1=p(()=>{W7();xQ={allowBooleanAttributes:!1,unpairedTags:[]};cQ=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g")});var A1,P1,f1,v1,S1,E1,N1,C1,h1,D1,o7,b1,y1,nQ,q7,C2;var h2=p(()=>{A1={amp:"&",AMP:"&",lt:"<",LT:"<",gt:">",GT:">",quot:'"',QUOT:'"',apos:"'",lsquo:"\u2018",rsquo:"\u2019",ldquo:"\u201C",rdquo:"\u201D",lsquor:"\u201A",rsquor:"\u2019",ldquor:"\u201E",bdquo:"\u201E",comma:",",period:".",colon:":",semi:";",excl:"!",quest:"?",num:"#",dollar:"$",percent:"%",amp:"&",ast:"*",commat:"@",lowbar:"_",verbar:"|",vert:"|",sol:"/",bsol:"\\",lbrace:"{",rbrace:"}",lbrack:"[",rbrack:"]",lpar:"(",rpar:")",nbsp:"\xA0",iexcl:"\xA1",cent:"\xA2",pound:"\xA3",curren:"\xA4",yen:"\xA5",brvbar:"\xA6",sect:"\xA7",uml:"\xA8",copy:"\xA9",COPY:"\xA9",ordf:"\xAA",laquo:"\xAB",not:"\xAC",shy:"\xAD",reg:"\xAE",REG:"\xAE",macr:"\xAF",deg:"\xB0",plusmn:"\xB1",sup2:"\xB2",sup3:"\xB3",acute:"\xB4",micro:"\xB5",para:"\xB6",middot:"\xB7",cedil:"\xB8",sup1:"\xB9",ordm:"\xBA",raquo:"\xBB",frac14:"\xBC",frac12:"\xBD",half:"\xBD",frac34:"\xBE",iquest:"\xBF",times:"\xD7",div:"\xF7",divide:"\xF7"},P1={Agrave:"\xC0",agrave:"\xE0",Aacute:"\xC1",aacute:"\xE1",Acirc:"\xC2",acirc:"\xE2",Atilde:"\xC3",atilde:"\xE3",Auml:"\xC4",auml:"\xE4",Aring:"\xC5",aring:"\xE5",AElig:"\xC6",aelig:"\xE6",Ccedil:"\xC7",ccedil:"\xE7",Egrave:"\xC8",egrave:"\xE8",Eacute:"\xC9",eacute:"\xE9",Ecirc:"\xCA",ecirc:"\xEA",Euml:"\xCB",euml:"\xEB",Igrave:"\xCC",igrave:"\xEC",Iacute:"\xCD",iacute:"\xED",Icirc:"\xCE",icirc:"\xEE",Iuml:"\xCF",iuml:"\xEF",ETH:"\xD0",eth:"\xF0",Ntilde:"\xD1",ntilde:"\xF1",Ograve:"\xD2",ograve:"\xF2",Oacute:"\xD3",oacute:"\xF3",Ocirc:"\xD4",ocirc:"\xF4",Otilde:"\xD5",otilde:"\xF5",Ouml:"\xD6",ouml:"\xF6",Oslash:"\xD8",oslash:"\xF8",Ugrave:"\xD9",ugrave:"\xF9",Uacute:"\xDA",uacute:"\xFA",Ucirc:"\xDB",ucirc:"\xFB",Uuml:"\xDC",uuml:"\xFC",Yacute:"\xDD",yacute:"\xFD",THORN:"\xDE",thorn:"\xFE",szlig:"\xDF",yuml:"\xFF",Yuml:"\u0178"},f1={Amacr:"\u0100",amacr:"\u0101",Abreve:"\u0102",abreve:"\u0103",Aogon:"\u0104",aogon:"\u0105",Cacute:"\u0106",cacute:"\u0107",Ccirc:"\u0108",ccirc:"\u0109",Cdot:"\u010A",cdot:"\u010B",Ccaron:"\u010C",ccaron:"\u010D",Dcaron:"\u010E",dcaron:"\u010F",Dstrok:"\u0110",dstrok:"\u0111",Emacr:"\u0112",emacr:"\u0113",Ecaron:"\u011A",ecaron:"\u011B",Edot:"\u0116",edot:"\u0117",Eogon:"\u0118",eogon:"\u0119",Gcirc:"\u011C",gcirc:"\u011D",Gbreve:"\u011E",gbreve:"\u011F",Gdot:"\u0120",gdot:"\u0121",Gcedil:"\u0122",Hcirc:"\u0124",hcirc:"\u0125",Hstrok:"\u0126",hstrok:"\u0127",Itilde:"\u0128",itilde:"\u0129",Imacr:"\u012A",imacr:"\u012B",Iogon:"\u012E",iogon:"\u012F",Idot:"\u0130",IJlig:"\u0132",ijlig:"\u0133",Jcirc:"\u0134",jcirc:"\u0135",Kcedil:"\u0136",kcedil:"\u0137",kgreen:"\u0138",Lacute:"\u0139",lacute:"\u013A",Lcedil:"\u013B",lcedil:"\u013C",Lcaron:"\u013D",lcaron:"\u013E",Lmidot:"\u013F",lmidot:"\u0140",Lstrok:"\u0141",lstrok:"\u0142",Nacute:"\u0143",nacute:"\u0144",Ncaron:"\u0147",ncaron:"\u0148",Ncedil:"\u0145",ncedil:"\u0146",ENG:"\u014A",eng:"\u014B",Omacr:"\u014C",omacr:"\u014D",Odblac:"\u0150",odblac:"\u0151",OElig:"\u0152",oelig:"\u0153",Racute:"\u0154",racute:"\u0155",Rcaron:"\u0158",rcaron:"\u0159",Rcedil:"\u0156",rcedil:"\u0157",Sacute:"\u015A",sacute:"\u015B",Scirc:"\u015C",scirc:"\u015D",Scedil:"\u015E",scedil:"\u015F",Scaron:"\u0160",scaron:"\u0161",Tcedil:"\u0162",tcedil:"\u0163",Tcaron:"\u0164",tcaron:"\u0165",Tstrok:"\u0166",tstrok:"\u0167",Utilde:"\u0168",utilde:"\u0169",Umacr:"\u016A",umacr:"\u016B",Ubreve:"\u016C",ubreve:"\u016D",Uring:"\u016E",uring:"\u016F",Udblac:"\u0170",udblac:"\u0171",Uogon:"\u0172",uogon:"\u0173",Wcirc:"\u0174",wcirc:"\u0175",Ycirc:"\u0176",ycirc:"\u0177",Zacute:"\u0179",zacute:"\u017A",Zdot:"\u017B",zdot:"\u017C",Zcaron:"\u017D",zcaron:"\u017E"},v1={Alpha:"\u0391",alpha:"\u03B1",Beta:"\u0392",beta:"\u03B2",Gamma:"\u0393",gamma:"\u03B3",Delta:"\u0394",delta:"\u03B4",Epsilon:"\u0395",epsilon:"\u03B5",epsiv:"\u03F5",varepsilon:"\u03F5",Zeta:"\u0396",zeta:"\u03B6",Eta:"\u0397",eta:"\u03B7",Theta:"\u0398",theta:"\u03B8",thetasym:"\u03D1",vartheta:"\u03D1",Iota:"\u0399",iota:"\u03B9",Kappa:"\u039A",kappa:"\u03BA",kappav:"\u03F0",varkappa:"\u03F0",Lambda:"\u039B",lambda:"\u03BB",Mu:"\u039C",mu:"\u03BC",Nu:"\u039D",nu:"\u03BD",Xi:"\u039E",xi:"\u03BE",Omicron:"\u039F",omicron:"\u03BF",Pi:"\u03A0",pi:"\u03C0",piv:"\u03D6",varpi:"\u03D6",Rho:"\u03A1",rho:"\u03C1",rhov:"\u03F1",varrho:"\u03F1",Sigma:"\u03A3",sigma:"\u03C3",sigmaf:"\u03C2",sigmav:"\u03C2",varsigma:"\u03C2",Tau:"\u03A4",tau:"\u03C4",Upsilon:"\u03A5",upsilon:"\u03C5",upsi:"\u03C5",Upsi:"\u03D2",upsih:"\u03D2",Phi:"\u03A6",phi:"\u03C6",phiv:"\u03D5",varphi:"\u03D5",Chi:"\u03A7",chi:"\u03C7",Psi:"\u03A8",psi:"\u03C8",Omega:"\u03A9",omega:"\u03C9",ohm:"\u03A9",Gammad:"\u03DC",gammad:"\u03DD",digamma:"\u03DD"},S1={Afr:"\uD835\uDD04",afr:"\uD835\uDD1E",Acy:"\u0410",acy:"\u0430",Bcy:"\u0411",bcy:"\u0431",Vcy:"\u0412",vcy:"\u0432",Gcy:"\u0413",gcy:"\u0433",Dcy:"\u0414",dcy:"\u0434",IEcy:"\u0415",iecy:"\u0435",IOcy:"\u0401",iocy:"\u0451",ZHcy:"\u0416",zhcy:"\u0436",Zcy:"\u0417",zcy:"\u0437",Icy:"\u0418",icy:"\u0438",Jcy:"\u0419",jcy:"\u0439",Kcy:"\u041A",kcy:"\u043A",Lcy:"\u041B",lcy:"\u043B",Mcy:"\u041C",mcy:"\u043C",Ncy:"\u041D",ncy:"\u043D",Ocy:"\u041E",ocy:"\u043E",Pcy:"\u041F",pcy:"\u043F",Rcy:"\u0420",rcy:"\u0440",Scy:"\u0421",scy:"\u0441",Tcy:"\u0422",tcy:"\u0442",Ucy:"\u0423",ucy:"\u0443",Fcy:"\u0424",fcy:"\u0444",KHcy:"\u0425",khcy:"\u0445",TScy:"\u0426",tscy:"\u0446",CHcy:"\u0427",chcy:"\u0447",SHcy:"\u0428",shcy:"\u0448",SHCHcy:"\u0429",shchcy:"\u0449",HARDcy:"\u042A",hardcy:"\u044A",Ycy:"\u042B",ycy:"\u044B",SOFTcy:"\u042C",softcy:"\u044C",Ecy:"\u042D",ecy:"\u044D",YUcy:"\u042E",yucy:"\u044E",YAcy:"\u042F",yacy:"\u044F",DJcy:"\u0402",djcy:"\u0452",GJcy:"\u0403",gjcy:"\u0453",Jukcy:"\u0404",jukcy:"\u0454",DScy:"\u0405",dscy:"\u0455",Iukcy:"\u0406",iukcy:"\u0456",YIcy:"\u0407",yicy:"\u0457",Jsercy:"\u0408",jsercy:"\u0458",LJcy:"\u0409",ljcy:"\u0459",NJcy:"\u040A",njcy:"\u045A",TSHcy:"\u040B",tshcy:"\u045B",KJcy:"\u040C",kjcy:"\u045C",Ubrcy:"\u040E",ubrcy:"\u045E",DZcy:"\u040F",dzcy:"\u045F"},E1={plus:"+",minus:"\u2212",mnplus:"\u2213",mp:"\u2213",pm:"\xB1",times:"\xD7",div:"\xF7",divide:"\xF7",sdot:"\u22C5",star:"\u2606",starf:"\u2605",bigstar:"\u2605",lowast:"\u2217",ast:"*",midast:"*",compfn:"\u2218",smallcircle:"\u2218",bullet:"\u2022",bull:"\u2022",nbsp:"\xA0",hellip:"\u2026",mldr:"\u2026",prime:"\u2032",Prime:"\u2033",tprime:"\u2034",bprime:"\u2035",backprime:"\u2035",minus:"\u2212",minusd:"\u2238",dotminus:"\u2238",plusdo:"\u2214",dotplus:"\u2214",plusmn:"\xB1",minusplus:"\u2213",mnplus:"\u2213",mp:"\u2213",setminus:"\u2216",smallsetminus:"\u2216",Backslash:"\u2216",setmn:"\u2216",ssetmn:"\u2216",lowbar:"_",verbar:"|",vert:"|",VerticalLine:"|",colon:":",Colon:"\u2237",Proportion:"\u2237",ratio:"\u2236",equals:"=",ne:"\u2260",nequiv:"\u2262",equiv:"\u2261",Congruent:"\u2261",sim:"\u223C",thicksim:"\u223C",thksim:"\u223C",sime:"\u2243",simeq:"\u2243",TildeEqual:"\u2243",asymp:"\u2248",approx:"\u2248",thickapprox:"\u2248",thkap:"\u2248",TildeTilde:"\u2248",ncong:"\u2247",cong:"\u2245",TildeFullEqual:"\u2245",asympeq:"\u224D",CupCap:"\u224D",bump:"\u224E",Bumpeq:"\u224E",HumpDownHump:"\u224E",bumpe:"\u224F",bumpeq:"\u224F",HumpEqual:"\u224F",dotminus:"\u2238",minusd:"\u2238",plusdo:"\u2214",dotplus:"\u2214",le:"\u2264",LessEqual:"\u2264",ge:"\u2265",GreaterEqual:"\u2265",lesseqgtr:"\u22DA",lesseqqgtr:"\u2A8B",greater:">",less:"<"},N1={alefsym:"\u2135",aleph:"\u2135",beth:"\u2136",gimel:"\u2137",daleth:"\u2138",forall:"\u2200",ForAll:"\u2200",part:"\u2202",PartialD:"\u2202",exist:"\u2203",Exists:"\u2203",nexist:"\u2204",nexists:"\u2204",empty:"\u2205",emptyset:"\u2205",emptyv:"\u2205",varnothing:"\u2205",nabla:"\u2207",Del:"\u2207",isin:"\u2208",isinv:"\u2208",in:"\u2208",Element:"\u2208",notin:"\u2209",notinva:"\u2209",ni:"\u220B",niv:"\u220B",SuchThat:"\u220B",ReverseElement:"\u220B",notni:"\u220C",notniva:"\u220C",prod:"\u220F",Product:"\u220F",coprod:"\u2210",Coproduct:"\u2210",sum:"\u2211",Sum:"\u2211",minus:"\u2212",mp:"\u2213",plusdo:"\u2214",dotplus:"\u2214",setminus:"\u2216",lowast:"\u2217",radic:"\u221A",Sqrt:"\u221A",prop:"\u221D",propto:"\u221D",Proportional:"\u221D",varpropto:"\u221D",infin:"\u221E",infintie:"\u29DD",ang:"\u2220",angle:"\u2220",angmsd:"\u2221",measuredangle:"\u2221",angsph:"\u2222",mid:"\u2223",VerticalBar:"\u2223",nmid:"\u2224",nsmid:"\u2224",npar:"\u2226",parallel:"\u2225",spar:"\u2225",nparallel:"\u2226",nspar:"\u2226",and:"\u2227",wedge:"\u2227",or:"\u2228",vee:"\u2228",cap:"\u2229",cup:"\u222A",int:"\u222B",Integral:"\u222B",conint:"\u222E",ContourIntegral:"\u222E",Conint:"\u222F",DoubleContourIntegral:"\u222F",Cconint:"\u2230",there4:"\u2234",therefore:"\u2234",Therefore:"\u2234",becaus:"\u2235",because:"\u2235",Because:"\u2235",ratio:"\u2236",Proportion:"\u2237",minusd:"\u2238",dotminus:"\u2238",mDDot:"\u223A",homtht:"\u223B",sim:"\u223C",bsimg:"\u223D",backsim:"\u223D",ac:"\u223E",mstpos:"\u223E",acd:"\u223F",VerticalTilde:"\u2240",wr:"\u2240",wreath:"\u2240",nsime:"\u2244",nsimeq:"\u2244",nsimeq:"\u2244",ncong:"\u2247",simne:"\u2246",ncongdot:"\u2A6D\u0338",ngsim:"\u2275",nsim:"\u2241",napprox:"\u2249",nap:"\u2249",ngeq:"\u2271",nge:"\u2271",nleq:"\u2270",nle:"\u2270",ngtr:"\u226F",ngt:"\u226F",nless:"\u226E",nlt:"\u226E",nprec:"\u2280",npr:"\u2280",nsucc:"\u2281",nsc:"\u2281"},C1={larr:"\u2190",leftarrow:"\u2190",LeftArrow:"\u2190",uarr:"\u2191",uparrow:"\u2191",UpArrow:"\u2191",rarr:"\u2192",rightarrow:"\u2192",RightArrow:"\u2192",darr:"\u2193",downarrow:"\u2193",DownArrow:"\u2193",harr:"\u2194",leftrightarrow:"\u2194",LeftRightArrow:"\u2194",varr:"\u2195",updownarrow:"\u2195",UpDownArrow:"\u2195",nwarr:"\u2196",nwarrow:"\u2196",UpperLeftArrow:"\u2196",nearr:"\u2197",nearrow:"\u2197",UpperRightArrow:"\u2197",searr:"\u2198",searrow:"\u2198",LowerRightArrow:"\u2198",swarr:"\u2199",swarrow:"\u2199",LowerLeftArrow:"\u2199",lArr:"\u21D0",Leftarrow:"\u21D0",uArr:"\u21D1",Uparrow:"\u21D1",rArr:"\u21D2",Rightarrow:"\u21D2",dArr:"\u21D3",Downarrow:"\u21D3",hArr:"\u21D4",Leftrightarrow:"\u21D4",iff:"\u21D4",vArr:"\u21D5",Updownarrow:"\u21D5",lAarr:"\u21DA",Lleftarrow:"\u21DA",rAarr:"\u21DB",Rrightarrow:"\u21DB",lrarr:"\u21C6",leftrightarrows:"\u21C6",rlarr:"\u21C4",rightleftarrows:"\u21C4",lrhar:"\u21CB",leftrightharpoons:"\u21CB",ReverseEquilibrium:"\u21CB",rlhar:"\u21CC",rightleftharpoons:"\u21CC",Equilibrium:"\u21CC",udarr:"\u21C5",UpArrowDownArrow:"\u21C5",duarr:"\u21F5",DownArrowUpArrow:"\u21F5",llarr:"\u21C7",leftleftarrows:"\u21C7",rrarr:"\u21C9",rightrightarrows:"\u21C9",ddarr:"\u21CA",downdownarrows:"\u21CA",har:"\u21BD",lhard:"\u21BD",leftharpoondown:"\u21BD",lharu:"\u21BC",leftharpoonup:"\u21BC",rhard:"\u21C1",rightharpoondown:"\u21C1",rharu:"\u21C0",rightharpoonup:"\u21C0",lsh:"\u21B0",Lsh:"\u21B0",rsh:"\u21B1",Rsh:"\u21B1",ldsh:"\u21B2",rdsh:"\u21B3",hookleftarrow:"\u21A9",hookrightarrow:"\u21AA",mapstoleft:"\u21A4",mapstoup:"\u21A5",map:"\u21A6",mapsto:"\u21A6",mapstodown:"\u21A7",crarr:"\u21B5",nwarrow:"\u2196",nearrow:"\u2197",searrow:"\u2198",swarrow:"\u2199",nleftarrow:"\u219A",nleftrightarrow:"\u21AE",nrightarrow:"\u219B",nrarr:"\u219B",larrtl:"\u21A2",rarrtl:"\u21A3",leftarrowtail:"\u21A2",rightarrowtail:"\u21A3",twoheadleftarrow:"\u219E",twoheadrightarrow:"\u21A0",Larr:"\u219E",Rarr:"\u21A0",larrhk:"\u21A9",rarrhk:"\u21AA",larrlp:"\u21AB",looparrowleft:"\u21AB",rarrlp:"\u21AC",looparrowright:"\u21AC",harrw:"\u21AD",leftrightsquigarrow:"\u21AD",nrarrw:"\u219D\u0338",rarrw:"\u219D",rightsquigarrow:"\u219D",larrbfs:"\u291F",rarrbfs:"\u2920",nvHarr:"\u2904",nvlArr:"\u2902",nvrArr:"\u2903",larrfs:"\u291D",rarrfs:"\u291E",Map:"\u2905",larrsim:"\u2973",rarrsim:"\u2974",harrcir:"\u2948",Uarrocir:"\u2949",lurdshar:"\u294A",ldrdhar:"\u2967",ldrushar:"\u294B",rdldhar:"\u2969",lrhard:"\u296D",rlhar:"\u21CC",uharr:"\u21BE",uharl:"\u21BF",dharr:"\u21C2",dharl:"\u21C3",Uarr:"\u219F",Darr:"\u21A1",zigrarr:"\u21DD",nwArr:"\u21D6",neArr:"\u21D7",seArr:"\u21D8",swArr:"\u21D9",nharr:"\u21AE",nhArr:"\u21CE",nlarr:"\u219A",nlArr:"\u21CD",nrarr:"\u219B",nrArr:"\u21CF",larrb:"\u21E4",LeftArrowBar:"\u21E4",rarrb:"\u21E5",RightArrowBar:"\u21E5"},h1={square:"\u25A1",Square:"\u25A1",squ:"\u25A1",squf:"\u25AA",squarf:"\u25AA",blacksquar:"\u25AA",blacksquare:"\u25AA",FilledVerySmallSquare:"\u25AA",blk34:"\u2593",blk12:"\u2592",blk14:"\u2591",block:"\u2588",srect:"\u25AD",rect:"\u25AD",sdot:"\u22C5",sdotb:"\u22A1",dotsquare:"\u22A1",triangle:"\u25B5",tri:"\u25B5",trine:"\u25B5",utri:"\u25B5",triangledown:"\u25BF",dtri:"\u25BF",tridown:"\u25BF",triangleleft:"\u25C3",ltri:"\u25C3",triangleright:"\u25B9",rtri:"\u25B9",blacktriangle:"\u25B4",utrif:"\u25B4",blacktriangledown:"\u25BE",dtrif:"\u25BE",blacktriangleleft:"\u25C2",ltrif:"\u25C2",blacktriangleright:"\u25B8",rtrif:"\u25B8",loz:"\u25CA",lozenge:"\u25CA",blacklozenge:"\u29EB",lozf:"\u29EB",bigcirc:"\u25EF",xcirc:"\u25EF",circ:"\u02C6",Circle:"\u25CB",cir:"\u25CB",o:"\u25CB",bullet:"\u2022",bull:"\u2022",hellip:"\u2026",mldr:"\u2026",nldr:"\u2025",boxh:"\u2500",HorizontalLine:"\u2500",boxv:"\u2502",boxdr:"\u250C",boxdl:"\u2510",boxur:"\u2514",boxul:"\u2518",boxvr:"\u251C",boxvl:"\u2524",boxhd:"\u252C",boxhu:"\u2534",boxvh:"\u253C",boxH:"\u2550",boxV:"\u2551",boxdR:"\u2552",boxDr:"\u2553",boxDR:"\u2554",boxDl:"\u2555",boxdL:"\u2556",boxDL:"\u2557",boxuR:"\u2558",boxUr:"\u2559",boxUR:"\u255A",boxUl:"\u255C",boxuL:"\u255B",boxUL:"\u255D",boxvR:"\u255E",boxVr:"\u255F",boxVR:"\u2560",boxVl:"\u2562",boxvL:"\u2561",boxVL:"\u2563",boxHd:"\u2564",boxhD:"\u2565",boxHD:"\u2566",boxHu:"\u2567",boxhU:"\u2568",boxHU:"\u2569",boxvH:"\u256A",boxVh:"\u256B",boxVH:"\u256C"},D1={excl:"!",iexcl:"\xA1",brvbar:"\xA6",sect:"\xA7",uml:"\xA8",copy:"\xA9",ordf:"\xAA",laquo:"\xAB",not:"\xAC",shy:"\xAD",reg:"\xAE",macr:"\xAF",deg:"\xB0",plusmn:"\xB1",sup2:"\xB2",sup3:"\xB3",acute:"\xB4",micro:"\xB5",para:"\xB6",middot:"\xB7",cedil:"\xB8",sup1:"\xB9",ordm:"\xBA",raquo:"\xBB",frac14:"\xBC",frac12:"\xBD",frac34:"\xBE",iquest:"\xBF",nbsp:"\xA0",comma:",",period:".",colon:":",semi:";",vert:"|",Verbar:"\u2016",verbar:"|",dblac:"\u02DD",circ:"\u02C6",caron:"\u02C7",breve:"\u02D8",dot:"\u02D9",ring:"\u02DA",ogon:"\u02DB",tilde:"\u02DC",DiacriticalGrave:"`",DiacriticalAcute:"\xB4",DiacriticalTilde:"\u02DC",DiacriticalDot:"\u02D9",DiacriticalDoubleAcute:"\u02DD",grave:"`",acute:"\xB4"},o7={cent:"\xA2",pound:"\xA3",curren:"\xA4",yen:"\xA5",euro:"\u20AC",dollar:"$",euro:"\u20AC",fnof:"\u0192",inr:"\u20B9",af:"\u060B",birr:"\u1265\u122D",peso:"\u20B1",rub:"\u20BD",won:"\u20A9",yuan:"\xA5",cedil:"\xB8"},b1={frac12:"\xBD",half:"\xBD",frac13:"\u2153",frac14:"\xBC",frac15:"\u2155",frac16:"\u2159",frac18:"\u215B",frac23:"\u2154",frac25:"\u2156",frac34:"\xBE",frac35:"\u2157",frac38:"\u215C",frac45:"\u2158",frac56:"\u215A",frac58:"\u215D",frac78:"\u215E",frasl:"\u2044"},y1={trade:"\u2122",TRADE:"\u2122",telrec:"\u2315",target:"\u2316",ulcorn:"\u231C",ulcorner:"\u231C",urcorn:"\u231D",urcorner:"\u231D",dlcorn:"\u231E",llcorner:"\u231E",drcorn:"\u231F",lrcorner:"\u231F",intercal:"\u22BA",intcal:"\u22BA",oplus:"\u2295",CirclePlus:"\u2295",ominus:"\u2296",CircleMinus:"\u2296",otimes:"\u2297",CircleTimes:"\u2297",osol:"\u2298",odot:"\u2299",CircleDot:"\u2299",oast:"\u229B",circledast:"\u229B",odash:"\u229D",circleddash:"\u229D",ocirc:"\u229A",circledcirc:"\u229A",boxplus:"\u229E",plusb:"\u229E",boxminus:"\u229F",minusb:"\u229F",boxtimes:"\u22A0",timesb:"\u22A0",boxdot:"\u22A1",sdotb:"\u22A1",veebar:"\u22BB",vee:"\u2228",barvee:"\u22BD",and:"\u2227",wedge:"\u2227",Cap:"\u22D2",Cup:"\u22D3",Fork:"\u22D4",pitchfork:"\u22D4",epar:"\u22D5",ltlarr:"\u2976",nvap:"\u224D\u20D2",nvsim:"\u223C\u20D2",nvge:"\u2265\u20D2",nvle:"\u2264\u20D2",nvlt:"<\u20D2",nvgt:">\u20D2",nvltrie:"\u22B4\u20D2",nvrtrie:"\u22B5\u20D2",Vdash:"\u22A9",dashv:"\u22A3",vDash:"\u22A8",Vdash:"\u22A9",Vvdash:"\u22AA",nvdash:"\u22AC",nvDash:"\u22AD",nVdash:"\u22AE",nVDash:"\u22AF"},nQ={...A1,...P1,...f1,...v1,...S1,...E1,...N1,...C1,...h1,...D1,...o7,...b1,...y1},q7={amp:"&",apos:"'",gt:">",lt:"<",quot:'"'},C2={nbsp:"\xA0",copy:"\xA9",reg:"\xAE",trade:"\u2122",mdash:"\u2014",ndash:"\u2013",hellip:"\u2026",laquo:"\xAB",raquo:"\xBB",lsquo:"\u2018",rsquo:"\u2019",ldquo:"\u201C",rdquo:"\u201D",bull:"\u2022",para:"\xB6",sect:"\xA7",deg:"\xB0",frac12:"\xBD",frac14:"\xBC",frac34:"\xBE"}});function k1(Q){if(Q[0]==="#")throw Error(`[EntityReplacer] Invalid character '#' in entity name: "${Q}"`);for(let $ of Q)if(aQ.has($))throw Error(`[EntityReplacer] Invalid character '${$}' in entity name: "${Q}"`);return Q}function D2(...Q){let $=Object.create(null);for(let J of Q){if(!J)continue;for(let Y of Object.keys(J)){let G=J[Y];if(typeof G==="string")$[Y]=G;else if(G&&typeof G==="object"&&G.val!==void 0){let z=G.val;if(typeof z==="string")$[Y]=z}}}return $}function iQ(Q){if(!Q||Q===O$)return new Set([O$]);if(Q===b2)return new Set([b2]);if(Q===t7)return new Set([t7]);if(Array.isArray(Q))return new Set(Q);return new Set([O$])}function oQ(Q){if(!Q)return{xmlVersion:1,onLevel:O0.allow,nullLevel:O0.remove};let $=Q.xmlVersion===1.1?1.1:1,J=O0[Q.onNCR]??O0.allow,Y=O0[Q.nullNCR]??O0.remove,G=Math.max(Y,O0.remove);return{xmlVersion:$,onLevel:J,nullLevel:G}}class H7{constructor(Q={}){this._limit=Q.limit||{},this._maxTotalExpansions=this._limit.maxTotalExpansions||0,this._maxExpandedLength=this._limit.maxExpandedLength||0,this._postCheck=typeof Q.postCheck==="function"?Q.postCheck:(J)=>J,this._limitTiers=iQ(this._limit.applyLimitsTo??O$),this._numericAllowed=Q.numericAllowed??!0,this._baseMap=D2(q7,Q.namedEntities||null),this._externalMap=Object.create(null),this._inputMap=Object.create(null),this._totalExpansions=0,this._expandedLength=0,this._removeSet=new Set(Q.remove&&Array.isArray(Q.remove)?Q.remove:[]),this._leaveSet=new Set(Q.leave&&Array.isArray(Q.leave)?Q.leave:[]);let $=oQ(Q.ncr);this._ncrXmlVersion=$.xmlVersion,this._ncrOnLevel=$.onLevel,this._ncrNullLevel=$.nullLevel}setExternalEntities(Q){if(Q)for(let $ of Object.keys(Q))k1($);this._externalMap=D2(Q)}addExternalEntity(Q,$){if(k1(Q),typeof $==="string"&&$.indexOf("&")===-1)this._externalMap[Q]=$}addInputEntities(Q){this._totalExpansions=0,this._expandedLength=0,this._inputMap=D2(Q)}reset(){return this._inputMap=Object.create(null),this._totalExpansions=0,this._expandedLength=0,this}setXmlVersion(Q){this._ncrXmlVersion=Q===1.1?1.1:1}decode(Q){if(typeof Q!=="string"||Q.length===0)return Q;let $=Q,J=[],Y=Q.length,G=0,z=0,W=this._maxTotalExpansions>0,X=this._maxExpandedLength>0,H=W||X;while(z<Y){if(Q.charCodeAt(z)!==38){z++;continue}let Z=z+1;while(Z<Y&&Q.charCodeAt(Z)!==59&&Z-z<=32)Z++;if(Z>=Y||Q.charCodeAt(Z)!==59){z++;continue}let K=Q.slice(z+1,Z);if(K.length===0){z++;continue}let _,U;if(this._removeSet.has(K)){if(_="",U===void 0)U=O$}else if(this._leaveSet.has(K)){z++;continue}else if(K.charCodeAt(0)===35){let L=this._resolveNCR(K);if(L===void 0){z++;continue}_=L,U=t7}else{let L=this._resolveName(K);_=L?.value,U=L?.tier}if(_===void 0){z++;continue}if(z>G)J.push(Q.slice(G,z));if(J.push(_),G=Z+1,z=G,H&&this._tierCounts(U)){if(W){if(this._totalExpansions++,this._totalExpansions>this._maxTotalExpansions)throw Error(`[EntityReplacer] Entity expansion count limit exceeded: ${this._totalExpansions} > ${this._maxTotalExpansions}`)}if(X){let L=_.length-(K.length+2);if(L>0){if(this._expandedLength+=L,this._expandedLength>this._maxExpandedLength)throw Error(`[EntityReplacer] Expanded content length limit exceeded: ${this._expandedLength} > ${this._maxExpandedLength}`)}}}}if(G<Y)J.push(Q.slice(G));let q=J.length===0?Q:J.join("");return this._postCheck(q,$)}_tierCounts(Q){if(this._limitTiers.has(b2))return!0;return this._limitTiers.has(Q)}_resolveName(Q){if(Q in this._inputMap)return{value:this._inputMap[Q],tier:O$};if(Q in this._externalMap)return{value:this._externalMap[Q],tier:O$};if(Q in this._baseMap)return{value:this._baseMap[Q],tier:t7};return}_classifyNCR(Q){if(Q===0)return this._ncrNullLevel;if(Q>=55296&&Q<=57343)return O0.remove;if(this._ncrXmlVersion===1){if(Q>=1&&Q<=31&&!sQ.has(Q))return O0.remove}return-1}_applyNCRAction(Q,$,J){switch(Q){case O0.allow:return String.fromCodePoint(J);case O0.remove:return"";case O0.leave:return;case O0.throw:throw Error(`[EntityDecoder] Prohibited numeric character reference &${$}; (U+${J.toString(16).toUpperCase().padStart(4,"0")})`);default:return String.fromCodePoint(J)}}_resolveNCR(Q){let $=Q.charCodeAt(1),J;if($===120||$===88)J=parseInt(Q.slice(2),16);else J=parseInt(Q.slice(1),10);if(Number.isNaN(J)||J<0||J>1114111)return;let Y=this._classifyNCR(J);if(!this._numericAllowed&&Y<O0.remove)return;let G=Y===-1?this._ncrOnLevel:Math.max(this._ncrOnLevel,Y);return this._applyNCRAction(G,Q,J)}}var aQ,O$="external",t7="base",b2="all",O0,sQ;var x1=p(()=>{h2();aQ=new Set("!?\\\\/[]$%{}^&*()<>|+");O0=Object.freeze({allow:0,leave:1,remove:2,throw:3}),sQ=new Set([9,10,13])});var g1=p(()=>{x1();h2()});function eQ(Q,$){if(typeof Q!=="string")return;let J=Q.toLowerCase();if(z7.some((Y)=>J===Y.toLowerCase()))throw Error(`[SECURITY] Invalid ${$}: "${Q}" is a reserved JavaScript keyword that could cause prototype pollution`);if(s7.some((Y)=>J===Y.toLowerCase()))throw Error(`[SECURITY] Invalid ${$}: "${Q}" is a reserved JavaScript keyword that could cause prototype pollution`)}function m1(Q,$){if(typeof Q==="boolean")return{enabled:Q,maxEntitySize:1e4,maxExpansionDepth:1e4,maxTotalExpansions:1/0,maxExpandedLength:1e5,maxEntityCount:1000,allowedTags:null,tagFilter:null,appliesTo:"all"};if(typeof Q==="object"&&Q!==null)return{enabled:Q.enabled!==!1,maxEntitySize:Math.max(1,Q.maxEntitySize??1e4),maxExpansionDepth:Math.max(1,Q.maxExpansionDepth??1e4),maxTotalExpansions:Math.max(1,Q.maxTotalExpansions??1/0),maxExpandedLength:Math.max(1,Q.maxExpandedLength??1e5),maxEntityCount:Math.max(1,Q.maxEntityCount??1000),allowedTags:Q.allowedTags??null,tagFilter:Q.tagFilter??null,appliesTo:Q.appliesTo??"all"};return m1(!0)}var u1=(Q)=>{if(z7.includes(Q))return"__"+Q;return Q},tQ,c1=function(Q){let $=Object.assign({},tQ,Q),J=[{value:$.attributeNamePrefix,name:"attributeNamePrefix"},{value:$.attributesGroupName,name:"attributesGroupName"},{value:$.textNodeName,name:"textNodeName"},{value:$.cdataPropName,name:"cdataPropName"},{value:$.commentPropName,name:"commentPropName"}];for(let{value:Y,name:G}of J)if(Y)eQ(Y,G);if($.onDangerousProperty===null)$.onDangerousProperty=u1;if($.processEntities=m1($.processEntities,$.htmlEntities),$.unpairedTagsSet=new Set($.unpairedTags),$.stopNodes&&Array.isArray($.stopNodes))$.stopNodes=$.stopNodes.map((Y)=>{if(typeof Y==="string"&&Y.startsWith("*."))return".."+Y.substring(2);return Y});return $};var l1=p(()=>{W7();tQ={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(Q,$){return $},attributeValueProcessor:function(Q,$){return $},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,entityDecoder:null,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(Q,$,J){return Q},captureMetaData:!1,maxNestedTags:100,strictReservedNames:!0,jPath:!0,onDangerousProperty:u1}});class w0{constructor(Q){this.tagname=Q,this.child=[],this[":@"]=Object.create(null)}add(Q,$){if(Q==="__proto__")Q="#__proto__";this.child.push({[Q]:$})}addChild(Q,$){if(Q.tagname==="__proto__")Q.tagname="#__proto__";if(Q[":@"]&&Object.keys(Q[":@"]).length>0)this.child.push({[Q.tagname]:Q.child,[":@"]:Q[":@"]});else this.child.push({[Q.tagname]:Q.child});if($!==void 0)this.child[this.child.length-1][e7]={startIndex:$}}static getMetaDataSymbol(){return e7}}var e7;var $2=p(()=>{if(typeof Symbol!=="function")e7="@@xmlMetadata";else e7=Symbol("XML Node Metadata")});class Q2{constructor(Q){this.suppressValidationErr=!Q,this.options=Q}readDocType(Q,$){let J=Object.create(null),Y=0;if(Q[$+3]==="O"&&Q[$+4]==="C"&&Q[$+5]==="T"&&Q[$+6]==="Y"&&Q[$+7]==="P"&&Q[$+8]==="E"){$=$+9;let G=1,z=!1,W=!1,X="";for(;$<Q.length;$++)if(Q[$]==="<"&&!W){if(z&&V$(Q,"!ENTITY",$)){$+=7;let H,q;if([H,q,$]=this.readEntityExp(Q,$+1,this.suppressValidationErr),q.indexOf("&")===-1){if(this.options.enabled!==!1&&this.options.maxEntityCount!=null&&Y>=this.options.maxEntityCount)throw Error(`Entity count (${Y+1}) exceeds maximum allowed (${this.options.maxEntityCount})`);J[H]=q,Y++}}else if(z&&V$(Q,"!ELEMENT",$)){$+=8;let{index:H}=this.readElementExp(Q,$+1);$=H}else if(z&&V$(Q,"!ATTLIST",$))$+=8;else if(z&&V$(Q,"!NOTATION",$)){$+=9;let{index:H}=this.readNotationExp(Q,$+1,this.suppressValidationErr);$=H}else if(V$(Q,"!--",$))W=!0;else throw Error("Invalid DOCTYPE");G++,X=""}else if(Q[$]===">"){if(W){if(Q[$-1]==="-"&&Q[$-2]==="-")W=!1,G--}else G--;if(G===0)break}else if(Q[$]==="[")z=!0;else X+=Q[$];if(G!==0)throw Error("Unclosed DOCTYPE")}else throw Error("Invalid Tag instead of DOCTYPE");return{entities:J,i:$}}readEntityExp(Q,$){$=V0(Q,$);let J=$;while($<Q.length&&!/\s/.test(Q[$])&&Q[$]!=='"'&&Q[$]!=="'")$++;let Y=Q.substring(J,$);if(Z7(Y),$=V0(Q,$),!this.suppressValidationErr){if(Q.substring($,$+6).toUpperCase()==="SYSTEM")throw Error("External entities are not supported");else if(Q[$]==="%")throw Error("Parameter entities are not supported")}let G="";if([$,G]=this.readIdentifierVal(Q,$,"entity"),this.options.enabled!==!1&&this.options.maxEntitySize!=null&&G.length>this.options.maxEntitySize)throw Error(`Entity "${Y}" size (${G.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`);return $--,[Y,G,$]}readNotationExp(Q,$){$=V0(Q,$);let J=$;while($<Q.length&&!/\s/.test(Q[$]))$++;let Y=Q.substring(J,$);!this.suppressValidationErr&&Z7(Y),$=V0(Q,$);let G=Q.substring($,$+6).toUpperCase();if(!this.suppressValidationErr&&G!=="SYSTEM"&&G!=="PUBLIC")throw Error(`Expected SYSTEM or PUBLIC, found "${G}"`);$+=G.length,$=V0(Q,$);let z=null,W=null;if(G==="PUBLIC"){if([$,z]=this.readIdentifierVal(Q,$,"publicIdentifier"),$=V0(Q,$),Q[$]==='"'||Q[$]==="'")[$,W]=this.readIdentifierVal(Q,$,"systemIdentifier")}else if(G==="SYSTEM"){if([$,W]=this.readIdentifierVal(Q,$,"systemIdentifier"),!this.suppressValidationErr&&!W)throw Error("Missing mandatory system identifier for SYSTEM notation")}return{notationName:Y,publicIdentifier:z,systemIdentifier:W,index:--$}}readIdentifierVal(Q,$,J){let Y="",G=Q[$];if(G!=='"'&&G!=="'")throw Error(`Expected quoted string, found "${G}"`);$++;let z=$;while($<Q.length&&Q[$]!==G)$++;if(Y=Q.substring(z,$),Q[$]!==G)throw Error(`Unterminated ${J} value`);return $++,[$,Y]}readElementExp(Q,$){$=V0(Q,$);let J=$;while($<Q.length&&!/\s/.test(Q[$]))$++;let Y=Q.substring(J,$);if(!this.suppressValidationErr&&!E$(Y))throw Error(`Invalid element name: "${Y}"`);$=V0(Q,$);let G="";if(Q[$]==="E"&&V$(Q,"MPTY",$))$+=4;else if(Q[$]==="A"&&V$(Q,"NY",$))$+=2;else if(Q[$]==="("){$++;let z=$;while($<Q.length&&Q[$]!==")")$++;if(G=Q.substring(z,$),Q[$]!==")")throw Error("Unterminated content model")}else if(!this.suppressValidationErr)throw Error(`Invalid Element Expression, found "${Q[$]}"`);return{elementName:Y,contentModel:G.trim(),index:$}}readAttlistExp(Q,$){$=V0(Q,$);let J=$;while($<Q.length&&!/\s/.test(Q[$]))$++;let Y=Q.substring(J,$);Z7(Y),$=V0(Q,$),J=$;while($<Q.length&&!/\s/.test(Q[$]))$++;let G=Q.substring(J,$);if(!Z7(G))throw Error(`Invalid attribute name: "${G}"`);$=V0(Q,$);let z="";if(Q.substring($,$+8).toUpperCase()==="NOTATION"){if(z="NOTATION",$+=8,$=V0(Q,$),Q[$]!=="(")throw Error(`Expected '(', found "${Q[$]}"`);$++;let X=[];while($<Q.length&&Q[$]!==")"){let H=$;while($<Q.length&&Q[$]!=="|"&&Q[$]!==")")$++;let q=Q.substring(H,$);if(q=q.trim(),!Z7(q))throw Error(`Invalid notation name: "${q}"`);if(X.push(q),Q[$]==="|")$++,$=V0(Q,$)}if(Q[$]!==")")throw Error("Unterminated list of notations");$++,z+=" ("+X.join("|")+")"}else{let X=$;while($<Q.length&&!/\s/.test(Q[$]))$++;z+=Q.substring(X,$);let H=["CDATA","ID","IDREF","IDREFS","ENTITY","ENTITIES","NMTOKEN","NMTOKENS"];if(!this.suppressValidationErr&&!H.includes(z.toUpperCase()))throw Error(`Invalid attribute type: "${z}"`)}$=V0(Q,$);let W="";if(Q.substring($,$+8).toUpperCase()==="#REQUIRED")W="#REQUIRED",$+=8;else if(Q.substring($,$+7).toUpperCase()==="#IMPLIED")W="#IMPLIED",$+=7;else[$,W]=this.readIdentifierVal(Q,$,"ATTLIST");return{elementName:Y,attributeName:G,attributeType:z,defaultValue:W,index:$}}}function V$(Q,$,J){for(let Y=0;Y<$.length;Y++)if($[Y]!==Q[J+Y+1])return!1;return!0}function Z7(Q){if(E$(Q))return Q;else throw Error(`Invalid entity name ${Q}`)}var V0=(Q,$)=>{while($<Q.length&&/\s/.test(Q[$]))$++;return $};var d1=p(()=>{W7()});function y2(Q,$={}){if($=Object.assign({},JJ,$),!Q||typeof Q!=="string")return Q;let J=Q.trim();if(J.length===0)return Q;else if($.skipLike!==void 0&&$.skipLike.test(J))return Q;else if(J==="0")return 0;else if($.hex&&$J.test(J))return WJ(J,16);else if(!isFinite(J))return XJ(Q,Number(J),$);else if(J.includes("e")||J.includes("E"))return GJ(Q,J,$);else{let Y=QJ.exec(J);if(Y){let G=Y[1]||"",z=Y[2],W=zJ(Y[3]),X=G?Q[z.length+1]===".":Q[z.length]===".";if(!$.leadingZeros&&(z.length>1||z.length===1&&!X))return Q;else{let H=Number(J),q=String(H);if(H===0)return H;if(q.search(/[eE]/)!==-1)if($.eNotation)return H;else return Q;else if(J.indexOf(".")!==-1)if(q==="0")return H;else if(q===W)return H;else if(q===`${G}${W}`)return H;else return Q;let Z=z?W:J;if(z)return Z===q||G+Z===q?H:Q;else return Z===q||Z===G+q?H:Q}}else return Q}}function GJ(Q,$,J){if(!J.eNotation)return Q;let Y=$.match(YJ);if(Y){let G=Y[1]||"",z=Y[3].indexOf("e")===-1?"E":"e",W=Y[2],X=G?Q[W.length+1]===z:Q[W.length]===z;if(W.length>1&&X)return Q;else if(W.length===1&&(Y[3].startsWith(`.${z}`)||Y[3][0]===z))return Number($);else if(W.length>0)if(J.leadingZeros&&!X)return $=(Y[1]||"")+Y[3],Number($);else return Q;else return Number($)}else return Q}function zJ(Q){if(Q&&Q.indexOf(".")!==-1){if(Q=Q.replace(/0+$/,""),Q===".")Q="0";else if(Q[0]===".")Q="0"+Q;else if(Q[Q.length-1]===".")Q=Q.substring(0,Q.length-1);return Q}return Q}function WJ(Q,$){if(parseInt)return parseInt(Q,$);else if(Number.parseInt)return Number.parseInt(Q,$);else if(window&&window.parseInt)return window.parseInt(Q,$);else throw Error("parseInt, Number.parseInt, window.parseInt are not supported")}function XJ(Q,$,J){let Y=$===1/0;switch(J.infinity.toLowerCase()){case"null":return null;case"infinity":return $;case"string":return Y?"Infinity":"-Infinity";case"original":default:return Q}}var $J,QJ,JJ,YJ;var p1=p(()=>{$J=/^[-+]?0x[a-fA-F0-9]+$/,QJ=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,JJ={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0,infinity:"original"};YJ=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/});function k2(Q){if(typeof Q==="function")return Q;if(Array.isArray(Q))return($)=>{for(let J of Q){if(typeof J==="string"&&$===J)return!0;if(J instanceof RegExp&&J.test($))return!0}};return()=>!1}class N${constructor(Q,$={},J){this.pattern=Q,this.separator=$.separator||".",this.segments=this._parse(Q),this.data=J,this._hasDeepWildcard=this.segments.some((Y)=>Y.type==="deep-wildcard"),this._hasAttributeCondition=this.segments.some((Y)=>Y.attrName!==void 0),this._hasPositionSelector=this.segments.some((Y)=>Y.position!==void 0)}_parse(Q){let $=[],J=0,Y="";while(J<Q.length)if(Q[J]===this.separator)if(J+1<Q.length&&Q[J+1]===this.separator){if(Y.trim())$.push(this._parseSegment(Y.trim())),Y="";$.push({type:"deep-wildcard"}),J+=2}else{if(Y.trim())$.push(this._parseSegment(Y.trim()));Y="",J++}else Y+=Q[J],J++;if(Y.trim())$.push(this._parseSegment(Y.trim()));return $}_parseSegment(Q){let $={type:"tag"},J=null,Y=Q,G=Q.match(/^([^\[]+)(\[[^\]]*\])(.*)$/);if(G){if(Y=G[1]+G[3],G[2]){let q=G[2].slice(1,-1);if(q)J=q}}let z=void 0,W=Y;if(Y.includes("::")){let q=Y.indexOf("::");if(z=Y.substring(0,q).trim(),W=Y.substring(q+2).trim(),!z)throw Error(`Invalid namespace in pattern: ${Q}`)}let X=void 0,H=null;if(W.includes(":")){let q=W.lastIndexOf(":"),Z=W.substring(0,q).trim(),K=W.substring(q+1).trim();if(["first","last","odd","even"].includes(K)||/^nth\(\d+\)$/.test(K))X=Z,H=K;else X=W}else X=W;if(!X)throw Error(`Invalid segment pattern: ${Q}`);if($.tag=X,z)$.namespace=z;if(J)if(J.includes("=")){let q=J.indexOf("=");$.attrName=J.substring(0,q).trim(),$.attrValue=J.substring(q+1).trim()}else $.attrName=J.trim();if(H){let q=H.match(/^nth\((\d+)\)$/);if(q)$.position="nth",$.positionValue=parseInt(q[1],10);else $.position=H}return $}get length(){return this.segments.length}hasDeepWildcard(){return this._hasDeepWildcard}hasAttributeCondition(){return this._hasAttributeCondition}hasPositionSelector(){return this._hasPositionSelector}toString(){return this.pattern}}class _7{constructor(){this._byDepthAndTag=new Map,this._wildcardByDepth=new Map,this._deepWildcards=[],this._patterns=new Set,this._sealed=!1}add(Q){if(this._sealed)throw TypeError("ExpressionSet is sealed. Create a new ExpressionSet to add more expressions.");if(this._patterns.has(Q.pattern))return this;if(this._patterns.add(Q.pattern),Q.hasDeepWildcard())return this._deepWildcards.push(Q),this;let $=Q.length,Y=Q.segments[Q.segments.length-1]?.tag;if(!Y||Y==="*"){if(!this._wildcardByDepth.has($))this._wildcardByDepth.set($,[]);this._wildcardByDepth.get($).push(Q)}else{let G=`${$}:${Y}`;if(!this._byDepthAndTag.has(G))this._byDepthAndTag.set(G,[]);this._byDepthAndTag.get(G).push(Q)}return this}addAll(Q){for(let $ of Q)this.add($);return this}has(Q){return this._patterns.has(Q.pattern)}get size(){return this._patterns.size}seal(){return this._sealed=!0,this}get isSealed(){return this._sealed}matchesAny(Q){return this.findMatch(Q)!==null}findMatch(Q){let $=Q.getDepth(),J=Q.getCurrentTag(),Y=`${$}:${J}`,G=this._byDepthAndTag.get(Y);if(G){for(let W=0;W<G.length;W++)if(Q.matches(G[W]))return G[W]}let z=this._wildcardByDepth.get($);if(z){for(let W=0;W<z.length;W++)if(Q.matches(z[W]))return z[W]}for(let W=0;W<this._deepWildcards.length;W++)if(Q.matches(this._deepWildcards[W]))return this._deepWildcards[W];return null}}class r1{constructor(Q){this._matcher=Q}get separator(){return this._matcher.separator}getCurrentTag(){let Q=this._matcher.path;return Q.length>0?Q[Q.length-1].tag:void 0}getCurrentNamespace(){let Q=this._matcher.path;return Q.length>0?Q[Q.length-1].namespace:void 0}getAttrValue(Q){let $=this._matcher.path;if($.length===0)return;return $[$.length-1].values?.[Q]}hasAttr(Q){let $=this._matcher.path;if($.length===0)return!1;let J=$[$.length-1];return J.values!==void 0&&Q in J.values}getPosition(){let Q=this._matcher.path;if(Q.length===0)return-1;return Q[Q.length-1].position??0}getCounter(){let Q=this._matcher.path;if(Q.length===0)return-1;return Q[Q.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this._matcher.path.length}toString(Q,$=!0){return this._matcher.toString(Q,$)}toArray(){return this._matcher.path.map((Q)=>Q.tag)}matches(Q){return this._matcher.matches(Q)}matchesAny(Q){return Q.matchesAny(this._matcher)}}class U7{constructor(Q={}){this.separator=Q.separator||".",this.path=[],this.siblingStacks=[],this._pathStringCache=null,this._view=new r1(this)}push(Q,$=null,J=null){if(this._pathStringCache=null,this.path.length>0)this.path[this.path.length-1].values=void 0;let Y=this.path.length;if(!this.siblingStacks[Y])this.siblingStacks[Y]=new Map;let G=this.siblingStacks[Y],z=J?`${J}:${Q}`:Q,W=G.get(z)||0,X=0;for(let q of G.values())X+=q;G.set(z,W+1);let H={tag:Q,position:X,counter:W};if(J!==null&&J!==void 0)H.namespace=J;if($!==null&&$!==void 0)H.values=$;this.path.push(H)}pop(){if(this.path.length===0)return;this._pathStringCache=null;let Q=this.path.pop();if(this.siblingStacks.length>this.path.length+1)this.siblingStacks.length=this.path.length+1;return Q}updateCurrent(Q){if(this.path.length>0){let $=this.path[this.path.length-1];if(Q!==null&&Q!==void 0)$.values=Q}}getCurrentTag(){return this.path.length>0?this.path[this.path.length-1].tag:void 0}getCurrentNamespace(){return this.path.length>0?this.path[this.path.length-1].namespace:void 0}getAttrValue(Q){if(this.path.length===0)return;return this.path[this.path.length-1].values?.[Q]}hasAttr(Q){if(this.path.length===0)return!1;let $=this.path[this.path.length-1];return $.values!==void 0&&Q in $.values}getPosition(){if(this.path.length===0)return-1;return this.path[this.path.length-1].position??0}getCounter(){if(this.path.length===0)return-1;return this.path[this.path.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this.path.length}toString(Q,$=!0){let J=Q||this.separator;if(J===this.separator&&$===!0){if(this._pathStringCache!==null)return this._pathStringCache;let G=this.path.map((z)=>z.namespace?`${z.namespace}:${z.tag}`:z.tag).join(J);return this._pathStringCache=G,G}return this.path.map((G)=>$&&G.namespace?`${G.namespace}:${G.tag}`:G.tag).join(J)}toArray(){return this.path.map((Q)=>Q.tag)}reset(){this._pathStringCache=null,this.path=[],this.siblingStacks=[]}matches(Q){let $=Q.segments;if($.length===0)return!1;if(Q.hasDeepWildcard())return this._matchWithDeepWildcard($);return this._matchSimple($)}_matchSimple(Q){if(this.path.length!==Q.length)return!1;for(let $=0;$<Q.length;$++)if(!this._matchSegment(Q[$],this.path[$],$===this.path.length-1))return!1;return!0}_matchWithDeepWildcard(Q){let $=this.path.length-1,J=Q.length-1;while(J>=0&&$>=0){let Y=Q[J];if(Y.type==="deep-wildcard"){if(J--,J<0)return!0;let G=Q[J],z=!1;for(let W=$;W>=0;W--)if(this._matchSegment(G,this.path[W],W===this.path.length-1)){$=W-1,J--,z=!0;break}if(!z)return!1}else{if(!this._matchSegment(Y,this.path[$],$===this.path.length-1))return!1;$--,J--}}return J<0}_matchSegment(Q,$,J){if(Q.tag!=="*"&&Q.tag!==$.tag)return!1;if(Q.namespace!==void 0){if(Q.namespace!=="*"&&Q.namespace!==$.namespace)return!1}if(Q.attrName!==void 0){if(!J)return!1;if(!$.values||!(Q.attrName in $.values))return!1;if(Q.attrValue!==void 0){if(String($.values[Q.attrName])!==String(Q.attrValue))return!1}}if(Q.position!==void 0){if(!J)return!1;let Y=$.counter??0;if(Q.position==="first"&&Y!==0)return!1;else if(Q.position==="odd"&&Y%2!==1)return!1;else if(Q.position==="even"&&Y%2!==0)return!1;else if(Q.position==="nth"&&Y!==Q.positionValue)return!1}return!0}matchesAny(Q){return Q.matchesAny(this)}snapshot(){return{path:this.path.map((Q)=>({...Q})),siblingStacks:this.siblingStacks.map((Q)=>new Map(Q))}}restore(Q){this._pathStringCache=null,this.path=Q.path.map(($)=>({...$})),this.siblingStacks=Q.siblingStacks.map(($)=>new Map($))}readOnly(){return this._view}}var n1=()=>{};var x2=p(()=>{n1()});function qJ(Q,$){if(!Q)return{};let J=$.attributesGroupName?Q[$.attributesGroupName]:Q;if(!J)return{};let Y={};for(let G in J)if(G.startsWith($.attributeNamePrefix)){let z=G.substring($.attributeNamePrefix.length);Y[z]=J[G]}else Y[G]=J[G];return Y}function HJ(Q){if(!Q||typeof Q!=="string")return;let $=Q.indexOf(":");if($!==-1&&$>0){let J=Q.substring(0,$);if(J!=="xmlns")return J}return}class J2{constructor(Q,$){this.options=Q,this.currentNode=null,this.tagsNodeStack=[],this.parseXml=LJ,this.parseTextData=ZJ,this.resolveNameSpace=KJ,this.buildAttributesMap=UJ,this.isItStopNode=BJ,this.replaceEntitiesValue=OJ,this.readStopNodeData=MJ,this.saveTextToParentTag=VJ,this.addChild=FJ,this.ignoreAttributesFn=k2(this.options.ignoreAttributes),this.entityExpansionCount=0,this.currentExpandedLength=0;let J={...q7};if(this.options.entityDecoder)this.entityDecoder=this.options.entityDecoder;else{if(typeof this.options.htmlEntities==="object")J=this.options.htmlEntities;else if(this.options.htmlEntities===!0)J={...C2,...o7};this.entityDecoder=new H7({namedEntities:{...J,...$},numericAllowed:this.options.htmlEntities,limit:{maxTotalExpansions:this.options.processEntities.maxTotalExpansions,maxExpandedLength:this.options.processEntities.maxExpandedLength,applyLimitsTo:this.options.processEntities.appliesTo}})}this.matcher=new U7,this.readonlyMatcher=this.matcher.readOnly(),this.isCurrentNodeStopNode=!1,this.stopNodeExpressionsSet=new _7;let Y=this.options.stopNodes;if(Y&&Y.length>0){for(let G=0;G<Y.length;G++){let z=Y[G];if(typeof z==="string")this.stopNodeExpressionsSet.add(new N$(z));else if(z instanceof N$)this.stopNodeExpressionsSet.add(z)}this.stopNodeExpressionsSet.seal()}}}function ZJ(Q,$,J,Y,G,z,W){let X=this.options;if(Q!==void 0){if(X.trimValues&&!Y)Q=Q.trim();if(Q.length>0){if(!W)Q=this.replaceEntitiesValue(Q,$,J);let H=X.jPath?J.toString():J,q=X.tagValueProcessor($,Q,H,G,z);if(q===null||q===void 0)return Q;else if(typeof q!==typeof Q||q!==Q)return q;else if(X.trimValues)return m2(Q,X.parseTagValue,X.numberParseOptions);else if(Q.trim()===Q)return m2(Q,X.parseTagValue,X.numberParseOptions);else return Q}}}function KJ(Q){if(this.options.removeNSPrefix){let $=Q.split(":"),J=Q.charAt(0)==="/"?"/":"";if($[0]==="xmlns")return"";if($.length===2)Q=J+$[1]}return Q}function UJ(Q,$,J,Y=!1){let G=this.options;if(Y===!0||G.ignoreAttributes!==!0&&typeof Q==="string"){let z=i7(Q,_J),W=z.length,X={},H=Array(W),q=!1,Z={};for(let U=0;U<W;U++){let L=this.resolveNameSpace(z[U][1]),F=z[U][4];if(L.length&&F!==void 0){let O=F;if(G.trimValues)O=O.trim();O=this.replaceEntitiesValue(O,J,this.readonlyMatcher),H[U]=O,Z[L]=O,q=!0}}if(q&&typeof $==="object"&&$.updateCurrent)$.updateCurrent(Z);let K=G.jPath?$.toString():this.readonlyMatcher,_=!1;for(let U=0;U<W;U++){let L=this.resolveNameSpace(z[U][1]);if(this.ignoreAttributesFn(L,K))continue;let F=G.attributeNamePrefix+L;if(L.length){if(G.transformAttributeName)F=G.transformAttributeName(F);if(F=a1(F,G),z[U][4]!==void 0){let O=H[U],M=G.attributeValueProcessor(L,O,K);if(M===null||M===void 0)X[F]=O;else if(typeof M!==typeof O||M!==O)X[F]=M;else X[F]=m2(O,G.parseAttributeValue,G.numberParseOptions);_=!0}else if(G.allowBooleanAttributes)X[F]=!0,_=!0}}if(!_)return;if(G.attributesGroupName&&!G.preserveOrder){let U={};return U[G.attributesGroupName]=X,U}return X}}function FJ(Q,$,J,Y){if(!this.options.captureMetaData)Y=void 0;let G=this.options.jPath?J.toString():J,z=this.options.updateTag($.tagname,G,$[":@"]);if(z===!1);else if(typeof z==="string")$.tagname=z,Q.addChild($,Y);else Q.addChild($,Y)}function OJ(Q,$,J){let Y=this.options.processEntities;if(!Y||!Y.enabled)return Q;if(Y.allowedTags){let G=this.options.jPath?J.toString():J;if(!(Array.isArray(Y.allowedTags)?Y.allowedTags.includes($):Y.allowedTags($,G)))return Q}if(Y.tagFilter){let G=this.options.jPath?J.toString():J;if(!Y.tagFilter($,G))return Q}return this.entityDecoder.decode(Q)}function VJ(Q,$,J,Y){if(Q){if(Y===void 0)Y=$.child.length===0;if(Q=this.parseTextData(Q,$.tagname,J,!1,$[":@"]?Object.keys($[":@"]).length!==0:!1,Y),Q!==void 0&&Q!=="")$.add(this.options.textNodeName,Q);Q=""}return Q}function BJ(){if(this.stopNodeExpressionsSet.size===0)return!1;return this.matcher.matchesAny(this.stopNodeExpressionsSet)}function RJ(Q,$,J=">"){let Y=0,G=Q.length,z=J.charCodeAt(0),W=J.length>1?J.charCodeAt(1):-1,X="",H=$;for(let q=$;q<G;q++){let Z=Q.charCodeAt(q);if(Y){if(Z===Y)Y=0}else if(Z===34||Z===39)Y=Z;else if(Z===z)if(W!==-1){if(Q.charCodeAt(q+1)===W)return X+=Q.substring(H,q),{data:X,index:q}}else return X+=Q.substring(H,q),{data:X,index:q};else if(Z===9&&!Y)X+=Q.substring(H,q)+" ",H=q+1}}function C$(Q,$,J,Y){let G=Q.indexOf($,J);if(G===-1)throw Error(Y);else return G+$.length-1}function wJ(Q,$,J,Y){let G=Q.indexOf($,J);if(G===-1)throw Error(Y);return G}function u2(Q,$,J,Y=">"){let G=RJ(Q,$+1,Y);if(!G)return;let{data:z,index:W}=G,X=z.search(/\s/),H=z,q=!0;if(X!==-1)H=z.substring(0,X),z=z.substring(X+1).trimStart();let Z=H;if(J){let K=H.indexOf(":");if(K!==-1)H=H.substr(K+1),q=H!==G.data.substr(K+1)}return{tagName:H,tagExp:z,closeIndex:W,attrExpPresent:q,rawTagName:Z}}function MJ(Q,$,J){let Y=J,G=1,z=Q.length;for(;J<z;J++)if(Q[J]==="<"){let W=Q.charCodeAt(J+1);if(W===47){let X=wJ(Q,">",J,`${$} is not closed`);if(Q.substring(J+2,X).trim()===$){if(G--,G===0)return{tagContent:Q.substring(Y,J),i:X}}J=X}else if(W===63)J=C$(Q,"?>",J+1,"StopNode is not closed.");else if(W===33&&Q.charCodeAt(J+2)===45&&Q.charCodeAt(J+3)===45)J=C$(Q,"-->",J+3,"StopNode is not closed.");else if(W===33&&Q.charCodeAt(J+2)===91)J=C$(Q,"]]>",J,"StopNode is not closed.")-2;else{let X=u2(Q,J,">");if(X){if((X&&X.tagName)===$&&X.tagExp[X.tagExp.length-1]!=="/")G++;J=X.closeIndex}}}}function m2(Q,$,J){if($&&typeof Q==="string"){let Y=Q.trim();if(Y==="true")return!0;else if(Y==="false")return!1;else return y2(Q,J)}else if(B1(Q))return Q;else return""}function g2(Q,$,J,Y){if(Q){let G=Q($);if(J===$)J=G;$=G}return $=a1($,Y),{tagName:$,tagExp:J}}function a1(Q,$){if(s7.includes(Q))throw Error(`[SECURITY] Invalid name: "${Q}" is a reserved JavaScript keyword that could cause prototype pollution`);else if(z7.includes(Q))return $.onDangerousProperty(Q);return Q}var _J,LJ=function(Q){Q=Q.replace(/\r\n?/g,`
101
101
  `);let $=new w0("!xml"),J=$,Y="";this.matcher.reset(),this.entityDecoder.reset(),this.entityExpansionCount=0,this.currentExpandedLength=0;let G=this.options,z=new Q2(G.processEntities),W=Q.length;for(let X=0;X<W;X++)if(Q[X]==="<"){let q=Q.charCodeAt(X+1);if(q===47){let Z=C$(Q,">",X,"Closing Tag is not closed."),K=Q.substring(X+2,Z).trim();if(G.removeNSPrefix){let U=K.indexOf(":");if(U!==-1)K=K.substr(U+1)}if(K=g2(G.transformTagName,K,"",G).tagName,J)Y=this.saveTextToParentTag(Y,J,this.readonlyMatcher);let _=this.matcher.getCurrentTag();if(K&&G.unpairedTagsSet.has(K))throw Error(`Unpaired tag can not be used as closing tag: </${K}>`);if(_&&G.unpairedTagsSet.has(_))this.matcher.pop(),this.tagsNodeStack.pop();this.matcher.pop(),this.isCurrentNodeStopNode=!1,J=this.tagsNodeStack.pop(),Y="",X=Z}else if(q===63){let Z=u2(Q,X,!1,"?>");if(!Z)throw Error("Pi Tag is not closed.");Y=this.saveTextToParentTag(Y,J,this.readonlyMatcher);let K=this.buildAttributesMap(Z.tagExp,this.matcher,Z.tagName,!0);if(K){let _=K[this.options.attributeNamePrefix+"version"];this.entityDecoder.setXmlVersion(Number(_)||1)}if(G.ignoreDeclaration&&Z.tagName==="?xml"||G.ignorePiTags);else{let _=new w0(Z.tagName);if(_.add(G.textNodeName,""),Z.tagName!==Z.tagExp&&Z.attrExpPresent&&G.ignoreAttributes!==!0)_[":@"]=K;this.addChild(J,_,this.readonlyMatcher,X)}X=Z.closeIndex+1}else if(q===33&&Q.charCodeAt(X+2)===45&&Q.charCodeAt(X+3)===45){let Z=C$(Q,"-->",X+4,"Comment is not closed.");if(G.commentPropName){let K=Q.substring(X+4,Z-2);Y=this.saveTextToParentTag(Y,J,this.readonlyMatcher),J.add(G.commentPropName,[{[G.textNodeName]:K}])}X=Z}else if(q===33&&Q.charCodeAt(X+2)===68){let Z=z.readDocType(Q,X);this.entityDecoder.addInputEntities(Z.entities),X=Z.i}else if(q===33&&Q.charCodeAt(X+2)===91){let Z=C$(Q,"]]>",X,"CDATA is not closed.")-2,K=Q.substring(X+9,Z);Y=this.saveTextToParentTag(Y,J,this.readonlyMatcher);let _=this.parseTextData(K,J.tagname,this.readonlyMatcher,!0,!1,!0,!0);if(_==null)_="";if(G.cdataPropName)J.add(G.cdataPropName,[{[G.textNodeName]:K}]);else J.add(G.textNodeName,_);X=Z+2}else{let Z=u2(Q,X,G.removeNSPrefix);if(!Z){let j=Q.substring(Math.max(0,X-50),Math.min(W,X+50));throw Error(`readTagExp returned undefined at position ${X}. Context: "${j}"`)}let{tagName:K,rawTagName:_,tagExp:U,attrExpPresent:L,closeIndex:F}=Z;if({tagName:K,tagExp:U}=g2(G.transformTagName,K,U,G),G.strictReservedNames&&(K===G.commentPropName||K===G.cdataPropName||K===G.textNodeName||K===G.attributesGroupName))throw Error(`Invalid tag name: ${K}`);if(J&&Y){if(J.tagname!=="!xml")Y=this.saveTextToParentTag(Y,J,this.readonlyMatcher,!1)}let O=J;if(O&&G.unpairedTagsSet.has(O.tagname))J=this.tagsNodeStack.pop(),this.matcher.pop();let M=!1;if(U.length>0&&U.lastIndexOf("/")===U.length-1){if(M=!0,K[K.length-1]==="/")K=K.substr(0,K.length-1),U=K;else U=U.substr(0,U.length-1);L=K!==U}let T=null,f={},P=void 0;if(P=HJ(_),K!==$.tagname)this.matcher.push(K,{},P);if(K!==U&&L){if(T=this.buildAttributesMap(U,this.matcher,K),T)f=qJ(T,G)}if(K!==$.tagname)this.isCurrentNodeStopNode=this.isItStopNode();let I=X;if(this.isCurrentNodeStopNode){let j="";if(M)X=Z.closeIndex;else if(G.unpairedTagsSet.has(K))X=Z.closeIndex;else{let h=this.readStopNodeData(Q,_,F+1);if(!h)throw Error(`Unexpected end of ${_}`);X=h.i,j=h.tagContent}let A=new w0(K);if(T)A[":@"]=T;A.add(G.textNodeName,j),this.matcher.pop(),this.isCurrentNodeStopNode=!1,this.addChild(J,A,this.readonlyMatcher,I)}else{if(M){({tagName:K,tagExp:U}=g2(G.transformTagName,K,U,G));let j=new w0(K);if(T)j[":@"]=T;this.addChild(J,j,this.readonlyMatcher,I),this.matcher.pop(),this.isCurrentNodeStopNode=!1}else if(G.unpairedTagsSet.has(K)){let j=new w0(K);if(T)j[":@"]=T;this.addChild(J,j,this.readonlyMatcher,I),this.matcher.pop(),this.isCurrentNodeStopNode=!1,X=Z.closeIndex;continue}else{let j=new w0(K);if(this.tagsNodeStack.length>G.maxNestedTags)throw Error("Maximum nested tags exceeded");if(this.tagsNodeStack.push(J),T)j[":@"]=T;this.addChild(J,j,this.readonlyMatcher,I),J=j}Y="",X=F}}}else Y+=Q[X];return $.child};var i1=p(()=>{W7();$2();d1();p1();x2();x2();g1();_J=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm")});function TJ(Q,$){if(!Q||typeof Q!=="object")return{};if(!$)return Q;let J={};for(let Y in Q)if(Y.startsWith($)){let G=Y.substring($.length);J[G]=Q[Y]}else J[Y]=Q[Y];return J}function l2(Q,$,J,Y){return s1(Q,$,J,Y)}function s1(Q,$,J,Y){let G,z={};for(let W=0;W<Q.length;W++){let X=Q[W],H=IJ(X);if(H!==void 0&&H!==$.textNodeName){let q=TJ(X[":@"]||{},$.attributeNamePrefix);J.push(H,q)}if(H===$.textNodeName)if(G===void 0)G=X[H];else G+=""+X[H];else if(H===void 0)continue;else if(X[H]){let q=s1(X[H],$,J,Y),Z=AJ(q,$);if(X[":@"])jJ(q,X[":@"],Y,$);else if(Object.keys(q).length===1&&q[$.textNodeName]!==void 0&&!$.alwaysCreateTextNode)q=q[$.textNodeName];else if(Object.keys(q).length===0)if($.alwaysCreateTextNode)q[$.textNodeName]="";else q="";if(X[c2]!==void 0&&typeof q==="object"&&q!==null)q[c2]=X[c2];if(z[H]!==void 0&&Object.prototype.hasOwnProperty.call(z,H)){if(!Array.isArray(z[H]))z[H]=[z[H]];z[H].push(q)}else{let K=$.jPath?Y.toString():Y;if($.isArray(H,K,Z))z[H]=[q];else z[H]=q}if(H!==void 0&&H!==$.textNodeName)J.pop()}}if(typeof G==="string"){if(G.length>0)z[$.textNodeName]=G}else if(G!==void 0)z[$.textNodeName]=G;return z}function IJ(Q){let $=Object.keys(Q);for(let J=0;J<$.length;J++){let Y=$[J];if(Y!==":@")return Y}}function jJ(Q,$,J,Y){if($){let G=Object.keys($),z=G.length;for(let W=0;W<z;W++){let X=G[W],H=X.startsWith(Y.attributeNamePrefix)?X.substring(Y.attributeNamePrefix.length):X,q=Y.jPath?J.toString()+"."+H:J;if(Y.isArray(X,q,!0,!0))Q[X]=[$[X]];else Q[X]=$[X]}}}function AJ(Q,$){let{textNodeName:J}=$,Y=Object.keys(Q).length;if(Y===0)return!0;if(Y===1&&(Q[J]||typeof Q[J]==="boolean"||Q[J]===0))return!0;return!1}var c2;var o1=p(()=>{$2();c2=w0.getMetaDataSymbol()});class L7{constructor(Q){this.externalEntities={},this.options=c1(Q)}parse(Q,$){if(typeof Q!=="string"&&Q.toString)Q=Q.toString();else if(typeof Q!=="string")throw Error("XML data is accepted in String or Bytes[] form.");if($){if($===!0)$={};let G=I1(Q,$);if(G!==!0)throw Error(`${G.err.msg}:${G.err.line}:${G.err.col}`)}let J=new J2(this.options,this.externalEntities),Y=J.parseXml(Q);if(this.options.preserveOrder||Y===void 0)return Y;else return l2(Y,this.options,J.matcher,J.readonlyMatcher)}addEntity(Q,$){if($.indexOf("&")!==-1)throw Error("Entity value can't have '&'");else if(Q.indexOf("&")!==-1||Q.indexOf(";")!==-1)throw Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");else if($==="&")throw Error("An entity with value '&' is not permitted");else this.externalEntities[Q]=$}static getMetaDataSymbol(){return w0.getMetaDataSymbol()}}var t1=p(()=>{l1();i1();o1();j1();$2()});var e1=p(()=>{t1()});import*as Y$ from"crypto";class F7{credentials;config;cache;xmlParser;constructor(Q,$){this.credentials=Q||this.loadCredentials(),this.config={maxRetries:3,retryDelay:1000,cacheEnabled:!0,defaultCacheTTL:60000,...$},this.cache=new Map,this.xmlParser=new L7({ignoreAttributes:!1,attributeNamePrefix:"@_",textNodeName:"#text",parseAttributeValue:!0,trimValues:!0})}loadCredentials(){let Q=process.env.AWS_ACCESS_KEY_ID,$=process.env.AWS_SECRET_ACCESS_KEY,J=process.env.AWS_SESSION_TOKEN;if(Q&&$)return{accessKeyId:Q,secretAccessKey:$,sessionToken:J};return{accessKeyId:"",secretAccessKey:""}}ec2CredentialsCache;async getCredentials(){let Q=process.env.AWS_ACCESS_KEY_ID,$=process.env.AWS_SECRET_ACCESS_KEY;if(Q&&$)return{accessKeyId:Q,secretAccessKey:$,sessionToken:process.env.AWS_SESSION_TOKEN};if(this.ec2CredentialsCache){let J=Date.now();if(this.ec2CredentialsCache.expiration>J+300000)return this.ec2CredentialsCache.credentials}try{let Y=await(await fetch("http://169.254.169.254/latest/api/token",{method:"PUT",headers:{"X-aws-ec2-metadata-token-ttl-seconds":"21600"}})).text(),z=await(await fetch("http://169.254.169.254/latest/meta-data/iam/security-credentials/",{headers:{"X-aws-ec2-metadata-token":Y}})).text(),X=await(await fetch(`http://169.254.169.254/latest/meta-data/iam/security-credentials/${z}`,{headers:{"X-aws-ec2-metadata-token":Y}})).json(),H={accessKeyId:X.AccessKeyId,secretAccessKey:X.SecretAccessKey,sessionToken:X.Token};return this.ec2CredentialsCache={credentials:H,expiration:new Date(X.Expiration).getTime()},H}catch(J){throw Error("AWS credentials not found. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables, or run on an EC2 instance with an IAM role.")}}async request(Q){if(Q.method==="GET"&&this.config.cacheEnabled&&Q.cacheKey){let Y=this.getFromCache(Q.cacheKey);if(Y!==null)return Y}let $=Q.retries??this.config.maxRetries??3,J=null;for(let Y=0;Y<=$;Y++)try{let G=await this.makeRequest(Q);if(Q.method==="GET"&&this.config.cacheEnabled&&Q.cacheKey)this.setInCache(Q.cacheKey,G,Q.cacheTTL??this.config.defaultCacheTTL??60000);return G}catch(G){if(J=G,!this.shouldRetry(G))throw G;if(Y===$)throw G;let W=this.calculateRetryDelay(Y);await this.sleep(W)}throw J||Error("Request failed after retries")}async makeRequest(Q){let $=Q.credentials||await this.getCredentials();if(!$||!$.accessKeyId||!$.secretAccessKey)throw Error("AWS credentials not provided");let J=this.buildUrl(Q),Y=this.signRequest(Q,$),G=await fetch(J,{method:Q.method,headers:Y,body:Q.body}),z=await G.text();if(!G.ok)throw this.parseError(z,G.status,G.headers);if(!z||z.trim()===""){if(Q.returnHeaders)return{body:null,headers:this.headersToObject(G.headers)};return null}if(Q.rawResponse){if(Q.returnHeaders)return{body:z,headers:this.headersToObject(G.headers)};return z}let W;if(z.startsWith("<"))W=this.parseXmlResponse(z);else try{W=JSON.parse(z)}catch{W=z}if(Q.returnHeaders)return{body:W,headers:this.headersToObject(G.headers)};return W}headersToObject(Q){let $={};return Q.forEach((J,Y)=>{$[Y]=J}),$}buildUrl(Q){let{service:$,region:J,path:Y,queryParams:G}=Q,z;if($==="s3")z=`s3.${J}.amazonaws.com`;else if($==="cloudfront")z="cloudfront.amazonaws.com";else if($==="iam")z="iam.amazonaws.com";else if($==="route53")z="route53.amazonaws.com";else if($==="route53domains")z="route53domains.us-east-1.amazonaws.com";else if($==="ecr")z=`api.ecr.${J}.amazonaws.com`;else if($==="ses")z=`email.${J}.amazonaws.com`;else z=`${$}.${J}.amazonaws.com`;let W=`https://${z}${Y}`;if(G&&Object.keys(G).length>0){let X=new URLSearchParams(G).toString();W+=`?${X}`}return W}signRequest(Q,$){let{service:J,region:Y,method:G,path:z,queryParams:W,body:X}=Q,H=new Date,q=this.getAmzDate(H),Z=this.getDateStamp(H),K;if(J==="s3")K=`s3.${Y}.amazonaws.com`;else if(J==="cloudfront")K="cloudfront.amazonaws.com";else if(J==="iam")K="iam.amazonaws.com";else if(J==="route53")K="route53.amazonaws.com";else if(J==="route53domains")K="route53domains.us-east-1.amazonaws.com";else if(J==="ecr")K=`api.ecr.${Y}.amazonaws.com`;else if(J==="ses")K=`email.${Y}.amazonaws.com`;else K=`${J}.${Y}.amazonaws.com`;let _={host:K,"x-amz-date":q,...Q.headers||{}};if($.sessionToken)_["x-amz-security-token"]=$.sessionToken;if(X){if(!Object.keys(_).some((v)=>v.toLowerCase()==="content-type"))_["content-type"]="application/x-www-form-urlencoded";_["content-length"]=Buffer.byteLength(X).toString()}let U=this.sha256(X||"");_["x-amz-content-sha256"]=U;let L=z,F=W?new URLSearchParams(W).toString():"",O=Object.keys(_).sort((B,v)=>B.toLowerCase().localeCompare(v.toLowerCase())),M=O.map((B)=>`${B.toLowerCase()}:${_[B].trim()}
@@ -182,8 +182,8 @@ host:${W}
182
182
  </SelectObjectContentRequest>`;return await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${Q}/${$}`,queryParams:{select:"","select-type":"2"},headers:{"Content-Type":"application/xml"},body:X,rawResponse:!0})}}var J9=p(()=>{d2()});var G9={};f7(G9,{startSmtpServer:()=>vJ,SmtpServer:()=>n2});import*as Y9 from"net";import*as Y2 from"tls";import*as O7 from"fs";import*as V7 from"crypto";class n2{config;ses;s3;server;tlsServer;sessions=new Map;constructor(Q){if(this.config={port:587,tlsPort:465,host:"0.0.0.0",...Q},this.ses=new p2(Q.region||"us-east-1"),Q.sentBucket)this.s3=new r2(Q.region||"us-east-1")}async start(){if(this.server=Y9.createServer((Q)=>{this.handleConnection(Q,!1)}),this.server.listen(this.config.port,this.config.host,()=>{console.log(`SMTP server listening on ${this.config.host}:${this.config.port} (STARTTLS)`)}),this.config.tls?.key&&this.config.tls?.cert){let Q={key:O7.readFileSync(this.config.tls.key),cert:O7.readFileSync(this.config.tls.cert)};this.tlsServer=Y2.createServer(Q,($)=>{this.handleConnection($,!0)}),this.tlsServer.listen(this.config.tlsPort,this.config.host,()=>{console.log(`SMTP server listening on ${this.config.host}:${this.config.tlsPort} (TLS)`)})}}async stop(){if(this.server)this.server.close();if(this.tlsServer)this.tlsServer.close();for(let Q of this.sessions.values())Q.socket.destroy();this.sessions.clear()}handleConnection(Q,$){let J=V7.randomUUID(),Y={id:J,socket:Q,secure:$,state:"greeting",authenticated:!1,rcptTo:[],dataBuffer:"",tlsUpgraded:$};this.sessions.set(J,Y),console.log(`SMTP connection from ${Q.remoteAddress} (session: ${J.slice(0,8)})`),this.send(Y,`220 ${this.config.domain} ESMTP Mail Server`),Y.state="ready";let G="";Q.on("data",async(z)=>{G+=z.toString();let W;while((W=G.indexOf(`\r
183
183
  `))!==-1){let X=G.slice(0,W);if(G=G.slice(W+2),Y.state==="data")await this.handleDataLine(Y,X);else await this.handleCommand(Y,X)}}),Q.on("close",()=>{console.log(`SMTP session ${J.slice(0,8)} closed`),this.sessions.delete(J)}),Q.on("error",(z)=>{console.error(`SMTP session ${J.slice(0,8)} error:`,z.message),this.sessions.delete(J)})}send(Q,$){if(!Q.socket.destroyed)Q.socket.write(`${$}\r
184
184
  `)}async handleCommand(Q,$){let J=$.trim();if(!J)return;let Y=J.split(" ")[0].toUpperCase(),G=J.slice(Y.length).trim();switch(console.log(`SMTP CMD [${Q.username||"anon"}]: ${Y} ${G.includes("AUTH")?"***":G}`),Y){case"EHLO":case"HELO":await this.handleEhlo(Q,G);break;case"STARTTLS":await this.handleStartTls(Q);break;case"AUTH":await this.handleAuth(Q,G);break;case"MAIL":await this.handleMailFrom(Q,G);break;case"RCPT":await this.handleRcptTo(Q,G);break;case"DATA":await this.handleData(Q);break;case"RSET":this.resetSession(Q),this.send(Q,"250 OK");break;case"NOOP":this.send(Q,"250 OK");break;case"QUIT":this.send(Q,`221 ${this.config.domain} closing connection`),Q.socket.end();break;default:this.send(Q,"500 Unrecognized command")}}async handleEhlo(Q,$){let J=[`250-${this.config.domain} Hello ${$}`,"250-SIZE 26214400","250-8BITMIME","250-PIPELINING"];if(!Q.secure&&this.config.tls?.key)J.push("250-STARTTLS");J.push("250-AUTH PLAIN LOGIN"),J.push("250 OK");for(let Y of J)this.send(Q,Y)}async handleStartTls(Q){if(Q.secure||Q.tlsUpgraded){this.send(Q,"503 TLS already active");return}if(!this.config.tls?.key||!this.config.tls?.cert){this.send(Q,"454 TLS not available");return}this.send(Q,"220 Ready to start TLS");let $={key:O7.readFileSync(this.config.tls.key),cert:O7.readFileSync(this.config.tls.cert),isServer:!0},J=new Y2.TLSSocket(Q.socket,$);Q.socket=J,Q.secure=!0,Q.tlsUpgraded=!0,this.resetSession(Q)}async handleAuth(Q,$){let J=$.split(" "),Y=J[0].toUpperCase();if(Y==="PLAIN")if(J[1])await this.handleAuthPlain(Q,J[1]);else this.send(Q,"334 "),Q.state="ready";else if(Y==="LOGIN"){this.send(Q,"334 VXNlcm5hbWU6");let G=Q.socket.listeners("data")[0];Q.socket.removeAllListeners("data");let z="username",W="";Q.socket.on("data",async(X)=>{try{let H=X.toString().trim();if(z==="username")W=Buffer.from(H,"base64").toString("utf-8"),z="password",this.send(Q,"334 UGFzc3dvcmQ6");else if(z==="password"){let q=Buffer.from(H,"base64").toString("utf-8");Q.socket.removeAllListeners("data"),Q.socket.on("data",G),await this.authenticateUser(Q,W,q)}}catch(H){Q.socket.removeAllListeners("data"),Q.socket.on("data",G),this.send(Q,"535 Authentication failed"),console.error(`SMTP AUTH LOGIN error: ${H.message}`)}})}else this.send(Q,"504 Unrecognized authentication mechanism")}async handleAuthPlain(Q,$){try{let Y=Buffer.from($,"base64").toString("utf-8").split("\x00"),G=Y.length===3?Y[1]:Y[0],z=Y.length===3?Y[2]:Y[1];await this.authenticateUser(Q,G,z)}catch(J){this.send(Q,"535 Authentication failed")}}async authenticateUser(Q,$,J){let Y=$.includes("@")?$.split("@")[0]:$,G=this.config.users[Y],z=G?(()=>{try{let W=Buffer.from(G.password,"utf-8"),X=Buffer.from(J,"utf-8");if(W.length!==X.length){let H=Math.max(W.length,X.length),q=Buffer.alloc(H),Z=Buffer.alloc(H);return q.set(W),Z.set(X),V7.timingSafeEqual(q,Z),!1}return V7.timingSafeEqual(W,X)}catch{return!1}})():!1;if(G&&z)Q.authenticated=!0,Q.username=Y,Q.email=G.email,this.send(Q,"235 Authentication successful"),console.log(`SMTP AUTH success: ${Y}`);else this.send(Q,"535 Authentication failed"),console.log(`SMTP AUTH failed: ${$}`)}async handleMailFrom(Q,$){if(!Q.authenticated){this.send(Q,"530 Authentication required");return}let J=$.match(/FROM:\s*<([^>]*)>/i);if(!J){this.send(Q,"501 Syntax error in MAIL FROM");return}let Y=J[1];if(!Y.endsWith(`@${this.config.domain}`)){this.send(Q,`553 Sender address must be from @${this.config.domain}`);return}Q.mailFrom=Y,Q.state="mail",this.send(Q,"250 OK")}async handleRcptTo(Q,$){if(!Q.authenticated){this.send(Q,"530 Authentication required");return}if(!Q.mailFrom){this.send(Q,"503 MAIL FROM required first");return}let J=$.match(/TO:\s*<([^>]*)>/i);if(!J){this.send(Q,"501 Syntax error in RCPT TO");return}Q.rcptTo.push(J[1]),Q.state="rcpt",this.send(Q,"250 OK")}async handleData(Q){if(!Q.authenticated){this.send(Q,"530 Authentication required");return}if(Q.rcptTo.length===0){this.send(Q,"503 RCPT TO required first");return}Q.state="data",Q.dataBuffer="",this.send(Q,"354 Start mail input; end with <CRLF>.<CRLF>")}async handleDataLine(Q,$){if($===".")await this.sendEmail(Q);else{let J=$.startsWith(".")?$.slice(1):$;Q.dataBuffer+=`${J}\r
185
- `}}async sendEmail(Q){try{let $=Q.dataBuffer,J=await this.ses.sendRawEmail({source:Q.mailFrom,destinations:Q.rcptTo,rawMessage:$});if(console.log(`SMTP: Email sent via SES, MessageId: ${J.MessageId}`),this.s3&&this.config.sentBucket)try{let Y=`${this.config.sentPrefix||"sent/"}${Q.email}/${Date.now()}-${J.MessageId}`;await this.s3.putObject({bucket:this.config.sentBucket,key:Y,body:$,contentType:"message/rfc822"}),console.log(`SMTP: Email stored in S3: ${Y}`)}catch(Y){console.error("SMTP: Failed to store sent email in S3 (email was sent successfully):",Y.message)}this.send(Q,`250 OK Message accepted, ID: ${J.MessageId}`),this.resetSession(Q)}catch($){console.error("SMTP: Failed to send email:",$.message),this.send(Q,`451 Failed to send: ${$.message}`),this.resetSession(Q)}}resetSession(Q){Q.state="ready",Q.mailFrom=void 0,Q.rcptTo=[],Q.dataBuffer=""}}async function vJ(Q){let $=new n2(Q);return await $.start(),$}var z9=p(()=>{$9();J9()});import k0 from"process";import{bold as v7,dim as x0,green as G8,intro as z8,log as e,onUnknownSubcommand as W8}from"@stacksjs/cli";import{storage as w3}from"@stacksjs/storage";function _G(Q){Q.command("about","Display diagnostic information about Stacks").action(async()=>{e.debug("Running `buddy about` ..."),await z8("buddy about");try{let J=(await w3.readPackageJson("./package.json")).version||"unknown",Y=k0.versions.bun||"N/A",G=k0.versions.node||"N/A",z=k0.platform,W=k0.arch,X=k0.version,H=k0.env.NODE_ENV||k0.env.APP_ENV||"development";if(e.info(""),e.info(G8(v7("Stacks Framework"))),e.info(x0("\u2500".repeat(50))),e.info(""),e.info(v7("Version Information:")),e.info(` Stacks: ${x0(J)}`),e.info(` Bun: ${x0(Y)}`),G!=="N/A")e.info(` Node: ${x0(G)}`);e.info(""),e.info(v7("Environment:")),e.info(` Mode: ${x0(H)}`),e.info(` OS: ${x0(`${z} ${W}`)}`),e.info(` Runtime: ${x0(X)}`),e.info(""),e.info(v7("Configuration:")),e.info(` Cache: ${x0("file")}`),e.info(` Debug: ${x0(k0.env.DEBUG?"enabled":"disabled")}`),e.info("")}catch($){e.error("Failed to retrieve system information:",$),k0.exit(1)}}),W8(Q,"about")}import n0 from"process";import{runAction as S7}from"@stacksjs/actions";import{intro as E7,log as N7,onUnknownSubcommand as X8,outro as a0}from"@stacksjs/cli";import{Action as C7}from"@stacksjs/enums";import{ExitCode as i0}from"@stacksjs/types";function RG(Q){let $={setup:"Set up authentication (migrations + personal access client)",token:"Create a personal access client token",client:"Create a new OAuth client",prune:"Prune expired and revoked tokens",project:"Target a specific project",verbose:"Enable verbose output"};Q.command("auth:setup",$.setup).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{N7.debug("Running `buddy auth:setup` ...",J);let Y=await E7("buddy auth:setup"),G=await S7(C7.AuthSetup,J);if(G.isErr)await a0("While setting up authentication, there was an issue",{startTime:Y,useSeconds:!0},G.error),n0.exit(i0.FatalError);await a0("Authentication setup completed successfully.",{startTime:Y,useSeconds:!0}),n0.exit(i0.Success)}),Q.command("auth:token",$.token).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{N7.debug("Running `buddy auth:token` ...",J);let Y=await E7("buddy auth:token"),G=await S7(C7.CreatePersonalAccessClient,J);if(G.isErr)await a0("While creating the personal access client token, there was an issue",{startTime:Y,useSeconds:!0},G.error),n0.exit(i0.FatalError);await a0("Personal access client token created successfully.",{startTime:Y,useSeconds:!0}),n0.exit(i0.Success)}),Q.command("auth:client",$.client).option("-n, --name [name]","Client name",{default:"OAuth Client"}).option("-r, --redirect [redirect]","Redirect URI",{default:"http://localhost"}).option("--personal","Create a personal access client",{default:!1}).option("--password","Create a password grant client",{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{N7.debug("Running `buddy auth:client` ...",J);let Y=await E7("buddy auth:client"),G=await S7(C7.AuthClient,J);if(G.isErr)await a0("While creating the OAuth client, there was an issue",{startTime:Y,useSeconds:!0},G.error),n0.exit(i0.FatalError);await a0("OAuth client created successfully.",{startTime:Y,useSeconds:!0}),n0.exit(i0.Success)}),Q.command("auth:prune",$.prune).option("--expired","Prune expired tokens (default: true)",{default:!0}).option("--revoked","Prune revoked tokens (default: true)",{default:!0}).option("-d, --days [days]","Prune revoked tokens older than N days",{default:7}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{N7.debug("Running `buddy auth:prune` ...",J);let Y=await E7("buddy auth:prune"),G=await S7(C7.AuthPrune,J);if(G.isErr)await a0("While pruning tokens, there was an issue",{startTime:Y,useSeconds:!0},G.error),n0.exit(i0.FatalError);await a0("Token pruning completed successfully.",{startTime:Y,useSeconds:!0}),n0.exit(i0.Success)}),X8(Q,"auth")}import l$ from"process";import{intro as Z2,log as I0,onUnknownSubcommand as q8,outro as h7}from"@stacksjs/cli";import{Action as Y0}from"@stacksjs/enums";import{ExitCode as d$}from"@stacksjs/types";var K2;async function G0(...Q){if(!K2)K2=(await import("@stacksjs/actions")).runAction;return K2(...Q)}function AG(Q){let $={build:"Build any of your libraries (packages) for production use",components:"Build your component library",webComponents:"Build your framework agnostic web component library",elements:"An alias to the -w flag",buddy:"Build the Buddy binary",functions:"Build your function library",desktop:"Build the Desktop Application",pages:"Build your frontend",docs:"Build your documentation",framework:"Build Stacks framework",cli:"Automagically build the CLI",server:"Build the Stacks cloud server (Docker image)",select:"What are you trying to build?",project:"Target a specific project",verbose:"Enable verbose output"};Q.command("build [type]",$.build).option("-c, --components",$.components).option("-w, --web-components",$.webComponents).option("-e, --elements",$.elements).option("-f, --functions",$.functions).option("-p, --views",$.pages).option("--pages",$.pages).option("-d, --docs",$.docs).option("-b, --buddy",$.buddy,{default:!1}).option("-s, --stacks",$.framework,{default:!1}).option("--project [project]",$.project,{default:!1}).option("--server",$.server,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J,Y)=>{switch(I0.debug("Running `buddy build` ...",Y),J){case"components":Y.components=!0;break;case"web-components":Y.webComponents=!0;break;case"functions":Y.functions=!0;break;case"views":Y.views=!0;break;case"docs":Y.docs=!0;break;case"buddy":Y.buddy=!0;break;case"cli":Y.buddy=!0;break;case"stacks":Y.stacks=!0;break;case"server":Y.server=!0;break;default:break}if(H8(Y))Y.stacks=!0;if(Y.docs)await G0(Y0.BuildDocs);if(Y.components)await G0(Y0.BuildComponentLibs);if(Y.webComponents)await G0(Y0.BuildWebComponentLib);if(Y.functions)await G0(Y0.BuildFunctionLib);if(Y.views)await G0(Y0.BuildViews);if(Y.stacks)await G0(Y0.BuildStacks);if(Y.buddy)await G0(Y0.BuildCli);if(Y.server)await G0(Y0.BuildServer);l$.exit(d$.Success)}),Q.command("build:components","Automagically build component libraries for production use & npm/CDN distribution").alias("prod:components").option("-c, --components",$.components,{default:!0}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{I0.debug("Running `buddy build:components` ...",J),await G0(Y0.BuildComponentLibs,J)}),Q.command("build:cli",$.cli).alias("prod:cli").option("-b, --buddy",$.buddy,{default:!0}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{I0.debug("Running `buddy build:cli` ...",J),await G0(Y0.BuildCli,J)}),Q.command("build:server",$.server).alias("prod:server").alias("build:docker").option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{I0.debug("Running `buddy build:server` ...",J),await G0(Y0.BuildServer,J)}),Q.command("build:functions","Automagically build function library for npm/CDN distribution").option("-f, --functions",$.functions,{default:!0}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{I0.debug("Running `buddy build:functions` ...",J),await G0(Y0.BuildFunctionLib,J)}),Q.command("build:web-components","Automagically build Web Component library for npm/CDN distribution").alias("build:wc").alias("prod:web-components").alias("prod:wc").option("-w, --web-components",$.webComponents,{default:!0}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{I0.debug("Running `buddy build:web-components` ...",J),await G0(Y0.BuildWebComponentLib,J)}),Q.command("build:docs","Automagically build your documentation site.").alias("prod:docs").alias("build:documentation").alias("prod:documentation").option("-d, --docs",$.docs,{default:!0}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{I0.debug("Running `buddy build:docs` ...",J),await G0(Y0.BuildDocs,J)}),Q.command("build:core","Automagically build the Stacks core.").option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{I0.debug("Running `buddy build:core` ...",J);let Y=await Z2("buddy build:core"),G=await G0(Y0.BuildCore,J);if(G.isErr)I0.error("Failed to build the Stacks core.",G.error),l$.exit(d$.FatalError);await h7("Core packages built successfully",{startTime:Y,useSeconds:!0})}),Q.command("build:desktop",$.desktop).alias("prod:desktop").option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{I0.debug("Running `buddy build:desktop` ...",J);let Y=await Z2("buddy build:desktop"),G=await G0(Y0.BuildDesktop,J);if(G.isErr)await h7("While running the build:desktop command, there was an issue",{startTime:Y,useSeconds:!0},G.error),l$.exit(d$.FatalError);console.log(""),await h7("Exited",{startTime:Y,useSeconds:!0}),l$.exit(d$.Success)}),Q.command("build:stacks","Build the Stacks framework.").option("-s, --stacks",$.framework,{default:!0}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{I0.debug("Running `buddy build:stacks` ...",J);let Y=await Z2("buddy build:stacks"),G=await G0(Y0.BuildStacks,J);if(G.isErr)I0.error("Failed to build Stacks.",G.error),l$.exit(d$.FatalError);await h7("Stacks built successfully",{startTime:Y,useSeconds:!0})}),q8(Q,"build")}function H8(Q){return!Q.components&&!Q.webComponents&&!Q.elements&&!Q.functions&&!Q.views&&!Q.docs&&!Q.stacks&&!Q.buddy&&!Q.server}import Z8 from"process";import{runAction as K8}from"@stacksjs/actions";import{intro as _8,log as U8,onUnknownSubcommand as L8,outro as M3}from"@stacksjs/cli";import{Action as F8}from"@stacksjs/enums";import{ExitCode as O8}from"@stacksjs/types";function CG(Q){let $={changelog:"Create a CHANGELOG.md file",quiet:"Minimal output",dryRun:"Do not write the file, just output the changes",project:"Target a specific project",verbose:"Enable verbose output"};Q.command("changelog",$.changelog).option("-q, --quiet",$.quiet,{default:!1}).option("-d, --dry-run",$.dryRun,{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{U8.debug("Running `buddy changelog` ...",J);let Y=await _8("buddy changelog"),G=await K8(F8.Changelog,J);if(G.isErr)await M3("While running the changelog command, there was an issue",{...J,startTime:Y,useSeconds:!0},G.error),Z8.exit(O8.FatalError);await M3("Generated CHANGELOG.md",{...J,startTime:Y,useSeconds:!0,type:"success"})}),L8(Q,"changelog")}import _2 from"process";import{runAction as V8}from"@stacksjs/actions";import{intro as B8,log as T3,onUnknownSubcommand as R8,outro as I3}from"@stacksjs/cli";import{Action as w8}from"@stacksjs/enums";import{ExitCode as U2}from"@stacksjs/types";function gG(Q){let $={clean:"Removes all node_modules & lock files",project:"Target a specific project",verbose:"Enable verbose output"};Q.command("clean",$.clean).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{if(T3.debug("Running `buddy clean` ...",J),!Q.isForce&&!Q.isNoInteraction){let{confirm:z}=await import("@stacksjs/cli");if(!await z({message:"This will remove all node_modules and lock files. Continue?",initial:!1}))T3.info("Clean cancelled"),_2.exit(U2.Success)}let Y=await B8("buddy clean"),G=await V8(w8.Clean,J);if(G.isErr)await I3("While running the clean command, there was an issue",{startTime:Y,useSeconds:!0},G.error),_2.exit(U2.FatalError);await I3("Cleaned up",{startTime:Y,useSeconds:!0,message:"Cleaned up"}),_2.exit(U2.Success)}),R8(Q,"clean")}import b from"process";import{intro as w$,italic as V2,log as y,onUnknownSubcommand as E8,outro as r,prompts as a$,runCommand as S3,underline as E3}from"@stacksjs/cli";import{addJumpBox as N8,deleteCdkRemnants as C8,deleteIamUsers as h8,deleteJumpBox as B2,deleteLogGroups as D8,deleteParameterStore as b8,deleteStacksBuckets as y8,deleteStacksFunctions as k8,deleteSubnets as x8,deleteVpcs as g8,getCloudFrontDistributionId as N3,getJumpBoxInstanceId as u8}from"@stacksjs/cloud";import{path as C3}from"@stacksjs/path";import{ExitCode as l}from"@stacksjs/types";function i$(Q){if(!Q||typeof Q!=="object")return!1;let $=Q;if(typeof $.isErr==="function")return $.isErr();return!!$.isErr}function s$(Q){if(!Q||typeof Q!=="object")return"Unknown error";return String(Q.error||"Unknown error")}function m8(Q){if(!Q||typeof Q!=="object")return;return Q.value}function oG(Q){let $={cloud:"Interact with the Stacks Cloud",ssh:"SSH into the Stacks Cloud",add:"Add a resource to the Stacks Cloud",remove:"Remove the Stacks Cloud. In case it fails, try again",optimizeCost:"Remove certain resources that may be re-applied at a later time",cleanUp:"Remove all resources that were retained during the cloud deletion",invalidateCache:"Invalidate the CloudFront cache",diff:"Show the diff of the current, undeployed cloud changes ",paths:"The paths to invalidate",project:"Target a specific project",verbose:"Enable verbose output"};Q.command("cloud",$.cloud).option("--ssh",$.ssh,{default:!1}).option("--connect",$.ssh,{default:!1}).option("--invalidate-cache",$.invalidateCache,{default:!1}).option("--paths [paths]",$.paths).option("--diff",$.diff,{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{y.debug("Running `buddy cloud` ...",J);let Y=performance.now();if(J.ssh||J.connect){let G=await u8(),z=await S3(`aws ssm start-session --target ${G}`,{...J,cwd:C3.projectPath(),stdin:"pipe"});if(i$(z))await r("While running the cloud command, there was an issue",{startTime:Y,useSeconds:!0},s$(z)),b.exit(l.FatalError);await r("Exited",{startTime:Y,useSeconds:!0}),b.exit(l.Success)}if(J.invalidateCache){let{confirm:G}=await a$({name:"confirm",type:"confirm",message:"Would you like to invalidate the CDN (CloudFront) cache?"});if(!G)await r("Exited",{startTime:Y,useSeconds:!0}),b.exit(l.Success);y.info("Invalidating the CloudFront cache...");let{AWSCloudFrontClient:z}=await import("@stacksjs/ts-cloud"),W=new z,X=await N3();try{let H=await W.invalidateAll(X);y.success(`Invalidation created: ${H}`),y.info("Status: pending")}catch(H){y.error(`Failed to invalidate CloudFront cache: ${H.message}`)}await r("Exited",{startTime:Y,useSeconds:!0}),b.exit(l.Success)}if(J.diff){try{let{InfrastructureGenerator:G}=await import("@stacksjs/ts-cloud"),{CloudFormationClient:z}=await import("@stacksjs/ts-cloud/aws"),{tsCloud:W}=await Promise.resolve().then(() => (n$(),r$)),X=b.env.APP_ENV||b.env.NODE_ENV||"production",q=new G({config:W,environment:X}).generate().toJSON(),Z=`${W.project?.slug||"stacks"}-${X}`,K=new z(b.env.AWS_REGION||"us-east-1"),_="{}";try{_=(await K.getTemplate(Z)).TemplateBody}catch{y.info("No deployed stack found. Showing full template as diff.")}if(_===q)y.info("No changes detected.");else y.info("Changes detected between deployed and local template:"),y.info(`Current template: ${_.length} bytes`),y.info(`New template: ${q.length} bytes`)}catch(G){y.error(`Failed to compute diff: ${G.message}`)}await r("Cloud diff complete",{startTime:Y,useSeconds:!0}),b.exit(l.Success)}y.info("Not implemented yet. Read more about `buddy cloud` here: https://stacksjs.com/docs/cloud"),b.exit(l.Success)}),Q.command("cloud:add",$.add).option("--jump-box","Remove the jump-box",{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{y.debug("Running `buddy cloud:add` ...",J);let Y=await w$("buddy cloud:add");if(J.jumpBox){let{confirm:G}=await a$({name:"confirm",type:"confirm",message:"Would you like to add a jump-box to your cloud?"});if(!G)await r("Exited",{startTime:Y,useSeconds:!0}),b.exit(l.Success);y.info("The jump-box is getting added to your cloud resources..."),y.info("This takes a few moments, please be patient."),await new Promise((W)=>setTimeout(W,2000));let z=await N8();if(i$(z))await r("While running the cloud:add command, there was an issue",{startTime:Y,useSeconds:!0},s$(z)),b.exit(l.FatalError);y.info(V2("View the jump-box in the AWS console:")),y.info(E3("https://us-east-1.console.aws.amazon.com/ec2/home?region=us-east-1#Instances:instanceState=running")),y.info(V2("Once it finished initializing, you may SSH into it:")),y.info(E3("buddy cloud --ssh")),await r("Your jump-box was added.",{startTime:Y,useSeconds:!0}),b.exit(l.Success)}y.info("This functionality is not yet implemented."),b.exit(l.Success)}),Q.command("cloud:remove",$.remove).alias("cloud:destroy").alias("cloud:rm").alias("undeploy").option("--jump-box","Remove the jump-box",{default:!1}).option("--force","Force deletion of stack in bad state",{default:!1}).option("--yes","Skip confirmation prompts",{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{y.debug("Running `buddy cloud:remove` ...",J);let Y=await w$("buddy cloud:remove");if(J.jumpBox){let{confirm:z}=await a$({name:"confirm",type:"confirm",message:"Would you like to remove your jump-box for now?"});if(!z)await r("Exited",{startTime:Y,useSeconds:!0}),b.exit(l.Success);let W=await B2();if(i$(W))await r("While removing your jump-box, there was an issue",{startTime:Y,useSeconds:!0},s$(W)),b.exit(l.FatalError);await r("Your jump-box was removed.",{startTime:Y,useSeconds:!0}),b.exit(l.Success)}console.log(""),console.log("Removing cloud infrastructure..."),console.log(` ${V2("This typically takes 2-5 minutes.")}`),console.log("");let G=b.env.APP_ENV||b.env.NODE_ENV||"production";if(!b.env.AWS_ACCESS_KEY_ID||!b.env.AWS_SECRET_ACCESS_KEY){let{existsSync:z,readFileSync:W}=await import("fs"),{projectPath:X}=await import("@stacksjs/path"),H=[X(`.env.${G}`),X(".env")];for(let q of H)if(z(q)){let K=W(q,"utf-8").split(`
186
- `);for(let _ of K){let U=_.trim();if(U.startsWith("#")||!U.includes("="))continue;let[L,...F]=U.split("="),O=F.join("=").replace(/^["']|["']$/g,"");if(L==="AWS_ACCESS_KEY_ID"||L==="AWS_SECRET_ACCESS_KEY"||L==="AWS_REGION"||L==="AWS_ACCOUNT_ID")b.env[L]=O}break}}delete b.env.AWS_PROFILE;try{let{undeployStack:z}=await Promise.resolve().then(() => (v3(),f3)),W=b.env.AWS_REGION||"us-east-1";await z({environment:G,region:W,verbose:J.verbose}),await r("Cloud infrastructure removed",{startTime:Y,useSeconds:!0}),b.exit(l.Success)}catch(z){console.log(""),console.error("\u2717 Failed to remove cloud infrastructure");let W=String(z.message||z);if(W.includes("security token")||W.includes("credentials"))console.log(""),console.error(" AWS credentials are invalid or expired"),console.log(" Check your AWS credentials in .env.production:"),console.log(" - AWS_ACCESS_KEY_ID"),console.log(" - AWS_SECRET_ACCESS_KEY");else if(W.includes("region")||W.includes("AWS_REGION"))console.log(""),console.error(" AWS Region not configured"),console.log(" Add AWS_REGION to your .env.production file");else if(W.includes("AccessDenied"))console.log(""),console.error(" Access denied"),console.log(" Your AWS credentials may not have permission to delete stacks");else console.error(` ${W}`);if(console.log(""),console.log("Troubleshooting:"),console.log(" ./buddy cloud:cleanup - Clean up resources manually"),console.log(" --verbose - Show detailed error information"),console.log(""),J.verbose)console.error("Error details:",z);await r("Failed to remove infrastructure",{startTime:Y,useSeconds:!0}),b.exit(l.FatalError)}}),Q.command("cloud:optimize-cost",$.optimizeCost).option("--jump-box","Remove the jump-box",{default:!0}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{y.debug("Running `buddy cloud:optimize-cost` ...",J);let Y=await w$("buddy cloud:optimize-cost");if(J.jumpBox){let{confirm:G}=await a$({name:"confirm",type:"confirm",message:"Would you like to remove your jump-box to optimize your costs?"});if(!G)await r("Exited",{startTime:Y,useSeconds:!0}),b.exit(l.Success);await B2(),await r("Your jump-box was removed & cost optimizations are applied.",{startTime:Y,useSeconds:!0}),b.exit(l.Success)}await r("No cost optimization was applied",{startTime:Y,useSeconds:!0}),b.exit(l.Success)}),Q.command("cloud:cleanup",$.cleanUp).alias("cloud:clean-up").option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{y.debug("Running `buddy cloud:cleanup` ...",J);let Y=await w$("buddy cloud:cleanup");delete b.env.AWS_PROFILE,y.info("Cleaning up your cloud resources will take a while to complete. Please be patient."),await new Promise((W)=>setTimeout(W,2000));let G=[{label:"jump-boxes",fn:B2,ignoreErrors:["Jump-box not found"]},{label:"retained S3 buckets",fn:y8},{label:"retained Lambda functions",fn:k8,ignoreErrors:["No stacks functions found"]},{label:"remaining Stacks logs",fn:D8},{label:"stored parameters",fn:b8},{label:"VPCs",fn:g8},{label:"Subnets",fn:x8},{label:"CDK remnants",fn:C8},{label:"IAM users",fn:h8}],z=[];for(let W of G){y.info(`Removing any ${W.label}...`);try{let X=await W.fn();if(i$(X)){let H=s$(X);if(!W.ignoreErrors?.includes(H))y.warn(`${W.label} cleanup issue: ${H}`),z.push({label:W.label,error:H})}else{let H=m8(X);if(H)y.info(String(H))}}catch(X){let H=X.message||"AWS SDK error";y.warn(`${W.label} cleanup skipped: ${H}`),z.push({label:W.label,error:H})}}if(z.length>0){y.warn(`Cleanup completed with ${z.length} issue(s):`);for(let{label:W,error:X}of z)y.warn(` - ${W}: ${X}`)}await r("AWS resources have been removed",{startTime:Y,useSeconds:!0}),b.exit(l.Success)}),Q.command("cloud:invalidate-cache",$.invalidateCache).option("--paths [paths]",$.paths,{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{y.debug("Running `buddy cloud:invalidate-cache` ...",J);let Y=await w$("buddy cloud:invalidate-cache"),{confirm:G}=await a$({name:"confirm",type:"confirm",message:"Would you like to invalidate the CloudFront cache?"});if(!G)await r("Exited",{startTime:Y,useSeconds:!0}),b.exit(l.Success);y.info("Invalidating the CloudFront cache...");let z=await N3();if(!z)await r("Could not resolve CloudFront distribution ID",{startTime:Y,useSeconds:!0},"Ensure your cloud stack is deployed before invalidating cache."),b.exit(l.FatalError);let W=J.paths?String(J.paths):"/*",X=await S3(`aws cloudfront create-invalidation --distribution-id ${z} --paths ${W}`,{...J,cwd:C3.projectPath(),stdin:"pipe"});if(i$(X))await r("While running the cloud command, there was an issue",{startTime:Y,useSeconds:!0},s$(X)),b.exit(l.FatalError);await r("Exited",{startTime:Y,useSeconds:!0}),b.exit(l.Success)}),Q.command("cloud:diff",$.diff).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{y.debug("Running `buddy cloud:diff` ...",J);let Y=await w$("buddy cloud:diff");try{let{InfrastructureGenerator:G}=await import("@stacksjs/ts-cloud"),{CloudFormationClient:z}=await import("@stacksjs/ts-cloud/aws"),{tsCloud:W}=await Promise.resolve().then(() => (n$(),r$)),X=b.env.APP_ENV||b.env.NODE_ENV||"production",q=new G({config:W,environment:X}).generate().toJSON(),Z=`${W.project?.slug||"stacks"}-${X}`,K=new z(b.env.AWS_REGION||"us-east-1"),_="{}";try{_=(await K.getTemplate(Z)).TemplateBody}catch{y.info("No deployed stack found. Showing full template as diff.")}if(_===q)y.info("No changes detected.");else y.info("Changes detected between deployed and local template:"),y.info(`Current template: ${_.length} bytes`),y.info(`New template: ${q.length} bytes`)}catch(G){await r("While running the cloud diff command, there was an issue",{startTime:Y,useSeconds:!0},G.message),b.exit(l.FatalError)}await r("Cloud diff complete",{startTime:Y,useSeconds:!0}),b.exit(l.Success)}),E8(Q,"cloud")}import{runCommit as c8}from"@stacksjs/actions";import{log as l8}from"@stacksjs/logging";import{onUnknownSubcommand as d8}from"@stacksjs/cli";function Jz(Q){let $={commit:"Commit your stashed changes",project:"Target a specific project",verbose:"Enable verbose output"};Q.command("commit",$.commit).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{l8.debug("Running `buddy commit` ...",J),await c8(J)}),d8(Q,"commit")}import p8 from"process";import{log as r8,onUnknownSubcommand as n8}from"@stacksjs/cli";function Wz(Q){let $={completion:"Generate shell completion scripts",shell:"Shell type (bash, zsh, fish)"};Q.command("completion [shell]",$.completion).option("-s, --shell [shell]",$.shell).example("buddy completion bash").example("buddy completion zsh").example("buddy completion fish").example("buddy completion bash > /usr/local/etc/bash_completion.d/buddy").action(async(J,Y)=>{r8.debug("Running `buddy completion` ...",Y);let G=J||Y.shell||"bash",W=(Q.commands||[]).map((X)=>X.name).filter(Boolean);switch(G){case"bash":console.log(a8(W));break;case"zsh":console.log(i8(W));break;case"fish":console.log(s8(W));break;default:console.error(`Unknown shell: ${G}`),console.error("Supported shells: bash, zsh, fish"),p8.exit(1)}}),n8(Q,"completion")}function a8(Q){return`# buddy completion for bash
185
+ `}}async sendEmail(Q){try{let $=Q.dataBuffer,J=await this.ses.sendRawEmail({source:Q.mailFrom,destinations:Q.rcptTo,rawMessage:$});if(console.log(`SMTP: Email sent via SES, MessageId: ${J.MessageId}`),this.s3&&this.config.sentBucket)try{let Y=`${this.config.sentPrefix||"sent/"}${Q.email}/${Date.now()}-${J.MessageId}`;await this.s3.putObject({bucket:this.config.sentBucket,key:Y,body:$,contentType:"message/rfc822"}),console.log(`SMTP: Email stored in S3: ${Y}`)}catch(Y){console.error("SMTP: Failed to store sent email in S3 (email was sent successfully):",Y.message)}this.send(Q,`250 OK Message accepted, ID: ${J.MessageId}`),this.resetSession(Q)}catch($){console.error("SMTP: Failed to send email:",$.message),this.send(Q,`451 Failed to send: ${$.message}`),this.resetSession(Q)}}resetSession(Q){Q.state="ready",Q.mailFrom=void 0,Q.rcptTo=[],Q.dataBuffer=""}}async function vJ(Q){let $=new n2(Q);return await $.start(),$}var z9=p(()=>{$9();J9()});import k0 from"process";import{bold as v7,dim as x0,green as G5,intro as z5,log as e,onUnknownSubcommand as W5}from"@stacksjs/cli";import{storage as w3}from"@stacksjs/storage";function _G(Q){Q.command("about","Display diagnostic information about Stacks").action(async()=>{e.debug("Running `buddy about` ..."),await z5("buddy about");try{let J=(await w3.readPackageJson("./package.json")).version||"unknown",Y=k0.versions.bun||"N/A",G=k0.versions.node||"N/A",z=k0.platform,W=k0.arch,X=k0.version,H=k0.env.NODE_ENV||k0.env.APP_ENV||"development";if(e.info(""),e.info(G5(v7("Stacks Framework"))),e.info(x0("\u2500".repeat(50))),e.info(""),e.info(v7("Version Information:")),e.info(` Stacks: ${x0(J)}`),e.info(` Bun: ${x0(Y)}`),G!=="N/A")e.info(` Node: ${x0(G)}`);e.info(""),e.info(v7("Environment:")),e.info(` Mode: ${x0(H)}`),e.info(` OS: ${x0(`${z} ${W}`)}`),e.info(` Runtime: ${x0(X)}`),e.info(""),e.info(v7("Configuration:")),e.info(` Cache: ${x0("file")}`),e.info(` Debug: ${x0(k0.env.DEBUG?"enabled":"disabled")}`),e.info("")}catch($){e.error("Failed to retrieve system information:",$),k0.exit(1)}}),W5(Q,"about")}import n0 from"process";import{runAction as S7}from"@stacksjs/actions";import{intro as E7,log as N7,onUnknownSubcommand as X5,outro as a0}from"@stacksjs/cli";import{Action as C7}from"@stacksjs/enums";import{ExitCode as i0}from"@stacksjs/types";function RG(Q){let $={setup:"Set up authentication (migrations + personal access client)",token:"Create a personal access client token",client:"Create a new OAuth client",prune:"Prune expired and revoked tokens",project:"Target a specific project",verbose:"Enable verbose output"};Q.command("auth:setup",$.setup).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{N7.debug("Running `buddy auth:setup` ...",J);let Y=await E7("buddy auth:setup"),G=await S7(C7.AuthSetup,J);if(G.isErr)await a0("While setting up authentication, there was an issue",{startTime:Y,useSeconds:!0},G.error),n0.exit(i0.FatalError);await a0("Authentication setup completed successfully.",{startTime:Y,useSeconds:!0}),n0.exit(i0.Success)}),Q.command("auth:token",$.token).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{N7.debug("Running `buddy auth:token` ...",J);let Y=await E7("buddy auth:token"),G=await S7(C7.CreatePersonalAccessClient,J);if(G.isErr)await a0("While creating the personal access client token, there was an issue",{startTime:Y,useSeconds:!0},G.error),n0.exit(i0.FatalError);await a0("Personal access client token created successfully.",{startTime:Y,useSeconds:!0}),n0.exit(i0.Success)}),Q.command("auth:client",$.client).option("-n, --name [name]","Client name",{default:"OAuth Client"}).option("-r, --redirect [redirect]","Redirect URI",{default:"http://localhost"}).option("--personal","Create a personal access client",{default:!1}).option("--password","Create a password grant client",{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{N7.debug("Running `buddy auth:client` ...",J);let Y=await E7("buddy auth:client"),G=await S7(C7.AuthClient,J);if(G.isErr)await a0("While creating the OAuth client, there was an issue",{startTime:Y,useSeconds:!0},G.error),n0.exit(i0.FatalError);await a0("OAuth client created successfully.",{startTime:Y,useSeconds:!0}),n0.exit(i0.Success)}),Q.command("auth:prune",$.prune).option("--expired","Prune expired tokens (default: true)",{default:!0}).option("--revoked","Prune revoked tokens (default: true)",{default:!0}).option("-d, --days [days]","Prune revoked tokens older than N days",{default:7}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{N7.debug("Running `buddy auth:prune` ...",J);let Y=await E7("buddy auth:prune"),G=await S7(C7.AuthPrune,J);if(G.isErr)await a0("While pruning tokens, there was an issue",{startTime:Y,useSeconds:!0},G.error),n0.exit(i0.FatalError);await a0("Token pruning completed successfully.",{startTime:Y,useSeconds:!0}),n0.exit(i0.Success)}),X5(Q,"auth")}import l$ from"process";import{intro as Z2,log as I0,onUnknownSubcommand as q5,outro as h7}from"@stacksjs/cli";import{Action as Y0}from"@stacksjs/enums";import{ExitCode as d$}from"@stacksjs/types";var K2;async function G0(...Q){if(!K2)K2=(await import("@stacksjs/actions")).runAction;return K2(...Q)}function AG(Q){let $={build:"Build any of your libraries (packages) for production use",components:"Build your component library",webComponents:"Build your framework agnostic web component library",elements:"An alias to the -w flag",buddy:"Build the Buddy binary",functions:"Build your function library",desktop:"Build the Desktop Application",pages:"Build your frontend",docs:"Build your documentation",framework:"Build Stacks framework",cli:"Automagically build the CLI",server:"Build the Stacks cloud server (Docker image)",select:"What are you trying to build?",project:"Target a specific project",verbose:"Enable verbose output"};Q.command("build [type]",$.build).option("-c, --components",$.components).option("-w, --web-components",$.webComponents).option("-e, --elements",$.elements).option("-f, --functions",$.functions).option("-p, --views",$.pages).option("--pages",$.pages).option("-d, --docs",$.docs).option("-b, --buddy",$.buddy,{default:!1}).option("-s, --stacks",$.framework,{default:!1}).option("--project [project]",$.project,{default:!1}).option("--server",$.server,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J,Y)=>{switch(I0.debug("Running `buddy build` ...",Y),J){case"components":Y.components=!0;break;case"web-components":Y.webComponents=!0;break;case"functions":Y.functions=!0;break;case"views":Y.views=!0;break;case"docs":Y.docs=!0;break;case"buddy":Y.buddy=!0;break;case"cli":Y.buddy=!0;break;case"stacks":Y.stacks=!0;break;case"server":Y.server=!0;break;default:break}if(H5(Y))Y.stacks=!0;if(Y.docs)await G0(Y0.BuildDocs);if(Y.components)await G0(Y0.BuildComponentLibs);if(Y.webComponents)await G0(Y0.BuildWebComponentLib);if(Y.functions)await G0(Y0.BuildFunctionLib);if(Y.views)await G0(Y0.BuildViews);if(Y.stacks)await G0(Y0.BuildStacks);if(Y.buddy)await G0(Y0.BuildCli);if(Y.server)await G0(Y0.BuildServer);l$.exit(d$.Success)}),Q.command("build:components","Automagically build component libraries for production use & npm/CDN distribution").alias("prod:components").option("-c, --components",$.components,{default:!0}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{I0.debug("Running `buddy build:components` ...",J),await G0(Y0.BuildComponentLibs,J)}),Q.command("build:cli",$.cli).alias("prod:cli").option("-b, --buddy",$.buddy,{default:!0}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{I0.debug("Running `buddy build:cli` ...",J),await G0(Y0.BuildCli,J)}),Q.command("build:server",$.server).alias("prod:server").alias("build:docker").option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{I0.debug("Running `buddy build:server` ...",J),await G0(Y0.BuildServer,J)}),Q.command("build:functions","Automagically build function library for npm/CDN distribution").option("-f, --functions",$.functions,{default:!0}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{I0.debug("Running `buddy build:functions` ...",J),await G0(Y0.BuildFunctionLib,J)}),Q.command("build:web-components","Automagically build Web Component library for npm/CDN distribution").alias("build:wc").alias("prod:web-components").alias("prod:wc").option("-w, --web-components",$.webComponents,{default:!0}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{I0.debug("Running `buddy build:web-components` ...",J),await G0(Y0.BuildWebComponentLib,J)}),Q.command("build:docs","Automagically build your documentation site.").alias("prod:docs").alias("build:documentation").alias("prod:documentation").option("-d, --docs",$.docs,{default:!0}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{I0.debug("Running `buddy build:docs` ...",J),await G0(Y0.BuildDocs,J)}),Q.command("build:core","Automagically build the Stacks core.").option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{I0.debug("Running `buddy build:core` ...",J);let Y=await Z2("buddy build:core"),G=await G0(Y0.BuildCore,J);if(G.isErr)I0.error("Failed to build the Stacks core.",G.error),l$.exit(d$.FatalError);await h7("Core packages built successfully",{startTime:Y,useSeconds:!0})}),Q.command("build:desktop",$.desktop).alias("prod:desktop").option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{I0.debug("Running `buddy build:desktop` ...",J);let Y=await Z2("buddy build:desktop"),G=await G0(Y0.BuildDesktop,J);if(G.isErr)await h7("While running the build:desktop command, there was an issue",{startTime:Y,useSeconds:!0},G.error),l$.exit(d$.FatalError);console.log(""),await h7("Exited",{startTime:Y,useSeconds:!0}),l$.exit(d$.Success)}),Q.command("build:stacks","Build the Stacks framework.").option("-s, --stacks",$.framework,{default:!0}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{I0.debug("Running `buddy build:stacks` ...",J);let Y=await Z2("buddy build:stacks"),G=await G0(Y0.BuildStacks,J);if(G.isErr)I0.error("Failed to build Stacks.",G.error),l$.exit(d$.FatalError);await h7("Stacks built successfully",{startTime:Y,useSeconds:!0})}),q5(Q,"build")}function H5(Q){return!Q.components&&!Q.webComponents&&!Q.elements&&!Q.functions&&!Q.views&&!Q.docs&&!Q.stacks&&!Q.buddy&&!Q.server}import Z5 from"process";import{runAction as K5}from"@stacksjs/actions";import{intro as _5,log as U5,onUnknownSubcommand as L5,outro as M3}from"@stacksjs/cli";import{Action as F5}from"@stacksjs/enums";import{ExitCode as O5}from"@stacksjs/types";function CG(Q){let $={changelog:"Create a CHANGELOG.md file",quiet:"Minimal output",dryRun:"Do not write the file, just output the changes",project:"Target a specific project",verbose:"Enable verbose output"};Q.command("changelog",$.changelog).option("-q, --quiet",$.quiet,{default:!1}).option("-d, --dry-run",$.dryRun,{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{U5.debug("Running `buddy changelog` ...",J);let Y=await _5("buddy changelog"),G=await K5(F5.Changelog,J);if(G.isErr)await M3("While running the changelog command, there was an issue",{...J,startTime:Y,useSeconds:!0},G.error),Z5.exit(O5.FatalError);await M3("Generated CHANGELOG.md",{...J,startTime:Y,useSeconds:!0,type:"success"})}),L5(Q,"changelog")}import _2 from"process";import{runAction as V5}from"@stacksjs/actions";import{intro as B5,log as T3,onUnknownSubcommand as R5,outro as I3}from"@stacksjs/cli";import{Action as w5}from"@stacksjs/enums";import{ExitCode as U2}from"@stacksjs/types";function gG(Q){let $={clean:"Removes all node_modules & lock files",project:"Target a specific project",verbose:"Enable verbose output"};Q.command("clean",$.clean).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{if(T3.debug("Running `buddy clean` ...",J),!Q.isForce&&!Q.isNoInteraction){let{confirm:z}=await import("@stacksjs/cli");if(!await z({message:"This will remove all node_modules and lock files. Continue?",initial:!1}))T3.info("Clean cancelled"),_2.exit(U2.Success)}let Y=await B5("buddy clean"),G=await V5(w5.Clean,J);if(G.isErr)await I3("While running the clean command, there was an issue",{startTime:Y,useSeconds:!0},G.error),_2.exit(U2.FatalError);await I3("Cleaned up",{startTime:Y,useSeconds:!0,message:"Cleaned up"}),_2.exit(U2.Success)}),R5(Q,"clean")}import b from"process";import{intro as w$,italic as V2,log as y,onUnknownSubcommand as E5,outro as r,prompts as a$,runCommand as S3,underline as E3}from"@stacksjs/cli";import{addJumpBox as N5,deleteCdkRemnants as C5,deleteIamUsers as h5,deleteJumpBox as B2,deleteLogGroups as D5,deleteParameterStore as b5,deleteStacksBuckets as y5,deleteStacksFunctions as k5,deleteSubnets as x5,deleteVpcs as g5,getCloudFrontDistributionId as N3,getJumpBoxInstanceId as u5}from"@stacksjs/cloud";import{path as C3}from"@stacksjs/path";import{ExitCode as l}from"@stacksjs/types";function i$(Q){if(!Q||typeof Q!=="object")return!1;let $=Q;if(typeof $.isErr==="function")return $.isErr();return!!$.isErr}function s$(Q){if(!Q||typeof Q!=="object")return"Unknown error";return String(Q.error||"Unknown error")}function m5(Q){if(!Q||typeof Q!=="object")return;return Q.value}function oG(Q){let $={cloud:"Interact with the Stacks Cloud",ssh:"SSH into the Stacks Cloud",add:"Add a resource to the Stacks Cloud",remove:"Remove the Stacks Cloud. In case it fails, try again",optimizeCost:"Remove certain resources that may be re-applied at a later time",cleanUp:"Remove all resources that were retained during the cloud deletion",invalidateCache:"Invalidate the CloudFront cache",diff:"Show the diff of the current, undeployed cloud changes ",paths:"The paths to invalidate",project:"Target a specific project",verbose:"Enable verbose output"};Q.command("cloud",$.cloud).option("--ssh",$.ssh,{default:!1}).option("--connect",$.ssh,{default:!1}).option("--invalidate-cache",$.invalidateCache,{default:!1}).option("--paths [paths]",$.paths).option("--diff",$.diff,{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{y.debug("Running `buddy cloud` ...",J);let Y=performance.now();if(J.ssh||J.connect){let G=await u5(),z=await S3(`aws ssm start-session --target ${G}`,{...J,cwd:C3.projectPath(),stdin:"pipe"});if(i$(z))await r("While running the cloud command, there was an issue",{startTime:Y,useSeconds:!0},s$(z)),b.exit(l.FatalError);await r("Exited",{startTime:Y,useSeconds:!0}),b.exit(l.Success)}if(J.invalidateCache){let{confirm:G}=await a$({name:"confirm",type:"confirm",message:"Would you like to invalidate the CDN (CloudFront) cache?"});if(!G)await r("Exited",{startTime:Y,useSeconds:!0}),b.exit(l.Success);y.info("Invalidating the CloudFront cache...");let{AWSCloudFrontClient:z}=await import("@stacksjs/ts-cloud"),W=new z,X=await N3();try{let H=await W.invalidateAll(X);y.success(`Invalidation created: ${H}`),y.info("Status: pending")}catch(H){y.error(`Failed to invalidate CloudFront cache: ${H.message}`)}await r("Exited",{startTime:Y,useSeconds:!0}),b.exit(l.Success)}if(J.diff){try{let{InfrastructureGenerator:G}=await import("@stacksjs/ts-cloud"),{CloudFormationClient:z}=await import("@stacksjs/ts-cloud/aws"),{tsCloud:W}=await Promise.resolve().then(() => (n$(),r$)),X=b.env.APP_ENV||b.env.NODE_ENV||"production",q=new G({config:W,environment:X}).generate().toJSON(),Z=`${W.project?.slug||"stacks"}-${X}`,K=new z(b.env.AWS_REGION||"us-east-1"),_="{}";try{_=(await K.getTemplate(Z)).TemplateBody}catch{y.info("No deployed stack found. Showing full template as diff.")}if(_===q)y.info("No changes detected.");else y.info("Changes detected between deployed and local template:"),y.info(`Current template: ${_.length} bytes`),y.info(`New template: ${q.length} bytes`)}catch(G){y.error(`Failed to compute diff: ${G.message}`)}await r("Cloud diff complete",{startTime:Y,useSeconds:!0}),b.exit(l.Success)}y.info("Not implemented yet. Read more about `buddy cloud` here: https://stacksjs.com/docs/cloud"),b.exit(l.Success)}),Q.command("cloud:add",$.add).option("--jump-box","Remove the jump-box",{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{y.debug("Running `buddy cloud:add` ...",J);let Y=await w$("buddy cloud:add");if(J.jumpBox){let{confirm:G}=await a$({name:"confirm",type:"confirm",message:"Would you like to add a jump-box to your cloud?"});if(!G)await r("Exited",{startTime:Y,useSeconds:!0}),b.exit(l.Success);y.info("The jump-box is getting added to your cloud resources..."),y.info("This takes a few moments, please be patient."),await new Promise((W)=>setTimeout(W,2000));let z=await N5();if(i$(z))await r("While running the cloud:add command, there was an issue",{startTime:Y,useSeconds:!0},s$(z)),b.exit(l.FatalError);y.info(V2("View the jump-box in the AWS console:")),y.info(E3("https://us-east-1.console.aws.amazon.com/ec2/home?region=us-east-1#Instances:instanceState=running")),y.info(V2("Once it finished initializing, you may SSH into it:")),y.info(E3("buddy cloud --ssh")),await r("Your jump-box was added.",{startTime:Y,useSeconds:!0}),b.exit(l.Success)}y.info("This functionality is not yet implemented."),b.exit(l.Success)}),Q.command("cloud:remove",$.remove).alias("cloud:destroy").alias("cloud:rm").alias("undeploy").option("--jump-box","Remove the jump-box",{default:!1}).option("--force","Force deletion of stack in bad state",{default:!1}).option("--yes","Skip confirmation prompts",{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{y.debug("Running `buddy cloud:remove` ...",J);let Y=await w$("buddy cloud:remove");if(J.jumpBox){let{confirm:z}=await a$({name:"confirm",type:"confirm",message:"Would you like to remove your jump-box for now?"});if(!z)await r("Exited",{startTime:Y,useSeconds:!0}),b.exit(l.Success);let W=await B2();if(i$(W))await r("While removing your jump-box, there was an issue",{startTime:Y,useSeconds:!0},s$(W)),b.exit(l.FatalError);await r("Your jump-box was removed.",{startTime:Y,useSeconds:!0}),b.exit(l.Success)}console.log(""),console.log("Removing cloud infrastructure..."),console.log(` ${V2("This typically takes 2-5 minutes.")}`),console.log("");let G=b.env.APP_ENV||b.env.NODE_ENV||"production";if(!b.env.AWS_ACCESS_KEY_ID||!b.env.AWS_SECRET_ACCESS_KEY){let{existsSync:z,readFileSync:W}=await import("fs"),{projectPath:X}=await import("@stacksjs/path"),H=[X(`.env.${G}`),X(".env")];for(let q of H)if(z(q)){let K=W(q,"utf-8").split(`
186
+ `);for(let _ of K){let U=_.trim();if(U.startsWith("#")||!U.includes("="))continue;let[L,...F]=U.split("="),O=F.join("=").replace(/^["']|["']$/g,"");if(L==="AWS_ACCESS_KEY_ID"||L==="AWS_SECRET_ACCESS_KEY"||L==="AWS_REGION"||L==="AWS_ACCOUNT_ID")b.env[L]=O}break}}delete b.env.AWS_PROFILE;try{let{undeployStack:z}=await Promise.resolve().then(() => (v3(),f3)),W=b.env.AWS_REGION||"us-east-1";await z({environment:G,region:W,verbose:J.verbose}),await r("Cloud infrastructure removed",{startTime:Y,useSeconds:!0}),b.exit(l.Success)}catch(z){console.log(""),console.error("\u2717 Failed to remove cloud infrastructure");let W=String(z.message||z);if(W.includes("security token")||W.includes("credentials"))console.log(""),console.error(" AWS credentials are invalid or expired"),console.log(" Check your AWS credentials in .env.production:"),console.log(" - AWS_ACCESS_KEY_ID"),console.log(" - AWS_SECRET_ACCESS_KEY");else if(W.includes("region")||W.includes("AWS_REGION"))console.log(""),console.error(" AWS Region not configured"),console.log(" Add AWS_REGION to your .env.production file");else if(W.includes("AccessDenied"))console.log(""),console.error(" Access denied"),console.log(" Your AWS credentials may not have permission to delete stacks");else console.error(` ${W}`);if(console.log(""),console.log("Troubleshooting:"),console.log(" ./buddy cloud:cleanup - Clean up resources manually"),console.log(" --verbose - Show detailed error information"),console.log(""),J.verbose)console.error("Error details:",z);await r("Failed to remove infrastructure",{startTime:Y,useSeconds:!0}),b.exit(l.FatalError)}}),Q.command("cloud:optimize-cost",$.optimizeCost).option("--jump-box","Remove the jump-box",{default:!0}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{y.debug("Running `buddy cloud:optimize-cost` ...",J);let Y=await w$("buddy cloud:optimize-cost");if(J.jumpBox){let{confirm:G}=await a$({name:"confirm",type:"confirm",message:"Would you like to remove your jump-box to optimize your costs?"});if(!G)await r("Exited",{startTime:Y,useSeconds:!0}),b.exit(l.Success);await B2(),await r("Your jump-box was removed & cost optimizations are applied.",{startTime:Y,useSeconds:!0}),b.exit(l.Success)}await r("No cost optimization was applied",{startTime:Y,useSeconds:!0}),b.exit(l.Success)}),Q.command("cloud:cleanup",$.cleanUp).alias("cloud:clean-up").option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{y.debug("Running `buddy cloud:cleanup` ...",J);let Y=await w$("buddy cloud:cleanup");delete b.env.AWS_PROFILE,y.info("Cleaning up your cloud resources will take a while to complete. Please be patient."),await new Promise((W)=>setTimeout(W,2000));let G=[{label:"jump-boxes",fn:B2,ignoreErrors:["Jump-box not found"]},{label:"retained S3 buckets",fn:y5},{label:"retained Lambda functions",fn:k5,ignoreErrors:["No stacks functions found"]},{label:"remaining Stacks logs",fn:D5},{label:"stored parameters",fn:b5},{label:"VPCs",fn:g5},{label:"Subnets",fn:x5},{label:"CDK remnants",fn:C5},{label:"IAM users",fn:h5}],z=[];for(let W of G){y.info(`Removing any ${W.label}...`);try{let X=await W.fn();if(i$(X)){let H=s$(X);if(!W.ignoreErrors?.includes(H))y.warn(`${W.label} cleanup issue: ${H}`),z.push({label:W.label,error:H})}else{let H=m5(X);if(H)y.info(String(H))}}catch(X){let H=X.message||"AWS SDK error";y.warn(`${W.label} cleanup skipped: ${H}`),z.push({label:W.label,error:H})}}if(z.length>0){y.warn(`Cleanup completed with ${z.length} issue(s):`);for(let{label:W,error:X}of z)y.warn(` - ${W}: ${X}`)}await r("AWS resources have been removed",{startTime:Y,useSeconds:!0}),b.exit(l.Success)}),Q.command("cloud:invalidate-cache",$.invalidateCache).option("--paths [paths]",$.paths,{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{y.debug("Running `buddy cloud:invalidate-cache` ...",J);let Y=await w$("buddy cloud:invalidate-cache"),{confirm:G}=await a$({name:"confirm",type:"confirm",message:"Would you like to invalidate the CloudFront cache?"});if(!G)await r("Exited",{startTime:Y,useSeconds:!0}),b.exit(l.Success);y.info("Invalidating the CloudFront cache...");let z=await N3();if(!z)await r("Could not resolve CloudFront distribution ID",{startTime:Y,useSeconds:!0},"Ensure your cloud stack is deployed before invalidating cache."),b.exit(l.FatalError);let W=J.paths?String(J.paths):"/*",X=await S3(`aws cloudfront create-invalidation --distribution-id ${z} --paths ${W}`,{...J,cwd:C3.projectPath(),stdin:"pipe"});if(i$(X))await r("While running the cloud command, there was an issue",{startTime:Y,useSeconds:!0},s$(X)),b.exit(l.FatalError);await r("Exited",{startTime:Y,useSeconds:!0}),b.exit(l.Success)}),Q.command("cloud:diff",$.diff).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{y.debug("Running `buddy cloud:diff` ...",J);let Y=await w$("buddy cloud:diff");try{let{InfrastructureGenerator:G}=await import("@stacksjs/ts-cloud"),{CloudFormationClient:z}=await import("@stacksjs/ts-cloud/aws"),{tsCloud:W}=await Promise.resolve().then(() => (n$(),r$)),X=b.env.APP_ENV||b.env.NODE_ENV||"production",q=new G({config:W,environment:X}).generate().toJSON(),Z=`${W.project?.slug||"stacks"}-${X}`,K=new z(b.env.AWS_REGION||"us-east-1"),_="{}";try{_=(await K.getTemplate(Z)).TemplateBody}catch{y.info("No deployed stack found. Showing full template as diff.")}if(_===q)y.info("No changes detected.");else y.info("Changes detected between deployed and local template:"),y.info(`Current template: ${_.length} bytes`),y.info(`New template: ${q.length} bytes`)}catch(G){await r("While running the cloud diff command, there was an issue",{startTime:Y,useSeconds:!0},G.message),b.exit(l.FatalError)}await r("Cloud diff complete",{startTime:Y,useSeconds:!0}),b.exit(l.Success)}),E5(Q,"cloud")}import{runCommit as c5}from"@stacksjs/actions";import{log as l5}from"@stacksjs/logging";import{onUnknownSubcommand as d5}from"@stacksjs/cli";function Jz(Q){let $={commit:"Commit your stashed changes",project:"Target a specific project",verbose:"Enable verbose output"};Q.command("commit",$.commit).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{l5.debug("Running `buddy commit` ...",J),await c5(J)}),d5(Q,"commit")}import p5 from"process";import{log as r5,onUnknownSubcommand as n5}from"@stacksjs/cli";function Wz(Q){let $={completion:"Generate shell completion scripts",shell:"Shell type (bash, zsh, fish)"};Q.command("completion [shell]",$.completion).option("-s, --shell [shell]",$.shell).example("buddy completion bash").example("buddy completion zsh").example("buddy completion fish").example("buddy completion bash > /usr/local/etc/bash_completion.d/buddy").action(async(J,Y)=>{r5.debug("Running `buddy completion` ...",Y);let G=J||Y.shell||"bash",W=(Q.commands||[]).map((X)=>X.name).filter(Boolean);switch(G){case"bash":console.log(a5(W));break;case"zsh":console.log(i5(W));break;case"fish":console.log(s5(W));break;default:console.error(`Unknown shell: ${G}`),console.error("Supported shells: bash, zsh, fish"),p5.exit(1)}}),n5(Q,"completion")}function a5(Q){return`# buddy completion for bash
187
187
 
188
188
  _buddy_completion() {
189
189
  local cur prev commands
@@ -216,7 +216,7 @@ complete -F _buddy_completion buddy
216
216
  # - macOS: /usr/local/etc/bash_completion.d/buddy
217
217
  #
218
218
  # Then reload your shell or run: source ~/.bashrc
219
- `}function i8(Q){return`#compdef buddy
219
+ `}function i5(Q){return`#compdef buddy
220
220
 
221
221
  # buddy completion for zsh
222
222
 
@@ -264,7 +264,7 @@ _buddy "$@"
264
264
  # Then add to your ~/.zshrc:
265
265
  # fpath=(~/.zsh/completions $fpath)
266
266
  # autoload -Uz compinit && compinit
267
- `}function s8(Q){return`# buddy completion for fish
267
+ `}function s5(Q){return`# buddy completion for fish
268
268
 
269
269
  # Remove old completions
270
270
  complete -c buddy -e
@@ -289,18 +289,18 @@ complete -c buddy -s f -l force -d "Skip confirmation prompts"
289
289
  # ~/.config/fish/completions/buddy.fish
290
290
  #
291
291
  # Fish will automatically load it on startup
292
- `}import{existsSync as o8,readFileSync as t8,writeFileSync as e8}from"fs";import R2 from"process";import{italic as $5,log as Z$}from"@stacksjs/cli";import{projectPath as Q5}from"@stacksjs/path";var w2=[{id:"0.65-cache-driver-rename",description:"Rename `cache.driver` to `cache.default` (introduced in 0.65).",files:["cache.ts"],shouldApply:(Q)=>/\bdriver\s*:/.test(Q)&&!Q.includes("default:"),apply:(Q)=>Q.replace(/(\bcache\b[\s\S]*?)\bdriver(\s*:)/m,"$1default$2")},{id:"0.68-search-engine-name",description:"Rename `searchEngine.driver` to `searchEngine.default` (matches other configs).",files:["search-engine.ts"],shouldApply:(Q)=>/\bdriver\s*:/.test(Q),apply:(Q)=>Q.replace(/\bdriver(\s*:)/g,"default$1")},{id:"0.70-ports-string-to-number",description:'Convert string port values like `"3000"` to numbers (TypeScript types now require number).',files:["ports.ts"],shouldApply:(Q)=>/:\s*['"]\d+['"]/.test(Q),apply:(Q)=>Q.replace(/:\s*['"](\d+)['"]/g,": $1")}];async function J5(Q){let $=[],J=[],Y=Q.only?w2.filter((G)=>G.id===Q.only):w2;if(Y.length===0)return Z$.warn(`No matching codemods. Available: ${w2.map((G)=>G.id).join(", ")}`),{changed:$,skipped:J};for(let G of Y){Z$.info(`Codemod ${$5(G.id)} \u2014 ${G.description}`);for(let z of G.files){let W=Q5(`config/${z}`);if(!o8(W)){J.push(`${W} (missing)`);continue}let X=t8(W,"utf-8");if(!G.shouldApply(X)){J.push(`${W} (no changes)`);continue}let H=G.apply(X);if(H===X){J.push(`${W} (no changes)`);continue}if(Q.dryRun)Z$.info(`[dry-run] would update ${W}`),Y5(X,H);else e8(W,H),Z$.success(`updated ${W}`);$.push(W)}}return{changed:$,skipped:J}}function Y5(Q,$){let J=Q.split(`
292
+ `}import{existsSync as o5,readFileSync as t5,writeFileSync as e5}from"fs";import R2 from"process";import{italic as $8,log as Z$}from"@stacksjs/cli";import{projectPath as Q8}from"@stacksjs/path";var w2=[{id:"0.65-cache-driver-rename",description:"Rename `cache.driver` to `cache.default` (introduced in 0.65).",files:["cache.ts"],shouldApply:(Q)=>/\bdriver\s*:/.test(Q)&&!Q.includes("default:"),apply:(Q)=>Q.replace(/(\bcache\b[\s\S]*?)\bdriver(\s*:)/m,"$1default$2")},{id:"0.68-search-engine-name",description:"Rename `searchEngine.driver` to `searchEngine.default` (matches other configs).",files:["search-engine.ts"],shouldApply:(Q)=>/\bdriver\s*:/.test(Q),apply:(Q)=>Q.replace(/\bdriver(\s*:)/g,"default$1")},{id:"0.70-ports-string-to-number",description:'Convert string port values like `"3000"` to numbers (TypeScript types now require number).',files:["ports.ts"],shouldApply:(Q)=>/:\s*['"]\d+['"]/.test(Q),apply:(Q)=>Q.replace(/:\s*['"](\d+)['"]/g,": $1")}];async function J8(Q){let $=[],J=[],Y=Q.only?w2.filter((G)=>G.id===Q.only):w2;if(Y.length===0)return Z$.warn(`No matching codemods. Available: ${w2.map((G)=>G.id).join(", ")}`),{changed:$,skipped:J};for(let G of Y){Z$.info(`Codemod ${$8(G.id)} \u2014 ${G.description}`);for(let z of G.files){let W=Q8(`config/${z}`);if(!o5(W)){J.push(`${W} (missing)`);continue}let X=t5(W,"utf-8");if(!G.shouldApply(X)){J.push(`${W} (no changes)`);continue}let H=G.apply(X);if(H===X){J.push(`${W} (no changes)`);continue}if(Q.dryRun)Z$.info(`[dry-run] would update ${W}`),Y8(X,H);else e5(W,H),Z$.success(`updated ${W}`);$.push(W)}}return{changed:$,skipped:J}}function Y8(Q,$){let J=Q.split(`
293
293
  `),Y=$.split(`
294
294
  `),G=Math.max(J.length,Y.length);for(let z=0;z<G;z++){let W=J[z],X=Y[z];if(W===X)continue;if(W!==void 0)R2.stdout.write(` - ${W}
295
295
  `);if(X!==void 0)R2.stdout.write(` + ${X}
296
296
  `)}R2.stdout.write(`
297
- `)}function _z(Q){Q.command("config:migrate","Apply config-shape codemods for the latest Stacks version").option("--dry-run","Preview changes without writing",{default:!1}).option("--only [id]","Run a single codemod by id",{default:""}).action(async($)=>{Z$.info("Running `buddy config:migrate` ...");let{changed:J,skipped:Y}=await J5({dryRun:Boolean($.dryRun),only:$.only?.length?$.only:void 0});if(Z$.info(`Changed: ${J.length}, Skipped: ${Y.length}`),Y.length>0)for(let G of Y)Z$.debug(` skipped: ${G}`)})}import s0 from"process";import{log as M2,onUnknownSubcommand as G5,outro as h3,runCommand as z5}from"@stacksjs/cli";import{path as W5}from"@stacksjs/path";import{ExitCode as y7}from"@stacksjs/types";function Bz(Q){let $={configure:"Configure options",aws:"Configure the AWS connection",project:"Target a specific project",profile:"The AWS profile to use",verbose:"Enable verbose output"};Q.command("configure",$.configure).option("--aws",$.aws,{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{if(M2.debug("Running `buddy configure` ...",J),J?.aws)await D3(J),s0.exit(y7.Success);M2.info("Not implemented yet. Please use the --aws flag to configure AWS."),s0.exit(y7.Success)}),Q.command("configure:aws",$.aws).option("-p, --project [project]",$.project,{default:!1}).option("--profile",$.profile,{default:s0.env.AWS_PROFILE}).option("--verbose",$.verbose,{default:!1}).option("--access-key-id","The AWS access key").option("--secret-access-key","The AWS secret access key").option("--region","The AWS region").option("--output","The AWS output format").option("--quiet","Suppress output").action(async(J)=>{M2.debug("Running `buddy configure:aws` ...",J),await D3(J),s0.exit(y7.Success)}),G5(Q,"configure")}async function D3(Q){let $=performance.now(),J=Q?.accessKeyId??s0.env.AWS_ACCESS_KEY_ID,Y=Q?.secretAccessKey??s0.env.AWS_SECRET_ACCESS_KEY,G="us-east-1",z=Q?.output??"json",W=s0.env.AWS_PROFILE??Q?.profile,X=W?`aws configure --profile ${W}`:"aws configure",H=`${J}
297
+ `)}function _z(Q){Q.command("config:migrate","Apply config-shape codemods for the latest Stacks version").option("--dry-run","Preview changes without writing",{default:!1}).option("--only [id]","Run a single codemod by id",{default:""}).action(async($)=>{Z$.info("Running `buddy config:migrate` ...");let{changed:J,skipped:Y}=await J8({dryRun:Boolean($.dryRun),only:$.only?.length?$.only:void 0});if(Z$.info(`Changed: ${J.length}, Skipped: ${Y.length}`),Y.length>0)for(let G of Y)Z$.debug(` skipped: ${G}`)})}import s0 from"process";import{log as M2,onUnknownSubcommand as G8,outro as h3,runCommand as z8}from"@stacksjs/cli";import{path as W8}from"@stacksjs/path";import{ExitCode as y7}from"@stacksjs/types";function Bz(Q){let $={configure:"Configure options",aws:"Configure the AWS connection",project:"Target a specific project",profile:"The AWS profile to use",verbose:"Enable verbose output"};Q.command("configure",$.configure).option("--aws",$.aws,{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{if(M2.debug("Running `buddy configure` ...",J),J?.aws)await D3(J),s0.exit(y7.Success);M2.info("Not implemented yet. Please use the --aws flag to configure AWS."),s0.exit(y7.Success)}),Q.command("configure:aws",$.aws).option("-p, --project [project]",$.project,{default:!1}).option("--profile",$.profile,{default:s0.env.AWS_PROFILE}).option("--verbose",$.verbose,{default:!1}).option("--access-key-id","The AWS access key").option("--secret-access-key","The AWS secret access key").option("--region","The AWS region").option("--output","The AWS output format").option("--quiet","Suppress output").action(async(J)=>{M2.debug("Running `buddy configure:aws` ...",J),await D3(J),s0.exit(y7.Success)}),G8(Q,"configure")}async function D3(Q){let $=performance.now(),J=Q?.accessKeyId??s0.env.AWS_ACCESS_KEY_ID,Y=Q?.secretAccessKey??s0.env.AWS_SECRET_ACCESS_KEY,G="us-east-1",z=Q?.output??"json",W=s0.env.AWS_PROFILE??Q?.profile,X=W?`aws configure --profile ${W}`:"aws configure",H=`${J}
298
298
  ${Y}
299
299
  us-east-1
300
300
  ${z}
301
- `,q=await z5(X,{cwd:W5.projectPath(),stdin:"pipe",input:H});if(q.isErr)await h3("While running the cloud command, there was an issue",{startTime:$,useSeconds:!0},q.error),s0.exit(y7.FatalError);if(Q?.quiet)return;await h3("Exited",{startTime:$,useSeconds:!0})}m7();import{chmodSync as f5}from"fs";import g0 from"process";import{runAction as v5}from"@stacksjs/actions";import{bold as S5,cyan as E5,dim as N5,intro as C5,log as n,onUnknownSubcommand as h5,runCommand as c7}from"@stacksjs/cli";import{Action as D5}from"@stacksjs/enums";import{resolve as k3}from"@stacksjs/path";import{isFolder as b5}from"@stacksjs/storage";import{ExitCode as o0}from"@stacksjs/types";import{useOnline as y5}from"@stacksjs/utils";function uz(Q){let $={name:"The name of the project",command:"Create a new Stacks project",ui:"Are you building a UI?",components:"Are you building UI components?",webComponents:"Automagically built optimized custom elements/web components?",vue:"Automagically built a Vue component library?",views:"How about views?",functions:"Are you developing functions/composables?",api:"Are you building an API?",database:"Do you need a database?",notifications:"Do you need notifications? e.g. email, SMS, push or chat notifications",cache:"Do you need caching?",email:"Do you need email?",project:"Target a specific project",verbose:"Enable verbose output"};Q.command("new [name]",$.command).alias("create [name]").option("-n, --name [name]",$.name,{default:!1}).option("-u, --ui",$.ui,{default:!0}).option("-c, --components",$.components,{default:!0}).option("-w, --web-components",$.webComponents,{default:!0}).option("-v, --vue",$.vue,{default:!0}).option("-p, --views",$.views,{default:!0}).option("-f, --functions",$.functions,{default:!0}).option("-a, --api",$.api,{default:!0}).option("-d, --database",$.database,{default:!0}).option("-ca, --cache",$.cache,{default:!1}).option("-e, --email",$.email,{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J,Y)=>{n.debug("Running `buddy new <name>` ...",Y);let G=await C5("buddy new");J=J??Y.name;let z=k3(g0.cwd(),J);k5(z),x5();let W=await g5(J,z,Y);if(W.isErr)n.error(W.error),g0.exit(o0.FatalError);if(await m5(z,Y),u5(z),await c5(z,Y),G){let X=performance.now()-G;n.success(N5(`[${X.toFixed(2)}ms] Completed`))}n.info(S5("Welcome to the Stacks Framework! \u269B\uFE0F")),n.info("To learn more, visit https://stacksjs.com"),g0.exit(o0.Success)}),h5(Q,"new")}function k5(Q){if(b5(Q))n.error(`Path ${Q} already exists`),g0.exit(o0.FatalError)}function x5(){if(!y5())n.info("It appears you are disconnected from the internet."),n.info("The Stacks setup requires a brief internet connection for setup."),n.info("For instance, it installs your dependencies from."),g0.exit(o0.FatalError)}async function g5(Q,$,J){n.info("Setting up your stack.");let Y=await c7(`bunx --bun @stacksjs/gitit stacks ${Q}`,J);return n.success(`Successfully scaffolded your project at ${E5($)}`),Y}function u5(Q){for(let $ of["buddy","bootstrap"])try{f5(k3(Q,$),493)}catch{}}async function m5(Q,$){n.info("Ensuring your environment is ready..."),await T$(),await I$(Q),n.success("Environment is ready")}async function c5(Q,$){n.info("Installing & setting up Stacks"),n.info("Running bun install...");let J=await c7("bun install",{...$,cwd:Q});if(J?.isErr)n.error(J.error),g0.exit(o0.FatalError);if(n.info("Copying .env.example \u2192 .env"),J=await c7("cp .env.example .env",{...$,cwd:Q}),J?.isErr)n.error(J.error),g0.exit(o0.FatalError);n.info("Generating application key...");let Y=await v5(D5.KeyGenerate,{...$,cwd:Q});if(Y.isErr)n.error(Y.error),g0.exit(o0.FatalError);if(n.info("Initializing git repository..."),J=await c7("git init",{...$,cwd:Q}),J.isErr)n.error(J.error),g0.exit(o0.FatalError);n.success("Installed & set-up \uD83D\uDE80")}import{existsSync as j0,readFileSync as t0,readdirSync as o5,statSync as t5}from"fs";import{homedir as A$}from"os";import{join as _$}from"path";import E from"process";import{runAction as e5}from"@stacksjs/actions";import{italic as Q7,onUnknownSubcommand as $6,outro as l7,prompts as j$}from"@stacksjs/cli";import{app as p3,email as c,cloud as l3}from"@stacksjs/config";import{runAction as l5}from"@stacksjs/actions";import{config as g3}from"@stacksjs/config";import{Action as d5}from"@stacksjs/enums";import{err as rz,handleError as nz,ok as az}from"@stacksjs/error-handling";import{log as Z0}from"@stacksjs/logging";import{path as p5}from"@stacksjs/path";import{fs as x3}from"@stacksjs/storage";import{Route53Client as r5,Route53DomainsClient as u3}from"@stacksjs/ts-cloud";function n5(Q){if(!Q)return;return Q.replace(/^https?:\/\//,"").replace(/\/$/,"")}function a5(Q){if(!/^[a-zA-Z0-9.-]+$/.test(Q))throw Error(`Invalid nameserver value: ${Q}`);return Q}function T2(Q){try{let $=p5.projectConfigPath("dns.ts"),Y=x3.readFileSync($,"utf-8").replace(/nameservers: \[.*?\]/s,`nameservers: [${Q.map((G)=>`'${a5(G)}'`).join(", ")}]`);x3.writeFileSync($,Y,"utf-8"),Z0.info("Nameservers have been set.")}catch($){Z0.error("Error updating nameservers:",$)}}async function i5(Q){if(Z0.debug("Getting nameservers for domain:",Q),!Q)return[];try{return(await new u3().getDomainDetail({DomainName:Q}))?.Nameservers?.map((Y)=>Y.Name)||[]}catch($){return Z0.debug("Domain not registered via Route53 Domains:",$),[]}}async function s5(Q,$){if(!$)$=g3.app.url;let J=await i5($);if(!J||J.length===0)return Z0.debug("Domain is not registered via Route53 Domains - skipping automatic nameserver update"),T2(Q),!1;if(JSON.stringify(J.sort())!==JSON.stringify(Q.sort())){Z0.info("Updating your domain nameservers to match the ones in your hosted zone..."),Z0.debug("Hosted zone nameservers:",Q),Z0.debug("Domain nameservers:",J);try{return await new u3().updateDomainNameservers({DomainName:$,Nameservers:Q.map((G)=>({Name:G}))}),T2(Q),Z0.info("Nameservers updated."),!0}catch(Y){return Z0.debug("Failed to update nameservers via Route53 Domains:",Y),T2(Q),!1}}return Z0.success("Your nameservers are up to date."),!0}async function m3(Q){if(Z0.debug("Checking if domain has been added to cloud..."),!Q)Q=g3.app.url;if(Q=n5(Q),!Q)return!1;Z0.debug("domainName:",Q);let $=new r5,J=await $.listHostedZonesByName({DNSName:Q});if(Z0.debug("Existing hosted zones:",J),!J||!J.HostedZones||J.HostedZones.length===0)return!1;let Y=J.HostedZones.find((G)=>G.Name===`${Q}.`);if(Y){Z0.debug("Hosted zone found:",Y);let z=(await $.getHostedZone({Id:Y.Id})).DelegationSet?.NameServers||[];return await s5(z,Q),!0}return!1}async function c3(Q){return await l5(d5.DomainsAdd,Q)}m7();import{env as Q6}from"@stacksjs/env";import{Action as J6}from"@stacksjs/enums";import{path as E0}from"@stacksjs/path";import{ExitCode as K0}from"@stacksjs/types";var R={info:(...Q)=>console.log("\u2139",...Q),success:(...Q)=>console.log("\u2713",...Q),warn:(...Q)=>console.log("\u26A0",...Q),error:(...Q)=>console.error("\u2717",...Q),debug:(...Q)=>{if(E.argv.includes("--verbose")||E.argv.includes("-v"))console.log("\uD83D\uDD0D",...Q)}},r3="github.com/mail-os/mail",Y6=`${r3}@0.1.0`,n3="linux-x86_64",I2=["mail","mail-x86_64-linux","mail-x86_64-linux-gnu"];function G6(Q,$,J=8){let Y=new Set($),G=[];if(!j0(Q))return G;function z(W,X){if(X>J)return;for(let H of o5(W)){if(H===".git"||H==="node_modules")continue;let q=_$(W,H),Z=t5(q);if(Z.isDirectory())z(q,X+1);else if(Z.isFile()&&Y.has(H))G.push(q)}}return z(Q,0),G}function A2(Q){let $=t0(Q).slice(0,4);return $[0]===127&&$[1]===69&&$[2]===76&&$[3]===70}function z6(){let Q=_$(A$(),"Code","Tools","pantry","packages","ts-pantry","bin","cli.ts");if(j0(Q))return{command:"bun",args:[Q]};let $=E0.projectPath("pantry/.bin/pantry");if(j0($))return{command:$,args:[]};let J=_$(A$(),".local","share","pantry","global","bin","pantry");if(j0(J))return{command:J,args:[]};return{command:"pantry",args:[]}}async function W6(){let{execFileSync:Q}=await import("child_process"),$=z6();Q($.command,[...$.args,"install",Y6,"--install-dir",E0.projectPath("pantry"),"--platform",n3,"--quiet"],{cwd:E0.projectPath(),stdio:E.argv.includes("--verbose")||E.argv.includes("-v")?"inherit":"pipe",env:E.env})}async function X6(){let Q=[...I2.map(($)=>E0.projectPath(`pantry/.bin/${$}`)),...I2.map(($)=>_$(A$(),".local","share","pantry","global","bin",$))];for(let $ of Q)if(j0($)&&A2($))return $;for(let $ of[E0.projectPath("pantry"),_$(A$(),".local","share","pantry")])for(let J of G6($,I2))if(A2(J))return J;return null}async function q6(Q=!1){let $=E0.projectPath();await T$(),await I$($),await u7({cwd:$,verbose:Q}),await g7($)}function H6(){let Q=_$(A$(),".aws","credentials"),$=_$(A$(),".aws","config");if(!j0(Q))return{};try{let Y=t0(Q,"utf-8").split(`
302
- `),G=["default","stacks"],z="",W={},X={};for(let q of Y){let Z=q.trim(),K=Z.match(/^\[(.+)\]$/);if(K){z=K[1],X[z]={};continue}let _=Z.match(/^(\w+)\s*=\s*(.+)$/);if(_&&z){let[,U,L]=_;if(U==="aws_access_key_id")X[z].accessKeyId=L;else if(U==="aws_secret_access_key")X[z].secretAccessKey=L}}for(let q of G)if(X[q]?.accessKeyId&&X[q]?.secretAccessKey){W=X[q],R.debug(`Using AWS credentials from ~/.aws/credentials [${q}] profile`);break}if(!W.accessKeyId){for(let[q,Z]of Object.entries(X))if(Z.accessKeyId&&Z.secretAccessKey){W=Z,R.debug(`Using AWS credentials from ~/.aws/credentials [${q}] profile`);break}}let H;if(j0($)){let Z=t0($,"utf-8").match(/region\s*=\s*(.+)/);if(Z)H=Z[1].trim()}return{...W,region:H}}catch(J){return R.debug("Failed to read AWS credentials file:",J),{}}}async function d3(Q,$,J,Y){J.info("Setting up email DNS records...");try{let{SESClient:G}=await import("@stacksjs/ts-cloud"),{Route53Client:z}=await import("@stacksjs/ts-cloud"),W=new G($),X=new z($);J.info(`Getting DKIM tokens for ${Q}...`);let q=(await W.getEmailIdentity(Q)).DkimAttributes?.Tokens||[];if(q.length===0){J.warn("No DKIM tokens found - domain may not be set up in SES yet");return}J.info(`Found ${q.length} DKIM tokens`);let K=(await X.listHostedZones()).HostedZones?.find((F)=>F.Name===`${Q}.`);if(!K){J.warn(`Hosted zone not found for ${Q} - DNS records must be added manually`),J.info("DKIM records needed:");for(let F of q)J.info(` CNAME: ${F}._domainkey.${Q} -> ${F}.dkim.amazonses.com`);J.info(` MX: ${Q} -> 10 inbound-smtp.${$}.amazonaws.com`);return}let _=K.Id?.replace("/hostedzone/","");J.info(`Found hosted zone: ${_}`);for(let F of q){let O=`${F}._domainkey.${Q}`,M=`${F}.dkim.amazonses.com`;try{await X.changeResourceRecordSets({HostedZoneId:_,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:O,Type:"CNAME",TTL:300,ResourceRecords:[{Value:M}]}}]}}),J.success(`Added DKIM record: ${F}._domainkey`)}catch(T){J.warn(`Failed to add DKIM record: ${T.message}`)}}let U=Y?.mailSubdomain||"mail",L=Y?.mode==="server"?`10 ${U}.${Q}`:`10 inbound-smtp.${$}.amazonaws.com`;try{await X.changeResourceRecordSets({HostedZoneId:_,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:Q,Type:"MX",TTL:300,ResourceRecords:[{Value:L}]}}]}}),J.success(`Added MX record: ${L}`)}catch(F){J.warn(`Failed to add MX record: ${F.message}`)}try{await X.changeResourceRecordSets({HostedZoneId:_,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:Q,Type:"TXT",TTL:300,ResourceRecords:[{Value:'"v=spf1 include:amazonses.com ~all"'}]}}]}}),J.success("Added SPF record")}catch(F){J.warn(`Failed to add SPF record: ${F.message}`)}try{await X.changeResourceRecordSets({HostedZoneId:_,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:`_dmarc.${Q}`,Type:"TXT",TTL:300,ResourceRecords:[{Value:`"v=DMARC1;p=quarantine;pct=25;rua=mailto:dmarcreports@${Q}"`}]}}]}}),J.success("Added DMARC record")}catch(F){J.warn(`Failed to add DMARC record: ${F.message}`)}try{let O=`${E.env.APP_NAME?.toLowerCase().replace(/[^a-z0-9]/g,"-")||"stacks"}-email-rules`;await W.setActiveReceiptRuleSet(O),J.success(`Activated email receipt rule set: ${O}`)}catch(F){J.warn(`Failed to activate receipt rule set: ${F.message}`)}J.success("Email DNS records configured!"),J.info("Note: DKIM verification may take 5-15 minutes to complete")}catch(G){J.warn(`Failed to set up email DNS records: ${G.message}`),J.info("You can manually set up DNS records using: buddy email:verify")}}async function Z6(Q,$,J,Y){try{let{DynamoDBClient:G}=await import("@stacksjs/ts-cloud"),z=await import("crypto"),W=new G(J),X=`${Q}-mail-users`,H=c?.mailboxes||[];if(H.length===0){let q=`admin@${$}`,Z=z.randomBytes(16).toString("hex"),K=z.createHash("sha256").update(Z).digest("hex");try{await W.putItem({TableName:X,Item:{email:{S:q},passwordHash:{S:K},createdAt:{S:new Date().toISOString()},displayName:{S:"Admin"}}}),Y.success(`Created default mail user: ${q}`),Y.info(`Password: ${Z}`),Y.info("Save this password - it will not be shown again!")}catch(_){if(_.message?.includes("ConditionalCheckFailedException")||_.message?.includes("already exists"))Y.debug("Default mail user already exists");else throw _}}else for(let q of H){let Z=q,K=typeof q==="string"?`${q}@${$}`:`${Z.name||Z.address?.split("@")[0]}@${$}`,_=typeof q==="object"&&Z.password?Z.password:z.randomBytes(16).toString("hex"),U=z.createHash("sha256").update(_).digest("hex");try{if(await W.putItem({TableName:X,Item:{email:{S:K},passwordHash:{S:U},createdAt:{S:new Date().toISOString()},displayName:{S:typeof q==="object"?Z.displayName||Z.name||K:q}}}),Y.success(`Created mail user: ${K}`),typeof q!=="object"||!Z.password)Y.info(` Password: ${_}`)}catch(L){if(L.message?.includes("ConditionalCheckFailedException"))Y.debug(`Mail user ${K} already exists`);else Y.warn(`Failed to create mail user ${K}: ${L.message}`)}}}catch(G){Y.warn(`Failed to create mail users: ${G.message}`)}}async function j2(Q,$,J){try{let{S3Client:Y}=await import("@stacksjs/ts-cloud"),G=new Y($);if(J==="serverless"){let W=E0.frameworkPath("core/mail-server/server.ts");if(j0(W)){let H=t0(W,"utf-8");await G.putObject({bucket:Q,key:"mail-server/server.ts",body:H,contentType:"text/typescript"}),R.success("Uploaded serverless mail server code to S3")}let X=E0.frameworkPath("core/mail-server/package.json");if(j0(X)){let H=t0(X,"utf-8");await G.putObject({bucket:Q,key:"mail-server/package.json",body:H,contentType:"application/json"})}return}let z=!1;try{await W6();let W=await X6();if(W&&j0(W)&&A2(W)){R.info(`Uploading Pantry mail binary: ${W}`);let X=t0(W);await G.putObject({bucket:Q,key:"mail-server/smtp-server",body:X,contentType:"application/octet-stream"}),R.success("Uploaded Linux x86_64 mail server binary to S3"),z=!0}}catch(W){R.debug(`Pantry mail install failed: ${W.message}`)}if(!z)R.warn(`No Pantry-provided ${n3} mail binary found. Release ${r3}, then run the Pantry binary sync for that package.`)}catch(Y){R.debug(`Could not upload mail server to S3 (bucket may not exist yet): ${Y.message}`)}}function FW(Q){let $={deploy:"Deploy your project",project:"Target a specific project",production:"Deploy to production",development:"Deploy to development",staging:"Deploy to staging",yes:"Confirm all prompts by default",domain:"Specify a domain to deploy to",verbose:"Enable verbose output"};Q.command("deploy [env]",$.deploy).option("--domain",$.domain,{default:void 0}).option("-p, --project [project]",$.project,{default:!1}).option("--prod",$.production,{default:!0}).option("--dev",$.development,{default:!1}).option("--yes",$.yes,{default:!1}).option("--staging",$.staging,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J,Y)=>{R.debug("Running `buddy deploy` ...",Y),await q6(Y.verbose===!0);let G=J||"production";if(E.env.AWS_ACCESS_KEY_ID&&E.env.AWS_SECRET_ACCESS_KEY)delete E.env.AWS_PROFILE;let z=performance.now();console.log(""),console.log("\uD83D\uDE80 Deploy"),console.log("");let W;if(G==="production"||G==="prod"){let Z=E0.projectPath(".env.production");if(j0(Z)){let _=t0(Z,"utf-8").match(/^APP_URL=(.+)$/m);if(_)W=_[1].trim(),R.debug("Using APP_URL from .env.production:",W)}}let X=Q6.APP_URL,H=Y.domain||W||X||p3.url;if((Y.prod||G==="production"||G==="prod")&&!Y.yes)await K6();if(!H)R.info("No domain found in your .env.production or ./config/app.ts"),R.info("Please ensure your domain is properly configured."),R.info("For more info, check out the docs or join our Discord."),E.exit(K0.FatalError);R.info(`Deploying to ${Q7(H)} (${G})`),await F6(Y),Y.domain=await _6(H,Y,z);let q=await e5(J6.Deploy,Y);if(q.isErr)await l7("While running the `buddy deploy`, there was an issue",{startTime:z,useSeconds:!0},q.error),E.exit(K0.FatalError);await l7("Project deployed.",{startTime:z,useSeconds:!0})}),$6(Q,"deploy")}async function K6(){if(!await j$.confirm({message:"Are you sure you want to deploy to production?",initial:!0}))R.info("Aborting deployment..."),E.exit(K0.InvalidArgument)}async function _6(Q,$,J){if(R.debug("Configuring domain...",Q),!Q)R.info("We could not identify a domain to deploy to."),R.warn("Please set your .env or ./config/app.ts properly."),R.info("Alternatively, specify a domain to deploy via the `--domain` flag."),console.log(""),R.info(" \u27A1\uFE0F Example: `buddy deploy --domain example.com`"),console.log(""),E.exit(K0.FatalError);if(Q.includes("localhost"))R.info("You are deploying to a local environment."),R.warn("Please set your .env or ./config/app.ts properly. The domain we are deploying cannot be a `localhost` domain."),R.info("Alternatively, specify a domain to deploy via the `--domain` flag."),console.log(""),R.info(" \u27A1\uFE0F Example: `buddy deploy --domain example.com`"),console.log(""),E.exit(K0.FatalError);if(await m3(Q))return R.info("Domain is properly configured"),R.info("Your cloud is deploying..."),R.info(`${Q7("This may take a while...")}`),Q;console.log(""),R.info(` \uD83D\uDC4B It appears to be your first ${Q7(Q)} deployment.`),console.log(""),R.info(Q7("Let\u2019s ensure it is all connected properly.")),R.info(Q7("One moment...")),console.log("");let Y=await c3({...$,deploy:!0,startTime:J});if(Y.isErr)await l7("While running the `buddy deploy`, there was an issue",{startTime:J,useSeconds:!0},Y.error),E.exit(K0.FatalError);await l7("Added your domain.",{startTime:J,useSeconds:!0}),E.exit(K0.Success)}async function U6(){let Q=await j$.text({message:"AWS Access Key ID:",validate:(G)=>G.length>0?!0:"Access Key ID is required"});if(!Q)R.info("Deployment cancelled"),E.exit(K0.Success);let $=await j$.password({message:"AWS Secret Access Key:",validate:(G)=>G.length>0?!0:"Secret Access Key is required"});if(!$)R.info("Deployment cancelled"),E.exit(K0.Success);let J=await j$.text({message:"AWS Region:",initial:"us-east-1"});if(!J)R.info("Deployment cancelled"),E.exit(K0.Success);let{setEnv:Y}=await import("@stacksjs/env");await Y("AWS_ACCESS_KEY_ID",Q,{file:".env.production",encrypt:!0}),await Y("AWS_SECRET_ACCESS_KEY",$,{file:".env.production",encrypt:!0}),await Y("AWS_REGION",J||"us-east-1",{file:".env.production"}),E.env.AWS_ACCESS_KEY_ID=Q,E.env.AWS_SECRET_ACCESS_KEY=$,E.env.AWS_REGION=J||"us-east-1",R.success("AWS credentials saved securely to .env.production"),console.log("")}function L6(){let Q=E.env.APP_ENV||E.env.NODE_ENV||"production",$=[E0.projectPath(`.env.${Q}`),E0.projectPath(".env")];for(let J of $){if(!j0(J))continue;try{let G=t0(J,"utf-8").split(`
303
- `),z,W,X,H;for(let q of G){let Z=q.trim();if(Z.startsWith("#")||!Z.includes("="))continue;let[K,..._]=Z.split("="),U=_.join("=").trim();if(K==="AWS_ACCESS_KEY_ID"&&U)z=U;else if(K==="AWS_SECRET_ACCESS_KEY"&&U)W=U;else if(K==="AWS_REGION"&&U)X=U;else if(K==="AWS_ACCOUNT_ID"&&U)H=U}if(z&&W)return R.debug(`Found AWS credentials in ${J}`),{accessKeyId:z,secretAccessKey:W,region:X,accountId:H}}catch(Y){R.debug(`Failed to read ${J} file:`,Y)}}return{}}async function F6(Q){let $=!1;try{R.info("Ensuring AWS cloud stack exists...");let J=E.env.AWS_ACCESS_KEY_ID&&E.env.AWS_SECRET_ACCESS_KEY;if(!J){let F=L6();if(F.accessKeyId&&F.secretAccessKey){if(E.env.AWS_ACCESS_KEY_ID=F.accessKeyId,E.env.AWS_SECRET_ACCESS_KEY=F.secretAccessKey,F.region&&!E.env.AWS_REGION)E.env.AWS_REGION=F.region;if(F.accountId&&!E.env.AWS_ACCOUNT_ID)E.env.AWS_ACCOUNT_ID=F.accountId;J=!0;let O=E.env.APP_ENV||E.env.NODE_ENV||"production";R.success(`Using AWS credentials from .env.${O}`)}}if(!J){let F=H6();if(F.accessKeyId&&F.secretAccessKey){if(E.env.AWS_ACCESS_KEY_ID=F.accessKeyId,E.env.AWS_SECRET_ACCESS_KEY=F.secretAccessKey,F.region&&!E.env.AWS_REGION)E.env.AWS_REGION=F.region;J=!0,R.success("Using AWS credentials from ~/.aws/credentials")}}if(!J){if(R.info("AWS credentials not found in .env or ~/.aws/credentials."),R.info("You can either:"),R.info(" 1. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in .env.production"),R.info(" 2. Add credentials to ~/.aws/credentials"),R.info(" 3. Configure them interactively below"),console.log(""),Q?.yes)R.info("Skipping credential setup (--yes flag provided)"),E.exit(K0.FatalError);let F=await j$.confirm({message:"Would you like to configure AWS credentials now?",initial:!0});if(R.debug("setupCredentials response:",F,typeof F),F===void 0||F===!1){if(F===void 0)console.log(""),R.info("Deployment cancelled"),E.exit(K0.Success);return console.log(""),R.info("Skipping cloud infrastructure check"),R.info("You can configure AWS credentials later by running: buddy configure:aws"),!0}await U6()}else R.success("AWS credentials found");let Y=(E.env.APP_NAME||p3.name||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-"),G=`${Y}-cloud`,{AWSCloudFormationClient:z}=await import("@stacksjs/ts-cloud"),W=new z(E.env.AWS_REGION||"us-east-1"),X=!1,H=!1;try{let F=(await W.describeStacks({stackName:G})).Stacks?.[0];if(F){X=!0,R.success("Cloud stack exists");let{AWSCloudFormationClient:O}=await import("@stacksjs/ts-cloud"),T=await new O(E.env.AWS_REGION||"us-east-1").listStackResources(G),f=T.StackResourceSummaries?.some((i)=>i.LogicalResourceId==="EmailBucket"),P=T.StackResourceSummaries?.some((i)=>i.LogicalResourceId==="OutboundEmailLambda"),I=T.StackResourceSummaries?.some((i)=>i.LogicalResourceId==="EmailConversionLambda"),j=T.StackResourceSummaries?.some((i)=>i.LogicalResourceId==="EmailNotificationTopic"),A=T.StackResourceSummaries?.some((i)=>i.LogicalResourceId==="MailApiLambda"),h=T.StackResourceSummaries?.some((i)=>i.LogicalResourceId==="MailUsersTable"),V=T.StackResourceSummaries?.some((i)=>i.LogicalResourceId==="MailServerInstance"),N=F.Outputs?.find((i)=>i.OutputKey==="EmailDomain")?.OutputValue,B=(c?.from?.address?.includes("@")?c.from.address.split("@")[1]:void 0)||"stacksjs.com";if(!f&&c?.server?.scan!==void 0)R.info("Email infrastructure not found in stack, will update..."),H=!0;else if(N&&N!==B)R.info(`Email domain changed: ${N} -> ${B}, will update...`),H=!0;else if(f&&(!P||!I||!j))R.info("Email infrastructure incomplete, will update..."),H=!0;else if(f&&(!A||!h))R.info("Mail API infrastructure missing, will update..."),H=!0;else if(f&&!V&&c?.server?.enabled)R.info("Mail server EC2 instance missing, will update..."),H=!0;let v=(F.Outputs||[]).find((i)=>i.OutputKey==="MailServerMode")?.OutputValue,B0=c?.server?.mode||"serverless";if(v&&v!==B0)R.info(`Mail server mode changed: ${v} -> ${B0}, will update...`),H=!0;if(V&&c?.server?.enabled){if(E.env.FORCE_MAIL_UPDATE==="true")R.info("Forcing mail server update..."),H=!0}if(!H)return!0}}catch(F){R.debug(`Stack not found: ${F.message}`)}if(!X)R.info("Cloud stack not found, will be created by deploy action");return!0}catch(J){if(!$){if(R.error("Error checking cloud infrastructure"),R.error(`Error: ${J.message||J}`),Q?.verbose)console.error(J)}E.exit(K0.FatalError)}}import x from"process";import{bold as J7,cyan as m0,dim as Q0,green as Y7,intro as P2,log as N0,onUnknownSubcommand as V6,outro as U$,prompts as B6,runCommand as R6}from"@stacksjs/cli";import{Action as i3}from"@stacksjs/enums";import{libsPath as w6}from"@stacksjs/path";import{ExitCode as u0}from"@stacksjs/types";var a3="0.70.33";var f2;async function A0(){if(!f2)f2=await import("@stacksjs/actions");return f2}function AW(Q){let $={dev:"Start development server",frontend:"Start the frontend development server",components:"Start the Components development server",desktop:"Start the Desktop App development server",dashboard:"Start the Dashboard development server",api:"Start the local API development server",email:"Start the Email development server",docs:"Start the Documentation development server",systemTray:"Start the System Tray development server",interactive:"Get asked which development server to start",select:"Which development server are you trying to start?",withLocalhost:"Include the localhost URL in the output",project:"Target a specific project",verbose:"Enable verbose output"};Q.command("dev [server]",$.dev).option("-f, --frontend",$.frontend).option("-a, --api",$.api).option("-e, --email",$.email).option("-c, --components",$.components).option("-d, --dashboard",$.dashboard).option("-k, --desktop",$.desktop).option("-o, --docs",$.docs).option("-s, --system-tray",$.systemTray).option("-i, --interactive",$.interactive,{default:!1}).option("-l, --with-localhost",$.withLocalhost,{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J,Y)=>{let G=Bun.nanoseconds(),z=J||(Y.frontend?"frontend":void 0)||(Y.api?"api":void 0)||(Y.components?"components":void 0)||(Y.dashboard?"dashboard":void 0)||(Y.desktop?"desktop":void 0)||(Y.systemTray||Y["system-tray"]?"system-tray":void 0)||(Y.docs?"docs":void 0);if(z){let W={...Y},X=await A0();switch(z){case"frontend":await X.runFrontendDevServer(W);break;case"api":await X.runApiDevServer(W);break;case"components":await X.runComponentsDevServer(W);break;case"dashboard":await X.runDashboardDevServer(W);break;case"desktop":await X.runDesktopDevServer(W);break;case"system-tray":await X.runSystemTrayDevServer(W);break;case"docs":await X.runDocsDevServer(W);break;default:N0.error(`Unknown server: ${z}`),x.exit(u0.InvalidArgument)}}else if(P6(Y)){let X=(await B6({type:"select",name:"value",message:$.select,choices:[{value:"all",title:"All"},{value:"frontend",title:"Frontend"},{value:"api",title:"Backend"},{value:"dashboard",title:"Dashboard"},{value:"desktop",title:"Desktop"},{value:"email",title:"Email"},{value:"components",title:"Components"},{value:"docs",title:"Documentation"}]})).value;if(X==="components")await(await A0()).runComponentsDevServer(Y);else if(X==="api")await(await A0()).runApiDevServer(Y);else if(X==="dashboard")await(await A0()).runDashboardDevServer(Y);else if(X==="docs")await(await A0()).runDocsDevServer(Y);else N0.error("Invalid option during interactive mode"),x.exit(u0.InvalidArgument)}else await M6(Y,G);U$("Exited",{startTime:G,useSeconds:!0}),x.exit(u0.Success)}),Q.command("dev:components",$.components).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{let Y=await P2("buddy dev:components"),G=await R6("bun run dev",{cwd:w6("components/vue")});if(J.verbose)N0.info("buddy dev:components result",G);if(G.isErr)await U$("While running the dev:components command, there was an issue",{startTime:Y,useSeconds:!0},G.error),x.exit(u0.FatalError);console.log(""),await U$("Exited",{startTime:Y,useSeconds:!0}),x.exit(u0.Success)}),Q.command("dev:docs",$.docs).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{let Y=await P2("buddy dev:docs"),G=await(await A0()).runAction(i3.DevDocs,J);if(G.isErr)await U$("While running the dev:docs command, there was an issue",{startTime:Y,useSeconds:!0},G.error),x.exit(u0.FatalError);console.log(""),await U$("Exited",{startTime:Y,useSeconds:!0}),x.exit(u0.Success)}),Q.command("dev:desktop",$.desktop).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{let Y=await P2("buddy dev:desktop"),G=await(await A0()).runAction(i3.DevDesktop,J);if(G.isErr)await U$("While running the dev:desktop command, there was an issue",{startTime:Y,useSeconds:!0},G.error),x.exit(u0.FatalError);console.log(""),await U$("Exited",{startTime:Y,useSeconds:!0}),x.exit(u0.Success)}),Q.command("dev:api",$.api).option("-p, --project [project]",$.project,{default:!1}).option("--no-watch-types","Skip the model/config type-regeneration watcher",{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{let Y=await A0();if(J.watchTypes!==!1)Y.watchTypes(J).catch((G)=>{N0.warn("[dev:api] type watcher exited:",G)});await Y.runApiDevServer(J)}),Q.command("dev:frontend",$.frontend).alias("dev:pages").alias("dev:views").option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{await(await A0()).runFrontendDevServer(J)}),Q.command("dev:dashboard",$.dashboard).alias("dev:admin").option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{await(await A0()).runDashboardDevServer(J)}),Q.command("dev:system-tray",$.systemTray).alias("dev:tray").option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{await(await A0()).runSystemTrayDevServer(J)}),V6(Q,"dev")}async function M6(Q,$){let J=x.env.APP_URL,Y=Number(x.env.PORT)||3000,G=Number(x.env.PORT_API)||3008,z=Number(x.env.PORT_DOCS)||3006,W=Number(x.env.PORT_ADMIN)||3002,X=x.env.STACKS_DEV_DASHBOARD==="1",H=J&&J!=="localhost"&&!J.includes("localhost:"),q=H?J.replace(/^https?:\/\//,""):null,Z=q?`api.${q}`:null,K=q?`docs.${q}`:null,_=q?`dashboard.${q}`:null,U=q?`https://${q}`:`http://localhost:${Y}`,L=Z?`https://${Z}`:`http://localhost:${G}`,F=K?`https://${K}`:`http://localhost:${z}`,O=_?`https://${_}`:`http://localhost:${W}`;if(console.log(),console.log(` ${J7(m0("stacks"))} ${Q0(`v${a3}`)}`),console.log(),console.log(` ${Y7("\u279C")} ${J7("Frontend")}: ${m0(U)}`),console.log(` ${Y7("\u279C")} ${J7("API")}: ${m0(L)}`),console.log(` ${Y7("\u279C")} ${J7("Docs")}: ${m0(F)}`),X)console.log(` ${Y7("\u279C")} ${J7("Dashboard")}: ${m0(O)}`);if(Q.verbose&&q){if(console.log(` ${Q0("\u279C")} ${Q0("Proxy")}: ${Q0(`localhost:${Y} \u2192 ${q}`)}`),console.log(` ${Q0("\u279C")} ${Q0("Proxy")}: ${Q0(`localhost:${G} \u2192 ${Z}`)}`),console.log(` ${Q0("\u279C")} ${Q0("Proxy")}: ${Q0(`localhost:${z} \u2192 ${K}`)}`),X)console.log(` ${Q0("\u279C")} ${Q0("Proxy")}: ${Q0(`localhost:${W} \u2192 ${_}`)}`)}if(console.log(),x.env.STACKS_PROXY_MANAGED="1",x.env.STACKS_DEV_NO_KILL!=="1")try{await Bun.spawn(["pkill","-9","-f","bun --watch storage/framework/core/actions/src/dev/"],{stdout:"ignore",stderr:"ignore"}).exited,await new Promise((V)=>setTimeout(V,200))}catch{}let M=!1,T=1500,f=()=>{if(M)return;M=!0;try{x.kill(-x.pid,"SIGTERM")}catch{try{x.kill(0,"SIGTERM")}catch{}}setTimeout(()=>{try{x.kill(0,"SIGKILL")}catch{x.exit(1)}},T).unref()};x.on("SIGINT",f),x.on("SIGTERM",f);let P={...Q,quiet:!0},I=await A0(),j=[{name:"Frontend",port:Y},{name:"API",port:G},{name:"Docs",port:z},...X?[{name:"Dashboard",port:W}]:[]],A=30000,h=!1;Promise.all(j.map((V)=>j6(V.port,A))).then(async(V)=>{if(h)return;h=!0;let N=V.map((B,v)=>B?null:j[v].name).filter((B)=>B!==null);if($){let B=(Bun.nanoseconds()-$)/1e6,v=N.length?`ready in ${(B/1000).toFixed(1)}s \u2014 ${N.join(", ")} did not bind within ${A/1000}s`:`ready in ${(B/1000).toFixed(1)}s`;console.log(` ${Q0(v)}
301
+ `,q=await z8(X,{cwd:W8.projectPath(),stdin:"pipe",input:H});if(q.isErr)await h3("While running the cloud command, there was an issue",{startTime:$,useSeconds:!0},q.error),s0.exit(y7.FatalError);if(Q?.quiet)return;await h3("Exited",{startTime:$,useSeconds:!0})}m7();import{chmodSync as f8}from"fs";import g0 from"process";import{runAction as v8}from"@stacksjs/actions";import{bold as S8,cyan as E8,dim as N8,intro as C8,log as n,onUnknownSubcommand as h8,runCommand as c7}from"@stacksjs/cli";import{Action as D8}from"@stacksjs/enums";import{resolve as k3}from"@stacksjs/path";import{isFolder as b8}from"@stacksjs/storage";import{ExitCode as o0}from"@stacksjs/types";import{useOnline as y8}from"@stacksjs/utils";function uz(Q){let $={name:"The name of the project",command:"Create a new Stacks project",ui:"Are you building a UI?",components:"Are you building UI components?",webComponents:"Automagically built optimized custom elements/web components?",vue:"Automagically built a Vue component library?",views:"How about views?",functions:"Are you developing functions/composables?",api:"Are you building an API?",database:"Do you need a database?",notifications:"Do you need notifications? e.g. email, SMS, push or chat notifications",cache:"Do you need caching?",email:"Do you need email?",project:"Target a specific project",verbose:"Enable verbose output"};Q.command("new [name]",$.command).alias("create [name]").option("-n, --name [name]",$.name,{default:!1}).option("-u, --ui",$.ui,{default:!0}).option("-c, --components",$.components,{default:!0}).option("-w, --web-components",$.webComponents,{default:!0}).option("-v, --vue",$.vue,{default:!0}).option("-p, --views",$.views,{default:!0}).option("-f, --functions",$.functions,{default:!0}).option("-a, --api",$.api,{default:!0}).option("-d, --database",$.database,{default:!0}).option("-ca, --cache",$.cache,{default:!1}).option("-e, --email",$.email,{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J,Y)=>{n.debug("Running `buddy new <name>` ...",Y);let G=await C8("buddy new");J=J??Y.name;let z=k3(g0.cwd(),J);k8(z),x8();let W=await g8(J,z,Y);if(W.isErr)n.error(W.error),g0.exit(o0.FatalError);if(await m8(z,Y),u8(z),await c8(z,Y),G){let X=performance.now()-G;n.success(N8(`[${X.toFixed(2)}ms] Completed`))}n.info(S8("Welcome to the Stacks Framework! \u269B\uFE0F")),n.info("To learn more, visit https://stacksjs.com"),g0.exit(o0.Success)}),h8(Q,"new")}function k8(Q){if(b8(Q))n.error(`Path ${Q} already exists`),g0.exit(o0.FatalError)}function x8(){if(!y8())n.info("It appears you are disconnected from the internet."),n.info("The Stacks setup requires a brief internet connection for setup."),n.info("For instance, it installs your dependencies from."),g0.exit(o0.FatalError)}async function g8(Q,$,J){n.info("Setting up your stack.");let Y=await c7(`bunx --bun @stacksjs/gitit stacks ${Q}`,J);return n.success(`Successfully scaffolded your project at ${E8($)}`),Y}function u8(Q){for(let $ of["buddy","bootstrap"])try{f8(k3(Q,$),493)}catch{}}async function m8(Q,$){n.info("Ensuring your environment is ready..."),await T$(),await I$(Q),n.success("Environment is ready")}async function c8(Q,$){n.info("Installing & setting up Stacks"),n.info("Running bun install...");let J=await c7("bun install",{...$,cwd:Q});if(J?.isErr)n.error(J.error),g0.exit(o0.FatalError);if(n.info("Copying .env.example \u2192 .env"),J=await c7("cp .env.example .env",{...$,cwd:Q}),J?.isErr)n.error(J.error),g0.exit(o0.FatalError);n.info("Generating application key...");let Y=await v8(D8.KeyGenerate,{...$,cwd:Q});if(Y.isErr)n.error(Y.error),g0.exit(o0.FatalError);if(n.info("Initializing git repository..."),J=await c7("git init",{...$,cwd:Q}),J.isErr)n.error(J.error),g0.exit(o0.FatalError);n.success("Installed & set-up \uD83D\uDE80")}import{existsSync as j0,readFileSync as t0,readdirSync as o8,statSync as t8}from"fs";import{homedir as A$}from"os";import{join as _$}from"path";import E from"process";import{runAction as e8}from"@stacksjs/actions";import{italic as Q7,onUnknownSubcommand as $6,outro as l7,prompts as j$}from"@stacksjs/cli";import{app as p3,email as c,cloud as l3}from"@stacksjs/config";import{runAction as l8}from"@stacksjs/actions";import{config as g3}from"@stacksjs/config";import{Action as d8}from"@stacksjs/enums";import{err as rz,handleError as nz,ok as az}from"@stacksjs/error-handling";import{log as Z0}from"@stacksjs/logging";import{path as p8}from"@stacksjs/path";import{fs as x3}from"@stacksjs/storage";import{Route53Client as r8,Route53DomainsClient as u3}from"@stacksjs/ts-cloud";function n8(Q){if(!Q)return;return Q.replace(/^https?:\/\//,"").replace(/\/$/,"")}function a8(Q){if(!/^[a-zA-Z0-9.-]+$/.test(Q))throw Error(`Invalid nameserver value: ${Q}`);return Q}function T2(Q){try{let $=p8.projectConfigPath("dns.ts"),Y=x3.readFileSync($,"utf-8").replace(/nameservers: \[.*?\]/s,`nameservers: [${Q.map((G)=>`'${a8(G)}'`).join(", ")}]`);x3.writeFileSync($,Y,"utf-8"),Z0.info("Nameservers have been set.")}catch($){Z0.error("Error updating nameservers:",$)}}async function i8(Q){if(Z0.debug("Getting nameservers for domain:",Q),!Q)return[];try{return(await new u3().getDomainDetail({DomainName:Q}))?.Nameservers?.map((Y)=>Y.Name)||[]}catch($){return Z0.debug("Domain not registered via Route53 Domains:",$),[]}}async function s8(Q,$){if(!$)$=g3.app.url;let J=await i8($);if(!J||J.length===0)return Z0.debug("Domain is not registered via Route53 Domains - skipping automatic nameserver update"),T2(Q),!1;if(JSON.stringify(J.sort())!==JSON.stringify(Q.sort())){Z0.info("Updating your domain nameservers to match the ones in your hosted zone..."),Z0.debug("Hosted zone nameservers:",Q),Z0.debug("Domain nameservers:",J);try{return await new u3().updateDomainNameservers({DomainName:$,Nameservers:Q.map((G)=>({Name:G}))}),T2(Q),Z0.info("Nameservers updated."),!0}catch(Y){return Z0.debug("Failed to update nameservers via Route53 Domains:",Y),T2(Q),!1}}return Z0.success("Your nameservers are up to date."),!0}async function m3(Q){if(Z0.debug("Checking if domain has been added to cloud..."),!Q)Q=g3.app.url;if(Q=n8(Q),!Q)return!1;Z0.debug("domainName:",Q);let $=new r8,J=await $.listHostedZonesByName({DNSName:Q});if(Z0.debug("Existing hosted zones:",J),!J||!J.HostedZones||J.HostedZones.length===0)return!1;let Y=J.HostedZones.find((G)=>G.Name===`${Q}.`);if(Y){Z0.debug("Hosted zone found:",Y);let z=(await $.getHostedZone({Id:Y.Id})).DelegationSet?.NameServers||[];return await s8(z,Q),!0}return!1}async function c3(Q){return await l8(d8.DomainsAdd,Q)}m7();import{env as Q6}from"@stacksjs/env";import{Action as J6}from"@stacksjs/enums";import{path as E0}from"@stacksjs/path";import{ExitCode as K0}from"@stacksjs/types";var R={info:(...Q)=>console.log("\u2139",...Q),success:(...Q)=>console.log("\u2713",...Q),warn:(...Q)=>console.log("\u26A0",...Q),error:(...Q)=>console.error("\u2717",...Q),debug:(...Q)=>{if(E.argv.includes("--verbose")||E.argv.includes("-v"))console.log("\uD83D\uDD0D",...Q)}},r3="github.com/mail-os/mail",Y6=`${r3}@0.1.0`,n3="linux-x86_64",I2=["mail","mail-x86_64-linux","mail-x86_64-linux-gnu"];function G6(Q,$,J=8){let Y=new Set($),G=[];if(!j0(Q))return G;function z(W,X){if(X>J)return;for(let H of o8(W)){if(H===".git"||H==="node_modules")continue;let q=_$(W,H),Z=t8(q);if(Z.isDirectory())z(q,X+1);else if(Z.isFile()&&Y.has(H))G.push(q)}}return z(Q,0),G}function A2(Q){let $=t0(Q).slice(0,4);return $[0]===127&&$[1]===69&&$[2]===76&&$[3]===70}function z6(){let Q=_$(A$(),"Code","Tools","pantry","packages","ts-pantry","bin","cli.ts");if(j0(Q))return{command:"bun",args:[Q]};let $=E0.projectPath("pantry/.bin/pantry");if(j0($))return{command:$,args:[]};let J=_$(A$(),".local","share","pantry","global","bin","pantry");if(j0(J))return{command:J,args:[]};return{command:"pantry",args:[]}}async function W6(){let{execFileSync:Q}=await import("child_process"),$=z6();Q($.command,[...$.args,"install",Y6,"--install-dir",E0.projectPath("pantry"),"--platform",n3,"--quiet"],{cwd:E0.projectPath(),stdio:E.argv.includes("--verbose")||E.argv.includes("-v")?"inherit":"pipe",env:E.env})}async function X6(){let Q=[...I2.map(($)=>E0.projectPath(`pantry/.bin/${$}`)),...I2.map(($)=>_$(A$(),".local","share","pantry","global","bin",$))];for(let $ of Q)if(j0($)&&A2($))return $;for(let $ of[E0.projectPath("pantry"),_$(A$(),".local","share","pantry")])for(let J of G6($,I2))if(A2(J))return J;return null}async function q6(Q=!1){let $=E0.projectPath();await T$(),await I$($),await u7({cwd:$,verbose:Q}),await g7($)}function H6(){let Q=_$(A$(),".aws","credentials"),$=_$(A$(),".aws","config");if(!j0(Q))return{};try{let Y=t0(Q,"utf-8").split(`
302
+ `),G=["default","stacks"],z="",W={},X={};for(let q of Y){let Z=q.trim(),K=Z.match(/^\[(.+)\]$/);if(K){z=K[1],X[z]={};continue}let _=Z.match(/^(\w+)\s*=\s*(.+)$/);if(_&&z){let[,U,L]=_;if(U==="aws_access_key_id")X[z].accessKeyId=L;else if(U==="aws_secret_access_key")X[z].secretAccessKey=L}}for(let q of G)if(X[q]?.accessKeyId&&X[q]?.secretAccessKey){W=X[q],R.debug(`Using AWS credentials from ~/.aws/credentials [${q}] profile`);break}if(!W.accessKeyId){for(let[q,Z]of Object.entries(X))if(Z.accessKeyId&&Z.secretAccessKey){W=Z,R.debug(`Using AWS credentials from ~/.aws/credentials [${q}] profile`);break}}let H;if(j0($)){let Z=t0($,"utf-8").match(/region\s*=\s*(.+)/);if(Z)H=Z[1].trim()}return{...W,region:H}}catch(J){return R.debug("Failed to read AWS credentials file:",J),{}}}async function d3(Q,$,J,Y){J.info("Setting up email DNS records...");try{let{SESClient:G}=await import("@stacksjs/ts-cloud"),{Route53Client:z}=await import("@stacksjs/ts-cloud"),W=new G($),X=new z($);J.info(`Getting DKIM tokens for ${Q}...`);let q=(await W.getEmailIdentity(Q)).DkimAttributes?.Tokens||[];if(q.length===0){J.warn("No DKIM tokens found - domain may not be set up in SES yet");return}J.info(`Found ${q.length} DKIM tokens`);let K=(await X.listHostedZones()).HostedZones?.find((F)=>F.Name===`${Q}.`);if(!K){J.warn(`Hosted zone not found for ${Q} - DNS records must be added manually`),J.info("DKIM records needed:");for(let F of q)J.info(` CNAME: ${F}._domainkey.${Q} -> ${F}.dkim.amazonses.com`);J.info(` MX: ${Q} -> 10 inbound-smtp.${$}.amazonaws.com`);return}let _=K.Id?.replace("/hostedzone/","");J.info(`Found hosted zone: ${_}`);for(let F of q){let O=`${F}._domainkey.${Q}`,M=`${F}.dkim.amazonses.com`;try{await X.changeResourceRecordSets({HostedZoneId:_,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:O,Type:"CNAME",TTL:300,ResourceRecords:[{Value:M}]}}]}}),J.success(`Added DKIM record: ${F}._domainkey`)}catch(T){J.warn(`Failed to add DKIM record: ${T.message}`)}}let U=Y?.mailSubdomain||"mail",L=Y?.mode==="server"?`10 ${U}.${Q}`:`10 inbound-smtp.${$}.amazonaws.com`;try{await X.changeResourceRecordSets({HostedZoneId:_,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:Q,Type:"MX",TTL:300,ResourceRecords:[{Value:L}]}}]}}),J.success(`Added MX record: ${L}`)}catch(F){J.warn(`Failed to add MX record: ${F.message}`)}try{await X.changeResourceRecordSets({HostedZoneId:_,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:Q,Type:"TXT",TTL:300,ResourceRecords:[{Value:'"v=spf1 include:amazonses.com ~all"'}]}}]}}),J.success("Added SPF record")}catch(F){J.warn(`Failed to add SPF record: ${F.message}`)}try{await X.changeResourceRecordSets({HostedZoneId:_,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:`_dmarc.${Q}`,Type:"TXT",TTL:300,ResourceRecords:[{Value:`"v=DMARC1;p=quarantine;pct=25;rua=mailto:dmarcreports@${Q}"`}]}}]}}),J.success("Added DMARC record")}catch(F){J.warn(`Failed to add DMARC record: ${F.message}`)}try{let O=`${E.env.APP_NAME?.toLowerCase().replace(/[^a-z0-9]/g,"-")||"stacks"}-email-rules`;await W.setActiveReceiptRuleSet(O),J.success(`Activated email receipt rule set: ${O}`)}catch(F){J.warn(`Failed to activate receipt rule set: ${F.message}`)}J.success("Email DNS records configured!"),J.info("Note: DKIM verification may take 5-15 minutes to complete")}catch(G){J.warn(`Failed to set up email DNS records: ${G.message}`),J.info("You can manually set up DNS records using: buddy email:verify")}}async function Z6(Q,$,J,Y){try{let{DynamoDBClient:G}=await import("@stacksjs/ts-cloud"),z=await import("crypto"),W=new G(J),X=`${Q}-mail-users`,H=c?.mailboxes||[];if(H.length===0){let q=`admin@${$}`,Z=z.randomBytes(16).toString("hex"),K=z.createHash("sha256").update(Z).digest("hex");try{await W.putItem({TableName:X,Item:{email:{S:q},passwordHash:{S:K},createdAt:{S:new Date().toISOString()},displayName:{S:"Admin"}}}),Y.success(`Created default mail user: ${q}`),Y.info(`Password: ${Z}`),Y.info("Save this password - it will not be shown again!")}catch(_){if(_.message?.includes("ConditionalCheckFailedException")||_.message?.includes("already exists"))Y.debug("Default mail user already exists");else throw _}}else for(let q of H){let Z=q,K=typeof q==="string"?`${q}@${$}`:`${Z.name||Z.address?.split("@")[0]}@${$}`,_=typeof q==="object"&&Z.password?Z.password:z.randomBytes(16).toString("hex"),U=z.createHash("sha256").update(_).digest("hex");try{if(await W.putItem({TableName:X,Item:{email:{S:K},passwordHash:{S:U},createdAt:{S:new Date().toISOString()},displayName:{S:typeof q==="object"?Z.displayName||Z.name||K:q}}}),Y.success(`Created mail user: ${K}`),typeof q!=="object"||!Z.password)Y.info(` Password: ${_}`)}catch(L){if(L.message?.includes("ConditionalCheckFailedException"))Y.debug(`Mail user ${K} already exists`);else Y.warn(`Failed to create mail user ${K}: ${L.message}`)}}}catch(G){Y.warn(`Failed to create mail users: ${G.message}`)}}async function j2(Q,$,J){try{let{S3Client:Y}=await import("@stacksjs/ts-cloud"),G=new Y($);if(J==="serverless"){let W=E0.frameworkPath("core/mail-server/server.ts");if(j0(W)){let H=t0(W,"utf-8");await G.putObject({bucket:Q,key:"mail-server/server.ts",body:H,contentType:"text/typescript"}),R.success("Uploaded serverless mail server code to S3")}let X=E0.frameworkPath("core/mail-server/package.json");if(j0(X)){let H=t0(X,"utf-8");await G.putObject({bucket:Q,key:"mail-server/package.json",body:H,contentType:"application/json"})}return}let z=!1;try{await W6();let W=await X6();if(W&&j0(W)&&A2(W)){R.info(`Uploading Pantry mail binary: ${W}`);let X=t0(W);await G.putObject({bucket:Q,key:"mail-server/smtp-server",body:X,contentType:"application/octet-stream"}),R.success("Uploaded Linux x86_64 mail server binary to S3"),z=!0}}catch(W){R.debug(`Pantry mail install failed: ${W.message}`)}if(!z)R.warn(`No Pantry-provided ${n3} mail binary found. Release ${r3}, then run the Pantry binary sync for that package.`)}catch(Y){R.debug(`Could not upload mail server to S3 (bucket may not exist yet): ${Y.message}`)}}function FW(Q){let $={deploy:"Deploy your project",project:"Target a specific project",production:"Deploy to production",development:"Deploy to development",staging:"Deploy to staging",yes:"Confirm all prompts by default",domain:"Specify a domain to deploy to",verbose:"Enable verbose output"};Q.command("deploy [env]",$.deploy).option("--domain",$.domain,{default:void 0}).option("-p, --project [project]",$.project,{default:!1}).option("--prod",$.production,{default:!0}).option("--dev",$.development,{default:!1}).option("--yes",$.yes,{default:!1}).option("--staging",$.staging,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J,Y)=>{R.debug("Running `buddy deploy` ...",Y),await q6(Y.verbose===!0);let G=J||"production";if(E.env.AWS_ACCESS_KEY_ID&&E.env.AWS_SECRET_ACCESS_KEY)delete E.env.AWS_PROFILE;let z=performance.now();console.log(""),console.log("\uD83D\uDE80 Deploy"),console.log("");let W;if(G==="production"||G==="prod"){let Z=E0.projectPath(".env.production");if(j0(Z)){let _=t0(Z,"utf-8").match(/^APP_URL=(.+)$/m);if(_)W=_[1].trim(),R.debug("Using APP_URL from .env.production:",W)}}let X=Q6.APP_URL,H=Y.domain||W||X||p3.url;if((Y.prod||G==="production"||G==="prod")&&!Y.yes)await K6();if(!H)R.info("No domain found in your .env.production or ./config/app.ts"),R.info("Please ensure your domain is properly configured."),R.info("For more info, check out the docs or join our Discord."),E.exit(K0.FatalError);R.info(`Deploying to ${Q7(H)} (${G})`),await F6(Y),Y.domain=await _6(H,Y,z);let q=await e8(J6.Deploy,Y);if(q.isErr)await l7("While running the `buddy deploy`, there was an issue",{startTime:z,useSeconds:!0},q.error),E.exit(K0.FatalError);await l7("Project deployed.",{startTime:z,useSeconds:!0})}),$6(Q,"deploy")}async function K6(){if(!await j$.confirm({message:"Are you sure you want to deploy to production?",initial:!0}))R.info("Aborting deployment..."),E.exit(K0.InvalidArgument)}async function _6(Q,$,J){if(R.debug("Configuring domain...",Q),!Q)R.info("We could not identify a domain to deploy to."),R.warn("Please set your .env or ./config/app.ts properly."),R.info("Alternatively, specify a domain to deploy via the `--domain` flag."),console.log(""),R.info(" \u27A1\uFE0F Example: `buddy deploy --domain example.com`"),console.log(""),E.exit(K0.FatalError);if(Q.includes("localhost"))R.info("You are deploying to a local environment."),R.warn("Please set your .env or ./config/app.ts properly. The domain we are deploying cannot be a `localhost` domain."),R.info("Alternatively, specify a domain to deploy via the `--domain` flag."),console.log(""),R.info(" \u27A1\uFE0F Example: `buddy deploy --domain example.com`"),console.log(""),E.exit(K0.FatalError);if(await m3(Q))return R.info("Domain is properly configured"),R.info("Your cloud is deploying..."),R.info(`${Q7("This may take a while...")}`),Q;console.log(""),R.info(` \uD83D\uDC4B It appears to be your first ${Q7(Q)} deployment.`),console.log(""),R.info(Q7("Let\u2019s ensure it is all connected properly.")),R.info(Q7("One moment...")),console.log("");let Y=await c3({...$,deploy:!0,startTime:J});if(Y.isErr)await l7("While running the `buddy deploy`, there was an issue",{startTime:J,useSeconds:!0},Y.error),E.exit(K0.FatalError);await l7("Added your domain.",{startTime:J,useSeconds:!0}),E.exit(K0.Success)}async function U6(){let Q=await j$.text({message:"AWS Access Key ID:",validate:(G)=>G.length>0?!0:"Access Key ID is required"});if(!Q)R.info("Deployment cancelled"),E.exit(K0.Success);let $=await j$.password({message:"AWS Secret Access Key:",validate:(G)=>G.length>0?!0:"Secret Access Key is required"});if(!$)R.info("Deployment cancelled"),E.exit(K0.Success);let J=await j$.text({message:"AWS Region:",initial:"us-east-1"});if(!J)R.info("Deployment cancelled"),E.exit(K0.Success);let{setEnv:Y}=await import("@stacksjs/env");await Y("AWS_ACCESS_KEY_ID",Q,{file:".env.production",encrypt:!0}),await Y("AWS_SECRET_ACCESS_KEY",$,{file:".env.production",encrypt:!0}),await Y("AWS_REGION",J||"us-east-1",{file:".env.production"}),E.env.AWS_ACCESS_KEY_ID=Q,E.env.AWS_SECRET_ACCESS_KEY=$,E.env.AWS_REGION=J||"us-east-1",R.success("AWS credentials saved securely to .env.production"),console.log("")}function L6(){let Q=E.env.APP_ENV||E.env.NODE_ENV||"production",$=[E0.projectPath(`.env.${Q}`),E0.projectPath(".env")];for(let J of $){if(!j0(J))continue;try{let G=t0(J,"utf-8").split(`
303
+ `),z,W,X,H;for(let q of G){let Z=q.trim();if(Z.startsWith("#")||!Z.includes("="))continue;let[K,..._]=Z.split("="),U=_.join("=").trim();if(K==="AWS_ACCESS_KEY_ID"&&U)z=U;else if(K==="AWS_SECRET_ACCESS_KEY"&&U)W=U;else if(K==="AWS_REGION"&&U)X=U;else if(K==="AWS_ACCOUNT_ID"&&U)H=U}if(z&&W)return R.debug(`Found AWS credentials in ${J}`),{accessKeyId:z,secretAccessKey:W,region:X,accountId:H}}catch(Y){R.debug(`Failed to read ${J} file:`,Y)}}return{}}async function F6(Q){let $=!1;try{R.info("Ensuring AWS cloud stack exists...");let J=E.env.AWS_ACCESS_KEY_ID&&E.env.AWS_SECRET_ACCESS_KEY;if(!J){let F=L6();if(F.accessKeyId&&F.secretAccessKey){if(E.env.AWS_ACCESS_KEY_ID=F.accessKeyId,E.env.AWS_SECRET_ACCESS_KEY=F.secretAccessKey,F.region&&!E.env.AWS_REGION)E.env.AWS_REGION=F.region;if(F.accountId&&!E.env.AWS_ACCOUNT_ID)E.env.AWS_ACCOUNT_ID=F.accountId;J=!0;let O=E.env.APP_ENV||E.env.NODE_ENV||"production";R.success(`Using AWS credentials from .env.${O}`)}}if(!J){let F=H6();if(F.accessKeyId&&F.secretAccessKey){if(E.env.AWS_ACCESS_KEY_ID=F.accessKeyId,E.env.AWS_SECRET_ACCESS_KEY=F.secretAccessKey,F.region&&!E.env.AWS_REGION)E.env.AWS_REGION=F.region;J=!0,R.success("Using AWS credentials from ~/.aws/credentials")}}if(!J){if(R.info("AWS credentials not found in .env or ~/.aws/credentials."),R.info("You can either:"),R.info(" 1. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in .env.production"),R.info(" 2. Add credentials to ~/.aws/credentials"),R.info(" 3. Configure them interactively below"),console.log(""),Q?.yes)R.info("Skipping credential setup (--yes flag provided)"),E.exit(K0.FatalError);let F=await j$.confirm({message:"Would you like to configure AWS credentials now?",initial:!0});if(R.debug("setupCredentials response:",F,typeof F),F===void 0||F===!1){if(F===void 0)console.log(""),R.info("Deployment cancelled"),E.exit(K0.Success);return console.log(""),R.info("Skipping cloud infrastructure check"),R.info("You can configure AWS credentials later by running: buddy configure:aws"),!0}await U6()}else R.success("AWS credentials found");let Y=(E.env.APP_NAME||p3.name||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-"),G=`${Y}-cloud`,{AWSCloudFormationClient:z}=await import("@stacksjs/ts-cloud"),W=new z(E.env.AWS_REGION||"us-east-1"),X=!1,H=!1;try{let F=(await W.describeStacks({stackName:G})).Stacks?.[0];if(F){X=!0,R.success("Cloud stack exists");let{AWSCloudFormationClient:O}=await import("@stacksjs/ts-cloud"),T=await new O(E.env.AWS_REGION||"us-east-1").listStackResources(G),f=T.StackResourceSummaries?.some((i)=>i.LogicalResourceId==="EmailBucket"),P=T.StackResourceSummaries?.some((i)=>i.LogicalResourceId==="OutboundEmailLambda"),I=T.StackResourceSummaries?.some((i)=>i.LogicalResourceId==="EmailConversionLambda"),j=T.StackResourceSummaries?.some((i)=>i.LogicalResourceId==="EmailNotificationTopic"),A=T.StackResourceSummaries?.some((i)=>i.LogicalResourceId==="MailApiLambda"),h=T.StackResourceSummaries?.some((i)=>i.LogicalResourceId==="MailUsersTable"),V=T.StackResourceSummaries?.some((i)=>i.LogicalResourceId==="MailServerInstance"),N=F.Outputs?.find((i)=>i.OutputKey==="EmailDomain")?.OutputValue,B=(c?.from?.address?.includes("@")?c.from.address.split("@")[1]:void 0)||"stacksjs.com";if(!f&&c?.server?.scan!==void 0)R.info("Email infrastructure not found in stack, will update..."),H=!0;else if(N&&N!==B)R.info(`Email domain changed: ${N} -> ${B}, will update...`),H=!0;else if(f&&(!P||!I||!j))R.info("Email infrastructure incomplete, will update..."),H=!0;else if(f&&(!A||!h))R.info("Mail API infrastructure missing, will update..."),H=!0;else if(f&&!V&&c?.server?.enabled)R.info("Mail server EC2 instance missing, will update..."),H=!0;let v=(F.Outputs||[]).find((i)=>i.OutputKey==="MailServerMode")?.OutputValue,B0=c?.server?.mode||"serverless";if(v&&v!==B0)R.info(`Mail server mode changed: ${v} -> ${B0}, will update...`),H=!0;if(V&&c?.server?.enabled){if(E.env.FORCE_MAIL_UPDATE==="true")R.info("Forcing mail server update..."),H=!0}if(!H)return!0}}catch(F){R.debug(`Stack not found: ${F.message}`)}if(!X)R.info("Cloud stack not found, will be created by deploy action");return!0}catch(J){if(!$){if(R.error("Error checking cloud infrastructure"),R.error(`Error: ${J.message||J}`),Q?.verbose)console.error(J)}E.exit(K0.FatalError)}}import x from"process";import{bold as J7,cyan as m0,dim as Q0,green as Y7,intro as P2,log as N0,onUnknownSubcommand as V6,outro as U$,prompts as B6,runCommand as R6}from"@stacksjs/cli";import{Action as i3}from"@stacksjs/enums";import{libsPath as w6}from"@stacksjs/path";import{ExitCode as u0}from"@stacksjs/types";var a3="0.70.35";var f2;async function A0(){if(!f2)f2=await import("@stacksjs/actions");return f2}function AW(Q){let $={dev:"Start development server",frontend:"Start the frontend development server",components:"Start the Components development server",desktop:"Start the Desktop App development server",dashboard:"Start the Dashboard development server",api:"Start the local API development server",email:"Start the Email development server",docs:"Start the Documentation development server",systemTray:"Start the System Tray development server",interactive:"Get asked which development server to start",select:"Which development server are you trying to start?",withLocalhost:"Include the localhost URL in the output",project:"Target a specific project",verbose:"Enable verbose output"};Q.command("dev [server]",$.dev).option("-f, --frontend",$.frontend).option("-a, --api",$.api).option("-e, --email",$.email).option("-c, --components",$.components).option("-d, --dashboard",$.dashboard).option("-k, --desktop",$.desktop).option("-o, --docs",$.docs).option("-s, --system-tray",$.systemTray).option("-i, --interactive",$.interactive,{default:!1}).option("-l, --with-localhost",$.withLocalhost,{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J,Y)=>{let G=Bun.nanoseconds(),z=J||(Y.frontend?"frontend":void 0)||(Y.api?"api":void 0)||(Y.components?"components":void 0)||(Y.dashboard?"dashboard":void 0)||(Y.desktop?"desktop":void 0)||(Y.systemTray||Y["system-tray"]?"system-tray":void 0)||(Y.docs?"docs":void 0);if(z){let W={...Y},X=await A0();switch(z){case"frontend":await X.runFrontendDevServer(W);break;case"api":await X.runApiDevServer(W);break;case"components":await X.runComponentsDevServer(W);break;case"dashboard":await X.runDashboardDevServer(W);break;case"desktop":await X.runDesktopDevServer(W);break;case"system-tray":await X.runSystemTrayDevServer(W);break;case"docs":await X.runDocsDevServer(W);break;default:N0.error(`Unknown server: ${z}`),x.exit(u0.InvalidArgument)}}else if(P6(Y)){let X=(await B6({type:"select",name:"value",message:$.select,choices:[{value:"all",title:"All"},{value:"frontend",title:"Frontend"},{value:"api",title:"Backend"},{value:"dashboard",title:"Dashboard"},{value:"desktop",title:"Desktop"},{value:"email",title:"Email"},{value:"components",title:"Components"},{value:"docs",title:"Documentation"}]})).value;if(X==="components")await(await A0()).runComponentsDevServer(Y);else if(X==="api")await(await A0()).runApiDevServer(Y);else if(X==="dashboard")await(await A0()).runDashboardDevServer(Y);else if(X==="docs")await(await A0()).runDocsDevServer(Y);else N0.error("Invalid option during interactive mode"),x.exit(u0.InvalidArgument)}else await M6(Y,G);U$("Exited",{startTime:G,useSeconds:!0}),x.exit(u0.Success)}),Q.command("dev:components",$.components).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{let Y=await P2("buddy dev:components"),G=await R6("bun run dev",{cwd:w6("components/vue")});if(J.verbose)N0.info("buddy dev:components result",G);if(G.isErr)await U$("While running the dev:components command, there was an issue",{startTime:Y,useSeconds:!0},G.error),x.exit(u0.FatalError);console.log(""),await U$("Exited",{startTime:Y,useSeconds:!0}),x.exit(u0.Success)}),Q.command("dev:docs",$.docs).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{let Y=await P2("buddy dev:docs"),G=await(await A0()).runAction(i3.DevDocs,J);if(G.isErr)await U$("While running the dev:docs command, there was an issue",{startTime:Y,useSeconds:!0},G.error),x.exit(u0.FatalError);console.log(""),await U$("Exited",{startTime:Y,useSeconds:!0}),x.exit(u0.Success)}),Q.command("dev:desktop",$.desktop).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{let Y=await P2("buddy dev:desktop"),G=await(await A0()).runAction(i3.DevDesktop,J);if(G.isErr)await U$("While running the dev:desktop command, there was an issue",{startTime:Y,useSeconds:!0},G.error),x.exit(u0.FatalError);console.log(""),await U$("Exited",{startTime:Y,useSeconds:!0}),x.exit(u0.Success)}),Q.command("dev:api",$.api).option("-p, --project [project]",$.project,{default:!1}).option("--no-watch-types","Skip the model/config type-regeneration watcher",{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{let Y=await A0();if(J.watchTypes!==!1)Y.watchTypes(J).catch((G)=>{N0.warn("[dev:api] type watcher exited:",G)});await Y.runApiDevServer(J)}),Q.command("dev:frontend",$.frontend).alias("dev:pages").alias("dev:views").option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{await(await A0()).runFrontendDevServer(J)}),Q.command("dev:dashboard",$.dashboard).alias("dev:admin").option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{await(await A0()).runDashboardDevServer(J)}),Q.command("dev:system-tray",$.systemTray).alias("dev:tray").option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{await(await A0()).runSystemTrayDevServer(J)}),V6(Q,"dev")}async function M6(Q,$){let J=x.env.APP_URL,Y=Number(x.env.PORT)||3000,G=Number(x.env.PORT_API)||3008,z=Number(x.env.PORT_DOCS)||3006,W=Number(x.env.PORT_ADMIN)||3002,X=x.env.STACKS_DEV_DASHBOARD==="1",H=J&&J!=="localhost"&&!J.includes("localhost:"),q=H?J.replace(/^https?:\/\//,""):null,Z=q?`api.${q}`:null,K=q?`docs.${q}`:null,_=q?`dashboard.${q}`:null,U=q?`https://${q}`:`http://localhost:${Y}`,L=Z?`https://${Z}`:`http://localhost:${G}`,F=K?`https://${K}`:`http://localhost:${z}`,O=_?`https://${_}`:`http://localhost:${W}`;if(console.log(),console.log(` ${J7(m0("stacks"))} ${Q0(`v${a3}`)}`),console.log(),console.log(` ${Y7("\u279C")} ${J7("Frontend")}: ${m0(U)}`),console.log(` ${Y7("\u279C")} ${J7("API")}: ${m0(L)}`),console.log(` ${Y7("\u279C")} ${J7("Docs")}: ${m0(F)}`),X)console.log(` ${Y7("\u279C")} ${J7("Dashboard")}: ${m0(O)}`);if(Q.verbose&&q){if(console.log(` ${Q0("\u279C")} ${Q0("Proxy")}: ${Q0(`localhost:${Y} \u2192 ${q}`)}`),console.log(` ${Q0("\u279C")} ${Q0("Proxy")}: ${Q0(`localhost:${G} \u2192 ${Z}`)}`),console.log(` ${Q0("\u279C")} ${Q0("Proxy")}: ${Q0(`localhost:${z} \u2192 ${K}`)}`),X)console.log(` ${Q0("\u279C")} ${Q0("Proxy")}: ${Q0(`localhost:${W} \u2192 ${_}`)}`)}if(console.log(),x.env.STACKS_PROXY_MANAGED="1",x.env.STACKS_DEV_NO_KILL!=="1")try{await Bun.spawn(["pkill","-9","-f","bun --watch storage/framework/core/actions/src/dev/"],{stdout:"ignore",stderr:"ignore"}).exited,await new Promise((V)=>setTimeout(V,200))}catch{}let M=!1,T=1500,f=()=>{if(M)return;M=!0;try{x.kill(-x.pid,"SIGTERM")}catch{try{x.kill(0,"SIGTERM")}catch{}}setTimeout(()=>{try{x.kill(0,"SIGKILL")}catch{x.exit(1)}},T).unref()};x.on("SIGINT",f),x.on("SIGTERM",f);let P={...Q,quiet:!0},I=await A0(),j=[{name:"Frontend",port:Y},{name:"API",port:G},{name:"Docs",port:z},...X?[{name:"Dashboard",port:W}]:[]],A=30000,h=!1;Promise.all(j.map((V)=>j6(V.port,A))).then(async(V)=>{if(h)return;h=!0;let N=V.map((B,v)=>B?null:j[v].name).filter((B)=>B!==null);if($){let B=(Bun.nanoseconds()-$)/1e6,v=N.length?`ready in ${(B/1000).toFixed(1)}s \u2014 ${N.join(", ")} did not bind within ${A/1000}s`:`ready in ${(B/1000).toFixed(1)}s`;console.log(` ${Q0(v)}
304
304
  `)}if(x.env.STACKS_PRINT_ROUTES==="1")await I6(G).catch(()=>{})}).catch(()=>{}),await Promise.all([I.runFrontendDevServer(P).catch((V)=>{if(Q.verbose)N0.error(`Frontend: ${V}`)}),I.runApiDevServer(P).catch((V)=>{if(Q.verbose)N0.error(`API: ${V}`)}),I.runDocsDevServer(P).catch((V)=>{if(Q.verbose)N0.error(`Docs: ${V}`)}),X?I.runDashboardDevServer(P).catch((V)=>{if(Q.verbose)N0.error(`Dashboard: ${V}`)}):Promise.resolve(),H?A6(Q).catch((V)=>{if(Q.verbose)N0.warn(`Proxy: ${V}`)}):Promise.resolve()])}var T6={GET:m0,POST:Y7,PUT:m0,PATCH:m0,DELETE:m0,OPTIONS:Q0};async function I6(Q){try{let $=new AbortController,J=setTimeout(()=>$.abort(),1500),Y=await fetch(`http://127.0.0.1:${Q}/__routes`,{signal:$.signal}).catch(()=>null);if(clearTimeout(J),!Y||!Y.ok)return;let G=await Y.json();if(!Array.isArray(G)||G.length===0)return;let z=[...G].sort((X,H)=>X.path.localeCompare(H.path)||X.method.localeCompare(H.method)),W=Math.max(...z.map((X)=>X.path.length));console.log(` ${Q0("Registered routes")}
305
305
  `);for(let X of z){let q=(T6[X.method.toUpperCase()]??Q0)(X.method.toUpperCase().padEnd(6)),Z=X.path.padEnd(W),K=X.name?` ${Q0(`(${X.name})`)}`:"";console.log(` ${q} ${Z}${K}`)}console.log()}catch{}}async function j6(Q,$){let J=Date.now()+$;while(Date.now()<J){if(await new Promise((G)=>{let z=new AbortController,W=setTimeout(()=>z.abort(),800);fetch(`http://127.0.0.1:${Q}/__health`,{signal:z.signal,redirect:"manual"}).then(()=>{clearTimeout(W),G(!0)}).catch(()=>{clearTimeout(W),G(!1)})}))return!0;await new Promise((G)=>setTimeout(G,250))}return!1}async function A6(Q){let $=x.env.APP_URL;if(!$||$==="localhost"||$.includes("localhost:"))return;let J=$.replace(/^https?:\/\//,""),Y=`api.${J}`,G=`docs.${J}`,z=`dashboard.${J}`,W=Number(x.env.PORT)||3000,X=Number(x.env.PORT_API)||3008,H=Number(x.env.PORT_DOCS)||3006,q=Number(x.env.PORT_ADMIN)||3002,Z=`${x.env.HOME}/.stacks/ssl`,K=Q.verbose??!1,_=x.env.STACKS_DEV_DASHBOARD==="1";try{let{startProxies:U}=await import("@stacksjs/rpx");await U({proxies:[{from:`localhost:${W}`,to:J,cleanUrls:!1,pathRewrites:[{from:"/api",to:`localhost:${X}`,stripPrefix:!1}]},{from:`localhost:${X}`,to:Y,cleanUrls:!1},{from:`localhost:${H}`,to:G,cleanUrls:!1},..._?[{from:`localhost:${q}`,to:z,cleanUrls:!1}]:[]],https:{basePath:Z,validityDays:825},regenerateUntrustedCerts:!1,verbose:K})}catch(U){if(Q.verbose)N0.warn("Reverse proxy not available, skipping HTTPS"),N0.warn(String(U))}}function P6(Q){return Q.interactive}import s3 from"process";import{log as o3,onUnknownSubcommand as f6}from"@stacksjs/cli";import{config as v6}from"@stacksjs/config";import{DnsClient as S6,formatOutput as E6}from"@stacksjs/dnsx";import{ExitCode as t3}from"@stacksjs/types";function CW(Q){let $={dns:"Lists the DNS records for a domain",query:"Host name or IP address to query",type:"Type of the DNS record being queried (A, MX, NS\u2026)",nameserver:"Address of the nameserver to send packets to",class:"Network class of the DNS record being queried (IN, CH, HS)",udp:"Use the DNS protocol over UDP",tcp:"Use the DNS protocol over TCP",tls:"Use the DNS-over-TLS protocol",https:"Use the DNS-over-HTTPS protocol",short:"Short mode: display nothing but the first result",json:"Display the output as JSON",project:"Target a specific project",verbose:"Enable verbose output"};Q.command("dns [domain]",$.dns).option("-q, --query <query>",$.query).option("-t, --type <type>",$.type,{default:"A"}).option("-n, --nameserver <nameserver>",$.nameserver).option("--class <class>",$.class).option("-U, --udp",$.udp).option("-T, --tcp",$.tcp).option("-S, --tls",$.tls).option("-H, --https",$.https).option("-1, --short",$.short,{default:!1}).option("-J, --json",$.json,{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J,Y)=>{o3.debug("Running `buddy dns [domain]` ...",Y);let G=J||v6.app.url;try{let z=new S6({domains:[G],type:Y.type,nameserver:Y.nameserver,class:Y.class,udp:Y.udp,tcp:Y.tcp,tls:Y.tls,https:Y.https,short:Y.short,json:Y.json,verbose:Y.verbose}),W=performance.now(),X=await z.query(),H=performance.now()-W,q=E6(X,{json:Y.json??!1,short:Y.short??!1,showDuration:H,colors:{enabled:!0},rawSeconds:!1});console.log(q)}catch(z){o3.error(`DNS query failed: ${z instanceof Error?z.message:String(z)}`),s3.exit(t3.FatalError)}s3.exit(t3.Success)}),f6(Q,"dns")}import c0 from"process";import{bold as e3,dim as v2,green as $1,intro as N6,log as R0,onUnknownSubcommand as C6,red as h6,yellow as Q1}from"@stacksjs/cli";import{storage as J1}from"@stacksjs/storage";async function G7(Q,$,J){let Y=Date.now();try{let G=new AbortController,z=setTimeout(()=>G.abort(),2000),W=await Promise.race([J(),new Promise((X,H)=>G.signal.addEventListener("abort",()=>H(Error("timed out (>2s)"))))]);clearTimeout(z),Q.push({name:$,status:"pass",message:`${W} (${Date.now()-Y}ms)`})}catch(G){Q.push({name:$,status:"fail",message:G instanceof Error?G.message:String(G)})}}function kW(Q){Q.command("doctor","Run health checks on your Stacks installation").action(async()=>{R0.debug("Running `buddy doctor` ..."),await N6("buddy doctor");let $=[],J=c0.versions.bun;if(J)if(Number.parseInt(J.split(".")[0]||"0",10)>=1)$.push({name:"Bun Runtime",status:"pass",message:`v${J}`});else $.push({name:"Bun Runtime",status:"warn",message:`v${J} (v1.0+ recommended)`});else $.push({name:"Bun Runtime",status:"fail",message:"Not found"});let Y=c0.versions.node;if(Y)if(Number.parseInt(Y.split(".")[0]||"0",10)>=18)$.push({name:"Node.js",status:"pass",message:`v${Y}`});else $.push({name:"Node.js",status:"warn",message:`v${Y} (v18+ recommended)`});try{let q=await J1.readPackageJson("./package.json");if(q.name)$.push({name:"package.json",status:"pass",message:`Found: ${q.name}`})}catch{$.push({name:"package.json",status:"fail",message:"Not found in current directory"})}try{await J1.readTextFile(".env"),$.push({name:".env file",status:"pass",message:"Found"})}catch{$.push({name:".env file",status:"warn",message:"Not found (optional)"})}let G=c0.env.APP_KEY;if(G&&G.length>0)$.push({name:"APP_KEY",status:G.length>=32?"pass":"warn",message:G.length>=32?"Set (\u226532 chars)":`Set but short (${G.length} chars; \u226532 recommended)`});else $.push({name:"APP_KEY",status:"fail",message:"Not set \u2014 features that depend on it (encrypted columns, signed URLs, env decryption) will refuse to run. Run `buddy key:generate`."});await G7($,"Database",async()=>{let{db:q}=await import("@stacksjs/database");return await q.unsafe?.("SELECT 1"),"Reachable"}),await G7($,"Cache",async()=>{let{cache:q}=await import("@stacksjs/cache"),Z=`__doctor_${Date.now()}`;await q.set(Z,1,5);let K=await q.get(Z);if(await q.del(Z),K!==1)throw Error("round-trip failed");return"Round-trip ok"}),await G7($,"Queue driver",async()=>{let{config:q}=await import("@stacksjs/config");return`Driver: ${q.queue?.default??"sync"}`}),await G7($,"Mail driver",async()=>{let{config:q}=await import("@stacksjs/config");return`Driver: ${q.email?.default??"log"}`});let z=Boolean(c0.env.AWS_ACCESS_KEY_ID&&c0.env.AWS_SECRET_ACCESS_KEY),W=Boolean(c0.env.AWS_PROFILE)||Boolean(c0.env.AWS_ROLE_ARN);if(z||W)$.push({name:"AWS credentials",status:"pass",message:z?"Static keys in env":"IAM role configured"});else $.push({name:"AWS credentials",status:"warn",message:"Not configured (cloud / SES / S3 commands will fail)"});await G7($,".env decryption",async()=>{let q=await import("fs");if(!q.existsSync(".env"))return"No .env (skipped)";let Z=q.readFileSync(".env","utf8");if(!/(?:^|=)(?:enc|encrypted):/m.test(Z))return"No encrypted values";let K=c0.env.DOTENV_PRIVATE_KEY;if(!K)throw Error("Encrypted values present but DOTENV_PRIVATE_KEY is unset");let{parse:_}=await import("@stacksjs/env"),{errors:U}=_(Z,{privateKey:K});if(U.length>0)throw Error(U.join("; "));return"All encrypted values decrypt cleanly"}),R0.info(""),R0.info(e3("Health Check Results:")),R0.info(v2("\u2500".repeat(60))),R0.info("");let X=!1,H=!1;for(let q of $){let Z="",K=(_)=>_;if(q.status==="pass")Z="\u2713",K=$1;else if(q.status==="warn")Z="\u26A0",K=Q1,H=!0;else Z="\u2717",K=h6,X=!0;R0.info(`${K(Z)} ${e3(q.name.padEnd(20))} ${v2(q.message)}`)}if(R0.info(""),R0.info(v2("\u2500".repeat(60))),R0.info(""),X)R0.error("Some critical checks failed. Please address the issues above."),c0.exit(1);else if(H)R0.info(Q1("Some checks have warnings. Your system should work but may have issues."));else R0.success($1("All checks passed! Your Stacks installation looks healthy."));R0.info("")}),C6(Q,"doctor")}import e0 from"process";import{runAction as Y1}from"@stacksjs/actions";import{bgCyan as D6,bold as b6,intro as S2,italic as L$,log as d7,onUnknownSubcommand as y6,outro as $$,prompts as G1}from"@stacksjs/cli";import{config as z1}from"@stacksjs/config";import{addDomain as k6}from"@stacksjs/dns";import{Action as W1}from"@stacksjs/enums";import{ExitCode as Q$}from"@stacksjs/types";function rW(Q){let $={purchase:"Purchase a domain",add:"Add a domain to your cloud",remove:"Remove a domain from your cloud",skip:"Skip the confirmation prompt",project:"Target a specific project",verbose:"Enable verbose output"},J=z1.dns.contactInfo;Q.command("domains:purchase <domain>",$.purchase).option("--years <years>","Number of years to purchase the domain for",{default:1}).option("--privacy","Enable privacy protection",{default:!0}).option("--auto-renew","Enable auto-renew",{default:!0}).option("--first-name <firstName>","Registrant first name",{default:J?.firstName}).option("--last-name <lastName>","Registrant last name",{default:J?.lastName}).option("--organization <organization>","Registrant organization name",{default:J?.organizationName}).option("--address-line1 <address>","Registrant address line 1",{default:J?.addressLine1}).option("--address-line2 <address>","Registrant address line 2",{default:J?.addressLine2}).option("--city <city>","Registrant city",{default:J?.city}).option("--state <state>","Registrant state",{default:J?.state}).option("--country <country>","Registrant country code",{default:J?.countryCode}).option("--zip <zip>","Registrant zip",{default:J?.zip}).option("--phone <phone>","Registrant phone",{default:J?.phoneNumber}).option("--email <email>","Registrant email",{default:J?.email}).option("--admin-first-name <firstName>","Admin first name",{default:J?.admin?.firstName||J?.firstName}).option("--admin-last-name <lastName>","Admin last name",{default:J?.admin?.lastName||J?.lastName}).option("--admin-organization <organization>","Admin organization",{default:J?.admin?.organizationName||J?.organizationName}).option("--admin-address-line1 <address>","Admin address line 1",{default:J?.admin?.addressLine1||J?.addressLine1}).option("--admin-address-line2 <address>","Admin address line 2",{default:J?.admin?.addressLine2||J?.addressLine2}).option("--admin-city <city>","Admin city",{default:J?.admin?.city||J?.city}).option("--admin-state <state>","Admin state",{default:J?.admin?.state||J?.state}).option("--admin-country <country>","Admin country code",{default:J?.admin?.countryCode||J?.countryCode}).option("--admin-zip <zip>","Admin zip",{default:J?.admin?.zip||J?.zip}).option("--admin-phone <phone>","Admin phone number",{default:J?.admin?.phoneNumber||J?.phoneNumber}).option("--admin-email <email>","Admin email",{default:J?.admin?.email||J?.email}).option("--tech-first-name <firstName>","Tech first name",{default:J?.tech?.firstName||J?.firstName}).option("--tech-last-name <lastName>","Tech last name",{default:J?.tech?.lastName||J?.lastName}).option("--tech-organization <organization>","Tech organization name",{default:J?.tech?.organizationName||J?.organizationName}).option("--tech-address-line1 <address>","Tech address line 1",{default:J?.tech?.addressLine1||J?.addressLine1}).option("--tech-address-line2 <address>","Tech address line 2",{default:J?.tech?.addressLine2||J?.addressLine2}).option("--tech-city <city>","Tech city",{default:J?.tech?.city||J?.city}).option("--tech-state <state>","Tech state",{default:J?.tech?.state||J?.state}).option("--tech-country <country>","Tech country",{default:J?.tech?.countryCode||J?.countryCode}).option("--tech-zip <zip>","Tech zip",{default:J?.tech?.zip||J?.zip}).option("--tech-phone <phone>","Tech phone",{default:J?.tech?.phoneNumber||J?.phoneNumber}).option("--tech-email <email>","Tech email",{default:J?.tech?.email||J?.email}).option("--privacy-admin","Enable privacy protection for admin",{default:J?.privacyAdmin||J?.privacy||!0}).option("--privacy-tech","Enable privacy protection for tech",{default:J?.privacyTech||J?.privacy||!0}).option("--privacy-registrant","Enable privacy protection for registrant",{default:J?.privacyRegistrant||J?.privacy||!0}).option("--contact-type <type>","Contact type",{default:"person"}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(Y,G)=>{d7.debug("Running `buddy domains:purchase <domain>` ...",G),G.domain=Y;let z=await S2("buddy domains:purchase"),W=await Y1(W1.DomainsPurchase,G);if(W.isErr)await $$("While running the domains:purchase command, there was an issue",{startTime:z,useSeconds:!0},W.error),e0.exit(Q$.FatalError);let{confirm:X}=await G1({name:"confirm",type:"confirm",message:`Would you like to set ${Y} as your APP_URL?`});if(!X)await $$(`Alrighty! ${L$(Y)} was added to your account.`,{startTime:z,useSeconds:!0,type:"success"}),d7.info(`Please note, you may need to validate your email address. Check your ${L$(G.registrantEmail)} inbox.`),e0.exit(Q$.Success);let{writeEnv:H}=await import("@stacksjs/env");H("APP_URL",Y);let q=`Great! ${L$(Y)} was added to your account.`;q+=`
306
306
 
@@ -447,4 +447,4 @@ To enable SMS:`),console.log("1. Edit config/sms.ts and set enabled: true"),cons
447
447
  \uD83D\uDCA1 Make sure you entered the correct 6-digit code.`),console.log(" Run `buddy sms:add-phone <phone>` to resend the code.")}catch(Y){console.error("Error verifying phone:",Y.message)}process.exit(0)}),Q.command("sms:sandbox-list","List sandbox verified phone numbers").action(async()=>{console.log(`
448
448
  \uD83D\uDCF1 Sandbox Verified Numbers
449
449
  `),y$();try{let{PinpointSmsVoiceClient:$}=await import("@stacksjs/ts-cloud"),J=new $(process.env.AWS_REGION||"us-east-1"),Y=await W$(J.listSandboxPhones(),30000);if(Y.length===0)console.log("No verified sandbox numbers yet."),console.log(`
450
- To add a phone:`),console.log(" buddy sms:add-phone +1234567890");else for(let G of Y){let z=G.status==="VERIFIED"?"\u2705":"\u23F3";console.log(` ${z} ${G.phoneNumber} (${G.status})`),console.log(` ID: ${G.id}`)}}catch($){console.error("Error listing sandbox phones:",$.message)}process.exit(0)})}import s9 from"process";import{bold as L3,dim as X0,green as aY,intro as iY,log as k,onUnknownSubcommand as sY}from"@stacksjs/cli";var F3={async enable(){},async disable(){},async status(){return{enabled:!1,doNotTrack:!!s9.env.DO_NOT_TRACK,eventsQueued:0,lastSent:null}}};function KZ(Q){Q.command("telemetry","Manage telemetry settings").option("--enable","Enable telemetry").option("--disable","Disable telemetry").option("--status","Show telemetry status").example("buddy telemetry --status").example("buddy telemetry --enable").example("buddy telemetry --disable").action(async($)=>{k.debug("Running `buddy telemetry` ...",$),await iY("buddy telemetry");try{if($.enable){await F3.enable(),k.success("Telemetry enabled"),k.info(""),k.info(X0("Anonymous usage statistics will be collected")),k.info(X0("to help improve Buddy CLI.")),k.info(""),k.info(X0("You can disable telemetry anytime with:")),k.info(X0(" buddy telemetry --disable")),k.info("");return}if($.disable){await F3.disable(),k.success("Telemetry disabled"),k.info(""),k.info(X0("No usage statistics will be collected.")),k.info("");return}let J=await F3.status();if(k.info(""),k.info(aY(L3("Telemetry Status"))),k.info(X0("\u2500".repeat(50))),k.info(""),k.info(L3("Configuration:")),k.info(` Enabled: ${X0(J.enabled?"Yes":"No")}`),k.info(` DO_NOT_TRACK: ${X0(J.doNotTrack?"Yes (respected)":"No")}`),k.info(` Events queued: ${X0(J.eventsQueued)}`),J.lastSent){let Y=new Date(J.lastSent);k.info(` Last sent: ${X0(Y.toLocaleString())}`)}else k.info(` Last sent: ${X0("Never")}`);if(k.info(""),k.info(L3("Privacy:")),k.info(` ${X0("\u2022 Opt-in only (disabled by default)")}`),k.info(` ${X0("\u2022 No personal information collected")}`),k.info(` ${X0("\u2022 Anonymous user IDs only")}`),k.info(` ${X0("\u2022 Respects DO_NOT_TRACK environment variable")}`),k.info(""),!J.enabled)k.info(X0("To enable telemetry: buddy telemetry --enable")),k.info("");else k.info(X0("To disable telemetry: buddy telemetry --disable")),k.info("")}catch(J){k.error("Failed to manage telemetry:",J),s9.exit(1)}}),sY(Q,"telemetry")}import p0 from"process";import{runAction as X$}from"@stacksjs/actions";import{intro as P7,log as o9,onUnknownSubcommand as oY,outro as M0}from"@stacksjs/cli";import{Action as q$}from"@stacksjs/enums";import{projectPath as H$}from"@stacksjs/path";import{ExitCode as r0}from"@stacksjs/types";function RZ(Q){let $={command:"Runs your test suite",types:"Typechecks your codebase",coverage:"Generates a test coverage report",ui:"Runs your test suite in the browser",unit:"Runs your unit tests",feature:"Runs your feature tests",showReport:"Show the test report",project:"Target a specific project",verbose:"Enable verbose output"};Q.command("test",$.command).option("-f, --feature",$.feature,{default:!1}).option("-u, --unit",$.unit,{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!0}).action(async(J)=>{let Y=await P7("buddy test");if(J.feature&&J.unit){let G=await X$(q$.Test,{...J,cwd:H$()});if(G.isErr)await M0("While running `buddy test`, there was an issue",{startTime:Y,useSeconds:!0},G.error),p0.exit(r0.FatalError)}if(J.feature&&!J.unit){o9.info("Running Feature tests...");let G=await X$(q$.TestFeature,{...J,cwd:H$()});if(G.isErr)await M0("While running `buddy test`, there was an issue",{startTime:Y,useSeconds:!0},G.error),p0.exit(r0.FatalError)}if(!J.feature&&J.unit){o9.info("Running Unit tests...");let G=await X$(q$.TestUnit,{...J,cwd:H$()});if(G.isErr)await M0("While running `buddy test`, there was an issue",{startTime:Y,useSeconds:!0},G.error),p0.exit(r0.FatalError)}if(!J.feature&&!J.unit){let G=await X$(q$.Test,{...J,cwd:H$()});if(G.isErr)await M0("While running `buddy test`, there was an issue",{startTime:Y,useSeconds:!0},G.error),p0.exit(r0.FatalError)}await M0("Finished running tests",{startTime:Y,useSeconds:!0}),p0.exit(r0.Success)}),Q.command("test:unit",$.unit).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{let Y=await P7("buddy test:unit"),G=await X$(q$.TestUnit,{...J,verbose:!0,cwd:H$()});if(G.isErr)await M0("While running `buddy test:unit`, there was an issue",{startTime:Y,useSeconds:!0},G.error),p0.exit(r0.FatalError);await M0("Finished running unit tests",{startTime:Y,useSeconds:!0})}),Q.command("test:feature",$.feature).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{let Y=await P7("buddy test:feature"),G=await X$(q$.TestFeature,{...J,verbose:!0,cwd:H$()});if(G.isErr)await M0("While running `buddy test:feature`, there was an issue",{startTime:Y,useSeconds:!0},G.error),p0.exit(r0.FatalError);await M0("Finished running feature tests",{startTime:Y,useSeconds:!0})}),Q.command("test:ui",$.command).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{let Y=await P7("buddy test:ui"),G=await X$(q$.TestUi,{...J,verbose:!0,cwd:H$()});if(G.isErr)await M0("While running `buddy test:ui`, there was an issue",{startTime:Y,useSeconds:!0},G.error),p0.exit(r0.FatalError);await M0("Finished running tests in the browser",{startTime:Y,useSeconds:!0})}),Q.command("test:types",$.types).alias("typecheck").option("--verbose",$.verbose,{default:!1}).action(async(J)=>{let Y=await P7("buddy test:types"),G=await X$(q$.Typecheck,{...J,verbose:!0,cwd:H$()});if(G.isErr)await M0("While running `buddy test:types`, there was an issue",{startTime:Y,useSeconds:!0},G.error),p0.exit(r0.FatalError);await M0("Finished running typecheck",{startTime:Y,useSeconds:!0})}),oY(Q,"test")}import O3 from"process";import{intro as tY,log as eY,onUnknownSubcommand as $G,outro as V3}from"@stacksjs/cli";import{ExitCode as B3}from"@stacksjs/types";function jZ(Q){let $={tinker:"Interactive REPL with Stacks framework preloaded",eval:"Evaluate a single expression and exit",print:"Evaluate, print, and exit",noBanner:"Skip the welcome banner",preload:"Additional modules to preload (comma-separated)",project:"Target a specific project",verbose:"Enable verbose output"};Q.command("tinker",$.tinker).option("-e, --eval [expression]",$.eval,{default:""}).option("--print [expression]",$.print,{default:""}).option("--no-banner",$.noBanner,{default:!1}).option("--preload [modules]",$.preload,{default:""}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{eY.debug("Running `buddy tinker` ...",J);let Y=await tY("buddy tinker");try{let{startTinker:G}=await import("@stacksjs/tinker"),z=typeof J.preload==="string"&&J.preload?J.preload.split(",").map((X)=>X.trim()):void 0;if((await G({eval:typeof J.eval==="string"&&J.eval?J.eval:void 0,print:typeof J.print==="string"&&J.print?J.print:void 0,banner:J.noBanner!==!0,preload:z,verbose:J.verbose===!0})).exitCode!==0)await V3("Tinker session ended with errors",{startTime:Y,useSeconds:!0}),O3.exit(B3.FatalError);await V3("Tinker session ended.",{startTime:Y,useSeconds:!0}),O3.exit(B3.Success)}catch(G){await V3("While running the tinker command, there was an issue",{startTime:Y,useSeconds:!0},G instanceof Error?G:void 0),O3.exit(B3.FatalError)}}),$G(Q,"tinker")}import{generateTypes as QG}from"@stacksjs/actions";import{log as JG}from"@stacksjs/logging";import{onUnknownSubcommand as YG}from"@stacksjs/cli";function SZ(Q){let $={generate:"Generate the types of & for your library/libraries",fix:"wip",project:"Target a specific project",verbose:"Enable verbose output"};Q.command("types:generate",$.generate).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{JG.debug("Running `buddy types:generate` ...",J),await QG(J)}),Q.command("types:fix",$.fix).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async()=>{}),YG(Q,"types")}import F0 from"process";import{runAction as x$}from"@stacksjs/actions";import{intro as g$,log as R$,onUnknownSubcommand as GG,outro as S0}from"@stacksjs/cli";import{Action as u$}from"@stacksjs/enums";import{ExitCode as T0}from"@stacksjs/types";function yZ(Q){let $={upgrade:"Upgrade the Stacks framework to the latest version",version:"Install a specific version (e.g., 0.70.23)",canary:"Upgrade to the latest canary (development) build",stable:"Switch back to the latest stable release",force:"Force re-download, bypassing cache and version checks",from:"Sync from a local stacks checkout (e.g. ~/Code/stacks). Skips GitHub.",noPostinstall:"Skip post-sync hooks (auto-imports, bun install, migrate)",verbose:"Enable verbose output",dependencies:"Upgrade your dependencies (pantry.yaml & package.json)",bun:"Upgrade Bun to the latest version",shell:"Upgrade the shell integration (currently only supports Oh My Zsh)",binary:"Upgrade the `stacks` binary to the latest version",project:"Target a specific project",all:"Upgrade framework, dependencies, Bun, and binary"};Q.command("upgrade",$.upgrade).option("-v, --version <version>",$.version).option("--canary",$.canary,{default:!1}).option("--stable",$.stable,{default:!1}).option("-f, --force",$.force,{default:!1}).option("--from <path>",$.from).option("--no-postinstall",$.noPostinstall).option("--verbose",$.verbose,{default:!1}).alias("update").example("buddy upgrade").example("buddy upgrade --from ~/Code/stacks").example("buddy upgrade --version 0.70.23").example("buddy upgrade --canary").example("buddy upgrade --stable").example("buddy upgrade --force").action(async(J)=>{R$.debug("Running `buddy upgrade` ...",J);let Y={...J};if(Y.postinstall===!1)delete Y.postinstall,Y.noPostinstall=!0;let G=await g$("buddy upgrade"),z=await x$(u$.UpgradeFramework,Y);if(z.isErr)await S0("While running buddy upgrade, there was an issue",{startTime:G,useSeconds:!0},z.error),F0.exit(T0.FatalError);await S0("Upgrade complete.",{startTime:G,useSeconds:!0}),F0.exit(T0.Success)}),Q.command("upgrade:all",$.all).option("--canary",$.canary,{default:!1}).option("-f, --force",$.force,{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).example("buddy upgrade:all").action(async(J)=>{R$.debug("Running `buddy upgrade:all` ...",J);let Y=await g$("buddy upgrade:all");J.all=!0;let G=await x$(u$.Upgrade,J);if(G.isErr)await S0("While running buddy upgrade:all, there was an issue",{startTime:Y,useSeconds:!0},G.error),F0.exit(T0.FatalError);await S0("All upgrades complete.",{startTime:Y,useSeconds:!0}),F0.exit(T0.Success)}),Q.command("upgrade:dependencies",$.dependencies).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).alias("upgrade:deps").example("buddy upgrade:dependencies").action(async(J)=>{R$.debug("Running `buddy upgrade:dependencies` ...",J);let Y=await g$("buddy upgrade:dependencies");J.dependencies=!0;let G=await x$(u$.Upgrade,J);if(G.isErr)await S0("While running buddy upgrade:dependencies, there was an issue",{startTime:Y,useSeconds:!0},G.error),F0.exit(T0.FatalError);await S0("Dependencies upgraded.",{startTime:Y,useSeconds:!0}),F0.exit(T0.Success)}),Q.command("upgrade:bun",$.bun).option("--verbose",$.verbose,{default:!1}).example("buddy upgrade:bun").action(async(J)=>{R$.debug("Running `buddy upgrade:bun` ...",J);let Y=await g$("buddy upgrade:bun"),G=await x$(u$.UpgradeBun,J);if(G.isErr)await S0("While running buddy upgrade:bun, there was an issue",{startTime:Y,useSeconds:!0},G.error),F0.exit(T0.FatalError);await S0("Bun upgraded.",{startTime:Y,useSeconds:!0}),F0.exit(T0.Success)}),Q.command("upgrade:shell",$.shell).option("--verbose",$.verbose,{default:!1}).example("buddy upgrade:shell").action(async(J)=>{R$.debug("Running `buddy upgrade:shell` ...",J);let Y=await g$("buddy upgrade:shell"),G=await x$(u$.UpgradeShell,J);if(G.isErr)await S0("While running buddy upgrade:shell, there was an issue",{startTime:Y,useSeconds:!0},G.error),F0.exit(T0.FatalError);await S0("Shell integration upgraded.",{startTime:Y,useSeconds:!0}),F0.exit(T0.Success)}),Q.command("upgrade:binary",$.binary).option("--verbose",$.verbose,{default:!1}).example("buddy upgrade:binary").action(async(J)=>{if(F0.getuid&&F0.getuid()!==0)R$.warn("To upgrade the binary, you need to run this command with sudo, or as root."),F0.exit(T0.FatalError);R$.debug("Running `buddy upgrade:binary` ...",J);let Y=await g$("buddy upgrade:binary"),G=await x$(u$.UpgradeBinary,J);if(G.isErr)await S0("While running buddy upgrade:binary, there was an issue",{startTime:Y,useSeconds:!0},G.error),F0.exit(T0.FatalError);await S0("Binary upgraded.",{startTime:Y,useSeconds:!0}),F0.exit(T0.Success)}),GG(Q,"upgrade")}import{bold as t9,dim as e9,green as $8,intro as zG,log as R3,onUnknownSubcommand as WG}from"@stacksjs/cli";import{storage as XG}from"@stacksjs/storage";function uZ(Q){let $={version:"Retrieving Stacks build version"};Q.command("version",$.version).action(async()=>{R3.debug("Running `buddy version` ..."),await zG("buddy version");let J=await XG.readPackageJson("./package.json"),Y="wip",G=J.version;R3.info($8(t9("@stacksjs/ "))+e9(` ${G}`)),R3.info($8(t9("Bun: "))+e9(` ${Y}`))}),WG(Q,"version")}export{uZ as version,yZ as upgrade,SZ as types,jZ as tinker,RZ as test,KZ as telemetryCommand,M6 as startDevelopmentServer,XZ as sms,R5 as setup,GZ as seed,iH as search,cH as schedule,bH as saas,J5 as runConfigMigrations,vH as route,MH as release,LH as queue,XH as publish,oq as projects,pq as prepublish,gq as ports,Sq as phone,Pq as outdated,y3 as optimizePantryDeps,wq as migrate,_q as make,zq as mailCommands,a4 as list,d4 as lint,x4 as key,N4 as install,A4 as http,B4 as generate,_4 as fresh,z4 as env,T$ as ensurePantryInstalled,I$ as ensurePantryDependencies,u7 as ensureEnvIsSet,g7 as ensureAppKey,eW as email,rW as domains,kW as doctor,CW as dns,AW as dev,FW as deploy,uz as create,Bz as configure,_z as configMigrate,Wz as completion,Jz as commit,oG as cloud,gG as clean,CG as changelog,AG as build,RG as auth,_G as about};
450
+ To add a phone:`),console.log(" buddy sms:add-phone +1234567890");else for(let G of Y){let z=G.status==="VERIFIED"?"\u2705":"\u23F3";console.log(` ${z} ${G.phoneNumber} (${G.status})`),console.log(` ID: ${G.id}`)}}catch($){console.error("Error listing sandbox phones:",$.message)}process.exit(0)})}import s9 from"process";import{bold as L3,dim as X0,green as aY,intro as iY,log as k,onUnknownSubcommand as sY}from"@stacksjs/cli";var F3={async enable(){},async disable(){},async status(){return{enabled:!1,doNotTrack:!!s9.env.DO_NOT_TRACK,eventsQueued:0,lastSent:null}}};function KZ(Q){Q.command("telemetry","Manage telemetry settings").option("--enable","Enable telemetry").option("--disable","Disable telemetry").option("--status","Show telemetry status").example("buddy telemetry --status").example("buddy telemetry --enable").example("buddy telemetry --disable").action(async($)=>{k.debug("Running `buddy telemetry` ...",$),await iY("buddy telemetry");try{if($.enable){await F3.enable(),k.success("Telemetry enabled"),k.info(""),k.info(X0("Anonymous usage statistics will be collected")),k.info(X0("to help improve Buddy CLI.")),k.info(""),k.info(X0("You can disable telemetry anytime with:")),k.info(X0(" buddy telemetry --disable")),k.info("");return}if($.disable){await F3.disable(),k.success("Telemetry disabled"),k.info(""),k.info(X0("No usage statistics will be collected.")),k.info("");return}let J=await F3.status();if(k.info(""),k.info(aY(L3("Telemetry Status"))),k.info(X0("\u2500".repeat(50))),k.info(""),k.info(L3("Configuration:")),k.info(` Enabled: ${X0(J.enabled?"Yes":"No")}`),k.info(` DO_NOT_TRACK: ${X0(J.doNotTrack?"Yes (respected)":"No")}`),k.info(` Events queued: ${X0(J.eventsQueued)}`),J.lastSent){let Y=new Date(J.lastSent);k.info(` Last sent: ${X0(Y.toLocaleString())}`)}else k.info(` Last sent: ${X0("Never")}`);if(k.info(""),k.info(L3("Privacy:")),k.info(` ${X0("\u2022 Opt-in only (disabled by default)")}`),k.info(` ${X0("\u2022 No personal information collected")}`),k.info(` ${X0("\u2022 Anonymous user IDs only")}`),k.info(` ${X0("\u2022 Respects DO_NOT_TRACK environment variable")}`),k.info(""),!J.enabled)k.info(X0("To enable telemetry: buddy telemetry --enable")),k.info("");else k.info(X0("To disable telemetry: buddy telemetry --disable")),k.info("")}catch(J){k.error("Failed to manage telemetry:",J),s9.exit(1)}}),sY(Q,"telemetry")}import p0 from"process";import{runAction as X$}from"@stacksjs/actions";import{intro as P7,log as o9,onUnknownSubcommand as oY,outro as M0}from"@stacksjs/cli";import{Action as q$}from"@stacksjs/enums";import{projectPath as H$}from"@stacksjs/path";import{ExitCode as r0}from"@stacksjs/types";function RZ(Q){let $={command:"Runs your test suite",types:"Typechecks your codebase",coverage:"Generates a test coverage report",ui:"Runs your test suite in the browser",unit:"Runs your unit tests",feature:"Runs your feature tests",showReport:"Show the test report",project:"Target a specific project",verbose:"Enable verbose output"};Q.command("test",$.command).option("-f, --feature",$.feature,{default:!1}).option("-u, --unit",$.unit,{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!0}).action(async(J)=>{let Y=await P7("buddy test");if(J.feature&&J.unit){let G=await X$(q$.Test,{...J,cwd:H$()});if(G.isErr)await M0("While running `buddy test`, there was an issue",{startTime:Y,useSeconds:!0},G.error),p0.exit(r0.FatalError)}if(J.feature&&!J.unit){o9.info("Running Feature tests...");let G=await X$(q$.TestFeature,{...J,cwd:H$()});if(G.isErr)await M0("While running `buddy test`, there was an issue",{startTime:Y,useSeconds:!0},G.error),p0.exit(r0.FatalError)}if(!J.feature&&J.unit){o9.info("Running Unit tests...");let G=await X$(q$.TestUnit,{...J,cwd:H$()});if(G.isErr)await M0("While running `buddy test`, there was an issue",{startTime:Y,useSeconds:!0},G.error),p0.exit(r0.FatalError)}if(!J.feature&&!J.unit){let G=await X$(q$.Test,{...J,cwd:H$()});if(G.isErr)await M0("While running `buddy test`, there was an issue",{startTime:Y,useSeconds:!0},G.error),p0.exit(r0.FatalError)}await M0("Finished running tests",{startTime:Y,useSeconds:!0}),p0.exit(r0.Success)}),Q.command("test:unit",$.unit).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{let Y=await P7("buddy test:unit"),G=await X$(q$.TestUnit,{...J,verbose:!0,cwd:H$()});if(G.isErr)await M0("While running `buddy test:unit`, there was an issue",{startTime:Y,useSeconds:!0},G.error),p0.exit(r0.FatalError);await M0("Finished running unit tests",{startTime:Y,useSeconds:!0})}),Q.command("test:feature",$.feature).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{let Y=await P7("buddy test:feature"),G=await X$(q$.TestFeature,{...J,verbose:!0,cwd:H$()});if(G.isErr)await M0("While running `buddy test:feature`, there was an issue",{startTime:Y,useSeconds:!0},G.error),p0.exit(r0.FatalError);await M0("Finished running feature tests",{startTime:Y,useSeconds:!0})}),Q.command("test:ui",$.command).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{let Y=await P7("buddy test:ui"),G=await X$(q$.TestUi,{...J,verbose:!0,cwd:H$()});if(G.isErr)await M0("While running `buddy test:ui`, there was an issue",{startTime:Y,useSeconds:!0},G.error),p0.exit(r0.FatalError);await M0("Finished running tests in the browser",{startTime:Y,useSeconds:!0})}),Q.command("test:types",$.types).alias("typecheck").option("--verbose",$.verbose,{default:!1}).action(async(J)=>{let Y=await P7("buddy test:types"),G=await X$(q$.Typecheck,{...J,verbose:!0,cwd:H$()});if(G.isErr)await M0("While running `buddy test:types`, there was an issue",{startTime:Y,useSeconds:!0},G.error),p0.exit(r0.FatalError);await M0("Finished running typecheck",{startTime:Y,useSeconds:!0})}),oY(Q,"test")}import O3 from"process";import{intro as tY,log as eY,onUnknownSubcommand as $G,outro as V3}from"@stacksjs/cli";import{ExitCode as B3}from"@stacksjs/types";function jZ(Q){let $={tinker:"Interactive REPL with Stacks framework preloaded",eval:"Evaluate a single expression and exit",print:"Evaluate, print, and exit",noBanner:"Skip the welcome banner",preload:"Additional modules to preload (comma-separated)",project:"Target a specific project",verbose:"Enable verbose output"};Q.command("tinker",$.tinker).option("-e, --eval [expression]",$.eval,{default:""}).option("--print [expression]",$.print,{default:""}).option("--no-banner",$.noBanner,{default:!1}).option("--preload [modules]",$.preload,{default:""}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{eY.debug("Running `buddy tinker` ...",J);let Y=await tY("buddy tinker");try{let{startTinker:G}=await import("@stacksjs/tinker"),z=typeof J.preload==="string"&&J.preload?J.preload.split(",").map((X)=>X.trim()):void 0;if((await G({eval:typeof J.eval==="string"&&J.eval?J.eval:void 0,print:typeof J.print==="string"&&J.print?J.print:void 0,banner:J.noBanner!==!0,preload:z,verbose:J.verbose===!0})).exitCode!==0)await V3("Tinker session ended with errors",{startTime:Y,useSeconds:!0}),O3.exit(B3.FatalError);await V3("Tinker session ended.",{startTime:Y,useSeconds:!0}),O3.exit(B3.Success)}catch(G){await V3("While running the tinker command, there was an issue",{startTime:Y,useSeconds:!0},G instanceof Error?G:void 0),O3.exit(B3.FatalError)}}),$G(Q,"tinker")}import{generateTypes as QG}from"@stacksjs/actions";import{log as JG}from"@stacksjs/logging";import{onUnknownSubcommand as YG}from"@stacksjs/cli";function SZ(Q){let $={generate:"Generate the types of & for your library/libraries",fix:"wip",project:"Target a specific project",verbose:"Enable verbose output"};Q.command("types:generate",$.generate).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{JG.debug("Running `buddy types:generate` ...",J),await QG(J)}),Q.command("types:fix",$.fix).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async()=>{}),YG(Q,"types")}import F0 from"process";import{runAction as x$}from"@stacksjs/actions";import{intro as g$,log as R$,onUnknownSubcommand as GG,outro as S0}from"@stacksjs/cli";import{Action as u$}from"@stacksjs/enums";import{ExitCode as T0}from"@stacksjs/types";function yZ(Q){let $={upgrade:"Upgrade the Stacks framework to the latest version",version:"Install a specific version (e.g., 0.70.23)",canary:"Upgrade to the latest canary (development) build",stable:"Switch back to the latest stable release",force:"Force re-download, bypassing cache and version checks",from:"Sync from a local stacks checkout (e.g. ~/Code/stacks). Skips GitHub.",noPostinstall:"Skip post-sync hooks (auto-imports, bun install, migrate)",verbose:"Enable verbose output",dependencies:"Upgrade your dependencies (pantry.yaml & package.json)",bun:"Upgrade Bun to the latest version",shell:"Upgrade the shell integration (currently only supports Oh My Zsh)",binary:"Upgrade the `stacks` binary to the latest version",project:"Target a specific project",all:"Upgrade framework, dependencies, Bun, and binary"};Q.command("upgrade",$.upgrade).option("-v, --version <version>",$.version).option("--canary",$.canary,{default:!1}).option("--stable",$.stable,{default:!1}).option("-f, --force",$.force,{default:!1}).option("--from <path>",$.from).option("--no-postinstall",$.noPostinstall).option("--verbose",$.verbose,{default:!1}).alias("update").example("buddy upgrade").example("buddy upgrade --from ~/Code/stacks").example("buddy upgrade --version 0.70.23").example("buddy upgrade --canary").example("buddy upgrade --stable").example("buddy upgrade --force").action(async(J)=>{R$.debug("Running `buddy upgrade` ...",J);let Y={...J};if(Y.postinstall===!1)delete Y.postinstall,Y.noPostinstall=!0;let G=await g$("buddy upgrade"),z=await x$(u$.UpgradeFramework,Y);if(z.isErr)await S0("While running buddy upgrade, there was an issue",{startTime:G,useSeconds:!0},z.error),F0.exit(T0.FatalError);await S0("Upgrade complete.",{startTime:G,useSeconds:!0}),F0.exit(T0.Success)}),Q.command("upgrade:all",$.all).option("--canary",$.canary,{default:!1}).option("-f, --force",$.force,{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).example("buddy upgrade:all").action(async(J)=>{R$.debug("Running `buddy upgrade:all` ...",J);let Y=await g$("buddy upgrade:all");J.all=!0;let G=await x$(u$.Upgrade,J);if(G.isErr)await S0("While running buddy upgrade:all, there was an issue",{startTime:Y,useSeconds:!0},G.error),F0.exit(T0.FatalError);await S0("All upgrades complete.",{startTime:Y,useSeconds:!0}),F0.exit(T0.Success)}),Q.command("upgrade:dependencies",$.dependencies).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).alias("upgrade:deps").example("buddy upgrade:dependencies").action(async(J)=>{R$.debug("Running `buddy upgrade:dependencies` ...",J);let Y=await g$("buddy upgrade:dependencies");J.dependencies=!0;let G=await x$(u$.Upgrade,J);if(G.isErr)await S0("While running buddy upgrade:dependencies, there was an issue",{startTime:Y,useSeconds:!0},G.error),F0.exit(T0.FatalError);await S0("Dependencies upgraded.",{startTime:Y,useSeconds:!0}),F0.exit(T0.Success)}),Q.command("upgrade:bun",$.bun).option("--verbose",$.verbose,{default:!1}).example("buddy upgrade:bun").action(async(J)=>{R$.debug("Running `buddy upgrade:bun` ...",J);let Y=await g$("buddy upgrade:bun"),G=await x$(u$.UpgradeBun,J);if(G.isErr)await S0("While running buddy upgrade:bun, there was an issue",{startTime:Y,useSeconds:!0},G.error),F0.exit(T0.FatalError);await S0("Bun upgraded.",{startTime:Y,useSeconds:!0}),F0.exit(T0.Success)}),Q.command("upgrade:shell",$.shell).option("--verbose",$.verbose,{default:!1}).example("buddy upgrade:shell").action(async(J)=>{R$.debug("Running `buddy upgrade:shell` ...",J);let Y=await g$("buddy upgrade:shell"),G=await x$(u$.UpgradeShell,J);if(G.isErr)await S0("While running buddy upgrade:shell, there was an issue",{startTime:Y,useSeconds:!0},G.error),F0.exit(T0.FatalError);await S0("Shell integration upgraded.",{startTime:Y,useSeconds:!0}),F0.exit(T0.Success)}),Q.command("upgrade:binary",$.binary).option("--verbose",$.verbose,{default:!1}).example("buddy upgrade:binary").action(async(J)=>{if(F0.getuid&&F0.getuid()!==0)R$.warn("To upgrade the binary, you need to run this command with sudo, or as root."),F0.exit(T0.FatalError);R$.debug("Running `buddy upgrade:binary` ...",J);let Y=await g$("buddy upgrade:binary"),G=await x$(u$.UpgradeBinary,J);if(G.isErr)await S0("While running buddy upgrade:binary, there was an issue",{startTime:Y,useSeconds:!0},G.error),F0.exit(T0.FatalError);await S0("Binary upgraded.",{startTime:Y,useSeconds:!0}),F0.exit(T0.Success)}),GG(Q,"upgrade")}import{bold as t9,dim as e9,green as $5,intro as zG,log as R3,onUnknownSubcommand as WG}from"@stacksjs/cli";import{storage as XG}from"@stacksjs/storage";function uZ(Q){let $={version:"Retrieving Stacks build version"};Q.command("version",$.version).action(async()=>{R3.debug("Running `buddy version` ..."),await zG("buddy version");let J=await XG.readPackageJson("./package.json"),Y="wip",G=J.version;R3.info($5(t9("@stacksjs/ "))+e9(` ${G}`)),R3.info($5(t9("Bun: "))+e9(` ${Y}`))}),WG(Q,"version")}export{uZ as version,yZ as upgrade,SZ as types,jZ as tinker,RZ as test,KZ as telemetryCommand,M6 as startDevelopmentServer,XZ as sms,R8 as setup,GZ as seed,iH as search,cH as schedule,bH as saas,J8 as runConfigMigrations,vH as route,MH as release,LH as queue,XH as publish,oq as projects,pq as prepublish,gq as ports,Sq as phone,Pq as outdated,y3 as optimizePantryDeps,wq as migrate,_q as make,zq as mailCommands,a4 as list,d4 as lint,x4 as key,N4 as install,A4 as http,B4 as generate,_4 as fresh,z4 as env,T$ as ensurePantryInstalled,I$ as ensurePantryDependencies,u7 as ensureEnvIsSet,g7 as ensureAppKey,eW as email,rW as domains,kW as doctor,CW as dns,AW as dev,FW as deploy,uz as create,Bz as configure,_z as configMigrate,Wz as completion,Jz as commit,oG as cloud,gG as clean,CG as changelog,AG as build,RG as auth,_G as about};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@stacksjs/buddy",
3
3
  "type": "module",
4
- "version": "0.70.33",
4
+ "version": "0.70.35",
5
5
  "description": "Meet Buddy. The Stacks runtime.",
6
6
  "author": "Chris Breuer",
7
7
  "contributors": [