@stacksjs/buddy 0.70.23 → 0.70.28

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 (130) hide show
  1. package/README.md +15 -23
  2. package/dist/cli.js +3 -1
  3. package/dist/index.js +449 -1
  4. package/dist/src/cli.d.ts +1 -0
  5. package/dist/src/commands/about.d.ts +2 -0
  6. package/dist/src/commands/auth.d.ts +2 -0
  7. package/dist/src/commands/build.d.ts +2 -0
  8. package/dist/src/commands/changelog.d.ts +2 -0
  9. package/dist/src/commands/clean.d.ts +2 -0
  10. package/dist/src/commands/cloud.d.ts +2 -0
  11. package/dist/src/commands/commit.d.ts +2 -0
  12. package/dist/src/commands/completion.d.ts +2 -0
  13. package/dist/src/commands/config-migrate.d.ts +26 -0
  14. package/dist/src/commands/configure.d.ts +2 -0
  15. package/dist/src/commands/create.d.ts +2 -0
  16. package/dist/src/commands/deploy.d.ts +2 -0
  17. package/dist/{dev.d.ts → src/commands/dev.d.ts} +1 -3
  18. package/dist/src/commands/dns.d.ts +2 -0
  19. package/dist/src/commands/doctor.d.ts +2 -0
  20. package/dist/src/commands/domains.d.ts +2 -0
  21. package/dist/src/commands/email.d.ts +2 -0
  22. package/dist/src/commands/env.d.ts +2 -0
  23. package/dist/src/commands/fresh.d.ts +2 -0
  24. package/dist/src/commands/generate.d.ts +2 -0
  25. package/dist/src/commands/http.d.ts +2 -0
  26. package/dist/src/commands/index.d.ts +49 -0
  27. package/dist/src/commands/install.d.ts +2 -0
  28. package/dist/src/commands/key.d.ts +2 -0
  29. package/dist/src/commands/lint.d.ts +2 -0
  30. package/dist/src/commands/list.d.ts +2 -0
  31. package/dist/src/commands/mail.d.ts +2 -0
  32. package/dist/src/commands/make.d.ts +2 -0
  33. package/dist/src/commands/migrate.d.ts +2 -0
  34. package/dist/src/commands/outdated.d.ts +2 -0
  35. package/dist/src/commands/phone.d.ts +2 -0
  36. package/dist/src/commands/ports.d.ts +2 -0
  37. package/dist/src/commands/prepublish.d.ts +2 -0
  38. package/dist/src/commands/projects.d.ts +2 -0
  39. package/dist/src/commands/publish.d.ts +2 -0
  40. package/dist/src/commands/queue.d.ts +2 -0
  41. package/dist/src/commands/release.d.ts +2 -0
  42. package/dist/src/commands/route.d.ts +2 -0
  43. package/dist/src/commands/saas.d.ts +2 -0
  44. package/dist/src/commands/schedule.d.ts +2 -0
  45. package/dist/src/commands/search.d.ts +2 -0
  46. package/dist/src/commands/seed.d.ts +2 -0
  47. package/dist/src/commands/setup.d.ts +12 -0
  48. package/dist/src/commands/sms.d.ts +2 -0
  49. package/dist/src/commands/telemetry.d.ts +2 -0
  50. package/dist/src/commands/test.d.ts +2 -0
  51. package/dist/src/commands/tinker.d.ts +2 -0
  52. package/dist/src/commands/types.d.ts +2 -0
  53. package/dist/src/commands/upgrade.d.ts +2 -0
  54. package/dist/src/commands/version.d.ts +2 -0
  55. package/dist/src/index.d.ts +1 -0
  56. package/package.json +64 -61
  57. package/dist/add.d.ts +0 -4
  58. package/dist/build.d.ts +0 -4
  59. package/dist/changelog.d.ts +0 -3
  60. package/dist/chunk-1nq7pv3c.js +0 -7
  61. package/dist/chunk-29k4nndh.js +0 -2
  62. package/dist/chunk-39dwerh8.js +0 -5
  63. package/dist/chunk-3zqgxrhy.js +0 -2
  64. package/dist/chunk-496r9jw6.js +0 -3
  65. package/dist/chunk-4k60zpwd.js +0 -2
  66. package/dist/chunk-51tnc6dm.js +0 -2
  67. package/dist/chunk-5nbczt72.js +0 -2
  68. package/dist/chunk-6fsr2f40.js +0 -10
  69. package/dist/chunk-6v69415e.js +0 -2
  70. package/dist/chunk-7pg49t20.js +0 -2
  71. package/dist/chunk-8d01gfhw.js +0 -2
  72. package/dist/chunk-8kjkww7q.js +0 -8
  73. package/dist/chunk-97pfgxpz.js +0 -15
  74. package/dist/chunk-a47wfx2k.js +0 -2
  75. package/dist/chunk-cqrmkpzz.js +0 -8
  76. package/dist/chunk-ftse0wqn.js +0 -5410
  77. package/dist/chunk-jffk6kjy.js +0 -2
  78. package/dist/chunk-kg8bv5wt.js +0 -55
  79. package/dist/chunk-knytfag6.js +0 -33
  80. package/dist/chunk-ksjzw2hp.js +0 -2
  81. package/dist/chunk-mk0bde63.js +0 -2
  82. package/dist/chunk-qm8eqyn5.js +0 -2
  83. package/dist/chunk-rdgds02z.js +0 -3
  84. package/dist/chunk-sk9vc7y5.js +0 -1
  85. package/dist/chunk-sq3kqg71.js +0 -35
  86. package/dist/chunk-t2wb516a.js +0 -3
  87. package/dist/chunk-t4y0mz3y.js +0 -10
  88. package/dist/chunk-vgn2n3rk.js +0 -2
  89. package/dist/chunk-wzns1fp3.js +0 -1
  90. package/dist/chunk-xc6fz0pt.js +0 -2
  91. package/dist/chunk-xfhw9xck.js +0 -240
  92. package/dist/chunk-yzwe58rn.js +0 -25
  93. package/dist/clean.d.ts +0 -3
  94. package/dist/cli.d.ts +0 -4
  95. package/dist/cloud.d.ts +0 -3
  96. package/dist/commit.d.ts +0 -3
  97. package/dist/configure.d.ts +0 -4
  98. package/dist/create.d.ts +0 -8
  99. package/dist/custom-cli.d.ts +0 -1
  100. package/dist/deploy.d.ts +0 -7
  101. package/dist/dns.d.ts +0 -18
  102. package/dist/domains.d.ts +0 -3
  103. package/dist/env.d.ts +0 -20
  104. package/dist/fresh.d.ts +0 -3
  105. package/dist/generate.d.ts +0 -3
  106. package/dist/http.d.ts +0 -6
  107. package/dist/index.d.ts +0 -1
  108. package/dist/install.d.ts +0 -3
  109. package/dist/key.d.ts +0 -3
  110. package/dist/lint.d.ts +0 -3
  111. package/dist/list.d.ts +0 -3
  112. package/dist/make.d.ts +0 -1
  113. package/dist/migrate.d.ts +0 -3
  114. package/dist/outdated.d.ts +0 -3
  115. package/dist/ports.d.ts +0 -6
  116. package/dist/prepublish.d.ts +0 -3
  117. package/dist/projects.d.ts +0 -3
  118. package/dist/queue.d.ts +0 -3
  119. package/dist/release.d.ts +0 -9
  120. package/dist/route.d.ts +0 -3
  121. package/dist/saas.d.ts +0 -3
  122. package/dist/schedule.d.ts +0 -3
  123. package/dist/search.d.ts +0 -3
  124. package/dist/seed.d.ts +0 -3
  125. package/dist/setup.d.ts +0 -8
  126. package/dist/test.d.ts +0 -3
  127. package/dist/tinker.d.ts +0 -3
  128. package/dist/types.d.ts +0 -3
  129. package/dist/upgrade.d.ts +0 -4
  130. package/dist/version.d.ts +0 -3
package/dist/index.js CHANGED
@@ -1,2 +1,450 @@
1
1
  // @bun
