@stacksjs/ts-cloud 0.9.2 → 0.9.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/aws/index.js +1 -269
- package/dist/bin/chunk-00kg80qg.js +1 -0
- package/dist/bin/chunk-09nwf2gy.js +34 -0
- package/dist/bin/chunk-1k5kszjp.js +111 -0
- package/dist/bin/chunk-21e0mavm.js +1 -0
- package/dist/bin/chunk-271gk1n2.js +6 -0
- package/dist/bin/chunk-2empps47.js +2 -0
- package/dist/bin/chunk-38pq971s.js +2 -0
- package/dist/bin/chunk-3gykfyq4.js +37 -0
- package/dist/bin/chunk-3vqfexc4.js +70 -0
- package/dist/bin/chunk-4vrqm9h0.js +2 -0
- package/dist/bin/chunk-598yf4bs.js +1 -0
- package/dist/bin/chunk-5ectjq0b.js +1 -0
- package/dist/bin/chunk-5erkxpt7.js +512 -0
- package/dist/bin/chunk-5mrtzemj.js +1 -0
- package/dist/bin/chunk-5n9fmabb.js +1 -0
- package/dist/bin/chunk-9knpg30y.js +1 -0
- package/dist/bin/chunk-9pvsff8g.js +1 -0
- package/dist/bin/chunk-ax9mr6wm.js +44 -0
- package/dist/bin/chunk-axhnkn5g.js +2 -0
- package/dist/bin/chunk-c1vcdgvr.js +1 -0
- package/dist/bin/chunk-ctd2vg9w.js +2 -0
- package/dist/bin/chunk-dbgffky8.js +1 -0
- package/dist/bin/chunk-ddk4rt4j.js +6 -0
- package/dist/bin/chunk-dwr30vbv.js +1 -0
- package/dist/bin/chunk-e0rkrq70.js +1 -0
- package/dist/bin/chunk-e3xrwh9z.js +1 -0
- package/dist/bin/chunk-etrb03mt.js +1507 -0
- package/dist/bin/chunk-fhc6ntvd.js +2 -0
- package/dist/bin/chunk-fpm59y25.js +6 -0
- package/dist/bin/chunk-fvbxvq6b.js +1 -0
- package/dist/bin/chunk-fy8j3y8p.js +92 -0
- package/dist/bin/chunk-fz21b57w.js +1 -0
- package/dist/bin/chunk-gavvf0pg.js +141 -0
- package/dist/bin/chunk-ggn7ax8p.js +4 -0
- package/dist/bin/chunk-gpe2prkm.js +1 -0
- package/dist/bin/chunk-h5pa5men.js +2 -0
- package/dist/bin/chunk-hm08xdxf.js +2 -0
- package/dist/bin/chunk-hzgz13nf.js +1 -0
- package/dist/bin/chunk-j703btc5.js +50 -0
- package/dist/bin/chunk-k9t9wvms.js +1 -0
- package/dist/bin/chunk-m669wtgr.js +1 -0
- package/dist/bin/chunk-m7dgskt1.js +1 -0
- package/dist/bin/chunk-mh0kdzqp.js +2 -0
- package/dist/bin/chunk-mr0atd2s.js +2 -0
- package/dist/bin/chunk-mz0wbbsj.js +3 -0
- package/dist/bin/chunk-ngcyftm2.js +1 -0
- package/dist/bin/chunk-p66ptpmr.js +2 -0
- package/dist/bin/chunk-qk9qgepa.js +1 -0
- package/dist/bin/chunk-rxcvf10f.js +7364 -0
- package/dist/bin/chunk-rytk89az.js +60 -0
- package/dist/bin/chunk-tga3hhwk.js +6 -0
- package/dist/bin/chunk-tx0tqq2k.js +8 -0
- package/dist/bin/chunk-vek8a0w6.js +1 -0
- package/dist/bin/chunk-vm3q5gf2.js +3 -0
- package/dist/bin/chunk-y7s5r8y6.js +3 -0
- package/dist/bin/chunk-yv9sth30.js +1 -0
- package/dist/bin/chunk-zmegvjp8.js +581 -0
- package/dist/bin/cli.js +417 -10597
- package/dist/bin/dashboard-server.js +1 -6998
- package/dist/chunk-0ccta6z6.js +6 -0
- package/dist/chunk-0k1cs6pp.js +1 -0
- package/dist/chunk-1egjn203.js +704 -0
- package/dist/chunk-2wx29qga.js +5 -0
- package/dist/chunk-5m5rqmv7.js +1 -0
- package/dist/chunk-8ea5022g.js +114 -0
- package/dist/chunk-8xqn3c0w.js +2 -0
- package/dist/chunk-b4esxhmw.js +2 -0
- package/dist/chunk-b8e5wzwn.js +44 -0
- package/dist/chunk-bggt4n6e.js +2 -0
- package/dist/chunk-cwkg37rs.js +37 -0
- package/dist/chunk-dskvqt67.js +7355 -0
- package/dist/chunk-gahsdmxf.js +1617 -0
- package/dist/chunk-gnv3r2jg.js +1 -0
- package/dist/chunk-hg3c48cp.js +34 -0
- package/dist/chunk-m5azeva3.js +2 -0
- package/dist/chunk-r3qf56b3.js +92 -0
- package/dist/chunk-sdqa9ghv.js +141 -0
- package/dist/chunk-svrvvcm7.js +1 -0
- package/dist/chunk-v0p3hpc3.js +60 -0
- package/dist/chunk-wdzjbecg.js +50 -0
- package/dist/chunk-ww8k3g7j.js +1 -0
- package/dist/chunk-xmqfc62w.js +1 -0
- package/dist/chunk-xrebj679.js +435 -0
- package/dist/chunk-xt3s24vr.js +2 -0
- package/dist/chunk-y21zk0pn.js +4 -0
- package/dist/deploy/attach-credentials.d.ts +57 -0
- package/dist/deploy/index.js +1 -168
- package/dist/deploy/site-ports.d.ts +151 -0
- package/dist/deploy/site-target.d.ts +24 -1
- package/dist/dns/index.js +1 -41
- package/dist/drivers/index.js +1 -154
- package/dist/index.js +100 -6129
- package/dist/protection/index.js +1 -89
- package/dist/push/index.js +1 -509
- package/dist/spend/index.js +1 -173
- package/dist/ui/404.html +16 -548
- package/dist/ui/_stx/chunk.5ddb5087.js +90 -0
- package/dist/ui/_stx/chunk.9fd39d5b.js +86 -0
- package/dist/ui/_stx/chunk.d5301f79.js +119 -0
- package/dist/ui/_stx/crosswind.222ed683.css +1 -0
- package/dist/ui/_stx/crosswind.616c25f3.css +1 -0
- package/dist/ui/_stx/crosswind.80baa894.css +320 -0
- package/dist/ui/_stx/crosswind.906ee17c.css +1 -0
- package/dist/ui/_stx/crosswind.996ed49e.css +1 -0
- package/dist/ui/_stx/crosswind.b7a99a5c.css +1 -0
- package/dist/ui/_stx/router.fa5bc4dc.js +4 -0
- package/dist/ui/_stx/runtime.c696d17a.js +1 -0
- package/dist/ui/_stx/style.448ab192.css +1 -0
- package/dist/ui/accept-invitation.html +2 -1133
- package/dist/ui/access-denied.html +7 -1130
- package/dist/ui/account/automation.html +12 -1134
- package/dist/ui/account/security.html +13 -1136
- package/dist/ui/applications/compose.html +12 -1134
- package/dist/ui/applications/new.html +13 -1137
- package/dist/ui/data/backups.html +91 -1136
- package/dist/ui/data/services.html +89 -1136
- package/dist/ui/data/volumes.html +61 -1136
- package/dist/ui/index.html +60 -1136
- package/dist/ui/infrastructure/topology.html +128 -1135
- package/dist/ui/integrations.html +13 -1138
- package/dist/ui/operations/alerts.html +59 -1136
- package/dist/ui/operations/configuration.html +13 -1135
- package/dist/ui/operations/jobs.html +87 -1136
- package/dist/ui/operations/maintenance.html +12 -1134
- package/dist/ui/operations/observability.html +93 -1136
- package/dist/ui/operations/previews.html +12 -1134
- package/dist/ui/operations/queue.html +12 -1134
- package/dist/ui/operations/regions.html +12 -1134
- package/dist/ui/operations/releases.html +12 -1134
- package/dist/ui/operations/spend.html +65 -1136
- package/dist/ui/operations/workloads.html +115 -1136
- package/dist/ui/robots.txt +2 -0
- package/dist/ui/security.html +24 -1136
- package/dist/ui/server/actions.html +67 -1138
- package/dist/ui/server/activity.html +7 -1130
- package/dist/ui/server/capacity.html +12 -1134
- package/dist/ui/server/database.html +166 -1135
- package/dist/ui/server/deployments.html +60 -1136
- package/dist/ui/server/diagnostics.html +7 -1130
- package/dist/ui/server/firewall.html +286 -1212
- package/dist/ui/server/fleet.html +45 -1136
- package/dist/ui/server/logs.html +34 -1135
- package/dist/ui/server/metrics.html +124 -1140
- package/dist/ui/server/security.html +7 -1130
- package/dist/ui/server/services.html +46 -1133
- package/dist/ui/server/sites.html +287 -1137
- package/dist/ui/server/ssh-keys.html +62 -1135
- package/dist/ui/server/team.html +155 -1136
- package/dist/ui/server/terminal.html +97 -1183
- package/dist/ui/serverless/alarms.html +62 -1135
- package/dist/ui/serverless/assets.html +47 -1132
- package/dist/ui/serverless/cost.html +7 -1130
- package/dist/ui/serverless/data.html +46 -1135
- package/dist/ui/serverless/deployments.html +47 -1132
- package/dist/ui/serverless/firewall.html +7 -1130
- package/dist/ui/serverless/functions.html +50 -1136
- package/dist/ui/serverless/logs.html +34 -1135
- package/dist/ui/serverless/metrics.html +7 -1130
- package/dist/ui/serverless/queues.html +58 -1135
- package/dist/ui/serverless/secrets.html +62 -1136
- package/dist/ui/serverless/traces.html +12 -1134
- package/dist/ui/serverless.html +64 -1137
- package/dist/ui-src/pages/server/firewall.stx +14 -14
- package/package.json +3 -3
- package/dist/chunk-01d86gt1.js +0 -1324
- package/dist/chunk-050r7ycy.js +0 -46516
- package/dist/chunk-29rse4p1.js +0 -12203
- package/dist/chunk-32e7ya18.js +0 -642
- package/dist/chunk-4cjrg98a.js +0 -597
- package/dist/chunk-50jpda9q.js +0 -371
- package/dist/chunk-6a1t7fnq.js +0 -12121
- package/dist/chunk-728jvrr0.js +0 -1701
- package/dist/chunk-7m60qnc8.js +0 -1762
- package/dist/chunk-aa2dkn7b.js +0 -205
- package/dist/chunk-d48vtdj4.js +0 -433
- package/dist/chunk-f55nkpvb.js +0 -8
- package/dist/chunk-fgk8cqew.js +0 -152
- package/dist/chunk-he9a874b.js +0 -769
- package/dist/chunk-hg7rhrgd.js +0 -7274
- package/dist/chunk-k2yyatfw.js +0 -10
- package/dist/chunk-k4px0bnv.js +0 -23
- package/dist/chunk-nsgqsmrh.js +0 -1779
- package/dist/chunk-qr803fye.js +0 -2122
- package/dist/chunk-rds0sy87.js +0 -1771
- package/dist/chunk-rxgchb08.js +0 -42033
- package/dist/chunk-ttz2ra5j.js +0 -12
- package/dist/chunk-v0bahtg2.js +0 -4
- package/dist/chunk-va2yd85b.js +0 -200
- package/dist/chunk-x9s0cqfx.js +0 -13
- package/dist/chunk-zqtpg06c.js +0 -1752
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import{hd as c,id as f,jd as a,kd as r,ld as s}from"./chunk-ctd2vg9w.js";import{nd as p}from"./chunk-gavvf0pg.js";import{Uf as l}from"./chunk-h5pa5men.js";import{Zf as D}from"./chunk-j703btc5.js";import{$f as w}from"./chunk-fy8j3y8p.js";import{Vo as m}from"./chunk-mh0kdzqp.js";function n(G){let{bucketName:Q,domain:z,aliases:q,certificateArn:F,defaultRootObject:J="index.html",errorDocument:_="404.html",passthroughUrls:$=!1,singlePageApp:W=!1,dynamicApp:j=!1,computeOriginDomain:S,computeOriginPort:B=3008,computeOriginId:x="app-compute",retainOnStackDelete:C=!1}=G,M=C?{DeletionPolicy:"Retain",UpdateReplacePolicy:"Retain"}:{},y=j&&!!S,R=y?["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"]:["GET","HEAD"],N=y?["GET","HEAD"]:["GET","HEAD"],I={},h={};I.S3Bucket={Type:"AWS::S3::Bucket",...M,Properties:{BucketName:Q,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:J,ErrorDocument:_}}},h.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},h.BucketArn={Description:"S3 Bucket ARN",Value:{"Fn::GetAtt":["S3Bucket","Arn"]}},I.CloudFrontOAC={Type:"AWS::CloudFront::OriginAccessControl",...M,Properties:{OriginAccessControlConfig:{Name:`OAC-${Q}`,Description:`OAC for ${Q}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}};let E;if($&&y)E="InstallRootRedirectFunction",I[E]={Type:"AWS::CloudFront::Function",Properties:{Name:{"Fn::Sub":"${AWS::StackName}-install-root-redirect"},AutoPublish:!0,FunctionConfig:{Comment:"Redirect curl pantry.dev | bash (GET /) to /install.sh on S3",Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) {
|
|
2
|
+
var request = event.request;
|
|
3
|
+
if (request.uri === '/' || request.uri === '') {
|
|
4
|
+
return {
|
|
5
|
+
statusCode: 302,
|
|
6
|
+
statusDescription: 'Found',
|
|
7
|
+
headers: {
|
|
8
|
+
location: { value: 'https://' + request.headers.host.value + '/install.sh' }
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
return request;
|
|
13
|
+
}`}};if(!$)I.UrlRewriteFunction={Type:"AWS::CloudFront::Function",Properties:{Name:{"Fn::Sub":"${AWS::StackName}-url-rewrite"},AutoPublish:!0,FunctionConfig:{Comment:"Append .html extension to URLs without extensions",Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) {
|
|
14
|
+
const request = event.request;
|
|
15
|
+
var uri = request.uri;
|
|
16
|
+
|
|
17
|
+
// If URI ends with /, serve index.html
|
|
18
|
+
if (uri.endsWith('/')) {
|
|
19
|
+
request.uri = uri + 'index.html';
|
|
20
|
+
}
|
|
21
|
+
// If URI doesn't have an extension, append .html
|
|
22
|
+
else if (!uri.includes('.')) {
|
|
23
|
+
request.uri = uri + '.html';
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
return request;
|
|
27
|
+
}`}};let O={Id:`S3-${Q}`,DomainName:{"Fn::GetAtt":["S3Bucket","RegionalDomainName"]},S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{"Fn::GetAtt":["CloudFrontOAC","Id"]}},K=y?{Id:x,DomainName:S,CustomOriginConfig:{HTTPPort:B,HTTPSPort:443,OriginProtocolPolicy:"http-only",OriginSSLProtocols:["TLSv1.2"]}}:null,Z=y?x:`S3-${Q}`,U={Enabled:!0,DefaultRootObject:J,HttpVersion:"http2and3",IPV6Enabled:!0,PriceClass:"PriceClass_100",Origins:K?[K,O]:[O],DefaultCacheBehavior:{TargetOriginId:Z,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:R,CachedMethods:N,Compress:!0,...y?{CachePolicyId:"4135ea2d-6df8-44a3-9df3-4b5a84be39ad",OriginRequestPolicyId:"b689b0a8-53d0-40ab-baf2-68738e2966ac",...$&&E?{FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":[E,"FunctionARN"]}}]}:{}}:{CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",...!$&&{FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":["UrlRewriteFunction","FunctionARN"]}}]}}},...y&&$?{CacheBehaviors:[{PathPattern:"/install.sh",TargetOriginId:`S3-${Q}`,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6"}]}:{},CustomErrorResponses:W?[{ErrorCode:403,ResponseCode:200,ResponsePagePath:`/${J}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:200,ResponsePagePath:`/${J}`,ErrorCachingMinTTL:300}]:[{ErrorCode:403,ResponseCode:404,ResponsePagePath:`/${_}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:404,ResponsePagePath:`/${_}`,ErrorCachingMinTTL:300}]};if(z&&F)U.Aliases=q&&q.length>0?q:[z],U.ViewerCertificate={AcmCertificateArn:F,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};else U.ViewerCertificate={CloudFrontDefaultCertificate:!0};return I.CloudFrontDistribution={Type:"AWS::CloudFront::Distribution",...M,DependsOn:["S3Bucket","CloudFrontOAC",...$&&y&&E?[E]:[],...!$?["UrlRewriteFunction"]:[]],Properties:{DistributionConfig:U}},h.DistributionId={Description:"CloudFront Distribution ID",Value:{Ref:"CloudFrontDistribution"}},h.DistributionDomain={Description:"CloudFront Distribution Domain",Value:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]}},I.S3BucketPolicy={Type:"AWS::S3::BucketPolicy",...M,DependsOn:["S3Bucket","CloudFrontDistribution"],Properties:{Bucket:{Ref:"S3Bucket"},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":"arn:aws:s3:::${S3Bucket}/*"},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":"arn:aws:cloudfront::${AWS::AccountId}:distribution/${CloudFrontDistribution}"}}}}]}}},h.SiteUrl={Description:"Site URL",Value:z?`https://${z}`:{"Fn::Sub":"https://${CloudFrontDistribution.DomainName}"}},{AWSTemplateFormatVersion:"2010-09-09",Description:`Static site infrastructure for ${z||Q} (External DNS)`,Resources:I,Outputs:h}}async function d(G){let Q=G.region||"us-east-1",z="us-east-1",q=G.domain,F=G.bucket||q.replace(/\./g,"-"),J=G.stackName||`${G.siteName}-static-site`,_=new l("us-east-1"),$=new f("us-east-1"),W=null;if(!G.skipDnsVerification){W=s(G.dnsProvider),console.log(`Verifying DNS provider can manage ${q}...`);let X=await W.listRecords(q);if(!X.success){let Y=X.message||"unknown error — check API credentials and domain ownership";return{success:!1,stackName:J,bucket:F,message:`DNS provider '${W.name}' cannot manage domain ${q}: ${Y}`}}console.log(`DNS provider '${W.name}' verified for ${q}`)}else console.log(`Skipping DNS verification for ${q}`);let j=G.certificateArn,x=q.split(".").length===2?`www.${q}`:void 0;if(!j){console.log(`Checking for existing SSL certificate for ${q}...`);let X=await $.findCertificateByDomain(q),Y=!1;if(X&&X.Status==="ISSUED"){if(x&&X.SubjectAlternativeNames)Y=X.SubjectAlternativeNames.includes(x)||X.SubjectAlternativeNames.some((V)=>V===`*.${q}`);else Y=!0;if(Y)j=X.CertificateArn,console.log(`Found existing certificate with www coverage: ${j}`);else console.log(`Existing certificate doesn't cover ${x}, requesting new one...`)}if(!j){if(!W)return{success:!1,stackName:J,bucket:F,message:`No DNS provider available to validate SSL certificate for ${q}. Provide a certificateArn or enable DNS verification.`};console.log(`Requesting new SSL certificate for ${q}${x?` (including ${x})`:""}...`);let T=await new r(W,"us-east-1").findOrCreateCertificate({domainName:q,subjectAlternativeNames:x?[x]:void 0,waitForValidation:!0,maxWaitMinutes:10});if(T.status!=="issued")return{success:!1,stackName:J,bucket:F,message:`SSL certificate validation failed. Status: ${T.status}`};j=T.certificateArn,console.log(`Certificate issued: ${j}`)}}let C=!1,M;try{let X=await _.describeStacks({stackName:J});if(X.Stacks.length>0){let Y=X.Stacks[0],V=Y.StackStatus;if(V==="DELETE_IN_PROGRESS")console.log("Previous stack is still being deleted, waiting..."),await _.waitForStack(J,"stack-delete-complete"),C=!1;else if(V==="DELETE_COMPLETE")C=!1;else C=!0,M=(Y.Outputs||[]).find((H)=>H.OutputKey==="BucketName")?.OutputValue}}catch(X){if(X.message?.includes("does not exist")||X.code==="ValidationError")C=!1;else throw X}let y=M||F;if(!C){let X=new w(Q),Y=new p,V=!1;if(q)try{console.log(`Checking for existing CloudFront distributions with alias ${q}...`);let T=await Y.listDistributions();for(let H of T){let L=[];if(H.Aliases?.Items){if(Array.isArray(H.Aliases.Items))L=H.Aliases.Items;else if(typeof H.Aliases.Items==="object"){let v=H.Aliases.Items.CNAME;if(typeof v==="string")L=[v];else if(Array.isArray(v))L=v}}if(L.includes(q)){V=!0,console.log(`Found existing CloudFront distribution ${H.Id} with alias ${q}`),console.log("Reusing existing infrastructure for updates...");let A=(await Y.getDistributionConfig(H.Id)).DistributionConfig?.Origins?.Items,b;if(A){let P=[];if(Array.isArray(A))P=A;else if(A.Origin)P=Array.isArray(A.Origin)?A.Origin:[A.Origin];else P=[A];for(let g of P){let k=(g.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(k){b=k[1];break}}}if(b)return console.log(`Using existing S3 bucket: ${b}`),{success:!0,stackName:`existing-${H.Id}`,bucket:b,distributionId:H.Id,distributionDomain:H.DomainName,domain:q,certificateArn:j,message:"Using existing CloudFront distribution",_existingInfrastructure:!0}}}}catch{}if(!V)try{if((await X.headBucket(F)).exists){console.log(`Found orphaned S3 bucket ${F}, cleaning up...`);try{let H=X.emptyBucket(F).then(()=>X.deleteBucket(F)),L=new Promise((v,A)=>setTimeout(()=>A(Error("Bucket cleanup timeout")),30000));await Promise.race([H,L]),console.log(`Deleted orphaned S3 bucket ${F}`)}catch(H){console.log(`Note: Could not clean up S3 bucket: ${H.message}`);let L=Date.now().toString(36);y=`${F}-${L}`,console.log(`Using alternative bucket name: ${y}`)}}}catch{}}let N=n({bucketName:y,domain:q,aliases:x?[q,x]:[q],certificateArn:j,defaultRootObject:G.defaultRootObject,errorDocument:G.errorDocument,passthroughUrls:G.passthroughUrls,singlePageApp:G.singlePageApp,dynamicApp:G.dynamicApp,computeOriginDomain:G.computeOriginDomain,computeOriginPort:G.computeOriginPort,computeOriginId:G.computeOriginId}),I=Object.entries(G.tags||{}).map(([X,Y])=>({Key:X,Value:Y}));if(I.push({Key:"ManagedBy",Value:"ts-cloud"}),I.push({Key:"Application",Value:G.siteName}),W)I.push({Key:"DnsProvider",Value:W.name});let h,E=!1;if(C){E=!0,console.log(`Updating CloudFormation stack: ${J}`);try{h=(await _.updateStack({stackName:J,templateBody:JSON.stringify(N),capabilities:["CAPABILITY_IAM"],tags:I})).StackId,console.log(`Update initiated, stack ID: ${h}`)}catch(X){if(X.message?.includes("No updates are to be performed")){let Y=await _.describeStacks({stackName:J});h=Y.Stacks[0].StackId;let V=Y.Stacks[0]?.Outputs||[],T=(L)=>V.find((v)=>v.OutputKey===L)?.OutputValue,H=T("DistributionDomain");if(H)await u(W,q,H);return{success:!0,stackId:h,stackName:J,bucket:T("BucketName")||y,distributionId:T("DistributionId"),distributionDomain:H,domain:q,certificateArn:j,message:"Static site infrastructure is already up to date"}}else throw X}}else console.log(`Creating CloudFormation stack: ${J}`),console.log(`Bucket name: ${y}`),console.log(`Domain: ${q}`),console.log(`Certificate ARN: ${j}`),h=(await _.createStack({stackName:J,templateBody:JSON.stringify(N),capabilities:["CAPABILITY_IAM"],tags:I,onFailure:"DELETE"})).StackId,console.log(`Create initiated, stack ID: ${h}`);console.log(`Waiting for stack to reach ${E?"stack-update-complete":"stack-create-complete"}...`);try{await _.waitForStack(J,E?"stack-update-complete":"stack-create-complete"),console.log("Stack operation completed successfully!")}catch(X){if(X.message?.includes("must be verified")||X.message?.includes("Access denied for operation")){console.log("CloudFront account verification required - checking for existing infrastructure...");try{let V=new p,T=await V.listDistributions();for(let H of T){let L=[];if(H.Aliases?.Items){if(Array.isArray(H.Aliases.Items))L=H.Aliases.Items;else if(typeof H.Aliases.Items==="object"){let v=H.Aliases.Items.CNAME;if(typeof v==="string")L=[v];else if(Array.isArray(v))L=v}}if(L.includes(q)){console.log(`Found existing CloudFront distribution ${H.Id} with alias ${q}`),console.log("Using existing infrastructure despite account verification requirement...");let A=(await V.getDistributionConfig(H.Id)).DistributionConfig?.Origins?.Items,b;if(A){let P=[];if(Array.isArray(A))P=A;else if(A.Origin)P=Array.isArray(A.Origin)?A.Origin:[A.Origin];else P=[A];for(let g of P){let k=(g.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(k){b=k[1];break}}}if(b){console.log(`Using existing S3 bucket: ${b}`);let P=H.DomainName;if(P)await u(W,q,P);return{success:!0,stackName:`existing-${H.Id}`,bucket:b,distributionId:H.Id,distributionDomain:H.DomainName,domain:q,certificateArn:j,message:"Using existing CloudFront distribution (account verification pending for new distributions)"}}}}}catch{}return console.log(`
|
|
28
|
+
┌─────────────────────────────────────────────────────────────────────────────┐
|
|
29
|
+
│ AWS ACCOUNT VERIFICATION REQUIRED │
|
|
30
|
+
├─────────────────────────────────────────────────────────────────────────────┤
|
|
31
|
+
│ Your AWS account must be verified before you can create CloudFront │
|
|
32
|
+
│ distributions. This is a one-time requirement for new AWS accounts. │
|
|
33
|
+
│ │
|
|
34
|
+
│ To verify your account: │
|
|
35
|
+
│ │
|
|
36
|
+
│ 1. Go to: https://console.aws.amazon.com/support/home#/ │
|
|
37
|
+
│ 2. Click "Create case" │
|
|
38
|
+
│ 3. Select "Service limit increase" │
|
|
39
|
+
│ 4. For Service: Select "CloudFront" │
|
|
40
|
+
│ 5. For Request: "Please verify my account for CloudFront access" │
|
|
41
|
+
│ 6. Submit the case │
|
|
42
|
+
│ │
|
|
43
|
+
│ Verification typically takes 1-2 business days. │
|
|
44
|
+
│ After verification, re-run: bunx bunpress deploy │
|
|
45
|
+
└─────────────────────────────────────────────────────────────────────────────┘`),{success:!1,stackId:h,stackName:J,bucket:y,message:"CloudFront account verification required. Please contact AWS Support."}}return{success:!1,stackId:h,stackName:J,bucket:y,message:`Stack deployment failed: ${X.message}`}}let K=(await _.describeStacks({stackName:J})).Stacks[0]?.Outputs||[],Z=(X)=>K.find((Y)=>Y.OutputKey===X)?.OutputValue,U=Z("DistributionDomain");if(U&&W)console.log(`Creating DNS records via ${W.name}...`),await u(W,q,U);else if(U&&!W)console.log("Skipping DNS record creation (DNS verification was skipped)");return{success:!0,stackId:h,stackName:J,bucket:Z("BucketName")||y,distributionId:Z("DistributionId"),distributionDomain:U,domain:q,certificateArn:j,message:"Static site infrastructure deployed successfully with external DNS"}}async function u(G,Q,z){if(!G){console.log("Skipping DNS record creation (DNS verification was skipped)");return}if(Q.split(".").length===2)if(G instanceof c){console.log(`Creating Route53 alias record for apex domain ${Q} -> ${z}`);let J=await G.createCloudFrontAlias({domain:Q,name:Q,cloudFrontDomainName:z});if(!J.success)console.warn(`Warning: Could not create Route53 alias record: ${J.message}`),console.warn("Please manually create an A-record alias in Route53:"),console.warn(` ${Q} -> ${z}`);else console.log(`Created Route53 alias record: ${Q} -> ${z}`);let _=`www.${Q}`;console.log(`Creating Route53 alias record for ${_} -> ${z}`);let $=await G.createCloudFrontAlias({domain:Q,name:_,cloudFrontDomainName:z});if(!$.success)console.warn(`Warning: Could not create www Route53 alias: ${$.message}`),console.warn("Please manually create an A-record alias in Route53:"),console.warn(` ${_} -> ${z}`);else console.log(`Created Route53 alias record: ${_} -> ${z}`)}else{try{let W=await G.listRecords(Q,"A");if(W.success)for(let j of W.records){let S=j.name.replace(/\.$/,"");if(S===Q||S==="")console.log(`Removing existing root A record (${j.content}) to make room for ALIAS...`),await G.deleteRecord(Q,{name:Q,type:"A",content:j.content})}}catch(W){console.log(`Note: Could not check for conflicting A records: ${W instanceof Error?W.message:W}`)}console.log(`Creating ALIAS record for apex domain ${Q} -> ${z}`);let J=await G.upsertRecord(Q,{name:Q,type:"ALIAS",content:z,ttl:600});if(!J.success)console.warn(`Warning: Could not create ALIAS record: ${J.message}`),console.warn("Please manually create an ALIAS record in your DNS provider:"),console.warn(` ${Q} -> ${z}`);else console.log(`Created ALIAS record: ${Q} -> ${z}`);let _=`www.${Q}`;console.log(`Creating CNAME record for ${_} -> ${z}`);let $=await G.upsertRecord(Q,{name:_,type:"CNAME",content:z,ttl:600});if(!$.success)console.warn(`Warning: Could not create www DNS record: ${$.message}`),console.warn("Please manually create a CNAME record:"),console.warn(` ${_} -> ${z}`);else console.log(`Created CNAME record: ${_} -> ${z}`)}else{console.log(`Creating CNAME record for ${Q} -> ${z}`);let J=await G.upsertRecord(Q,{name:Q,type:"CNAME",content:z,ttl:600});if(!J.success)console.warn(`Warning: Could not create DNS record: ${J.message}`),console.warn("Please manually create a CNAME record:"),console.warn(` ${Q} -> ${z}`);else console.log(`Created CNAME record: ${Q} -> ${z}`)}}async function Hq(G){let{sourceDir:Q,cleanBucket:z=!1,onProgress:q,...F}=G;q?.("infrastructure","Deploying CloudFormation stack...");let J=await d(F);if(!J.success)return J;if(z){q?.("clean","Cleaning old files from S3...");try{await new w(F.region||"us-east-1").emptyBucket(J.bucket)}catch(j){console.log(`Note: Could not clean bucket: ${j.message}`)}}q?.("upload","Uploading files to S3...");let{uploadStaticFiles:_}=await import("./chunk-ngcyftm2.js"),$=await _({sourceDir:Q,bucket:J.bucket,region:F.region||"us-east-1",cacheControl:F.cacheControl,onProgress:(j,S,B)=>{q?.("upload",`${j}/${S}: ${B}`)}});if($.errors.length>0)return{...J,success:!1,message:`Upload errors: ${$.errors.join(", ")}`,filesUploaded:$.uploaded};if(J.distributionId&&$.uploaded>0){q?.("invalidate","Invalidating CloudFront cache...");let{invalidateCache:j}=await import("./chunk-ngcyftm2.js");await j(J.distributionId)}q?.("complete","Deployment complete!");let W=$.skipped>0?`Deployed ${$.uploaded} files (${$.skipped} unchanged) with external DNS`:`Deployed ${$.uploaded} files successfully with external DNS`;return{...J,filesUploaded:$.uploaded,filesSkipped:$.skipped,message:W}}function t(G){let{bucketName:Q,domain:z,certificateArn:q,hostedZoneId:F,defaultRootObject:J="index.html",errorDocument:_="404.html"}=G,$={},W={};$.S3Bucket={Type:"AWS::S3::Bucket",Properties:{BucketName:Q,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:J,ErrorDocument:_}}},W.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},W.BucketArn={Description:"S3 Bucket ARN",Value:{"Fn::GetAtt":["S3Bucket","Arn"]}},$.CloudFrontOAC={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`OAC-${Q}`,Description:`OAC for ${Q}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},$.UrlRewriteFunction={Type:"AWS::CloudFront::Function",Properties:{Name:{"Fn::Sub":"${AWS::StackName}-url-rewrite"},AutoPublish:!0,FunctionConfig:{Comment:"Append .html extension to URLs without extensions",Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) {
|
|
46
|
+
const request = event.request;
|
|
47
|
+
var uri = request.uri;
|
|
48
|
+
|
|
49
|
+
// If URI ends with /, serve index.html
|
|
50
|
+
if (uri.endsWith('/')) {
|
|
51
|
+
request.uri = uri + 'index.html';
|
|
52
|
+
}
|
|
53
|
+
// If URI doesn't have an extension, append .html
|
|
54
|
+
else if (!uri.includes('.')) {
|
|
55
|
+
request.uri = uri + '.html';
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
return request;
|
|
59
|
+
}`}};let j={Enabled:!0,DefaultRootObject:J,HttpVersion:"http2and3",IPV6Enabled:!0,PriceClass:"PriceClass_100",Origins:[{Id:`S3-${Q}`,DomainName:{"Fn::GetAtt":["S3Bucket","RegionalDomainName"]},S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{"Fn::GetAtt":["CloudFrontOAC","Id"]}}],DefaultCacheBehavior:{TargetOriginId:`S3-${Q}`,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD"],CachedMethods:["GET","HEAD"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":["UrlRewriteFunction","FunctionARN"]}}]},CustomErrorResponses:[{ErrorCode:403,ResponseCode:200,ResponsePagePath:`/${J}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:404,ResponsePagePath:`/${_}`,ErrorCachingMinTTL:300}]};if(z&&q)j.Aliases=[z],j.ViewerCertificate={AcmCertificateArn:q,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};else j.ViewerCertificate={CloudFrontDefaultCertificate:!0};if($.CloudFrontDistribution={Type:"AWS::CloudFront::Distribution",DependsOn:["S3Bucket","CloudFrontOAC","UrlRewriteFunction"],Properties:{DistributionConfig:j}},W.DistributionId={Description:"CloudFront Distribution ID",Value:{Ref:"CloudFrontDistribution"}},W.DistributionDomain={Description:"CloudFront Distribution Domain",Value:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]}},$.S3BucketPolicy={Type:"AWS::S3::BucketPolicy",DependsOn:["S3Bucket","CloudFrontDistribution"],Properties:{Bucket:{Ref:"S3Bucket"},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":"arn:aws:s3:::${S3Bucket}/*"},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":"arn:aws:cloudfront::${AWS::AccountId}:distribution/${CloudFrontDistribution}"}}}}]}}},z&&F)$.DNSRecord={Type:"AWS::Route53::RecordSet",DependsOn:"CloudFrontDistribution",Properties:{HostedZoneId:F,Name:z,Type:"A",AliasTarget:{DNSName:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}},$.DNSRecordIPv6={Type:"AWS::Route53::RecordSet",DependsOn:"CloudFrontDistribution",Properties:{HostedZoneId:F,Name:z,Type:"AAAA",AliasTarget:{DNSName:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}},W.SiteUrl={Description:"Site URL",Value:{"Fn::Sub":"https://${DNSRecord}"}};return{AWSTemplateFormatVersion:"2010-09-09",Description:`Static site infrastructure for ${z||Q}`,Resources:$,Outputs:W}}async function o(G){if(G.dnsProvider&&G.dnsProvider.provider!=="route53"){let K=G.domain||(G.subdomain&&G.baseDomain?`${G.subdomain}.${G.baseDomain}`:void 0);if(!K)return{success:!1,stackName:G.stackName||`${G.siteName}-static-site`,bucket:G.bucket||`${G.siteName}-${Date.now()}`,message:"Domain is required when using external DNS provider"};return d({siteName:G.siteName,region:G.region,domain:K,bucket:G.bucket,certificateArn:G.certificateArn,stackName:G.stackName,defaultRootObject:G.defaultRootObject,errorDocument:G.errorDocument,cacheControl:G.cacheControl,tags:G.tags,dnsProvider:G.dnsProvider})}let Q=G.region||"us-east-1",z="us-east-1",q;if(G.domain)q=G.domain;else if(G.subdomain&&G.baseDomain)q=`${G.subdomain}.${G.baseDomain}`;let F=G.bucket||(q?q.replace(/\./g,"-"):`${G.siteName}-${Date.now()}`),J=G.stackName||`${G.siteName}-static-site`,_=new l(z),$=new D,W=new f("us-east-1"),j=new a("us-east-1"),S=G.hostedZoneId,B=G.certificateArn;if(q&&!S){let K=await $.findHostedZoneForDomain(q);if(K)S=K.Id.replace("/hostedzone/","");else return{success:!1,stackName:J,bucket:F,message:`No Route53 hosted zone found for ${G.baseDomain||q}. Please create one first.`}}if(q&&!B&&S){let K=await W.findCertificateByDomain(q);if(K&&K.Status==="ISSUED")B=K.CertificateArn;else B=(await j.requestAndValidate({domainName:q,hostedZoneId:S,waitForValidation:!0,maxWaitMinutes:10})).certificateArn}let x=!1,C;try{let K=await _.describeStacks({stackName:J});if(K.Stacks.length>0){let Z=K.Stacks[0],U=Z.StackStatus;if(U==="DELETE_IN_PROGRESS")console.log("Previous stack is still being deleted, waiting..."),await _.waitForStack(J,"stack-delete-complete"),x=!1;else if(U==="DELETE_COMPLETE")x=!1;else x=!0,C=(Z.Outputs||[]).find((Y)=>Y.OutputKey==="BucketName")?.OutputValue}}catch(K){if(K.message?.includes("does not exist")||K.code==="ValidationError")x=!1;else throw K}let M=C||F;if(!x){let K=new w(Q),Z=new p,U=!1;if(q){try{console.log(`Checking for existing CloudFront distribution for ${q}...`);let X=await Z.listDistributions();for(let Y of X){let V=[];if(Y.Aliases?.Items){if(Array.isArray(Y.Aliases.Items))V=Y.Aliases.Items;else if(typeof Y.Aliases.Items==="object"){let T=Y.Aliases.Items.CNAME;if(typeof T==="string")V=[T];else if(Array.isArray(T))V=T}}if(V.includes(q)){U=!0,console.log(`Found existing CloudFront distribution ${Y.Id} for ${q}`);let H=(await Z.getDistributionConfig(Y.Id)).DistributionConfig?.Origins?.Items,L;if(H){let v=[];if(Array.isArray(H))v=H;else if(H.Origin)v=Array.isArray(H.Origin)?H.Origin:[H.Origin];else v=[H];for(let A of v){let P=(A.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(P){L=P[1];break}}}if(L){let v=q.replace(/\./g,"-");if(!L.startsWith(v)&&!L.includes(G.siteName)){console.log(`Warning: Found distribution with mismatched bucket ${L}, skipping...`);continue}if(console.log(`Using existing S3 bucket: ${L}`),S&&Y.DomainName)try{console.log(`Ensuring Route53 records exist for ${q}...`),await $.createAliasRecord({HostedZoneId:S,Name:q,Type:"A",TargetHostedZoneId:D.CloudFrontHostedZoneId,TargetDNSName:Y.DomainName,EvaluateTargetHealth:!1}),await $.createAliasRecord({HostedZoneId:S,Name:q,Type:"AAAA",TargetHostedZoneId:D.CloudFrontHostedZoneId,TargetDNSName:Y.DomainName,EvaluateTargetHealth:!1}),console.log(`Route53 records ensured for ${q}`)}catch(A){console.log(`Note: Could not update Route53 records: ${A.message}`)}return{success:!0,stackName:`existing-${Y.Id}`,bucket:L,distributionId:Y.Id,distributionDomain:Y.DomainName,domain:q,certificateArn:B,message:"Using existing CloudFront distribution"}}}}}catch{}if(S)try{let Y=(await $.listResourceRecordSets({HostedZoneId:S})).ResourceRecordSets||[];for(let V of Y)if(V.Name===`${q}.`&&(V.Type==="A"||V.Type==="AAAA")){if(V.AliasTarget){console.log(`Found orphaned Route53 ${V.Type} record for ${q}, cleaning up...`);try{await $.deleteRecord({HostedZoneId:S,RecordSet:V}),console.log(`Deleted orphaned Route53 ${V.Type} record for ${q}`)}catch(T){console.log(`Note: Could not delete Route53 record: ${T.message}`)}}}}catch{}}if(!U)try{if((await K.headBucket(F)).exists){console.log(`Found orphaned S3 bucket ${F}, cleaning up...`);try{let Y=K.emptyBucket(F).then(()=>K.deleteBucket(F)),V=new Promise((T,H)=>setTimeout(()=>H(Error("Bucket cleanup timeout")),30000));await Promise.race([Y,V]),console.log(`Deleted orphaned S3 bucket ${F}`)}catch(Y){console.log(`Note: Could not clean up S3 bucket: ${Y.message}`);let V=Date.now().toString(36);M=`${F}-${V}`,console.log(`Using alternative bucket name: ${M}`)}}}catch{}}let y=t({bucketName:M,domain:q,certificateArn:B,hostedZoneId:S,defaultRootObject:G.defaultRootObject,errorDocument:G.errorDocument}),R=Object.entries(G.tags||{}).map(([K,Z])=>({Key:K,Value:Z}));R.push({Key:"ManagedBy",Value:"ts-cloud"}),R.push({Key:"Application",Value:G.siteName});let N,I=!1;if(x){I=!0,console.log(`Updating CloudFormation stack: ${J}`),console.log(`Using existing bucket: ${M}`),console.log(`Domain: ${q||"not specified"}`),console.log(`Certificate ARN: ${B||"not specified"}`);try{N=(await _.updateStack({stackName:J,templateBody:JSON.stringify(y),capabilities:["CAPABILITY_IAM"],tags:R})).StackId,console.log(`Update initiated, stack ID: ${N}`)}catch(K){if(K.message?.includes("No updates are to be performed")){let Z=await _.describeStacks({stackName:J});N=Z.Stacks[0].StackId;let U=Z.Stacks[0]?.Outputs||[],X=(Y)=>U.find((V)=>V.OutputKey===Y)?.OutputValue;return{success:!0,stackId:N,stackName:J,bucket:X("BucketName")||M,distributionId:X("DistributionId"),distributionDomain:X("DistributionDomain"),domain:q,certificateArn:B,message:"Static site infrastructure is already up to date"}}else throw K}}else console.log(`Creating CloudFormation stack: ${J}`),console.log(`Bucket name: ${M}`),console.log(`Domain: ${q||"not specified"}`),console.log(`Certificate ARN: ${B||"not specified"}`),console.log("Stack does not exist, creating..."),N=(await _.createStack({stackName:J,templateBody:JSON.stringify(y),capabilities:["CAPABILITY_IAM"],tags:R,onFailure:"DELETE"})).StackId,console.log(`Create initiated, stack ID: ${N}`);console.log(`Waiting for stack to reach ${I?"stack-update-complete":"stack-create-complete"}...`);try{await _.waitForStack(J,I?"stack-update-complete":"stack-create-complete"),console.log("Stack operation completed successfully!")}catch(K){if(K.message?.includes("must be verified")||K.message?.includes("Access denied for operation")||K.message?.includes("failed")){console.log("CloudFormation deployment failed, trying direct API creation...");let Z=new p;if(q)try{let U=await Z.listDistributions();for(let X of U){let Y=[];if(X.Aliases?.Items){if(Array.isArray(X.Aliases.Items))Y=X.Aliases.Items;else if(typeof X.Aliases.Items==="object"){let V=X.Aliases.Items.CNAME;if(typeof V==="string")Y=[V];else if(Array.isArray(V))Y=V}}if(Y.includes(q)){console.log(`Found existing CloudFront distribution ${X.Id} with alias ${q}`);let T=(await Z.getDistributionConfig(X.Id)).DistributionConfig?.Origins?.Items,H;if(T){let L=[];if(Array.isArray(T))L=T;else if(T.Origin)L=Array.isArray(T.Origin)?T.Origin:[T.Origin];else L=[T];for(let v of L){let b=(v.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(b){H=b[1];break}}}if(H)return console.log(`Using existing S3 bucket: ${H}`),{success:!0,stackName:`existing-${X.Id}`,bucket:H,distributionId:X.Id,distributionDomain:X.DomainName,domain:q,certificateArn:B,message:"Using existing CloudFront distribution (account verification pending for new distributions)"}}}}catch{}console.log("No existing infrastructure found, creating via direct API calls...");try{let U=new w(Q);if((await U.headBucket(M)).exists)console.log(`Using existing S3 bucket: ${M}`);else console.log(`Creating S3 bucket: ${M}...`),await U.createBucket(M);await U.putBucketWebsite(M,{IndexDocument:G.defaultRootObject||"index.html",ErrorDocument:G.errorDocument||"404.html"}),await U.putPublicAccessBlock(M,{BlockPublicAcls:!0,IgnorePublicAcls:!0,BlockPublicPolicy:!1,RestrictPublicBuckets:!1}),console.log(`S3 bucket ${M} configured`);let Y=`OAC-${M}`;console.log(`Creating Origin Access Control: ${Y}...`);let V=await Z.findOrCreateOriginAccessControl(Y);console.log(`Origin Access Control ${V.Id} ready`),console.log("Creating CloudFront distribution...");let T=await Z.createDistributionForS3({bucketName:M,bucketRegion:Q,originAccessControlId:V.Id,aliases:q?[q]:[],certificateArn:B,defaultRootObject:G.defaultRootObject||"index.html",comment:`Distribution for ${q||M}`});console.log(`CloudFront distribution ${T.Id} created`),console.log("Updating S3 bucket policy...");let H=p.getS3BucketPolicyForCloudFront(M,T.ARN);if(await U.putBucketPolicy(M,H),console.log("S3 bucket policy updated"),q&&S){console.log(`Creating Route53 records for ${q}...`);try{await $.createAliasRecord({HostedZoneId:S,Name:q,Type:"A",TargetHostedZoneId:D.CloudFrontHostedZoneId,TargetDNSName:T.DomainName,EvaluateTargetHealth:!1}),await $.createAliasRecord({HostedZoneId:S,Name:q,Type:"AAAA",TargetHostedZoneId:D.CloudFrontHostedZoneId,TargetDNSName:T.DomainName,EvaluateTargetHealth:!1}),console.log(`Route53 records created for ${q}`)}catch(L){console.log(`Note: Could not create Route53 records: ${L.message}`)}}return{success:!0,stackName:`direct-${T.Id}`,bucket:M,distributionId:T.Id,distributionDomain:T.DomainName,domain:q,certificateArn:B,message:"Static site infrastructure created via direct API calls"}}catch(U){return console.log(`Direct API creation failed: ${U.message}`),{success:!1,stackId:N,stackName:J,bucket:M,message:`Deployment failed: ${U.message}`}}}return{success:!1,stackId:N,stackName:J,bucket:M,message:`Stack deployment failed: ${K.message}`}}let E=(await _.describeStacks({stackName:J})).Stacks[0]?.Outputs||[],O=(K)=>E.find((Z)=>Z.OutputKey===K)?.OutputValue;return{success:!0,stackId:N,stackName:J,bucket:O("BucketName")||M,distributionId:O("DistributionId"),distributionDomain:O("DistributionDomain"),domain:q,certificateArn:B,message:"Static site infrastructure deployed successfully"}}async function i(G){let{sourceDir:Q,bucket:z,region:q,cacheControl:F="max-age=31536000, public",onProgress:J}=G,_=new w(q),{readdir:$}=await import("node:fs/promises"),{join:W,relative:j}=await import("node:path"),{createHash:S}=await import("node:crypto");async function B(E){let O=[],K=await $(E,{withFileTypes:!0});for(let Z of K){let U=W(E,Z.name);if(Z.isDirectory())O.push(...await B(U));else O.push(U)}return O}function x(E){let O=E.split(".").pop()?.toLowerCase();return{html:"text/html; charset=utf-8",css:"text/css; charset=utf-8",js:"application/javascript; charset=utf-8",json:"application/json; charset=utf-8",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",ico:"image/x-icon",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",xml:"application/xml",txt:"text/plain; charset=utf-8",sh:"text/plain; charset=utf-8",bash:"text/plain; charset=utf-8",ps1:"text/plain; charset=utf-8"}[O||""]||"application/octet-stream"}function C(E){return S("md5").update(E).digest("hex")}async function M(){let E=new Map,O;do{let K=await _.listObjects({bucket:z,maxKeys:1000,continuationToken:O});for(let Z of K.objects){let U=Z.ETag?.replace(/"/g,"")||"";E.set(Z.Key,U)}O=K.nextContinuationToken}while(O);return E}let y=await B(Q),R=[],N=0,I=0,h=await M();for(let E of y){let O=j(Q,E),K=x(E),Z=E.endsWith(".html")?"max-age=3600, public":F;try{let U=Buffer.from(await Bun.file(E).arrayBuffer()),X=C(U),Y=h.get(O);if(Y&&Y===X){I++,J?.(N+I,y.length,O);continue}await _.putObject({bucket:z,key:O,body:U,contentType:K,cacheControl:Z}),N++,J?.(N+I,y.length,O)}catch(U){R.push(`Failed to upload ${O}: ${U.message}`)}}return{uploaded:N,skipped:I,errors:R}}async function qq(G){return{invalidationId:(await new p().invalidateAll(G)).Id}}async function jq(G,Q="us-east-1"){let z=new l(Q);try{let _=((await z.describeStacks({stackName:G})).Stacks[0]?.Outputs||[]).find(($)=>$.OutputKey==="BucketName")?.OutputValue;if(_)await new w(Q).emptyBucket(_)}catch{}await z.deleteStack(G);let q=await z.waitForStackComplete(G,60,1e4);return{success:q.success||q.status==="DELETE_COMPLETE",message:q.success?"Static site deleted successfully":`Deletion failed: ${q.status}`}}async function Mq(G){let{sourceDir:Q,cleanBucket:z=!1,onProgress:q,...F}=G;q?.("infrastructure","Deploying CloudFormation stack...");let J=await o(F);if(!J.success)return J;if(z){q?.("clean","Cleaning old files from S3...");try{await new w(F.region||"us-east-1").emptyBucket(J.bucket)}catch(W){console.log(`Note: Could not clean bucket: ${W.message}`)}}q?.("upload","Uploading files to S3...");let _=await i({sourceDir:Q,bucket:J.bucket,region:F.region||"us-east-1",cacheControl:F.cacheControl,onProgress:(W,j,S)=>{q?.("upload",`${W}/${j}: ${S}`)}});if(_.errors.length>0)return{...J,success:!1,message:`Upload errors: ${_.errors.join(", ")}`,filesUploaded:_.uploaded};if(J.distributionId&&_.uploaded>0)q?.("invalidate","Invalidating CloudFront cache..."),await qq(J.distributionId);q?.("complete","Deployment complete!");let $=_.skipped>0?`Deployed ${_.uploaded} files (${_.skipped} unchanged)`:`Deployed ${_.uploaded} files successfully`;return{...J,filesUploaded:_.uploaded,filesSkipped:_.skipped,message:$}}
|
|
60
|
+
export{t as p,o as q,i as r,qq as s,jq as t,Mq as u,Hq as v};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{nh as o,oh as n}from"./chunk-rxcvf10f.js";function dj(j,Z){return`/var/www/${j}-${Z}`}var Hj=new Set(["laravel","php","statamic","wordpress"]);function i(j){return j.type!=null&&Hj.has(j.type)}function Yj(j){let Z=j.proxyTo;if(Z==null)return[];return(Array.isArray(Z)?Z:[Z]).map((z)=>String(z).trim()).filter((z)=>z.length>0)}function Fj(j){return Yj(j).length>0}function t(j){if(j.deploy)return j.deploy;if(i(j))return"server";if(j.start)return"server";return"bucket"}function f(j){if(j.redirect)return"redirect";if(Fj(j))return"proxy";if(i(j))return"server-php";if(t(j)==="bucket")return"bucket";return j.start?"server-app":"server-static"}function wj(j){return j.infrastructure?.compute!=null||Boolean(j.cloud?.attachTo?.trim())}function pj(j,Z={}){let $=[],z=[],Q=j.sites||{},W=wj(j),q=n(j);if(q)$.push(q);let H=new Map;for(let[K,X]of Object.entries(Q)){if(!X)continue;let F=t(X),L=f(X);if(L==="redirect"){if(!X.domain)$.push(`Site '${K}' is a redirect site but has no \`domain\` to redirect from.`);if(!(typeof X.redirect==="string"?X.redirect:X.redirect?.to))$.push(`Site '${K}' is a redirect site but has no redirect target (\`redirect\` / \`redirect.to\`).`);if(!W)$.push(`Site '${K}' is a redirect site but no \`infrastructure.compute\` is configured to host the gateway that serves the redirect.`);let J=[];if(X.start)J.push("start");if(X.root)J.push("root");if(X.proxyTo)J.push("proxyTo");if(J.length>0)z.push(`Site '${K}' is a redirect site but also sets ${J.join(", ")}. These are ignored.`);continue}if(L==="proxy"){if(!X.domain)$.push(`Site '${K}' is a proxy site but has no \`domain\` to route from.`);if(!W)$.push(`Site '${K}' is a proxy site but no \`infrastructure.compute\` is configured to host the gateway that forwards it.`);let M=[];if(X.start)M.push("start");if(X.root)M.push("root");if(typeof X.port==="number")M.push("port");if(X.build)M.push("build");if(X.preStart&&X.preStart.length>0)M.push("preStart");if(M.length>0)z.push(`Site '${K}' sets \`proxyTo\`, so ts-cloud ships and supervises nothing for it. ${M.join(", ")} ${M.length===1?"is":"are"} ignored — remove ${M.length===1?"it":"them"}, or drop \`proxyTo\` to let ts-cloud own the service.`);continue}if(F==="server"&&!X.start&&!X.root){$.push(`Site '${K}' sets deploy:'server' but declares neither \`start\` (dynamic app) nor \`root\` (static site to serve). Add one.`);continue}if(L==="server-php"){if(!W)$.push(`Site '${K}' is a PHP site (type:'${X.type}') but no \`infrastructure.compute\` is configured. Add a server (infrastructure.compute) with PHP provisioning.`);if(!X.repository?.url)$.push(`Site '${K}' is a PHP site (type:'${X.type}') but has no \`repository.url\` to clone. PHP sites deploy via git.`)}else if(L==="server-app"){if(!W)$.push(`Site '${K}' deploys to a server (deploy:'server'${X.deploy?"":" inferred from `start`"}) but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`);if(typeof X.port==="number"){let M=Z.occupiedPorts?.get(X.port);if(M)$.push(`Site '${K}' wants port ${X.port}, which project '${M}' already serves on this box. Attached projects share one port namespace. Give '${K}' a free port, or let the attach allocate one.`);let J=H.get(X.port);if(J)$.push(`Sites '${J}' and '${K}' both use port ${X.port}. Server apps sharing a box must use distinct ports.`);else H.set(X.port,K)}}else if(L==="server-static"){if(!X.root)$.push(`Site '${K}' is a server static site (deploy:'server', no \`start\`) but has no \`root\` directory to serve.`);if(!W)$.push(`Site '${K}' deploys to a server (deploy:'server') but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`)}else{if(!X.root)$.push(`Site '${K}' deploys to a bucket but has no \`root\` directory to upload.`);let M=[];if(X.start)M.push("start");if(typeof X.port==="number")M.push("port");if(X.preStart&&X.preStart.length>0)M.push("preStart");if(M.length>0)z.push(`Site '${K}' deploys to a bucket but sets server-only field(s): ${M.join(", ")}. These are ignored. Set deploy:'server' to use them.`)}}return{errors:$,warnings:z}}function rj(j){let Z=f(j);return Z!=="bucket"&&Z!=="redirect"&&Z!=="proxy"}function oj(j){return f(j)==="bucket"}function nj(j,Z){if(o(j)==="serverless")return!0;let $=Object.entries(j.sites??{}).filter(([,Q])=>Q!=null),z=Z?$.filter(([Q])=>Q===Z):$;if(z.length===0)return!0;return!z.every(([,Q])=>{let W=f(Q);return W==="redirect"||W==="proxy"})}var s={php:"php.net",nginx:"nginx.org",composer:"getcomposer.org",mysql:"mysql.com",mariadb:"mariadb.com/server",postgres:"postgresql.org",vitess:"vitess.io",etcd:"etcd.io",redis:"redis.io",memcached:"memcached.org",meilisearch:"meilisearch.com",git:"git-scm.com",certbot:"certbot.eff.org",bun:"bun.sh",node:"nodejs.org",deno:"deno.land"};var y="/opt/pantry";function v(j){return`'${j.split("'").join("'\\''")}'`}function tj(j={}){return["export DEBIAN_FRONTEND=noninteractive","export PANTRY_SERVICE_SCOPE=system","export PANTRY_INSTALL_DIR=/usr/local/bin",j.version?`export PANTRY_VERSION=${v(j.version)}`:'export PANTRY_VERSION="${PANTRY_VERSION:-latest}"',"command -v curl >/dev/null 2>&1 || (apt-get update -y && apt-get install -y curl ca-certificates)","command -v unzip >/dev/null 2>&1 || (apt-get update -y && apt-get install -y unzip)",'OS=$(uname -s | tr \'[:upper:]\' \'[:lower:]\'); ARCH=$(uname -m); case "$ARCH" in x86_64|amd64) ARCH=x64 ;; arm64|aarch64) ARCH=arm64 ;; esac; ZIP="pantry-${OS}-${ARCH}.zip"; if [ "${PANTRY_VERSION:-latest}" = latest ]; then REL=\'latest/download\'; else REL="download/v${PANTRY_VERSION}"; fi; TMP=$(mktemp -d); curl -fsSL -o "${TMP}/${ZIP}" "https://github.com/pantry-pm/pantry/releases/${REL}/${ZIP}"; unzip -o "${TMP}/${ZIP}" -d /usr/local/bin; chmod +x /usr/local/bin/pantry; rm -rf "${TMP}"','export PATH="/usr/local/bin:$PATH"',"mkdir -p /opt/pantry"]}function T(){return'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true'}function m(j){if(j.length===0)return[];return[`(cd /opt/pantry && pantry install ${[...new Set(j)].map(v).join(" ")})`]}function a(j){return[...new Set(j)].flatMap((Z)=>[`(cd /opt/pantry && pantry start ${v(Z)})`,`(cd /opt/pantry && pantry enable ${v(Z)})`])}var w=`${y}/pantry/.bin`,h=15306,b=15991,E=15999,e=16101,P=2379,B="/var/lib/vitess",g=100;function Bj(j){return j===!0||typeof j==="object"&&j!==null}function Dj(j){return typeof j==="object"&&j!==null?j:{}}function G(j){return`'${String(j).split("'").join("'\\''")}'`}function Lj(j){let $=[j.version?`vitess.io@${j.version}`:"vitess.io"];if(j.mode!=="combo"&&!j.etcdEndpoint)$.push("etcd.io");return $.push("mysql.com@8.0.43"),$}var Y="vitess",Nj=`${w}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`,zj="/usr/local/lib/vitess",l=new Map;function u(j){return`${zj}/${j}.sh`}function O(j,Z){return l.set(j,Cj(Z)),`/bin/sh ${u(j)}`}function jj(){let j=[`mkdir -p ${zj}`];for(let[Z,$]of l)j.push(`cat > ${u(Z)} <<'TS_CLOUD_VITESS_LAUNCHER_EOF'`,$,"TS_CLOUD_VITESS_LAUNCHER_EOF",`chmod 0755 ${u(Z)}`);return j}function Cj(j){return["#!/bin/sh","set -e",`cd ${y}`,`PANTRY_ENV="$(pantry env 2>/dev/null | grep -E '^(export [A-Za-z_]|[A-Za-z_][A-Za-z0-9_]*=)' || true)"`,'if [ -n "$PANTRY_ENV" ]; then eval "$PANTRY_ENV"; fi',`VT_MYSQL_ROOT="$(dirname "$(dirname "$(readlink -f ${w}/mysqld 2>/dev/null)")")"`,`VTROOT="$(dirname "$(dirname "$(readlink -f ${w}/mysqlctld 2>/dev/null)")")"`,"export VT_MYSQL_ROOT VTROOT",'LD_LIBRARY_PATH="$VT_MYSQL_ROOT/lib:$VTROOT/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"',"export LD_LIBRARY_PATH",`exec ${j.join(" ")}`].join(`
|
|
2
|
+
`)}function V(j){let Z=["[Unit]",`Description=${j.description}`,`After=network.target${j.after?.length?` ${j.after.join(" ")}`:""}`];if(j.requires?.length)Z.push(`Requires=${j.requires.join(" ")}`);return Z.push("","[Service]","Type=simple",`User=${Y}`,`Group=${Y}`,`Environment="PATH=${Nj}"`,`Environment="VTDATAROOT=${B}"`,...Object.entries(j.environment??{}).map(([$,z])=>`Environment="${$}=${z}"`),...(j.execStartPre??[]).map(($)=>`ExecStartPre=${$}`),`ExecStart=${j.execStart}`,"Restart=always","RestartSec=5","LimitNOFILE=65535","","[Install]","WantedBy=multi-user.target"),Z.join(`
|
|
3
|
+
`)}function Zj(j,Z){return[`cat > /etc/systemd/system/${j}.service <<'TS_CLOUD_VITESS_UNIT_EOF'`,Z,"TS_CLOUD_VITESS_UNIT_EOF"]}function Oj(j){let Z=j.cell??"zone1",$=j.vtgatePort??h,Q=`${((j.keyspaces?.length)?j.keyspaces:[{name:"app"}]).map((W)=>{let q=(W.sharded?["-80","80-"]:["0"]).map((H)=>`shards:{name:"${H}"}`).join(" ");return`keyspaces:{name:"${W.name}" ${q}}`}).join(" ")} cells:"${Z}"`;return V({description:"Vitess (vtcombo, single-process development stack)",execStart:O("vtcombo",[`${w}/vtcombo`,`--cell ${Z}`,`--proto-topo ${G(Q)}`,`--mysql-server-port ${$}`,"--mysql-server-bind-address 127.0.0.1","--mysql-auth-server-impl none","--start-mysql",`--port ${b}`,`--grpc-port ${E}`])})}function Vj(){return V({description:"etcd (Vitess topology store)",execStart:O("etcd",[`${w}/etcd`,`--data-dir ${B}/etcd`,`--listen-client-urls http://127.0.0.1:${P}`,`--advertise-client-urls http://127.0.0.1:${P}`]),execStartPre:[`+/bin/mkdir -p ${B}/etcd`,`+/bin/chown ${Y}:${Y} ${B}/etcd`]})}function c(j){return["--topo-implementation etcd2",`--topo-global-server-address ${j.etcdEndpoint??`http://127.0.0.1:${P}`}`,"--topo-global-root /vitess/global"]}function Uj(j){let Z=!j.etcdEndpoint;return V({description:"Vitess vtctld (control plane)",after:Z?["vitess-etcd.service"]:[],requires:Z?["vitess-etcd.service"]:[],execStart:O("vtctld",[`${w}/vtctld`,...c(j),`--cell ${j.cell??"zone1"}`,"--service-map grpc-vtctl,grpc-vtctld",`--grpc-port ${E}`,`--port ${E+1}`])})}function Aj(j,Z,$){let z=j.cell??"zone1";return V({description:`Vitess vttablet (${Z}/${$})`,after:["vitess-vtctld.service","vitess-mysqlctld.service"],requires:["vitess-mysqlctld.service"],execStart:O("vttablet",[`${w}/vttablet`,...c(j),`--tablet-path ${z}-${String(g).padStart(10,"0")}`,`--init-keyspace ${Z}`,`--init-shard ${$}`,"--init-tablet-type replica",`--service-map ${G("grpc-queryservice,grpc-tabletmanager,grpc-updatestream")}`,`--port ${e}`,`--grpc-port ${e+1}`,`--db-port ${j.mysqlPort??3306}`,`--mycnf-mysql-port ${j.mysqlPort??3306}`])})}function kj(j){return V({description:"Vitess mysqlctld (managed mysqld)",execStart:O("mysqlctld",[`${w}/mysqlctld`,`--tablet-uid ${g}`,`--mysql-port ${j.mysqlPort??3306}`,'--init-db-sql-file "$VTROOT/config/init_db.sql"',"--wait-time 2m"]),execStartPre:[`+/bin/mkdir -p ${B}`,`+/bin/chown ${Y}:${Y} ${B}`]})}var Wj="/etc/vitess/auth.json",A="/var/lib/vitess/vtgate-auth.sha256";function Rj(j){let Z=j.username??"vitess",$=j.password??"";return["mkdir -p /etc/vitess",'VTESS_AUTH_TMP="$(mktemp)"',`cat > "$VTESS_AUTH_TMP" <<'TS_CLOUD_VITESS_AUTH_EOF'`,JSON.stringify({[Z]:[{Password:$,UserData:Z}]}),"TS_CLOUD_VITESS_AUTH_EOF",`VTESS_VTGATE_AUTH_SHA="$(sha256sum "$VTESS_AUTH_TMP" | awk '{print $1}')"`,"VTESS_VTGATE_AUTH_CHANGED=1",`if [ -f ${A} ] && [ "$(cat ${A})" = "$VTESS_VTGATE_AUTH_SHA" ]; then VTESS_VTGATE_AUTH_CHANGED=0; fi`,`install -o ${Y} -g ${Y} -m 0600 "$VTESS_AUTH_TMP" ${Wj}`,'rm -f "$VTESS_AUTH_TMP"']}function Ij(j){let Z=j.cell??"zone1";return V({description:"Vitess vtgate (query router)",after:["vitess-vtctld.service"],execStart:O("vtgate",[`${w}/vtgate`,...c(j),`--cell ${Z}`,`--cells-to-watch ${Z}`,"--tablet-types-to-wait PRIMARY,REPLICA",`--service-map ${G("grpc-vtgateservice")}`,`--mysql-server-port ${j.vtgatePort??h}`,`--mysql-server-bind-address ${j.bindAddress??"127.0.0.1"}`,"--mysql-auth-server-impl static",`--mysql-auth-server-static-file ${Wj}`,`--port ${b}`,`--grpc-port ${b+1}`])})}function fj(j){let Z=j.cell??"zone1",$=j.etcdEndpoint??`http://127.0.0.1:${P}`,z=`${w}/vtctldclient --server 127.0.0.1:${E}`,Q=[`for i in $(seq 1 30); do ${z} GetCellInfoNames >/dev/null 2>&1 && break; sleep 2; done`,`if ! ${z} GetCellInfoNames 2>/dev/null | grep -qx ${G(Z)}; then`,` ${z} AddCellInfo --root ${G(`/vitess/${Z}`)} --server-address ${G($)} ${G(Z)}`,"fi"];for(let W of j.keyspaces??[]){let q=W.sharded?" --sharded":"";Q.push(`if ! ${z} GetKeyspace ${G(W.name)} >/dev/null 2>&1; then`,` ${z} CreateKeyspace${q} ${G(W.name)}`,"fi");let H=`${Z}-${String(g).padStart(10,"0")}`;for(let K of W.sharded?["-80","80-"]:["0"]){let X=`${W.name}/${K}`;Q.push("for i in $(seq 1 90); do",` if ${z} GetShard ${G(X)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then break; fi`,` ${z} PlannedReparentShard ${G(X)} --new-primary ${G(H)} >/dev/null 2>&1 && break`,` ${z} InitShardPrimary --force ${G(X)} ${G(H)} >/dev/null 2>&1 && break`," sleep 2","done",`if ! ${z} GetShard ${G(X)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then`,` echo "no primary could be elected for ${X}" >&2; exit 1`,"fi")}Q.push(`${z} RebuildKeyspaceGraph ${G(W.name)} >/dev/null`)}return Q}function $j(j){let Z=j.vtgatePort??h;return["for i in $(seq 1 60); do",` if (cd ${y} && eval "$(pantry env 2>/dev/null)"; MYSQL_PWD=${G(j.password??"")} ${w}/mysql -h 127.0.0.1 -P ${Z} -u ${G(j.username??"vitess")} --connect-timeout=2 -e 'SHOW KEYSPACES') >/dev/null 2>&1; then`,` echo "vtgate is serving on ${Z}"; exit 0`," fi"," sleep 2","done",`echo "vtgate did not become ready on port ${Z}" >&2`,"exit 1"]}function Xj(j){if(!Bj(j))return[];let Z=Dj(j),$=Z.mode==="combo";l.clear();let z=[...m(Lj(Z)),`VT_MYSQL_LIB="$(dirname "$(dirname "$(readlink -f ${w}/mysqld)")")/lib"`,'if [ -d "$VT_MYSQL_LIB" ]; then',` printf '%s\\n' "$VT_MYSQL_LIB" > /etc/ld.so.conf.d/vitess-mysql.conf`," ldconfig","else",' echo "mysqld library directory not found under $VT_MYSQL_LIB" >&2; exit 1',"fi",`id -u ${Y} >/dev/null 2>&1 || useradd --system --home-dir ${B} --shell /usr/sbin/nologin ${Y}`,`mkdir -p ${B}`,`chown -R ${Y}:${Y} ${B}`];if($)return z.push(...Zj("vitess-vtcombo",Oj(Z)),...jj(),"systemctl daemon-reload","systemctl enable --now vitess-vtcombo.service",...$j(Z)),z;z.push(...Rj(Z));let Q=[];if(!Z.etcdEndpoint)Q.push(["vitess-etcd",Vj()]);Q.push(["vitess-vtctld",Uj(Z)],["vitess-mysqlctld",kj(Z)],["vitess-vtgate",Ij(Z)]);for(let W of Z.keyspaces??[])for(let q of W.sharded?["-80","80-"]:["0"])Q.push([`vitess-vttablet-${W.name}-${q.replace(/-/g,"x")}`,Aj(Z,W.name,q)]);for(let[W,q]of Q)z.push(...Zj(W,q));z.push(...jj()),z.push("systemctl daemon-reload");for(let[W]of Q)z.push(`systemctl enable --now ${W}.service`);return z.push(`if [ "$VTESS_VTGATE_AUTH_CHANGED" = 1 ]; then systemctl restart vitess-vtgate.service; printf '%s\\n' "$VTESS_VTGATE_AUTH_SHA" > ${A}; chown ${Y}:${Y} ${A}; chmod 0600 ${A}; fi`,...fj(Z),...$j(Z)),z}var vj=new Set(["singlestore","vitess"]);function Jj(j){if(j?.engine&&vj.has(j.engine))return!1;return!j?.host||j.host==="127.0.0.1"||j.host==="localhost"}function d(j,Z="psql"){let $=j?.port??5432;if(Jj(j))return`${Z} -p ${$} -U postgres`;let z=j?.username||"postgres";return`${j?.password?`PGPASSWORD='${j.password.replace(/'/g,"'\\''")}' `:""}${Z} -h ${j.host} -p ${$} -U ${z} -w`}function D(j){return j===!0||typeof j==="object"&&j!=null}function yj(j){let Z=[],$=[];if(D(j.mysql))Z.push(typeof j.mysql==="object"&&j.mysql.version?`mysql.com@${j.mysql.version}`:"mysql.com@8.0.43"),$.push("mysql");else if(D(j.mariadb))Z.push(s.mariadb),$.push("mariadb");if(D(j.postgres))Z.push("postgresql.org"),$.push("postgres");if(D(j.redis))Z.push("redis.io"),$.push("redis");if(D(j.memcached))Z.push("memcached.org"),$.push("memcached");if(D(j.meilisearch))Z.push("meilisearch.com"),$.push("meilisearch");return{packages:Z,services:$}}function $Z(j={},Z={}){let $=yj(j),z=Xj(j.vitess);if($.packages.length===0)return z;return[...m($.packages),...a($.services),...z]}function zZ(j,Z={}){if(!j?.name)return[];if(!Jj(j))return[];let $=j.name,z=j.username||$,Q=j.password||"",W=D(Z.postgres)||j.engine==="postgres",q=D(Z.mariadb)||j.engine==="mariadb",H=D(Z.mysql)||j.engine==="mysql";if(W&&!H&&!q){let J=(x)=>`"${x.replace(/"/g,'""')}"`,C=(x)=>`'${x.replace(/'/g,"''")}'`,U=(x,I)=>["DO $$ BEGIN",` IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${C(x)}) THEN`,` CREATE ROLE ${J(x)} LOGIN PASSWORD ${C(I)};`," ELSE",` ALTER ROLE ${J(x)} LOGIN PASSWORD ${C(I)};`," END IF;","END $$;"],k=(x)=>{let I=x.databases&&x.databases.length>0?x.databases:[$],_=[];for(let S of I)if(x.access==="readonly")_.push(`GRANT CONNECT ON DATABASE ${J(S)} TO ${J(x.username)};`,`\\connect ${J(S)}`,`GRANT USAGE ON SCHEMA public TO ${J(x.username)};`,`GRANT SELECT ON ALL TABLES IN SCHEMA public TO ${J(x.username)};`,`ALTER DEFAULT PRIVILEGES FOR ROLE ${J(z)} IN SCHEMA public GRANT SELECT ON TABLES TO ${J(x.username)};`,"\\connect postgres");else _.push(`GRANT ALL PRIVILEGES ON DATABASE ${J(S)} TO ${J(x.username)};`);return _},R=j.users||[],Gj=j.port??5432;return[T(),`for i in $(seq 1 30); do pg_isready -p ${Gj} -q && break; sleep 2; done`,`${d(j)} <<'TS_CLOUD_PG_EOF'`,...U(z,Q),`SELECT 'CREATE DATABASE ${J($)} OWNER ${J(z)}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = ${C($)})\\gexec`,...R.flatMap((x)=>[...U(x.username,x.password),...k(x)]),"TS_CLOUD_PG_EOF"]}let K=q?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock",X=(J)=>J.replace(/`/g,"``"),F=(J)=>J.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),L=(J)=>{let C=J.databases&&J.databases.length>0?J.databases:[$],U=J.access==="readonly"?"SELECT":"ALL PRIVILEGES",k=[`CREATE USER IF NOT EXISTS '${F(J.username)}'@'%' IDENTIFIED BY '${F(J.password)}';`,`CREATE USER IF NOT EXISTS '${F(J.username)}'@'localhost' IDENTIFIED BY '${F(J.password)}';`,`ALTER USER '${F(J.username)}'@'%' IDENTIFIED BY '${F(J.password)}';`,`ALTER USER '${F(J.username)}'@'localhost' IDENTIFIED BY '${F(J.password)}';`];for(let R of C)k.push(`GRANT ${U} ON \`${X(R)}\`.* TO '${F(J.username)}'@'%';`,`GRANT ${U} ON \`${X(R)}\`.* TO '${F(J.username)}'@'localhost';`);return k},M=j.users||[];return[T(),`for i in $(seq 1 30); do mysqladmin --socket=${K} -u root ping 2>/dev/null | grep -q alive && break; sleep 2; done`,`mysql --socket=${K} -u root <<'TS_CLOUD_SQL_EOF'`,`CREATE DATABASE IF NOT EXISTS \`${X($)}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`,...L({username:z,password:Q}),...M.flatMap(L),"FLUSH PRIVILEGES;","TS_CLOUD_SQL_EOF"]}function WZ(j){if(!j?.name)return{};let Z=j.engine==="singlestore",$=j.engine==="vitess",z=j.engine==="postgres"?"pgsql":Z?"singlestore":$?"vitess":"mysql",Q=j.port??(j.engine==="postgres"?5432:$?15306:3306),W={DB_CONNECTION:z,DB_HOST:j.host||"127.0.0.1",DB_PORT:String(Q),DB_DATABASE:j.name};if(j.username)W.DB_USERNAME=j.username;if(j.password)W.DB_PASSWORD=j.password;if((Z||$)&&j.ssl!==!1)W.DB_SSL="true";return W}var r="/var/backups/ts-cloud",mj="/etc/ts-cloud/backups.config.ts",Qj="/etc/cron.d/ts-cloud-backups",p="/usr/local/bin/ts-cloud-backup.sh";function Ej(j){if(!j.name)return null;let Z=j.host||"127.0.0.1",$=j.engine==="postgres",z=$?"postgresql":"mysql",Q=j.port??($?5432:3306),W=(q)=>q.replace(/\\/g,"\\\\").replace(/'/g,"\\'");return[" {",` type: '${z}',`,` name: '${W(j.name)}',`," connection: {",` hostname: '${W(Z)}',`,` port: ${Q},`,` database: '${W(j.name)}',`,` username: '${W(j.username||j.name)}',`,` password: '${W(j.password||"")}',`," ssl: false,"," },"," includeSchema: true,"," includeData: true,"," },"].join(`
|
|
4
|
+
`)}function Pj(j,Z){let $=j?Ej(j):null,z=Z.bucket?[" destinations: ["," {"," type: 's3',",` bucket: '${Z.bucket}',`," prefix: 'db-backups',",...Z.endpoint?[` endpoint: '${Z.endpoint}',`]:[]," optional: false,"," },"," ],"]:[];return["import type { BackupConfig } from 'ts-backups'","","const config: BackupConfig = {"," verbose: true,",` outputPath: '${r}',`," retention: {",` count: ${Z.retentionCount??5},`,` maxAge: ${Z.retentionDays??30},`," },"," databases: [",...$?[$]:[]," ],",...z,"}","","export default config",""].join(`
|
|
5
|
+
`)}function QZ(j){let{database:Z,backups:$}=j;if(!$.enabled)return[];let z=$.schedule||"0 2 * * *",Q=Pj(Z,$);return["export DEBIAN_FRONTEND=noninteractive",`mkdir -p /etc/ts-cloud ${r}`,"command -v bun >/dev/null 2>&1 || (curl -fsSL https://bun.sh/install | bash && ln -sf /root/.bun/bin/bun /usr/local/bin/bun)","bun add -g ts-backups || true",`cat > ${mj} <<'TS_CLOUD_BACKUP_CFG_EOF'`,Q.replace(/\n$/,""),"TS_CLOUD_BACKUP_CFG_EOF",`cat > ${p} <<'TS_CLOUD_BACKUP_RUN_EOF'`,"#!/bin/bash","set -uo pipefail",'export PATH="/root/.bun/bin:/usr/local/bin:$PATH"','notify() { [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "$1" || true; }',"cd /etc/ts-cloud",'if ! ts-backups backup --config /etc/ts-cloud/backups.config.ts; then notify "❌ ts-cloud backup failed"; exit 1; fi',"TS_CLOUD_BACKUP_RUN_EOF",`chmod +x ${p}`,`cat > ${Qj} <<'TS_CLOUD_BACKUP_CRON_EOF'`,`${z} root ${p} >> /var/log/ts-cloud-backup.log 2>&1`,"TS_CLOUD_BACKUP_CRON_EOF",`chmod 644 ${Qj}`]}function _j(j){return j==="mariadb"?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock"}function qZ(j,Z={}){if(!j?.name)return[];let $=j.name,z=j.engine==="postgres",Q=Z.from?`TS_CLOUD_DUMP="${Z.from}"`:`TS_CLOUD_DUMP="$(find ${r} -type f -name '*${$}*.sql' -o -type f -name '*${$}*.sql.gz' 2>/dev/null | xargs -r ls -1t 2>/dev/null | head -1)"`,W=z?`${d(j)} -d "${$}"`:`mysql --socket=${_j(j.engine)} -u root "${$}"`;return["set -uo pipefail",'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true',Q,'[ -n "$TS_CLOUD_DUMP" ] && [ -f "$TS_CLOUD_DUMP" ] || { echo "no backup dump found to restore" >&2; exit 1; }','echo "[ts-cloud] restoring '+$+' from $TS_CLOUD_DUMP"',`case "$TS_CLOUD_DUMP" in *.gz) gunzip -c "$TS_CLOUD_DUMP" ;; *) cat "$TS_CLOUD_DUMP" ;; esac | ${W}`,'echo "restore complete"']}var Kj=["storage",".env"],MZ=4;function N(j){return`${j.replace(/\/+$/,"")}/.ts-cloud`}function Sj(j){return`${N(j)}/deploy-history.log`}function Tj(j,Z){return`${N(j)}/deploys/${Z}.log`}function Mj(j){return`${N(j)}/shared-paths`}function xZ(j,Z){let $=j.replace(/\/+$/,"");return{base:$,releases:`${$}/releases`,shared:`${$}/shared`,current:`${$}/current`,release:`${$}/releases/${Z}`}}function bj(j){let Z=j.split("/").pop()||j;if(Z===".env"||Z.startsWith(".env."))return!0;return/\.[a-z0-9]+$/i.test(Z)}function uj(j){return typeof j==="string"?j:j.path}function GZ(j){let Z=new Map;for(let $ of j)Z.set(uj($),$);return[...Z.values()]}function xj(j,Z){if(typeof Z==="string")return{path:Z,target:`${j.shared}/${Z}`,seed:!0};return{path:Z.path,target:Z.target??`${j.shared}/${Z.path}`,seed:Z.seed!==!1}}function hj(j){return["ts_cloud_adopt_shared() {",' TS_CLOUD_SP="$1"',' TS_CLOUD_DST="$2"',` TS_CLOUD_SRC="${j.current}/$TS_CLOUD_SP"`,' if [ -e "$TS_CLOUD_DST" ]; then return 0; fi',' if [ -L "$TS_CLOUD_SRC" ] || [ ! -e "$TS_CLOUD_SRC" ]; then return 0; fi',' mkdir -p "$(dirname "$TS_CLOUD_DST")"',' cp -a "$TS_CLOUD_SRC" "$TS_CLOUD_DST"'," for TS_CLOUD_SIDECAR in -wal -shm; do",' if [ -f "$TS_CLOUD_SRC$TS_CLOUD_SIDECAR" ]; then cp -a "$TS_CLOUD_SRC$TS_CLOUD_SIDECAR" "$TS_CLOUD_DST$TS_CLOUD_SIDECAR"; fi'," done",' echo "[ts-cloud] adopted $TS_CLOUD_SP from the live release into shared/ — it now survives deploys"'," return 0","}"]}function HZ(j,Z=Kj){let $=[`mkdir -p ${j.releases} ${j.shared}`,...hj(j)],z=Z.map((W)=>xj(j,W));for(let{path:W,target:q,seed:H}of z){if(!H)continue;if($.push(`ts_cloud_adopt_shared '${W}' '${q}'`),bj(W))$.push(`mkdir -p "$(dirname ${q})"`,`touch ${q}`);else if(W==="storage")$.push(`mkdir -p ${q}/app/public`,`mkdir -p ${q}/framework/cache/data`,`mkdir -p ${q}/framework/sessions`,`mkdir -p ${q}/framework/testing`,`mkdir -p ${q}/framework/views`,`mkdir -p ${q}/logs`);else $.push(`mkdir -p ${q}`)}let Q=Mj(j.base);return $.push(`mkdir -p ${N(j.base)}`,`cat > ${Q} <<'TS_CLOUD_SHARED_PATHS_EOF'`,...z.map((W)=>`${W.path} ${W.target}`),"TS_CLOUD_SHARED_PATHS_EOF"),$}function YZ(j,Z=900){let $=`${N(j.base)}/deploy.lock`;return[`mkdir -p "$(dirname ${$})"`,`exec 9>${$}`,`flock -w ${Z} 9 || { echo "[ts-cloud] another deploy of this site has held the lock for ${Z}s — refusing to race it" >&2; exit 1; }`]}function FZ(j){let Z=`${j.release}.incoming`;return[`rm -rf ${Z}`,`mkdir -p ${Z}`,...gj(j),'if [ "$TS_CLOUD_IS_LIVE" = "yes" ]; then',` TS_CLOUD_STAGED=${Z}`,"else",` rm -rf ${j.release}`,` mkdir -p ${j.release}`,` rmdir ${Z}`,` TS_CLOUD_STAGED=${j.release}`,"fi"]}function wZ(j){let Z=`TS_CLOUD_TRAP_LIVE="$(readlink -f ${j.current} 2>/dev/null || true)"`,$=`TS_CLOUD_TRAP_TARGET="$(readlink -f ${j.release} 2>/dev/null || echo ${j.release})"`;return`trap '${`if [ $? -ne 0 ]; then ${Z}; ${$}; [ "$TS_CLOUD_TRAP_LIVE" = "$TS_CLOUD_TRAP_TARGET" ] || rm -rf ${j.release}; fi`}' EXIT`}function gj(j){return[`TS_CLOUD_LIVE_PATH="$(readlink -f ${j.current} 2>/dev/null || true)"`,`TS_CLOUD_RELEASE_PATH="$(readlink -f ${j.release} 2>/dev/null || echo ${j.release})"`,'if [ -n "$TS_CLOUD_LIVE_PATH" ] && [ "$TS_CLOUD_LIVE_PATH" = "$TS_CLOUD_RELEASE_PATH" ]; then TS_CLOUD_IS_LIVE=yes; else TS_CLOUD_IS_LIVE=no; fi']}function BZ(j){let Z=`${j.release}.incoming`;return[`if [ "$TS_CLOUD_STAGED" = "${Z}" ]; then`,` rm -rf ${j.release}.previous`,` mv ${j.release} ${j.release}.previous`,` mv ${Z} ${j.release}`,` rm -rf ${j.release}.previous`,"fi"]}function DZ(j,Z=Kj){let $=[];for(let z of Z){let{path:Q,target:W,seed:q}=xj(j,z),H=`${j.release}/${Q}`,K=[`rm -rf ${H}`,`mkdir -p "$(dirname ${H})"`,`ln -sfn ${W} ${H}`];if(q){$.push(...K);continue}$.push(`if [ -e ${W} ]; then`,...K.map((X)=>` ${X}`),"fi")}return $}function qj(j,Z){let $=Mj(j.base);return[`if [ -f ${$} ]; then`,' while IFS="\t" read -r TS_CLOUD_SP TS_CLOUD_TGT; do',' [ -n "$TS_CLOUD_SP" ] || continue',` [ -n "$TS_CLOUD_TGT" ] || TS_CLOUD_TGT="${j.shared}/$TS_CLOUD_SP"`,' [ -e "$TS_CLOUD_TGT" ] || continue',` rm -rf ${Z}/"$TS_CLOUD_SP"`,` mkdir -p "$(dirname ${Z}/"$TS_CLOUD_SP")"`,` ln -sfn "$TS_CLOUD_TGT" ${Z}/"$TS_CLOUD_SP"`,` done < ${$}`,"fi"]}function LZ(j){return[`ln -sfn ${j.release} ${j.current}.tmp`,`mv -Tf ${j.current}.tmp ${j.current}`]}function NZ(j,Z={}){let $=Z.to?[`[ -d ${j.releases}/${Z.to} ] || { echo "rollback target ${j.releases}/${Z.to} not found" >&2; exit 1; }`,...qj(j,`${j.releases}/${Z.to}`),`ln -sfn ${j.releases}/${Z.to} ${j.current}.tmp`,`mv -Tf ${j.current}.tmp ${j.current}`]:[`TS_CLOUD_CURRENT=$(readlink -f ${j.current} 2>/dev/null || true)`,`TS_CLOUD_PREV=$(ls -1dt ${j.releases}/*/ 2>/dev/null | sed 's#/$##' | while read -r r; do [ "$(readlink -f "$r")" != "$TS_CLOUD_CURRENT" ] && { echo "$r"; break; }; done)`,'[ -n "$TS_CLOUD_PREV" ] || { echo "no previous release to roll back to" >&2; exit 1; }',...qj(j,'"$TS_CLOUD_PREV"'),`ln -sfn "$TS_CLOUD_PREV" ${j.current}.tmp`,`mv -Tf ${j.current}.tmp ${j.current}`,'echo "rolled back to $TS_CLOUD_PREV"'];if(!Z.unitBase)return $;let z=Z.unitBase;return[...$,`TS_CLOUD_RB_ID=$(basename "$(readlink -f ${j.current})")`,`if [ -f /etc/systemd/system/${z}@.service ]; then systemctl start "${z}@\${TS_CLOUD_RB_ID}.service"; sleep 2; systemctl is-active --quiet "${z}@\${TS_CLOUD_RB_ID}.service" || { echo "rolled-back release failed to start" >&2; exit 1; }; systemctl enable "${z}@\${TS_CLOUD_RB_ID}.service" 2>/dev/null || true; systemctl list-units --plain --no-legend --type=service "${z}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v "^${z}@\${TS_CLOUD_RB_ID}.service$" || true; } | while read -r TS_CLOUD_U; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done; elif [ -f /etc/systemd/system/${z}.service ]; then systemctl restart ${z}.service; fi`]}function CZ(j,Z=4){let $=Math.max(1,Z);return[`TS_CLOUD_CURRENT=$(readlink -f ${j.current} 2>/dev/null || true)`,`ls -1dt ${j.releases}/*/ 2>/dev/null | sed 's#/$##' | tail -n +${$+1} | while read -r TS_CLOUD_OLD; do`,' [ "$(readlink -f "$TS_CLOUD_OLD")" = "$TS_CLOUD_CURRENT" ] || rm -rf "$TS_CLOUD_OLD"',"done"]}function lj(j){return`${N(j)}/owner`}function OZ(j,Z){let $=lj(j);return[`if [ -f "${$}" ]; then`,` TS_CLOUD_OWNER=$(cat "${$}")`,` if [ "$TS_CLOUD_OWNER" != "${Z}" ]; then`,` echo "[ts-cloud] REFUSING deploy: ${j} belongs to project '$TS_CLOUD_OWNER', not '${Z}'. Another project on this box derives the same site key — give one of them a distinct site name/domain, or remove ${$} to transfer ownership." >&2`," exit 1"," fi","else",` mkdir -p "$(dirname "${$}")"`,` printf '%s\\n' "${Z}" > "${$}"`,"fi"]}function VZ(j,Z){let $=N(j),z=Tj(j,Z.releaseId),Q=Sj(j),W=Math.max(1,Z.keepLogs??20),q=Z.commit||"",H=Z.branch||"";return[`mkdir -p ${$}/deploys`,`exec > >(tee -a ${z}) 2>&1`,`echo "[ts-cloud] deploy ${Z.releaseId} commit=${q} branch=${H} starting $(date -u +%Y-%m-%dT%H:%M:%SZ)"`,"ts_cloud_record_deploy() {"," TS_CLOUD_RC=$?",' if [ "$TS_CLOUD_RC" -eq 0 ]; then TS_CLOUD_ST=success; else TS_CLOUD_ST=failed; fi',` printf '%s\\t%s\\t%s\\t%s\\trc=%s\\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "${Z.releaseId}" "${q}" "$TS_CLOUD_ST" "$TS_CLOUD_RC" >> ${Q}`,"}","trap ts_cloud_record_deploy EXIT",`ls -1t ${$}/deploys/*.log 2>/dev/null | tail -n +${W+1} | while read -r TS_CLOUD_OLDLOG; do rm -f "$TS_CLOUD_OLDLOG"; done`]}
|
|
6
|
+
export{dj as gf,i as hf,Yj as if,f as jf,wj as kf,pj as lf,rj as mf,oj as nf,nj as of,y as pf,tj as qf,T as rf,m as sf,a as tf,Xj as uf,d as vf,$Z as wf,zZ as xf,WZ as yf,p as zf,QZ as Af,qZ as Bf,Kj as Cf,MZ as Df,Sj as Ef,xZ as Ff,GZ as Gf,HZ as Hf,YZ as If,FZ as Jf,wZ as Kf,BZ as Lf,DZ as Mf,LZ as Nf,NZ as Of,CZ as Pf,OZ as Qf,VZ as Rf};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{ng as I}from"./chunk-etrb03mt.js";var _=(e)=>e==null?void 0:String(e),b=(e)=>Number(e)===1,y=(e,r)=>{try{return e==null?r:JSON.parse(String(e))}catch{return r}};function C(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),scope:{type:String(e.scope_type),id:String(e.scope_id),environmentId:_(e.environment_id),resourceId:_(e.resource_id),previewId:_(e.preview_id)},key:String(e.key),kind:String(e.kind),value:_(e.value),valueFingerprint:String(e.value_fingerprint),secretRef:_(e.secret_ref),backend:String(e.backend),backendVersion:_(e.backend_version),origin:String(e.origin),required:b(e.required),metadata:y(e.metadata,{}),lastUsedAt:_(e.last_used_at),rotatedAt:_(e.rotated_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function R(e){return{entryId:String(e.entry_id),resourceId:String(e.resource_id),injectionTarget:String(e.injection_target),required:b(e.required),requiresRedeploy:b(e.requires_redeploy),lastDeployedVersion:e.last_deployed_version==null?void 0:Number(e.last_deployed_version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}class q{controlPlane;now;constructor(e,r=()=>new Date){this.controlPlane=e;this.now=r}get(e){let r=this.controlPlane.database.query("SELECT * FROM configuration_entries WHERE id=?").get(e);return r?C(r):void 0}find(e,r,o){let t=this.controlPlane.database.query("SELECT * FROM configuration_entries WHERE project_id=? AND scope_type=? AND scope_id=? AND key=?").get(e,r.type,r.id,o);return t?C(t):void 0}list(e){let r=["project_id=?"],o=[e.projectId];if(e.scope)r.push("scope_type=?","scope_id=?"),o.push(e.scope.type,e.scope.id);if(e.kind)r.push("kind=?"),o.push(e.kind);return this.controlPlane.database.query(`SELECT * FROM configuration_entries WHERE ${r.join(" AND ")} ORDER BY key,scope_type,scope_id`).all(...o).map(C)}create(e){this.validateScope(e),this.validateEntry(e);let r=crypto.randomUUID(),o=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO configuration_entries (id,organization_id,project_id,scope_type,scope_id,environment_id,resource_id,preview_id,key,kind,value,value_fingerprint,secret_ref,backend,backend_version,origin,required,metadata,last_used_at,rotated_at,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[r,e.organizationId,e.projectId,e.scope.type,e.scope.id,e.scope.environmentId??null,e.scope.resourceId??null,e.scope.previewId??null,e.key,e.kind,e.value??null,e.valueFingerprint,e.secretRef??null,e.backend,e.backendVersion??null,e.origin,e.required?1:0,JSON.stringify(e.metadata),e.lastUsedAt??null,e.rotatedAt??null,1,o,o]),this.get(r)}update(e,r,o){let t=this.get(e);if(!t)throw Error("Configuration entry was not found.");if(this.validateEntry({...t,...o}),this.controlPlane.database.run("UPDATE configuration_entries SET value=?,value_fingerprint=?,secret_ref=?,backend=?,backend_version=?,required=?,metadata=?,rotated_at=?,version=version+1,updated_at=? WHERE id=? AND version=?",[o.value??null,o.valueFingerprint,o.secretRef??null,o.backend,o.backendVersion??null,o.required?1:0,JSON.stringify(o.metadata),o.rotatedAt??null,this.now().toISOString(),e,r]).changes!==1)throw Error("Configuration entry changed; refresh and retry.");return this.get(e)}remove(e,r){let o=this.get(e);if(!o)throw Error("Configuration entry was not found.");if(o.version!==r)throw Error("Configuration entry changed; refresh and retry.");if(this.controlPlane.database.run("DELETE FROM configuration_entries WHERE id=? AND version=?",[e,r]).changes<1)throw Error("Configuration entry changed; refresh and retry.");return o}setDependency(e){let r=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO configuration_dependencies (entry_id,resource_id,injection_target,required,requires_redeploy,last_deployed_version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?) ON CONFLICT(entry_id,resource_id) DO UPDATE SET injection_target=excluded.injection_target,required=excluded.required,requires_redeploy=excluded.requires_redeploy,last_deployed_version=excluded.last_deployed_version,updated_at=excluded.updated_at",[e.entryId,e.resourceId,e.injectionTarget,e.required?1:0,e.requiresRedeploy?1:0,e.lastDeployedVersion??null,r,r]),this.dependencies(e.entryId).find((o)=>o.resourceId===e.resourceId)}dependencies(e){return this.controlPlane.database.query("SELECT * FROM configuration_dependencies WHERE entry_id=? ORDER BY resource_id").all(e).map(R)}dependenciesForResource(e){return this.controlPlane.database.query("SELECT * FROM configuration_dependencies WHERE resource_id=? ORDER BY entry_id").all(e).map(R)}mutation(e){let r=this.controlPlane.database.query("SELECT request_hash,result FROM configuration_mutations WHERE idempotency_key=?").get(e);return r?{requestHash:r.request_hash,result:y(r.result,{})}:void 0}recordMutation(e){this.controlPlane.database.run("INSERT INTO configuration_mutations (id,project_id,idempotency_key,request_hash,result,actor_id,created_at) VALUES (?,?,?,?,?,?,?)",[crypto.randomUUID(),e.projectId,e.idempotencyKey,e.requestHash,JSON.stringify(e.result),e.actorId??null,this.now().toISOString()])}validateEntry(e){if(!/^[A-Za-z_][A-Za-z0-9_]{0,255}$/.test(e.key))throw Error(`Invalid configuration key: ${e.key}`);if(e.kind==="variable"&&(e.value==null||e.secretRef||e.backend!=="plaintext"))throw Error("Variables require a plaintext value and cannot use a secret backend.");if(e.kind==="secret"&&(e.value!=null||!e.secretRef||e.backend==="plaintext"))throw Error("Secrets require a non-plaintext backend reference and cannot store a plaintext value.")}validateScope(e){let r=this.controlPlane.getProject(e.projectId);if(!r||r.organizationId!==e.organizationId)throw Error("Configuration project does not belong to the organization.");let o=e.scope;if(o.type==="project"){if(o.id!==e.projectId||o.environmentId||o.resourceId||o.previewId)throw Error("Project configuration scope must reference only its project.");return}if(o.type==="environment"){let n=this.controlPlane.database.query("SELECT project_id FROM environments WHERE id=?").get(o.id);if(!n||n.project_id!==e.projectId||o.environmentId&&o.environmentId!==o.id||o.resourceId||o.previewId)throw Error("Environment configuration scope does not belong to the project.");return}if(o.type==="service"||o.type==="function"){let n=this.controlPlane.getResource(o.id);if(!n||n.projectId!==e.projectId||o.type==="function"&&n.kind!=="function"||o.resourceId&&o.resourceId!==o.id||o.environmentId&&n.environmentId!==o.environmentId||o.previewId)throw Error(`${o.type==="function"?"Function":"Service"} configuration scope does not belong to the project.`);return}let t=this.controlPlane.database.query("SELECT project_id,base_environment_id,resource_id FROM preview_instances WHERE id=?").get(o.id);if(!t||t.project_id!==e.projectId||o.previewId&&o.previewId!==o.id||o.environmentId&&o.environmentId!==t.base_environment_id||o.resourceId&&o.resourceId!==t.resource_id)throw Error("Preview configuration scope does not belong to the project.")}}var P=/^[A-Za-z_][A-Za-z0-9_]{0,255}$/;function O(e){let r={n:`
|
|
2
|
+
`,r:"\r",t:"\t","\\":"\\",'"':'"',$:"$"};return e.replace(/\\(n|r|t|\\|"|\$)/g,(o,t)=>r[t])}function x(e){let r={},o=[],t=e.replace(/\r\n?/g,`
|
|
3
|
+
`).split(`
|
|
4
|
+
`);for(let n=0;n<t.length;n++){let s=n+1,c=t[n];if(!c.trim()||c.trimStart().startsWith("#"))continue;if(/^\s*export\s+/.test(c))c=c.replace(/^\s*export\s+/,"");let l=c.match(/^\s*([^=\s]+)\s*=\s*(.*)$/);if(!l){o.push({line:s,severity:"error",code:"invalid_line",message:"Expected KEY=VALUE."});continue}let i=l[1],a=l[2];if(!P.test(i)){o.push({line:s,key:i,severity:"error",code:"invalid_key",message:`Invalid environment variable name: ${i}`});continue}let d=a;if(a.startsWith('"')||a.startsWith("'")){let g=a[0],f=[a.slice(1)],S=!1;while(!0){let m=f[f.length-1],h=!1,E=-1;for(let u=0;u<m.length;u++){if(g==='"'&&m[u]==="\\"&&!h){h=!0;continue}if(m[u]===g&&!h){E=u;break}h=!1}if(E>=0){f[f.length-1]=m.slice(0,E),S=!0;break}if(++n>=t.length)break;f.push(t[n])}if(!S){o.push({line:s,key:i,severity:"error",code:"unterminated_quote",message:`Unterminated quoted value for ${i}.`});continue}if(d=f.join(`
|
|
5
|
+
`),g==='"')d=O(d)}else d=a.replace(/\s+#.*$/,"").trim();if(Object.hasOwn(r,i)){let g=r[i]!==d;if(o.push({line:s,key:i,severity:g?"error":"warning",code:g?"conflict":"duplicate",message:g?`${i} has conflicting values.`:`${i} is duplicated with the same value.`}),g)continue}r[i]=d}return{values:r,diagnostics:o,valid:!o.some((n)=>n.severity==="error")}}function j(e){return Object.entries(e).sort(([r],[o])=>r.localeCompare(o)).map(([r,o])=>{if(!P.test(r))throw Error(`Invalid environment variable name: ${r}`);return`${r}=${JSON.stringify(o)}`}).join(`
|
|
6
|
+
`)+(Object.keys(e).length?`
|
|
7
|
+
`:"")}import{createCipheriv as T,createDecipheriv as k,createHash as D,randomBytes as W}from"node:crypto";class w{controlPlane;now;kind="local_encrypted";key;constructor(e,r,o=()=>new Date){this.controlPlane=e;this.now=o;if(!r)throw Error("Configuration encryption key is required.");this.key=D("sha256").update(`ts-cloud:configuration:${r}`).digest()}encrypt(e){let r=W(12),o=T("aes-256-gcm",this.key,r),t=Buffer.concat([o.update(e,"utf8"),o.final()]);return`v1.${r.toString("base64url")}.${o.getAuthTag().toString("base64url")}.${t.toString("base64url")}`}decrypt(e){let[r,o,t,n]=e.split(".");if(r!=="v1"||!o||!t||!n)throw Error("Encrypted configuration secret is unavailable.");try{let s=k("aes-256-gcm",this.key,Buffer.from(o,"base64url"));return s.setAuthTag(Buffer.from(t,"base64url")),Buffer.concat([s.update(Buffer.from(n,"base64url")),s.final()]).toString("utf8")}catch{throw Error("Encrypted configuration secret could not be decrypted.")}}async put(e){if(!e.value)throw Error("Configuration secrets cannot be empty.");let r=e.reference??`secret://configuration/${e.name}/${crypto.randomUUID()}`;if(!/^secret:\/\/configuration\/[A-Za-z0-9._/-]+$/.test(r))throw Error("Invalid local configuration secret reference.");let t=(this.controlPlane.database.query("SELECT version FROM configuration_secret_values WHERE reference=?").get(r)?.version??0)+1,n=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO configuration_secret_values (reference,ciphertext,fingerprint,version,created_at,updated_at) VALUES (?,?,?,?,?,?) ON CONFLICT(reference) DO UPDATE SET ciphertext=excluded.ciphertext,fingerprint=excluded.fingerprint,version=excluded.version,updated_at=excluded.updated_at",[r,this.encrypt(e.value),D("sha256").update(e.value).digest("hex"),t,n,n]),{reference:r,version:String(t)}}async resolve(e){let r=this.controlPlane.database.query("SELECT ciphertext FROM configuration_secret_values WHERE reference=?").get(e);if(!r)throw Error("Configuration secret was not found.");return this.decrypt(r.ciphertext)}async remove(e){this.controlPlane.database.run("DELETE FROM configuration_secret_values WHERE reference=?",[e])}async validate(e){return!!this.controlPlane.database.query("SELECT 1 AS found FROM configuration_secret_values WHERE reference=?").get(e)}}class N{client;region;kind="aws_secrets_manager";constructor(e,r){this.client=e;this.region=r}async put(e){if(e.reference){let o=this.id(e.reference),t=await this.client.putSecretValue({SecretId:o,SecretString:e.value,ClientRequestToken:e.idempotencyKey});return{reference:e.reference,version:t.VersionId??e.idempotencyKey}}let r=await this.client.createSecret({Name:e.name,SecretString:e.value,ClientRequestToken:e.idempotencyKey,Tags:[{Key:"managed-by",Value:"ts-cloud"}]});return{reference:`aws-sm://${this.region}/${encodeURIComponent(r.ARN??r.Name??e.name)}`,version:r.VersionId??e.idempotencyKey}}async resolve(e){let r=await this.client.getSecretValue({SecretId:this.id(e)});if(r.SecretString==null)throw Error("AWS Secrets Manager value is unavailable.");return r.SecretString}async remove(e){await this.client.deleteSecret({SecretId:this.id(e),RecoveryWindowInDays:7})}async validate(e){try{return await this.client.describeSecret(this.id(e)),!0}catch{return!1}}id(e){let r=new URL(e);if(r.protocol!=="aws-sm:"||r.hostname!==this.region)throw Error("Invalid AWS Secrets Manager reference.");return decodeURIComponent(r.pathname.slice(1))}}class ${client;region;kind="aws_ssm";constructor(e,r){this.client=e;this.region=r}async put(e){let r=e.reference?this.name(e.reference):`/${e.name.replace(/^\/+/,"")}`,o=await this.client.putParameter({Name:r,Value:e.value,Type:"SecureString",Overwrite:!!e.reference,Description:"Managed by ts-cloud"});return{reference:`aws-ssm://${this.region}${r}`,version:String(o.Version??1)}}async resolve(e){let r=await this.client.getParameter({Name:this.name(e),WithDecryption:!0});if(r.Parameter?.Value==null)throw Error("AWS SSM parameter value is unavailable.");return r.Parameter.Value}async remove(e){await this.client.deleteParameter({Name:this.name(e)})}async validate(e){try{return!!(await this.client.getParameter({Name:this.name(e),WithDecryption:!1})).Parameter}catch{return!1}}name(e){let r=new URL(e);if(r.protocol!=="aws-ssm:"||r.hostname!==this.region||!r.pathname.startsWith("/"))throw Error("Invalid AWS SSM reference.");return r.pathname}}class M{kind="external";async put(){throw Error("External secret references cannot be written by ts-cloud.")}async resolve(){throw Error("External secrets must be resolved by the deployment provider.")}async remove(){}async validate(e){return/^(?:vault|doppler|op|external):\/\//.test(e)}}import{createHmac as L}from"node:crypto";var B=/^(?:secret|aws-sm|aws-ssm|vault|doppler|op|external):\/\//,U=/^(?:AWS_|TS_CLOUD_|PORT$|HOST$)/;function v(e){return[...new Set(e)].sort()}function A(e,r={}){let o=e.kind==="secret";return{id:e.id,key:e.key,kind:e.kind,scope:e.scope,inherited:!!r.inherited,overridden:!!r.overridden,required:e.required,backend:!o||r.canReadSecretMetadata?e.backend:void 0,backendVersion:!o||r.canReadSecretMetadata?e.backendVersion:void 0,reference:o&&r.canReadSecretMetadata?e.secretRef:void 0,value:!o?e.value:void 0,lastUsedAt:e.lastUsedAt,rotatedAt:e.rotatedAt,version:e.version,updatedAt:e.updatedAt}}class V{store;backends=new Map;fingerprintKey;now;constructor(e,r){if(this.store=e,this.fingerprintKey=r.fingerprintKey??r.encryptionKey,this.now=r.now??(()=>new Date),!this.fingerprintKey)throw Error("Configuration fingerprint key is required.");let o=r.backends??[new w(e.controlPlane,r.encryptionKey,this.now)];for(let t of o)this.backends.set(t.kind,t)}list(e){let r=e.search?.toLowerCase();return this.store.list(e).filter((o)=>!r||o.key.toLowerCase().includes(r)).map((o)=>A(o,{canReadSecretMetadata:e.canReadSecretMetadata}))}plan(e){let r=this.store.list({projectId:e.projectId,scope:e.scope}),o=new Map(r.map((i)=>[i.key,i])),t=[],n=[],s=[],c=[];for(let[i,a]of Object.entries(e.values)){t.push(...this.warnings(i,a));let d=o.get(i);if(!d)n.push(i);else if(d.valueFingerprint!==this.fingerprint(a))s.push(i);else c.push(i)}let l=e.removeMissing?r.filter((i)=>!Object.hasOwn(e.values,i.key)).map((i)=>i.key):[];return{added:v(n),changed:v(s),removed:v(l),unchanged:v(c),affectedResourceIds:this.affectedResources(e.projectId,e.scope,[...n,...s,...l]),warnings:t}}async set(e){let r=this.requestHash(e),o=e.idempotencyKey;if(o){let m=this.store.mutation(o);if(m){if(m.requestHash!==r)throw Error("Idempotency key was already used for a different configuration mutation.");let h=this.store.get(String(m.result.entryId??""));if(!h)throw Error("Idempotent configuration result is no longer available.");return{entry:h,mutation:m.result.mutation,warnings:[]}}}if(e.value!=null&&B.test(e.value))throw Error("Secret references must use the reference field, not a plaintext value field.");let t=this.store.find(e.projectId,e.scope,e.key),n=this.fingerprint(e.value??e.reference??"");if(t&&e.expectedVersion!=null&&t.version!==e.expectedVersion)throw Error("Configuration entry changed; refresh and retry.");if(t&&t.kind!==e.kind)throw Error("Delete the existing entry before changing between variable and secret kinds.");let s=e.kind==="variable"?"plaintext":e.backend??(e.reference?"external":"local_encrypted");if(!!t&&(t.valueFingerprint!==n||t.backend!==s||t.required!==!!e.required)&&(this.isProduction(t)||this.store.dependencies(t.id).length>0)&&!e.confirmed)throw Error("Confirmation is required because this replacement affects production or dependent services.");let l=e.reference,i;if(e.kind==="secret"){let m=this.backend(s);if(e.reference&&e.value==null){if(!await m.validate(e.reference))throw Error("Secret backend reference is unavailable or invalid.");i=t?.backendVersion??"external"}else{if(e.value==null)throw Error("A secret value or external reference is required.");let h=await m.put({reference:t?.backend===s?t.secretRef:void 0,name:this.backendName(e),value:e.value,idempotencyKey:o??crypto.randomUUID()});l=h.reference,i=h.version}}let a=e.kind==="variable"?e.value:void 0;if(e.kind==="variable"&&a==null)throw Error("A variable value is required.");let d=!t||t.valueFingerprint!==n||t.backend!==s||t.secretRef!==l||t.backendVersion!==i||t.required!==!!e.required,g=t?d?this.store.update(t.id,t.version,{value:a,valueFingerprint:n,secretRef:l,backend:s,backendVersion:i,required:!!e.required,metadata:I(e.metadata??t.metadata),rotatedAt:e.kind==="secret"?this.now().toISOString():t.rotatedAt}):t:this.store.create({organizationId:e.organizationId,projectId:e.projectId,scope:e.scope,key:e.key,kind:e.kind,value:a,valueFingerprint:n,secretRef:l,backend:s,backendVersion:i,origin:e.origin??"managed",required:!!e.required,metadata:I(e.metadata??{}),rotatedAt:e.kind==="secret"?this.now().toISOString():void 0}),f=this.affectedResources(e.projectId,e.scope,[e.key]),S={added:t?[]:[e.key],changed:t&&d?[e.key]:[],removed:[],unchanged:t&&!d?[e.key]:[],affectedResourceIds:f,versions:{[e.key]:g.version}};if(o)this.store.recordMutation({projectId:e.projectId,idempotencyKey:o,requestHash:r,actorId:e.actorId,result:{entryId:g.id,mutation:S}});return this.audit(e.projectId,e.actorId,t&&d?"configuration.updated":t?"configuration.unchanged":"configuration.created",g,f),{entry:g,mutation:S,warnings:this.warnings(e.key,e.value??"")}}async importDotenv(e){let r=x(e.source);if(!r.valid)return{document:r,warnings:[]};let o=new Set(e.secretKeys??[]),t={added:[],changed:[],removed:[],unchanged:[],affectedResourceIds:[],versions:{}},n=[];for(let[s,c]of Object.entries(r.values)){let l=await this.set({...e,source:void 0,key:s,value:c,kind:o.has(s)?"secret":"variable",idempotencyKey:e.idempotencyKey?`${e.idempotencyKey}:${s}`:void 0});t.added.push(...l.mutation.added),t.changed.push(...l.mutation.changed),t.unchanged.push(...l.mutation.unchanged),t.affectedResourceIds.push(...l.mutation.affectedResourceIds),Object.assign(t.versions,l.mutation.versions),n.push(...l.warnings)}return t.added=v(t.added),t.changed=v(t.changed),t.unchanged=v(t.unchanged),t.affectedResourceIds=v(t.affectedResourceIds),{document:r,mutation:t,warnings:n}}exportVariables(e){return j(Object.fromEntries(this.store.list({projectId:e.projectId,scope:e.scope,kind:"variable"}).map((r)=>[r.key,r.value??""])))}async transfer(e){let r=this.store.get(e.entryId);if(!r)throw Error("Configuration entry was not found.");if(r.scope.type===e.targetScope.type&&r.scope.id===e.targetScope.id)throw Error("Choose a different destination scope.");let o=r.kind==="variable"?r.value:r.backend==="external"?void 0:await this.backend(r.backend).resolve(r.secretRef),t=r.kind==="secret"?r.backend:void 0,n=await this.set({organizationId:r.organizationId,projectId:r.projectId,scope:e.targetScope,key:r.key,kind:r.kind,value:o,reference:r.backend==="external"?r.secretRef:void 0,backend:t,required:r.required,metadata:r.metadata,confirmed:e.confirmed,actorId:e.actorId,idempotencyKey:e.idempotencyKey?`${e.idempotencyKey}:copy`:void 0,origin:r.origin});if(e.mode==="move")await this.remove({entryId:r.id,expectedVersion:r.version,confirmed:e.confirmed,actorId:e.actorId});let s={added:n.mutation.added,changed:n.mutation.changed,removed:e.mode==="move"?[r.key]:[],unchanged:n.mutation.unchanged,affectedResourceIds:v([...n.mutation.affectedResourceIds,...this.affectedResources(r.projectId,r.scope,[r.key])]),versions:n.mutation.versions};return{entry:n.entry,mutation:s}}async resolve(e){let r=this.store.list({projectId:e.projectId}),o=r.filter((a)=>this.applies(a,e)).sort((a,d)=>this.rank(a.scope.type)-this.rank(d.scope.type)),t=new Map,n=new Set;for(let a of o){if(t.has(a.key))n.add(a.key);t.set(a.key,a)}let s={},c={},l=[],i=new Set(e.allowedPreviewSecrets??[]);for(let[a,d]of t){if(e.previewId&&d.kind==="secret"&&d.scope.type!=="preview"&&(!e.trustedPreview||!i.has(a)))continue;if(d.kind==="variable")s[a]=d.value??"";else if(e.nativeReferences)s[a]=d.secretRef;else{let g=this.backend(d.backend);if(!await g.validate(d.secretRef)){if(l.push({key:a,code:"stale_reference",message:`${a} points to an unavailable secret.`}),d.required)l.push({key:a,code:"missing_required",message:`${a} is required but unavailable.`});continue}s[a]=await g.resolve(d.secretRef)}c[a]=A(d,{inherited:d.scope.type!==(e.previewId?"preview":e.functionId?"function":e.resourceId?"service":e.environmentId?"environment":"project"),overridden:n.has(a),canReadSecretMetadata:e.canReadSecretMetadata}),this.store.controlPlane.database.run("UPDATE configuration_entries SET last_used_at=? WHERE id=?",[this.now().toISOString(),d.id])}return{values:s,entries:c,warnings:l,configurationHash:this.fingerprint([...t.values()].map((a)=>`${a.key}:${a.valueFingerprint}:${a.version}`).sort().join(`
|
|
8
|
+
`))}}async reveal(e){let r=this.store.get(e.entryId);if(!r||r.kind!=="secret")throw Error("Configuration secret was not found.");if(!e.canRevealSecrets)throw Error("Secret reveal permission is required.");if(!e.recentlyAuthenticated)throw Error("Recent authentication is required to reveal a secret.");let o=await this.backend(r.backend).resolve(r.secretRef);return this.audit(r.projectId,e.actorId,"configuration.secret.revealed",r,[]),o}async remove(e){let r=this.store.get(e.entryId);if(!r)throw Error("Configuration entry was not found.");let o=this.store.dependencies(r.id);if(((r.scope.environmentId?this.store.controlPlane.listEnvironments(r.projectId).some((c)=>c.id===r.scope.environmentId&&c.kind==="production"):r.scope.type==="project")||o.length)&&!e.confirmed)throw Error("Confirmation is required because this configuration affects production or dependent services.");if(r.kind==="secret"&&r.backend!=="external")await this.backend(r.backend).remove(r.secretRef);this.store.remove(r.id,e.expectedVersion);let n=v(o.map((c)=>c.resourceId)),s={added:[],changed:[],removed:[r.key],unchanged:[],affectedResourceIds:n,versions:{}};return this.audit(r.projectId,e.actorId,"configuration.deleted",r,n),s}applies(e,r){if(e.scope.type==="project")return!0;if(e.scope.type==="environment")return e.scope.id===r.environmentId;if(e.scope.type==="service")return e.scope.id===r.resourceId;if(e.scope.type==="function")return e.scope.id===r.functionId;return e.scope.id===r.previewId}rank(e){return{project:0,environment:1,service:2,function:3,preview:4}[e]}fingerprint(e){return`hmac-sha256:${L("sha256",this.fingerprintKey).update(e).digest("hex")}`}requestHash(e){return this.fingerprint(JSON.stringify({...e,idempotencyKey:void 0,actorId:void 0}))}backend(e){let r=this.backends.get(e);if(!r)throw Error(`Configuration secret backend is not configured: ${e}`);return r}backendName(e){return`ts-cloud/${e.projectId}/${e.scope.type}/${e.scope.id}/${e.key}`.replace(/[^A-Za-z0-9/_+=.@-]/g,"-")}isProduction(e){return e.scope.type==="project"||!!e.scope.environmentId&&this.store.controlPlane.listEnvironments(e.projectId).some((r)=>r.id===e.scope.environmentId&&r.kind==="production")}warnings(e,r){let o=[];if(U.test(e))o.push({key:e,code:"reserved",message:`${e} may be reserved by the runtime or provider.`});if(Buffer.byteLength(r)>65536)o.push({key:e,code:"limit",message:`${e} exceeds the portable 64 KiB value limit.`});return o}affectedResources(e,r,o){let t=this.store.list({projectId:e,scope:r}).filter((n)=>o.includes(n.key)).flatMap((n)=>this.store.dependencies(n.id).map((s)=>s.resourceId));if(r.type==="service"||r.type==="function")return v([...t,r.id]);if(r.type==="environment")return v([...t,...this.store.controlPlane.listResources(e,r.id).map((n)=>n.id)]);if(r.type==="preview"){let n=this.store.controlPlane.database.query("SELECT resource_id FROM preview_instances WHERE id=?").get(r.id);return v([...t,...n?[n.resource_id]:[]])}return v([...t,...this.store.controlPlane.listResources(e).map((n)=>n.id)])}audit(e,r,o,t,n){this.store.controlPlane.appendEvent({projectId:e,actorId:r,type:o,payload:{entryId:t.id,key:t.key,kind:t.kind,scopeType:t.scope.type,scopeId:t.scope.id,backend:t.backend,version:t.version,affectedResourceIds:n}})}}async function X(e,r,o,t){let n={added:0,changed:0,removed:0,overridden:0},s=async(c,l)=>{let i=e.store.list({projectId:r.project.id,scope:c,kind:"variable"}),a=new Set(Object.keys(l));for(let d of i.filter((g)=>g.origin==="config"&&!a.has(g.key)))await e.remove({entryId:d.id,expectedVersion:d.version,confirmed:!0,actorId:t}),n.removed++;for(let[d,g]of Object.entries(l)){let f=e.store.find(r.project.id,c,d);if(f?.origin!=="config"){if(f)n.overridden++;else await e.set({organizationId:r.organization.id,projectId:r.project.id,scope:c,key:d,kind:"variable",value:String(g),origin:"config",confirmed:!0,actorId:t}),n.added++;continue}if(f.value===String(g))continue;await e.set({organizationId:r.organization.id,projectId:r.project.id,scope:c,key:d,kind:"variable",value:String(g),origin:"config",confirmed:!0,actorId:t,expectedVersion:f.version}),n.changed++}};for(let[c,l]of Object.entries(o.environments??{})){let i=r.environments.get(c);if(!i)continue;let a=l,d={...a.variables??{},...a.app?.env??{}};await s({type:"environment",id:i.id,environmentId:i.id},d);for(let[g,f]of Object.entries(o.sites??{})){let S=r.store.listResources(r.project.id,i.id).find((m)=>m.kind==="application"&&m.slug===g);if(S)await s({type:"service",id:S.id,environmentId:i.id,resourceId:S.id},{...f.env??{}})}for(let[g,f]of Object.entries(o.infrastructure?.functions??{})){let S=r.store.listResources(r.project.id,i.id).find((m)=>m.kind==="function"&&m.slug===g);if(S)await s({type:"function",id:S.id,environmentId:i.id,resourceId:S.id},{...f.environment??{}})}}return n}export{q as ag,x as bg,j as cg,w as dg,N as eg,$ as fg,M as gg,V as hg,X as ig};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{id as a,jd as b}from"./chunk-ctd2vg9w.js";import"./chunk-j703btc5.js";import"./chunk-fpm59y25.js";import"./chunk-mh0kdzqp.js";export{b as ACMDnsValidator,a as ACMClient};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{yd as Wg}from"./chunk-4vrqm9h0.js";import{Jd as Zg,Od as $g}from"./chunk-mz0wbbsj.js";import{Rd as xg}from"./chunk-p66ptpmr.js";import{Tf as Yg}from"./chunk-axhnkn5g.js";import{Uf as Og}from"./chunk-h5pa5men.js";import{$f as s,_f as c}from"./chunk-fy8j3y8p.js";import{Og as Q,Pg as gg}from"./chunk-fpm59y25.js";import{Gh as Xg,Un as Bg}from"./chunk-rxcvf10f.js";class r{client;region;constructor(g="us-east-1",T){this.region=g,this.client=new Q(c(T))}async query(g){let T=new URLSearchParams(gg({Version:"2010-08-01",...g})).toString();return this.client.request({service:"monitoring",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:T})}async getMetricStatistics(g){let T={Action:"GetMetricStatistics",Namespace:g.Namespace,MetricName:g.MetricName,StartTime:g.StartTime.toISOString(),EndTime:g.EndTime.toISOString(),Period:g.Period};(g.Statistics??[]).forEach((P,Y)=>{T[`Statistics.member.${Y+1}`]=P}),(g.ExtendedStatistics??[]).forEach((P,Y)=>{T[`ExtendedStatistics.member.${Y+1}`]=P}),(g.Dimensions??[]).forEach((P,Y)=>{T[`Dimensions.member.${Y+1}.Name`]=P.Name,T[`Dimensions.member.${Y+1}.Value`]=P.Value});let N=await this.query(T),L=(N.GetMetricStatisticsResult||N)?.Datapoints?.member??[];if(!Array.isArray(L))L=L?[L]:[];return L.map((P)=>{let Y={},X=P.ExtendedStatistics?.entry;if(X){if(!Array.isArray(X))X=[X];for(let Z of X)if(Z?.key!=null)Y[Z.key]=Number(Z.value)}return{Timestamp:P.Timestamp,Sum:P.Sum!=null?Number(P.Sum):void 0,Average:P.Average!=null?Number(P.Average):void 0,Maximum:P.Maximum!=null?Number(P.Maximum):void 0,Minimum:P.Minimum!=null?Number(P.Minimum):void 0,Percentiles:Object.keys(Y).length?Y:void 0,Unit:P.Unit}})}async getMetricSeries(g){let T=/^p\d/.test(g.Stat);return(await this.getMetricStatistics({Namespace:g.Namespace,MetricName:g.MetricName,Dimensions:g.Dimensions,StartTime:g.StartTime,EndTime:g.EndTime,Period:g.Period,Statistics:T?[]:[g.Stat],ExtendedStatistics:T?[g.Stat]:[]})).slice().sort((z,L)=>new Date(z.Timestamp??0).getTime()-new Date(L.Timestamp??0).getTime()).map((z)=>T?z.Percentiles?.[g.Stat]??0:z[g.Stat]??0)}async describeAlarms(g){let T={Action:"DescribeAlarms"};if(g?.AlarmNamePrefix)T.AlarmNamePrefix=g.AlarmNamePrefix;if(g?.MaxRecords)T.MaxRecords=g.MaxRecords;let N=await this.query(T),L=(N.DescribeAlarmsResult||N)?.MetricAlarms?.member??[];if(!Array.isArray(L))L=L?[L]:[];return L.map((P)=>({AlarmName:P.AlarmName,StateValue:P.StateValue,MetricName:P.MetricName,ComparisonOperator:P.ComparisonOperator,Threshold:P.Threshold!=null?Number(P.Threshold):void 0,Namespace:P.Namespace}))}async putMetricAlarm(g){let T={Action:"PutMetricAlarm",AlarmName:g.AlarmName,Namespace:g.Namespace,MetricName:g.MetricName,ComparisonOperator:g.ComparisonOperator,Threshold:g.Threshold,EvaluationPeriods:g.EvaluationPeriods,Period:g.Period,Statistic:g.Statistic};if(g.AlarmDescription)T.AlarmDescription=g.AlarmDescription;(g.Dimensions??[]).forEach((N,z)=>{T[`Dimensions.member.${z+1}.Name`]=N.Name,T[`Dimensions.member.${z+1}.Value`]=N.Value}),(g.AlarmActions??[]).forEach((N,z)=>{T[`AlarmActions.member.${z+1}`]=N}),await this.query(T)}async deleteAlarms(g){if(!g.length)return;let T={Action:"DeleteAlarms"};g.forEach((N,z)=>{T[`AlarmNames.member.${z+1}`]=N}),await this.query(T)}}class a{client;region;constructor(g="us-east-1",T){this.region=g,this.client=new Q(void 0,{profile:T})}async createLogGroup(g,T){await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.CreateLogGroup","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({logGroupName:g,...T?{tags:T}:{}})})}async putRetentionPolicy(g,T){if(![1,3,5,7,14,30,60,90,120,150,180,365,400,545,731,1096,1827,2192,2557,2922,3288,3653].includes(T))throw Error("Unsupported CloudWatch Logs retention period");await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.PutRetentionPolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({logGroupName:g,retentionInDays:T})})}async describeLogStreams(g){let T={logGroupName:g.logGroupName};if(g.logStreamNamePrefix)T.logStreamNamePrefix=g.logStreamNamePrefix;if(g.orderBy)T.orderBy=g.orderBy;if(g.descending!==void 0)T.descending=g.descending;if(g.limit)T.limit=g.limit;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.DescribeLogStreams","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(T)})}async getLogEvents(g){let T={logGroupName:g.logGroupName,logStreamName:g.logStreamName};if(g.startTime)T.startTime=g.startTime;if(g.endTime)T.endTime=g.endTime;if(g.limit)T.limit=g.limit;if(g.startFromHead!==void 0)T.startFromHead=g.startFromHead;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.GetLogEvents","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(T)})}async describeLogGroups(g){let T={};if(g?.logGroupNamePrefix)T.logGroupNamePrefix=g.logGroupNamePrefix;if(g?.limit)T.limit=g.limit;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.DescribeLogGroups","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(T)})}async deleteLogGroup(g){await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.DeleteLogGroup","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({logGroupName:g})})}async filterLogEvents(g){let T={logGroupName:g.logGroupName};if(g.logStreamNames)T.logStreamNames=g.logStreamNames;if(g.startTime)T.startTime=g.startTime;if(g.endTime)T.endTime=g.endTime;if(g.filterPattern)T.filterPattern=g.filterPattern;if(g.limit)T.limit=g.limit;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.FilterLogEvents","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(T)})}}import{createHash as jg}from"node:crypto";import{existsSync as Tg,mkdirSync as Vg,readdirSync as Hg,readFileSync as Ug,rmSync as Kg,writeFileSync as Eg}from"node:fs";import{homedir as Qg}from"node:os";import{join as m}from"node:path";var Ng=1,Lg=3600000,Rg=24*Lg,Fg=Lg,qg=30*Rg;function i(){let g=process.env.XDG_CACHE_HOME;return m(g&&g.trim()?g:m(Qg(),".cache"),"ts-cloud","cost-explorer")}function f(g){return m(i(),g??"__default__")}function Gg(g){let T={s:g.start,e:g.end,g:g.granularity,m:[...g.metrics].sort(),gb:[...g.groupBy].map((N)=>`${N.Type}:${N.Key}`).sort(),f:g.filter??null};return jg("sha256").update(JSON.stringify(T)).digest("hex").slice(0,24)}function Ag(g,T){let N=Date.parse(`${T}T00:00:00Z`);if(Number.isNaN(N))return!1;let z=new Date,L=Date.UTC(z.getUTCFullYear(),z.getUTCMonth(),1);return N<=L}function Sg(g){return Ag(g.start,g.end)?qg:Fg}function zg(g,T){let N=m(f(g),`${Gg(T)}.json`);if(!Tg(N))return null;let z;try{z=JSON.parse(Ug(N,"utf-8"))}catch{return null}if(z.schema!==Ng)return null;let L=Date.now()-z.savedAt;if(L<0||L>Sg(T))return null;return{response:z.response,ageSeconds:Math.floor(L/1000)}}function Jg(g,T,N){let z=f(g);Vg(z,{recursive:!0});let L={schema:Ng,savedAt:Date.now(),key:T,response:N};Eg(m(z,`${Gg(T)}.json`),JSON.stringify(L))}function wg(g){let T=g===void 0?i():f(g);if(!Tg(T))return{deletedFiles:0,scope:g??"all profiles"};let N=0;function z(L){for(let P of Hg(L,{withFileTypes:!0})){let Y=m(L,P.name);if(P.isDirectory())z(Y);else if(P.isFile()&&P.name.endsWith(".json"))N++}}return z(T),Kg(T,{recursive:!0,force:!0}),{deletedFiles:N,scope:g??"all profiles"}}function vg(g){return g===void 0?i():f(g)}class e{client;profile;useCache;lastCacheAgeSeconds=null;constructor(g,T){this.profile=g,this.useCache=T?.useCache??!0,this.client=new Q(c(g))}async getCostByService(g){return(await this.getCostByDimension({...g,dimension:"SERVICE"})).map((N)=>({service:N.key,amount:N.amount,unit:N.unit}))}async getCostByDimension(g){let{start:T,end:N,dimension:z,granularity:L="MONTHLY",filter:P}=g,Y=["UnblendedCost"],X=[{Type:"DIMENSION",Key:z}],Z={start:T,end:N,granularity:L,metrics:Y,groupBy:X,filter:P};if(this.useCache){let U=zg(this.profile,Z);if(U)return this.lastCacheAgeSeconds=U.ageSeconds,U.response}this.lastCacheAgeSeconds=null;let W=new Map,G;do{let U={TimePeriod:{Start:T,End:N},Granularity:L,Metrics:Y,GroupBy:X};if(P)U.Filter=P;if(G)U.NextPageToken=G;let S=await this.client.request({service:"ce",region:"us-east-1",method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"AWSInsightsIndexService.GetCostAndUsage"},body:JSON.stringify(U)});for(let v of S?.ResultsByTime??[])for(let K of v?.Groups??[]){let C=K.Keys?.[0]??"Unknown",u=Number.parseFloat(K.Metrics?.UnblendedCost?.Amount??"0"),l=K.Metrics?.UnblendedCost?.Unit??"USD",_=W.get(C);W.set(C,{key:C,amount:(_?.amount??0)+u,unit:l})}G=S?.NextPageToken||void 0}while(G);let b=[...W.values()].filter((U)=>U.amount>0).sort((U,S)=>S.amount-U.amount);if(this.useCache)Jg(this.profile,Z,b);return b}async getDailyTotals(g){return((await this.client.request({service:"ce",region:"us-east-1",method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"AWSInsightsIndexService.GetCostAndUsage"},body:JSON.stringify({TimePeriod:{Start:g.start,End:g.end},Granularity:"DAILY",Metrics:["UnblendedCost"]})}))?.ResultsByTime??[]).map((z)=>Number.parseFloat(z.Total?.UnblendedCost?.Amount??"0"))}}class p{client;region;constructor(g="us-east-1"){this.region=g,this.client=new Q}async describeFileSystems(g){let T=[];if(g?.FileSystemId)T.push(`FileSystemId=${encodeURIComponent(g.FileSystemId)}`);if(g?.CreationToken)T.push(`CreationToken=${encodeURIComponent(g.CreationToken)}`);let N=`/2015-02-01/file-systems${T.length>0?`?${T.join("&")}`:""}`;return{FileSystems:((await this.client.request({service:"elasticfilesystem",region:this.region,method:"GET",path:N,headers:{"Content-Type":"application/json"}})).FileSystems||[]).map((L)=>({FileSystemId:L.FileSystemId,Name:L.Name,CreationTime:L.CreationTime,LifeCycleState:L.LifeCycleState,NumberOfMountTargets:L.NumberOfMountTargets,SizeInBytes:L.SizeInBytes?{Value:L.SizeInBytes.Value,Timestamp:L.SizeInBytes.Timestamp}:void 0,PerformanceMode:L.PerformanceMode,Encrypted:L.Encrypted,ThroughputMode:L.ThroughputMode,Tags:L.Tags}))}}}class t{client;region;constructor(g="us-east-1"){this.region=g,this.client=new Q}async call(g,T){return this.client.request({service:"wafv2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`AWSWAF_20190729.${g}`},body:JSON.stringify(T)})}async listWebACLs(g="REGIONAL"){return(await this.call("ListWebACLs",{Scope:g,Limit:100}))?.WebACLs??[]}async getWebACLRules(g,T,N="REGIONAL"){return((await this.call("GetWebACL",{Name:g,Id:T,Scope:N}))?.WebACL?.Rules??[]).map((P)=>({Name:P.Name,Priority:P.Priority,Action:P.Action?Object.keys(P.Action)[0]:P.OverrideAction?Object.keys(P.OverrideAction)[0]:"count"}))}}function Pg(g){return String(g).padStart(2,"0")}function y(g){return`${g.getUTCFullYear()}-${Pg(g.getUTCMonth()+1)}-${Pg(g.getUTCDate())}`}function _g(g){let T=Math.max(0,Math.round((Date.now()-g)/1000));if(T<60)return`${T}s ago`;let N=Math.round(T/60);if(N<60)return`${N}m ago`;let z=Math.round(N/60);if(z<48)return`${z}h ago`;return`${Math.round(z/24)}d ago`}async function k(g,T,N,z,L,P){let Y=await g.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:N,Dimensions:[{Name:"FunctionName",Value:T}],StartTime:L,EndTime:P,Period:86400,Statistics:[z]}).catch(()=>[]);if(!Y.length)return 0;if(z==="Sum")return Y.reduce((X,Z)=>X+(Z.Sum??0),0);if(z==="Maximum")return Math.max(...Y.map((X)=>X.Maximum??0));return Y.reduce((X,Z)=>X+(Z.Average??0),0)/Y.length}async function w(g,T,N,z,L,P,Y){let X=await g.getMetricStatistics({Namespace:T,MetricName:N,Dimensions:z,StartTime:P,EndTime:Y,Period:86400,Statistics:[L]}).catch(()=>[]);if(!X.length)return 0;if(L==="Sum")return X.reduce((Z,W)=>Z+(W.Sum??0),0);if(L==="Maximum")return Math.max(...X.map((Z)=>Z.Maximum??0));return X.reduce((Z,W)=>Z+(W.Average??0),0)/X.length}async function n(g,T,N,z,L){let P=await g.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"Duration",Dimensions:[{Name:"FunctionName",Value:T}],StartTime:z,EndTime:L,Period:86400,ExtendedStatistics:[N]}).catch(()=>[]);return Math.round(P.reduce((Y,X)=>Y+(X.Percentiles?.[N]??0),0))}async function PT(g,T){let N=await $g(g,T),z=N.region,L=new r(z),P=new xg(z),Y=new a(z),X=new Date,Z=new Date(X.getTime()-86400000),W=g.environments?.[T]?.app,G={};G.app={name:N.slug,env:T,region:z,runtime:W?.kind==="php"?`php-${W?.phpVersion??"8.3"} (fpm)`:W?.kind??"node",url:N.endpoint??"",build:N.lastRelease?.sha?.slice(0,7)??"—",deployedAt:N.lastRelease?.timestamp??"—"},G.maintenance={enabled:!1},G.scheduler={enabled:N.scheduler!=="off",expression:N.scheduler==="sub-minute"?"rate(1 minute) · sub-minute":"rate(1 minute)",lastRun:"—"};let b=0,U=0,S=0,v=[],K=[],C=[];for(let J of N.functions){let[O,x,B,V,$,H,E,R,I]=await Promise.all([k(L,J.name,"Invocations","Sum",Z,X),k(L,J.name,"Errors","Sum",Z,X),k(L,J.name,"Throttles","Sum",Z,X),k(L,J.name,"Duration","Average",Z,X),P.getFunction(J.name).catch(()=>null),n(L,J.name,"p50",Z,X),n(L,J.name,"p95",Z,X),n(L,J.name,"p99",Z,X),L.getMetricSeries({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:[{Name:"FunctionName",Value:J.name}],StartTime:new Date(X.getTime()-43200000),EndTime:X,Period:3600,Stat:"Sum"}).catch(()=>[])]);b+=O,U+=x,S=Math.max(S,V);let D=$?.Configuration?.MemorySize??0,F=Object.keys($?.Configuration?.Environment?.Variables??{}),M=[],j=0;try{let{events:d=[]}=await Y.filterLogEvents({logGroupName:`/aws/lambda/${J.name}`,startTime:Z.getTime(),limit:120});for(let A of d){let h=(A.message??"").trim(),o=/Max Memory Used:\s*(\d+)\s*MB/.exec(h);if(o)j=Math.max(j,Number(o[1]));if(h&&!/^(?:START|END|REPORT|INIT_START)/.test(h))C.push({source:J.mode||J.name,timestamp:new Date(A.timestamp??0).toISOString(),when:_g(A.timestamp??0),message:h.slice(0,400),level:/error|exception|fatal|panic|traceback/i.test(h)?"error":/warn|warning|timeout|retr(?:y|ies)|throttl/i.test(h)?"warn":"info"})}M=d.filter((A)=>!/^(?:START|END|REPORT|INIT_START)/.test((A.message??"").trim())).slice(-6).map((A)=>({ts:new Date(A.timestamp??0).toISOString().slice(11,19),msg:(A.message??"").trim().slice(0,120),err:/error|exception|fatal/i.test(A.message??"")}))}catch{}let q=Math.max(1,...I);v.push({key:J.mode,name:J.name,version:J.version,memory:D,timeout:$?.Configuration?.Timeout??0,runtime:$?.Configuration?.Runtime??"provided.al2023",invocations:Math.round(O),errors:Math.round(x),p95:E||Math.round(V),status:"active",provisioned:J.provisioned?`${J.provisioned.allocated}/${J.provisioned.requested}`:void 0}),K.push({key:J.mode,name:J.name,runtime:$?.Configuration?.Runtime??"provided.al2023",arch:$?.Configuration?.Architectures?.[0]??"x86_64",memory:D,timeout:$?.Configuration?.Timeout??0,ephemeral:$?.Configuration?.EphemeralStorage?.Size??512,version:J.version,concurrency:W?.concurrency??"—",invocations:Math.round(O),errors:Math.round(x),throttles:Math.round(B),p50:H||Math.round(V),p95:E||Math.round(V),p99:R||Math.round(V),maxMem:j,spark:I.length?I.map((d)=>Math.round(d/q*100)):[0],env:F.length?F:["(none)"],recent:M.length?M:[{ts:"—",msg:"no recent events",err:!1}]})}G.functions=v,G.functionsDetail=K,G.serverlessLogs=C.sort((J,O)=>String(O.timestamp).localeCompare(String(J.timestamp))).slice(0,600),G.serverlessLogsEmptyReason=C.length?void 0:"No recent function logs were found in CloudWatch for this environment.";let u=b?Number((U/b*100).toFixed(2)):0,l=Math.round(await k(L,N.functions[0]?.name??"","ConcurrentExecutions","Maximum",Z,X));G.metrics={invocations:Math.round(b),errorRatePct:u,p95Ms:Math.round(S),coldStartPct:void 0,concurrency:l,estCostUsd:void 0};try{let J=new Wg(z),O=[],x=[],B=0;try{let{QueueUrl:$}=await J.getQueueUrl(`${N.slug}-${T}-dlq`),{Attributes:H}=await J.getQueueAttributes($);B=Number(H.ApproximateNumberOfMessages??0)}catch{}let V=W?Bg(W,N.slug,T):[];for(let $ of V){let H=$.name.replace(`${N.slug}-${T}-`,""),E=0,R=0;try{let{QueueUrl:D}=await J.getQueueUrl($.name),{Attributes:F}=await J.getQueueAttributes(D);E=Number(F.ApproximateNumberOfMessages??0),R=Number(F.ApproximateNumberOfMessagesNotVisible??0)}catch{}let I=Math.round(await w(L,"AWS/SQS","NumberOfMessagesDeleted",[{Name:"QueueName",Value:$.name}],"Sum",Z,X));O.push({name:H,visible:E,inFlight:R,processed:I,dlq:B}),x.push({name:$.name,short:H,visible:E,inFlight:R,delayed:0,processed:I,oldestSec:0,concurrency:$.concurrency??W?.queueConcurrency??"—",tries:W?.queueTries??3,visTimeout:(W?.queueTimeout??120)*6,dlq:B})}if(O.length)G.queues=O;if(x.length)G.queuesDetail=x;G.dlqItems=[]}catch{}try{let J=new Og(z),{Stacks:O}=await J.describeStacks({stackName:Xg(g,T)}),x={};for(let B of O?.[0]?.Outputs??[])if(B.OutputKey)x[B.OutputKey]=B.OutputValue??"";if(W?.database?.connection==="aurora-serverless"){let B=`${N.slug}-${T}-db`,V=[{Name:"DBClusterIdentifier",Value:B}],[$,H]=await Promise.all([w(L,"AWS/RDS","ServerlessDatabaseCapacity",V,"Average",Z,X),w(L,"AWS/RDS","DatabaseConnections",V,"Maximum",Z,X)]);if(G.aurora={id:B,engine:"aurora-mysql",minAcu:W?.database?.minCapacity??0.5,maxAcu:W?.database?.maxCapacity??4,currentAcu:$?Number($.toFixed(1)):W?.database?.minCapacity??0.5,database:"app",connections:Math.round(H),status:x.DbEndpoint?"available":"creating"},W?.rdsProxy)G.proxy={name:`${N.slug}-${T}-proxy`,endpoint:x.DbProxyEndpoint??"—",pooledConns:Math.round(H),status:"available"}}if(W?.cache?.driver==="elasticache"){let B=`${N.slug}-${T}-cache`,V=[{Name:"CacheClusterId",Value:`${B}-001`}],[$,H]=await Promise.all([w(L,"AWS/ElastiCache","CacheHits",V,"Sum",Z,X),w(L,"AWS/ElastiCache","CacheMisses",V,"Sum",Z,X)]),E=$+H>0?Number(($/($+H)*100).toFixed(1)):0;G.redis={id:B,node:"cache.t4g.micro",engine:"redis",hitRate:E,status:x.CacheEndpoint?"available":"creating"}}if(W?.efs){let B=0;try{if(x.EfsFileSystemId){let V=new p(z),{FileSystems:$}=await V.describeFileSystems({FileSystemId:x.EfsFileSystemId});B=Number((($?.[0]?.SizeInBytes?.Value??0)/1048576).toFixed(1))}}catch{}G.efs={id:x.EfsFileSystemId??"efs",mount:"/mnt/local",sizeMb:B,status:"available"}}G.assetsInfo=x.AssetsCdnDomain?{bucket:x.AssetsBucketName??`${N.slug}-${T}-assets`,cdn:x.AssetsCdnDomain,customDomain:W?.assetDomain??"—",assetUrl:N.assetUrl??"—",files:0,sizeMb:0,cacheHitPct:0,build:G.app.build}:void 0}catch{}if(G.assetsInfo)try{let O=await new s(z).list({bucket:G.assetsInfo.bucket,maxKeys:1000});G.assetsInfo.files=O.length,G.assetsInfo.sizeMb=Number((O.reduce((x,B)=>x+(B.Size??0),0)/1048576).toFixed(1)),G.assetsRecent=O.slice(0,8).map((x)=>({path:`/${x.Key}`,size:`${Math.max(1,Math.round((x.Size??0)/1024))} KB`,type:x.Key.split(".").pop()??""}))}catch{}try{if(W?.secrets){let J=Array.isArray(W.secrets)?W.secrets.map((O)=>({key:O.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),source:O})):Object.entries(W.secrets).map(([O,x])=>({key:O,source:String(x)}));G.secretsList=J.map((O)=>({...O,updated:"—"}))}}catch{}try{let J=new s(z),O=`${N.slug}-${T}-deployments`,x=await J.getObjectJson(O,`deployments/${N.slug}/${T}/history.json`).catch(()=>null);if(x?.records?.length)G.deploymentsDetail=x.records.slice(-12).reverse().map((B)=>({sha:(B.sha??"").slice(0,7),status:B.status??"success",when:B.timestamp??"—",took:B.took??"—",by:B.by??"—",version:B.version??"—",hooks:B.hooks??[]}))}catch{}G.metricsTotals={invocations:G.metrics.invocations,errors:Math.round(U),errorRatePct:u,p95Ms:G.metrics.p95Ms,throttles:K.reduce((J,O)=>J+O.throttles,0),coldStartPct:void 0,estCostUsd:void 0,concurrency:l},G.metricsPerFn=K.map((J)=>({key:J.key,invocations:J.invocations,errors:J.errors,throttles:J.throttles,avgMs:J.p50,maxMs:J.p99,costUsd:void 0}));try{G.invSpark=await L.getMetricSeries({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:[{Name:"FunctionName",Value:N.functions.find((J)=>J.mode==="http")?.name??""}],StartTime:new Date(X.getTime()-86400000),EndTime:X,Period:3600,Stat:"Sum"})}catch{}try{let J=new e,O=X,x=new Date(Date.UTC(O.getUTCFullYear(),O.getUTCMonth(),1)),B=new Date(Date.UTC(O.getUTCFullYear(),O.getUTCMonth()-1,1)),[V,$]=await Promise.all([J.getCostByService({start:y(x),end:y(O),granularity:"MONTHLY"}).catch(()=>[]),J.getCostByService({start:y(B),end:y(x),granularity:"MONTHLY"}).catch(()=>[])]);if(V.length){let H=V.reduce((j,q)=>j+q.amount,0),E=$.reduce((j,q)=>j+q.amount,0),R=O.getUTCDate(),I=new Date(Date.UTC(O.getUTCFullYear(),O.getUTCMonth()+1,0)).getUTCDate();G.costSummary={monthToDateUsd:Number(H.toFixed(2)),projectedUsd:Number((H/R*I).toFixed(2)),lastMonthUsd:Number(E.toFixed(2)),dailyAvgUsd:Number((H/R).toFixed(2))},G.costServices=V.filter((j)=>j.amount>0).sort((j,q)=>q.amount-j.amount).slice(0,12).map((j)=>({name:j.service,usd:Number(j.amount.toFixed(2)),note:""})),G.metrics.estCostUsd=Number((H/R).toFixed(2)),G.metricsTotals.estCostUsd=G.metrics.estCostUsd,G.costTrend=await J.getDailyTotals({start:y(x),end:y(O)}).catch(()=>[]);let D=V.find((j)=>/lambda/i.test(j.service))?.amount??0,F=(j)=>j.invocations*(j.p50/1000)*(j.memory/1024),M=K.reduce((j,q)=>j+F(q),0)||1;G.costPerFn=K.map((j)=>({key:j.key,requests:j.invocations,gbSec:Math.round(F(j)),usd:Number((D*(F(j)/M)).toFixed(2))}))}}catch{}if(W?.firewall)try{let J=await L.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"BlockedRequests",StartTime:Z,EndTime:X,Period:86400,Statistics:["Sum"]}).catch(()=>[]),O=await L.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"AllowedRequests",StartTime:Z,EndTime:X,Period:86400,Statistics:["Sum"]}).catch(()=>[]);G.waf={enabled:!0,scope:"REGIONAL",acl:`${N.slug}-${T}-waf`,allowed24h:Math.round(O.reduce((x,B)=>x+(B.Sum??0),0)),blocked24h:Math.round(J.reduce((x,B)=>x+(B.Sum??0),0))};try{let x=new t(z),B=await x.listWebACLs("REGIONAL"),V=B.find(($)=>$.Name?.includes(`${N.slug}-${T}`))??B[0];if(V?.Name&&V.Id){G.waf.acl=V.Name;let $=await x.getWebACLRules(V.Name,V.Id,"REGIONAL");if($.length)G.wafRules=$.map((H)=>({name:H.Name??"—",detail:`priority ${H.Priority??0}`,action:H.Action??"count",blocked24h:0}))}}catch{}}catch{}let _=[];if(G.aurora)_.push({name:"Aurora Serverless v2",detail:`${G.aurora.id} · ${G.aurora.minAcu}-${G.aurora.maxAcu} ACU`,status:G.aurora.status});if(G.proxy)_.push({name:"RDS Proxy",detail:G.proxy.name,status:G.proxy.status});if(G.redis)_.push({name:`ElastiCache (${G.redis.engine})`,detail:`${G.redis.node} · ${G.redis.hitRate}% hit rate`,status:G.redis.status});if(G.efs)_.push({name:"EFS",detail:`${G.efs.mount} · ${G.efs.sizeMb} MB`,status:G.efs.status});if(_.length)G.dataServices=_;if(N.scheduler!=="off"&&W?.kind==="php")try{let J=await Zg(g,T,"schedule:list"),O=[];for(let x of(J||"").split(`
|
|
2
|
+
`)){let B=/^\s*([\d*/,\-\s]+?)\s{2,}(.+?)(?:\s{2,}Next Due.*)?$/.exec(x);if(B&&/[*\d]/.test(B[1])&&B[1].trim().split(/\s+/).length===5)O.push({command:B[2].trim().replace(/^php artisan /,""),cron:B[1].trim(),desc:"",lastRun:"—",lastStatus:"ok"})}if(O.length)G.schedulerTasks=O}catch{}return G.topology=Yg(G,{project:g.project.name,environment:T}),G}
|
|
3
|
+
export{a as sd,r as td,wg as ud,vg as vd,e as wd,PT as xd};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{Bf as F,Ef as H,Ff as w,Of as A,gf as $,pf as Z}from"./chunk-tga3hhwk.js";function C(z){return`'${z.split("'").join("'\\''")}'`}function q(z){let G=z.user||"root",K=z.script.join(`
|
|
2
|
+
`),M=G==="root"?'bash -l "$TS_CLOUD_RECIPE"':`runuser -l ${C(G)} -c "bash $TS_CLOUD_RECIPE"`;return["set -uo pipefail",`echo "__TS_CLOUD_RECIPE_BEGIN__ ${z.name} (user=${G})"`,"TS_CLOUD_RECIPE=$(mktemp)",`cat > "$TS_CLOUD_RECIPE" <<'TS_CLOUD_RECIPE_EOF'`,K,"TS_CLOUD_RECIPE_EOF",'chmod +r "$TS_CLOUD_RECIPE"',M,"TS_CLOUD_RC=$?",'rm -f "$TS_CLOUD_RECIPE"',`echo "__TS_CLOUD_RECIPE_END__ ${z.name} exit=$TS_CLOUD_RC"`,"exit $TS_CLOUD_RC"]}var j={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};async function X(z){return await z.driver.findComputeTargets({slug:z.slug,environment:z.environment,role:z.role||"app"})}async function B(z,G){let K=z.logger||j,M=await X(z);if(M.length===0)return{success:!1,error:`No '${z.role||"app"}' servers found for ${z.slug}/${z.environment}.`};let Q=$(z.slug,G.siteName),W=w(Q,G.to||"unused"),U=["set -uo pipefail",...A(W,{...G.to?{to:G.to}:{},unitBase:`${z.slug}-${G.siteName}`}),`(cd ${Z} && pantry restart php-fpm) 2>/dev/null || true`,`(cd ${W.current} && eval "$(cd ${Z} && pantry env 2>/dev/null)" && php artisan queue:restart) 2>/dev/null || true`];K.step(`Rolling back ${G.siteName}${G.to?` to ${G.to}`:" to the previous release"} on ${M.length} server(s)...`);let V=await z.driver.runRemoteDeploy({targets:M,commands:U,comment:`ts-cloud rollback ${z.slug}/${G.siteName}`,tags:{Project:z.slug,Environment:z.environment,Role:z.role||"app"}});if(!V.success)K.error(`Rollback failed: ${V.error||"unknown error"}`);else K.success(`Rolled back ${G.siteName}.`);return{success:V.success,error:V.error,perInstance:V.perInstance}}async function I(z,G){let K=await X(z);if(K.length===0)return{success:!1,error:`No '${z.role||"app"}' servers found for ${z.slug}/${z.environment}.`};let M=H($(z.slug,G.siteName)),Q=Math.max(1,G.limit??20),W=[`[ -f ${M} ] && tail -n ${Q} ${M} || echo "no deploy history for ${G.siteName}"`],U=await z.driver.runRemoteDeploy({targets:K,commands:W,comment:`ts-cloud deploy:history ${z.slug}/${G.siteName}`,tags:{Project:z.slug,Environment:z.environment,Role:z.role||"app"}});return{success:U.success,error:U.error,perInstance:U.perInstance}}async function L(z,G){let K=z.logger||j,M=await X(z);if(M.length===0)return{success:!1,error:`No '${z.role||"app"}' servers found for ${z.slug}/${z.environment}.`};K.step(`Running recipe '${G.name}' as ${G.user||"root"} on ${M.length} server(s)...`);let Q=await z.driver.runRemoteDeploy({targets:M,commands:q({name:G.name,script:G.script,user:G.user}),comment:`ts-cloud recipe ${G.name}`,tags:{Project:z.slug,Environment:z.environment,Role:z.role||"app"}});if(!Q.success)K.error(`Recipe '${G.name}' failed: ${Q.error||"unknown error"}`);else K.success(`Recipe '${G.name}' completed.`);return{success:Q.success,error:Q.error,perInstance:Q.perInstance}}async function S(z,G){let K=z.logger||j;if(!G.database?.name)return{success:!1,error:"No appDatabase configured to restore."};let M=await X(z);if(M.length===0)return{success:!1,error:`No '${z.role||"app"}' servers found for ${z.slug}/${z.environment}.`};K.step(`Restoring database '${G.database.name}'${G.from?` from ${G.from}`:" from the latest backup"} on ${M.length} server(s)...`);let Q=await z.driver.runRemoteDeploy({targets:M,commands:F(G.database,{from:G.from}),comment:`ts-cloud db:restore ${z.slug}/${G.database.name}`,tags:{Project:z.slug,Environment:z.environment,Role:z.role||"app"}});if(!Q.success)K.error(`Restore failed: ${Q.error||"unknown error"}`);else K.success(`Restored ${G.database.name}.`);return{success:Q.success,error:Q.error,perInstance:Q.perInstance}}
|
|
3
|
+
export{B as od,I as pd,L as qd,S as rd};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{dd as a}from"./chunk-fhc6ntvd.js";import"./chunk-fpm59y25.js";import"./chunk-mh0kdzqp.js";export{a as RDSClient};
|