@stacksjs/ts-cloud 0.16.30 → 0.16.32
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 -1
- package/dist/bin/{chunk-5nf3fxgw.js → chunk-12j17qm5.js} +1 -1
- package/dist/bin/{chunk-0n0jscsr.js → chunk-24473jks.js} +1 -1
- package/dist/bin/chunk-3932p1z3.js +1 -0
- package/dist/bin/chunk-3eztnxgw.js +1 -0
- package/dist/bin/{chunk-10sypz59.js → chunk-4182gadf.js} +1 -1
- package/dist/bin/chunk-4er4ktcs.js +1 -0
- package/dist/bin/{chunk-7577ykbj.js → chunk-6wz04wnk.js} +1 -1
- package/dist/bin/{chunk-remzfbhd.js → chunk-6yr12f64.js} +3 -3
- package/dist/bin/{chunk-8c4fnga8.js → chunk-79sd00d1.js} +1 -1
- package/dist/bin/{chunk-bkzt5ntz.js → chunk-81mt497w.js} +1 -1
- package/dist/bin/{chunk-dmyr6etw.js → chunk-8mgwqpmx.js} +1 -1
- package/dist/bin/{chunk-e6xn8g28.js → chunk-985ev3ns.js} +1 -1
- package/dist/bin/{chunk-bvtpvstn.js → chunk-9e62z9je.js} +11 -11
- package/dist/bin/{chunk-g1krw34t.js → chunk-9eq18gds.js} +1 -1
- package/dist/bin/chunk-9zhp2z0s.js +1 -0
- package/dist/bin/{chunk-g00a221j.js → chunk-b9psp74n.js} +14 -14
- package/dist/bin/chunk-bmmr5mq6.js +1 -0
- package/dist/bin/{chunk-je602ntp.js → chunk-cr56pxpt.js} +1 -1
- package/dist/bin/chunk-dvv2z19r.js +1 -0
- package/dist/bin/{chunk-y9cdqk8c.js → chunk-efbmb8rw.js} +1 -1
- package/dist/bin/chunk-eyrmv6c4.js +1 -0
- package/dist/bin/{chunk-9nnfyqme.js → chunk-f7dtn45y.js} +3 -3
- package/dist/bin/chunk-fnnv0t66.js +1 -0
- package/dist/bin/{chunk-1chq0c2k.js → chunk-fpxb97q5.js} +1 -1
- package/dist/bin/chunk-fwmje99n.js +1 -0
- package/dist/bin/{chunk-k8r5zfnf.js → chunk-gcm9n6ww.js} +1 -1
- package/dist/bin/{chunk-6hrycgbh.js → chunk-gzxpkk0c.js} +1 -1
- package/dist/bin/{chunk-s3mv4z3f.js → chunk-jhp53qsd.js} +1 -1
- package/dist/bin/{chunk-jeg6vw5v.js → chunk-jzby2kzy.js} +1 -1
- package/dist/bin/{chunk-xtqx4v3f.js → chunk-kgtzvh2k.js} +1 -1
- package/dist/bin/{chunk-a9yp82q5.js → chunk-kqf19j9m.js} +1 -1
- package/dist/bin/{chunk-nb5vjsdg.js → chunk-mpq5ct10.js} +4 -4
- package/dist/bin/chunk-n775dk3f.js +1 -0
- package/dist/bin/{chunk-kne9dmwr.js → chunk-nnawqw34.js} +32 -32
- package/dist/bin/chunk-ppj604c9.js +1 -0
- package/dist/bin/chunk-prq5gw4j.js +1 -0
- package/dist/bin/chunk-pt71fyem.js +1 -0
- package/dist/bin/{chunk-1wtkv65w.js → chunk-py8cvqvx.js} +1 -1
- package/dist/bin/{chunk-3ykx59eg.js → chunk-q6z8wvvb.js} +1 -1
- package/dist/bin/{chunk-q9tvzcr7.js → chunk-qe56mnjc.js} +3 -3
- package/dist/bin/chunk-qvj454fy.js +1 -0
- package/dist/bin/{chunk-j8dkatkk.js → chunk-sdy79wz7.js} +4 -4
- package/dist/bin/chunk-smj97rs5.js +1 -0
- package/dist/bin/{chunk-yrq5bkxe.js → chunk-tg45thhb.js} +1 -1
- package/dist/bin/{chunk-e4p6hwct.js → chunk-tgwx5haz.js} +1 -1
- package/dist/bin/{chunk-9p7g25kx.js → chunk-vhz2wmb8.js} +81 -81
- package/dist/bin/{chunk-a1kpwbjg.js → chunk-wt7wjgcr.js} +3 -3
- package/dist/bin/{chunk-j2yy3tth.js → chunk-x56s9b7f.js} +1 -1
- package/dist/bin/chunk-yf3zys06.js +1 -0
- package/dist/bin/{chunk-ee6ssn26.js → chunk-zhkbdsfs.js} +1 -1
- package/dist/bin/{chunk-jf8jp6f5.js → chunk-zk3nm0td.js} +1 -1
- package/dist/bin/chunk-zmjm7bmm.js +1 -0
- package/dist/bin/cli.js +46 -46
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/chunk-05bmq0z1.js +1 -0
- package/dist/chunk-0qdgw73b.js +1 -0
- package/dist/{chunk-75bga11p.js → chunk-2mw7bjhn.js} +1 -1
- package/dist/{chunk-92w1g5d9.js → chunk-4hdp9ms2.js} +1 -1
- package/dist/{chunk-m3a4brpj.js → chunk-4jgy95bv.js} +5 -5
- package/dist/{chunk-z8qz33yk.js → chunk-57fhsqzb.js} +2 -2
- package/dist/{chunk-3kpnn06d.js → chunk-983txhkg.js} +1 -1
- package/dist/{chunk-b6ar7eqc.js → chunk-efssa93f.js} +1 -1
- package/dist/{chunk-26cq0zjv.js → chunk-jh38v9zp.js} +2 -2
- package/dist/{chunk-f733qy2d.js → chunk-kavwrxm8.js} +2 -2
- package/dist/{chunk-9n0q2cxj.js → chunk-nq51dyxz.js} +4 -4
- package/dist/{chunk-h3kkh31v.js → chunk-peeqkk92.js} +81 -81
- package/dist/chunk-pf6sanwe.js +1 -0
- package/dist/{chunk-2c8pcbq8.js → chunk-r45340yc.js} +34 -34
- package/dist/{chunk-mqm1hxaw.js → chunk-rqe0sfqw.js} +2 -2
- package/dist/{chunk-1erk1r1m.js → chunk-s909414m.js} +1 -1
- package/dist/{chunk-t3yzfbe7.js → chunk-t1gts5j9.js} +4 -4
- package/dist/{chunk-yc2rm4v9.js → chunk-wbabf3hg.js} +1 -1
- package/dist/{chunk-aeqm2v91.js → chunk-xbh2vr95.js} +34 -34
- package/dist/deploy/index.js +1 -1
- package/dist/drivers/index.js +1 -1
- package/dist/drivers/shared/deploy-script.d.ts +67 -0
- package/dist/index.js +3 -3
- package/dist/operations/index.js +1 -1
- package/dist/protection/index.js +1 -1
- package/dist/spend/index.js +1 -1
- package/dist/ui/404.html +1 -1
- package/dist/ui/accept-invitation.html +1 -1
- package/dist/ui/access-denied.html +1 -1
- package/dist/ui/account/automation.html +6 -6
- package/dist/ui/account/security.html +2 -2
- package/dist/ui/applications/compose.html +6 -6
- package/dist/ui/applications/new.html +2 -2
- package/dist/ui/data/backups.html +6 -6
- package/dist/ui/data/services.html +6 -6
- package/dist/ui/data/volumes.html +6 -6
- package/dist/ui/index.html +6 -6
- package/dist/ui/infrastructure/topology.html +6 -6
- package/dist/ui/integrations.html +1 -1
- package/dist/ui/operations/alerts.html +6 -6
- package/dist/ui/operations/configuration.html +6 -6
- package/dist/ui/operations/jobs.html +6 -6
- package/dist/ui/operations/maintenance.html +6 -6
- package/dist/ui/operations/observability.html +6 -6
- package/dist/ui/operations/previews.html +5 -5
- package/dist/ui/operations/queue.html +6 -6
- package/dist/ui/operations/regions.html +6 -6
- package/dist/ui/operations/releases.html +6 -6
- package/dist/ui/operations/spend.html +6 -6
- package/dist/ui/operations/workloads.html +6 -6
- package/dist/ui/security.html +1 -1
- package/dist/ui/server/actions.html +6 -6
- package/dist/ui/server/activity.html +1 -1
- package/dist/ui/server/capacity.html +6 -6
- package/dist/ui/server/database.html +6 -6
- package/dist/ui/server/deployments.html +6 -6
- package/dist/ui/server/diagnostics.html +2 -2
- package/dist/ui/server/firewall.html +6 -6
- package/dist/ui/server/fleet.html +6 -6
- package/dist/ui/server/logs.html +6 -6
- package/dist/ui/server/metrics.html +6 -6
- package/dist/ui/server/security.html +2 -2
- package/dist/ui/server/services.html +2 -2
- package/dist/ui/server/sites.html +6 -6
- package/dist/ui/server/ssh-keys.html +6 -6
- package/dist/ui/server/team.html +6 -6
- package/dist/ui/server/terminal.html +2 -2
- package/dist/ui/serverless/alarms.html +6 -6
- package/dist/ui/serverless/assets.html +1 -1
- package/dist/ui/serverless/cost.html +1 -1
- package/dist/ui/serverless/data.html +5 -5
- package/dist/ui/serverless/deployments.html +2 -2
- package/dist/ui/serverless/firewall.html +2 -2
- package/dist/ui/serverless/functions.html +6 -6
- package/dist/ui/serverless/logs.html +6 -6
- package/dist/ui/serverless/metrics.html +2 -2
- package/dist/ui/serverless/queues.html +6 -6
- package/dist/ui/serverless/secrets.html +6 -6
- package/dist/ui/serverless/traces.html +6 -6
- package/dist/ui/serverless.html +5 -5
- package/package.json +3 -3
- package/dist/bin/chunk-052sk11z.js +0 -1
- package/dist/bin/chunk-1d4663e1.js +0 -1
- package/dist/bin/chunk-223yq2z0.js +0 -1
- package/dist/bin/chunk-675txngy.js +0 -1
- package/dist/bin/chunk-98e48n5j.js +0 -1
- package/dist/bin/chunk-ckmgwd81.js +0 -1
- package/dist/bin/chunk-ecxchy9q.js +0 -1
- package/dist/bin/chunk-gcazbfsv.js +0 -1
- package/dist/bin/chunk-gg6vwdnn.js +0 -1
- package/dist/bin/chunk-gz0gahzh.js +0 -1
- package/dist/bin/chunk-hdkxj8p9.js +0 -1
- package/dist/bin/chunk-hg60j47r.js +0 -1
- package/dist/bin/chunk-jxh78anm.js +0 -1
- package/dist/bin/chunk-mv0t7j76.js +0 -1
- package/dist/bin/chunk-p8f1qgz2.js +0 -1
- package/dist/bin/chunk-pa106cr4.js +0 -1
- package/dist/bin/chunk-w3815pxd.js +0 -1
- package/dist/chunk-43pe4shw.js +0 -1
- package/dist/chunk-94tb2msg.js +0 -1
- package/dist/chunk-d8wcqgpx.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{ed,td,rd,nd,zu,Hu}from"./chunk-mpq5ct10.js";import"./chunk-py8cvqvx.js";import"./chunk-9e62z9je.js";import"./chunk-x56s9b7f.js";import"./chunk-efbmb8rw.js";import"./chunk-kqf19j9m.js";import"./chunk-qe56mnjc.js";export{zu as deleteStaticSite,td as deployStaticSite,Hu as deployStaticSiteFull,ed as generateStaticSiteTemplate,nd as invalidateCache,rd as uploadStaticFiles};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{wd,ac,Ad,co,lo,uo,Es}from"./chunk-sdy79wz7.js";import"./chunk-nnawqw34.js";export{wd as MANAGEMENT_DASHBOARD_SITE,Es as buildManagementDashboardArtifact,ac as dashboardCredentialsFile,lo as ensureManagementDashboard,uo as managementDashboardSiteNames,Ad as resolveDashboardAuth,co as resolveUiSource};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{fi,wo,u,N,Hs}from"./chunk-qe56mnjc.js";export{u as AWSClient,N as buildQueryParams,wo as coerceXmlValues,Hs as detectCredentialSource,fi as resolveS3Endpoint};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{u}from"./chunk-
|
|
1
|
+
import{u}from"./chunk-qe56mnjc.js";class B{client;region;constructor(e="us-east-1"){this.region=e,this.client=new u}async createHostedZone(e){let t=e.CallerReference||`${Date.now()}-${Math.random().toString(36).slice(2)}`,o=`<?xml version="1.0" encoding="UTF-8"?>
|
|
2
2
|
<CreateHostedZoneRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
|
|
3
3
|
<Name>${e.Name}</Name>
|
|
4
4
|
<CallerReference>${t}</CallerReference>`;if(e.HostedZoneConfig){if(o+=`
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{ct}from"./chunk-kgtzvh2k.js";import"./chunk-qe56mnjc.js";export{ct as STSClient};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{De,ta,Ro,fa,un,Bo,ha,ya,wa,Ca}from"./chunk-kne9dmwr.js";import{n,r,a,e,p,i,Se}from"./chunk-e4p6hwct.js";import{u}from"./chunk-q9tvzcr7.js";import{v}from"./chunk-j2yy3tth.js";import{R}from"./chunk-1chq0c2k.js";import{g}from"./chunk-a9yp82q5.js";import{existsSync as de,readdirSync as me,readFileSync as pe,statSync as fe}from"node:fs";import{join as ne,relative as ye}from"node:path";class K{client;region;constructor(t="us-east-1",s){this.region=t,this.client=new u(void 0,{profile:s})}async createSecret(t){let s={Name:t.Name};if(t.Description)s.Description=t.Description;if(t.KmsKeyId)s.KmsKeyId=t.KmsKeyId;if(t.SecretBinary)s.SecretBinary=t.SecretBinary;if(t.SecretString)s.SecretString=t.SecretString;if(t.Tags&&t.Tags.length>0)s.Tags=t.Tags;if(t.AddReplicaRegions&&t.AddReplicaRegions.length>0)s.AddReplicaRegions=t.AddReplicaRegions;if(t.ForceOverwriteReplicaSecret!==void 0)s.ForceOverwriteReplicaSecret=t.ForceOverwriteReplicaSecret;s.ClientRequestToken=t.ClientRequestToken||crypto.randomUUID();let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.CreateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId,ReplicationStatus:o.ReplicationStatus}}async updateSecret(t){let s={SecretId:t.SecretId,ClientRequestToken:t.ClientRequestToken||crypto.randomUUID()};if(t.Description)s.Description=t.Description;if(t.KmsKeyId)s.KmsKeyId=t.KmsKeyId;if(t.SecretBinary)s.SecretBinary=t.SecretBinary;if(t.SecretString)s.SecretString=t.SecretString;let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.UpdateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId}}async putSecretValue(t){let s={SecretId:t.SecretId};if(t.SecretBinary)s.SecretBinary=t.SecretBinary;if(t.SecretString)s.SecretString=t.SecretString;if(t.VersionStages&&t.VersionStages.length>0)s.VersionStages=t.VersionStages;s.ClientRequestToken=t.ClientRequestToken||crypto.randomUUID();let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.PutSecretValue","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId,VersionStages:o.VersionStages}}async getSecretValue(t){let s={SecretId:t.SecretId};if(t.VersionId)s.VersionId=t.VersionId;if(t.VersionStage)s.VersionStage=t.VersionStage;let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.GetSecretValue","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId,SecretBinary:o.SecretBinary,SecretString:o.SecretString,VersionStages:o.VersionStages,CreatedDate:o.CreatedDate}}async describeSecret(t){let s={SecretId:t},o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.DescribeSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return this.parseSecret(o)}async listSecrets(t){let s={};if(t?.MaxResults)s.MaxResults=t.MaxResults;if(t?.NextToken)s.NextToken=t.NextToken;if(t?.Filters&&t.Filters.length>0)s.Filters=t.Filters;if(t?.SortOrder)s.SortOrder=t.SortOrder;let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.ListSecrets","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{SecretList:o.SecretList?.map((c)=>this.parseSecret(c)),NextToken:o.NextToken}}async deleteSecret(t){let s={SecretId:t.SecretId};if(t.RecoveryWindowInDays!==void 0)s.RecoveryWindowInDays=t.RecoveryWindowInDays;if(t.ForceDeleteWithoutRecovery!==void 0)s.ForceDeleteWithoutRecovery=t.ForceDeleteWithoutRecovery;let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.DeleteSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,DeletionDate:o.DeletionDate}}async restoreSecret(t){let s={SecretId:t},o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.RestoreSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name}}async rotateSecret(t){let s={SecretId:t.SecretId};if(t.ClientRequestToken)s.ClientRequestToken=t.ClientRequestToken;if(t.RotationLambdaARN)s.RotationLambdaARN=t.RotationLambdaARN;if(t.RotationRules)s.RotationRules=t.RotationRules;if(t.RotateImmediately!==void 0)s.RotateImmediately=t.RotateImmediately;let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.RotateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId}}async cancelRotateSecret(t){let s={SecretId:t},o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.CancelRotateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name}}async getResourcePolicy(t){let s={SecretId:t},o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.GetResourcePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,ResourcePolicy:o.ResourcePolicy}}async putResourcePolicy(t){let s={SecretId:t.SecretId,ResourcePolicy:t.ResourcePolicy};if(t.BlockPublicPolicy!==void 0)s.BlockPublicPolicy=t.BlockPublicPolicy;let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.PutResourcePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name}}async deleteResourcePolicy(t){let s={SecretId:t},o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.DeleteResourcePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name}}async tagResource(t){let s={SecretId:t.SecretId,Tags:t.Tags};await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.TagResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)})}async untagResource(t){let s={SecretId:t.SecretId,TagKeys:t.TagKeys};await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.UntagResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)})}async setString(t,s,o){try{let c=await this.putSecretValue({SecretId:t,SecretString:s});return{ARN:c.ARN,VersionId:c.VersionId}}catch(c){if(c.code==="ResourceNotFoundException"){let l=await this.createSecret({Name:t,SecretString:s,Description:o?.description,KmsKeyId:o?.kmsKeyId,Tags:o?.tags});return{ARN:l.ARN,VersionId:l.VersionId}}throw c}}async setJson(t,s,o){return this.setString(t,JSON.stringify(s),o)}async getString(t){return(await this.getSecretValue({SecretId:t})).SecretString}async getJson(t){let s=await this.getString(t);if(s)return JSON.parse(s);return}async listAll(){let t=[],s;do{let o=await this.listSecrets({NextToken:s});if(o.SecretList)t.push(...o.SecretList);s=o.NextToken}while(s);return t}parseSecret(t){return{ARN:t.ARN,Name:t.Name,Description:t.Description,KmsKeyId:t.KmsKeyId,RotationEnabled:t.RotationEnabled,RotationLambdaARN:t.RotationLambdaARN,RotationRules:t.RotationRules,LastRotatedDate:t.LastRotatedDate,LastChangedDate:t.LastChangedDate,LastAccessedDate:t.LastAccessedDate,DeletedDate:t.DeletedDate,NextRotationDate:t.NextRotationDate,Tags:t.Tags,SecretVersionsToStages:t.SecretVersionsToStages,CreatedDate:t.CreatedDate,PrimaryRegion:t.PrimaryRegion}}}function E(t,s){let o=t.environments?.[s]?.app;if(!o)throw Error(`No serverless app configured for environment '${s}'. Add environments.${s}.app to your config.`);let c=t.project.slug,l=t.environments?.[s]?.region||t.project.region||"us-east-1";return{app:o,slug:c,region:l,stackName:De(t,s),artifactBucket:ta(c,s),assetsBucket:Ro(c,s)}}function yt(t,s){let o=E(t,s),c=`${o.slug}-${s}`;return{region:o.region,slug:o.slug,stackName:o.stackName,functions:{http:`${c}-http`,queue:`${c}-queue`,cli:`${c}-cli`}}}async function q(t,s=8){let o;for(let c=0;c<s;c++)try{return await t()}catch(l){let d=l?.code||l?.name||"",m=String(l?.message||"");if(d==="ResourceConflictException"||/update is in progress|currently in the following state/i.test(m)){o=l,await new Promise((f)=>setTimeout(f,3000));continue}throw l}throw o}var ie=(t,s)=>`releases/${t}/${s}/current.json`;async function G(t,s,o,c){try{return await t.getObjectJson(s,ie(o,c))}catch{return null}}async function ae(t,s,o,c,l){await t.putObjectJson(s,ie(o,c),l)}async function Re(t,s){if(!t.secrets)return{};let o=new K(s),c={},l=Array.isArray(t.secrets)?t.secrets.map((d)=>({envName:d.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),secretId:d})):Object.entries(t.secrets).map(([d,m])=>({envName:d,secretId:m}));if(Array.isArray(t.secrets)){let d=new Map;for(let{envName:f,secretId:S}of l)d.set(f,[...d.get(f)??[],S]);let m=[...d.entries()].filter(([,f])=>f.length>1);if(m.length){let f=m.map(([S,h])=>`${S} ← ${h.join(", ")}`).join("; ");throw Error(`serverless secrets: multiple secrets map to the same env var (${f}). Use the map form { ENV_NAME: 'secret/id' } to disambiguate.`)}}for(let{envName:d,secretId:m}of l){let S=(await o.getSecretValue({SecretId:m})).SecretString??"";try{let h=JSON.parse(S);if(h&&typeof h==="object"&&!Array.isArray(h)){for(let[C,w]of Object.entries(h))c[C]=String(w);continue}}catch{}c[d]=S}return c}function Id(t,s){let o={},c=s.DbProxyEndpoint||s.DbEndpoint;if(c)o.DB_CONNECTION="mysql",o.DB_HOST=c,o.DB_PORT="3306",o.DB_DATABASE=o.DB_DATABASE||"app";if(s.CacheEndpoint){if(o.REDIS_HOST=s.CacheEndpoint,o.REDIS_PORT="6379",t.cache?.driver==="elasticache")o.CACHE_STORE="redis",o.CACHE_DRIVER="redis",o.SESSION_DRIVER="redis"}return o}function ws(t,s,o,c,l,d,m,f={}){let S=t.kind==="php"?wa({cacheDriver:t.cache?.driver==="elasticache"?"redis":"dynamodb"}):{};return{TSCLOUD_LAMBDA_MODE:c,TSCLOUD_ENV:o,MAINTENANCE_MODE:"0",...t.octane?{TSCLOUD_OCTANE:"1"}:{},...t.serveAssets?{TSCLOUD_SERVE_ASSETS:"1"}:{},...t.redirectRobotsTxt===!1?{TSCLOUD_REDIRECT_ROBOTS_TXT:"0"}:{},...S,...f,...s.app.cache?.driver!=="elasticache"?{TSCLOUD_CACHE_TABLE:`${s.slug}-${o}-cache`}:{},...m?{TSCLOUD_QUEUE:m,SQS_QUEUE:m}:{},...d?{ASSET_URL:d}:{},...t.env??{},...l}}function he(t){let s=t.slice(t.lastIndexOf(".")).toLowerCase();return{".html":"text/html",".css":"text/css",".js":"text/javascript",".mjs":"text/javascript",".json":"application/json",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".txt":"text/plain",".map":"application/json"}[s]??"application/octet-stream"}function*oe(t){for(let s of me(t)){let o=ne(t,s);if(fe(o).isDirectory())yield*oe(o);else yield o}}async function ve(t,s,o,c,l=!1){let d=0;for(let m of oe(o)){let f=ye(o,m).replace(/\\/g,"/");if(!l&&f.split("/").some((S)=>S.startsWith(".")))continue;await t.putObject({bucket:s,key:`${c}/${f}`,body:pe(m),contentType:he(m),cacheControl:"public, max-age=31536000, immutable"}),d++}return d}function po(t,s){let o=Object.entries(s).reduce((c,[l,d])=>c+Buffer.byteLength(`${l}=${d}`,"utf8"),0);if(o>4096){let c=Object.entries(s).map(([l,d])=>[l,Buffer.byteLength(`${l}=${d}`,"utf8")]).sort((l,d)=>d[1]-l[1]).slice(0,5).map(([l,d])=>`${l} (${d}B)`).join(", ");throw Error(`${t}: environment variables total ${o}B, over AWS's 4096B limit (${o-4096}B too large). Largest: ${c}. Move large/secret values out of env — store them in Secrets Manager and fetch at cold start.`)}}async function U(t,s,o,c){po(s,o),await q(()=>t.updateFunctionConfiguration({FunctionName:s,Environment:{Variables:o}})),await t.waitForFunctionActive(s,120);let l=c.kind==="image"?{FunctionName:s,ImageUri:c.imageUri}:{FunctionName:s,S3Bucket:c.bucket,S3Key:c.key};await q(()=>t.updateFunctionCode(l)),await t.waitForFunctionActive(s,120)}async function X(t,s){let c=(await q(()=>t.publishVersion({FunctionName:s}))).Version;if(!c)throw Error(`publishVersion returned no version for ${s}`);return await q(()=>t.updateAlias({FunctionName:s,Name:"live",FunctionVersion:c})),c}async function up(t,s,o={}){let c=E(t,s),{app:l,slug:d,region:m,stackName:f,artifactBucket:S}=c,h=o.projectRoot??process.cwd();i(`Deploying serverless app: ${d} (${s})`),e(`Stack: ${f}`),e(`Region: ${m}`);let C=new g(m),w=new v(m),b=new R(m),P=l.kind==="php",O=l.packaging==="image",N=Bo(l),V,I,k,Y,M=[];if(O&&N.usesLayer&&N.layerKind!=="php")throw Error(`packaging: 'image' currently supports PHP and managed Node runtimes. ${N.kind}${N.kind==="node"?` ${N.version}`:""} uses a custom runtime — `+"use the default zip packaging (the runtime layer is built + attached automatically).");if(O){p("Building + pushing container image");let{buildAndPushServerlessImage:y}=await import("./chunk-gg6vwdnn.js"),A=await y({app:l,projectRoot:h,region:m,repository:`${d}-${s}`,skipBuild:o.skipBuild,onStep:(D)=>e(` ${D}`)});V=A.handlers,I={kind:"image",imageUri:A.imageUri},k=A.tag,M.push({ParameterKey:"ImageUri",ParameterValue:A.imageUri})}else{p("Packaging application");let y=P?Ca({projectRoot:h,app:l,skipBuild:o.skipBuild,onStep:(x)=>e(` ${x}`)}):await un({projectRoot:h,app:l,skipBuild:o.skipBuild,onStep:(x)=>e(` ${x}`)}),A=fa(d,s,y.sha256);if(e(`Artifact: ${y.sha256.slice(0,12)} (${(y.zip.length/1024).toFixed(0)} KB)`),V=y.handlers,k=y.sha256,N.usesLayer){let x=N.layerEnvVar?process.env[N.layerEnvVar]:void 0;if(Y=l.layers??(x?[x]:void 0),!Y?.length){let ge=N.layerKind==="php"?"serverless:build-php-layer":N.layerKind==="bun"?"serverless:build-bun-layer":"serverless:build-node-layer";throw Error(`${N.kind} apps on provided.al2023 need a runtime layer. Set environments.<env>.app.layers or the ${N.layerEnvVar} env var (build one with \`cloud ${ge}\`)${N.kind==="node"?", or use a managed Node version (18/20/22)":""}.`)}}if(!await C.bucketExists(S))p(`Creating artifact bucket ${S}`),await C.createBucket(S);if(await C.headObject(S,A).then((x)=>x!==null).catch(()=>!1))e("Artifact already uploaded — reusing");else p("Uploading artifact"),await C.putObject({bucket:S,key:A,body:y.zip,contentType:"application/zip"});I={kind:"zip",bucket:S,key:A},M.push({ParameterKey:"ArtifactBucket",ParameterValue:S},{ParameterKey:"ArtifactKey",ParameterValue:A})}let T=ya({config:t,environment:s,app:l,handlers:V,runtimeLayers:Y}),te=JSON.stringify(T.template),re=["CAPABILITY_NAMED_IAM"],L=await w.describeStacks({stackName:f}).then((y)=>y.Stacks[0]?.StackStatus).catch(()=>{return}),J=L!==void 0;if(L&&/DELETE_IN_PROGRESS/.test(L))p("Waiting for an in-progress stack delete to finish"),await w.waitForStack(f,"stack-delete-complete").catch(()=>{}),J=!1;else if(L&&/(?:ROLLBACK_COMPLETE|REVIEW_IN_PROGRESS|CREATE_FAILED)/.test(L))p(`Deleting unusable stack (status ${L}) before recreate`),await w.deleteStack(f),await w.waitForStack(f,"stack-delete-complete").catch(()=>{}),J=!1;p(J?"Updating infrastructure stack":"Creating infrastructure stack");try{if(J)await w.updateStack({stackName:f,templateBody:te,parameters:M,capabilities:re}),await w.waitForStack(f,"stack-update-complete");else await w.createStack({stackName:f,templateBody:te,parameters:M,capabilities:re,onFailure:"DELETE"}),await w.waitForStack(f,"stack-create-complete")}catch(y){if(/No updates are to be performed/i.test(String(y?.message)))e("No infrastructure changes");else throw y}let Q=await w.getStackOutputs(f).catch(()=>({})),B;if(l.assets){let y=ne(h,l.assets);if(de(y)){let A=l.assetDomain||Q.AssetsCdnDomain;B=A?`https://${A}/${k}`:void 0,p(`Syncing assets from ${l.assets}`);let D=await ve(C,c.assetsBucket,y,k,l.dotFilesAsAssets);e(`Uploaded ${D} asset(s)${B?` → ${B}`:""}`)}else a(`Assets directory not found: ${y}`)}p("Resolving secrets");let _=await Re(l,m);if(l.database?.connection==="aurora-serverless")try{let A=await new K(m).getSecretValue({SecretId:`${d}/${s}/db`}),D=JSON.parse(A.SecretString??"{}");if(D.username)_.DB_USERNAME=D.username;if(D.password)_.DB_PASSWORD=D.password}catch(y){a(`Could not resolve Aurora DB credentials: ${y.message}`)}if(!await C.bucketExists(S))await C.createBucket(S);let H=await G(C,S,d,s),F={},Z=T.queueNames[0],ee=Id(l,Q);if(p("Activating functions"),F.http=ws(l,c,s,"http",_,B,Z,ee),await U(b,T.functionNames.http,F.http,I),F.cli=ws(l,c,s,"cli",_,B,Z,ee),await U(b,T.functionNames.cli,F.cli,I),T.queueNames.length)F.queue=ws(l,c,s,"queue",_,B,Z,ee),await U(b,T.functionNames.queue,F.queue,I);let se=(l.provisionedConcurrency??0)>0,W={};if(se){if(p("Publishing versions + flipping live alias"),W.http=await X(b,T.functionNames.http),W.cli=await X(b,T.functionNames.cli),T.queueNames.length)W.queue=await X(b,T.functionNames.queue)}if(await ae(C,S,d,s,{sha:k,code:I,previousSha:H?.sha,previousCode:H?.code,previousFunctionEnv:H?.functionEnv,...se?{functionVersions:W,previousFunctionVersions:H?.functionVersions}:{},functionEnv:F,functionNames:{http:T.functionNames.http,cli:T.functionNames.cli,...T.queueNames.length?{queue:T.functionNames.queue}:{}},assetUrl:B,timestamp:new Date().toISOString()}),!o.skipDeployHooks&&l.deploy?.length){p("Running deploy hooks");for(let y of l.deploy){e(` deploy: ${y}`);let A=await b.invoke({FunctionName:T.functionNames.cli,InvocationType:"RequestResponse",Payload:{command:y},LogType:"Tail"});if(A.FunctionError)throw r("Deploy hook failed — the new build is ALREADY LIVE."),e(` Roll back with: cloud serverless:rollback --env ${s}`),Error(`Deploy hook failed (${y}): ${A.Payload}`)}}let j=Q.HttpApiEndpoint;if(!o.skipHealthCheck&&j){p("Health check");try{let y=await fetch(j,{method:"GET"});e(`GET ${j} → ${y.status}`)}catch(y){a(`Health check could not reach ${j}: ${y.message}`)}}Se(["Serverless deploy complete","",j?`URL: ${j}`:"",`Stack: ${f}`,`Build: ${k.slice(0,12)}`].filter(Boolean).join(`
|
|
2
|
-
`),"green")}async function
|
|
3
|
-
export{K,yt,Id,
|
|
1
|
+
import{De,ta,Ro,fa,un,Bo,ha,ya,Ca,wa}from"./chunk-nnawqw34.js";import{n,r,a,e,p,i,Se}from"./chunk-tgwx5haz.js";import{u}from"./chunk-qe56mnjc.js";import{v}from"./chunk-x56s9b7f.js";import{R}from"./chunk-fpxb97q5.js";import{g}from"./chunk-kqf19j9m.js";import{existsSync as de,readdirSync as me,readFileSync as pe,statSync as fe}from"node:fs";import{join as ne,relative as ye}from"node:path";class K{client;region;constructor(t="us-east-1",s){this.region=t,this.client=new u(void 0,{profile:s})}async createSecret(t){let s={Name:t.Name};if(t.Description)s.Description=t.Description;if(t.KmsKeyId)s.KmsKeyId=t.KmsKeyId;if(t.SecretBinary)s.SecretBinary=t.SecretBinary;if(t.SecretString)s.SecretString=t.SecretString;if(t.Tags&&t.Tags.length>0)s.Tags=t.Tags;if(t.AddReplicaRegions&&t.AddReplicaRegions.length>0)s.AddReplicaRegions=t.AddReplicaRegions;if(t.ForceOverwriteReplicaSecret!==void 0)s.ForceOverwriteReplicaSecret=t.ForceOverwriteReplicaSecret;s.ClientRequestToken=t.ClientRequestToken||crypto.randomUUID();let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.CreateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId,ReplicationStatus:o.ReplicationStatus}}async updateSecret(t){let s={SecretId:t.SecretId,ClientRequestToken:t.ClientRequestToken||crypto.randomUUID()};if(t.Description)s.Description=t.Description;if(t.KmsKeyId)s.KmsKeyId=t.KmsKeyId;if(t.SecretBinary)s.SecretBinary=t.SecretBinary;if(t.SecretString)s.SecretString=t.SecretString;let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.UpdateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId}}async putSecretValue(t){let s={SecretId:t.SecretId};if(t.SecretBinary)s.SecretBinary=t.SecretBinary;if(t.SecretString)s.SecretString=t.SecretString;if(t.VersionStages&&t.VersionStages.length>0)s.VersionStages=t.VersionStages;s.ClientRequestToken=t.ClientRequestToken||crypto.randomUUID();let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.PutSecretValue","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId,VersionStages:o.VersionStages}}async getSecretValue(t){let s={SecretId:t.SecretId};if(t.VersionId)s.VersionId=t.VersionId;if(t.VersionStage)s.VersionStage=t.VersionStage;let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.GetSecretValue","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId,SecretBinary:o.SecretBinary,SecretString:o.SecretString,VersionStages:o.VersionStages,CreatedDate:o.CreatedDate}}async describeSecret(t){let s={SecretId:t},o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.DescribeSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return this.parseSecret(o)}async listSecrets(t){let s={};if(t?.MaxResults)s.MaxResults=t.MaxResults;if(t?.NextToken)s.NextToken=t.NextToken;if(t?.Filters&&t.Filters.length>0)s.Filters=t.Filters;if(t?.SortOrder)s.SortOrder=t.SortOrder;let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.ListSecrets","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{SecretList:o.SecretList?.map((c)=>this.parseSecret(c)),NextToken:o.NextToken}}async deleteSecret(t){let s={SecretId:t.SecretId};if(t.RecoveryWindowInDays!==void 0)s.RecoveryWindowInDays=t.RecoveryWindowInDays;if(t.ForceDeleteWithoutRecovery!==void 0)s.ForceDeleteWithoutRecovery=t.ForceDeleteWithoutRecovery;let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.DeleteSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,DeletionDate:o.DeletionDate}}async restoreSecret(t){let s={SecretId:t},o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.RestoreSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name}}async rotateSecret(t){let s={SecretId:t.SecretId};if(t.ClientRequestToken)s.ClientRequestToken=t.ClientRequestToken;if(t.RotationLambdaARN)s.RotationLambdaARN=t.RotationLambdaARN;if(t.RotationRules)s.RotationRules=t.RotationRules;if(t.RotateImmediately!==void 0)s.RotateImmediately=t.RotateImmediately;let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.RotateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId}}async cancelRotateSecret(t){let s={SecretId:t},o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.CancelRotateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name}}async getResourcePolicy(t){let s={SecretId:t},o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.GetResourcePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,ResourcePolicy:o.ResourcePolicy}}async putResourcePolicy(t){let s={SecretId:t.SecretId,ResourcePolicy:t.ResourcePolicy};if(t.BlockPublicPolicy!==void 0)s.BlockPublicPolicy=t.BlockPublicPolicy;let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.PutResourcePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name}}async deleteResourcePolicy(t){let s={SecretId:t},o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.DeleteResourcePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name}}async tagResource(t){let s={SecretId:t.SecretId,Tags:t.Tags};await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.TagResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)})}async untagResource(t){let s={SecretId:t.SecretId,TagKeys:t.TagKeys};await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.UntagResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)})}async setString(t,s,o){try{let c=await this.putSecretValue({SecretId:t,SecretString:s});return{ARN:c.ARN,VersionId:c.VersionId}}catch(c){if(c.code==="ResourceNotFoundException"){let l=await this.createSecret({Name:t,SecretString:s,Description:o?.description,KmsKeyId:o?.kmsKeyId,Tags:o?.tags});return{ARN:l.ARN,VersionId:l.VersionId}}throw c}}async setJson(t,s,o){return this.setString(t,JSON.stringify(s),o)}async getString(t){return(await this.getSecretValue({SecretId:t})).SecretString}async getJson(t){let s=await this.getString(t);if(s)return JSON.parse(s);return}async listAll(){let t=[],s;do{let o=await this.listSecrets({NextToken:s});if(o.SecretList)t.push(...o.SecretList);s=o.NextToken}while(s);return t}parseSecret(t){return{ARN:t.ARN,Name:t.Name,Description:t.Description,KmsKeyId:t.KmsKeyId,RotationEnabled:t.RotationEnabled,RotationLambdaARN:t.RotationLambdaARN,RotationRules:t.RotationRules,LastRotatedDate:t.LastRotatedDate,LastChangedDate:t.LastChangedDate,LastAccessedDate:t.LastAccessedDate,DeletedDate:t.DeletedDate,NextRotationDate:t.NextRotationDate,Tags:t.Tags,SecretVersionsToStages:t.SecretVersionsToStages,CreatedDate:t.CreatedDate,PrimaryRegion:t.PrimaryRegion}}}function E(t,s){let o=t.environments?.[s]?.app;if(!o)throw Error(`No serverless app configured for environment '${s}'. Add environments.${s}.app to your config.`);let c=t.project.slug,l=t.environments?.[s]?.region||t.project.region||"us-east-1";return{app:o,slug:c,region:l,stackName:De(t,s),artifactBucket:ta(c,s),assetsBucket:Ro(c,s)}}function yt(t,s){let o=E(t,s),c=`${o.slug}-${s}`;return{region:o.region,slug:o.slug,stackName:o.stackName,functions:{http:`${c}-http`,queue:`${c}-queue`,cli:`${c}-cli`}}}async function q(t,s=8){let o;for(let c=0;c<s;c++)try{return await t()}catch(l){let d=l?.code||l?.name||"",m=String(l?.message||"");if(d==="ResourceConflictException"||/update is in progress|currently in the following state/i.test(m)){o=l,await new Promise((f)=>setTimeout(f,3000));continue}throw l}throw o}var ie=(t,s)=>`releases/${t}/${s}/current.json`;async function G(t,s,o,c){try{return await t.getObjectJson(s,ie(o,c))}catch{return null}}async function ae(t,s,o,c,l){await t.putObjectJson(s,ie(o,c),l)}async function Re(t,s){if(!t.secrets)return{};let o=new K(s),c={},l=Array.isArray(t.secrets)?t.secrets.map((d)=>({envName:d.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),secretId:d})):Object.entries(t.secrets).map(([d,m])=>({envName:d,secretId:m}));if(Array.isArray(t.secrets)){let d=new Map;for(let{envName:f,secretId:S}of l)d.set(f,[...d.get(f)??[],S]);let m=[...d.entries()].filter(([,f])=>f.length>1);if(m.length){let f=m.map(([S,h])=>`${S} ← ${h.join(", ")}`).join("; ");throw Error(`serverless secrets: multiple secrets map to the same env var (${f}). Use the map form { ENV_NAME: 'secret/id' } to disambiguate.`)}}for(let{envName:d,secretId:m}of l){let S=(await o.getSecretValue({SecretId:m})).SecretString??"";try{let h=JSON.parse(S);if(h&&typeof h==="object"&&!Array.isArray(h)){for(let[C,w]of Object.entries(h))c[C]=String(w);continue}}catch{}c[d]=S}return c}function Id(t,s){let o={},c=s.DbProxyEndpoint||s.DbEndpoint;if(c)o.DB_CONNECTION="mysql",o.DB_HOST=c,o.DB_PORT="3306",o.DB_DATABASE=o.DB_DATABASE||"app";if(s.CacheEndpoint){if(o.REDIS_HOST=s.CacheEndpoint,o.REDIS_PORT="6379",t.cache?.driver==="elasticache")o.CACHE_STORE="redis",o.CACHE_DRIVER="redis",o.SESSION_DRIVER="redis"}return o}function Cs(t,s,o,c,l,d,m,f={}){let S=t.kind==="php"?Ca({cacheDriver:t.cache?.driver==="elasticache"?"redis":"dynamodb"}):{};return{TSCLOUD_LAMBDA_MODE:c,TSCLOUD_ENV:o,MAINTENANCE_MODE:"0",...t.octane?{TSCLOUD_OCTANE:"1"}:{},...t.serveAssets?{TSCLOUD_SERVE_ASSETS:"1"}:{},...t.redirectRobotsTxt===!1?{TSCLOUD_REDIRECT_ROBOTS_TXT:"0"}:{},...S,...f,...s.app.cache?.driver!=="elasticache"?{TSCLOUD_CACHE_TABLE:`${s.slug}-${o}-cache`}:{},...m?{TSCLOUD_QUEUE:m,SQS_QUEUE:m}:{},...d?{ASSET_URL:d}:{},...t.env??{},...l}}function he(t){let s=t.slice(t.lastIndexOf(".")).toLowerCase();return{".html":"text/html",".css":"text/css",".js":"text/javascript",".mjs":"text/javascript",".json":"application/json",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".txt":"text/plain",".map":"application/json"}[s]??"application/octet-stream"}function*oe(t){for(let s of me(t)){let o=ne(t,s);if(fe(o).isDirectory())yield*oe(o);else yield o}}async function ve(t,s,o,c,l=!1){let d=0;for(let m of oe(o)){let f=ye(o,m).replace(/\\/g,"/");if(!l&&f.split("/").some((S)=>S.startsWith(".")))continue;await t.putObject({bucket:s,key:`${c}/${f}`,body:pe(m),contentType:he(m),cacheControl:"public, max-age=31536000, immutable"}),d++}return d}function po(t,s){let o=Object.entries(s).reduce((c,[l,d])=>c+Buffer.byteLength(`${l}=${d}`,"utf8"),0);if(o>4096){let c=Object.entries(s).map(([l,d])=>[l,Buffer.byteLength(`${l}=${d}`,"utf8")]).sort((l,d)=>d[1]-l[1]).slice(0,5).map(([l,d])=>`${l} (${d}B)`).join(", ");throw Error(`${t}: environment variables total ${o}B, over AWS's 4096B limit (${o-4096}B too large). Largest: ${c}. Move large/secret values out of env — store them in Secrets Manager and fetch at cold start.`)}}async function U(t,s,o,c){po(s,o),await q(()=>t.updateFunctionConfiguration({FunctionName:s,Environment:{Variables:o}})),await t.waitForFunctionActive(s,120);let l=c.kind==="image"?{FunctionName:s,ImageUri:c.imageUri}:{FunctionName:s,S3Bucket:c.bucket,S3Key:c.key};await q(()=>t.updateFunctionCode(l)),await t.waitForFunctionActive(s,120)}async function X(t,s){let c=(await q(()=>t.publishVersion({FunctionName:s}))).Version;if(!c)throw Error(`publishVersion returned no version for ${s}`);return await q(()=>t.updateAlias({FunctionName:s,Name:"live",FunctionVersion:c})),c}async function up(t,s,o={}){let c=E(t,s),{app:l,slug:d,region:m,stackName:f,artifactBucket:S}=c,h=o.projectRoot??process.cwd();i(`Deploying serverless app: ${d} (${s})`),e(`Stack: ${f}`),e(`Region: ${m}`);let C=new g(m),w=new v(m),b=new R(m),P=l.kind==="php",O=l.packaging==="image",N=Bo(l),V,I,k,Y,M=[];if(O&&N.usesLayer&&N.layerKind!=="php")throw Error(`packaging: 'image' currently supports PHP and managed Node runtimes. ${N.kind}${N.kind==="node"?` ${N.version}`:""} uses a custom runtime — `+"use the default zip packaging (the runtime layer is built + attached automatically).");if(O){p("Building + pushing container image");let{buildAndPushServerlessImage:y}=await import("./chunk-n775dk3f.js"),A=await y({app:l,projectRoot:h,region:m,repository:`${d}-${s}`,skipBuild:o.skipBuild,onStep:(D)=>e(` ${D}`)});V=A.handlers,I={kind:"image",imageUri:A.imageUri},k=A.tag,M.push({ParameterKey:"ImageUri",ParameterValue:A.imageUri})}else{p("Packaging application");let y=P?wa({projectRoot:h,app:l,skipBuild:o.skipBuild,onStep:(x)=>e(` ${x}`)}):await un({projectRoot:h,app:l,skipBuild:o.skipBuild,onStep:(x)=>e(` ${x}`)}),A=fa(d,s,y.sha256);if(e(`Artifact: ${y.sha256.slice(0,12)} (${(y.zip.length/1024).toFixed(0)} KB)`),V=y.handlers,k=y.sha256,N.usesLayer){let x=N.layerEnvVar?process.env[N.layerEnvVar]:void 0;if(Y=l.layers??(x?[x]:void 0),!Y?.length){let ge=N.layerKind==="php"?"serverless:build-php-layer":N.layerKind==="bun"?"serverless:build-bun-layer":"serverless:build-node-layer";throw Error(`${N.kind} apps on provided.al2023 need a runtime layer. Set environments.<env>.app.layers or the ${N.layerEnvVar} env var (build one with \`cloud ${ge}\`)${N.kind==="node"?", or use a managed Node version (18/20/22)":""}.`)}}if(!await C.bucketExists(S))p(`Creating artifact bucket ${S}`),await C.createBucket(S);if(await C.headObject(S,A).then((x)=>x!==null).catch(()=>!1))e("Artifact already uploaded — reusing");else p("Uploading artifact"),await C.putObject({bucket:S,key:A,body:y.zip,contentType:"application/zip"});I={kind:"zip",bucket:S,key:A},M.push({ParameterKey:"ArtifactBucket",ParameterValue:S},{ParameterKey:"ArtifactKey",ParameterValue:A})}let T=ya({config:t,environment:s,app:l,handlers:V,runtimeLayers:Y}),te=JSON.stringify(T.template),re=["CAPABILITY_NAMED_IAM"],L=await w.describeStacks({stackName:f}).then((y)=>y.Stacks[0]?.StackStatus).catch(()=>{return}),J=L!==void 0;if(L&&/DELETE_IN_PROGRESS/.test(L))p("Waiting for an in-progress stack delete to finish"),await w.waitForStack(f,"stack-delete-complete").catch(()=>{}),J=!1;else if(L&&/(?:ROLLBACK_COMPLETE|REVIEW_IN_PROGRESS|CREATE_FAILED)/.test(L))p(`Deleting unusable stack (status ${L}) before recreate`),await w.deleteStack(f),await w.waitForStack(f,"stack-delete-complete").catch(()=>{}),J=!1;p(J?"Updating infrastructure stack":"Creating infrastructure stack");try{if(J)await w.updateStack({stackName:f,templateBody:te,parameters:M,capabilities:re}),await w.waitForStack(f,"stack-update-complete");else await w.createStack({stackName:f,templateBody:te,parameters:M,capabilities:re,onFailure:"DELETE"}),await w.waitForStack(f,"stack-create-complete")}catch(y){if(/No updates are to be performed/i.test(String(y?.message)))e("No infrastructure changes");else throw y}let Q=await w.getStackOutputs(f).catch(()=>({})),B;if(l.assets){let y=ne(h,l.assets);if(de(y)){let A=l.assetDomain||Q.AssetsCdnDomain;B=A?`https://${A}/${k}`:void 0,p(`Syncing assets from ${l.assets}`);let D=await ve(C,c.assetsBucket,y,k,l.dotFilesAsAssets);e(`Uploaded ${D} asset(s)${B?` → ${B}`:""}`)}else a(`Assets directory not found: ${y}`)}p("Resolving secrets");let _=await Re(l,m);if(l.database?.connection==="aurora-serverless")try{let A=await new K(m).getSecretValue({SecretId:`${d}/${s}/db`}),D=JSON.parse(A.SecretString??"{}");if(D.username)_.DB_USERNAME=D.username;if(D.password)_.DB_PASSWORD=D.password}catch(y){a(`Could not resolve Aurora DB credentials: ${y.message}`)}if(!await C.bucketExists(S))await C.createBucket(S);let H=await G(C,S,d,s),F={},Z=T.queueNames[0],ee=Id(l,Q);if(p("Activating functions"),F.http=Cs(l,c,s,"http",_,B,Z,ee),await U(b,T.functionNames.http,F.http,I),F.cli=Cs(l,c,s,"cli",_,B,Z,ee),await U(b,T.functionNames.cli,F.cli,I),T.queueNames.length)F.queue=Cs(l,c,s,"queue",_,B,Z,ee),await U(b,T.functionNames.queue,F.queue,I);let se=(l.provisionedConcurrency??0)>0,W={};if(se){if(p("Publishing versions + flipping live alias"),W.http=await X(b,T.functionNames.http),W.cli=await X(b,T.functionNames.cli),T.queueNames.length)W.queue=await X(b,T.functionNames.queue)}if(await ae(C,S,d,s,{sha:k,code:I,previousSha:H?.sha,previousCode:H?.code,previousFunctionEnv:H?.functionEnv,...se?{functionVersions:W,previousFunctionVersions:H?.functionVersions}:{},functionEnv:F,functionNames:{http:T.functionNames.http,cli:T.functionNames.cli,...T.queueNames.length?{queue:T.functionNames.queue}:{}},assetUrl:B,timestamp:new Date().toISOString()}),!o.skipDeployHooks&&l.deploy?.length){p("Running deploy hooks");for(let y of l.deploy){e(` deploy: ${y}`);let A=await b.invoke({FunctionName:T.functionNames.cli,InvocationType:"RequestResponse",Payload:{command:y},LogType:"Tail"});if(A.FunctionError)throw r("Deploy hook failed — the new build is ALREADY LIVE."),e(` Roll back with: cloud serverless:rollback --env ${s}`),Error(`Deploy hook failed (${y}): ${A.Payload}`)}}let j=Q.HttpApiEndpoint;if(!o.skipHealthCheck&&j){p("Health check");try{let y=await fetch(j,{method:"GET"});e(`GET ${j} → ${y.status}`)}catch(y){a(`Health check could not reach ${j}: ${y.message}`)}}Se(["Serverless deploy complete","",j?`URL: ${j}`:"",`Stack: ${f}`,`Build: ${k.slice(0,12)}`].filter(Boolean).join(`
|
|
2
|
+
`),"green")}async function ws(t,s){let o=E(t,s),c=new g(o.region),l=new R(o.region),d=await G(c,o.artifactBucket,o.slug,s);if(!d)throw Error("No previous release to redeploy. Run a full deploy first.");i(`Redeploying ${o.slug} (${s}) — build ${d.sha.slice(0,12)}`);for(let[m,f]of Object.entries(d.functionNames)){if(!f)continue;p(`Re-activating ${m} (${f})`),await U(l,f,d.functionEnv[m]??{},d.code);let S=d.functionVersions?.[m];if(S)await q(()=>l.updateAlias({FunctionName:f,Name:"live",FunctionVersion:S}))}n("Redeploy complete")}async function As(t,s){let o=E(t,s),c=new g(o.region),l=new R(o.region),d=await G(c,o.artifactBucket,o.slug,s);if(!d?.previousCode)throw Error("No previous release to roll back to.");i(`Rolling back ${o.slug} (${s}) → ${d.previousSha?.slice(0,12)}`);for(let[m,f]of Object.entries(d.functionNames)){if(!f)continue;p(`Restoring ${m} (${f})`);let S=d.previousFunctionEnv?.[m]??d.functionEnv[m]??{};await U(l,f,S,d.previousCode);let h=d.previousFunctionVersions?.[m];if(h)await q(()=>l.updateAlias({FunctionName:f,Name:"live",FunctionVersion:h}))}await ae(c,o.artifactBucket,o.slug,s,{...d,sha:d.previousSha??d.sha,code:d.previousCode,functionEnv:d.previousFunctionEnv??d.functionEnv,functionVersions:d.previousFunctionVersions??d.functionVersions,previousSha:void 0,previousCode:void 0,previousFunctionEnv:void 0,previousFunctionVersions:void 0,timestamp:new Date().toISOString()}),n("Rollback complete")}async function mo(t,s,o,c){let l=E(t,s),d=new R(l.region),m=`${l.slug}-${s}-http`,S={...(await d.getFunction(m)).Configuration?.Environment?.Variables??{}};if(S.MAINTENANCE_MODE=o?"1":"0",o&&c)S.MAINTENANCE_BYPASS_SECRET=c;if(!o)delete S.MAINTENANCE_BYPASS_SECRET;if(await q(()=>d.updateFunctionConfiguration({FunctionName:m,Environment:{Variables:S}})),(l.app.provisionedConcurrency??0)>0)await d.waitForFunctionActive(m,120),await X(d,m);n(o?"Application is now in maintenance mode (503)":"Application is live")}async function Mt(t,s,o){let c=E(t,s),l=new R(c.region),d=`${c.slug}-${s}-cli`,m=await l.invoke({FunctionName:d,InvocationType:"RequestResponse",Payload:{command:o},LogType:"Tail"});if(m.FunctionError)throw Error(`Command failed: ${m.Payload}`);return m.Payload??""}var ce=(t,s)=>`commands/${t}/${s}/history.json`,Ne=50;async function le(t,s,o,c){try{return(await t.getObjectJson(s,ce(o,c)))?.records??[]}catch{return[]}}async function pp(t,s,o){let c=E(t,s),l=new R(c.region),d=`${c.slug}-${s}-cli`,m=await l.invoke({FunctionName:d,InvocationType:"RequestResponse",Payload:{command:o},LogType:"Tail"}),f=m.Payload??"",S=m.FunctionError?"error":"ok",h=-1;try{let C=new g(c.region);if(await C.bucketExists(c.artifactBucket)){let w=await le(C,c.artifactBucket,c.slug,s);h=w.reduce((b,P)=>Math.max(b,P.id),0)+1,w.push({id:h,command:o,timestamp:new Date().toISOString(),status:S,output:f.slice(0,4000)}),await C.putObjectJson(c.artifactBucket,ce(c.slug,s),{records:w.slice(-Ne)})}}catch{}if(m.FunctionError)throw Error(`Command failed${h>0?` (#${h})`:""}: ${f}`);return{id:h,status:S,output:f}}async function Rd(t,s){let o=E(t,s),c=new g(o.region);return le(c,o.artifactBucket,o.slug,s)}async function mp(t,s,o){let c=await Rd(t,s);if(!c.length)return;return o==null?c[c.length-1]:c.find((l)=>l.id===o)}async function gp(t,s,o){let c=Buffer.from(o,"utf-8").toString("base64");return Mt(t,s,`tscloud:db-query --sql-base64=${c}`)}async function z(t,s){let o=E(t,s),c=new v(o.region),l=new R(o.region),d=new g(o.region),m="not deployed",f={};try{let{Stacks:O}=await c.describeStacks({stackName:o.stackName});m=O?.[0]?.StackStatus??m;for(let N of O?.[0]?.Outputs??[])if(N.OutputKey)f[N.OutputKey]=N.OutputValue??""}catch{}let S=ha(o.app,o.slug,s),h=o.app.provisionedConcurrency??0,C=["http","cli",...S.length?["queue"]:[]],w=`${o.slug}-${s}`,b=[];for(let O of C){let N=`${w}-${O}`,V={mode:O,name:N,version:"$LATEST"};if(h>0){let I=await l.getAlias(N,"live").catch(()=>null);if(I?.FunctionVersion){V.version=I.FunctionVersion;let k=await l.getProvisionedConcurrencyConfig(N,"live").catch(()=>null);if(k)V.provisioned={status:k.Status??"-",allocated:k.AllocatedProvisionedConcurrentExecutions??0,requested:k.RequestedProvisionedConcurrentExecutions??0}}}b.push(V)}let P=await G(d,o.artifactBucket,o.slug,s).catch(()=>null);return{slug:o.slug,environment:s,region:o.region,stackStatus:m,endpoint:f.HttpApiEndpoint,assetUrl:P?.assetUrl,scheduler:o.app.scheduler??"on",queues:S,provisionedConcurrency:h,functions:b,lastRelease:P?{sha:P.sha,timestamp:P.timestamp}:void 0}}function ue(t,s){return`${t}-${s}-db`}async function Is(t,s,o,c){let l=E(t,s);if(l.app.database?.connection!=="aurora-serverless")throw Error("No Aurora Serverless v2 database is configured for this environment.");let{RDSClient:d}=await import("./chunk-pt71fyem.js"),m=new d(l.region),f=ue(l.slug,s);p(`Scaling ${f} → ${o}–${c} ACUs`),await m.modifyDBCluster({DBClusterIdentifier:f,ServerlessV2ScalingConfiguration:{MinCapacity:o,MaxCapacity:c},ApplyImmediately:!0}),n(`Scaling applied to ${f} (takes effect shortly).`)}async function fp(t,s,o){let c=E(t,s);if(c.app.database?.connection!=="aurora-serverless")throw Error("No Aurora Serverless v2 database is configured for this environment.");if(!o.toTime&&!o.latest)throw Error("Specify a restore point: --to <ISO timestamp> or --latest.");let{RDSClient:l}=await import("./chunk-pt71fyem.js"),d=new l(c.region),m=ue(c.slug,s),f=o.latest?"latest":o.toTime.toISOString().replace(/[^0-9]/g,"").slice(0,14),S=o.target??`${m}-restore-${f}`;p(`Restoring ${m} → new cluster ${S} (${o.latest?"latest restorable time":o.toTime.toISOString()})`),await d.restoreDBClusterToPointInTime({DBClusterIdentifier:S,SourceDBClusterIdentifier:m,RestoreToTime:o.toTime,UseLatestRestorableTime:o.latest}),p("Waiting for the restored cluster to be ready");for(let h=0;h<120;h++){let{DBClusters:C}=await d.describeDBClusters({DBClusterIdentifier:S}),w=C?.[0]?.Status;if(w&&w!=="creating")break;await new Promise((b)=>setTimeout(b,15000))}return p("Adding a writer instance"),await d.createDBInstance({DBInstanceIdentifier:`${S}-1`,DBClusterIdentifier:S,Engine:"aurora-mysql",DBInstanceClass:"db.serverless"}),n(`Restore complete → cluster ${S} with writer ${S}-1. Point an env's database at it once available.`),S}
|
|
3
|
+
export{K,yt,Id,Cs,po,up,ws,As,mo,Mt,pp,Rd,mp,gp,z,Is,fp};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Wn}from"./chunk-zk3nm0td.js";import"./chunk-tg45thhb.js";import"./chunk-f7dtn45y.js";import"./chunk-fpxb97q5.js";import"./chunk-tgwx5haz.js";import"./chunk-x56s9b7f.js";import"./chunk-kqf19j9m.js";import"./chunk-qe56mnjc.js";import"./chunk-nnawqw34.js";export{Wn as resolveDashboardData};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{u}from"./chunk-q9tvzcr7.js";import{deflateRawSync as y}from"zlib";function d(n,e){let t=typeof e==="string"?Buffer.from(e,"utf-8"):e,i=y(t),r=f(t),s=new Date,l=(s.getHours()<<11|s.getMinutes()<<5|s.getSeconds()>>1)&65535,c=(s.getFullYear()-1980<<9|s.getMonth()+1<<5|s.getDate())&65535,m=Buffer.from(n,"utf-8"),a=Buffer.alloc(30+m.length);a.writeUInt32LE(67324752,0),a.writeUInt16LE(20,4),a.writeUInt16LE(0,6),a.writeUInt16LE(8,8),a.writeUInt16LE(l,10),a.writeUInt16LE(c,12),a.writeUInt32LE(r,14),a.writeUInt32LE(i.length,18),a.writeUInt32LE(t.length,22),a.writeUInt16LE(m.length,26),a.writeUInt16LE(0,28),m.copy(a,30);let o=Buffer.alloc(46+m.length);o.writeUInt32LE(33639248,0),o.writeUInt16LE(20,4),o.writeUInt16LE(20,6),o.writeUInt16LE(0,8),o.writeUInt16LE(8,10),o.writeUInt16LE(l,12),o.writeUInt16LE(c,14),o.writeUInt32LE(r,16),o.writeUInt32LE(i.length,20),o.writeUInt32LE(t.length,24),o.writeUInt16LE(m.length,28),o.writeUInt16LE(0,30),o.writeUInt16LE(0,32),o.writeUInt16LE(0,34),o.writeUInt16LE(0,36),o.writeUInt32LE(0,38),o.writeUInt32LE(0,42),m.copy(o,46);let p=a.length+i.length,h=o.length,g=Buffer.alloc(22);return g.writeUInt32LE(101010256,0),g.writeUInt16LE(0,4),g.writeUInt16LE(0,6),g.writeUInt16LE(1,8),g.writeUInt16LE(1,10),g.writeUInt32LE(h,12),g.writeUInt32LE(p,16),g.writeUInt16LE(0,20),Buffer.concat([a,i,o,g])}function f(n){let e=[];for(let i=0;i<256;i++){let r=i;for(let s=0;s<8;s++)r=r&1?3988292384^r>>>1:r>>>1;e[i]=r}let t=4294967295;for(let i=0;i<n.length;i++)t=e[(t^n[i])&255]^t>>>8;return(t^4294967295)>>>0}class R{client;region;constructor(n="us-east-1",e){this.region=n,this.client=new u(void 0,{profile:e})}async createFunction(n){return await this.client.request({service:"lambda",region:this.region,method:"POST",path:"/2015-03-31/functions",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})}async getFunction(n){return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2015-03-31/functions/${encodeURIComponent(n)}`,headers:{"Content-Type":"application/json"}})}async updateFunctionCode(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/code`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async updateFunctionCodeInline(n,e,t="index.js"){let i=d(t,e);return this.updateFunctionCode({FunctionName:n,ZipFile:i.toString("base64")})}async updateFunctionConfiguration(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/configuration`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async deleteFunction(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2015-03-31/functions/${encodeURIComponent(n)}`,headers:{"Content-Type":"application/json"}})}async invoke(n){let{FunctionName:e,InvocationType:t="RequestResponse",Payload:i,LogType:r}=n,s={"Content-Type":"application/json","X-Amz-Invocation-Type":t};if(r)s["X-Amz-Log-Type"]=r;let l=i?typeof i==="string"?i:JSON.stringify(i):void 0,c=await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/invocations`,headers:s,body:l,returnHeaders:!0});return{StatusCode:c.statusCode||200,FunctionError:c.headers?.["x-amz-function-error"],LogResult:c.headers?.["x-amz-log-result"],Payload:typeof c.body==="string"?c.body:JSON.stringify(c.body),ExecutedVersion:c.headers?.["x-amz-executed-version"]}}async listFunctions(n){let e={};if(n?.MaxItems)e.MaxItems=String(n.MaxItems);if(n?.Marker)e.Marker=n.Marker;if(n?.FunctionVersion)e.FunctionVersion=n.FunctionVersion;return await this.client.request({service:"lambda",region:this.region,method:"GET",path:"/2015-03-31/functions",queryParams:Object.keys(e).length>0?e:void 0,headers:{"Content-Type":"application/json"}})}async addPermission(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/policy`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async removePermission(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2015-03-31/functions/${encodeURIComponent(n)}/policy/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async publishVersion(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/versions`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async createAlias(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/aliases`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async updateAlias(n){let{FunctionName:e,Name:t,...i}=n;return this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/aliases/${encodeURIComponent(t)}`,headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}async getAlias(n,e){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2015-03-31/functions/${encodeURIComponent(n)}/aliases/${encodeURIComponent(e)}`})}catch(t){if(/ResourceNotFound/i.test(String(t?.message)))return null;throw t}}async getProvisionedConcurrencyConfig(n,e){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2019-09-30/functions/${encodeURIComponent(n)}/provisioned-concurrency`,queryParams:{Qualifier:e}})}catch(t){if(/ProvisionedConcurrencyConfigNotFound|ResourceNotFound/i.test(String(t?.message)))return null;throw t}}async putProvisionedConcurrencyConfig(n){let{FunctionName:e,Qualifier:t,ProvisionedConcurrentExecutions:i}=n;return this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2019-09-30/functions/${encodeURIComponent(e)}/provisioned-concurrency`,queryParams:{Qualifier:t},headers:{"Content-Type":"application/json"},body:JSON.stringify({ProvisionedConcurrentExecutions:i})})}async getFunctionConcurrency(n){try{return(await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`}))?.ReservedConcurrentExecutions??null}catch(e){if(/ResourceNotFound|ProvisionedConcurrencyConfigNotFound/i.test(String(e?.message)))return null;throw e}}async putFunctionConcurrency(n,e){await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`,headers:{"Content-Type":"application/json"},body:JSON.stringify({ReservedConcurrentExecutions:e})})}async deleteFunctionConcurrency(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`})}async deleteProvisionedConcurrencyConfig(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2019-09-30/functions/${encodeURIComponent(n)}/provisioned-concurrency`,queryParams:{Qualifier:e}})}async waitForFunctionActive(n,e=60){let t=Date.now(),i=e*1000;while(Date.now()-t<i)try{let r=await this.getFunction(n),s=r.Configuration?.State;if(s==="Active")return r.Configuration;if(s==="Failed")throw Error(`Function ${n} failed: ${r.Configuration?.StateReason}`);await new Promise((l)=>setTimeout(l,2000))}catch(r){if(r.code==="ResourceNotFoundException"){await new Promise((s)=>setTimeout(s,2000));continue}throw r}throw Error(`Timeout waiting for function ${n} to become active`)}async functionExists(n){try{return await this.getFunction(n),!0}catch(e){if(e.code==="ResourceNotFoundException"||e.statusCode===404)return!1;throw e}}async createFunctionUrl(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2021-10-31/functions/${encodeURIComponent(e)}/url`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async getFunctionUrl(n){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2021-10-31/functions/${encodeURIComponent(n)}/url`,headers:{"Content-Type":"application/json"}})}catch(e){if(e.statusCode===404)return null;throw e}}async deleteFunctionUrl(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2021-10-31/functions/${encodeURIComponent(n)}/url`,headers:{"Content-Type":"application/json"}})}async createFunctionWithCode(n){let{Code:e,Filename:t="index.js",...i}=n,r=d(t,e);return this.createFunction({...i,Code:{ZipFile:r.toString("base64")}})}async addFunctionUrlPermission(n){return this.addPermission({FunctionName:n,StatementId:"FunctionURLAllowPublicAccess",Action:"lambda:InvokeFunctionUrl",Principal:"*",FunctionUrlAuthType:"NONE"})}async publishLayerVersion(n){let{LayerName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2018-10-31/layers/${encodeURIComponent(e)}/versions`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async listLayerVersions(n,e){let t={};if(e?.CompatibleRuntime)t.CompatibleRuntime=e.CompatibleRuntime;if(e?.CompatibleArchitecture)t.CompatibleArchitecture=e.CompatibleArchitecture;if(e?.MaxItems)t.MaxItems=String(e.MaxItems);if(e?.Marker)t.Marker=e.Marker;return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions`,queryParams:Object.keys(t).length>0?t:void 0,headers:{"Content-Type":"application/json"}})}async getLayerVersion(n,e){return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions/${e}`,headers:{"Content-Type":"application/json"}})}async addLayerVersionPermission(n){let{LayerName:e,VersionNumber:t,...i}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2018-10-31/layers/${encodeURIComponent(e)}/versions/${t}/policy`,headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}async deleteLayerVersion(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions/${e}`,headers:{"Content-Type":"application/json"}})}}
|
|
1
|
+
import{u}from"./chunk-qe56mnjc.js";import{deflateRawSync as y}from"zlib";function d(n,e){let t=typeof e==="string"?Buffer.from(e,"utf-8"):e,i=y(t),r=f(t),s=new Date,l=(s.getHours()<<11|s.getMinutes()<<5|s.getSeconds()>>1)&65535,c=(s.getFullYear()-1980<<9|s.getMonth()+1<<5|s.getDate())&65535,m=Buffer.from(n,"utf-8"),a=Buffer.alloc(30+m.length);a.writeUInt32LE(67324752,0),a.writeUInt16LE(20,4),a.writeUInt16LE(0,6),a.writeUInt16LE(8,8),a.writeUInt16LE(l,10),a.writeUInt16LE(c,12),a.writeUInt32LE(r,14),a.writeUInt32LE(i.length,18),a.writeUInt32LE(t.length,22),a.writeUInt16LE(m.length,26),a.writeUInt16LE(0,28),m.copy(a,30);let o=Buffer.alloc(46+m.length);o.writeUInt32LE(33639248,0),o.writeUInt16LE(20,4),o.writeUInt16LE(20,6),o.writeUInt16LE(0,8),o.writeUInt16LE(8,10),o.writeUInt16LE(l,12),o.writeUInt16LE(c,14),o.writeUInt32LE(r,16),o.writeUInt32LE(i.length,20),o.writeUInt32LE(t.length,24),o.writeUInt16LE(m.length,28),o.writeUInt16LE(0,30),o.writeUInt16LE(0,32),o.writeUInt16LE(0,34),o.writeUInt16LE(0,36),o.writeUInt32LE(0,38),o.writeUInt32LE(0,42),m.copy(o,46);let p=a.length+i.length,h=o.length,g=Buffer.alloc(22);return g.writeUInt32LE(101010256,0),g.writeUInt16LE(0,4),g.writeUInt16LE(0,6),g.writeUInt16LE(1,8),g.writeUInt16LE(1,10),g.writeUInt32LE(h,12),g.writeUInt32LE(p,16),g.writeUInt16LE(0,20),Buffer.concat([a,i,o,g])}function f(n){let e=[];for(let i=0;i<256;i++){let r=i;for(let s=0;s<8;s++)r=r&1?3988292384^r>>>1:r>>>1;e[i]=r}let t=4294967295;for(let i=0;i<n.length;i++)t=e[(t^n[i])&255]^t>>>8;return(t^4294967295)>>>0}class R{client;region;constructor(n="us-east-1",e){this.region=n,this.client=new u(void 0,{profile:e})}async createFunction(n){return await this.client.request({service:"lambda",region:this.region,method:"POST",path:"/2015-03-31/functions",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})}async getFunction(n){return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2015-03-31/functions/${encodeURIComponent(n)}`,headers:{"Content-Type":"application/json"}})}async updateFunctionCode(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/code`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async updateFunctionCodeInline(n,e,t="index.js"){let i=d(t,e);return this.updateFunctionCode({FunctionName:n,ZipFile:i.toString("base64")})}async updateFunctionConfiguration(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/configuration`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async deleteFunction(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2015-03-31/functions/${encodeURIComponent(n)}`,headers:{"Content-Type":"application/json"}})}async invoke(n){let{FunctionName:e,InvocationType:t="RequestResponse",Payload:i,LogType:r}=n,s={"Content-Type":"application/json","X-Amz-Invocation-Type":t};if(r)s["X-Amz-Log-Type"]=r;let l=i?typeof i==="string"?i:JSON.stringify(i):void 0,c=await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/invocations`,headers:s,body:l,returnHeaders:!0});return{StatusCode:c.statusCode||200,FunctionError:c.headers?.["x-amz-function-error"],LogResult:c.headers?.["x-amz-log-result"],Payload:typeof c.body==="string"?c.body:JSON.stringify(c.body),ExecutedVersion:c.headers?.["x-amz-executed-version"]}}async listFunctions(n){let e={};if(n?.MaxItems)e.MaxItems=String(n.MaxItems);if(n?.Marker)e.Marker=n.Marker;if(n?.FunctionVersion)e.FunctionVersion=n.FunctionVersion;return await this.client.request({service:"lambda",region:this.region,method:"GET",path:"/2015-03-31/functions",queryParams:Object.keys(e).length>0?e:void 0,headers:{"Content-Type":"application/json"}})}async addPermission(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/policy`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async removePermission(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2015-03-31/functions/${encodeURIComponent(n)}/policy/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async publishVersion(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/versions`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async createAlias(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/aliases`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async updateAlias(n){let{FunctionName:e,Name:t,...i}=n;return this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/aliases/${encodeURIComponent(t)}`,headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}async getAlias(n,e){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2015-03-31/functions/${encodeURIComponent(n)}/aliases/${encodeURIComponent(e)}`})}catch(t){if(/ResourceNotFound/i.test(String(t?.message)))return null;throw t}}async getProvisionedConcurrencyConfig(n,e){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2019-09-30/functions/${encodeURIComponent(n)}/provisioned-concurrency`,queryParams:{Qualifier:e}})}catch(t){if(/ProvisionedConcurrencyConfigNotFound|ResourceNotFound/i.test(String(t?.message)))return null;throw t}}async putProvisionedConcurrencyConfig(n){let{FunctionName:e,Qualifier:t,ProvisionedConcurrentExecutions:i}=n;return this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2019-09-30/functions/${encodeURIComponent(e)}/provisioned-concurrency`,queryParams:{Qualifier:t},headers:{"Content-Type":"application/json"},body:JSON.stringify({ProvisionedConcurrentExecutions:i})})}async getFunctionConcurrency(n){try{return(await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`}))?.ReservedConcurrentExecutions??null}catch(e){if(/ResourceNotFound|ProvisionedConcurrencyConfigNotFound/i.test(String(e?.message)))return null;throw e}}async putFunctionConcurrency(n,e){await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`,headers:{"Content-Type":"application/json"},body:JSON.stringify({ReservedConcurrentExecutions:e})})}async deleteFunctionConcurrency(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`})}async deleteProvisionedConcurrencyConfig(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2019-09-30/functions/${encodeURIComponent(n)}/provisioned-concurrency`,queryParams:{Qualifier:e}})}async waitForFunctionActive(n,e=60){let t=Date.now(),i=e*1000;while(Date.now()-t<i)try{let r=await this.getFunction(n),s=r.Configuration?.State;if(s==="Active")return r.Configuration;if(s==="Failed")throw Error(`Function ${n} failed: ${r.Configuration?.StateReason}`);await new Promise((l)=>setTimeout(l,2000))}catch(r){if(r.code==="ResourceNotFoundException"){await new Promise((s)=>setTimeout(s,2000));continue}throw r}throw Error(`Timeout waiting for function ${n} to become active`)}async functionExists(n){try{return await this.getFunction(n),!0}catch(e){if(e.code==="ResourceNotFoundException"||e.statusCode===404)return!1;throw e}}async createFunctionUrl(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2021-10-31/functions/${encodeURIComponent(e)}/url`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async getFunctionUrl(n){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2021-10-31/functions/${encodeURIComponent(n)}/url`,headers:{"Content-Type":"application/json"}})}catch(e){if(e.statusCode===404)return null;throw e}}async deleteFunctionUrl(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2021-10-31/functions/${encodeURIComponent(n)}/url`,headers:{"Content-Type":"application/json"}})}async createFunctionWithCode(n){let{Code:e,Filename:t="index.js",...i}=n,r=d(t,e);return this.createFunction({...i,Code:{ZipFile:r.toString("base64")}})}async addFunctionUrlPermission(n){return this.addPermission({FunctionName:n,StatementId:"FunctionURLAllowPublicAccess",Action:"lambda:InvokeFunctionUrl",Principal:"*",FunctionUrlAuthType:"NONE"})}async publishLayerVersion(n){let{LayerName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2018-10-31/layers/${encodeURIComponent(e)}/versions`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async listLayerVersions(n,e){let t={};if(e?.CompatibleRuntime)t.CompatibleRuntime=e.CompatibleRuntime;if(e?.CompatibleArchitecture)t.CompatibleArchitecture=e.CompatibleArchitecture;if(e?.MaxItems)t.MaxItems=String(e.MaxItems);if(e?.Marker)t.Marker=e.Marker;return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions`,queryParams:Object.keys(t).length>0?t:void 0,headers:{"Content-Type":"application/json"}})}async getLayerVersion(n,e){return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions/${e}`,headers:{"Content-Type":"application/json"}})}async addLayerVersionPermission(n){let{LayerName:e,VersionNumber:t,...i}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2018-10-31/layers/${encodeURIComponent(e)}/versions/${t}/policy`,headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}async deleteLayerVersion(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions/${e}`,headers:{"Content-Type":"application/json"}})}}
|
|
2
2
|
export{R};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{V}from"./chunk-tg45thhb.js";import"./chunk-qe56mnjc.js";export{V as SQSClient};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{te,h}from"./chunk-jeg6vw5v.js";import{eo}from"./chunk-573red0g.js";var Ju=["edge.requests","edge.egress_gb","function.invocations","function.gb_seconds","build.minutes","compute.instance_hours","storage.gb_hours","object.egress_gb","object.requests","database.gb_hours","database.io_requests","telemetry.ingest_gb","image.transformations"],Qr={"edge.requests":{key:"edge.requests",unit:"requests",label:"Edge requests",precision:0},"edge.egress_gb":{key:"edge.egress_gb",unit:"gb",label:"Edge egress",precision:3},"function.invocations":{key:"function.invocations",unit:"invocations",label:"Function invocations",precision:0},"function.gb_seconds":{key:"function.gb_seconds",unit:"gb_seconds",label:"Function compute",precision:2},"build.minutes":{key:"build.minutes",unit:"minutes",label:"Build minutes",precision:2},"compute.instance_hours":{key:"compute.instance_hours",unit:"hours",label:"Instance hours",precision:2},"storage.gb_hours":{key:"storage.gb_hours",unit:"gb_hours",label:"Block storage",precision:2},"object.egress_gb":{key:"object.egress_gb",unit:"gb",label:"Object storage egress",precision:3},"object.requests":{key:"object.requests",unit:"requests",label:"Object storage requests",precision:0},"database.gb_hours":{key:"database.gb_hours",unit:"gb_hours",label:"Database storage",precision:2},"database.io_requests":{key:"database.io_requests",unit:"requests",label:"Database I/O",precision:0},"telemetry.ingest_gb":{key:"telemetry.ingest_gb",unit:"gb",label:"Telemetry ingest",precision:3},"image.transformations":{key:"image.transformations",unit:"count",label:"Image transformations",precision:0}},qi=["notify","block_builds","block_deployments","throttle_requests","suspend_functions","serve_static","suspend_project"],oe={notify:0,block_builds:1,block_deployments:2,throttle_requests:3,suspend_functions:4,serve_static:5,suspend_project:6};var Xu=1e6;function tr(e){if(e.tiers&&e.tiers.length>0)return e.tiers;return[{upToQuantity:null,microCentsPerUnit:e.microCentsPerUnit??0}]}function ja(e,t){if(!(e>0))return 0;let r=[...t].sort((s,a)=>{if(s.upToQuantity===null)return 1;if(a.upToQuantity===null)return-1;return s.upToQuantity-a.upToQuantity}),n=e,o=0,i=0;for(let s of r){if(n<=0)break;let d=(s.upToQuantity===null?1/0:s.upToQuantity)-o;if(d<=0)continue;let c=Math.min(n,d);i+=c*s.microCentsPerUnit,n-=c,o+=c}if(n>0){let s=r.reduce((a,d)=>Math.max(a,d.microCentsPerUnit),0);i+=n*s}return i}function id(e,t,r,n){let o=e.entries.filter((a)=>a.meter===t);if(o.length===0)return;let i=o.filter((a)=>a.provider===r),s=i.length>0?i:o.filter((a)=>a.provider==="*");return s.find((a)=>a.region===n)??s.find((a)=>a.region==null)}function is(e,t,r=0){let n=id(e,t.meter,t.provider,t.region),o=Math.max(0,t.quantity);if(!n)return{meter:t.meter,provider:t.provider??"unknown",region:t.region,quantity:o,includedQuantity:0,billableQuantity:o,costCents:0,unpriced:!0};let i=Math.max(0,n.includedQuantity??0),s=Math.max(0,r-i),a=Math.max(0,i-Math.max(0,r)),d=Math.min(o,a),c=o-d,u=tr(n),p=ja(s+c,u)-ja(s,u);return{meter:t.meter,provider:n.provider,region:n.region??t.region,quantity:o,includedQuantity:d,billableQuantity:c,costCents:p/1e6,unpriced:!1}}function Qu(e,t){let r=new Map,n=[];for(let o of t){let i=`${o.meter}\x00${o.provider??""}\x00${o.region??""}`,s=r.get(i)??0,a=is(e,o,s);r.set(i,s+a.quantity),n.push(a)}return{currency:e.currency,totalCents:n.reduce((o,i)=>o+i.costCents,0),lines:n,unpricedMeters:[...new Set(n.filter((o)=>o.unpriced).map((o)=>String(o.meter)))]}}function Yu(e){return Math.round(e*100)/100}function Zu(e,...t){let r=new Map,n=(i)=>`${i.meter}\x00${i.provider}\x00${i.region??""}`;for(let i of e.entries)r.set(n(i),i);let o=e.currency;for(let i of t){o=i.currency||o;for(let s of i.entries)r.set(n(s),s)}return{currency:o,entries:[...r.values()]}}var V=(e)=>Math.round(e*1e6),N=(e)=>Math.round(e*1e6),Va={currency:"USD",entries:[{meter:"edge.requests",provider:"aws",microCentsPerUnit:N(0.00075)},{meter:"edge.egress_gb",provider:"aws",includedQuantity:100,tiers:[{upToQuantity:10240,microCentsPerUnit:V(8.5)},{upToQuantity:51200,microCentsPerUnit:V(8)},{upToQuantity:null,microCentsPerUnit:V(6)}]},{meter:"function.invocations",provider:"aws",includedQuantity:1e6,microCentsPerUnit:N(0.002)},{meter:"function.gb_seconds",provider:"aws",includedQuantity:400000,microCentsPerUnit:N(0.00166667)},{meter:"storage.gb_hours",provider:"aws",microCentsPerUnit:N(0.010958904109589041)},{meter:"object.egress_gb",provider:"aws",includedQuantity:100,microCentsPerUnit:V(9)},{meter:"object.requests",provider:"aws",microCentsPerUnit:N(0.000039999999999999996)},{meter:"database.gb_hours",provider:"aws",microCentsPerUnit:N(0.015753424657534248)},{meter:"compute.instance_hours",provider:"aws",microCentsPerUnit:N(4.16)},{meter:"edge.egress_gb",provider:"hetzner",includedQuantity:20480,microCentsPerUnit:V(0.108)},{meter:"object.egress_gb",provider:"hetzner",includedQuantity:1024,microCentsPerUnit:V(0.108)},{meter:"compute.instance_hours",provider:"hetzner",microCentsPerUnit:N(0.95)},{meter:"storage.gb_hours",provider:"hetzner",microCentsPerUnit:N(0.006027397260273972)},{meter:"edge.requests",provider:"hetzner",microCentsPerUnit:0},{meter:"edge.requests",provider:"local",microCentsPerUnit:0},{meter:"edge.egress_gb",provider:"local",microCentsPerUnit:0},{meter:"function.invocations",provider:"local",microCentsPerUnit:0},{meter:"function.gb_seconds",provider:"local",microCentsPerUnit:0},{meter:"build.minutes",provider:"*",includedQuantity:6000,microCentsPerUnit:N(0.8)},{meter:"telemetry.ingest_gb",provider:"*",includedQuantity:5,microCentsPerUnit:V(50)},{meter:"image.transformations",provider:"*",includedQuantity:5000,microCentsPerUnit:N(0.05)}]};var tt=new Map;function rt(e){let t=tt.get(e);if(!t)t=new Intl.DateTimeFormat("en-US",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",weekday:"short",hourCycle:"h23"}),tt.set(e,t);return t}var rr={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6};function Wi(e){try{return rt(e),!0}catch{return!1}}function os(e,t){let r=rt(t).formatToParts(e),n=(o)=>r.find((i)=>i.type===o)?.value??"0";return{year:Number(n("year")),month:Number(n("month")),day:Number(n("day")),hour:Number(n("hour")),minute:Number(n("minute")),second:Number(n("second")),weekday:rr[n("weekday")]??0}}function za(e,t){let r=os(e,t);return Date.UTC(r.year,r.month-1,r.day,r.hour,r.minute,r.second)-Math.floor(e.getTime()/1000)*1000}function Yr(e,t,r,n,o=0){let i=Date.UTC(t,r-1,n,o),s=new Date(i-za(new Date(i),e));return new Date(i-za(s,e))}function nr(e,t){return new Date(Date.UTC(e,t-1,1)).toLocaleString("en-US",{month:"long",year:"numeric",timeZone:"UTC"})}function gr(e,t,r=new Date){let n=Wi(t)?t:"UTC",o=os(r,n),i,s,a;if(e==="daily")i=Yr(n,o.year,o.month,o.day),s=Yr(n,o.year,o.month,o.day+1),a=`${o.year}-${String(o.month).padStart(2,"0")}-${String(o.day).padStart(2,"0")}`;else if(e==="weekly"){let u=(o.weekday+6)%7;i=Yr(n,o.year,o.month,o.day-u),s=Yr(n,o.year,o.month,o.day-u+7);let p=os(i,n);a=`week of ${p.year}-${String(p.month).padStart(2,"0")}-${String(p.day).padStart(2,"0")}`}else i=Yr(n,o.year,o.month,1),s=Yr(n,o.year,o.month+1,1),a=nr(o.year,o.month);let d=s.getTime()-i.getTime(),c=Math.max(0,Math.min(d,r.getTime()-i.getTime()));return{start:i.toISOString(),end:s.toISOString(),elapsedMs:c,totalMs:d,label:a}}function ep(e,t,r=new Date){let n=gr(e,t,r),o=new Date(new Date(n.start).getTime()-1),i=gr(e,t,o);return{...i,elapsedMs:i.totalMs}}function ri(e){let r=(typeof e==="string"?new Date(e):e).getTime();if(!Number.isFinite(r))throw Error("hourBucket requires a valid date");return new Date(Math.floor(r/3600000)*3600000).toISOString()}function tp(e,t,r=9600){let n=Math.floor(new Date(e).getTime()/3600000)*3600000,o=new Date(t).getTime();if(!Number.isFinite(n)||!Number.isFinite(o))throw Error("hourBucketsBetween requires valid dates");let i=[];for(let s=n;s<o&&i.length<r;s+=3600000)i.push(new Date(s).toISOString());return i}import{createHash as or}from"node:crypto";var le=1073741824,Ha=[{match:"request.count",meter:"edge.requests"},{match:"traffic.requests",meter:"edge.requests"},{match:"http.request",meter:"edge.requests",field:"count"},{match:"traffic.bytes_out",meter:"edge.egress_gb",scale:1/le},{match:"storage.egress.day",meter:"object.egress_gb",scale:1/le},{match:"storage.egress.month",meter:"object.egress_gb",scale:1/le,cumulative:!0},{match:"storage.egress.day_downloads",meter:"object.requests"},{match:"function.invocation",meter:"function.invocations",field:"count"},{match:"function.duration_ms",meter:"function.gb_seconds",scale:0.001},{match:"build.duration_ms",meter:"build.minutes",scale:0.000016666666666666667},{match:"telemetry.ingest_bytes",meter:"telemetry.ingest_gb",scale:1/le},{match:"image.transform",meter:"image.transformations",field:"count"}];function ir(e,t){return e.match.endsWith("*")?t.startsWith(e.match.slice(0,-1)):e.match===t}function od(e,t=Ha){return t.find((r)=>!r.match.endsWith("*")&&r.match===e)??t.find((r)=>ir(r,e))}function sr(e,t){let r=t.field??"value",n=r==="count"?1:r==="bytesOut"?e.bytesOut:r==="bytesIn"?e.bytesIn:r==="durationMs"?e.durationMs:e.value;if(n==null||!Number.isFinite(n))return;return n*(t.scale??1)}function sd(e,t){return or("sha256").update([t,e.meter,e.organizationId,e.projectId??"",e.environmentId??"",e.resourceId??"",e.timestamp].join("\x00")).digest("hex").slice(0,32)}class ss{resetToleranceRatio;last=new Map;constructor(e=0.999){this.resetToleranceRatio=e}delta(e,t,r=new Date){if(!Number.isFinite(t)||t<0)return;let n=new Date(r).getTime(),o=this.last.get(e);if(!o)return this.last.set(e,{value:t,at:n}),t>0?t:void 0;if(n<o.at)return;if(t<o.value&&t>=o.value*this.resetToleranceRatio)return;if(this.last.set(e,{value:t,at:n}),t>=o.value){let i=t-o.value;return i>0?i:void 0}return t>0?t:void 0}prune(e){let t=e.getTime(),r=0;for(let[n,o]of this.last)if(o.at<t)this.last.delete(n),r++;return r}get size(){return this.last.size}}function nt(e,t){let r=e[t];return typeof r==="string"&&r.length>0?r:void 0}function qa(e,t,r={}){let n=r.mappings??Ha,o=r.counters,i=[];for(let s of t){let a=od(s.name,n);if(!a)continue;let d=sr(s,a);if(d==null)continue;if(a.cumulative){if(!o)continue;let u=[s.projectId,s.environmentId??"",s.resourceId??"",s.name,s.source].join("\x00"),p=o.delta(u,d,s.timestamp);if(p==null)continue;d=p}if(!(d>0))continue;let c={organizationId:e,projectId:s.projectId,environmentId:s.environmentId,resourceId:s.resourceId,provider:nt(s.attributes,"provider")??r.defaultProvider,region:s.region??nt(s.attributes,"region"),meter:a.meter,quantity:d,timestamp:s.timestamp,attributes:{source:s.source,signal:s.name}};i.push({...c,key:sd(c,s.id)})}return i}function Wa(e){let t=new Map;for(let r of e){let n=new Date(Math.floor(new Date(r.timestamp).getTime()/3600000)*3600000).toISOString(),o=[r.organizationId,r.projectId??"",r.environmentId??"",r.resourceId??"",r.provider??"",r.region??"",r.meter,n].join("\x00"),i=t.get(o);if(i)i.quantity+=r.quantity;else t.set(o,{...r,timestamp:n})}return[...t.values()]}import{createHash as ar}from"node:crypto";var K=(e)=>{if(typeof e!=="string")return{};try{return JSON.parse(e)}catch{return{}}},j=(e)=>typeof e==="string"&&e!==""?e:void 0,ue=(e)=>Number(e)===1,ot=(e)=>e==null?void 0:Number(e);function it(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:j(e.project_id),environmentId:j(e.environment_id),name:String(e.name),period:String(e.period),timezone:String(e.timezone),currency:String(e.currency),softLimitCents:ot(e.soft_limit_cents),hardLimitCents:ot(e.hard_limit_cents),thresholds:K(e.thresholds),meters:K(e.meters),graceSeconds:Number(e.grace_seconds),hysteresisPercent:Number(e.hysteresis_percent),dryRun:ue(e.dry_run),enabled:ue(e.enabled),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Ae(e){return{id:String(e.id),budgetId:String(e.budget_id),organizationId:String(e.organization_id),projectId:j(e.project_id),environmentId:j(e.environment_id),action:String(e.action),state:String(e.state),reason:String(e.reason),restore:K(e.restore),triggeredAtPercent:Number(e.triggered_at_percent),simulated:ue(e.simulated),appliedAt:j(e.applied_at),releasedAt:j(e.released_at),error:j(e.error),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function st(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:j(e.project_id),environmentId:j(e.environment_id),signal:String(e.signal),direction:String(e.direction),observed:Number(e.observed),expected:Number(e.expected),score:Number(e.score),deltaPercent:Number(e.delta_percent),severity:String(e.severity),bucketStart:String(e.bucket_start),evidence:K(e.evidence),acknowledgedAt:j(e.acknowledged_at),createdAt:String(e.created_at)}}function dr(e){return{organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:String(e.environment_id),resourceId:String(e.resource_id),provider:String(e.provider),region:String(e.region),meter:String(e.meter),bucketStart:String(e.bucket_start),quantity:Number(e.quantity),costCents:Number(e.cost_cents),sampleCount:Number(e.sample_count),updatedAt:String(e.updated_at)}}function fr(e,t,r){return[e,t??"",r??""].join("/")}var Gi=[{atPercent:50,actions:["notify"]},{atPercent:80,actions:["notify"]},{atPercent:100,actions:["notify"],onProjection:!0},{atPercent:100,actions:["notify","block_builds","block_deployments"]},{atPercent:115,actions:["notify","block_builds","block_deployments","throttle_requests"]}];class hr{controlPlane;options;constructor(e,t={}){this.controlPlane=e;this.options=t}now(){return(this.options.now?.()??new Date).toISOString()}get priceBook(){return this.options.priceBook??Va}query(e,t=[]){return this.controlPlane.database.query(e).all(...t)}createBudget(e){let t=e.name.trim();if(!t)throw Error("Budgets require a name.");if(e.softLimitCents==null&&e.hardLimitCents==null)throw Error("A budget needs a soft limit, a hard limit, or both.");if(e.softLimitCents!=null&&e.hardLimitCents!=null&&e.softLimitCents>e.hardLimitCents)throw Error("The soft limit must not exceed the hard limit.");let r=e.timezone??"UTC";if(!Wi(r))throw Error(`Unknown timezone: ${r}`);let n=(e.thresholds??[...Gi]).filter((s)=>Number.isFinite(s.atPercent)&&s.atPercent>=0);if(e.environmentId&&!e.projectId)throw Error("An environment-scoped budget must also name its project.");let o=crypto.randomUUID(),i=this.now();return this.controlPlane.database.run("INSERT INTO spend_budgets (id,organization_id,project_id,environment_id,name,period,timezone,currency,soft_limit_cents,hard_limit_cents,thresholds,meters,grace_seconds,hysteresis_percent,dry_run,enabled,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,1,?,?)",[o,e.organizationId,e.projectId??null,e.environmentId??null,t,e.period,r,e.currency??"USD",e.softLimitCents??null,e.hardLimitCents??null,JSON.stringify(n),JSON.stringify(e.meters??[]),Math.max(0,Math.floor(e.graceSeconds??0)),Math.max(0,e.hysteresisPercent??5),e.dryRun?1:0,e.enabled===!1?0:1,i,i]),this.getBudget(o)}getBudget(e){let t=this.query("SELECT * FROM spend_budgets WHERE id = ?",[e])[0];return t?it(t):void 0}listBudgets(e){let t=["organization_id = ?"],r=[e.organizationId];if(e.projectId)t.push("(project_id IS NULL OR project_id = ?)"),r.push(e.projectId);if(e.enabledOnly)t.push("enabled = 1");return this.query(`SELECT * FROM spend_budgets WHERE ${t.join(" AND ")} ORDER BY created_at`,r).map(it)}budgetsForScope(e,t,r){return this.listBudgets({organizationId:e,enabledOnly:!0}).filter((n)=>{if(n.projectId&&n.projectId!==t)return!1;if(n.environmentId&&n.environmentId!==r)return!1;return!0}).sort((n,o)=>Number(!!n.projectId)-Number(!!o.projectId)||Number(!!n.environmentId)-Number(!!o.environmentId))}updateBudget(e,t,r){let n=this.getBudget(e);if(!n)throw Error("Budget was not found.");if(r!=null&&r!==n.version)throw Error(`Budget was modified concurrently (expected version ${r}, found ${n.version}).`);let o={...n,...t};if(o.softLimitCents==null&&o.hardLimitCents==null)throw Error("A budget needs a soft limit, a hard limit, or both.");if(o.softLimitCents!=null&&o.hardLimitCents!=null&&o.softLimitCents>o.hardLimitCents)throw Error("The soft limit must not exceed the hard limit.");if(t.timezone&&!Wi(t.timezone))throw Error(`Unknown timezone: ${t.timezone}`);return this.controlPlane.database.run("UPDATE spend_budgets SET name=?,period=?,timezone=?,currency=?,soft_limit_cents=?,hard_limit_cents=?,thresholds=?,meters=?,grace_seconds=?,hysteresis_percent=?,dry_run=?,enabled=?,version=version+1,updated_at=? WHERE id=?",[o.name,o.period,o.timezone,o.currency??"USD",o.softLimitCents??null,o.hardLimitCents??null,JSON.stringify(o.thresholds??[]),JSON.stringify(o.meters??[]),Math.max(0,Math.floor(o.graceSeconds??0)),Math.max(0,o.hysteresisPercent??5),o.dryRun?1:0,o.enabled===!1?0:1,this.now(),e]),this.getBudget(e)}deleteBudget(e){return this.controlPlane.database.run("DELETE FROM spend_budgets WHERE id = ?",[e]).changes>0}ingestUsage(e){let t={applied:0,duplicates:0,costCents:0,unpricedMeters:[]},r=new Set,n=this.now();return this.controlPlane.database.transaction((i)=>{for(let s of i){if(!(s.quantity>0)||!Number.isFinite(s.quantity))continue;let a=s.key??this.deltaFallbackKey(s);if(this.controlPlane.database.run("INSERT OR IGNORE INTO spend_usage_receipts (key,organization_id,bucket_start,created_at) VALUES (?,?,?,?)",[a,s.organizationId,ri(s.timestamp),n]).changes===0){t.duplicates++;continue}let c={projectId:s.projectId??"",environmentId:s.environmentId??"",resourceId:s.resourceId??"",provider:s.provider??"",region:s.region??""},u=this.periodQuantity(s),p=is(this.priceBook,{meter:s.meter,quantity:s.quantity,provider:s.provider,region:s.region},u);if(p.unpriced)r.add(String(s.meter));this.controlPlane.database.run(`INSERT INTO spend_usage (organization_id,project_id,environment_id,resource_id,provider,region,meter,bucket_start,quantity,cost_cents,sample_count,updated_at)
|
|
1
|
+
import{te,h}from"./chunk-jzby2kzy.js";import{eo}from"./chunk-573red0g.js";var Ju=["edge.requests","edge.egress_gb","function.invocations","function.gb_seconds","build.minutes","compute.instance_hours","storage.gb_hours","object.egress_gb","object.requests","database.gb_hours","database.io_requests","telemetry.ingest_gb","image.transformations"],Qr={"edge.requests":{key:"edge.requests",unit:"requests",label:"Edge requests",precision:0},"edge.egress_gb":{key:"edge.egress_gb",unit:"gb",label:"Edge egress",precision:3},"function.invocations":{key:"function.invocations",unit:"invocations",label:"Function invocations",precision:0},"function.gb_seconds":{key:"function.gb_seconds",unit:"gb_seconds",label:"Function compute",precision:2},"build.minutes":{key:"build.minutes",unit:"minutes",label:"Build minutes",precision:2},"compute.instance_hours":{key:"compute.instance_hours",unit:"hours",label:"Instance hours",precision:2},"storage.gb_hours":{key:"storage.gb_hours",unit:"gb_hours",label:"Block storage",precision:2},"object.egress_gb":{key:"object.egress_gb",unit:"gb",label:"Object storage egress",precision:3},"object.requests":{key:"object.requests",unit:"requests",label:"Object storage requests",precision:0},"database.gb_hours":{key:"database.gb_hours",unit:"gb_hours",label:"Database storage",precision:2},"database.io_requests":{key:"database.io_requests",unit:"requests",label:"Database I/O",precision:0},"telemetry.ingest_gb":{key:"telemetry.ingest_gb",unit:"gb",label:"Telemetry ingest",precision:3},"image.transformations":{key:"image.transformations",unit:"count",label:"Image transformations",precision:0}},qi=["notify","block_builds","block_deployments","throttle_requests","suspend_functions","serve_static","suspend_project"],oe={notify:0,block_builds:1,block_deployments:2,throttle_requests:3,suspend_functions:4,serve_static:5,suspend_project:6};var Xu=1e6;function tr(e){if(e.tiers&&e.tiers.length>0)return e.tiers;return[{upToQuantity:null,microCentsPerUnit:e.microCentsPerUnit??0}]}function ja(e,t){if(!(e>0))return 0;let r=[...t].sort((s,a)=>{if(s.upToQuantity===null)return 1;if(a.upToQuantity===null)return-1;return s.upToQuantity-a.upToQuantity}),n=e,o=0,i=0;for(let s of r){if(n<=0)break;let d=(s.upToQuantity===null?1/0:s.upToQuantity)-o;if(d<=0)continue;let c=Math.min(n,d);i+=c*s.microCentsPerUnit,n-=c,o+=c}if(n>0){let s=r.reduce((a,d)=>Math.max(a,d.microCentsPerUnit),0);i+=n*s}return i}function id(e,t,r,n){let o=e.entries.filter((a)=>a.meter===t);if(o.length===0)return;let i=o.filter((a)=>a.provider===r),s=i.length>0?i:o.filter((a)=>a.provider==="*");return s.find((a)=>a.region===n)??s.find((a)=>a.region==null)}function is(e,t,r=0){let n=id(e,t.meter,t.provider,t.region),o=Math.max(0,t.quantity);if(!n)return{meter:t.meter,provider:t.provider??"unknown",region:t.region,quantity:o,includedQuantity:0,billableQuantity:o,costCents:0,unpriced:!0};let i=Math.max(0,n.includedQuantity??0),s=Math.max(0,r-i),a=Math.max(0,i-Math.max(0,r)),d=Math.min(o,a),c=o-d,u=tr(n),p=ja(s+c,u)-ja(s,u);return{meter:t.meter,provider:n.provider,region:n.region??t.region,quantity:o,includedQuantity:d,billableQuantity:c,costCents:p/1e6,unpriced:!1}}function Qu(e,t){let r=new Map,n=[];for(let o of t){let i=`${o.meter}\x00${o.provider??""}\x00${o.region??""}`,s=r.get(i)??0,a=is(e,o,s);r.set(i,s+a.quantity),n.push(a)}return{currency:e.currency,totalCents:n.reduce((o,i)=>o+i.costCents,0),lines:n,unpricedMeters:[...new Set(n.filter((o)=>o.unpriced).map((o)=>String(o.meter)))]}}function Yu(e){return Math.round(e*100)/100}function Zu(e,...t){let r=new Map,n=(i)=>`${i.meter}\x00${i.provider}\x00${i.region??""}`;for(let i of e.entries)r.set(n(i),i);let o=e.currency;for(let i of t){o=i.currency||o;for(let s of i.entries)r.set(n(s),s)}return{currency:o,entries:[...r.values()]}}var V=(e)=>Math.round(e*1e6),N=(e)=>Math.round(e*1e6),Va={currency:"USD",entries:[{meter:"edge.requests",provider:"aws",microCentsPerUnit:N(0.00075)},{meter:"edge.egress_gb",provider:"aws",includedQuantity:100,tiers:[{upToQuantity:10240,microCentsPerUnit:V(8.5)},{upToQuantity:51200,microCentsPerUnit:V(8)},{upToQuantity:null,microCentsPerUnit:V(6)}]},{meter:"function.invocations",provider:"aws",includedQuantity:1e6,microCentsPerUnit:N(0.002)},{meter:"function.gb_seconds",provider:"aws",includedQuantity:400000,microCentsPerUnit:N(0.00166667)},{meter:"storage.gb_hours",provider:"aws",microCentsPerUnit:N(0.010958904109589041)},{meter:"object.egress_gb",provider:"aws",includedQuantity:100,microCentsPerUnit:V(9)},{meter:"object.requests",provider:"aws",microCentsPerUnit:N(0.000039999999999999996)},{meter:"database.gb_hours",provider:"aws",microCentsPerUnit:N(0.015753424657534248)},{meter:"compute.instance_hours",provider:"aws",microCentsPerUnit:N(4.16)},{meter:"edge.egress_gb",provider:"hetzner",includedQuantity:20480,microCentsPerUnit:V(0.108)},{meter:"object.egress_gb",provider:"hetzner",includedQuantity:1024,microCentsPerUnit:V(0.108)},{meter:"compute.instance_hours",provider:"hetzner",microCentsPerUnit:N(0.95)},{meter:"storage.gb_hours",provider:"hetzner",microCentsPerUnit:N(0.006027397260273972)},{meter:"edge.requests",provider:"hetzner",microCentsPerUnit:0},{meter:"edge.requests",provider:"local",microCentsPerUnit:0},{meter:"edge.egress_gb",provider:"local",microCentsPerUnit:0},{meter:"function.invocations",provider:"local",microCentsPerUnit:0},{meter:"function.gb_seconds",provider:"local",microCentsPerUnit:0},{meter:"build.minutes",provider:"*",includedQuantity:6000,microCentsPerUnit:N(0.8)},{meter:"telemetry.ingest_gb",provider:"*",includedQuantity:5,microCentsPerUnit:V(50)},{meter:"image.transformations",provider:"*",includedQuantity:5000,microCentsPerUnit:N(0.05)}]};var tt=new Map;function rt(e){let t=tt.get(e);if(!t)t=new Intl.DateTimeFormat("en-US",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",weekday:"short",hourCycle:"h23"}),tt.set(e,t);return t}var rr={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6};function Wi(e){try{return rt(e),!0}catch{return!1}}function os(e,t){let r=rt(t).formatToParts(e),n=(o)=>r.find((i)=>i.type===o)?.value??"0";return{year:Number(n("year")),month:Number(n("month")),day:Number(n("day")),hour:Number(n("hour")),minute:Number(n("minute")),second:Number(n("second")),weekday:rr[n("weekday")]??0}}function za(e,t){let r=os(e,t);return Date.UTC(r.year,r.month-1,r.day,r.hour,r.minute,r.second)-Math.floor(e.getTime()/1000)*1000}function Yr(e,t,r,n,o=0){let i=Date.UTC(t,r-1,n,o),s=new Date(i-za(new Date(i),e));return new Date(i-za(s,e))}function nr(e,t){return new Date(Date.UTC(e,t-1,1)).toLocaleString("en-US",{month:"long",year:"numeric",timeZone:"UTC"})}function gr(e,t,r=new Date){let n=Wi(t)?t:"UTC",o=os(r,n),i,s,a;if(e==="daily")i=Yr(n,o.year,o.month,o.day),s=Yr(n,o.year,o.month,o.day+1),a=`${o.year}-${String(o.month).padStart(2,"0")}-${String(o.day).padStart(2,"0")}`;else if(e==="weekly"){let u=(o.weekday+6)%7;i=Yr(n,o.year,o.month,o.day-u),s=Yr(n,o.year,o.month,o.day-u+7);let p=os(i,n);a=`week of ${p.year}-${String(p.month).padStart(2,"0")}-${String(p.day).padStart(2,"0")}`}else i=Yr(n,o.year,o.month,1),s=Yr(n,o.year,o.month+1,1),a=nr(o.year,o.month);let d=s.getTime()-i.getTime(),c=Math.max(0,Math.min(d,r.getTime()-i.getTime()));return{start:i.toISOString(),end:s.toISOString(),elapsedMs:c,totalMs:d,label:a}}function ep(e,t,r=new Date){let n=gr(e,t,r),o=new Date(new Date(n.start).getTime()-1),i=gr(e,t,o);return{...i,elapsedMs:i.totalMs}}function ri(e){let r=(typeof e==="string"?new Date(e):e).getTime();if(!Number.isFinite(r))throw Error("hourBucket requires a valid date");return new Date(Math.floor(r/3600000)*3600000).toISOString()}function tp(e,t,r=9600){let n=Math.floor(new Date(e).getTime()/3600000)*3600000,o=new Date(t).getTime();if(!Number.isFinite(n)||!Number.isFinite(o))throw Error("hourBucketsBetween requires valid dates");let i=[];for(let s=n;s<o&&i.length<r;s+=3600000)i.push(new Date(s).toISOString());return i}import{createHash as or}from"node:crypto";var le=1073741824,Ha=[{match:"request.count",meter:"edge.requests"},{match:"traffic.requests",meter:"edge.requests"},{match:"http.request",meter:"edge.requests",field:"count"},{match:"traffic.bytes_out",meter:"edge.egress_gb",scale:1/le},{match:"storage.egress.day",meter:"object.egress_gb",scale:1/le},{match:"storage.egress.month",meter:"object.egress_gb",scale:1/le,cumulative:!0},{match:"storage.egress.day_downloads",meter:"object.requests"},{match:"function.invocation",meter:"function.invocations",field:"count"},{match:"function.duration_ms",meter:"function.gb_seconds",scale:0.001},{match:"build.duration_ms",meter:"build.minutes",scale:0.000016666666666666667},{match:"telemetry.ingest_bytes",meter:"telemetry.ingest_gb",scale:1/le},{match:"image.transform",meter:"image.transformations",field:"count"}];function ir(e,t){return e.match.endsWith("*")?t.startsWith(e.match.slice(0,-1)):e.match===t}function od(e,t=Ha){return t.find((r)=>!r.match.endsWith("*")&&r.match===e)??t.find((r)=>ir(r,e))}function sr(e,t){let r=t.field??"value",n=r==="count"?1:r==="bytesOut"?e.bytesOut:r==="bytesIn"?e.bytesIn:r==="durationMs"?e.durationMs:e.value;if(n==null||!Number.isFinite(n))return;return n*(t.scale??1)}function sd(e,t){return or("sha256").update([t,e.meter,e.organizationId,e.projectId??"",e.environmentId??"",e.resourceId??"",e.timestamp].join("\x00")).digest("hex").slice(0,32)}class ss{resetToleranceRatio;last=new Map;constructor(e=0.999){this.resetToleranceRatio=e}delta(e,t,r=new Date){if(!Number.isFinite(t)||t<0)return;let n=new Date(r).getTime(),o=this.last.get(e);if(!o)return this.last.set(e,{value:t,at:n}),t>0?t:void 0;if(n<o.at)return;if(t<o.value&&t>=o.value*this.resetToleranceRatio)return;if(this.last.set(e,{value:t,at:n}),t>=o.value){let i=t-o.value;return i>0?i:void 0}return t>0?t:void 0}prune(e){let t=e.getTime(),r=0;for(let[n,o]of this.last)if(o.at<t)this.last.delete(n),r++;return r}get size(){return this.last.size}}function nt(e,t){let r=e[t];return typeof r==="string"&&r.length>0?r:void 0}function qa(e,t,r={}){let n=r.mappings??Ha,o=r.counters,i=[];for(let s of t){let a=od(s.name,n);if(!a)continue;let d=sr(s,a);if(d==null)continue;if(a.cumulative){if(!o)continue;let u=[s.projectId,s.environmentId??"",s.resourceId??"",s.name,s.source].join("\x00"),p=o.delta(u,d,s.timestamp);if(p==null)continue;d=p}if(!(d>0))continue;let c={organizationId:e,projectId:s.projectId,environmentId:s.environmentId,resourceId:s.resourceId,provider:nt(s.attributes,"provider")??r.defaultProvider,region:s.region??nt(s.attributes,"region"),meter:a.meter,quantity:d,timestamp:s.timestamp,attributes:{source:s.source,signal:s.name}};i.push({...c,key:sd(c,s.id)})}return i}function Wa(e){let t=new Map;for(let r of e){let n=new Date(Math.floor(new Date(r.timestamp).getTime()/3600000)*3600000).toISOString(),o=[r.organizationId,r.projectId??"",r.environmentId??"",r.resourceId??"",r.provider??"",r.region??"",r.meter,n].join("\x00"),i=t.get(o);if(i)i.quantity+=r.quantity;else t.set(o,{...r,timestamp:n})}return[...t.values()]}import{createHash as ar}from"node:crypto";var K=(e)=>{if(typeof e!=="string")return{};try{return JSON.parse(e)}catch{return{}}},j=(e)=>typeof e==="string"&&e!==""?e:void 0,ue=(e)=>Number(e)===1,ot=(e)=>e==null?void 0:Number(e);function it(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:j(e.project_id),environmentId:j(e.environment_id),name:String(e.name),period:String(e.period),timezone:String(e.timezone),currency:String(e.currency),softLimitCents:ot(e.soft_limit_cents),hardLimitCents:ot(e.hard_limit_cents),thresholds:K(e.thresholds),meters:K(e.meters),graceSeconds:Number(e.grace_seconds),hysteresisPercent:Number(e.hysteresis_percent),dryRun:ue(e.dry_run),enabled:ue(e.enabled),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Ae(e){return{id:String(e.id),budgetId:String(e.budget_id),organizationId:String(e.organization_id),projectId:j(e.project_id),environmentId:j(e.environment_id),action:String(e.action),state:String(e.state),reason:String(e.reason),restore:K(e.restore),triggeredAtPercent:Number(e.triggered_at_percent),simulated:ue(e.simulated),appliedAt:j(e.applied_at),releasedAt:j(e.released_at),error:j(e.error),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function st(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:j(e.project_id),environmentId:j(e.environment_id),signal:String(e.signal),direction:String(e.direction),observed:Number(e.observed),expected:Number(e.expected),score:Number(e.score),deltaPercent:Number(e.delta_percent),severity:String(e.severity),bucketStart:String(e.bucket_start),evidence:K(e.evidence),acknowledgedAt:j(e.acknowledged_at),createdAt:String(e.created_at)}}function dr(e){return{organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:String(e.environment_id),resourceId:String(e.resource_id),provider:String(e.provider),region:String(e.region),meter:String(e.meter),bucketStart:String(e.bucket_start),quantity:Number(e.quantity),costCents:Number(e.cost_cents),sampleCount:Number(e.sample_count),updatedAt:String(e.updated_at)}}function fr(e,t,r){return[e,t??"",r??""].join("/")}var Gi=[{atPercent:50,actions:["notify"]},{atPercent:80,actions:["notify"]},{atPercent:100,actions:["notify"],onProjection:!0},{atPercent:100,actions:["notify","block_builds","block_deployments"]},{atPercent:115,actions:["notify","block_builds","block_deployments","throttle_requests"]}];class hr{controlPlane;options;constructor(e,t={}){this.controlPlane=e;this.options=t}now(){return(this.options.now?.()??new Date).toISOString()}get priceBook(){return this.options.priceBook??Va}query(e,t=[]){return this.controlPlane.database.query(e).all(...t)}createBudget(e){let t=e.name.trim();if(!t)throw Error("Budgets require a name.");if(e.softLimitCents==null&&e.hardLimitCents==null)throw Error("A budget needs a soft limit, a hard limit, or both.");if(e.softLimitCents!=null&&e.hardLimitCents!=null&&e.softLimitCents>e.hardLimitCents)throw Error("The soft limit must not exceed the hard limit.");let r=e.timezone??"UTC";if(!Wi(r))throw Error(`Unknown timezone: ${r}`);let n=(e.thresholds??[...Gi]).filter((s)=>Number.isFinite(s.atPercent)&&s.atPercent>=0);if(e.environmentId&&!e.projectId)throw Error("An environment-scoped budget must also name its project.");let o=crypto.randomUUID(),i=this.now();return this.controlPlane.database.run("INSERT INTO spend_budgets (id,organization_id,project_id,environment_id,name,period,timezone,currency,soft_limit_cents,hard_limit_cents,thresholds,meters,grace_seconds,hysteresis_percent,dry_run,enabled,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,1,?,?)",[o,e.organizationId,e.projectId??null,e.environmentId??null,t,e.period,r,e.currency??"USD",e.softLimitCents??null,e.hardLimitCents??null,JSON.stringify(n),JSON.stringify(e.meters??[]),Math.max(0,Math.floor(e.graceSeconds??0)),Math.max(0,e.hysteresisPercent??5),e.dryRun?1:0,e.enabled===!1?0:1,i,i]),this.getBudget(o)}getBudget(e){let t=this.query("SELECT * FROM spend_budgets WHERE id = ?",[e])[0];return t?it(t):void 0}listBudgets(e){let t=["organization_id = ?"],r=[e.organizationId];if(e.projectId)t.push("(project_id IS NULL OR project_id = ?)"),r.push(e.projectId);if(e.enabledOnly)t.push("enabled = 1");return this.query(`SELECT * FROM spend_budgets WHERE ${t.join(" AND ")} ORDER BY created_at`,r).map(it)}budgetsForScope(e,t,r){return this.listBudgets({organizationId:e,enabledOnly:!0}).filter((n)=>{if(n.projectId&&n.projectId!==t)return!1;if(n.environmentId&&n.environmentId!==r)return!1;return!0}).sort((n,o)=>Number(!!n.projectId)-Number(!!o.projectId)||Number(!!n.environmentId)-Number(!!o.environmentId))}updateBudget(e,t,r){let n=this.getBudget(e);if(!n)throw Error("Budget was not found.");if(r!=null&&r!==n.version)throw Error(`Budget was modified concurrently (expected version ${r}, found ${n.version}).`);let o={...n,...t};if(o.softLimitCents==null&&o.hardLimitCents==null)throw Error("A budget needs a soft limit, a hard limit, or both.");if(o.softLimitCents!=null&&o.hardLimitCents!=null&&o.softLimitCents>o.hardLimitCents)throw Error("The soft limit must not exceed the hard limit.");if(t.timezone&&!Wi(t.timezone))throw Error(`Unknown timezone: ${t.timezone}`);return this.controlPlane.database.run("UPDATE spend_budgets SET name=?,period=?,timezone=?,currency=?,soft_limit_cents=?,hard_limit_cents=?,thresholds=?,meters=?,grace_seconds=?,hysteresis_percent=?,dry_run=?,enabled=?,version=version+1,updated_at=? WHERE id=?",[o.name,o.period,o.timezone,o.currency??"USD",o.softLimitCents??null,o.hardLimitCents??null,JSON.stringify(o.thresholds??[]),JSON.stringify(o.meters??[]),Math.max(0,Math.floor(o.graceSeconds??0)),Math.max(0,o.hysteresisPercent??5),o.dryRun?1:0,o.enabled===!1?0:1,this.now(),e]),this.getBudget(e)}deleteBudget(e){return this.controlPlane.database.run("DELETE FROM spend_budgets WHERE id = ?",[e]).changes>0}ingestUsage(e){let t={applied:0,duplicates:0,costCents:0,unpricedMeters:[]},r=new Set,n=this.now();return this.controlPlane.database.transaction((i)=>{for(let s of i){if(!(s.quantity>0)||!Number.isFinite(s.quantity))continue;let a=s.key??this.deltaFallbackKey(s);if(this.controlPlane.database.run("INSERT OR IGNORE INTO spend_usage_receipts (key,organization_id,bucket_start,created_at) VALUES (?,?,?,?)",[a,s.organizationId,ri(s.timestamp),n]).changes===0){t.duplicates++;continue}let c={projectId:s.projectId??"",environmentId:s.environmentId??"",resourceId:s.resourceId??"",provider:s.provider??"",region:s.region??""},u=this.periodQuantity(s),p=is(this.priceBook,{meter:s.meter,quantity:s.quantity,provider:s.provider,region:s.region},u);if(p.unpriced)r.add(String(s.meter));this.controlPlane.database.run(`INSERT INTO spend_usage (organization_id,project_id,environment_id,resource_id,provider,region,meter,bucket_start,quantity,cost_cents,sample_count,updated_at)
|
|
2
2
|
VALUES (?,?,?,?,?,?,?,?,?,?,1,?)
|
|
3
3
|
ON CONFLICT(organization_id,project_id,environment_id,resource_id,provider,region,meter,bucket_start) DO UPDATE SET
|
|
4
4
|
quantity = quantity + excluded.quantity,
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{J,U,ui,Ls,Bt,pc}from"./chunk-
|
|
1
|
+
import{J,U,ui,Ls,Bt,pc}from"./chunk-wt7wjgcr.js";function c(e){return`'${e.split("'").join("'\\''")}'`}function m(e){let r=e.user||"root",s=e.script.join(`
|
|
2
2
|
`),t=r==="root"?'bash -l "$TS_CLOUD_RECIPE"':`runuser -l ${c(r)} -c "bash $TS_CLOUD_RECIPE"`;return["set -uo pipefail",`echo "__TS_CLOUD_RECIPE_BEGIN__ ${e.name} (user=${r})"`,"TS_CLOUD_RECIPE=$(mktemp)",`cat > "$TS_CLOUD_RECIPE" <<'TS_CLOUD_RECIPE_EOF'`,s,"TS_CLOUD_RECIPE_EOF",'chmod +r "$TS_CLOUD_RECIPE"',t,"TS_CLOUD_RC=$?",'rm -f "$TS_CLOUD_RECIPE"',`echo "__TS_CLOUD_RECIPE_END__ ${e.name} exit=$TS_CLOUD_RC"`,"exit $TS_CLOUD_RC"]}var l={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};async function i(e){return await e.driver.findComputeTargets({slug:e.slug,environment:e.environment,role:e.role||"app"})}async function ks(e,r){let s=e.logger||l,t=await i(e);if(t.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};let n=J(e.slug,r.siteName),u=Bt(n,r.to||"unused"),o=["set -uo pipefail",...pc(u,{...r.to?{to:r.to}:{},unitBase:`${e.slug}-${r.siteName}`}),`(cd ${U} && pantry restart php-fpm) 2>/dev/null || true`,`(cd ${u.current} && eval "$(cd ${U} && pantry env 2>/dev/null)" && php artisan queue:restart) 2>/dev/null || true`];s.step(`Rolling back ${r.siteName}${r.to?` to ${r.to}`:" to the previous release"} on ${t.length} server(s)...`);let a=await e.driver.runRemoteDeploy({targets:t,commands:o,comment:`ts-cloud rollback ${e.slug}/${r.siteName}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});if(!a.success)s.error(`Rollback failed: ${a.error||"unknown error"}`);else s.success(`Rolled back ${r.siteName}.`);return{success:a.success,error:a.error,perInstance:a.perInstance}}async function hp(e,r){let s=await i(e);if(s.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};let t=Ls(J(e.slug,r.siteName)),n=Math.max(1,r.limit??20),u=[`[ -f ${t} ] && tail -n ${n} ${t} || echo "no deploy history for ${r.siteName}"`],o=await e.driver.runRemoteDeploy({targets:s,commands:u,comment:`ts-cloud deploy:history ${e.slug}/${r.siteName}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});return{success:o.success,error:o.error,perInstance:o.perInstance}}async function yp(e,r){let s=e.logger||l,t=await i(e);if(t.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};s.step(`Running recipe '${r.name}' as ${r.user||"root"} on ${t.length} server(s)...`);let n=await e.driver.runRemoteDeploy({targets:t,commands:m({name:r.name,script:r.script,user:r.user}),comment:`ts-cloud recipe ${r.name}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});if(!n.success)s.error(`Recipe '${r.name}' failed: ${n.error||"unknown error"}`);else s.success(`Recipe '${r.name}' completed.`);return{success:n.success,error:n.error,perInstance:n.perInstance}}async function _s(e,r){let s=e.logger||l;if(!r.database?.name)return{success:!1,error:"No appDatabase configured to restore."};let t=await i(e);if(t.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};s.step(`Restoring database '${r.database.name}'${r.from?` from ${r.from}`:" from the latest backup"} on ${t.length} server(s)...`);let n=await e.driver.runRemoteDeploy({targets:t,commands:ui(r.database,{from:r.from}),comment:`ts-cloud db:restore ${e.slug}/${r.database.name}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});if(!n.success)s.error(`Restore failed: ${n.error||"unknown error"}`);else s.success(`Restored ${r.database.name}.`);return{success:n.success,error:n.error,perInstance:n.perInstance}}
|
|
3
3
|
export{ks,hp,yp,_s};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Uo,un,Sa,Ii,jo,Vo}from"./chunk-
|
|
1
|
+
import{Uo,un,Sa,Ii,jo,Vo}from"./chunk-nnawqw34.js";import{e}from"./chunk-tgwx5haz.js";import{ht}from"./chunk-985ev3ns.js";import{execFileSync as C}from"node:child_process";import{mkdirSync as w,mkdtempSync as I,rmSync as U,writeFileSync as g}from"node:fs";import{tmpdir as j}from"node:os";import{dirname as O,join as o}from"node:path";function E(s,t){for(let r of t){let d=o(s,r.name);w(O(d),{recursive:!0}),g(d,r.data,r.mode?{mode:r.mode}:void 0)}}async function Vu(s){let{app:t,projectRoot:r,region:d,repository:u}=s,x=t.architecture??"x86_64",R=x==="arm64"?"linux/arm64":"linux/amd64",b=t.kind==="php",n=s.onStep??(()=>{}),a=I(o(j(),"tscloud-img-"));try{let h=o(a,"app");w(h,{recursive:!0});let f,y;if(b){jo({projectRoot:r,app:t,skipBuild:s.skipBuild,onStep:n}),n("staging application tree");let i=Vo(r);E(h,i),E(o(a,"runtime"),Ii().map((c)=>({name:c.path,data:c.contents,mode:c.mode})));let v=t.handlers?.http??"public/index.php";f={http:v,queue:t.handlers?.queue??v,cli:t.handlers?.cli??v},y=Uo(i.map((c)=>`${c.name}:${c.data.length}`).join("|"))}else{n("bundling application");let i=await un({projectRoot:r,app:t,skipBuild:s.skipBuild,onStep:n});g(o(h,"index.mjs"),i.bundle),f=i.handlers,y=i.sha256}let B=y.slice(0,16);g(o(a,"Dockerfile"),Sa({kind:t.kind??"node",phpVersion:t.phpVersion,architecture:x}));let k=new ht(d),p;try{p=(await k.describeRepositories({repositoryNames:[u]})).repositories?.[0]?.repositoryUri??""}catch{p=""}if(!p)n(`creating ECR repository ${u}`),p=(await k.createRepository({repositoryName:u,imageScanningConfiguration:{scanOnPush:!0}})).repository?.repositoryUri??"";if(!p)throw Error(`could not resolve ECR repository URI for ${u}`);let l=`${p}:${B}`;n("docker build"),C("docker",["build","--platform",R,"--provenance=false","--sbom=false","-t",l,a],{stdio:"inherit"}),n("ecr auth + push");let m=(await k.getAuthorizationToken()).authorizationData?.[0];if(!m?.authorizationToken||!m.proxyEndpoint)throw Error("failed to get an ECR authorization token");let A=m.proxyEndpoint.replace(/^https?:\/\//,""),S=o(a,".docker");return w(S,{recursive:!0}),g(o(S,"config.json"),JSON.stringify({auths:{[A]:{auth:m.authorizationToken}}})),C("docker",["push",l],{stdio:"inherit",env:{...process.env,DOCKER_CONFIG:S}}),e(`Image: ${l}`),{imageUri:l,tag:B,handlers:f}}finally{U(a,{recursive:!0,force:!0})}}
|
|
2
2
|
export{Vu};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{A}from"./chunk-
|
|
1
|
+
import{A}from"./chunk-nnawqw34.js";var se=["project:read","config:read","config:write","deployments:read","deployments:create","deployments:cancel","deployments:rollback","runtime:read","runtime:restart","runtime:logs","runtime:terminal","data:read","data:write","data:admin","backups:read","backups:create","backups:restore","secrets:read","secrets:write","fleet:read","fleet:manage","users:read","users:manage","users:transfer-ownership","audit:read","billing:read","billing:manage","security:read","security:manage","security:waive","sources:read","sources:manage","applications:read","applications:manage","automation:read","automation:manage","tags:manage"],K=["project:read","config:read","deployments:read","runtime:read","runtime:logs","data:read","backups:read","security:read","sources:read","applications:read","billing:read"],Ee={owner:new Set(se),admin:new Set(se.filter((e)=>e!=="users:transfer-ownership")),deployer:new Set([...K,"deployments:create","deployments:cancel","deployments:rollback","sources:manage","applications:manage"]),operator:new Set([...K,"runtime:restart","backups:create","security:manage","sources:manage","applications:manage"]),viewer:new Set(K),auditor:new Set(["project:read","config:read","deployments:read","runtime:read","data:read","backups:read","audit:read","security:read","sources:read","applications:read"])};function sn(e){return Ee[e]}function P(e,t){if(e.type==="organization")return e.id===void 0||e.id===t.organizationId;if(!e.id)return!1;if(e.type==="project")return e.id===t.projectId;if(e.type==="environment")return e.id===t.environmentId;return e.id===t.resourceId}function te(e){let{membership:t,capability:r,target:i}=e;if(!t||t.status!=="active"||t.organizationId!==i.organizationId)return{allowed:!1,reason:"inactive-membership"};let a=e.grants.filter((s)=>s.organizationId===i.organizationId&&s.membershipId===t.id&&s.capability===r&&P(s.scope,i)),E=a.find((s)=>s.effect==="deny");if(E)return{allowed:!1,reason:"explicit-deny",inheritedFrom:{kind:"grant",id:E.id,scope:E.scope}};let T=a.find((s)=>s.effect==="allow");if(T)return{allowed:!0,reason:"explicit-allow",inheritedFrom:{kind:"grant",id:T.id,scope:T.scope}};if(!P(t.scope,i))return{allowed:!1,reason:"scope-mismatch"};if(sn(t.roleTemplate).has(r))return{allowed:!0,reason:"role-template",inheritedFrom:{kind:"membership",id:t.id,scope:t.scope}};return{allowed:!1,reason:"missing-capability"}}function an(e){return se.filter((t)=>te({...e,capability:t}).allowed)}import{createHash as S,randomBytes as oe}from"node:crypto";import{chmodSync as H,existsSync as Z,mkdirSync as Te,statSync as de}from"node:fs";import{dirname as ee}from"node:path";import{Database as Ne}from"bun:sqlite";var l=40,j=[{version:1,name:"core_control_plane",sql:`
|
|
2
2
|
CREATE TABLE projects (
|
|
3
3
|
id TEXT PRIMARY KEY,
|
|
4
4
|
slug TEXT NOT NULL UNIQUE,
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{u}from"./chunk-
|
|
1
|
+
import{u}from"./chunk-qe56mnjc.js";class ct{client;region;constructor(t="us-east-1",e){this.region=t,this.client=new u(void 0,{profile:e})}async getCallerIdentity(){let t=await this.client.request({service:"sts",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetCallerIdentity&Version=2011-06-15"});if(typeof t==="string"){let n=t.match(/<Account>(\d+)<\/Account>/),r=t.match(/<UserId>([^<]+)<\/UserId>/),i=t.match(/<Arn>([^<]+)<\/Arn>/);return{Account:n?.[1],UserId:r?.[1],Arn:i?.[1]}}let e=t?.GetCallerIdentityResponse?.GetCallerIdentityResult||t?.GetCallerIdentityResult;if(e)return{Account:String(e.Account),UserId:e.UserId,Arn:e.Arn};if(t?.Account)return{Account:String(t.Account),UserId:t.UserId,Arn:t.Arn};return{Account:void 0,UserId:void 0,Arn:void 0}}}
|
|
2
2
|
export{ct};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{fi,u}from"./chunk-
|
|
1
|
+
import{fi,u}from"./chunk-qe56mnjc.js";import{gi}from"./chunk-6k5g8b1w.js";import*as c from"node:crypto";import{readFileSync as B}from"node:fs";import{readdir as L}from"node:fs/promises";import{join as z}from"node:path";function vt(e){if(e){let i=D(e);if(!i)throw Error(`AWS profile '${e}' not found in ~/.aws/credentials`);return i}let t=process.env.AWS_ACCESS_KEY_ID,s=process.env.AWS_SECRET_ACCESS_KEY;if(t&&s)return{accessKeyId:t,secretAccessKey:s,sessionToken:process.env.AWS_SESSION_TOKEN};return D(process.env.AWS_PROFILE||"default")??{accessKeyId:"",secretAccessKey:""}}function D(e){let{existsSync:t,readFileSync:s}=gi("node:fs"),{homedir:i}=gi("node:os"),{join:n}=gi("node:path"),r=process.env.AWS_SHARED_CREDENTIALS_FILE||n(i(),".aws","credentials");if(!t(r))return null;let o=s(r,"utf-8"),a=null,l,d,y;for(let h of o.split(`
|
|
2
2
|
`)){let m=h.trim();if(!m||m.startsWith("#")||m.startsWith(";"))continue;let p=m.match(/^\[([^\]]+)\]$/);if(p){if(a===e&&l&&d)return{accessKeyId:l,secretAccessKey:d,sessionToken:y};a=p[1],l=void 0,d=void 0,y=void 0;continue}if(a===e){let[b,...S]=m.split("="),f=S.join("=").trim();switch(b.trim().toLowerCase()){case"aws_access_key_id":l=f;break;case"aws_secret_access_key":d=f;break;case"aws_session_token":y=f;break}}}if(a===e&&l&&d)return{accessKeyId:l,secretAccessKey:d,sessionToken:y};return null}function U(e){let{buffer:t,byteOffset:s,byteLength:i}=e;if(t instanceof ArrayBuffer)return t.slice(s,s+i);let n=new ArrayBuffer(i);return new Uint8Array(n).set(new Uint8Array(e)),n}function j(e,t){let s=e?.[t]??e;if(s===null||typeof s!=="object"||Array.isArray(s))return s;let i={...s};return delete i["@_xmlns"],i}class g{client;region;explicitProfile;endpoint;endpointProtocol="https";forcePathStyle;explicitCredentials;constructor(e="us-east-1",t,s){let i=typeof e==="string"?s:e,n=typeof e==="string"?e:e.region??"us-east-1",r=typeof e==="string"?t:e.profile,o=i?.endpoint?fi({region:n,path:"/",endpoint:i.endpoint}):void 0;this.region=n,this.explicitProfile=r,this.endpoint=o?.host,this.endpointProtocol=o?.protocol??"https",this.forcePathStyle=i?.forcePathStyle,this.explicitCredentials=i?.credentials,this.client=new u(i?.credentials,{profile:r,endpoint:i?.endpoint,forcePathStyle:i?.forcePathStyle})}getCredentials(){if(this.explicitCredentials?.accessKeyId&&this.explicitCredentials.secretAccessKey)return this.explicitCredentials;let e=vt(this.explicitProfile);if(e.accessKeyId&&e.secretAccessKey)return e;throw Error("S3 credentials not found. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY (or pass explicit credentials/profile), or configure ~/.aws/credentials.")}s3BaseHost(){return this.endpoint||`s3.${this.region}.amazonaws.com`}s3VirtualHost(e){return this.forcePathStyle?this.s3BaseHost():`${e}.${this.s3BaseHost()}`}objectPath(e,t){return this.forcePathStyle?`/${e}/${t}`:`/${t}`}objectUrl(e,t){return`${this.endpointProtocol}://${this.s3VirtualHost(e)}${this.objectPath(e,t)}`}async listBuckets(){let e=await this.client.request({service:"s3",region:this.region,method:"GET",path:"/"}),t=[],i=(e?.ListAllMyBucketsResult??e)?.Buckets?.Bucket;if(i){let n=Array.isArray(i)?i:[i];for(let r of n)t.push({Name:r.Name,CreationDate:r.CreationDate})}return{Buckets:t}}async createBucket(e,t){let s={};if(t?.acl)s["x-amz-acl"]=t.acl;let i;if(this.region!=="us-east-1"&&!this.endpoint)i=`<?xml version="1.0" encoding="UTF-8"?>
|
|
3
3
|
<CreateBucketConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
4
4
|
<LocationConstraint>${this.region}</LocationConstraint>
|