2
- import{$ as i,Aa as P,Ba as Q,P as e,Q as f,R as m,S as p,T as t,U as x,V as a,W as b,X as c,Y as d,Z as g,_ as h,aa as j,ba as k,ca as l,da as n,ea as q,fa as s,ga as u,ha as v,ia as w,ja as y,ka as z,la as A,ma as B,na as C,oa as D,pa as E,qa as F,ra as G,sa as H,ta as I,ua as J,va as K,wa as L,xa as M,ya as N,za as O}from"./chunk-ftse0wqn.js";import"./chunk-xfhw9xck.js";import"./chunk-29k4nndh.js";import"./chunk-t4y0mz3y.js";import"./chunk-knytfag6.js";import"./chunk-cqrmkpzz.js";import"./chunk-97pfgxpz.js";import"./chunk-6v69415e.js";import"./chunk-wzns1fp3.js";import"./chunk-5nbczt72.js";import"./chunk-39dwerh8.js";import"./chunk-yzwe58rn.js";import"./chunk-6fsr2f40.js";import"./chunk-sk9vc7y5.js";import"./chunk-xc6fz0pt.js";import"./chunk-4k60zpwd.js";import"./chunk-8kjkww7q.js";import"./chunk-3zqgxrhy.js";import"./chunk-ksjzw2hp.js";export{Q as version,P as upgrade,O as types,N as tinker,M as test,d as startDevelopmentServer,J as setup,I as seed,H as search,G as schedule,F as saas,E as route,D as release,C as queue,B as projects,A as prepublish,z as ports,y as outdated,K as optimizePkgxDeps,w as migrate,v as make,u as list,s as lint,q as key,n as install,l as http,k as generate,j as fresh,i as env,L as ensureEnvIsSet,h as domains,g as dns,c as dev,b as deploy,a as create,x as configure,t as commit,p as cloud,m as clean,f as changelog,e as build};
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
3
+ echo "Hello World from App Server 2!" > /tmp/test.txt
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"?>
6
+ <DistributionConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
7
+ <CallerReference>${V.CallerReference}</CallerReference>
8
+ <Aliases>
9
+ <Quantity>${Y.length}</Quantity>
10
+ <Items>
11
+ ${Y.map((B)=>` <CNAME>${B}</CNAME>`).join(`
12
+ `)}
13
+ </Items>
14
+ </Aliases>
15
+ <DefaultRootObject>${V.DefaultRootObject||"index.html"}</DefaultRootObject>
16
+ <Origins>
17
+ <Quantity>${V.Origins?.Quantity||0}</Quantity>
18
+ <Items>
19
+ ${(V.Origins?.Items||[]).map((B)=>` <Origin>
20
+ <Id>${B.Id}</Id>
21
+ <DomainName>${B.DomainName}</DomainName>
22
+ ${B.OriginPath?`<OriginPath>${B.OriginPath}</OriginPath>`:"<OriginPath></OriginPath>"}
23
+ ${B.S3OriginConfig?`<S3OriginConfig><OriginAccessIdentity>${B.S3OriginConfig.OriginAccessIdentity||""}</OriginAccessIdentity></S3OriginConfig>`:""}
24
+ ${B.CustomOriginConfig?`<CustomOriginConfig>
25
+ <HTTPPort>${B.CustomOriginConfig.HTTPPort}</HTTPPort>
26
+ <HTTPSPort>${B.CustomOriginConfig.HTTPSPort}</HTTPSPort>
27
+ <OriginProtocolPolicy>${B.CustomOriginConfig.OriginProtocolPolicy}</OriginProtocolPolicy>
28
+ <OriginSslProtocols><Quantity>${B.CustomOriginConfig.OriginSslProtocols?.Quantity||1}</Quantity><Items>${(B.CustomOriginConfig.OriginSslProtocols?.Items||["TLSv1.2"]).map((v)=>`<SslProtocol>${v}</SslProtocol>`).join("")}</Items></OriginSslProtocols>
29
+ </CustomOriginConfig>`:""}
30
+ ${B.OriginAccessControlId?`<OriginAccessControlId>${B.OriginAccessControlId}</OriginAccessControlId>`:""}
31
+ <ConnectionAttempts>${B.ConnectionAttempts||3}</ConnectionAttempts>
32
+ <ConnectionTimeout>${B.ConnectionTimeout||10}</ConnectionTimeout>
33
+ </Origin>`).join(`
34
+ `)}
35
+ </Items>
36
+ </Origins>
37
+ <DefaultCacheBehavior>
38
+ <TargetOriginId>${V.DefaultCacheBehavior?.TargetOriginId}</TargetOriginId>
39
+ <ViewerProtocolPolicy>${V.DefaultCacheBehavior?.ViewerProtocolPolicy||"redirect-to-https"}</ViewerProtocolPolicy>
40
+ <AllowedMethods>
41
+ <Quantity>${V.DefaultCacheBehavior?.AllowedMethods?.Quantity||3}</Quantity>
42
+ <Items>${(V.DefaultCacheBehavior?.AllowedMethods?.Items||["GET","HEAD","OPTIONS"]).map((B)=>`<Method>${B}</Method>`).join("")}</Items>
43
+ <CachedMethods>
44
+ <Quantity>${V.DefaultCacheBehavior?.AllowedMethods?.CachedMethods?.Quantity||2}</Quantity>
45
+ <Items>${(V.DefaultCacheBehavior?.AllowedMethods?.CachedMethods?.Items||["GET","HEAD"]).map((B)=>`<Method>${B}</Method>`).join("")}</Items>
46
+ </CachedMethods>
47
+ </AllowedMethods>
48
+ <Compress>${V.DefaultCacheBehavior?.Compress!==!1}</Compress>
49
+ <CachePolicyId>${V.DefaultCacheBehavior?.CachePolicyId||"658327ea-f89d-4fab-a63d-7e88639e58f6"}</CachePolicyId>
50
+ ${V.DefaultCacheBehavior?.OriginRequestPolicyId?`<OriginRequestPolicyId>${V.DefaultCacheBehavior.OriginRequestPolicyId}</OriginRequestPolicyId>`:""}
51
+ </DefaultCacheBehavior>
52
+ <CacheBehaviors>
53
+ <Quantity>${V.CacheBehaviors?.Quantity||0}</Quantity>
54
+ ${V.CacheBehaviors?.Quantity>0?`<Items>
55
+ ${(V.CacheBehaviors?.Items||[]).map((B)=>` <CacheBehavior>
56
+ <PathPattern>${B.PathPattern}</PathPattern>
57
+ <TargetOriginId>${B.TargetOriginId}</TargetOriginId>
58
+ <ViewerProtocolPolicy>${B.ViewerProtocolPolicy}</ViewerProtocolPolicy>
59
+ <AllowedMethods>
60
+ <Quantity>${B.AllowedMethods?.Quantity||3}</Quantity>
61
+ <Items>${(B.AllowedMethods?.Items||["GET","HEAD","OPTIONS"]).map((v)=>`<Method>${v}</Method>`).join("")}</Items>
62
+ <CachedMethods>
63
+ <Quantity>${B.AllowedMethods?.CachedMethods?.Quantity||2}</Quantity>
64
+ <Items>${(B.AllowedMethods?.CachedMethods?.Items||["GET","HEAD"]).map((v)=>`<Method>${v}</Method>`).join("")}</Items>
65
+ </CachedMethods>
66
+ </AllowedMethods>
67
+ <Compress>${B.Compress!==!1}</Compress>
68
+ <CachePolicyId>${B.CachePolicyId}</CachePolicyId>
69
+ ${B.OriginRequestPolicyId?`<OriginRequestPolicyId>${B.OriginRequestPolicyId}</OriginRequestPolicyId>`:""}
70
+ </CacheBehavior>`).join(`
71
+ `)}
72
+ </Items>`:""}
73
+ </CacheBehaviors>
74
+ <CustomErrorResponses>
75
+ <Quantity>${V.CustomErrorResponses?.Quantity||0}</Quantity>
76
+ ${V.CustomErrorResponses?.Quantity>0?`<Items>
77
+ ${(V.CustomErrorResponses?.Items||[]).map((B)=>` <CustomErrorResponse>
78
+ <ErrorCode>${B.ErrorCode}</ErrorCode>
79
+ <ResponsePagePath>${B.ResponsePagePath}</ResponsePagePath>
80
+ <ResponseCode>${B.ResponseCode}</ResponseCode>
81
+ <ErrorCachingMinTTL>${B.ErrorCachingMinTTL}</ErrorCachingMinTTL>
82
+ </CustomErrorResponse>`).join(`
83
+ `)}
84
+ </Items>`:""}
85
+ </CustomErrorResponses>
86
+ <Comment>${V.Comment||""}</Comment>
87
+ <PriceClass>${V.PriceClass||"PriceClass_100"}</PriceClass>
88
+ <Enabled>${V.Enabled!==!1}</Enabled>
89
+ <ViewerCertificate>
90
+ <ACMCertificateArn>${U.CertificateArn}</ACMCertificateArn>
91
+ <SSLSupportMethod>sni-only</SSLSupportMethod>
92
+ <MinimumProtocolVersion>TLSv1.2_2021</MinimumProtocolVersion>
93
+ </ViewerCertificate>
94
+ <HttpVersion>${V.HttpVersion||"http2and3"}</HttpVersion>
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(`
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]!==`
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
+ `||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
+ `);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()}
102
+ `).join(""),T=O.map((B)=>B.toLowerCase()).join(";"),f=[G,L,F,M,T,U].join(`
103
+ `),P="AWS4-HMAC-SHA256",I=J;if(J==="email")I="ses";if(J==="pinpoint")I="mobiletargeting";let j=`${Z}/${Y}/${I}/aws4_request`,A=[P,q,j,this.sha256(f)].join(`
104
+ `),h=this.getSignatureKey($.secretAccessKey,Z,Y,I),V=this.hmac(h,A),N=`${P} Credential=${$.accessKeyId}/${j}, SignedHeaders=${T}, Signature=${V}`;return{..._,Authorization:N}}getAmzDate(Q){return Q.toISOString().replace(/[:-]|\.\d{3}/g,"")}getDateStamp(Q){return Q.toISOString().slice(0,10).replace(/-/g,"")}sha256(Q){return Y$.createHash("sha256").update(Q,"utf8").digest("hex")}hmac(Q,$){return Y$.createHmac("sha256",Q).update($,"utf8").digest("hex")}getSignatureKey(Q,$,J,Y){let G=Y$.createHmac("sha256",`AWS4${Q}`).update($).digest(),z=Y$.createHmac("sha256",G).update(J).digest(),W=Y$.createHmac("sha256",z).update(Y).digest();return Y$.createHmac("sha256",W).update("aws4_request").digest()}parseXmlResponse(Q){try{let $=this.xmlParser.parse(Q);if($.ErrorResponse)throw this.createErrorFromXml($.ErrorResponse.Error);let J=Object.keys($);if(J.length===1)return $[J[0]];return $}catch($){if($.code||$.statusCode)throw $;return{}}}parseError(Q,$,J){let Y=Error();if(Y.statusCode=$,Y.requestId=J.get("x-amzn-requestid")||J.get("x-amz-request-id")||void 0,Q.startsWith("<"))try{let G=this.xmlParser.parse(Q);if(G.ErrorResponse?.Error){let z=G.ErrorResponse.Error;return Y.code=z.Code,Y.message=`AWS Error [${z.Code}]: ${z.Message||"Unknown error"}`,Y.type=z.Type,Y}if(G.Error)return Y.code=G.Error.Code,Y.message=`AWS Error [${G.Error.Code}]: ${G.Error.Message||"Unknown error"}`,Y}catch{}try{let G=JSON.parse(Q);if(G.__type||G.code)return Y.code=G.__type||G.code,Y.message=`AWS Error [${Y.code}]: ${G.message||G.Message||"Unknown error"}`,Y}catch{}return Y.message=`AWS API Error (${$}): ${Q}`,Y}createErrorFromXml(Q){let $=Error();return $.code=Q.Code,$.message=`AWS Error [${Q.Code}]: ${Q.Message||"Unknown error"}`,$.type=Q.Type,$}isRetryableError(Q){return["RequestTimeout","RequestTimeoutException","PriorRequestNotComplete","ConnectionError","ThrottlingException","Throttling","TooManyRequestsException","ProvisionedThroughputExceededException","RequestLimitExceeded","BandwidthLimitExceeded","SlowDown","ServiceUnavailable","ServiceUnavailableException","InternalError","InternalFailure","InternalServerError","InternalServiceException","TransientError","TransientFailure","IDPCommunicationErrorException","NetworkError","ConnectionRefusedException","EC2ThrottledException","503 Slow Down","500 InternalError"].includes(Q)}isRetryableStatusCode(Q){return Q>=500||Q===429}shouldRetry(Q){if(Q.name==="FetchError"||Q.name==="TypeError"||Q.code==="ECONNRESET")return!0;if(Q.code&&this.isRetryableError(Q.code))return!0;if(Q.statusCode&&this.isRetryableStatusCode(Q.statusCode))return!0;if(Q.statusCode&&Q.statusCode>=400&&Q.statusCode<500&&Q.statusCode!==429)return!1;if(Q.statusCode)return!1;return!0}calculateRetryDelay(Q){let $=this.config.retryDelay??1000,J=30000,Y=Math.min($*2**Q,30000),G=Math.random()*0.3*Y;return Y+G}sleep(Q){return new Promise(($)=>setTimeout($,Q))}getFromCache(Q){let $=this.cache.get(Q);if(!$)return null;if(Date.now()>$.expires)return this.cache.delete(Q),null;return $.data}setInCache(Q,$,J){this.cache.set(Q,{data:$,expires:Date.now()+J})}clearCache(){this.cache.clear()}clearExpiredCache(){let Q=Date.now();for(let[$,J]of this.cache.entries())if(Q>J.expires)this.cache.delete($)}}var d2=p(()=>{e1()});class p2{client;region;constructor(Q="us-east-1"){this.region=Q,this.client=new F7}async createEmailIdentity(Q){return await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/identities",headers:{"Content-Type":"application/json"},body:JSON.stringify(Q)})}async getEmailIdentity(Q){let $=await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/identities/${encodeURIComponent(Q)}`,headers:{"Content-Type":"application/json"}});return{IdentityType:$.IdentityType,IdentityName:Q,SendingEnabled:$.VerifiedForSendingStatus,VerificationStatus:$.VerificationStatus,DkimAttributes:$.DkimAttributes,MailFromAttributes:$.MailFromAttributes}}async putEmailIdentityMailFromAttributes(Q,$){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(Q)}/mail-from`,headers:{"Content-Type":"application/json"},body:JSON.stringify($)})}async listEmailIdentities(Q){let $="/v2/email/identities",J=[];if(Q?.PageSize)J.push(`PageSize=${Q.PageSize}`);if(Q?.NextToken)J.push(`NextToken=${encodeURIComponent(Q.NextToken)}`);if(J.length>0)$+=`?${J.join("&")}`;let Y=await this.client.request({service:"email",region:this.region,method:"GET",path:$,headers:{"Content-Type":"application/json"}});return{EmailIdentities:Y.EmailIdentities,NextToken:Y.NextToken}}async deleteEmailIdentity(Q){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/identities/${encodeURIComponent(Q)}`,headers:{"Content-Type":"application/json"}})}async putEmailIdentityDkimAttributes(Q){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(Q.EmailIdentity)}/dkim`,headers:{"Content-Type":"application/json"},body:JSON.stringify({SigningEnabled:Q.SigningEnabled})})}async sendEmail(Q){return{MessageId:(await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/outbound-emails",headers:{"Content-Type":"application/json"},body:JSON.stringify(Q)})).MessageId}}async sendBulkEmail(Q){return{BulkEmailEntryResults:(await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/outbound-bulk-emails",headers:{"Content-Type":"application/json"},body:JSON.stringify(Q)})).BulkEmailEntryResults}}async createEmailTemplate(Q){await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/templates",headers:{"Content-Type":"application/json"},body:JSON.stringify(Q)})}async getEmailTemplate(Q){return await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/templates/${encodeURIComponent(Q)}`,headers:{"Content-Type":"application/json"}})}async deleteEmailTemplate(Q){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/templates/${encodeURIComponent(Q)}`,headers:{"Content-Type":"application/json"}})}async listEmailTemplates(Q){let $="/v2/email/templates",J=[];if(Q?.PageSize)J.push(`PageSize=${Q.PageSize}`);if(Q?.NextToken)J.push(`NextToken=${encodeURIComponent(Q.NextToken)}`);if(J.length>0)$+=`?${J.join("&")}`;return await this.client.request({service:"email",region:this.region,method:"GET",path:$,headers:{"Content-Type":"application/json"}})}async getSendStatistics(){return{SendDataPoints:(await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendStatistics&Version=2010-12-01"})).GetSendStatisticsResponse?.GetSendStatisticsResult?.SendDataPoints?.member}}async getSendQuota(){let $=(await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendQuota&Version=2010-12-01"})).GetSendQuotaResponse?.GetSendQuotaResult;return{Max24HourSend:$?.Max24HourSend?Number($.Max24HourSend):void 0,MaxSendRate:$?.MaxSendRate?Number($.MaxSendRate):void 0,SentLast24Hours:$?.SentLast24Hours?Number($.SentLast24Hours):void 0}}async verifyDomain(Q){let $=await this.createEmailIdentity({EmailIdentity:Q});return{dkimTokens:$.DkimAttributes?.Tokens,verificationStatus:$.DkimAttributes?.Status}}async sendSimpleEmail(Q){let $=Array.isArray(Q.to)?Q.to:[Q.to],J=Q.replyTo?Array.isArray(Q.replyTo)?Q.replyTo:[Q.replyTo]:void 0,Y={};if(Q.text)Y.Text={Data:Q.text};if(Q.html)Y.Html={Data:Q.html};return this.sendEmail({FromEmailAddress:Q.from,Destination:{ToAddresses:$},Content:{Simple:{Subject:{Data:Q.subject},Body:Y}},ReplyToAddresses:J})}async sendTemplatedEmail(Q){let $=Array.isArray(Q.to)?Q.to:[Q.to],J=Q.replyTo?Array.isArray(Q.replyTo)?Q.replyTo:[Q.replyTo]:void 0;return this.sendEmail({FromEmailAddress:Q.from,Destination:{ToAddresses:$},Content:{Template:{TemplateName:Q.templateName,TemplateData:JSON.stringify(Q.templateData)}},ReplyToAddresses:J})}async getDkimRecords(Q){let $=await this.getEmailIdentity(Q);if(!$.DkimAttributes?.Tokens)return[];return $.DkimAttributes.Tokens.map((J)=>({name:`${J}._domainkey.${Q}`,type:"CNAME",value:`${J}.dkim.amazonses.com`}))}async isDomainVerified(Q){try{let $=await this.getEmailIdentity(Q);return $.VerificationStatus==="SUCCESS"&&$.SendingEnabled===!0}catch{return!1}}async waitForDomainVerification(Q,$=60,J=30000){for(let Y=0;Y<$;Y++){if(await this.isDomainVerified(Q))return!0;await new Promise((z)=>setTimeout(z,J))}return!1}buildFormBody(Q){return Object.entries(Q).filter(([,J])=>J!==void 0).map(([J,Y])=>`${encodeURIComponent(J)}=${encodeURIComponent(Y)}`).join("&")}async createReceiptRuleSet(Q){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"CreateReceiptRuleSet",Version:"2010-12-01",RuleSetName:Q})})}async deleteReceiptRuleSet(Q){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteReceiptRuleSet",Version:"2010-12-01",RuleSetName:Q})})}async setActiveReceiptRuleSet(Q){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"SetActiveReceiptRuleSet",Version:"2010-12-01",RuleSetName:Q})})}async listReceiptRuleSets(Q){let $={Action:"ListReceiptRuleSets",Version:"2010-12-01"};if(Q)$.NextToken=Q;let J=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody($)}),Y=J?.ListReceiptRuleSetsResponse?.ListReceiptRuleSetsResult||J?.ListReceiptRuleSetsResult,G=Y?.RuleSets?.member;return{RuleSets:Array.isArray(G)?G:G?[G]:[],NextToken:Y?.NextToken}}async describeReceiptRuleSet(Q){let $=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DescribeReceiptRuleSet",Version:"2010-12-01",RuleSetName:Q})}),J=$?.DescribeReceiptRuleSetResponse?.DescribeReceiptRuleSetResult||$?.DescribeReceiptRuleSetResult,Y=J?.Rules?.member;return{Metadata:J?.Metadata,Rules:Array.isArray(Y)?Y:Y?[Y]:[]}}async createReceiptRule(Q){let $={Action:"CreateReceiptRule",Version:"2010-12-01",RuleSetName:Q.RuleSetName,"Rule.Name":Q.Rule.Name,"Rule.Enabled":Q.Rule.Enabled!==!1?"true":"false"};if(Q.Rule.TlsPolicy)$["Rule.TlsPolicy"]=Q.Rule.TlsPolicy;if(Q.Rule.ScanEnabled!==void 0)$["Rule.ScanEnabled"]=Q.Rule.ScanEnabled?"true":"false";if(Q.After)$.After=Q.After;if(Q.Rule.Recipients)Q.Rule.Recipients.forEach((J,Y)=>{$[`Rule.Recipients.member.${Y+1}`]=J});Q.Rule.Actions.forEach((J,Y)=>{let G=Y+1;if(J.S3Action){if($[`Rule.Actions.member.${G}.S3Action.BucketName`]=J.S3Action.BucketName,J.S3Action.ObjectKeyPrefix)$[`Rule.Actions.member.${G}.S3Action.ObjectKeyPrefix`]=J.S3Action.ObjectKeyPrefix;if(J.S3Action.KmsKeyArn)$[`Rule.Actions.member.${G}.S3Action.KmsKeyArn`]=J.S3Action.KmsKeyArn}if(J.LambdaAction)$[`Rule.Actions.member.${G}.LambdaAction.FunctionArn`]=J.LambdaAction.FunctionArn,$[`Rule.Actions.member.${G}.LambdaAction.InvocationType`]=J.LambdaAction.InvocationType||"Event";if(J.SNSAction){if($[`Rule.Actions.member.${G}.SNSAction.TopicArn`]=J.SNSAction.TopicArn,J.SNSAction.Encoding)$[`Rule.Actions.member.${G}.SNSAction.Encoding`]=J.SNSAction.Encoding}if(J.StopAction){if($[`Rule.Actions.member.${G}.StopAction.Scope`]=J.StopAction.Scope,J.StopAction.TopicArn)$[`Rule.Actions.member.${G}.StopAction.TopicArn`]=J.StopAction.TopicArn}}),await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody($)})}async deleteReceiptRule(Q,$){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteReceiptRule",Version:"2010-12-01",RuleSetName:Q,RuleName:$})})}async receiptRuleSetExists(Q){try{return await this.describeReceiptRuleSet(Q),!0}catch($){if($.code==="RuleSetDoesNotExist"||$.statusCode===400)return!1;throw $}}async getActiveReceiptRuleSet(){let Q=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DescribeActiveReceiptRuleSet",Version:"2010-12-01"})}),$=Q?.DescribeActiveReceiptRuleSetResponse?.DescribeActiveReceiptRuleSetResult||Q?.DescribeActiveReceiptRuleSetResult;if(!$?.Metadata)return null;let J=$?.Rules?.member;return{Metadata:$?.Metadata,Rules:Array.isArray(J)?J:J?[J]:[]}}async updateReceiptRule(Q){let $={Action:"UpdateReceiptRule",Version:"2010-12-01",RuleSetName:Q.RuleSetName,"Rule.Name":Q.Rule.Name};if(Q.Rule.Enabled!==void 0)$["Rule.Enabled"]=Q.Rule.Enabled?"true":"false";if(Q.Rule.TlsPolicy)$["Rule.TlsPolicy"]=Q.Rule.TlsPolicy;if(Q.Rule.ScanEnabled!==void 0)$["Rule.ScanEnabled"]=Q.Rule.ScanEnabled?"true":"false";if(Q.Rule.Recipients)Q.Rule.Recipients.forEach((J,Y)=>{$[`Rule.Recipients.member.${Y+1}`]=J});Q.Rule.Actions.forEach((J,Y)=>{let G=Y+1;if(J.S3Action){if($[`Rule.Actions.member.${G}.S3Action.BucketName`]=J.S3Action.BucketName,J.S3Action.ObjectKeyPrefix)$[`Rule.Actions.member.${G}.S3Action.ObjectKeyPrefix`]=J.S3Action.ObjectKeyPrefix;if(J.S3Action.KmsKeyArn)$[`Rule.Actions.member.${G}.S3Action.KmsKeyArn`]=J.S3Action.KmsKeyArn}if(J.LambdaAction)$[`Rule.Actions.member.${G}.LambdaAction.FunctionArn`]=J.LambdaAction.FunctionArn,$[`Rule.Actions.member.${G}.LambdaAction.InvocationType`]=J.LambdaAction.InvocationType||"Event";if(J.SNSAction){if($[`Rule.Actions.member.${G}.SNSAction.TopicArn`]=J.SNSAction.TopicArn,J.SNSAction.Encoding)$[`Rule.Actions.member.${G}.SNSAction.Encoding`]=J.SNSAction.Encoding}if(J.StopAction){if($[`Rule.Actions.member.${G}.StopAction.Scope`]=J.StopAction.Scope,J.StopAction.TopicArn)$[`Rule.Actions.member.${G}.StopAction.TopicArn`]=J.StopAction.TopicArn}}),await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody($)})}async sendRawEmail(Q){let $=Buffer.from(Q.rawMessage).toString("base64"),J={Action:"SendRawEmail",Version:"2010-12-01",Source:Q.source,"RawMessage.Data":$};Q.destinations.forEach((z,W)=>{J[`Destinations.member.${W+1}`]=z});let Y=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)});return{MessageId:(Y?.SendRawEmailResponse?.SendRawEmailResult||Y?.SendRawEmailResult)?.MessageId}}}var $9=p(()=>{d2()});import*as D from"crypto";import{readdir as PJ}from"fs/promises";import{join as fJ}from"path";import{readFileSync as Q9}from"fs";class r2{client;region;constructor(Q="us-east-1",$){this.region=Q,this.client=new F7}getCredentials(){let Q=process.env.AWS_ACCESS_KEY_ID,$=process.env.AWS_SECRET_ACCESS_KEY,J=process.env.AWS_SESSION_TOKEN;if(!Q||!$)throw Error("AWS credentials not found. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables.");return{accessKeyId:Q,secretAccessKey:$,sessionToken:J}}async listBuckets(){let Q=await this.client.request({service:"s3",region:this.region,method:"GET",path:"/"}),$=[],J=Q?.ListAllMyBucketsResult?.Buckets?.Bucket;if(J){let Y=Array.isArray(J)?J:[J];for(let G of Y)$.push({Name:G.Name,CreationDate:G.CreationDate})}return{Buckets:$}}async createBucket(Q,$){let J={};if($?.acl)J["x-amz-acl"]=$.acl;let Y;if(this.region!=="us-east-1")Y=`<?xml version="1.0" encoding="UTF-8"?>
105
+ <CreateBucketConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
106
+ <LocationConstraint>${this.region}</LocationConstraint>
107
+ </CreateBucketConfiguration>`,J["Content-Type"]="application/xml";await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${Q}`,headers:J,body:Y})}async deleteBucket(Q){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${Q}`})}async emptyAndDeleteBucket(Q){let $=!0;while($){let J=await this.listAllObjects({bucket:Q});if(J.length===0){$=!1;break}let Y=J.map((G)=>G.Key);for(let G=0;G<Y.length;G+=1000){let z=Y.slice(G,G+1000);await this.deleteObjects(Q,z)}}await this.deleteBucket(Q)}async listAllObjects(Q){let $=[],J;do{let Y={"list-type":"2","max-keys":"1000"};if(Q.prefix)Y.prefix=Q.prefix;if(J)Y["continuation-token"]=J;let G=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${Q.bucket}`,queryParams:Y}),z=G?.ListBucketResult?.Contents;if(z){let X=Array.isArray(z)?z:[z];for(let H of X)$.push({Key:H.Key,LastModified:H.LastModified||"",Size:Number.parseInt(H.Size||"0",10),ETag:H.ETag})}let W=G?.ListBucketResult?.IsTruncated;J=W==="true"||W===!0?G?.ListBucketResult?.NextContinuationToken:void 0}while(J);return $}async list(Q){let $=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${Q.bucket}`}),J=[],Y=$?.ListBucketResult?.Contents;if(Y){let G=Array.isArray(Y)?Y:[Y];for(let z of G){if(Q.prefix&&!z.Key?.startsWith(Q.prefix))continue;if(J.push({Key:z.Key||"",LastModified:z.LastModified||"",Size:Number.parseInt(z.Size||"0",10),ETag:z.ETag}),Q.maxKeys&&J.length>=Q.maxKeys)break}}return J}async putObject(Q){let $={};if(Q.acl)$["x-amz-acl"]=Q.acl;if(Q.cacheControl)$["Cache-Control"]=Q.cacheControl;if(Q.contentType)$["Content-Type"]=Q.contentType;if(Q.metadata)for(let[Y,G]of Object.entries(Q.metadata))$[`x-amz-meta-${Y}`]=G;let J=typeof Q.body==="string"?Q.body:Buffer.isBuffer(Q.body)?Q.body.toString("base64"):String(Q.body);if(Buffer.isBuffer(Q.body)){let{accessKeyId:Y,secretAccessKey:G,sessionToken:z}=this.getCredentials(),W=`${Q.bucket}.s3.${this.region}.amazonaws.com`,X=`https://${W}/${Q.key}`,H=new Date,q=H.toISOString().replace(/[:-]|\.\d{3}/g,""),Z=H.toISOString().slice(0,10).replace(/-/g,""),K=D.createHash("sha256").update(Q.body).digest("hex"),_={host:W,"x-amz-date":q,"x-amz-content-sha256":K,...$};if(z)_["x-amz-security-token"]=z;let U=Object.keys(_).sort().map((N)=>`${N.toLowerCase()}:${_[N].trim()}
108
+ `).join(""),L=Object.keys(_).sort().map((N)=>N.toLowerCase()).join(";"),F=["PUT",`/${Q.key}`,"",U,L,K].join(`
109
+ `),O="AWS4-HMAC-SHA256",M=`${Z}/${this.region}/s3/aws4_request`,T=[O,q,M,D.createHash("sha256").update(F).digest("hex")].join(`
110
+ `),f=D.createHmac("sha256",`AWS4${G}`).update(Z).digest(),P=D.createHmac("sha256",f).update(this.region).digest(),I=D.createHmac("sha256",P).update("s3").digest(),j=D.createHmac("sha256",I).update("aws4_request").digest(),A=D.createHmac("sha256",j).update(T).digest("hex"),h=`${O} Credential=${Y}/${M}, SignedHeaders=${L}, Signature=${A}`,V=await fetch(X,{method:"PUT",headers:{..._,Authorization:h},body:typeof Q.body==="string"?Q.body:new Uint8Array(Q.body)});if(!V.ok){let N=await V.text();throw Error(`S3 PUT failed: ${V.status} ${N}`)}return}await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${Q.bucket}/${Q.key}`,headers:$,body:J})}async getObject(Q,$){return await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${Q}/${$}`,rawResponse:!0})}async copyObject(Q){let $={"x-amz-copy-source":`/${Q.sourceBucket}/${Q.sourceKey}`};if(Q.metadataDirective)$["x-amz-metadata-directive"]=Q.metadataDirective;if(Q.contentType)$["Content-Type"]=Q.contentType;if(Q.metadata)for(let[J,Y]of Object.entries(Q.metadata))$[`x-amz-meta-${J}`]=Y;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${Q.destinationBucket}/${Q.destinationKey}`,headers:$})}async deleteObject(Q,$){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${Q}/${$}`})}async deleteObjects(Q,$){let J=`<?xml version="1.0" encoding="UTF-8"?>
111
+ <Delete>
112
+ ${$.map((Y)=>`<Object><Key>${Y}</Key></Object>`).join(`
113
+ `)}
114
+ </Delete>`;await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${Q}`,queryParams:{delete:""},body:J,headers:{"Content-Type":"application/xml"}})}async bucketExists(Q){try{return await this.client.request({service:"s3",region:this.region,method:"HEAD",path:`/${Q}`}),!0}catch{return!1}}async copy(Q){let $=Q9(Q.source);await this.putObject({bucket:Q.bucket,key:Q.key,body:$,acl:Q.acl,cacheControl:Q.cacheControl,contentType:Q.contentType,metadata:Q.metadata})}async sync(Q){let $=await this.listFilesRecursive(Q.source);for(let J of $){if(Q.exclude&&Q.exclude.some((z)=>J.includes(z)))continue;if(Q.include&&!Q.include.some((z)=>J.includes(z)))continue;let Y=J.substring(Q.source.length+1),G=Q.prefix?`${Q.prefix}/${Y}`:Y;if(!Q.dryRun){let z=Q9(J);await this.putObject({bucket:Q.bucket,key:G,body:z,acl:Q.acl,cacheControl:Q.cacheControl,contentType:Q.contentType,metadata:Q.metadata})}}}async delete(Q,$){await this.deleteObject(Q,$)}async deletePrefix(Q,$){let Y=(await this.list({bucket:Q,prefix:$})).map((G)=>G.Key);if(Y.length>0)await this.deleteObjects(Q,Y)}async getBucketSize(Q,$){return(await this.list({bucket:Q,prefix:$})).reduce((Y,G)=>Y+G.Size,0)}async listFilesRecursive(Q){let $=[],J=await PJ(Q,{withFileTypes:!0});for(let Y of J){let G=fJ(Q,Y.name);if(Y.isDirectory()){let z=await this.listFilesRecursive(G);$.push(...z)}else $.push(G)}return $}async putBucketPolicy(Q,$){let{accessKeyId:J,secretAccessKey:Y,sessionToken:G}=this.getCredentials(),z=`s3.${this.region}.amazonaws.com`,W=typeof $==="string"?$:JSON.stringify($),X=new Date,H=X.toISOString().replace(/[:-]|\.\d{3}/g,""),q=X.toISOString().slice(0,10).replace(/-/g,""),Z=D.createHash("sha256").update(W).digest("hex"),K=`/${Q}`,_="policy=",U={host:z,"x-amz-date":H,"x-amz-content-sha256":Z,"content-type":"application/json"};if(G)U["x-amz-security-token"]=G;let L=Object.keys(U).sort().map((v)=>`${v.toLowerCase()}:${U[v].trim()}
115
+ `).join(""),F=Object.keys(U).sort().map((v)=>v.toLowerCase()).join(";"),O=["PUT",K,"policy=",L,F,Z].join(`
116
+ `),M="AWS4-HMAC-SHA256",T=`${q}/${this.region}/s3/aws4_request`,f=[M,H,T,D.createHash("sha256").update(O).digest("hex")].join(`
117
+ `),P=D.createHmac("sha256",`AWS4${Y}`).update(q).digest(),I=D.createHmac("sha256",P).update(this.region).digest(),j=D.createHmac("sha256",I).update("s3").digest(),A=D.createHmac("sha256",j).update("aws4_request").digest(),h=D.createHmac("sha256",A).update(f).digest("hex"),V=`${M} Credential=${J}/${T}, SignedHeaders=${F}, Signature=${h}`,N=`https://${z}${K}?policy=`,B=await fetch(N,{method:"PUT",headers:{...U,Authorization:V},body:W});if(!B.ok){let v=await B.text();throw Error(`Failed to put bucket policy: ${B.status} ${v}`)}}async getBucketPolicy(Q){let{accessKeyId:$,secretAccessKey:J,sessionToken:Y}=this.getCredentials(),G=`s3.${this.region}.amazonaws.com`,z=new Date,W=z.toISOString().replace(/[:-]|\.\d{3}/g,""),X=z.toISOString().slice(0,10).replace(/-/g,""),H=D.createHash("sha256").update("").digest("hex"),q=`/${Q}`,Z="policy=",K={host:G,"x-amz-date":W,"x-amz-content-sha256":H};if(Y)K["x-amz-security-token"]=Y;let _=Object.keys(K).sort().map((B)=>`${B.toLowerCase()}:${K[B].trim()}
118
+ `).join(""),U=Object.keys(K).sort().map((B)=>B.toLowerCase()).join(";"),L=["GET",q,"policy=",_,U,H].join(`
119
+ `),F="AWS4-HMAC-SHA256",O=`${X}/${this.region}/s3/aws4_request`,M=[F,W,O,D.createHash("sha256").update(L).digest("hex")].join(`
120
+ `),T=D.createHmac("sha256",`AWS4${J}`).update(X).digest(),f=D.createHmac("sha256",T).update(this.region).digest(),P=D.createHmac("sha256",f).update("s3").digest(),I=D.createHmac("sha256",P).update("aws4_request").digest(),j=D.createHmac("sha256",I).update(M).digest("hex"),A=`${F} Credential=${$}/${O}, SignedHeaders=${U}, Signature=${j}`,h=`https://${G}${q}?policy=`,V=await fetch(h,{method:"GET",headers:{...K,Authorization:A}});if(V.status===404)return null;if(!V.ok){let B=await V.text();throw Error(`Failed to get bucket policy: ${V.status} ${B}`)}let N=await V.text();try{return JSON.parse(N)}catch{throw Error(`Failed to parse bucket policy JSON: ${N.slice(0,200)}`)}}async deleteBucketPolicy(Q){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${Q}`,queryParams:{policy:""}})}async headBucket(Q){try{return{exists:!0,region:(await this.client.request({service:"s3",region:this.region,method:"HEAD",path:`/${Q}`,returnHeaders:!0}))?.headers?.["x-amz-bucket-region"]}}catch($){if($.statusCode===404)return{exists:!1};throw $}}async headObject(Q,$){try{let J=await this.client.request({service:"s3",region:this.region,method:"HEAD",path:`/${Q}/${$}`,returnHeaders:!0});return{ContentLength:J?.headers?.["content-length"]?parseInt(J.headers["content-length"]):void 0,ContentType:J?.headers?.["content-type"],ETag:J?.headers?.etag,LastModified:J?.headers?.["last-modified"]}}catch(J){if(J.statusCode===404)return null;throw J}}async getObjectBuffer(Q,$){let J=await this.getObject(Q,$);return Buffer.from(J)}async getObjectJson(Q,$){let J=await this.getObject(Q,$);try{return JSON.parse(J)}catch{throw Error(`Failed to parse JSON from s3://${Q}/${$}`)}}async putObjectJson(Q,$,J,Y){await this.putObject({bucket:Q,key:$,body:JSON.stringify(J),contentType:"application/json",...Y})}async getBucketVersioning(Q){return{Status:(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${Q}`,queryParams:{versioning:""}}))?.VersioningConfiguration?.Status}}async putBucketVersioning(Q,$){let J=`<?xml version="1.0" encoding="UTF-8"?>
121
+ <VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
122
+ <Status>${$}</Status>
123
+ </VersioningConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${Q}`,queryParams:{versioning:""},headers:{"Content-Type":"application/xml"},body:J})}async getBucketLifecycleConfiguration(Q){try{return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${Q}`,queryParams:{lifecycle:""}}))?.LifecycleConfiguration}catch($){if($.statusCode===404)return null;throw $}}async putBucketLifecycleConfiguration(Q,$){let Y=`<?xml version="1.0" encoding="UTF-8"?>
124
+ <LifecycleConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
125
+ ${$.map((G)=>{let z=`<Rule><ID>${G.ID}</ID><Status>${G.Status}</Status>`;if(G.Filter)z+=`<Filter><Prefix>${G.Filter.Prefix||""}</Prefix></Filter>`;else z+="<Filter><Prefix></Prefix></Filter>";if(G.Expiration){if(G.Expiration.Days)z+=`<Expiration><Days>${G.Expiration.Days}</Days></Expiration>`;else if(G.Expiration.Date)z+=`<Expiration><Date>${G.Expiration.Date}</Date></Expiration>`}if(G.Transitions)for(let W of G.Transitions)z+=`<Transition><Days>${W.Days}</Days><StorageClass>${W.StorageClass}</StorageClass></Transition>`;if(G.NoncurrentVersionExpiration)z+=`<NoncurrentVersionExpiration><NoncurrentDays>${G.NoncurrentVersionExpiration.NoncurrentDays}</NoncurrentDays></NoncurrentVersionExpiration>`;return z+="</Rule>",z}).join("")}
126
+ </LifecycleConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${Q}`,queryParams:{lifecycle:""},headers:{"Content-Type":"application/xml"},body:Y})}async deleteBucketLifecycleConfiguration(Q){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${Q}`,queryParams:{lifecycle:""}})}async getBucketCors(Q){try{return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${Q}`,queryParams:{cors:""}}))?.CORSConfiguration}catch($){if($.statusCode===404)return null;throw $}}async putBucketCors(Q,$){let Y=`<?xml version="1.0" encoding="UTF-8"?>
127
+ <CORSConfiguration>
128
+ ${$.map((G)=>{let z="<CORSRule>";for(let W of G.AllowedOrigins)z+=`<AllowedOrigin>${W}</AllowedOrigin>`;for(let W of G.AllowedMethods)z+=`<AllowedMethod>${W}</AllowedMethod>`;if(G.AllowedHeaders)for(let W of G.AllowedHeaders)z+=`<AllowedHeader>${W}</AllowedHeader>`;if(G.ExposeHeaders)for(let W of G.ExposeHeaders)z+=`<ExposeHeader>${W}</ExposeHeader>`;if(G.MaxAgeSeconds)z+=`<MaxAgeSeconds>${G.MaxAgeSeconds}</MaxAgeSeconds>`;return z+="</CORSRule>",z}).join("")}
129
+ </CORSConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${Q}`,queryParams:{cors:""},headers:{"Content-Type":"application/xml"},body:Y})}async deleteBucketCors(Q){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${Q}`,queryParams:{cors:""}})}async getBucketEncryption(Q){try{return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${Q}`,queryParams:{encryption:""}}))?.ServerSideEncryptionConfiguration}catch($){if($.statusCode===404)return null;throw $}}async putBucketEncryption(Q,$,J){let Y=`<ApplyServerSideEncryptionByDefault><SSEAlgorithm>${$}</SSEAlgorithm>`;if(J)Y+=`<KMSMasterKeyID>${J}</KMSMasterKeyID>`;Y+="</ApplyServerSideEncryptionByDefault>";let G=`<?xml version="1.0" encoding="UTF-8"?>
130
+ <ServerSideEncryptionConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
131
+ <Rule>${Y}</Rule>
132
+ </ServerSideEncryptionConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${Q}`,queryParams:{encryption:""},headers:{"Content-Type":"application/xml"},body:G})}async deleteBucketEncryption(Q){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${Q}`,queryParams:{encryption:""}})}async getBucketTagging(Q){try{let J=(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${Q}`,queryParams:{tagging:""}}))?.Tagging?.TagSet?.Tag;if(!J)return[];return Array.isArray(J)?J:[J]}catch($){if($.statusCode===404)return[];throw $}}async putBucketTagging(Q,$){let Y=`<?xml version="1.0" encoding="UTF-8"?>
133
+ <Tagging>
134
+ <TagSet>${$.map((G)=>`<Tag><Key>${G.Key}</Key><Value>${G.Value}</Value></Tag>`).join("")}</TagSet>
135
+ </Tagging>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${Q}`,queryParams:{tagging:""},headers:{"Content-Type":"application/xml"},body:Y})}async deleteBucketTagging(Q){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${Q}`,queryParams:{tagging:""}})}async getObjectTagging(Q,$){try{let Y=(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${Q}/${$}`,queryParams:{tagging:""}}))?.Tagging?.TagSet?.Tag;if(!Y)return[];return Array.isArray(Y)?Y:[Y]}catch(J){if(J.statusCode===404)return[];throw J}}async putObjectTagging(Q,$,J){let G=`<?xml version="1.0" encoding="UTF-8"?>
136
+ <Tagging>
137
+ <TagSet>${J.map((z)=>`<Tag><Key>${z.Key}</Key><Value>${z.Value}</Value></Tag>`).join("")}</TagSet>
138
+ </Tagging>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${Q}/${$}`,queryParams:{tagging:""},headers:{"Content-Type":"application/xml"},body:G})}async deleteObjectTagging(Q,$){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${Q}/${$}`,queryParams:{tagging:""}})}async getBucketAcl(Q){return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${Q}`,queryParams:{acl:""}}))?.AccessControlPolicy}async putBucketAcl(Q,$){await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${Q}`,queryParams:{acl:""},headers:{"x-amz-acl":$}})}async getObjectAcl(Q,$){return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${Q}/${$}`,queryParams:{acl:""}}))?.AccessControlPolicy}async putObjectAcl(Q,$,J){await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${Q}/${$}`,queryParams:{acl:""},headers:{"x-amz-acl":J}})}async getBucketLocation(Q){return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${Q}`,queryParams:{location:""}}))?.LocationConstraint||"us-east-1"}async getBucketLogging(Q){return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${Q}`,queryParams:{logging:""}}))?.BucketLoggingStatus}async putBucketLogging(Q,$,J){let Y=`<?xml version="1.0" encoding="UTF-8"?>
139
+ <BucketLoggingStatus xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
140
+ <LoggingEnabled>
141
+ <TargetBucket>${$}</TargetBucket>
142
+ <TargetPrefix>${J}</TargetPrefix>
143
+ </LoggingEnabled>
144
+ </BucketLoggingStatus>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${Q}`,queryParams:{logging:""},headers:{"Content-Type":"application/xml"},body:Y})}async getBucketNotificationConfiguration(Q){return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${Q}`,queryParams:{notification:""}}))?.NotificationConfiguration}async putBucketNotificationConfiguration(Q,$){let J="";if($.LambdaFunctionConfigurations)for(let G of $.LambdaFunctionConfigurations){if(J+="<CloudFunctionConfiguration>",G.Id)J+=`<Id>${G.Id}</Id>`;J+=`<CloudFunction>${G.LambdaFunctionArn}</CloudFunction>`;for(let z of G.Events)J+=`<Event>${z}</Event>`;if(G.Filter?.Key?.FilterRules){J+="<Filter><S3Key>";for(let z of G.Filter.Key.FilterRules)J+=`<FilterRule><Name>${z.Name}</Name><Value>${z.Value}</Value></FilterRule>`;J+="</S3Key></Filter>"}J+="</CloudFunctionConfiguration>"}if($.TopicConfigurations)for(let G of $.TopicConfigurations){if(J+="<TopicConfiguration>",G.Id)J+=`<Id>${G.Id}</Id>`;J+=`<Topic>${G.TopicArn}</Topic>`;for(let z of G.Events)J+=`<Event>${z}</Event>`;J+="</TopicConfiguration>"}if($.QueueConfigurations)for(let G of $.QueueConfigurations){if(J+="<QueueConfiguration>",G.Id)J+=`<Id>${G.Id}</Id>`;J+=`<Queue>${G.QueueArn}</Queue>`;for(let z of G.Events)J+=`<Event>${z}</Event>`;J+="</QueueConfiguration>"}let Y=`<?xml version="1.0" encoding="UTF-8"?>
145
+ <NotificationConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
146
+ ${J}
147
+ </NotificationConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${Q}`,queryParams:{notification:""},headers:{"Content-Type":"application/xml"},body:Y})}async getBucketWebsite(Q){try{return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${Q}`,queryParams:{website:""}}))?.WebsiteConfiguration}catch($){if($.statusCode===404)return null;throw $}}async putBucketWebsite(Q,$){let J="";if($.RedirectAllRequestsTo)J=`<RedirectAllRequestsTo>
148
+ <HostName>${$.RedirectAllRequestsTo.HostName}</HostName>
149
+ ${$.RedirectAllRequestsTo.Protocol?`<Protocol>${$.RedirectAllRequestsTo.Protocol}</Protocol>`:""}
150
+ </RedirectAllRequestsTo>`;else if(J=`<IndexDocument><Suffix>${$.IndexDocument}</Suffix></IndexDocument>`,$.ErrorDocument)J+=`<ErrorDocument><Key>${$.ErrorDocument}</Key></ErrorDocument>`;let Y=`<?xml version="1.0" encoding="UTF-8"?>
151
+ <WebsiteConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
152
+ ${J}
153
+ </WebsiteConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${Q}`,queryParams:{website:""},headers:{"Content-Type":"application/xml"},body:Y})}async deleteBucketWebsite(Q){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${Q}`,queryParams:{website:""}})}async getBucketReplication(Q){try{return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${Q}`,queryParams:{replication:""}}))?.ReplicationConfiguration}catch($){if($.statusCode===404)return null;throw $}}async deleteBucketReplication(Q){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${Q}`,queryParams:{replication:""}})}async getPublicAccessBlock(Q){try{return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${Q}`,queryParams:{publicAccessBlock:""}}))?.PublicAccessBlockConfiguration}catch($){if($.statusCode===404)return null;throw $}}async putPublicAccessBlock(Q,$){let J=`<?xml version="1.0" encoding="UTF-8"?>
154
+ <PublicAccessBlockConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
155
+ <BlockPublicAcls>${$.BlockPublicAcls??!0}</BlockPublicAcls>
156
+ <IgnorePublicAcls>${$.IgnorePublicAcls??!0}</IgnorePublicAcls>
157
+ <BlockPublicPolicy>${$.BlockPublicPolicy??!0}</BlockPublicPolicy>
158
+ <RestrictPublicBuckets>${$.RestrictPublicBuckets??!0}</RestrictPublicBuckets>
159
+ </PublicAccessBlockConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${Q}`,queryParams:{publicAccessBlock:""},headers:{"Content-Type":"application/xml"},body:J})}async deletePublicAccessBlock(Q){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${Q}`,queryParams:{publicAccessBlock:""}})}generatePresignedGetUrl(Q,$,J=3600){let{accessKeyId:Y,secretAccessKey:G}=this.getCredentials(),z=`${Q}.s3.${this.region}.amazonaws.com`,W=new Date,X=W.toISOString().replace(/[:-]|\.\d{3}/g,""),H=W.toISOString().slice(0,10).replace(/-/g,""),q=`${H}/${this.region}/s3/aws4_request`,Z=`${Y}/${q}`,K=new URLSearchParams({"X-Amz-Algorithm":"AWS4-HMAC-SHA256","X-Amz-Credential":Z,"X-Amz-Date":X,"X-Amz-Expires":J.toString(),"X-Amz-SignedHeaders":"host"}),_=["GET",`/${$}`,K.toString(),`host:${z}
160
+ `,"host","UNSIGNED-PAYLOAD"].join(`
161
+ `),U=["AWS4-HMAC-SHA256",X,q,D.createHash("sha256").update(_).digest("hex")].join(`
162
+ `),L=D.createHmac("sha256",`AWS4${G}`).update(H).digest(),F=D.createHmac("sha256",L).update(this.region).digest(),O=D.createHmac("sha256",F).update("s3").digest(),M=D.createHmac("sha256",O).update("aws4_request").digest(),T=D.createHmac("sha256",M).update(U).digest("hex");return K.append("X-Amz-Signature",T),`https://${z}/${$}?${K.toString()}`}generatePresignedPutUrl(Q,$,J,Y=3600){let{accessKeyId:G,secretAccessKey:z}=this.getCredentials(),W=`${Q}.s3.${this.region}.amazonaws.com`,X=new Date,H=X.toISOString().replace(/[:-]|\.\d{3}/g,""),q=X.toISOString().slice(0,10).replace(/-/g,""),Z=`${q}/${this.region}/s3/aws4_request`,K=`${G}/${Z}`,_=new URLSearchParams({"X-Amz-Algorithm":"AWS4-HMAC-SHA256","X-Amz-Credential":K,"X-Amz-Date":H,"X-Amz-Expires":Y.toString(),"X-Amz-SignedHeaders":"content-type;host"}),U=["PUT",`/${$}`,_.toString(),`content-type:${J}
163
+ host:${W}
164
+ `,"content-type;host","UNSIGNED-PAYLOAD"].join(`
165
+ `),L=["AWS4-HMAC-SHA256",H,Z,D.createHash("sha256").update(U).digest("hex")].join(`
166
+ `),F=D.createHmac("sha256",`AWS4${z}`).update(q).digest(),O=D.createHmac("sha256",F).update(this.region).digest(),M=D.createHmac("sha256",O).update("s3").digest(),T=D.createHmac("sha256",M).update("aws4_request").digest(),f=D.createHmac("sha256",T).update(L).digest("hex");return _.append("X-Amz-Signature",f),`https://${W}/${$}?${_.toString()}`}async createMultipartUpload(Q,$,J){let Y={};if(J?.contentType)Y["Content-Type"]=J.contentType;if(J?.metadata)for(let[z,W]of Object.entries(J.metadata))Y[`x-amz-meta-${z}`]=W;return{UploadId:(await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${Q}/${$}`,queryParams:{uploads:""},headers:Y}))?.InitiateMultipartUploadResult?.UploadId}}async uploadPart(Q,$,J,Y,G){let{accessKeyId:z,secretAccessKey:W,sessionToken:X}=this.getCredentials(),H=`${Q}.s3.${this.region}.amazonaws.com`,q=`https://${H}/${$}?partNumber=${Y}&uploadId=${encodeURIComponent(J)}`,Z=new Date,K=Z.toISOString().replace(/[:-]|\.\d{3}/g,""),_=Z.toISOString().slice(0,10).replace(/-/g,""),U=D.createHash("sha256").update(G).digest("hex"),L={host:H,"x-amz-date":K,"x-amz-content-sha256":U};if(X)L["x-amz-security-token"]=X;let F=Object.keys(L).sort().map((v)=>`${v.toLowerCase()}:${L[v].trim()}
167
+ `).join(""),O=Object.keys(L).sort().map((v)=>v.toLowerCase()).join(";"),M=["PUT",`/${$}`,`partNumber=${Y}&uploadId=${encodeURIComponent(J)}`,F,O,U].join(`
168
+ `),T="AWS4-HMAC-SHA256",f=`${_}/${this.region}/s3/aws4_request`,P=[T,K,f,D.createHash("sha256").update(M).digest("hex")].join(`
169
+ `),I=D.createHmac("sha256",`AWS4${W}`).update(_).digest(),j=D.createHmac("sha256",I).update(this.region).digest(),A=D.createHmac("sha256",j).update("s3").digest(),h=D.createHmac("sha256",A).update("aws4_request").digest(),V=D.createHmac("sha256",h).update(P).digest("hex"),N=`${T} Credential=${z}/${f}, SignedHeaders=${O}, Signature=${V}`,B=await fetch(q,{method:"PUT",headers:{...L,Authorization:N},body:new Uint8Array(G)});if(!B.ok){let v=await B.text();throw Error(`Upload part failed: ${B.status} ${v}`)}return{ETag:B.headers.get("etag")||""}}async completeMultipartUpload(Q,$,J,Y){let z=`<?xml version="1.0" encoding="UTF-8"?>
170
+ <CompleteMultipartUpload>${Y.sort((W,X)=>W.PartNumber-X.PartNumber).map((W)=>`<Part><PartNumber>${W.PartNumber}</PartNumber><ETag>${W.ETag}</ETag></Part>`).join("")}</CompleteMultipartUpload>`;await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${Q}/${$}`,queryParams:{uploadId:J},headers:{"Content-Type":"application/xml"},body:z})}async abortMultipartUpload(Q,$,J){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${Q}/${$}`,queryParams:{uploadId:J}})}async listMultipartUploads(Q){let J=(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${Q}`,queryParams:{uploads:""}}))?.ListMultipartUploadsResult?.Upload;if(!J)return[];return(Array.isArray(J)?J:[J]).map((G)=>({Key:G.Key,UploadId:G.UploadId,Initiated:G.Initiated}))}async restoreObject(Q,$,J,Y="Standard"){let G=`<?xml version="1.0" encoding="UTF-8"?>
171
+ <RestoreRequest>
172
+ <Days>${J}</Days>
173
+ <GlacierJobParameters>
174
+ <Tier>${Y}</Tier>
175
+ </GlacierJobParameters>
176
+ </RestoreRequest>`;await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${Q}/${$}`,queryParams:{restore:""},headers:{"Content-Type":"application/xml"},body:G})}async selectObjectContent(Q,$,J,Y,G="JSON"){let z="";if(Y==="CSV")z="<CSV><FileHeaderInfo>USE</FileHeaderInfo></CSV>";else if(Y==="JSON")z="<JSON><Type>DOCUMENT</Type></JSON>";else z="<Parquet/>";let W="";if(G==="CSV")W="<CSV/>";else W="<JSON/>";let X=`<?xml version="1.0" encoding="UTF-8"?>
177
+ <SelectObjectContentRequest>
178
+ <Expression>${J}</Expression>
179
+ <ExpressionType>SQL</ExpressionType>
180
+ <InputSerialization>${z}</InputSerialization>
181
+ <OutputSerialization>${W}</OutputSerialization>
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
+ `))!==-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
+ `)}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
187
+
188
+ _buddy_completion() {
189
+ local cur prev commands
190
+ COMPREPLY=()
191
+ cur="\${COMP_WORDS[COMP_CWORD]}"
192
+ prev="\${COMP_WORDS[COMP_CWORD-1]}"
193
+
194
+ commands="${Q.join(" ")}"
195
+
196
+ # Complete command names
197
+ if [ $COMP_CWORD -eq 1 ]; then
198
+ COMPREPLY=( $(compgen -W "$commands" -- "$cur") )
199
+ return 0
200
+ fi
201
+
202
+ # Complete global flags
203
+ case "$prev" in
204
+ buddy|*)
205
+ COMPREPLY=( $(compgen -W "--help --version --verbose --quiet --debug --no-interaction --env --dry-run --force" -- "$cur") )
206
+ return 0
207
+ ;;
208
+ esac
209
+ }
210
+
211
+ complete -F _buddy_completion buddy
212
+
213
+ # Installation:
214
+ # To install this completion script, save it to:
215
+ # - Linux: /etc/bash_completion.d/buddy or ~/.bash_completion
216
+ # - macOS: /usr/local/etc/bash_completion.d/buddy
217
+ #
218
+ # Then reload your shell or run: source ~/.bashrc
219
+ `}function i8(Q){return`#compdef buddy
220
+
221
+ # buddy completion for zsh
222
+
223
+ _buddy() {
224
+ local -a commands
225
+ commands=(
226
+ ${Q.map((J)=>` '${J}:${J} command'`).join(`
227
+ `)}
228
+ )
229
+
230
+ local -a global_flags
231
+ global_flags=(
232
+ '--help[Display help message]'
233
+ '--version[Display version number]'
234
+ '--verbose[Enable verbose output]'
235
+ '--quiet[Suppress non-essential output]'
236
+ '--debug[Enable debug mode]'
237
+ '--no-interaction[Do not ask interactive questions]'
238
+ '--env[Target environment]:environment:'
239
+ '--dry-run[Preview actions without executing]'
240
+ '--force[Skip confirmation prompts]'
241
+ )
242
+
243
+ _arguments -C \\
244
+ '1: :->command' \\
245
+ '*::arg:->args' \\
246
+ $global_flags
247
+
248
+ case $state in
249
+ command)
250
+ _describe 'buddy command' commands
251
+ ;;
252
+ *)
253
+ # Add subcommand-specific completions here if needed
254
+ ;;
255
+ esac
256
+ }
257
+
258
+ _buddy "$@"
259
+
260
+ # Installation:
261
+ # Save this file to a directory in your $fpath, for example:
262
+ # ~/.zsh/completions/_buddy
263
+ #
264
+ # Then add to your ~/.zshrc:
265
+ # fpath=(~/.zsh/completions $fpath)
266
+ # autoload -Uz compinit && compinit
267
+ `}function s8(Q){return`# buddy completion for fish
268
+
269
+ # Remove old completions
270
+ complete -c buddy -e
271
+
272
+ # Command completions
273
+ ${Q.map((J)=>`complete -c buddy -n "__fish_use_subcommand" -a "${J}" -d "${J} command"`).join(`
274
+ `)}
275
+
276
+ # Global flag completions
277
+ complete -c buddy -l help -d "Display help message"
278
+ complete -c buddy -l version -d "Display version number"
279
+ complete -c buddy -s v -l verbose -d "Enable verbose output"
280
+ complete -c buddy -s q -l quiet -d "Suppress non-essential output"
281
+ complete -c buddy -l debug -d "Enable debug mode"
282
+ complete -c buddy -s n -l no-interaction -d "Do not ask interactive questions"
283
+ complete -c buddy -l env -d "Target environment" -r
284
+ complete -c buddy -l dry-run -d "Preview actions without executing"
285
+ complete -c buddy -s f -l force -d "Skip confirmation prompts"
286
+
287
+ # Installation:
288
+ # Save this file to:
289
+ # ~/.config/fish/completions/buddy.fish
290
+ #
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(`
293
+ `),Y=$.split(`
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
+ `);if(X!==void 0)R2.stdout.write(` + ${X}
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}
298
+ ${Y}
299
+ us-east-1
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.28";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
+ `)}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
+ `);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
+
307
+ And your APP_URL has been set to ${L$(Y)}.
308
+
309
+ Please note, this change has not been deployed yet.
310
+
311
+ The next time you run ${D6(L$(b6(" buddy deploy ")))}, your app will deploy to ${L$(Y)}.
312
+
313
+ ${L$("You may need to deploy 2-3 times for the changes to take effect. Issue tracked here: https://github.com/stacksjs/stacks/issues/685")}`,await $$(q,{startTime:z,useSeconds:!0,type:"info"}),e0.exit(Q$.Success)}),Q.command("domains:add <domain>",$.add).option("--verbose",$.verbose,{default:!1}).action(async(Y)=>{d7.debug("Running `buddy domains:add <domain>` ...",Y);let G=await S2("buddy domains:add"),z=await k6({...Y,startTime:G});if(z.isErr)await $$("While running the `buddy deploy`, there was an issue",{startTime:G,useSeconds:!0},z.error),e0.exit(Q$.FatalError);await $$("Added your domain.",{startTime:G,useSeconds:!0}),e0.exit(Q$.Success)}),Q.command("domains:remove <domain>",$.remove).option("--yes",$.skip,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(Y)=>{d7.debug("Running `buddy domains:remove <domain>` ...",Y);let G=Y.domain||z1.app.url,z={...Y,domain:G},W=await S2("buddy domains:remove");if(!z.yes){let{confirm:H}=await G1({name:"confirm",type:"confirm",message:`Are you sure you want to remove ${G}?`});if(!H)await $$("Cancelled the domains:remove command",{startTime:W,useSeconds:!0,type:"info"}),e0.exit(Q$.Success)}let X=await Y1(W1.DomainsRemove,z);if(X.isErr)await $$("While running the domains:remove command, there was an issue",{startTime:W,useSeconds:!0},X.error),e0.exit(Q$.FatalError);await $$("Removed your domain DNS records.",{startTime:W,useSeconds:!0}),e0.exit(Q$.Success)}),y6(Q,"domains")}import{readFileSync as x6,existsSync as g6}from"fs";import s from"process";import{email as P0}from"@stacksjs/config";import{ExitCode as u6}from"@stacksjs/types";import{onUnknownSubcommand as m6}from"@stacksjs/cli";var c6=30000;async function q0(Q,$=c6){let J,Y=new Promise((G,z)=>{J=setTimeout(()=>z(Error(`Operation timed out after ${$}ms`)),$)});try{return await Promise.race([Q,Y])}finally{clearTimeout(J)}}var X1=!1;async function l6(Q,$){try{let{S3Client:J}=await import("@stacksjs/ts-cloud"),Y=new J($),G=Y.listObjects;if(typeof G!=="function")return{ok:!0};return await q0(G.call(Y,{bucket:Q,maxKeys:1}),5000),{ok:!0}}catch(J){let Y=J instanceof Error?J.message:String(J);if(/NoSuchBucket/i.test(Y))return{ok:!1,reason:`Bucket '${Q}' does not exist in region '${$}'.`,hint:"Run `buddy deploy` to create email infrastructure, or pass --bucket <name> if you know the correct bucket."};if(/AccessDenied|Forbidden/i.test(Y))return{ok:!1,reason:`Access denied to bucket '${Q}'.`,hint:"Check that AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY (or your IAM role) have s3:ListBucket permission for this bucket."};if(/region/i.test(Y)||/PermanentRedirect/i.test(Y))return{ok:!1,reason:`Bucket '${Q}' is not in region '${$}'.`,hint:"Set AWS_REGION to the bucket's actual region, or pass the right bucket for this region."};return{ok:!1,reason:Y,hint:"Check AWS connectivity and credentials."}}}async function P$(){if(X1)return;X1=!0;let Q=".env.production";if(!g6(Q))return;let{parse:$}=await import("@stacksjs/env"),J=x6(Q,"utf-8"),{parsed:Y}=$(J);for(let[G,z]of Object.entries(Y))if(s.env[G]===void 0)s.env[G]=z}var J$={email:"Email server management commands",verify:"Check domain verification status",test:"Send a test email",list:"List configured mailboxes",logs:"View email processing logs",status:"Show email server status",inbox:"View inbox emails from S3",reprocess:"Reprocess raw emails from S3 into mailbox structure"};function eW(Q){Q.command("email",J$.email).alias("mail").action(async()=>{console.log(`
314
+ \uD83D\uDCE7 Email Server Commands
315
+ `),console.log(" buddy email:verify - Check domain verification status"),console.log(" buddy email:test - Send a test email"),console.log(" buddy email:list - List configured mailboxes"),console.log(" buddy email:inbox - View inbox emails from S3"),console.log(" buddy email:reprocess - Reprocess raw emails into mailbox structure"),console.log(" buddy email:logs - View email processing logs"),console.log(" buddy email:status - Show email server status"),console.log("")}),Q.command("email:verify",J$.verify).action(async()=>{console.log(`
316
+ \uD83D\uDCE7 Checking Email Domain Verification...
317
+ `),await P$();try{let{SESClient:$}=await import("@stacksjs/ts-cloud"),J=new $(s.env.AWS_REGION||"us-east-1"),Y=(P0?.from?.address?.includes("@")?P0.from.address.split("@")[1]:void 0)||"stacksjs.com";console.log(`Domain: ${Y}`);let G=await q0(J.getEmailIdentity(Y));if(G){if(console.log(`
318
+ \u2705 Domain Status: ${G.VerificationStatus||"Unknown"}`),G.DkimAttributes){if(console.log(`
319
+ DKIM Status: ${G.DkimAttributes.Status||"Unknown"}`),G.DkimAttributes.Tokens){console.log(`
320
+ DKIM Records needed:`);for(let z of G.DkimAttributes.Tokens)console.log(` CNAME: ${z}._domainkey.${Y}`),console.log(` Value: ${z}.dkim.amazonses.com`)}}}else console.log("\n\u26A0\uFE0F Domain not found in SES. Run `buddy deploy` to set up email.")}catch($){console.error(`
321
+ \u274C Error checking verification:`,$.message)}s.exit(0)}),Q.command("email:test [recipient]",J$.test).action(async($)=>{let J=$||P0?.from?.address||"test@example.com";console.log(`
322
+ \uD83D\uDCE7 Sending Test Email to ${J}...
323
+ `),await P$();try{let{SESClient:Y}=await import("@stacksjs/ts-cloud"),G=new Y(s.env.AWS_REGION||"us-east-1"),z=(P0?.from?.address?.includes("@")?P0.from.address.split("@")[1]:void 0)||"stacksjs.com",W=`noreply@${z}`,X=await q0(G.sendEmail({FromEmailAddress:W,Destination:{ToAddresses:[J]},Content:{Simple:{Subject:{Data:"Test Email from Stacks",Charset:"UTF-8"},Body:{Text:{Data:"This is a test email sent from your Stacks application.",Charset:"UTF-8"},Html:{Data:`
324
+ <html>
325
+ <body style="font-family: sans-serif; padding: 20px;">
326
+ <h1>\uD83D\uDE80 Test Email from Stacks</h1>
327
+ <p>This is a test email sent from your Stacks application.</p>
328
+ <p>If you received this, your email server is working correctly!</p>
329
+ <hr>
330
+ <p style="color: #666; font-size: 12px;">
331
+ Sent from ${z} via Amazon SES
332
+ </p>
333
+ </body>
334
+ </html>
335
+ `,Charset:"UTF-8"}}}}}));console.log("\u2705 Test email sent successfully!"),console.log(` Message ID: ${X.MessageId}`)}catch(Y){if(console.error(`
336
+ \u274C Error sending test email:`,Y.message),Y.message.includes("not verified"))console.log(`
337
+ \uD83D\uDCA1 Tip: Make sure your domain is verified in SES.`),console.log(" Run `buddy email:verify` to check status.")}s.exit(0)}),Q.command("email:list",J$.list).action(async()=>{console.log(`
338
+ \uD83D\uDCE7 Configured Mailboxes
339
+ `);let $=(P0?.from?.address?.includes("@")?P0.from.address.split("@")[1]:void 0)||"stacksjs.com",J=P0?.mailboxes||[];if(console.log(`Domain: ${$}`),console.log(`Default From: ${P0?.from?.name} <${P0?.from?.address}>`),console.log(""),J.length===0)console.log("No mailboxes configured."),console.log(`
340
+ \uD83D\uDCA1 Add mailboxes in config/email.ts:`),console.log(' mailboxes: ["user@domain.com", "another@domain.com"]');else{console.log("Mailboxes:");for(let Y of J)console.log(` \uD83D\uDCEC ${Y}`)}console.log(""),s.exit(0)}),Q.command("email:logs",J$.logs).option("-n, --lines <count>","Number of log lines to show",{default:"20"}).action(async($)=>{console.log(`
341
+ \uD83D\uDCE7 Email Processing Logs
342
+ `),await P$();try{let{CloudWatchLogsClient:J}=await import("@stacksjs/ts-cloud"),Y=new J(s.env.AWS_REGION||"us-east-1"),z=`/aws/lambda/${(s.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-")}-inbound-email`;console.log(`Log Group: ${z}`),console.log(`Showing last ${$.lines} events...
343
+ `);let W=await q0(Y.describeLogStreams({logGroupName:z,orderBy:"LastEventTime",descending:!0,limit:1}));if(!W.logStreams||W.logStreams.length===0){console.log("No log streams found."),console.log(`
344
+ \uD83D\uDCA1 Logs will appear after emails are processed.`);return}let X=W.logStreams[0].logStreamName;if(!X){console.log("No log stream name found.");return}let H=await q0(Y.getLogEvents({logGroupName:z,logStreamName:X,limit:parseInt($.lines||"20",10)}));if(H.events&&H.events.length>0)for(let q of H.events){let Z=new Date(q.timestamp||0).toISOString();console.log(`[${Z}] ${q.message}`)}else console.log("No log events found."),console.log(`
345
+ \uD83D\uDCA1 Logs will appear after emails are processed.`)}catch(J){if(J.message.includes("ResourceNotFoundException")||J.message.includes("timed out"))console.log("Log group not found or not accessible. No emails have been processed yet.");else console.error("Error fetching logs:",J.message)}s.exit(0)}),Q.command("email:status",J$.status).action(async()=>{console.log(`
346
+ \uD83D\uDCE7 Email Server Status
347
+ `),await P$();try{let{AWSCloudFormationClient:$}=await import("@stacksjs/ts-cloud"),J=new $(s.env.AWS_REGION||"us-east-1"),G=`${(s.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-")}-cloud`,W=(await q0(J.listStackResources(G))).StackResourceSummaries?.filter((Z)=>Z.LogicalResourceId.includes("Email")||Z.LogicalResourceId.includes("Inbound")||Z.LogicalResourceId.includes("Outbound"))||[];if(W.length===0){console.log("\u274C Email server not deployed."),console.log("\n\uD83D\uDCA1 Run `buddy deploy` to set up email infrastructure.");return}console.log(`\u2705 Email Server Deployed
348
+ `),console.log("Resources:");for(let Z of W){let K=Z.ResourceStatus==="CREATE_COMPLETE"||Z.ResourceStatus==="UPDATE_COMPLETE"?"\u2705":"\u23F3";console.log(` ${K} ${Z.LogicalResourceId}`)}let q=((await q0(J.describeStacks({stackName:G}))).Stacks?.[0]?.Outputs||[]).filter((Z)=>Z.OutputKey?.includes("Email"));if(q.length>0){console.log(`
349
+ Configuration:`);for(let Z of q)console.log(` ${Z.OutputKey}: ${Z.OutputValue}`)}}catch($){console.error("Error checking status:",$.message)}s.exit(0)}),Q.command("email:inbox [mailbox]",J$.inbox).option("-n, --limit <count>","Number of emails to show",{default:"20"}).option("--raw <id>","Show raw email content for a specific message ID").option("--bucket <name>","S3 bucket name override").action(async($,J)=>{await P$();let Y=s.env.AWS_REGION||"us-east-1",G=(s.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-"),z=(P0?.from?.address?.includes("@")?P0.from.address.split("@")[1]:void 0)||"stacksjs.com",W=J?.bucket||`${G}-production-email`,X=await l6(W,Y);if(!X.ok)console.error(`
350
+ \u274C ${X.reason}
351
+ \uD83D\uDCA1 ${X.hint}
352
+ `),s.exit(u6.FatalError);if(J?.raw){console.log(`
353
+ \uD83D\uDCE7 Fetching raw email: ${J.raw}
354
+ `);try{let{S3Client:K}=await import("@stacksjs/ts-cloud"),_=new K(Y),U=null;try{U=await q0(_.getObject(W,`inbox/${J.raw}`))}catch(L){if($){let[F,O]=$.includes("@")?$.split("@"):[$,z],T=(await q0(_.listObjects({bucket:W,prefix:`mailboxes/${O}/${F}/`,maxKeys:1000}))).Contents?.find((f)=>f.Key.includes(J.raw)&&f.Key.endsWith("/raw.eml"));if(T)U=await q0(_.getObject(W,T.Key))}}if(U)console.log(U);else console.log("Email not found.")}catch(K){console.error("Error fetching email:",K.message)}s.exit(0);return}let H=$||`chris@${z}`,[q,Z]=H.includes("@")?H.split("@"):[H,z];console.log(`
355
+ \uD83D\uDCE7 Inbox for ${q}@${Z}
356
+ `),console.log(` Bucket: ${W}`),console.log("");try{let{S3Client:K}=await import("@stacksjs/ts-cloud"),_=new K(Y),U=parseInt(J?.limit||"20",10),L=`mailboxes/${Z}/${q}/inbox.json`,F=[],O="mailboxes";try{let M=await q0(_.getObject(W,L));if(M)try{F=JSON.parse(M),O="mailboxes"}catch{F=[]}}catch{}if(F.length===0){console.log(` No processed inbox found. Scanning raw emails from inbox/ ...
357
+ `),O="raw";try{let T=(await q0(_.listObjects({bucket:W,prefix:"inbox/",maxKeys:U}))).Contents||[];if(T.length===0){let P=(await q0(_.listObjects({bucket:W,prefix:"incoming/",maxKeys:U}))).Contents||[];T.push(...P)}for(let f of T.slice(0,U))try{let P=await q0(_.getObject(W,f.Key));if(!P)continue;let I=q1(P);F.push({messageId:f.Key.split("/").pop()||f.Key,from:I.from||"unknown",subject:I.subject||"No Subject",date:I.date||f.LastModified||"unknown",path:f.Key})}catch(P){F.push({messageId:f.Key.split("/").pop()||f.Key,from:"unknown",subject:"(could not parse)",date:f.LastModified||"unknown",path:f.Key})}}catch(M){console.error("Error listing emails:",M.message)}}if(F.length===0){console.log(" No emails found."),console.log(`
358
+ Waiting for emails to arrive at inbox/ in the S3 bucket.`),console.log(" Send an email to an @"+Z+" address to test."),s.exit(0);return}console.log(` Source: ${O} (${F.length} emails)
359
+ `),console.log(" %-4s %-20s %-30s %s","#","Date","From","Subject"),console.log(" "+"-".repeat(90));for(let M=0;M<Math.min(F.length,U);M++){let T=F[M],f=T.date?new Date(T.date).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):"?",P=(T.from||"").substring(0,20).padEnd(20),I=(T.subject||"").substring(0,40),j=T.read===!1?"*":" ";console.log(` ${j}${String(M+1).padStart(3)} ${f.padEnd(20)} ${P} ${I}`)}console.log(""),console.log(" * = unread"),console.log(`
360
+ View raw email: buddy email:inbox ${H} --raw <messageId>`)}catch(K){console.error("Error reading inbox:",K.message)}s.exit(0)}),Q.command("email:reprocess",J$.reprocess).option("--bucket <name>","S3 bucket name override").option("--prefix <prefix>","S3 prefix to scan",{default:"inbox/"}).option("--domain <domain>","Email domain",{default:"stacksjs.com"}).action(async($)=>{await P$();let J=s.env.AWS_REGION||"us-east-1",Y=(s.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-"),G=$?.bucket||`${Y}-production-email`,z=$?.prefix||"inbox/",W=$?.domain||"stacksjs.com";console.log(`
361
+ \uD83D\uDCE7 Reprocessing emails from s3://${G}/${z}
362
+ `);try{let{S3Client:X}=await import("@stacksjs/ts-cloud"),H=new X(J),Z=(await q0(H.listObjects({bucket:G,prefix:z,maxKeys:1000}),60000)).Contents||[];console.log(` Found ${Z.length} raw emails to process
363
+ `);let K={},_=0;for(let U of Z){if(!U.Key||U.Key.endsWith("/"))continue;try{let L=await q0(H.getObject(G,U.Key),15000);if(!L)continue;let F=q1(L),O=U.Key.split("/").pop()||U.Key,M=H1(F.from||""),T=d6(F.from||""),f=(F.to||"").split(",").map((V)=>V.trim()).filter(Boolean),P=F.subject||"No Subject",I=F.date||(U.LastModified?new Date(U.LastModified).toISOString():new Date().toISOString()),j="",A=L.indexOf(`\r
364
+ \r
365
+ `);if(A>0)j=L.substring(A+4,A+500).replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim().substring(0,200);let h=f.length>0?f:[`unknown@${W}`];for(let V of h){let N=H1(V);if(!N.endsWith(`@${W}`))continue;let[B]=N.split("@"),v=new Date(I),B0=v.getFullYear(),i=String(v.getMonth()+1).padStart(2,"0"),q2=String(v.getDate()).padStart(2,"0"),m$=`mailboxes/${W}/${B}/${B0}/${i}/${q2}/${O}`;await H.putObject({bucket:G,key:`${m$}/raw.eml`,body:L,contentType:"message/rfc822"});let c$={messageId:O,from:M,fromName:T,to:N,subject:P,date:I,preview:j,hasAttachments:!1};await H.putObject({bucket:G,key:`${m$}/metadata.json`,body:JSON.stringify(c$,null,2),contentType:"application/json"});let H2=`${W}/${B}`;if(!K[H2])K[H2]=[];K[H2].push({messageId:O,from:M,fromName:T,to:N,subject:P,date:I,read:!1,preview:j,hasAttachments:!1,path:m$})}if(_++,_%5===0)console.log(` Processed ${_}/${Z.length} emails...`)}catch(L){console.log(` Skipping ${U.Key}: ${L.message}`)}}for(let[U,L]of Object.entries(K)){let[F,O]=U.split("/"),M=`mailboxes/${F}/${O}/inbox.json`;L.sort((j,A)=>new Date(A.date).getTime()-new Date(j.date).getTime());let T=[];try{let j=await H.getObject(G,M);if(j)try{T=JSON.parse(j)}catch{T=[]}}catch{}let f=new Set(T.map((j)=>j.messageId)),P=L.filter((j)=>!f.has(j.messageId)),I=[...P,...T].slice(0,1000);await H.putObject({bucket:G,key:M,body:JSON.stringify(I,null,2),contentType:"application/json"}),console.log(` Updated inbox for ${O}@${F}: ${P.length} new emails (${I.length} total)`)}console.log(`
366
+ Done! Processed ${_} emails.`)}catch(X){console.error("Error reprocessing:",X.message)}s.exit(0)}),m6(Q,"email")}function q1(Q){let $={},J=Q.split(/\r?\n/),Y="",G="";for(let z of J){if(z==="")break;if(/^\s/.test(z)&&Y)G+=" "+z.trim(),$[Y]=G;else{let W=z.match(/^([^:]+):\s*(.*)$/);if(W)Y=W[1].toLowerCase(),G=W[2],$[Y]=G}}return $}function H1(Q){if(!Q)return"";let $=Q.match(/<([^>]+)>/);return($?$[1]:Q).toLowerCase().trim()}function d6(Q){if(!Q)return"";let $=Q.match(/^"?([^"<]+)"?\s*</);return $?$[1].trim():""}import J0 from"process";import{log as F$,onUnknownSubcommand as p6}from"@stacksjs/cli";import{decryptEnv as r6,encryptEnv as n6,getEnv as a6,getKeypair as i6,rotateKeypair as s6,setEnv as o6}from"@stacksjs/env";import{ExitCode as H0}from"@stacksjs/types";function z4(Q){let $={env:"Interact with your environment variables",get:"Get an environment variable",set:"Set an environment variable",encrypt:"Encrypt a value",decrypt:"Decrypt a value",check:"Check environment configuration and validate setup",pretty:"Pretty print the result",stdout:"Output the result to stdout",keypair:"Generate a keypair",fileKeys:"The path to the file containing the keys",excludeKey:"The key to exclude from encryption",rotate:"Rotate a keypair",format:"The format to output the result (json, shell, eval)",all:"Get all environment variables",file:"The environment file to use",project:"Target a specific project",verbose:"Enable verbose output"};Q.command("env:get [key]",$.get).option("-f, --file [file]",$.file,{default:""}).option("--format [format]",$.format,{default:"json"}).option("-a, --all",$.all,{default:!1}).option("-p, --pretty",$.pretty,{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).example("buddy env:get SECRET").example("buddy env:get SECRET --file .env.production").example("buddy env:get --all --pretty").example("buddy env:get --format shell").example("buddy env:get --format eval").example("buddy env:get --format json").action(async(J,Y)=>{F$.debug("Running `buddy env:get` ...",Y);let G=a6(J,{file:Y.file,keysFile:Y.fileKeys,all:Y.all,format:Y.format,prettyPrint:Y.pretty});if(G.success)console.log(G.output),J0.exit(H0.Success);else console.error(G.error),J0.exit(H0.FatalError)}),Q.command("env:set [key] [value]",$.set).option("-f, --file [file]",$.file,{default:""}).option("-fk, --file-keys [fileKeys]",$.fileKeys,{default:""}).option("--plain","Don't encrypt the value",{default:!1}).option("--verbose",$.verbose,{default:!1}).example("buddy env:set SECRET=value").example("buddy env:set SECRET value").example("buddy env:set SECRET value --file .env.production").example("buddy env:set SECRET value --plain").action(async(J,Y,G)=>{if(F$.debug("Running `buddy env:set` ...",G),!J||!Y)console.error("Both key and value are required"),J0.exit(H0.FatalError);let z=o6(J,Y,{file:G.file,keysFile:G.fileKeys,plain:G.plain});if(z.success)console.log(z.output),J0.exit(H0.Success);else console.error(z.error),J0.exit(H0.FatalError)}),Q.command("env:encrypt [key]",$.encrypt).option("-f, --file [file]",$.file,{default:""}).option("-fk, --file-keys [fileKeys]",$.fileKeys,{default:""}).option("-o, --stdout",$.stdout,{default:!1}).option("-ek, --exclude-key [excludeKey]",$.excludeKey,{default:""}).example("buddy env:encrypt").example("buddy env:encrypt --file .env.production").example('buddy env:encrypt -k "SECRET_*"').action(async(J,Y)=>{F$.debug("Running `buddy env:encrypt` ...",Y);let G=n6({file:Y.file,keysFile:Y.fileKeys,key:J,excludeKey:Y.excludeKey,stdout:Y.stdout});if(G.success)console.log(G.output),J0.exit(H0.Success);else console.error(G.error),J0.exit(H0.FatalError)}),Q.command("env:decrypt [key]",$.decrypt).option("-f, --file [file]",$.file,{default:""}).option("-fk, --file-keys [fileKeys]",$.fileKeys,{default:""}).option("-o, --stdout",$.stdout,{default:!1}).example("buddy env:decrypt").example("buddy env:decrypt --file .env.production").example('buddy env:decrypt -k "SECRET_*"').action(async(J,Y)=>{F$.debug("Running `buddy env:decrypt` ...",Y);let G=r6({file:Y.file,keysFile:Y.fileKeys,key:J,stdout:Y.stdout});if(G.success)console.log(G.output),J0.exit(H0.Success);else console.error(G.error),J0.exit(H0.FatalError)}),Q.command("env:keypair [key]",$.keypair).option("-f, --file [file]",$.file,{default:""}).option("-fk, --file-keys [fileKeys]",$.fileKeys,{default:""}).option("--format [format]",$.format,{default:"json"}).example("buddy env:keypair").example("buddy env:keypair --file .env.production").example("buddy env:keypair DOTENV_PRIVATE_KEY").action(async(J,Y)=>{F$.debug("Running `buddy env:keypair` ...",Y);let G=i6(J,{file:Y.file,keysFile:Y.fileKeys,format:Y.format});if(G.success)console.log(G.output),J0.exit(H0.Success);else console.error(G.error),J0.exit(H0.FatalError)}),Q.command("env:rotate [key]",$.rotate).option("-f, --file [file]",$.file,{default:""}).option("-fk, --file-keys [fileKeys]",$.fileKeys,{default:""}).option("-o, --stdout",$.stdout,{default:!1}).option("-ek, --exclude-key [excludeKey]",$.excludeKey,{default:""}).example("buddy env:rotate").example("buddy env:rotate --file .env.production").action(async(J,Y)=>{F$.debug("Running `buddy env:rotate` ...",Y);let G=s6({file:Y.file,keysFile:Y.fileKeys,key:J,excludeKey:Y.excludeKey,stdout:Y.stdout});if(G.success)console.log(G.output),J0.exit(H0.Success);else console.error(G.error),J0.exit(H0.FatalError)}),Q.command("env:check",$.check).option("-f, --file [file]",$.file,{default:""}).option("--verbose",$.verbose,{default:!1}).example("buddy env:check").example("buddy env:check --file .env.production").action(async(J)=>{F$.debug("Running `buddy env:check` ...",J);let{bold:Y,dim:G,green:z,red:W,yellow:X,intro:H}=await import("@stacksjs/cli"),{storage:q}=await import("@stacksjs/storage"),{existsSync:Z}=await import("fs"),{resolve:K}=await import("path");await H("buddy env:check");let _=[],U=J.file||".env",L=K(J0.cwd(),U);if(Z(L)){_.push({name:`${U} file`,status:"pass",message:"Found"});try{let T=await q.readTextFile(L),P=String(T).split(`
367
+ `).filter((V)=>V.trim()&&!V.startsWith("#")),I=P.length;if(_.push({name:"Environment variables",status:"pass",message:`${I} variables defined`}),P.some((V)=>V.startsWith("APP_KEY="))){let V=P.find((B0)=>B0.startsWith("APP_KEY=")),N=V?.indexOf("=")??-1,v=(N>=0?V.slice(N+1):"").trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1");if(v&&v.length>0)_.push({name:"APP_KEY",status:"pass",message:"Set"});else _.push({name:"APP_KEY",status:"warn",message:"Empty (run: buddy key:generate)"})}else _.push({name:"APP_KEY",status:"warn",message:"Not found (run: buddy key:generate)"});let A=P.some((V)=>V.startsWith("DOTENV_PUBLIC_KEY=")),h=P.some((V)=>V.startsWith("DOTENV_PRIVATE_KEY="));if(A&&h)_.push({name:"Encryption keys",status:"pass",message:"Public and private keys configured"});else if(A||h)_.push({name:"Encryption keys",status:"warn",message:"Incomplete keypair (run: buddy env:keypair)"});else _.push({name:"Encryption keys",status:"warn",message:"Not configured (optional)"})}catch(T){_.push({name:`${U} content`,status:"fail",message:`Cannot read file: ${T}`})}}else _.push({name:`${U} file`,status:"fail",message:"Not found"});let F=K(J0.cwd(),".env.keys");if(Z(F))_.push({name:".env.keys file",status:"pass",message:"Found"});else _.push({name:".env.keys file",status:"warn",message:"Not found (optional for encryption)"});console.log(""),console.log(Y("Environment Configuration Check:")),console.log(G("\u2500".repeat(60))),console.log("");let O=!1,M=!1;for(let T of _){let f="",P=(I)=>I;if(T.status==="pass")f="\u2713",P=z;else if(T.status==="warn")f="\u26A0",P=X,M=!0;else f="\u2717",P=W,O=!0;console.log(`${P(f)} ${Y(T.name.padEnd(25))} ${G(T.message)}`)}if(console.log(""),console.log(G("\u2500".repeat(60))),console.log(""),O)console.log(W("\u2717 Some critical checks failed. Please address the issues above.")),J0.exit(H0.FatalError);else if(M)console.log(X("\u26A0 Some checks have warnings. Your environment should work but may have issues.")),J0.exit(H0.Success);else console.log(z("\u2713 All checks passed! Your environment configuration looks healthy.")),J0.exit(H0.Success)}),p6(Q,"env")}import E2 from"process";import{runAction as t6}from"@stacksjs/actions";import{intro as e6,log as Z1,onUnknownSubcommand as $Q,outro as K1}from"@stacksjs/cli";import{Action as QQ}from"@stacksjs/enums";import{ExitCode as N2}from"@stacksjs/types";function _4(Q){let $={fresh:"Re-installs your npm dependencies",project:"Target a specific project",verbose:"Enable verbose output"};Q.command("fresh",$.fresh).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{if(Z1.debug("Running `buddy fresh` ...",J),!Q.isForce&&!Q.isNoInteraction){let{confirm:z}=await import("@stacksjs/cli");if(!await z({message:"This will remove and reinstall all dependencies. Continue?",initial:!1}))Z1.info("Fresh install cancelled"),E2.exit(N2.Success)}let Y=await e6("buddy fresh"),G=await t6(QQ.Fresh,{...J,stdout:"inherit"});if(G.isErr)await K1("While running `buddy fresh`, there was an issue",{startTime:Y,useSeconds:!0},G.error),E2.exit(N2.FatalError);await K1("Freshly reinstalled your dependencies",{startTime:Y,useSeconds:!0}),E2.exit(N2.Success)}),$Q(Q,"fresh")}import _1 from"process";import{generateComponentMeta as JQ,generateCoreSymlink as YQ,generateIdeHelpers as GQ,generateLibEntries as zQ,generateOpenApiSpec as WQ,generatePantryConfig as XQ,generateTypes as qQ,generateVsCodeCustomData as HQ,generateWebTypes as ZQ,invoke as KQ,watchTypes as _Q}from"@stacksjs/actions";import{intro as UQ,log as f0,onUnknownSubcommand as LQ,outro as FQ}from"@stacksjs/cli";import{ExitCode as U1}from"@stacksjs/types";function B4(Q){let $={command:"Automagically build any of your libraries/packages for production use. Select any of the following packages",types:"Generate your TypeScript types",entries:"Generate your function & Component Library Entry Points",webTypes:"Generate web-types.json for IDEs",customData:"Generate VS Code custom data (custom-elements.json) for IDEs",ideHelpers:"Generate IDE helpers",componentMeta:"Generate component meta information",coreSymlink:"Generate symlink of the core framework to the project root",pantry:"Generate the pantry configuration file",openApi:"Generate the OpenAPI specification",select:"What are you trying to generate?",project:"Target a specific project",verbose:"Enable verbose output"};Q.command("generate",$.command).option("-t, --types",$.types).option("-e, --entries",$.entries).option("-w, --web-types",$.webTypes).option("-c, --custom-data",$.customData).option("-i, --ide-helpers",$.ideHelpers).option("-c, --component-meta",$.componentMeta).option("-p, --pantry",$.pantry).option("-o, --openapi",$.openApi).option("-p, --project [project]",$.project,{default:!1}).option("--core-symlink",$.coreSymlink).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{f0.debug("Running `buddy generate` ...",J),await KQ(J),_1.exit(U1.Success)}),Q.command("generate:types",$.types).option("-p, --project [project]",$.project,{default:!1}).option("-w, --watch","Re-run on changes to models/ and config/",{default:!1}).option("--verbose",$.verbose,{default:!1}).alias("types:generate").action(async(J)=>{if(f0.debug("Running `buddy generate:types` ...",J),await qQ(J),J.watch)await _Q(J)}),Q.command("generate:entries",$.entries).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{f0.debug("Running `buddy generate:entries` ...",J),await zQ(J)}),Q.command("generate:web-types",$.webTypes).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{f0.debug("Running `buddy generate:web-types` ...",J),await ZQ(J)}),Q.command("generate:vscode-custom-data",$.customData).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{f0.debug("Running `buddy generate:vscode-custom-data` ...",J),await HQ(J)}),Q.command("generate:ide-helpers",$.ideHelpers).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{f0.debug("Running `buddy generate:ide-helpers` ...",J),await GQ(J)}),Q.command("generate:component-meta",$.componentMeta).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{f0.debug("Running `buddy generate:component-meta` ...",J),await JQ()}),Q.command("generate:pantry-config",$.pantry).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{f0.debug("Running `buddy generate:pantry-config` ...",J),await XQ()}),Q.command("generate:openapi-spec",$.openApi).alias("generate:openapi").option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{f0.debug("Running `buddy generate:openapi-spec` ...",J);let Y=await UQ("buddy generate:openapi-spec");await WQ(),await FQ("Generated OpenAPI specification",{startTime:Y,useSeconds:!0})}),Q.command("generate:migrations","Generate Migrations").action(async(J)=>{f0.debug("Running `buddy generate:migrations` ...",J);let{generateMigrations:Y}=await import("@stacksjs/database"),G=await Y();if(G?.isErr)f0.error("generateMigrations failed",G.error),_1.exit(U1.FatalError)}),Q.command("generate:core-symlink","Generate core symlink. A shortcut for core developers.").action(async(J)=>{f0.debug("Running `buddy core-symlink` ...",J),await YQ()}),LQ(Q,"generate")}import L1 from"process";import{log as p7}from"@stacksjs/cli";import{config as OQ}from"@stacksjs/config";import{HttxClient as VQ}from"@stacksjs/httx";import{ExitCode as F1}from"@stacksjs/types";function A4(Q){let $={http:"Send an HTTP request to a domain",project:"Target a specific project",verbose:"Enable verbose output"};Q.command("http [domain]",$.http).option("-p, --project [project]",$.project,{default:!1}).option("-v, --verbose",$.verbose,{default:!1}).action(async(J,Y)=>{p7.debug("Running `buddy http [domain]` ...",Y);let G=J||OQ.app.url,z=new VQ({verbose:Y.verbose});p7.info(`GET ${G}`),(await z.request(G.startsWith("http")?G:`https://${G}`,{method:"GET"})).match({ok:(X)=>{p7.info(`${X.status} ${X.statusText} (${X.timings.duration.toFixed(0)}ms)`),console.log(typeof X.data==="string"?X.data:JSON.stringify(X.data,null,2)),L1.exit(F1.Success)},err:(X)=>{p7.error(`Request failed: ${X.message}`),L1.exit(F1.FatalError)}})})}import BQ from"process";import{log as O1,onUnknownSubcommand as RQ,runCommand as wQ}from"@stacksjs/cli";import{path as MQ}from"@stacksjs/path";import{ExitCode as TQ}from"@stacksjs/types";function N4(Q){let $={install:"Install your dependencies",project:"Target a specific project",verbose:"Enable verbose output"};Q.command("install",$.install).option("-p, --project [project]",$.project,{default:!1}).option("-v, --verbose",$.verbose,{default:!1}).action(async(J)=>{O1.debug("Running `buddy install` ...",J);let Y=await wQ("bun install",{...J,cwd:MQ.projectPath()});if(Y&&typeof Y==="object"&&"isErr"in Y&&Y.isErr?.())O1.error("bun install failed"),BQ.exit(TQ.FatalError)}),RQ(Q,"install")}import IQ from"process";import{runAction as jQ}from"@stacksjs/actions";import{intro as AQ,log as V1,onUnknownSubcommand as PQ,outro as fQ}from"@stacksjs/cli";import{Action as vQ}from"@stacksjs/enums";import{ExitCode as SQ}from"@stacksjs/types";function x4(Q){let $={command:"Generate & set the application key.",project:"Target a specific project",verbose:"Enable verbose output"};Q.command("key:generate",$.command).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{V1.debug("Running `buddy key:generate` ...",J),await AQ("buddy key:generate");let Y=await jQ(vQ.KeyGenerate,J);if(Y.isErr)V1.error("Failed to set random application key.",Y.error),IQ.exit(SQ.FatalError);await fQ("Random application key set.")}),PQ(Q,"key")}import EQ from"process";import{intro as r7,log as S$,onUnknownSubcommand as NQ,outro as n7,runCommand as f$}from"@stacksjs/cli";import{path as v$}from"@stacksjs/path";import{ExitCode as CQ}from"@stacksjs/types";function a7(Q,$){if(!Q||typeof Q!=="object"||!("isErr"in Q))return;let J=Q.isErr;if(typeof J==="function"?J():J===!0)S$.error(`${$} reported failure`),EQ.exit(CQ.FatalError)}function d4(Q){let $={lint:"Automagically lints your project codebase",lintFix:"Automagically fixes all lint errors",format:"Format your project codebase",formatCheck:"Check formatting without making changes",project:"Target a specific project",verbose:"Enable verbose output"};Q.command("lint",$.lint).option("-f, --fix",$.lintFix,{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{S$.debug("Running `buddy lint` ...",J);let Y=await r7("buddy lint"),G=J.fix?await f$("bun storage/framework/core/actions/src/lint/fix.ts",{cwd:v$.projectPath()}):await f$("bun storage/framework/core/actions/src/lint/index.ts",{cwd:v$.projectPath()});a7(G,"lint"),await n7("Linted your project",{startTime:Y,useSeconds:!0})}),Q.command("lint:fix",$.lintFix).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{S$.debug("Running `buddy lint:fix` ...",J);let Y=await r7("buddy lint:fix");S$.info("Fixing lint errors...");let G=await f$("bun storage/framework/core/actions/src/lint/fix.ts",{cwd:v$.projectPath()});a7(G,"lint:fix"),await n7("Fixed lint errors",{startTime:Y,useSeconds:!0})}),Q.command("format",$.format).option("-w, --write","Write changes to files",{default:!1}).option("-c, --check",$.formatCheck,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{S$.debug("Running `buddy format` ...",J);let Y=await r7("buddy format"),G=J.check?await f$("bunx --bun pickier run --mode format --config ./pickier.config.ts --check",{cwd:v$.projectPath()}):await f$("bunx --bun pickier run --mode format --config ./pickier.config.ts --write",{cwd:v$.projectPath()});a7(G,"format"),await n7("Formatted your project",{startTime:Y,useSeconds:!0})}),Q.command("format:check",$.formatCheck).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{S$.debug("Running `buddy format:check` ...",J);let Y=await r7("buddy format:check"),G=await f$("bunx --bun pickier run --mode format --config ./pickier.config.ts --check",{cwd:v$.projectPath()});a7(G,"format:check"),await n7("Format check complete",{startTime:Y,useSeconds:!0})}),NQ(Q,"lint")}import{log as hQ}from"@stacksjs/logging";import{onUnknownSubcommand as DQ}from"@stacksjs/cli";function a4(Q){let $={list:"List all available Buddy commands",project:"Target a specific project",verbose:"Enable verbose output",filter:"Filter commands by name or group",namespace:"Filter commands by namespace (e.g., make, env, db)",grouped:"Group commands by category",format:"Output format (text, json)"};Q.command("list",$.list).option("-p, --project [project]",$.project,{default:!1}).option("-f, --filter [filter]",$.filter).option("-n, --namespace [namespace]",$.namespace).option("-g, --grouped",$.grouped,{default:!0}).option("--format [format]",$.format,{default:"text"}).option("--verbose",$.verbose,{default:!1}).example("buddy list").example("buddy list --filter=make").example("buddy list --namespace=make").example("buddy list --namespace=env").example("buddy list --no-grouped").example("buddy list --format=json").action(async(J)=>{hQ.debug("Running `buddy list` ...",J);let{bold:Y,dim:G,green:z}=await import("@stacksjs/cli"),W=Q.commands||[],X=W;if(J.filter){let H=String(J.filter).toLowerCase();X=W.filter((q)=>{let Z=q.name||"",K=q.description||"";return Z.toLowerCase().includes(H)||K.toLowerCase().includes(H)})}if(J.namespace){let H=String(J.namespace).toLowerCase();X=X.filter((q)=>{return(q.namespace||"").toLowerCase()===H})}if(X.length===0){if(J.format==="json")console.log(JSON.stringify({commands:[],total:0},null,2));else if(console.log(G("No commands found")),J.filter)console.log(G(`Try removing the filter: ${J.filter}`));return}if(J.format==="json"){let H=X.map((q)=>({name:q.name||"",description:q.description||"",aliases:q.aliasNames||[]}));console.log(JSON.stringify({commands:H,total:H.length},null,2));return}if(J.grouped){let H=new Map;for(let Z of X){let K=Z.name||"";if(!K)continue;let _="General";if(K.includes(":"))_=K.split(":")[0];else if(["dev","build","test","lint"].includes(K))_="Development";else if(["deploy","release","publish"].includes(K))_="Deployment";else if(["migrate","seed","fresh"].includes(K))_="Database";else if(["doctor","about","version"].includes(K))_="Info";if(!H.has(_))H.set(_,[]);H.get(_).push(Z)}console.log(""),console.log(Y(z("Available Commands:"))),console.log("");let q=Array.from(H.entries()).sort((Z,K)=>{let _=["Development","General","Info"],U=_.indexOf(Z[0]),L=_.indexOf(K[0]);if(U>=0&&L>=0)return U-L;if(U>=0)return-1;if(L>=0)return 1;return Z[0].localeCompare(K[0])});for(let[Z,K]of q){console.log(Y(`${Z}:`)),K.sort((_,U)=>(_.name||"").localeCompare(U.name||""));for(let _ of K){let U=(_.name||"").padEnd(20),L=_.description||"";console.log(` ${z(U)} ${G(L)}`)}console.log("")}}else{console.log(""),console.log(Y(z("Available Commands:"))),console.log(""),X.sort((H,q)=>(H.name||"").localeCompare(q.name||""));for(let H of X){let q=(H.name||"").padEnd(20),Z=H.description||"";console.log(` ${z(q)} ${G(Z)}`)}console.log("")}console.log(G(`Total: ${X.length} commands`)),console.log("")}),DQ(Q,"list")}import{log as S}from"@stacksjs/cli";import{ExitCode as g}from"@stacksjs/types";import{createHash as SJ,randomBytes as W9}from"crypto";import{readFileSync as X9,existsSync as q9}from"fs";import{execSync as B$}from"child_process";function zq(Q){Q.command("mail:user:add <email>","Add a mail user").option("--password <password>","User password (generated if not provided)").action(async($,J)=>{S.info(`Adding mail user: ${$}`);try{let Y=J.password||W9(16).toString("base64").replace(/[+/=]/g,"").substring(0,16),G=SJ("sha256").update(Y).digest("hex"),W=`${(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-")}-mail-users`,{DynamoDBClient:X}=await import("@stacksjs/ts-cloud");if(await new X(process.env.AWS_REGION||"us-east-1").putItem({TableName:W,Item:{email:{S:$.toLowerCase()},passwordHash:{S:G},createdAt:{S:new Date().toISOString()}}}),S.success(`User ${$} added successfully!`),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"),console.log(" MAIL CREDENTIALS"),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"),console.log(""),console.log(` Email: ${$}`),console.log(` Password: ${Y}`),console.log(""),console.log(" To connect with Mail.app, run:"),console.log(" buddy mail:proxy"),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"),console.log(""),!J.password)S.warn("Save this password! It will not be shown again.");process.exit(g.Success)}catch(Y){S.error(`Failed to add user: ${Y.message}`),process.exit(g.FatalError)}}),Q.command("mail:user:list","List mail users").action(async()=>{try{let J=`${(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-")}-mail-users`,{DynamoDBClient:Y}=await import("@stacksjs/ts-cloud"),z=await new Y(process.env.AWS_REGION||"us-east-1").scan({TableName:J});if(console.log(""),console.log("Mail Users:"),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),!z.Items||z.Items.length===0)console.log(" No users found");else for(let W of z.Items){let X=W.email?.S||"unknown",H=W.createdAt?.S||"unknown";console.log(` \uD83D\uDCE7 ${X}`),console.log(` Created: ${H}`)}console.log(""),process.exit(g.Success)}catch($){S.error(`Failed to list users: ${$.message}`),process.exit(g.FatalError)}}),Q.command("mail:user:delete <email>","Delete a mail user").action(async($)=>{try{let Y=`${(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-")}-mail-users`,{DynamoDBClient:G}=await import("@stacksjs/ts-cloud");await new G(process.env.AWS_REGION||"us-east-1").deleteItem({TableName:Y,Key:{email:{S:$.toLowerCase()}}}),S.success(`User ${$} deleted`),process.exit(g.Success)}catch(J){S.error(`Failed to delete user: ${J.message}`),process.exit(g.FatalError)}}),Q.command("mail:proxy","Start local IMAP proxy for Mail.app").option("--port <port>","IMAP proxy port",{default:"1993"}).option("--api <url>","Mail API URL").action(async($)=>{S.info("Starting IMAP proxy...");try{let J=$.api;if(!J){let{AWSCloudFormationClient:z}=await import("@stacksjs/ts-cloud"),W=new z(process.env.AWS_REGION||"us-east-1"),H=`${(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-")}-cloud`;try{J=((await W.describeStacks({stackName:H})).Stacks?.[0]?.Outputs||[]).find((_)=>_.OutputKey==="MailApiUrl")?.OutputValue}catch(q){}}if(!J)S.error("Mail API URL not found. Run `buddy deploy` first to create the mail infrastructure."),process.exit(g.FatalError);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"),console.log(" IMAP PROXY"),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"),console.log(""),console.log(` API URL: ${J}`),console.log(` Port: ${$.port}`),console.log(""),console.log(" Configure Mail.app with:"),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(" Account Type: IMAP"),console.log(" Incoming Server: localhost"),console.log(` Incoming Port: ${$.port}`),console.log(" SSL: No (local connection)"),console.log(" Outgoing Server: localhost"),console.log(` Outgoing Port: ${$.port}`),console.log(" Username: your-email@stacksjs.com"),console.log(" Password: your-password"),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"),console.log(""),process.env.MAIL_API_URL=J,process.env.IMAP_PORT=$.port;let{ImapProxy:Y}=await import("../../mail-server/src/proxy/imap-proxy"),G=new Y(Number.parseInt($.port,10),J);await G.start(),process.on("SIGINT",()=>{console.log(`
368
+ Shutting down proxy...`),G.stop(),process.exit(0)})}catch(J){S.error(`Failed to start proxy: ${J.message}`),process.exit(g.FatalError)}}),Q.command("mail:test","Test mail API connection").action(async()=>{try{let{AWSCloudFormationClient:$}=await import("@stacksjs/ts-cloud"),J=new $(process.env.AWS_REGION||"us-east-1"),G=`${(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-")}-cloud`,X=((await J.describeStacks({stackName:G})).Stacks?.[0]?.Outputs||[]).find((Z)=>Z.OutputKey==="MailApiUrl");if(!X?.OutputValue)S.error("Mail API not deployed. Run `buddy deploy` first."),process.exit(g.FatalError);let H=X.OutputValue;S.info(`Testing Mail API at ${H}`);let q=await fetch(`${H}/mailboxes`,{headers:{Authorization:`Basic ${Buffer.from("test@stacksjs.com:test").toString("base64")}`}});if(q.status===401)S.success("Mail API is responding (auth required)");else if(q.ok){S.success("Mail API is working!");let Z=await q.json();console.log("Response:",JSON.stringify(Z,null,2))}else S.warn(`Mail API returned status ${q.status}`);process.exit(g.Success)}catch($){S.error(`Failed to test API: ${$.message}`),process.exit(g.FatalError)}}),Q.command("mail:credentials [email]","Show SMTP credentials for email access").action(async($)=>{h$();let J=process.env.APP_DOMAIN||process.env.MAIL_DOMAIN||"stacksjs.com",Y=`mail.${J}`,G=$||`chris@${J}`,z=G.includes("@")?G.split("@")[0]:G,W=`MAIL_PASSWORD_${z.toUpperCase()}`,X=process.env[W];if(console.log(""),console.log("=========================================================="),console.log(` EMAIL CREDENTIALS \u2014 ${G}`),console.log("=========================================================="),console.log(""),console.log(` Email: ${G}`),console.log(` Host: ${Y}`),console.log(" Port: 587"),console.log(" Security: STARTTLS"),console.log(` Username: ${z}`),X)console.log(` Password: ${X}`);else console.log(` Password: (not set \u2014 add ${W} to .env.production)`);console.log(""),console.log("=========================================================="),console.log(""),process.exit(g.Success)}),Q.command("mail:logs","Show mail server logs from production").option("-n, --lines <count>","Number of log lines to show",{default:"50"}).option("-f, --follow","Follow log output (poll every 5s)").option("--filter <pattern>","Filter logs by pattern (e.g. AUTH, LOGIN, error)").action(async($)=>{h$();let J=process.env.AWS_REGION||"us-east-1",Y=(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-");try{let{EC2Client:G,SSMClient:z}=await import("@stacksjs/ts-cloud"),W=new G(J),X=new z(J);S.info("Finding mail server...");let q=(await W.describeInstances({Filters:[{Name:"tag:Name",Values:[`${Y}-mail-server`]},{Name:"instance-state-name",Values:["running"]}]})).Reservations?.[0]?.Instances?.[0]?.InstanceId;if(!q)S.error("No running mail server found."),S.info(`Looked for instances tagged: ${Y}-mail-server`),process.exit(g.FatalError);S.info(`Found instance: ${q}`);let Z=$.lines||"50",K=$.filter?$.filter.replace(/[^a-zA-Z0-9_.@\s-]/g,""):"",_=K?` | grep -iE '${K}'`:"",U=async()=>{let L=`journalctl -u smtp-server -u mail-server --no-pager -n ${Z} --since "10 minutes ago" 2>&1${_}`,F=await X.runShellCommand(q,[L],{timeoutSeconds:30,maxWaitMs:30000,pollIntervalMs:2000});if(!F.success)return S.error(`Failed to fetch logs: ${F.error||"Unknown error"}`),!1;if(F.output){let O=F.output.trim().split(`
369
+ `);for(let M of O)if(M.includes("error")||M.includes("Error")||M.includes("AUTH failed"))console.log(` \x1B[31m${M}\x1B[0m`);else if(M.includes("warning")||M.includes("Warning"))console.log(` \x1B[33m${M}\x1B[0m`);else if(M.includes("AUTH success")||M.includes("LOGIN completed")||M.includes("authenticated"))console.log(` \x1B[32m${M}\x1B[0m`);else console.log(` ${M}`)}else console.log(" No log entries found.");return!0};if(console.log(""),console.log("=========================================================="),console.log(" MAIL SERVER LOGS"),console.log("=========================================================="),console.log(""),await U(),$.follow){console.log(""),S.info("Following logs (Ctrl+C to stop)...");let L=!1,F=setInterval(()=>{if(L)return;L=!0,console.log(""),U().catch((O)=>S.error("Log polling failed:",O)).finally(()=>{L=!1})},5000);await new Promise((O)=>{process.on("SIGINT",()=>{clearInterval(F),O()})})}console.log(""),process.exit(g.Success)}catch(G){S.error(`Failed to fetch logs: ${G.message}`),process.exit(g.FatalError)}}),Q.command("mail:status","Show mail server status").action(async()=>{h$();let $=process.env.AWS_REGION||"us-east-1",J=(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-");try{let{EC2Client:Y,SSMClient:G}=await import("@stacksjs/ts-cloud"),z=new Y($),W=new G($),H=(await z.describeInstances({Filters:[{Name:"tag:Name",Values:[`${J}-mail-server`]},{Name:"instance-state-name",Values:["running"]}]})).Reservations?.[0]?.Instances?.[0]?.InstanceId;if(!H)S.error("No running mail server found."),S.info(`Looked for instances tagged: ${J}-mail-server`),process.exit(g.FatalError);let q=await W.runShellCommand(H,["echo === Service ===","(systemctl status smtp-server --no-pager 2>&1 || systemctl status mail-server --no-pager 2>&1) | head -15","echo === Ports ===",'ss -tlnp 2>&1 | grep -E "(25|587|465|993|143|110|995)" || echo "No mail ports listening"',"echo === Memory ===",`ps aux | grep -E "(smtp-server|bun|mail)" | grep -v grep | awk '{print $6/1024 "MB", $11}'`],{timeoutSeconds:30,maxWaitMs:30000,pollIntervalMs:2000});if(console.log(""),console.log("=========================================================="),console.log(" MAIL SERVER STATUS"),console.log("=========================================================="),console.log(""),q.success&&q.output)for(let Z of q.output.trim().split(`
370
+ `))console.log(` ${Z}`);else S.error(`Failed: ${q.error}`);console.log(""),process.exit(g.Success)}catch(Y){S.error(`Failed to get status: ${Y.message}`),process.exit(g.FatalError)}}),Q.command("mail:port25:request","Request port 25 unblock for direct SMTP delivery").option("--provider <provider>","Cloud provider: aws or hetzner",{default:"aws"}).option("--instance-id <id>","AWS EC2 instance ID (auto-detected if not provided)").option("--server-id <id>","Hetzner server ID (auto-detected if not provided)").option("--elastic-ip <ip>","AWS Elastic IP address").option("--rdns <hostname>","Reverse DNS hostname (e.g. mail.stacksjs.com)").option("--use-case <text>","Description of email use case").action(async($)=>{h$();let J=process.env.APP_DOMAIN||process.env.MAIL_DOMAIN||"stacksjs.com",Y=$.provider.toLowerCase();if(Y==="aws")await EJ($,J);else if(Y==="hetzner")await NJ($,J);else S.error(`Unknown provider: ${Y}. Use 'aws' or 'hetzner'.`),process.exit(g.FatalError)}),Q.command("mail:port25:status","Check outbound port 25 status on the mail server").option("--provider <provider>","Cloud provider: aws or hetzner",{default:"aws"}).action(async($)=>{h$();let J=process.env.AWS_REGION||"us-east-1",Y=(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-");if($.provider==="hetzner"){let G=process.env.HETZNER_API_TOKEN;if(!G)S.error("HETZNER_API_TOKEN not set"),process.exit(g.FatalError);try{let H=(await(await fetch("https://api.hetzner.cloud/v1/servers?label_selector=service=mail",{headers:{Authorization:`Bearer ${G}`}})).json()).servers?.[0]?.public_net?.ipv4?.ip;if(!H){let K=(await(await fetch("https://api.hetzner.cloud/v1/servers",{headers:{Authorization:`Bearer ${G}`}})).json()).servers?.find((_)=>_.name?.includes("mail"));if(K){let _=K.public_net?.ipv4?.ip;S.info(`Found Hetzner server: ${K.name} (${_})`);let U=B$(`ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 root@${_} "timeout 5 bash -c 'echo QUIT > /dev/tcp/gmail-smtp-in.l.google.com/25' 2>&1 && echo PORT_25_OPEN || echo PORT_25_BLOCKED"`,{encoding:"utf-8"});a2(U.trim(),"Hetzner",_)}else S.error("No mail server found on Hetzner")}else{let q=B$(`ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 root@${H} "timeout 5 bash -c 'echo QUIT > /dev/tcp/gmail-smtp-in.l.google.com/25' 2>&1 && echo PORT_25_OPEN || echo PORT_25_BLOCKED"`,{encoding:"utf-8"});a2(q.trim(),"Hetzner",H)}}catch(z){S.error(`Failed: ${z.message}`)}process.exit(g.Success)}try{let{EC2Client:G,SSMClient:z}=await import("@stacksjs/ts-cloud"),W=new G(J),X=new z(J),q=(await W.describeInstances({Filters:[{Name:"tag:Name",Values:[`${Y}-mail-server`]},{Name:"instance-state-name",Values:["running"]}]})).Reservations?.[0]?.Instances?.[0],Z=q?.InstanceId;if(!Z)S.error("No running mail server found."),process.exit(g.FatalError);let K=q?.PublicIpAddress||"unknown";S.info(`Testing port 25 on ${Z} (${K})...`);let _=await X.runShellCommand(Z,['timeout 5 bash -c "echo QUIT > /dev/tcp/gmail-smtp-in.l.google.com/25" 2>&1 && echo PORT_25_OPEN || echo PORT_25_BLOCKED'],{timeoutSeconds:15,maxWaitMs:20000,pollIntervalMs:2000});a2(_.output?.trim()||"PORT_25_BLOCKED","AWS",K),process.exit(g.Success)}catch(G){S.error(`Failed: ${G.message}`),process.exit(g.FatalError)}}),Q.command("mail:server","Start SMTP relay server").option("--port <port>","SMTP port",{default:"587"}).action(async($)=>{h$();let J=process.env.APP_DOMAIN||process.env.MAIL_DOMAIN||"stacksjs.com",Y=Number.parseInt($.port,10),G=["chris","blake","glenn"],z={},W=[];for(let X of G){let H=`MAIL_PASSWORD_${X.toUpperCase()}`,q=process.env[H];if(!q)q=W9(16).toString("base64url"),W.push(`${H}=${q}`);z[X]={password:q,email:`${X}@${J}`}}if(W.length>0){console.log(""),S.warn("Generated missing passwords. Add these to .env.production:");for(let X of W)console.log(` ${X}`)}console.log(""),console.log("=========================================================="),console.log(" SMTP RELAY SERVER"),console.log("=========================================================="),console.log(""),console.log(` Host: mail.${J}`),console.log(` Port: ${Y}`),console.log(` Domain: ${J}`),console.log(""),console.log(" Mailboxes:");for(let[X,H]of Object.entries(z))console.log(` ${X} (${H.email})`);console.log(""),console.log(" Relaying through AWS SES"),console.log("=========================================================="),console.log("");try{let{SmtpServer:X}=await Promise.resolve().then(() => (z9(),G9)),H=new X({port:Y,host:"0.0.0.0",domain:J,users:z,sentBucket:"stacks-production-email",sentPrefix:"sent/"});await H.start(),await new Promise((q)=>{process.on("SIGINT",async()=>{console.log(`
371
+ Shutting down SMTP server...`),await H.stop(),q()})}),process.exit(0)}catch(X){S.error(`Failed to start SMTP server: ${X.message}`),process.exit(g.FatalError)}})}function h$(){if(q9(".env.production")){let $=X9(".env.production","utf-8");for(let J of $.split(`
372
+ `)){let Y=J.indexOf("=");if(Y>0&&!J.startsWith("#")){let G=J.slice(0,Y).trim(),z=J.slice(Y+1).trim();if(!process.env[G])process.env[G]=z}}}if(!process.env.AWS_ACCESS_KEY_ID||!process.env.AWS_SECRET_ACCESS_KEY){let J=`${process.env.HOME||process.env.USERPROFILE||""}/.aws/credentials`;if(q9(J)){let Y=X9(J,"utf-8"),G=process.env.AWS_PROFILE||"default",z=Y.split(`
373
+ `),W=!1;for(let X of z){let H=X.trim();if(H.startsWith("[")){W=H===`[${G}]`;continue}if(W&&H.includes("=")){let q=H.indexOf("="),Z=H.slice(0,q).trim(),K=H.slice(q+1).trim();if(Z==="aws_access_key_id")process.env.AWS_ACCESS_KEY_ID=K;if(Z==="aws_secret_access_key")process.env.AWS_SECRET_ACCESS_KEY=K}}}}}function a2(Q,$,J){if(console.log(""),console.log("=========================================================="),console.log(" PORT 25 STATUS"),console.log("=========================================================="),console.log(""),console.log(` Provider: ${$}`),console.log(` Server IP: ${J}`),Q.includes("PORT_25_OPEN"))console.log(" Port 25: \x1B[32mOPEN\x1B[0m"),console.log(""),console.log(" Direct SMTP delivery is available!"),console.log(" Set SMTP_DELIVERY_METHOD=direct in your server env.");else console.log(" Port 25: \x1B[31mBLOCKED\x1B[0m"),console.log(""),console.log(` Run: buddy mail:port25:request --provider ${$.toLowerCase()}`);console.log(""),console.log("=========================================================="),console.log("")}async function EJ(Q,$){let J=process.env.AWS_REGION||"us-east-1",Y=(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-"),G=Q.instanceId,z=Q.elasticIp;if(!G||!z)try{let{EC2Client:q}=await import("@stacksjs/ts-cloud"),_=(await new q(J).describeInstances({Filters:[{Name:"tag:Name",Values:[`${Y}-mail-server`]},{Name:"instance-state-name",Values:["running"]}]})).Reservations?.[0]?.Instances?.[0];if(_)G=G||_.InstanceId,z=z||_.PublicIpAddress}catch{}let W=Q.rdns||`mail.${$}`,X=Q.useCase||[`We run a self-hosted mail server (mail.${$}) for our organization.`,"We send transactional emails (account notifications, password resets) and","occasional team communication. Expected volume: <1000 emails/day.","We have SPF, DKIM, and DMARC configured. We need outbound port 25","to deliver email directly to recipient mail servers via MX records."].join(" ");console.log(""),console.log("=========================================================="),console.log(" AWS PORT 25 UNBLOCK REQUEST"),console.log("=========================================================="),console.log(""),console.log(` Instance: ${G||"(not detected)"}`),console.log(` Elastic IP: ${z||"(not detected)"}`),console.log(` Reverse DNS: ${W}`),console.log(` Region: ${J}`),console.log("");try{let q=B$(`aws support create-case --subject "Request to remove email sending limitations" --communication-body "${X}
374
+
375
+ Elastic IP: ${z||"N/A"}
376
+ Instance ID: ${G||"N/A"}
377
+ Reverse DNS: ${W}
378
+ Region: ${J}" --service-code "amazon-ec2" --category-code "port-25-throttle" --severity-code "normal" --cc-email-addresses "" --language "en" --region us-east-1 2>&1`,{encoding:"utf-8"});if(q.includes("caseId"))try{let Z=JSON.parse(q).caseId;S.success(`Support case created: ${Z}`),S.info(""),S.info(" AWS will process this within 24-48 hours."),S.info(" Check status: aws support describe-cases --region us-east-1"),S.info(""),process.exit(g.Success)}catch{S.error("Failed to parse AWS support case response")}}catch{}if(z){S.info("Setting up reverse DNS (rDNS) for Elastic IP...");try{let q=B$(`aws ec2 describe-addresses --public-ips ${z} --region ${J} --query 'Addresses[0].AllocationId' --output text 2>&1`,{encoding:"utf-8"}).trim();if(q&&!q.includes("error"))B$(`aws ec2 modify-address-attribute --allocation-id ${q} --domain-name ${W} --region ${J} 2>&1`,{encoding:"utf-8"}),S.success(`Reverse DNS requested: ${z} -> ${W}`),console.log(" (rDNS propagation may take a few minutes)")}catch(q){S.warn(`rDNS setup failed: ${q.message}`),console.log(" You may need to set this up manually in the AWS console.")}}console.log(""),console.log(" The Support API requires a Business or Enterprise support plan."),console.log(" Opening the AWS web form instead..."),console.log(""),console.log(" Fill in these details:"),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(` Email address: admin@${$}`),console.log(" Use case: Sending outbound email from self-hosted mail server"),console.log(` Elastic IP: ${z||"(enter your Elastic IP)"}`),console.log(` rDNS: ${W}`),console.log(` Region: ${J}`),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log("");let H="https://console.aws.amazon.com/support/contacts#/rdns-limits";try{B$(`open "${H}" 2>/dev/null || xdg-open "${H}" 2>/dev/null || echo ""`,{encoding:"utf-8"}),S.info(`Opened: ${H}`)}catch{console.log(" Open this URL in your browser:"),console.log(` ${H}`)}console.log(""),console.log(" After AWS approves (24-48 hours), verify with:"),console.log(" buddy mail:port25:status"),console.log(""),process.exit(g.Success)}async function NJ(Q,$){let J=process.env.HETZNER_API_TOKEN;if(!J)S.error("HETZNER_API_TOKEN not set. Add it to .env or set it as an environment variable."),process.exit(g.FatalError);let Y=Q.serverId,G="",z="";try{let Z=await(await fetch("https://api.hetzner.cloud/v1/servers",{headers:{Authorization:`Bearer ${J}`}})).json(),K=Z.servers?.find((_)=>_.name?.includes("mail"))||Z.servers?.[0];if(K)Y=Y||String(K.id),G=K.public_net?.ipv4?.ip||"",z=K.name||""}catch{}let W=Q.rdns||`mail.${$}`,X=Q.useCase||[`Self-hosted mail server for ${$}.`,"Transactional + team email, <1000 emails/day.","SPF/DKIM/DMARC configured."].join(" ");if(console.log(""),console.log("=========================================================="),console.log(" HETZNER PORT 25 UNBLOCK REQUEST"),console.log("=========================================================="),console.log(""),console.log(` Server: ${z} (ID: ${Y||"unknown"})`),console.log(` Server IP: ${G||"(not detected)"}`),console.log(` rDNS: ${W}`),console.log(""),Y&&G){S.info("Setting reverse DNS...");try{let Z=await(await fetch(`https://api.hetzner.cloud/v1/servers/${Y}/actions/change_dns_ptr`,{method:"POST",headers:{Authorization:`Bearer ${J}`,"Content-Type":"application/json"},body:JSON.stringify({ip:G,dns_ptr:W})})).json();if(Z.action?.status==="running"||Z.action?.status==="success")S.success(`Reverse DNS set: ${G} -> ${W}`);else S.warn(`rDNS response: ${JSON.stringify(Z.error||Z)}`)}catch(q){S.warn(`rDNS failed: ${q.message}`)}}console.log(""),console.log(" To request port 25 unblock from Hetzner:"),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(" 1. Log in to https://console.hetzner.cloud"),console.log(` 2. Select project containing server "${z}"`),console.log(" 3. Go to Support (left sidebar) -> New support request"),console.log(" 4. Use this template:"),console.log(""),console.log(" Subject: Request to unblock outbound port 25 (SMTP)"),console.log(""),console.log(" Body:"),console.log(" \u2500\u2500\u2500\u2500\u2500"),console.log(` Server: ${z} (ID: ${Y}, IP: ${G})`),console.log(` Use case: ${X}`),console.log(` Reverse DNS: ${G} -> ${W}`),console.log(" We comply with all anti-spam regulations (CAN-SPAM, GDPR)."),console.log(" Please unblock outbound ports 25 and 465 for this server."),console.log(" \u2500\u2500\u2500\u2500\u2500"),console.log(""),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");let H="https://console.hetzner.cloud";try{B$(`open "${H}" 2>/dev/null || xdg-open "${H}" 2>/dev/null || echo ""`,{encoding:"utf-8"}),S.info(`Opened: ${H}`)}catch{console.log(` Open: ${H}`)}console.log(""),console.log(" After Hetzner approves, verify with:"),console.log(" buddy mail:port25:status --provider hetzner"),console.log(""),process.exit(g.Success)}import u from"process";import{createMiddleware as CJ,createMigration as hJ,createModel as H9,createNotification as Z9,createPage as DJ,invoke as bJ,makeAction as K9,makeCertificate as _9,makeCommand as U9,makeComponent as L9,makeDatabase as F9,makeFunction as O9,makeJob as V9,makeLanguage as B9,makePage as yJ,makePolicy as R9,makeQueueTable as w9,makeResource as M9,makeStack as T9,setDryRun as i2}from"@stacksjs/actions";import{intro as B7,italic as R7,onUnknownSubcommand as kJ,outro as y0}from"@stacksjs/cli";import{log as C}from"@stacksjs/logging";import{ExitCode as m}from"@stacksjs/types";function _q(Q){let $={action:"Create a new action",command:"Create a new CLI command",model:"Create a new model",middleware:"Create a new middleware",component:"Create a new component",page:"Create a new page",function:"Create a new function",job:"Create a new job",language:"Create a new language",database:"Create a new database",migration:"Create a new migration",factory:"Create a new factory",notification:"Create a new notification",policy:"Create a new authorization policy",resource:"Create a new API resource",name:"The name of the action",queue:"Make queue migration",stack:"Create a new stack",certificate:"Create a new SSL Certificate",select:"What are you trying to make?",project:"Target a specific project",verbose:"Enable verbose output"};Q.command("make [make]","The make command").option("-a, --action [action]",$.action,{default:!1}).option("-c, --component [component]",$.component,{default:!1}).option("-d, --database [database]",$.database,{default:!1}).option("-f, --factory [factory]",$.factory,{default:!1}).option("-f, --function [function]",$.function,{default:!1}).option("-l, --language [language]",$.language,{default:!1}).option("-m, --model [model]",$.model,{default:!1}).option("-mw, --middleware [middleware]",$.middleware,{default:!1}).option("-p, --page [page]",$.page,{default:!1}).option("-m, --migration [migration]",$.migration,{default:!1}).option("-n, --notification [notification]",$.notification,{default:!1}).option("-qt, --queue-table",$.queue,{default:!1}).option("-s, --stack [stack]",$.stack,{default:!1}).option("--dry-run","Preview the files that would be generated without writing",{default:!1}).option("--with-validation","Include a validation rules block in the generated stub",{default:!1}).option("--with-auth","Include auth-aware boilerplate in the generated stub",{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J,Y)=>{if(C.debug("Running `buddy make` ...",Y),!Q.args[0])C.error("You need to specify a name. Read more about the documentation here."),u.exit(m.FatalError);if(i2(Boolean(Y.dryRun||Y["dry-run"])),J)switch(Y.name=Q.args[1],J){case"action":await K9(Y);break;case"certificate":await _9();break;case"command":await U9(Y);break;case"component":await L9(Y);break;case"database":F9(Y);break;case"function":await O9(Y);break;case"job":await V9(Y);break;case"language":await B9(Y);break;case"migration":await hJ(Y);break;case"middleware":await CJ(Y);break;case"model":await H9(Y);break;case"page":await DJ(Y);break;case"notification":await Z9(Y);break;case"policy":await R9(Y);break;case"resource":await M9(Y);break;case"queue-table":await w9();break;case"stack":await T9(Y);break;default:}await bJ(Y),u.exit(m.Success)}),Q.command("make:action [name]",$.action).option("-n, --name [name]",$.name,{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--dry-run","Preview the file without writing",{default:!1}).option("--with-validation","Generate a stub that calls validate()",{default:!1}).option("--with-auth","Generate a stub that requires an authenticated user",{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J,Y)=>{if(C.info("Running `buddy make:action` ..."),C.debug("Running `buddy make:action` ...",J,Y),J=J??Y.name,Y.name=J,!J)C.error("You need to specify a name. Read more about the documentation here."),u.exit(m.FatalError);i2(Boolean(Y.dryRun||Y["dry-run"])),await K9(Y)}),Q.command("make:certificate",$.certificate).alias("make:cert").example("buddy make:certificate").action(async(J)=>{C.debug("Running `buddy make:certificate` ...",J),await _9()}),Q.command("scaffold:crud [name]","Generate model, migration, and CRUD actions").alias("make:crud").alias("make:scaffold").option("-n, --name [name]","Resource name (PascalCase)",{default:!1}).option("-f, --fields [fields]","Comma-separated field list, e.g. title:string,body:text,published:boolean",{default:""}).option("--dry-run","Preview the generated files without writing",{default:!1}).option("--verbose",$.verbose,{default:!1}).example("buddy scaffold:crud Post --fields=title:string,body:text,published:boolean").action(async(J,Y)=>{if(J=J??Y.name,!J)C.error("scaffold:crud requires a resource name. Example: buddy scaffold:crud Post --fields=title:string,body:text"),u.exit(m.FatalError);let{scaffoldCrud:G}=await import("@stacksjs/actions");i2(Boolean(Y.dryRun||Y["dry-run"]));try{await G(J,Y)}catch(z){C.error("scaffold:crud failed:",z),u.exit(m.FatalError)}}),Q.command("make:command [name]",$.command).option("-n, --name [name]",$.name,{default:!1}).option("-s, --signature [signature]","The command signature (CLI name)",{default:!1}).option("-d, --description [description]","The command description",{default:!1}).option("--no-register","Do not register in Commands.ts").option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).example("buddy make:command SendEmails").example("buddy make:command SendEmails --signature=send-emails").action(async(J,Y)=>{C.debug("Running `buddy make:command` ...",Y);let G=await B7("buddy make:command");if(J=J??Y.name,Y.name=J,!J)C.error("You need to specify a command name."),C.info("Example: buddy make:command SendEmails"),u.exit(m.FatalError);if(!await U9(Y))await y0("While running the make:command command, there was an issue",{startTime:G,useSeconds:!0}),u.exit(m.FatalError);await y0(`Created your ${R7(J)} command.`,{startTime:G,useSeconds:!0}),u.exit(m.Success)}),Q.command("make:component [name]",$.component).option("-n, --name [name]",$.name,{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J,Y)=>{if(C.debug("Running `buddy make:component` ...",Y),J=J??Y.name,Y.name=J,!J)C.error("You need to specify a name. Read more about the documentation here."),u.exit(m.FatalError);await L9(Y)}),Q.command("make:database [name]",$.database).option("-n, --name [name]",$.name,{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action((J,Y)=>{if(C.debug("Running `buddy make:database` ...",Y),J=J??Y.name,Y.name=J,!J)C.error("You need to specify a database name via the `--name` option, or as the command\u2019s argument."),C.info("Example: `buddy make:database my-cool-database`"),C.info("Or: `buddy make:database --name=my-cool-database`"),C.info("Read more about the documentation here: https://stacksjs.com/docs/make/database"),u.exit(m.FatalError);F9(Y)}),Q.command("make:factory [name]",$.factory).option("-n, --name [name]",$.name,{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action((J,Y)=>{if(C.debug("Running `buddy make:factory` ...",Y),J=J??Y.name,Y.name=J,!J)C.error("You need to specify a name. Read more about the documentation here."),u.exit(m.FatalError)}),Q.command("make:function [name]",$.function).option("-n, --name [name]",$.name,{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{C.debug("Running `buddy make:function` ...",J),await O9(J)}),Q.command("make:lang [name]",$.language).option("-n, --name [name]",$.name,{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J,Y)=>{if(C.debug("Running `buddy make:lang` ...",Y),J=J??Y.name,Y.name=J,!J)C.error("You need to specify a name. Read more about the documentation here."),u.exit(m.FatalError);await B9(Y)}),Q.command("make:migration [name]",$.migration).option("-n, --name [name]",$.name,{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action((J,Y)=>{if(C.debug("Running `buddy make:migration` ...",Y),J=J??Y.name,Y.name=J,!J)C.error("You need to specify a migration name"),u.exit(m.FatalError)}),Q.command("make:model [name]",$.model).option("-n, --name [name]",$.name,{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J,Y)=>{if(C.debug("Running `buddy make:model` ...",Y),J=J??Y.name,Y.name=J,!J)C.error("You need to specify a model name"),u.exit(m.FatalError);await H9(Y)}),Q.command("make:notification [name]",$.notification).option("-n, --name [name]",$.name,{default:!1}).option("-e, --email","Is it an email notification?",{default:!0}).option("-c, --chat","Is it a chat notification?",{default:!1}).option("-s, --sms","Is it a SMS notification?",{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J,Y)=>{C.debug("Running `buddy make:notification` ...",Y);let G=await B7("buddy make:notification");if(J=J??Y.name,Y.name=J,!J)C.error("You need to specify a name. Read more about the documentation here."),u.exit(m.FatalError);if(!await Z9(Y))await y0("While running the make:notification command, there was an issue",{startTime:G,useSeconds:!0}),u.exit(m.FatalError);await y0(`Created your ${R7(J)} notification.`,{startTime:G,useSeconds:!0}),u.exit(m.Success)}),Q.command("make:policy [name]",$.policy).option("-n, --name [name]",$.name,{default:!1}).option("-m, --model [model]","The model this policy is for",{default:!1}).option("--no-register","Do not register in Gates.ts",{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).example("buddy make:policy PostPolicy").example("buddy make:policy CommentPolicy --model=Comment").action(async(J,Y)=>{C.debug("Running `buddy make:policy` ...",Y);let G=await B7("buddy make:policy");if(J=J??Y.name,Y.name=J,!J)C.error("You need to specify a policy name."),C.info("Example: buddy make:policy PostPolicy"),u.exit(m.FatalError);if(!await R9(Y))await y0("While running the make:policy command, there was an issue",{startTime:G,useSeconds:!0}),u.exit(m.FatalError);await y0(`Created your ${R7(J)} policy.`,{startTime:G,useSeconds:!0}),u.exit(m.Success)}),Q.command("make:resource [name]",$.resource).option("-n, --name [name]",$.name,{default:!1}).option("-m, --model [model]","The model this resource is for",{default:!1}).option("-c, --collection","Create a collection resource",{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).example("buddy make:resource UserResource").example("buddy make:resource PostResource --model=Post").example("buddy make:resource PostCollection --collection").action(async(J,Y)=>{C.debug("Running `buddy make:resource` ...",Y);let G=await B7("buddy make:resource");if(J=J??Y.name,Y.name=J,!J)C.error("You need to specify a resource name."),C.info("Example: buddy make:resource UserResource"),u.exit(m.FatalError);if(!await M9(Y))await y0("While running the make:resource command, there was an issue",{startTime:G,useSeconds:!0}),u.exit(m.FatalError);await y0(`Created your ${R7(J)} resource.`,{startTime:G,useSeconds:!0}),u.exit(m.Success)}),Q.command("make:queue-table",$.migration).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{C.debug("Running `buddy make queue:table` ...",J),await w9()}),Q.command("make:stack [name]",$.stack).option("-n, --name [name]",$.name,{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J,Y)=>{if(C.debug("Running `buddy make:stack` ...",Y),J=J??Y.name,Y.name=J,!J)C.error("You need to specify a name. Read more about the documentation here."),u.exit(m.FatalError);await T9(Y)}),Q.command("make:view [name]",$.page).alias("make:page [name]").option("-n, --name [name]",$.name,{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J,Y)=>{if(C.debug("Running `buddy make:view` ...",Y),J=J??Y.name,Y.name=J,!J)C.error("You need to specify a name. Read more about the documentation here."),u.exit(m.FatalError);await yJ(Y)}),Q.command("make:job [name]",$.job).option("-n, --name [name]",$.name,{default:!1}).option("-q, --queue [queue]","The queue to dispatch to",{default:"default"}).option("-c, --class","Create a class-based job",{default:!1}).option("-t, --tries [tries]","Number of retry attempts",{default:3}).option("-b, --backoff [backoff]","Backoff delay in seconds",{default:3}).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J,Y)=>{C.debug("Running `buddy make:job` ...",Y);let G=await B7("buddy make:job");if(J=J??Y.name,Y.name=J,!J)C.error("You need to specify a job name."),C.info("Example: buddy make:job SendWelcomeEmail"),u.exit(m.FatalError);if(!await V9(Y))await y0("While running the make:job command, there was an issue",{startTime:G,useSeconds:!0}),u.exit(m.FatalError);await y0(`Created your ${R7(J)} job.`,{startTime:G,useSeconds:!0}),u.exit(m.Success)}),kJ(Q,"make")}import{closeSync as xJ,existsSync as j9,mkdirSync as gJ,openSync as uJ,readdirSync as mJ,rmSync as cJ}from"fs";import C0 from"process";import{intro as s2,log as U0,onUnknownSubcommand as lJ,outro as D$}from"@stacksjs/cli";import{Action as o2}from"@stacksjs/enums";import{appPath as dJ,frameworkPath as pJ,projectPath as rJ}from"@stacksjs/path";import{ExitCode as l0}from"@stacksjs/types";var t2;async function e2(...Q){if(!t2)t2=(await import("@stacksjs/actions")).runAction;return t2(...Q)}function nJ(){let Q=rJ(".stacks"),$=`${Q}/migrations.lock`;try{if(!j9(Q))gJ(Q,{recursive:!0});let J=uJ($,"wx");try{xJ(J)}catch{}return{acquired:!0,release:()=>{try{cJ($,{force:!0})}catch{}}}}catch{return{acquired:!1,release:()=>{}}}}function $3(Q){if(!j9(Q))return 0;let $=0,J=mJ(Q,{withFileTypes:!0});for(let Y of J)if(Y.isDirectory())$+=$3(`${Q}/${Y.name}`);else if(Y.name.endsWith(".ts")&&!Y.name.startsWith(".")&&!Y.name.startsWith("index"))$++;return $}function I9(){let Q=dJ("Models"),$=pJ("defaults/app/Models"),J=$3(Q),Y=$3($);if(J===0&&Y===0)return{valid:!1,error:"No models found. Please create models in app/Models or ensure framework defaults exist."};return{valid:!0}}function wq(Q){let $={migrate:"Migrates your database",project:"Target a specific project",verbose:"Enable verbose output",auth:"Also migrate auth tables (oauth_clients, oauth_access_tokens, oauth_refresh_tokens, password_resets)"};Q.command("migrate",$.migrate).alias("db:migrate").option("-d, --diff","Show the SQL that would be run",{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("-a, --auth",$.auth,{default:!0}).option("--no-auth","Skip auth/oauth table migrations").option("--verbose",$.verbose,{default:!1}).action(async(J)=>{U0.debug("Running `buddy migrate` ...",J);let Y=await s2("buddy migrate"),G=I9();if(!G.valid)console.error(`
379
+ \u274C Error: ${G.error}
380
+ `),C0.exit(l0.FatalError);let z=nJ();if(!z.acquired)U0.error("Another migration is already running (.stacks/migrations.lock exists). Wait for it to finish, or remove the lockfile if it is stale."),C0.exit(l0.FatalError);let W=await e2(o2.Migrate,J).finally(()=>z.release());if(W.isErr)await D$("While running the migrate command, there was an issue",{startTime:Y,useSeconds:!0},W.error),C0.exit(l0.FatalError);if(J.auth!==!1){U0.info("Migrating auth tables...");try{let{migrateAuthTables:H}=await import("@stacksjs/database"),q=await H({verbose:J.verbose});if(!q.success)U0.error(`Failed to migrate auth tables: ${q.error}`)}catch(H){U0.error("Failed to migrate auth tables:",H)}}let X=C0.env.APP_ENV||"local";await D$(`Migrated your ${X} database.${J.auth!==!1?" (including auth tables)":""}`,{startTime:Y,useSeconds:!0}),C0.exit(l0.Success)}),Q.command("migrate:fresh",$.migrate).alias("db:fresh").option("-d, --diff","Show the SQL that would be run",{default:!1}).option("-p, --project [project]",$.project,{default:!1}).option("-s, --seed","Run database seeders after migration",{default:!1}).option("-a, --auth",$.auth,{default:!0}).option("--no-auth","Skip auth/oauth table migrations").option("--verbose",$.verbose,{default:!1}).action(async(J)=>{U0.debug("Running `buddy migrate:fresh` ...",J);let Y=await s2("buddy migrate:fresh"),G=I9();if(!G.valid)console.error(`
381
+ \u274C Error: ${G.error}
382
+ `),C0.exit(l0.FatalError);let z=await e2(o2.MigrateFresh,J);if(z.isErr)await D$("While running the migrate:fresh command, there was an issue",{startTime:Y,useSeconds:!0},z.error),C0.exit(l0.FatalError);if(J.auth!==!1){U0.info("Migrating auth tables...");try{let{migrateAuthTables:H}=await import("@stacksjs/database"),q=await H({verbose:J.verbose});if(!q.success)U0.error(`Failed to migrate auth tables: ${q.error}`)}catch(H){U0.error("Failed to migrate auth tables:",H)}}if(J.seed){U0.info("Running database seeders...");try{let{seed:H}=await import("@stacksjs/database"),q=await H({verbose:J.verbose});if(q.failed>0){U0.warn(`Seeding completed with ${q.failed} failure(s)`);for(let Z of q.results)if(!Z.success)U0.error(` - ${Z.model}: ${Z.error}`)}else U0.success(`Seeded ${q.successful} model(s)`)}catch(H){U0.error("Failed to run seeders:",H)}}let W=[];if(J.auth!==!1)W.push("auth tables");if(J.seed)W.push("seeded");let X=W.length>0?` & ${W.join(" & ")}`:"";await D$(`All tables dropped successfully & migrated successfully${X}`,{startTime:Y,useSeconds:!0}),C0.exit(l0.Success)}),Q.command("migrate:dns",$.migrate).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{U0.debug("Running `buddy migrate:dns` ...",J);let Y=await s2("buddy migrate:dns"),G=await e2(o2.MigrateDns,{...J});if(G.isErr)await D$("While running the migrate:dns command, there was an issue",{startTime:Y,useSeconds:!0},G.error),C0.exit(l0.FatalError);let z=C0.env.APP_URL||"undefined";await D$(`Migrated your ${z} DNS.`,{startTime:Y,useSeconds:!0}),C0.exit(l0.Success)}),lJ(Q,"migrate")}var{$:A9}=globalThis.Bun;import{log as aJ}from"@stacksjs/logging";import{projectPath as iJ}from"@stacksjs/path";import{onUnknownSubcommand as sJ}from"@stacksjs/cli";function Pq(Q){let $={outdated:"List all the outdated project dependencies",project:"Target a specific project",verbose:"Enable verbose output"};Q.command("outdated",$.outdated).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async()=>{aJ.debug("Running `buddy outdated` ..."),A9.cwd(iJ());let J=await A9`bun outdated`.text();console.log(J)}),sJ(Q,"outdated")}import{readFileSync as oJ,existsSync as tJ}from"fs";var eJ=30000;async function b$(Q,$=eJ){let J,Y=new Promise((G,z)=>{J=setTimeout(()=>z(Error(`Operation timed out after ${$}ms`)),$)});try{return await Promise.race([Q,Y])}finally{clearTimeout(J)}}function Q3(){if(tJ(".env.production")){let $=oJ(".env.production","utf-8");for(let J of $.split(`
383
+ `)){let Y=J.indexOf("=");if(Y>0&&!J.startsWith("#"))process.env[J.slice(0,Y).trim()]=J.slice(Y+1).trim()}}}var w7={phone:"Phone/voice service management commands",status:"Show phone service status",numbers:"List phone numbers",search:"Search available phone numbers",setup:"Initialize phone infrastructure"};function Sq(Q){Q.command("phone",w7.phone).action(async()=>{console.log(`
384
+ \uD83D\uDCDE Phone Service Commands
385
+ `),console.log(" buddy phone:status - Show phone service status"),console.log(" buddy phone:numbers - List phone numbers"),console.log(" buddy phone:search - Search available phone numbers"),console.log(" buddy phone:setup - Initialize phone infrastructure"),console.log(""),process.exit(0)}),Q.command("phone:status",w7.status).action(async()=>{console.log(`
386
+ \uD83D\uDCDE Phone Service Status
387
+ `),Q3();try{let{ConnectClient:$}=await import("@stacksjs/ts-cloud"),J=new $(process.env.AWS_REGION||"us-east-1"),G=`${(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-")}-phone`;console.log(`Looking for Connect instance: ${G}`);let W=(await b$(J.listInstances({MaxResults:100}))).InstanceSummaryList?.find((X)=>X.InstanceAlias===G);if(W){if(console.log(`
388
+ \u2705 Phone Service Active
389
+ `),console.log(` Instance ID: ${W.Id}`),console.log(` Alias: ${W.InstanceAlias}`),console.log(` Status: ${W.InstanceStatus}`),console.log(` Inbound Calls: ${W.InboundCallsEnabled?"Enabled":"Disabled"}`),console.log(` Outbound Calls: ${W.OutboundCallsEnabled?"Enabled":"Disabled"}`),W.Id)try{let X=await b$(J.listPhoneNumbers({InstanceId:W.Id}));if(X.ListPhoneNumbersSummaryList&&X.ListPhoneNumbersSummaryList.length>0){console.log(`
390
+ Phone Numbers:`);for(let H of X.ListPhoneNumbersSummaryList)console.log(` \uD83D\uDCF1 ${H.PhoneNumber} (${H.PhoneNumberType})`)}else console.log(`
391
+ No phone numbers claimed yet.`)}catch{console.log(`
392
+ Could not retrieve phone numbers.`)}}else console.log(`
393
+ \u274C Phone service not deployed.`),console.log(`
394
+ \uD83D\uDCA1 To set up phone service:`),console.log(" 1. Enable phone in config/phone.ts"),console.log(" 2. Run `buddy deploy`")}catch($){console.error("Error checking status:",$.message)}process.exit(0)}),Q.command("phone:numbers",w7.numbers).action(async()=>{console.log(`
395
+ \uD83D\uDCDE Phone Numbers
396
+ `),Q3();try{let{ConnectClient:$}=await import("@stacksjs/ts-cloud"),J=new $(process.env.AWS_REGION||"us-east-1"),G=`${(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-")}-phone`,W=(await b$(J.listInstances({MaxResults:100}))).InstanceSummaryList?.find((H)=>H.InstanceAlias===G);if(!W?.Id){console.log("Phone service not deployed. Run `buddy phone:setup` first."),process.exit(0);return}let X=await b$(J.listPhoneNumbers({InstanceId:W.Id}));if(!X.ListPhoneNumbersSummaryList||X.ListPhoneNumbersSummaryList.length===0){console.log("No phone numbers claimed."),console.log("\n\uD83D\uDCA1 Use `buddy phone:search` to find available numbers."),process.exit(0);return}console.log(`Claimed Phone Numbers:
397
+ `);for(let H of X.ListPhoneNumbersSummaryList){if(console.log(` \uD83D\uDCF1 ${H.PhoneNumber}`),console.log(` Type: ${H.PhoneNumberType}`),console.log(` Country: ${H.PhoneNumberCountryCode}`),H.PhoneNumberDescription)console.log(` Description: ${H.PhoneNumberDescription}`);console.log("")}}catch($){console.error("Error listing numbers:",$.message)}process.exit(0)}),Q.command("phone:search [country]",w7.search).option("-t, --type <type>","Phone number type (TOLL_FREE, DID)",{default:"TOLL_FREE"}).action(async($,J)=>{let Y=$?.toUpperCase()||"US",G=J.type?.toUpperCase()||"TOLL_FREE";console.log(`
398
+ \uD83D\uDCDE Searching for ${G} numbers in ${Y}...
399
+ `),Q3();try{let{ConnectClient:z}=await import("@stacksjs/ts-cloud"),W=new z(process.env.AWS_REGION||"us-east-1"),H=`${(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-")}-phone`,Z=(await b$(W.listInstances({MaxResults:100}))).InstanceSummaryList?.find((_)=>_.InstanceAlias===H);if(!Z?.Arn){console.log("Phone service not deployed. Run `buddy phone:setup` first."),process.exit(0);return}let K=await b$(W.searchAvailablePhoneNumbers({TargetArn:Z.Arn,PhoneNumberCountryCode:Y,PhoneNumberType:G,MaxResults:10}));if(!K.AvailableNumbersList||K.AvailableNumbersList.length===0){console.log(`No ${G} numbers available in ${Y}.`),console.log(`
400
+ \uD83D\uDCA1 Try a different country or number type.`),process.exit(0);return}console.log(`Available Phone Numbers:
401
+ `);for(let _ of K.AvailableNumbersList)console.log(` \uD83D\uDCF1 ${_.PhoneNumber}`);console.log("\n\uD83D\uDCA1 To claim a number, use `buddy phone:claim <number>`")}catch(z){if(z.message.includes("not authorized"))console.log("Not authorized to search phone numbers."),console.log("Make sure your AWS account has Amazon Connect permissions.");else console.error("Error searching numbers:",z.message)}process.exit(0)}),Q.command("phone:setup",w7.setup).action(async()=>{console.log(`
402
+ \uD83D\uDCDE Phone Service Setup
403
+ `),console.log("Amazon Connect setup requires manual configuration."),console.log(`
404
+ Steps to set up phone service:
405
+ `),console.log("1. Enable phone in config/phone.ts:"),console.log(" enabled: true"),console.log(""),console.log("2. Run `buddy deploy` to create the Connect instance"),console.log(""),console.log("3. Access the Connect console to:"),console.log(" - Claim phone numbers"),console.log(" - Configure contact flows"),console.log(" - Set up routing profiles"),console.log(""),console.log("4. Use `buddy phone:status` to verify setup"),console.log(""),process.exit(0)})}var{$:G2}=globalThis.Bun;import J3 from"process";import{intro as Y3,italic as E9,onUnknownSubcommand as $Y,outro as G3}from"@stacksjs/cli";import{ports as P9}from"@stacksjs/config";import{log as $0}from"@stacksjs/logging";import{findProjectPath as f9,path as v9,projectPath as S9}from"@stacksjs/path";import{ExitCode as z3}from"@stacksjs/types";import{findStacksProjects as QY}from"@stacksjs/utils";function gq(Q){let $={command:"Let buddy check your project for potential issues and misconfigurations",ports:"Check if the ports are available",project:"Target a specific project",verbose:"Enable verbose output"};Q.command("ports",$.command).option("-l, --list","List the used ports",{default:!0}).option("-c, --check","Check if the ports are available",{default:!1}).option("-p, --project [name]",$.project,{default:void 0}).option("-q, --quiet","Use minimal output",{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{$0.debug("Running `buddy ports` ...",J);let Y;if(!J.quiet)Y=await Y3("buddy ports");if(J.project){let G=await f9(J.project);$0.debug(`Path: ${G}`);let z=await W3(G,J);$0.debug(`./buddy ports --quiet response for ${S9}`,z),z2(z,J)}else z2(P9,J);if(!J.quiet)await G3("Exited",{startTime:Y,useSeconds:!1});J3.exit(z3.Success)}),Q.command("ports:list",$.ports).option("-p, --project [name]",$.project,{default:void 0}).option("-q, --quiet","Use minimal output",{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{$0.debug("Running `buddy ports:list` ...",J);let Y;if(!J.quiet)Y=await Y3("buddy ports:list");if(J.project){if(!J.quiet)$0.info(`Listing ports for project: ${E9(J.project)}`);let G=await f9(J.project);$0.debug(`Path: ${G}`);let z=await W3(G,J);z2(z,J)}else z2(P9,J);if(!J.quiet)await G3("Exited",{startTime:Y,useSeconds:!1});J3.exit(z3.Success)}),Q.command("ports:check",$.ports).option("-p, --project [name]",$.project,{default:S9()}).option("-q, --quiet","Use minimal output",{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{$0.debug("Running `buddy ports:check` ...",J);let Y;if(!J.quiet)Y=await Y3("buddy ports:check");let G=await QY(void 0,{quiet:!0});$0.debug("Running `buddy ports`"),$0.debug(`Found ${G.length} projects`),$0.debug("Projects:",G);let z={};for(let W of G)z[W]=await W3(W,J);if($0.info("ProjectsPorts:",z),!J.quiet)await G3("Exited",{startTime:Y,useSeconds:!1});J3.exit(z3.Success)}),$Y(Q,"ports")}async function W3(Q,$){if(!$.quiet)$0.info(`Checking ports for project: ${E9(Q)}`);G2.cwd(Q);try{G2.env(await import(`${Q}/.env`))}catch(q){if(!$.quiet)$0.warn(`[ports] Failed to load ${Q}/.env (${q.message}). Falling back to current environment.`)}let J=await G2`./buddy projects:list --quiet`.text();$0.debug("ProjectListResponse",J);let Y=J.split(`
406
+ `).filter((q)=>q.startsWith(" - ")).map((q)=>q.trim().substring(4));$0.debug("Projects:",Y);let G=$.project??v9.projectPath(),z=Y.find((q)=>q.includes(G));if($0.debug(`Checking ports for project: ${z}`),z===""||!z)z=v9.projectPath();$0.debug(`$ Running: ./buddy ports:list --quiet via ${z}`);let W=await G2`./buddy ports:list --quiet`.json();$0.debug(`Response for ./buddy ports:list --quiet via ${z}`,W);let X=W.replace(/(\w+)(?=\s*:)/g,'"$1"');X=X.replace(/,(\s*\})/g,"$1");let H;try{H=JSON.parse(X)}catch{throw Error(`Failed to parse ports configuration: ${X.slice(0,200)}`)}return $0.debug(`Ports for ${z}`,H),H}function z2(Q,$){if(!$.quiet)console.log("");if(console.log(Q),!$.quiet)console.log("")}import{runAction as JY}from"@stacksjs/actions";import{Action as YY}from"@stacksjs/enums";import{log as GY}from"@stacksjs/logging";import{onUnknownSubcommand as zY}from"@stacksjs/cli";function pq(Q){let $={command:"Run your prepublish script",project:"Target a specific project",verbose:"Enable verbose output"};Q.command("prepublish",$.command).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{GY.debug("Running `buddy prepublish` ...",J),await JY(YY.Prepublish,J)}),zY(Q,"prepublish")}import N9 from"process";import{intro as C9,log as h9,onUnknownSubcommand as WY}from"@stacksjs/cli";import{ExitCode as D9}from"@stacksjs/types";import{findStacksProjects as b9}from"@stacksjs/utils";function oq(Q){let $={projects:"Find all Stacks projects on your system",verbose:"Enable verbose output"};Q.command("projects",$.projects).option("-q, --quiet","Use minimal output",{default:!1}).option("-l, --list","List all local Stacks projects",{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{if(h9.debug("Running `buddy projects` ...",J),!J.quiet)await C9("buddy projects");let Y=await b9(void 0,J);for(let G of Y)console.log(" - ",G);N9.exit(D9.Success)}),Q.command("projects:list",$.projects).option("-q, --quiet","Use minimal output",{default:!1}).option("-l, --list","List all local Stacks projects",{default:!0}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{if(h9.debug("Running `buddy projects` ...",J),!J.quiet)await C9("buddy projects:list");let Y=await b9(void 0,J);for(let G of Y)console.log(" - ",G);N9.exit(D9.Success)}),WY(Q,"projects")}import{existsSync as k9,mkdirSync as X3}from"fs";import{cp as XY,readdir as qY,stat as HY}from"fs/promises";import{dirname as x9,resolve as ZY}from"path";import h0 from"process";import{italic as z$,log as v0,onUnknownSubcommand as KY}from"@stacksjs/cli";import{path as z0}from"@stacksjs/path";import{fs as _Y,globSync as UY}from"@stacksjs/storage";import{ExitCode as M7}from"@stacksjs/types";function XH(Q){let $={command:"Publish a Stacks default into your userland (app/) directory so you can customize it",model:"Publish a default model from storage/framework/defaults/app/Models/ to app/Models/",controller:"Publish a default controller from storage/framework/defaults/app/Controllers/ to app/Controllers/",middleware:"Publish a default middleware from storage/framework/defaults/app/Middleware/ to app/Middleware/",action:"Publish a default action from storage/framework/defaults/app/Actions/ to app/Actions/",core:"Publish a framework package source from node_modules/@stacksjs/<pkg>/ into storage/framework/core/<pkg>/ for editing",name:"The name of the resource to publish (e.g. Cart, User)",pkg:"The name of the framework package (e.g. router, orm, faker \u2014 without @stacksjs/ prefix)",force:"Overwrite an existing userland file",verbose:"Enable verbose output"};Q.command("publish:model <name>",$.model).option("--force",$.force,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J,Y)=>{await G$({kind:"model",name:J,defaultsDir:z0.frameworkPath("defaults/app/Models"),userDir:z0.userModelsPath(),force:!!Y.force})}),Q.command("publish:controller <name>",$.controller).option("--force",$.force,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J,Y)=>{await G$({kind:"controller",name:J,defaultsDir:z0.frameworkPath("defaults/app/Controllers"),userDir:z0.userControllersPath(),force:!!Y.force})}),Q.command("publish:middleware <name>",$.middleware).option("--force",$.force,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J,Y)=>{await G$({kind:"middleware",name:J,defaultsDir:z0.frameworkPath("defaults/app/Middleware"),userDir:z0.userMiddlewarePath(),force:!!Y.force})}),Q.command("publish:action <name>",$.action).option("--force",$.force,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J,Y)=>{await G$({kind:"action",name:J,defaultsDir:z0.frameworkPath("defaults/app/Actions"),userDir:z0.userActionsPath(),force:!!Y.force})}),Q.command("publish:core <pkg>",$.core).option("--force",$.force,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J,Y)=>{await y9(J,!!Y.force)}),Q.command("publish [resource] [name]",$.command).option("--force",$.force,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J,Y,G)=>{if(!J||!Y)v0.error("Usage: buddy publish:<resource> <Name> (e.g. buddy publish:model Cart)"),h0.exit(M7.FatalError);let W={model:()=>G$({kind:"model",name:Y,defaultsDir:z0.frameworkPath("defaults/app/Models"),userDir:z0.userModelsPath(),force:!!G.force}),controller:()=>G$({kind:"controller",name:Y,defaultsDir:z0.frameworkPath("defaults/app/Controllers"),userDir:z0.userControllersPath(),force:!!G.force}),middleware:()=>G$({kind:"middleware",name:Y,defaultsDir:z0.frameworkPath("defaults/app/Middleware"),userDir:z0.userMiddlewarePath(),force:!!G.force}),action:()=>G$({kind:"action",name:Y,defaultsDir:z0.frameworkPath("defaults/app/Actions"),userDir:z0.userActionsPath(),force:!!G.force}),core:()=>y9(Y,!!G.force)}[J.toLowerCase()];if(!W)v0.error(`Unknown publishable resource: ${z$(J)}`),v0.info("Available: model, controller, middleware, action, core"),h0.exit(M7.FatalError);await W()}),KY(Q,"publish")}async function y9(Q,$){let J=Q.replace(/^@stacksjs\//,"").replace(/^core\//,""),Y=(H,q)=>{if(h0.stderr.write(`${H}
407
+ `),q)h0.stderr.write(` ${q}
408
+ `);h0.exit(M7.FatalError)};if(!J||J.includes("/")||J.includes(".."))Y(`Invalid package name: ${Q}`,"Use a short name like `router` or the fully qualified `@stacksjs/router`.");let G=ZY(h0.cwd(),"node_modules","@stacksjs",J),z=z0.frameworkPath(`core/${J}`);try{if(!(await HY(G)).isDirectory())Y(`${G} is not a directory.`)}catch{Y(`Could not find @stacksjs/${J} in node_modules.`,"Run `bun install` first, or check the package name.")}if(k9(z)&&!$)Y(`Already published: ${z.replace(`${h0.cwd()}/`,"")}`,"Pass --force to overwrite.");X3(x9(z),{recursive:!0});let W=new Set(["node_modules","dist",".bun",".cache","tsconfig.tsbuildinfo"]),X=0;await g9(G,z,W,()=>X++),v0.success(`Published @stacksjs/${J} \u2192 ${z$(z.replace(`${h0.cwd()}/`,""))} (${X} files)`),v0.info("Edit freely \u2014 local changes win over the installed package.")}async function g9(Q,$,J,Y){X3($,{recursive:!0});let G=await qY(Q,{withFileTypes:!0});for(let z of G){if(J.has(z.name))continue;let W=`${Q}/${z.name}`,X=`${$}/${z.name}`;if(z.isDirectory()){await g9(W,X,J,Y);continue}await XY(W,X,{force:!0,dereference:!0}),Y()}}async function G$(Q){let{kind:$,name:J,defaultsDir:Y,userDir:G,force:z}=Q,W=J.endsWith(".ts")?J:`${J}.ts`,X=UY([`${Y}/**/${W}`],{absolute:!0});if(!X.length)v0.error(`Could not find default ${$}: ${z$(W)}`),v0.info(`Looked under: ${z$(Y)}`),h0.exit(M7.FatalError);if(X.length>1){v0.warn(`Multiple defaults match ${z$(W)}; using the first:`);for(let Z of X)v0.info(` ${Z}`)}let H=X[0],q=`${G.replace(/\/$/,"")}/${W}`;if(k9(q)&&!z)v0.error(`Already exists: ${z$(q)}`),v0.info("Pass --force to overwrite."),h0.exit(M7.FatalError);X3(x9(q),{recursive:!0}),await _Y.promises.copyFile(H,q),v0.success(`Published ${$} ${z$(J)} \u2192 ${z$(q.replace(`${h0.cwd()}/`,""))}`)}import d from"process";import{runAction as D0}from"@stacksjs/actions";import{intro as d0,log as L0,onUnknownSubcommand as LY,outro as W0}from"@stacksjs/cli";import{Action as b0}from"@stacksjs/enums";import{ExitCode as a}from"@stacksjs/types";function LH(Q){let $={project:"Target a specific project",queue:"Specify queue name",verbose:"Enable verbose output",id:"Job or batch ID",all:"Apply to all items",force:"Force the operation without confirmation",connection:"Queue connection to use",concurrency:"Number of concurrent workers"};Q.command("queue:work","Start processing jobs on the queue").option("-p, --project [project]",$.project,{default:!1}).option("-q, --queue [queue]",$.queue,{default:!1}).option("-c, --connection [connection]",$.connection,{default:!1}).option("--concurrency [concurrency]",$.concurrency,{default:"1"}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{L0.debug("Running `buddy queue:work` ...",J);let Y=1e4,G=!1,z=(H)=>{if(G)return;G=!0,L0.info(`[queue] Received ${H}, draining workers (max ${Y/1000}s)\u2026`),setTimeout(()=>{L0.warn("[queue] Drain timeout exceeded \u2014 forcing shutdown."),d.exit(a.FatalError)},Y).unref()};d.on("SIGINT",()=>z("SIGINT")),d.on("SIGTERM",()=>z("SIGTERM"));let W=await d0("buddy queue:work"),X=await D0(b0.QueueWork,J);if(X.isErr)await W0("While running the queue:work command, there was an issue",{startTime:W,useSeconds:!0},X.error),d.exit(a.FatalError);d.exit(a.Success)}),Q.command("queue:failed","List all failed jobs").option("-p, --project [project]",$.project,{default:!1}).option("-q, --queue [queue]",$.queue,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{L0.debug("Running `buddy queue:failed` ...",J);let Y=await d0("buddy queue:failed"),G=await D0(b0.QueueFailed,J);if(G.isErr)await W0("While running the queue:failed command, there was an issue",{startTime:Y,useSeconds:!0},G.error),d.exit(a.FatalError);await W0("Listed all failed jobs",{startTime:Y,useSeconds:!0}),d.exit(a.Success)}),Q.command("queue:retry [id]","Retry failed jobs").option("-p, --project [project]",$.project,{default:!1}).option("-q, --queue [queue]",$.queue,{default:!1}).option("--all",$.all,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J,Y)=>{L0.debug("Running `buddy queue:retry` ...",Y);let G=await d0("buddy queue:retry"),z=await D0(b0.QueueRetry,{...Y,id:J});if(z.isErr)await W0("While running the queue:retry command, there was an issue",{startTime:G,useSeconds:!0},z.error),d.exit(a.FatalError);let W=Y.all?"Retried all failed jobs":`Retried failed job ${J}`;await W0(W,{startTime:G,useSeconds:!0}),d.exit(a.Success)}),Q.command("queue:clear","Clear all jobs from the queue").option("-p, --project [project]",$.project,{default:!1}).option("-q, --queue [queue]",$.queue,{default:!1}).option("--force",$.force,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{L0.debug("Running `buddy queue:clear` ...",J);let Y=await d0("buddy queue:clear"),G=await D0(b0.QueueClear,J);if(G.isErr)await W0("While running the queue:clear command, there was an issue",{startTime:Y,useSeconds:!0},G.error),d.exit(a.FatalError);let z=J.queue||"default";await W0(`Cleared all jobs from the "${z}" queue`,{startTime:Y,useSeconds:!0}),d.exit(a.Success)}),Q.command("queue:status","Display the status of queue workers").option("-p, --project [project]",$.project,{default:!1}).option("-q, --queue [queue]",$.queue,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{L0.debug("Running `buddy queue:status` ...",J);let Y=await d0("buddy queue:status"),G=await D0(b0.QueueStatus,J);if(G.isErr)await W0("While running the queue:status command, there was an issue",{startTime:Y,useSeconds:!0},G.error),d.exit(a.FatalError);await W0("Queue status displayed",{startTime:Y,useSeconds:!0}),d.exit(a.Success)}),Q.command("queue:flush","Delete all failed jobs").option("-p, --project [project]",$.project,{default:!1}).option("-q, --queue [queue]",$.queue,{default:!1}).option("--force",$.force,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{L0.debug("Running `buddy queue:flush` ...",J);let Y=await d0("buddy queue:flush"),G=await D0(b0.QueueFlush,J);if(G.isErr)await W0("While running the queue:flush command, there was an issue",{startTime:Y,useSeconds:!0},G.error),d.exit(a.FatalError);await W0("Flushed all failed jobs",{startTime:Y,useSeconds:!0}),d.exit(a.Success)}),Q.command("queue:table","Create a migration for the jobs database table").option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{L0.debug("Running `buddy queue:table` ...",J);let Y=await d0("buddy queue:table"),G=await D0(b0.QueueTable,J);if(G.isErr)await W0("While running the queue:table command, there was an issue",{startTime:Y,useSeconds:!0},G.error),d.exit(a.FatalError);await W0("Jobs table migration created",{startTime:Y,useSeconds:!0}),d.exit(a.Success)}),Q.command("queue:monitor","Monitor queue status in real-time").option("-p, --project [project]",$.project,{default:!1}).option("-q, --queue [queue]",$.queue,{default:!1}).option("-i, --interval [interval]","Refresh interval in milliseconds",{default:"2000"}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{L0.debug("Running `buddy queue:monitor` ...",J);let Y=await D0(b0.QueueMonitor,J);if(Y.isErr)L0.error("While running the queue:monitor command, there was an issue",Y.error),d.exit(a.FatalError);d.exit(a.Success)}),Q.command("queue:inspect [id]","Inspect a specific job").option("-p, --project [project]",$.project,{default:!1}).option("--failed","Inspect a failed job",{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J,Y)=>{L0.debug("Running `buddy queue:inspect` ...",Y);let G=await d0("buddy queue:inspect"),z=await D0(b0.QueueInspect,{...Y,id:J});if(z.isErr)await W0("While running the queue:inspect command, there was an issue",{startTime:G,useSeconds:!0},z.error),d.exit(a.FatalError);await W0("Job inspection complete",{startTime:G,useSeconds:!0}),d.exit(a.Success)}),Q.command("queue:schedule","Start the job scheduler for cron-based jobs").option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{L0.debug("Running `buddy queue:schedule` ...",J);let Y=await D0(b0.QueueSchedule,J);if(Y.isErr)L0.error("While running the queue:schedule command, there was an issue",Y.error),d.exit(a.FatalError);d.exit(a.Success)}),Q.command("queue:schedule:list","List all scheduled jobs").option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{L0.debug("Running `buddy queue:schedule:list` ...",J);let Y=await d0("buddy queue:schedule:list"),G=await D0(b0.QueueScheduleList,J);if(G.isErr)await W0("While running the queue:schedule:list command, there was an issue",{startTime:Y,useSeconds:!0},G.error),d.exit(a.FatalError);await W0("Listed all scheduled jobs",{startTime:Y,useSeconds:!0}),d.exit(a.Success)}),LY(Q,"queue")}import FY from"process";import{runAction as OY}from"@stacksjs/actions";import{intro as VY,italic as BY,log as W2,onUnknownSubcommand as RY,outro as wY}from"@stacksjs/cli";import{Action as MY}from"@stacksjs/enums";import{ExitCode as TY}from"@stacksjs/types";var T7={release:"Release a new version of your libraries/packages",project:"Target a specific project",dryRun:"Run the release without actually releasing",bump:"Non-interactive bump: patch | minor | major | prepatch | preminor | premajor | prerelease | x.y.z",verbose:"Enable verbose output"};function MH(Q){Q.command("release",T7.release).option("--dry-run",T7.dryRun,{default:!1}).option("-p, --project [project]",T7.project,{default:!1}).option("--bump <type>",T7.bump).option("--verbose",T7.verbose,{default:!1}).action(async($)=>{if(W2.debug("Running `buddy release` ...",$),$.dryRun)W2.warn("Dry run enabled. No changes will be made or committed.");let J=await VY("buddy release"),Y=await OY(MY.Release,$);if(Y.isErr)W2.error("Failed to release",Y.error),FY.exit(TY.FatalError);await wY("Triggered CI/CD Release via GitHub Actions",{startTime:J,useSeconds:!0}),W2.info(`Follow along: ${BY("https://github.com/stacksjs/stacks/actions")}`)}),RY(Q,"release")}import u9 from"process";import{runAction as IY}from"@stacksjs/actions";import{intro as jY,onUnknownSubcommand as AY,outro as m9}from"@stacksjs/cli";import{Action as PY}from"@stacksjs/enums";import{ExitCode as c9}from"@stacksjs/types";function vH(Q){let $={route:"Lists your routes",verbose:"Enable verbose output"};Q.command("route:list",$.route).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{let Y=await jY("buddy route:list"),G=await IY(PY.RouteList,J);if(G.isErr)await m9("While running the route:list command, there was an issue",{startTime:Y,useSeconds:!0},G.error),u9.exit(c9.FatalError);await m9("Successfully listed routes"),u9.exit(c9.Success)}),AY(Q,"route")}import l9 from"process";import{runAction as fY}from"@stacksjs/actions";import{intro as vY,log as SY,outro as d9}from"@stacksjs/cli";import{Action as EY}from"@stacksjs/enums";import{ExitCode as p9}from"@stacksjs/types";function bH(Q){let $={stripe:"Sets up stripe products in the dashboard",project:"Target a specific project",verbose:"Enable verbose output"};Q.command("stripe:setup",$.stripe).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{SY.debug("Running `buddy stripe:setup` ...",J);let Y=await vY("buddy stripe:setup"),G=await fY(EY.StripeSetup,J);if(G.isErr)await d9("While running the stripe:setup command, there was an issue",{startTime:Y,useSeconds:!0},G.error),l9.exit(p9.FatalError);await d9("Stripe products created successfully",{startTime:Y,useSeconds:!0}),l9.exit(p9.Success)})}import r9 from"process";import{runAction as NY}from"@stacksjs/actions";import{intro as CY,log as hY,outro as DY}from"@stacksjs/cli";import{Action as bY}from"@stacksjs/enums";import{ExitCode as n9}from"@stacksjs/types";function cH(Q){let $={project:"Target a specific project",schedule:"Run the scheduler",verbose:"Enable verbose output"};Q.command("schedule:run",$.schedule).option("-p, --project [project]",$.project,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{hY.debug("Running `buddy schedule:run` ...",J);let Y=await CY("buddy schedule:run"),G=await NY(bY.ScheduleRun,J);if(G.isErr)await DY("While running the schedule:run command, there was an issue",{startTime:Y,useSeconds:!0},G.error),r9.exit(n9.FatalError);r9.exit(n9.Success)})}import q3 from"process";import{runAction as a9}from"@stacksjs/actions";import{intro as i9,log as H3,outro as X2}from"@stacksjs/cli";import{Action as I7}from"@stacksjs/enums";import{ExitCode as Z3}from"@stacksjs/types";function iH(Q){let $={import:"Indexes database data to search engine",flush:"Flushes all data from search engine",settings:"Update index settings",list:"List index settings",model:"Target a specific model",project:"Target a specific project",verbose:"Enable verbose output"};Q.command("search-engine:update",$.import).option("-m, --model [model]",$.model,{default:""}).option("-f, --flush [flush]",$.flush,{default:!1}).option("-s, --settings [settings]",$.settings,{default:!1}).option("--verbose",$.verbose,{default:!1}).option("-p, --project [project]",$.project,{default:!1}).action(async(J)=>{H3.debug("Running `search-engine:update` ...",J);let Y=I7.SearchEngineImport,G="search-engine:update";if(J.model)Y=I7.SearchEngineImport,G=`search-engine:update --model ${J.model}`;if(J.settings)Y=I7.SearchEnginePushSettings,G="search-engine:update --settings";if(J.flush)Y=I7.SearchEngineFlush,G="search-engine:update --flush";let z=await i9(G),W=await a9(Y,J);if(W.isErr)await X2("While running the search-engine:update command, there was an issue",{startTime:z,useSeconds:!0},W.error),q3.exit(Z3.FatalError);await X2("Successfully imported model data to search engine.",{startTime:z,useSeconds:!0})}),Q.command("search-engine:settings",$.list).option("-m, --model [model]",$.model,{default:!1}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{if(!J.model)H3.error("Missing required option --model");H3.debug("Running `search-engine:settings` ...",J);let Y=await i9("search-engine:settings"),G=await a9(I7.SearchEngineListSettings,J);if(G.isErr)await X2("While running the search-engine:settings command, there was an issue",{startTime:Y,useSeconds:!0},G.error),q3.exit(Z3.FatalError);await X2("Successfully listed search engine index settings.",{startTime:Y,useSeconds:!0}),q3.exit(Z3.Success)})}import{existsSync as yY,readdirSync as kY}from"fs";import j7 from"process";import{runAction as xY}from"@stacksjs/actions";import{intro as gY,log as K3,onUnknownSubcommand as uY,outro as _3}from"@stacksjs/cli";import{Action as mY}from"@stacksjs/enums";import{appPath as cY,frameworkPath as lY}from"@stacksjs/path";import{ExitCode as A7}from"@stacksjs/types";function U3(Q){if(!yY(Q))return 0;let $=0,J=kY(Q,{withFileTypes:!0});for(let Y of J)if(Y.isDirectory())$+=U3(`${Q}/${Y.name}`);else if(Y.name.endsWith(".ts")&&!Y.name.startsWith(".")&&!Y.name.startsWith("index"))$++;return $}function dY(){let Q=cY("Models"),$=lY("defaults/app/Models"),J=U3(Q),Y=U3($);if(J===0&&Y===0)return{valid:!1,error:"No models found. Please create models in app/Models or ensure framework defaults exist."};return{valid:!0}}function GZ(Q){let $={seed:"Seed your database",project:"Target a specific project",verbose:"Enable verbose output"};Q.command("seed",$.seed).alias("db:seed").option("-p, --project [project]",$.project,{default:!1}).option("-c, --class [class]","Run a specific seeder class from database/seeders/",{default:""}).option("--verbose",$.verbose,{default:!1}).action(async(J)=>{K3.debug("Running `buddy seed` ...",J);let Y=await gY("buddy seed");if(J.class){let{runClassSeeders:X}=await import("@stacksjs/database"),H=await X({class:J.class});await _3(`Class seeders: ran=${H.ran.length}, skipped=${H.skipped.length}`,{startTime:Y,useSeconds:!0}),j7.exit(H.ran.length>0?A7.Success:A7.FatalError)}let G=dY();if(!G.valid)console.error(`
409
+ \u274C Error: ${G.error}
410
+ `),j7.exit(A7.FatalError);let z=await xY(mY.Seed,J);if(z.isErr)await _3("While running the seed command, there was an issue",{startTime:Y,useSeconds:!0},z.error),j7.exit(A7.FatalError);try{let{runClassSeeders:X}=await import("@stacksjs/database"),H=await X();if(H.ran.length>0)K3.info(`Also ran ${H.ran.length} class seeder(s): ${H.ran.join(", ")}`)}catch(X){K3.warn("Class seeders failed (non-fatal):",X)}let W=j7.env.APP_ENV||"local";await _3(`Seeded your ${W} database.`,{startTime:Y,useSeconds:!0}),j7.exit(A7.Success)}),uY(Q,"seed")}m7();import{readFileSync as pY,existsSync as rY}from"fs";var nY=30000;async function W$(Q,$=nY){let J,Y=new Promise((G,z)=>{J=setTimeout(()=>z(Error(`Operation timed out after ${$}ms`)),$)});try{return await Promise.race([Q,Y])}finally{clearTimeout(J)}}function y$(){if(rY(".env.production")){let $=pY(".env.production","utf-8");for(let J of $.split(`
411
+ `)){let Y=J.indexOf("=");if(Y>0&&!J.startsWith("#"))process.env[J.slice(0,Y).trim()]=J.slice(Y+1).trim()}}}var k$={sms:"SMS service management commands",status:"Show SMS service status",send:"Send a test SMS",setup:"Initialize SMS infrastructure",verify:"Verify a sandbox phone number","add-phone":"Add a phone to sandbox for testing"};function XZ(Q){Q.command("sms",k$.sms).action(async()=>{console.log(`
412
+ \uD83D\uDCF1 SMS Service Commands
413
+ `),console.log(" buddy sms:status - Show SMS service status"),console.log(" buddy sms:send - Send a test SMS"),console.log(" buddy sms:setup - Initialize SMS infrastructure"),console.log(" buddy sms:add-phone - Add a phone to sandbox for testing"),console.log(" buddy sms:verify - Verify a sandbox phone number with OTP"),console.log(""),process.exit(0)}),Q.command("sms:status",k$.status).action(async()=>{console.log(`
414
+ \uD83D\uDCF1 SMS Service Status
415
+ `),y$();try{let{getSmsInfrastructureStatus:$}=await import("@stacksjs/ts-cloud"),J=await W$($({region:process.env.AWS_REGION||"us-east-1",accountName:"stacks"}),30000);if(console.log("Phone Numbers:"),J.phoneNumbers.length===0)console.log(" No phone numbers provisioned"),console.log(" Run `buddy sms:setup` to provision a phone number");else for(let Y of J.phoneNumbers)console.log(` ${Y.phoneNumber}`),console.log(` Status: ${Y.status}`),console.log(` Two-Way: ${Y.twoWayEnabled?"Enabled":"Disabled"}`),console.log(` Capabilities: ${Y.capabilities.join(", ")||"N/A"}`);if(console.log(`
416
+ Account:`),console.log(` Sandbox Status: ${J.sandboxStatus==="IN_SANDBOX"?"\u26A0\uFE0F In Sandbox":"\u2705 Production"}`),console.log(` Spending Limit: $${J.spendingLimit}/month`),console.log(`
417
+ SNS Topics:`),J.topics.length===0)console.log(" No SMS topics configured");else for(let Y of J.topics)console.log(` ${Y.name}`);if(J.sandboxStatus==="IN_SANDBOX")console.log(`
418
+ \uD83D\uDCA1 To exit sandbox mode:`),console.log(" Run `buddy sms:setup` to file a support request"),console.log(" Or visit AWS Console > End User Messaging > SMS > Request production access");if(J.phoneNumbers.some((Y)=>Y.status==="PENDING"))console.log(`
419
+ \u23F3 Note: Phone number verification can take 24-72 hours for toll-free numbers`)}catch($){console.error("Error checking status:",$.message);try{let{PinpointSmsVoiceClient:J}=await import("@stacksjs/ts-cloud"),Y=new J(process.env.AWS_REGION||"us-east-1"),z=(await W$(Y.describePhoneNumbers({}))).PhoneNumbers?.filter((W)=>W.Status==="ACTIVE"||W.Status==="PENDING");if(z&&z.length>0){console.log(`
420
+ \u2705 SMS Service Active (End User Messaging)`);for(let W of z)console.log(` Phone: ${W.PhoneNumber} (${W.Status})`)}else console.log(`
421
+ \u274C SMS service not deployed.`),console.log(" Run `buddy sms:setup` to initialize")}catch{console.log(`
422
+ \u274C Could not connect to AWS. Check credentials.`)}}process.exit(0)}),Q.command("sms:send <phone> [message]",k$.send).option("--template <name>","Use a message template").action(async($,J,Y)=>{let G=J||"Test message from Stacks";console.log(`
423
+ \uD83D\uDCF1 Sending SMS to ${$}...
424
+ `),y$();try{let{SMSClient:z}=await import("@stacksjs/ts-cloud"),W=new z({region:process.env.AWS_REGION||"us-east-1"}),X=await import("@stacksjs/config").then((K)=>K.config?.sms),H=X?.originationNumber;if(!H){let{PinpointSmsVoiceClient:K}=await import("@stacksjs/ts-cloud"),_=new K(process.env.AWS_REGION||"us-east-1");H=(await W$(_.describePhoneNumbers({}))).PhoneNumbers?.find((F)=>F.Status==="ACTIVE")?.PhoneNumber}let q=G;if(Y?.template&&X?.templates){let K=X.templates.find((_)=>_.name===Y.template);if(K)q=K.body,console.log(`Using template: ${Y.template}`);else console.log(`Template "${Y.template}" not found. Using default message.`)}let Z=await W$(W.send({to:$,message:q,originationNumber:H}),30000);if(Z.messageId){if(console.log("\u2705 SMS sent successfully!"),console.log(` Message ID: ${Z.messageId}`),H)console.log(` From: ${H}`)}else console.log("\u274C SMS send failed")}catch(z){if(console.error("Error sending SMS:",z.message),z.message.includes("not found")||z.message.includes("No phone"))console.log(`
425
+ \uD83D\uDCA1 No origination phone number available.`),console.log(" Run `buddy sms:setup` to provision a phone number.");else if(z.message.includes("not authorized"))console.log(`
426
+ \uD83D\uDCA1 Make sure your AWS account has SMS permissions.`);else if(z.message.includes("sandbox"))console.log("\n\uD83D\uDCA1 Your account is in SMS sandbox. Run `buddy sms:setup` to request production access.");else if(z.message.includes("PENDING"))console.log(`
427
+ \uD83D\uDCA1 Phone number is still pending verification (24-72 hours for toll-free).`),console.log(" Run `buddy sms:status` to check current status.")}process.exit(0)}),Q.command("sms:setup",k$.setup).option("--dry-run","Show what would be done without making changes").action(async($)=>{console.log(`
428
+ \uD83D\uDCF1 SMS Service Setup
429
+ `),y$();try{let J=await import("@stacksjs/config").then((z)=>z.config?.sms);if(!J?.enabled){console.log("SMS is disabled in config/sms.ts"),console.log(`
430
+ To enable SMS:`),console.log("1. Edit config/sms.ts and set enabled: true"),console.log("2. Run `buddy sms:setup` again"),process.exit(0);return}if($.dryRun){console.log("[Dry Run] Would set up SMS infrastructure with config:"),console.log(` Provider: ${J.provider}`),console.log(` Country: ${J.defaultCountryCode}`),console.log(` Message Type: ${J.messageType}`),console.log(` Monthly Limit: $${J.maxSpendPerMonth||1}`),console.log(` Two-Way: ${J.twoWay?.enabled?"Enabled":"Disabled"}`),console.log(` Inbox: ${J.inbox?.enabled?"Enabled":"Disabled"}`),process.exit(0);return}console.log(`Setting up SMS infrastructure...
431
+ `);let{createSmsInfrastructure:Y}=await import("@stacksjs/ts-cloud"),G=await W$(Y({enabled:J.enabled,provider:J.provider||"pinpoint",originationNumber:J.originationNumber,defaultCountryCode:J.defaultCountryCode||"US",messageType:J.messageType||"TRANSACTIONAL",maxSpendPerMonth:J.maxSpendPerMonth,inbox:J.inbox,twoWay:J.twoWay,optOut:J.optOut||{enabled:!0,keywords:["STOP"]}}),120000);if(G.success){if(console.log(`
432
+ \u2705 SMS infrastructure setup complete!
433
+ `),G.phoneNumber)console.log(` Phone Number: ${G.phoneNumber} (${G.phoneNumberStatus})`);if(G.twoWayTopicArn)console.log(` Two-Way Topic: ${G.twoWayTopicArn}`);if(G.inboxBucket)console.log(` Inbox: s3://${G.inboxBucket}/${G.inboxPrefix}`);if(console.log(` Spending Limit: $${G.spendingLimit}/month`),console.log(` Sandbox Status: ${G.sandboxStatus}`),G.supportCaseId)console.log(`
434
+ \uD83D\uDCCB Support Case: ${G.supportCaseId}`),console.log(" A support ticket has been filed for sandbox exit.");if(G.warnings.length>0){console.log(`
435
+ \u26A0\uFE0F Warnings:`);for(let z of G.warnings)console.log(` - ${z}`)}console.log(`
436
+ \uD83D\uDCA1 Next steps:`),console.log(' - Run `buddy sms:send +1234567890 "Test"` to send a test SMS'),console.log(" - Run `buddy sms:status` to check current status")}else{console.log(`
437
+ \u274C SMS setup completed with errors:
438
+ `);for(let z of G.errors)console.log(` - ${z}`)}}catch(J){if(console.error("Error setting up SMS:",J.message),J.message.includes("timeout"))console.log(`
439
+ \uD83D\uDCA1 Setup timed out. Some operations may have completed.`),console.log(" Run `buddy sms:status` to check current status.")}process.exit(0)}),Q.command("sms:add-phone <phone>",k$["add-phone"]).action(async($)=>{console.log(`
440
+ \uD83D\uDCF1 Adding ${$} to SMS sandbox...
441
+ `),y$();try{let{PinpointSmsVoiceClient:J}=await import("@stacksjs/ts-cloud"),Y=new J(process.env.AWS_REGION||"us-east-1"),G=await W$(Y.addSandboxPhone($),30000);if(G.status==="VERIFIED")console.log("\u2705 Phone is already verified!"),console.log(` ID: ${G.verifiedDestinationNumberId}`);else if(G.status==="PENDING")console.log("\uD83D\uDCE8 Verification code sent to phone!"),console.log(` ID: ${G.verifiedDestinationNumberId}`),console.log(`
442
+ \uD83D\uDCA1 Next step:`),console.log(` Run: buddy sms:verify ${G.verifiedDestinationNumberId} <code>`),console.log(" Replace <code> with the 6-digit code you received");else console.log("\u2753 Unexpected status:",G.status),console.log(" Message:",G.message)}catch(J){if(console.error("Error adding phone:",J.message),J.message.includes("already exists"))console.log(`
443
+ \uD83D\uDCA1 Phone number may already be in the sandbox.`),console.log(" Run `buddy sms:status` to check sandbox numbers.")}process.exit(0)}),Q.command("sms:verify <id> <code>",k$.verify).action(async($,J)=>{console.log(`
444
+ \uD83D\uDCF1 Verifying sandbox phone...
445
+ `),y$();try{let{PinpointSmsVoiceClient:Y}=await import("@stacksjs/ts-cloud"),G=new Y(process.env.AWS_REGION||"us-east-1"),z=await W$(G.verifySandboxPhone($,J),30000);if(z.success)console.log("\u2705 Phone verified successfully!"),console.log(` Phone: ${z.phoneNumber}`),console.log(`
446
+ \uD83D\uDCA1 You can now send SMS to this phone while in sandbox mode.`),console.log(` Run: buddy sms:send ${z.phoneNumber} "Test message"`);else console.log("\u274C Verification failed"),console.log(` Error: ${z.message}`),console.log(`
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
+ \uD83D\uDCF1 Sandbox Verified Numbers
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};