@stacksjs/ts-cloud 0.12.12 → 0.12.14
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-16rs9egs.js +6 -0
- package/dist/bin/chunk-1j2sja1j.js +1 -0
- package/dist/bin/chunk-1rcsm0px.js +1 -0
- package/dist/bin/chunk-1s4dny8d.js +1 -0
- package/dist/bin/chunk-1wvrtg42.js +8 -0
- package/dist/bin/chunk-1x7mm26k.js +1 -0
- package/dist/bin/chunk-2paqksap.js +6 -0
- package/dist/bin/chunk-3gwmejhk.js +1 -0
- package/dist/bin/chunk-4201mvaj.js +2 -0
- package/dist/bin/chunk-49sthm4q.js +2 -0
- package/dist/bin/chunk-4yntpqbe.js +1 -0
- package/dist/bin/chunk-4zbnwt9b.js +2 -0
- package/dist/{chunk-2ybcnrte.js → bin/chunk-57w9nsjk.js} +3 -3
- package/dist/bin/chunk-61ysn56t.js +1 -0
- package/dist/bin/chunk-6vay4ggv.js +9 -0
- package/dist/bin/{chunk-wcem4cqb.js → chunk-7a7n6p2m.js} +2 -2
- package/dist/bin/chunk-7x0hrna6.js +1 -0
- package/dist/bin/{chunk-e2dnxp8d.js → chunk-80zkjpfz.js} +29 -29
- package/dist/bin/chunk-92nng29y.js +1 -0
- package/dist/bin/chunk-94cfdvrn.js +2 -0
- package/dist/bin/chunk-9q8zjavc.js +725 -0
- package/dist/bin/chunk-a929za72.js +2 -0
- package/dist/{chunk-ac87ds1k.js → bin/chunk-bckm6fre.js} +6 -6
- package/dist/bin/chunk-bj5nq0kn.js +7364 -0
- package/dist/bin/chunk-c51xp8f7.js +1 -0
- package/dist/bin/chunk-d7r6mhyv.js +34 -0
- package/dist/bin/chunk-dbmk60r7.js +60 -0
- package/dist/bin/chunk-dhxwmkhz.js +2 -0
- package/dist/bin/chunk-f1ke4ygp.js +1 -0
- package/dist/bin/chunk-f35pte64.js +44 -0
- package/dist/bin/{chunk-t5ngva49.js → chunk-f8mbjwme.js} +8 -8
- package/dist/bin/chunk-fnr6k11h.js +1 -0
- package/dist/bin/chunk-mzfct5en.js +1 -0
- package/dist/bin/chunk-n6qqa2fr.js +511 -0
- package/dist/bin/chunk-ngav845g.js +2 -0
- package/dist/bin/chunk-nrnq9adz.js +1 -0
- package/dist/bin/chunk-p36ns96s.js +1 -0
- package/dist/bin/chunk-pega3x2x.js +1 -0
- package/dist/bin/chunk-pt2bz3kr.js +1 -0
- package/dist/bin/chunk-q5aj280b.js +1 -0
- package/dist/bin/chunk-r6cvc2pr.js +1 -0
- package/dist/bin/chunk-rh2sqtew.js +1 -0
- package/dist/bin/chunk-rpg5k3wt.js +3 -0
- package/dist/bin/chunk-tkzpbb7n.js +1 -0
- package/dist/bin/chunk-vwyq2s2k.js +1 -0
- package/dist/bin/chunk-vx649y7t.js +1 -0
- package/dist/bin/chunk-vymg9ywg.js +2 -0
- package/dist/bin/chunk-w637s5q0.js +3 -0
- package/dist/bin/chunk-wge61ccr.js +2 -0
- package/dist/bin/{chunk-jxd3j00s.js → chunk-wr6a423y.js} +13 -13
- package/dist/bin/chunk-y7ece16e.js +111 -0
- package/dist/bin/chunk-ydpnsp4x.js +3 -0
- package/dist/bin/{chunk-t7rcfwqc.js → chunk-yhxpmk29.js} +32 -32
- package/dist/bin/chunk-yn34zgr2.js +1 -0
- package/dist/bin/chunk-ynr22ma8.js +2 -0
- package/dist/bin/chunk-yt8rgkqt.js +2 -0
- package/dist/bin/chunk-z2ez8wn9.js +37 -0
- package/dist/bin/cli.js +428 -428
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/chunk-30h9rgfn.js +6 -0
- package/dist/chunk-3kapcdpn.js +92 -0
- package/dist/chunk-5g1hsrab.js +4 -0
- package/dist/chunk-5qqb671d.js +1 -0
- package/dist/chunk-5ww7kc5z.js +114 -0
- package/dist/chunk-6g81m01r.js +141 -0
- package/dist/{chunk-q9a1z53k.js → chunk-6j8f4ahv.js} +51 -51
- package/dist/{chunk-6cxb8d6y.js → chunk-6nvn041c.js} +3 -3
- package/dist/chunk-7hy9p6xr.js +5 -0
- package/dist/chunk-7kwha0fw.js +585 -0
- package/dist/chunk-9mhcjht7.js +37 -0
- package/dist/chunk-9w32efae.js +1 -0
- package/dist/chunk-bqaqkmtr.js +2 -0
- package/dist/chunk-djd9xgkz.js +709 -0
- package/dist/chunk-e0919h5g.js +2 -0
- package/dist/{chunk-dndxwssj.js → chunk-e7ds04wb.js} +2 -2
- package/dist/chunk-fdexq9e1.js +1 -0
- package/dist/chunk-hw3p6pth.js +1 -0
- package/dist/chunk-jb8em9ba.js +2 -0
- package/dist/chunk-pkan6evc.js +2 -0
- package/dist/chunk-qzwack6w.js +44 -0
- package/dist/chunk-r5emv4x8.js +2 -0
- package/dist/chunk-thpce63q.js +34 -0
- package/dist/chunk-ttq6dvft.js +22 -0
- package/dist/chunk-vpy3zjqv.js +1 -0
- package/dist/chunk-vva43vnp.js +60 -0
- package/dist/{bin/chunk-m9r5jype.js → chunk-wjgnfg6q.js} +6 -6
- package/dist/chunk-wrnhbb13.js +1 -0
- package/dist/chunk-xxbvjq8g.js +7355 -0
- package/dist/chunk-zftpjxkr.js +2 -0
- package/dist/deploy/index.js +1 -1
- package/dist/dns/index.js +1 -1
- package/dist/drivers/index.d.ts +1 -0
- package/dist/drivers/index.js +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +91 -91
- package/dist/operations/index.js +1 -1
- package/dist/protection/index.js +1 -1
- package/dist/push/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 +1 -1
- package/dist/ui/data/backups.html +6 -6
- package/dist/ui/data/services.html +7 -7
- package/dist/ui/data/volumes.html +6 -6
- package/dist/ui/index.html +6 -6
- package/dist/ui/infrastructure/topology.html +9 -9
- 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 +6 -6
- 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 +9 -9
- package/dist/ui/security.html +2 -2
- 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 +1 -1
- package/dist/ui/server/sites.html +17 -17
- package/dist/ui/server/ssh-keys.html +6 -6
- package/dist/ui/server/team.html +5 -5
- package/dist/ui/server/terminal.html +2 -2
- package/dist/ui/serverless/alarms.html +5 -5
- package/dist/ui/serverless/assets.html +2 -2
- package/dist/ui/serverless/cost.html +2 -2
- package/dist/ui/serverless/data.html +6 -6
- package/dist/ui/serverless/deployments.html +2 -2
- package/dist/ui/serverless/firewall.html +2 -2
- package/dist/ui/serverless/functions.html +5 -5
- 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 +5 -5
- package/dist/ui/serverless.html +6 -6
- package/dist/ui-src/src/charts.ts +1141 -1294
- package/dist/ui-src/src/topology.ts +3 -3
- package/package.json +3 -3
- package/dist/bin/chunk-0b49jjgr.js +0 -2
- package/dist/bin/chunk-0xnnkeb1.js +0 -1
- package/dist/bin/chunk-227jmf2b.js +0 -2
- package/dist/bin/chunk-2nyyg44g.js +0 -1
- package/dist/bin/chunk-2ztr119n.js +0 -3
- package/dist/bin/chunk-43xj5cny.js +0 -1
- package/dist/bin/chunk-5w6y9pmz.js +0 -1
- package/dist/bin/chunk-5x4rdx8k.js +0 -37
- package/dist/bin/chunk-6zc6a6t3.js +0 -725
- package/dist/bin/chunk-7aagqqr9.js +0 -1
- package/dist/bin/chunk-85qrgshq.js +0 -44
- package/dist/bin/chunk-8zk8msx0.js +0 -2
- package/dist/bin/chunk-9j83q0r4.js +0 -1
- package/dist/bin/chunk-9nhqbes6.js +0 -60
- package/dist/bin/chunk-a4js49mx.js +0 -1
- package/dist/bin/chunk-a9e0hvwe.js +0 -6
- package/dist/bin/chunk-a9tgxf2h.js +0 -1
- package/dist/bin/chunk-aahrv359.js +0 -1
- package/dist/bin/chunk-bfx23be3.js +0 -1
- package/dist/bin/chunk-bpps61am.js +0 -111
- package/dist/bin/chunk-bzth6d1s.js +0 -6
- package/dist/bin/chunk-ca3taw2m.js +0 -1
- package/dist/bin/chunk-cgzp0328.js +0 -1
- package/dist/bin/chunk-d2aaef9v.js +0 -1
- package/dist/bin/chunk-e0z2t4mf.js +0 -6
- package/dist/bin/chunk-empfsmdk.js +0 -2
- package/dist/bin/chunk-er3mww4m.js +0 -1
- package/dist/bin/chunk-fmp5bv0j.js +0 -3
- package/dist/bin/chunk-g3kp5ddx.js +0 -1
- package/dist/bin/chunk-grepda40.js +0 -1
- package/dist/bin/chunk-h6xqtypj.js +0 -2
- package/dist/bin/chunk-hwk9ahms.js +0 -2
- package/dist/bin/chunk-k1xw3zbm.js +0 -34
- package/dist/bin/chunk-m07s5esk.js +0 -2
- package/dist/bin/chunk-n20kbxwb.js +0 -7364
- package/dist/bin/chunk-n2fnav53.js +0 -3
- package/dist/bin/chunk-nv211m42.js +0 -8
- package/dist/bin/chunk-psgjy3z4.js +0 -1
- package/dist/bin/chunk-qmnr82da.js +0 -1
- package/dist/bin/chunk-qqpb82ty.js +0 -2
- package/dist/bin/chunk-rqc8btkj.js +0 -2
- package/dist/bin/chunk-rs85xvt7.js +0 -1
- package/dist/bin/chunk-sj5csg49.js +0 -2
- package/dist/bin/chunk-tjgy10zm.js +0 -9
- package/dist/bin/chunk-v0beqdna.js +0 -1
- package/dist/bin/chunk-vf2s3tba.js +0 -1
- package/dist/bin/chunk-vzkfjrx2.js +0 -511
- package/dist/bin/chunk-wsh5ervz.js +0 -1
- package/dist/bin/chunk-xenhbdmr.js +0 -1
- package/dist/bin/chunk-xrdpxwbf.js +0 -1
- package/dist/bin/chunk-y68m9bx7.js +0 -2
- package/dist/chunk-4884der5.js +0 -1
- package/dist/chunk-4wdxsnn2.js +0 -44
- package/dist/chunk-5hhyyhjt.js +0 -1
- package/dist/chunk-5zkacdw1.js +0 -1
- package/dist/chunk-6f68caq0.js +0 -1
- package/dist/chunk-7z50g5xz.js +0 -4
- package/dist/chunk-8fh4m5ge.js +0 -1
- package/dist/chunk-97pb7wb1.js +0 -1
- package/dist/chunk-ea7tn8nn.js +0 -709
- package/dist/chunk-ess6vxfj.js +0 -2
- package/dist/chunk-j06r5rwv.js +0 -2
- package/dist/chunk-j1g67djb.js +0 -92
- package/dist/chunk-k8x8mrkr.js +0 -2
- package/dist/chunk-mnmz8t7q.js +0 -34
- package/dist/chunk-n1fyryha.js +0 -141
- package/dist/chunk-n1hg0jxs.js +0 -2
- package/dist/chunk-n5xmh0ma.js +0 -37
- package/dist/chunk-q22qfwsc.js +0 -22
- package/dist/chunk-r8t25tbm.js +0 -7355
- package/dist/chunk-t8hzekmk.js +0 -585
- package/dist/chunk-whyttetx.js +0 -5
- package/dist/chunk-yf8stygs.js +0 -114
- package/dist/chunk-ze5x2bpm.js +0 -2
- package/dist/chunk-zh0apedk.js +0 -60
- package/dist/chunk-zjyz926j.js +0 -2
package/dist/aws/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{le,Jt,zi,Ki,Hl,ya,Ia,Wi,Ji,Sa,ze,V,Ke,te,C,ue,rn,Ca,De,ba,nn,sn,on,wm,Rm,PA,NA,kA,BA,At,xA,_A,OA,LA,yt,Dm,Pm,Nm,It,km,Bm,xm,an,$A,MA,FA,Xt,UA,QA,HA,Ea,va,Gl,GA,qA,VA,Yt,_m,Om,Zt,We,cn,Ta,ql,jA,Vl,zA,St,KA,WA,JA,XA,re,YA,ZA,ey,ty,er,ry,ny,iy,dn,wa,Ra,jl,zl,Da,tr}from"../chunk-5ww7kc5z.js";import{pe,Je,ln,Lm}from"../chunk-thpce63q.js";import{y}from"../chunk-6g81m01r.js";import{Pe}from"../chunk-r5emv4x8.js";import{j}from"../chunk-zftpjxkr.js";import{un,Ne,Ct,bt,Et,pn,Yi,Zi,ge,es,ts,rs,ns,ne,is,ss,os,T,Pa,gn,Na,ie,rr}from"../chunk-pkan6evc.js";import{h}from"../chunk-wjgnfg6q.js";import{gr,Ie}from"../chunk-6nvn041c.js";import{f}from"../chunk-jb8em9ba.js";import{a}from"../chunk-3kapcdpn.js";import{mr,n,l,th}from"../chunk-30h9rgfn.js";export{ie as ACMClient,rr as ACMDnsValidator,n as AWSClient,Ta as ApplicationAutoScalingClient,Jt as AwsBackupClient,Rm as BedrockAgentClient,wm as BedrockAgentRuntimeClient,on as BedrockClient,sn as BedrockRuntimeClient,f as CloudFormationClient,y as CloudFrontClient,ue as CloudWatchLogsClient,bt as CloudflareProvider,At as ComprehendClient,rn as ConnectClient,Ji as CostExplorerClient,gn as DnsProviderFactory,De as DynamoDBClient,gr as EC2Client,Pe as ECRClient,ze as ECSClient,tr as EFSClient,Ca as ELBv2Client,We as ElastiCacheClient,ln as EmailClient,Zt as EventBridgeClient,Ct as GoDaddyProvider,pe as IAMClient,ql as ImapServer,Yt as KendraClient,C as LambdaClient,ba as OpenSearchClient,un as PROXIABLE_RECORD_TYPES,Ea as PersonalizeClient,Gl as PersonalizeEventsClient,va as PersonalizeRuntimeClient,an as PollyClient,Ne as PorkbunProvider,j as RDSClient,yt as RekognitionClient,h as Route53Client,Sa as Route53DomainsClient,ge as Route53Provider,a as S3Client,Je as SESClient,Ke as SNSClient,te as SQSClient,Ie as SSMClient,le as STSClient,cn as SchedulerClient,V as SecretsManagerClient,St as SmsClient,Da as SmsVoiceClient,Vl as SmtpServer,dn as SupportClient,wa as SupportTemplates,It as TextractClient,nn as TranscribeClient,Xt as TranslateClient,ne as UnifiedDnsValidator,er as VoiceClient,xA as analyzeSentiment,rs as applyZoneMigration,l as buildQueryParams,kA as completeWithClaude,LA as containsPii,Pm as countFacesInS3Image,XA as createDeliveryReceiptHandler,T as createDnsProvider,ss as createGoDaddyValidator,Wi as createObjectStorageClient,is as createPorkbunValidator,ny as createRecordingHandler,os as createRoute53Validator,FA as createSSML,WA as createScheduledSmsHandler,JA as createSmsClient,KA as createSmsInboxHandler,zl as createSmsInfrastructure,iy as createVoiceClient,ry as createVoicemailHandler,th as detectCredentialSource,Pa as detectDnsProvider,Dm as detectLabelsFromS3,OA as detectLanguage,Na as dnsProviders,Lm as email,es as exportRoute53Zone,_A as extractEntities,Bm as extractFormsFromS3,xm as extractTablesFromS3,km as extractTextFromS3,YA as formatPhoneNumber,BA as generateEmbeddings,ey as getCountryCode,GA as getRecommendations,qA as getSimilarItems,jl as getSmsInfrastructureStatus,Nm as isContentSafe,ty as isSamePhoneNumber,ZA as isValidPhoneNumber,Ki as keyMatchesFilters,NA as listClaudeModels,HA as listLanguages,MA as listVoices,Hl as migrateObjectStorage,re as normalizePhoneNumber,ts as planZoneMigration,Et as policyTag,ya as providerEndpoint,pn as qualifyName,Zi as reconcileDeclaredRecords,zi as remapKey,PA as requestModelAccess,Yi as resolveDeclaredRecords,Ia as resolveObjectStorage,mr as resolveS3Endpoint,Om as retrieveForRag,_m as search,Ra as setupSmsInfrastructure,jA as startImapServer,zA as startSmtpServer,$A as textToSpeech,VA as trackEvent,UA as translate,QA as translateToMultiple,ns as verifyZoneParity};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{Ke,A,Ft,Cr,hi}from"./chunk-bj5nq0kn.js";import{execSync as D}from"node:child_process";import{randomBytes as R}from"node:crypto";import{chmodSync as j,copyFileSync as x,existsSync as u,mkdirSync as w,readFileSync as U,statSync as N,writeFileSync as m}from"node:fs";import{tmpdir as E}from"node:os";import{basename as P,dirname as v,isAbsolute as O,join as a,resolve as B}from"node:path";import{fileURLToPath as C}from"node:url";function h(e){if(!e||typeof e!=="object")return e;return Object.fromEntries(Object.keys(e).map((r)=>[r,""]))}function M(e){let r=JSON.parse(JSON.stringify(e??{}));if(r.hetzner)delete r.hetzner.apiToken;delete r.aws,delete r.stateDir;for(let t of Object.values(r.sites??{})){if(t?.env)t.env=h(t.env);if(t?.environment)t.environment=h(t.environment)}for(let t of Object.values(r.environments??{}))if(t?.variables)t.variables=h(t.variables);for(let t of Object.values(r.infrastructure?.databases??{}))if(t?.password)t.password="";if(r.infrastructure?.appDatabase?.password)r.infrastructure.appDatabase.password="";if(r.infrastructure?.compute?.database?.password)r.infrastructure.compute.database.password="";if(r.infrastructure?.compute?.managedServices?.vitess?.password)r.infrastructure.compute.managedServices.vitess.password="";return r}function y(e){let r=M(e);return["// Generated by ts-cloud for the management dashboard — do not edit.","//","// This is the project's resolved cloud config, inlined so it needs no","// imports on the box. Credentials are deliberately absent.",`export default ${JSON.stringify(r,null,2)}`,""].join(`
|
|
2
|
+
`)}var Jl="dashboard";function La(){return Ke("dashboard-credentials.json")}function F(){return R(24).toString("base64url")}function Xl(e,r,t){let s=process.env.TS_CLOUD_UI_PASSWORD?.trim();if(s)return{password:s,source:"env"};if(b(process.env.TS_CLOUD_UI_PUBLIC))return{password:void 0,source:"public"};let n=La(),i=A(e,"dashboard-credentials.json");try{if(u(i)){let o=JSON.parse(U(i,"utf8"));if(o?.password)return{password:o.password,source:"generated"}}}catch{}let d=F();try{w(v(i),{recursive:!0}),m(i,`${JSON.stringify({username:r,password:d,generatedAt:new Date().toISOString()},null,2)}
|
|
3
|
+
`),j(i,384),t.info(`Management dashboard: generated a password for '${r}' and saved it to ${n} (read it there — it is not printed). Set TS_CLOUD_UI_PASSWORD to pin your own, or TS_CLOUD_UI_PUBLIC=1 to serve without auth.`)}catch(o){t.warn(`Management dashboard: could not persist the generated password (${o?.message??o}). Using it for this deploy only — pass: ${d}
|
|
4
|
+
This password is now in your deploy log. Set TS_CLOUD_UI_PASSWORD to a value of your own and redeploy once ${n} is writable.`)}return{password:d,source:"generated"}}var I={info:()=>{},warn:()=>{}};function b(e){return e!=null&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function J(){return Ke("dashboard-release")}function L(){let e=v(C(import.meta.url));for(let r of[a(e,"..","..","package.json"),a(e,"..","package.json")])try{let t=JSON.parse(U(r,"utf8"));if(t.name==="@stacksjs/ts-cloud"&&t.version)return`^${t.version}`}catch{}return"latest"}function z(){return process.env.TS_CLOUD_UI_VERSION?.trim()||L()}function V(e,r,t){if(!e?.project?.slug)return t.warn("Management dashboard: the cloud config has no project slug — skipping the live dashboard."),null;let s=A(r,"dashboard-release");try{w(s,{recursive:!0}),m(a(s,"cloud.config.ts"),y(e));let n=z();if(n.startsWith("file:")){let d=n.slice(5),o=O(d)?d:B(r,d);if(!u(o)||!N(o).isFile())n=L(),t.warn(`Management dashboard: TS_CLOUD_UI_VERSION points to a missing package file (${o}); using the deploying ts-cloud version ${n} instead.`);else{let c=P(o),l=a(s,c);if(o!==l)x(o,l);n=`file:./${c}`}}let i={name:"ts-cloud-dashboard",private:!0,type:"module",dependencies:{"@stacksjs/ts-cloud":n}};return m(a(s,"package.json"),`${JSON.stringify(i,null,2)}
|
|
5
|
+
`),J()}catch(n){return t.warn(`Management dashboard: could not stage the live release (${n?.message??n}) — skipping.`),null}}function no(e){if(u(a(e,"packages","ui","pages"))||u(a(e,"packages","ui","package.json")))return{uiRoot:"packages/ui/dist",build:"cd packages/ui && bun install && bun run build"};let r=v(C(import.meta.url)),t=[a(r,"ui"),a(r,"..","ui"),a(r,"..","..","ui"),a(r,"..","dist","ui")];for(let s of t)if(u(a(s,"index.html"))||u(a(s,"serverless.html")))return{uiRoot:s,build:!1};return null}function io(e,r={}){let t=r.logger??I,s=r.cwd??process.cwd();if(b(process.env.TS_CLOUD_UI_DISABLE))return t.info("Management dashboard: skipped (TS_CLOUD_UI_DISABLE set)."),e;if(e.cloud?.attachTo)return t.info(`Management dashboard: ${e.project.slug} is attached to ${e.cloud.attachTo}; the server owner's dashboard monitors every attached project.`),e;if(Ft(e))return e;let n=e.environments&&Object.keys(e.environments)[0],i=process.env.TS_CLOUD_UI_DOMAIN?.trim()||void 0,d=Number(process.env.TS_CLOUD_UI_PORT)||void 0,o={...e.sites??{}};if(!b(process.env.TS_CLOUD_UI_STATIC)){let g=V(e,s,t);if(!g)return e;let p=hi(e,n??"production",{uiRoot:g,build:!1,domain:i,port:d,live:!0});if(p.length===0)return t.info("Management dashboard: no domain resolved (set TS_CLOUD_UI_DOMAIN or configure a site domain) — skipping."),e;for(let{name:k,site:_}of p)o[k]=_,t.info(`Management dashboard → https://${_.domain} (sign in with your ts-cloud account; the first deploy prints an admin password once)`);return e.sites=o,e}let c=no(s);if(!c)return t.info("Management dashboard: UI not found (no local ui/ or packaged dist/ui) — skipping auto-deploy."),e;let l=process.env.TS_CLOUD_UI_USERNAME?.trim()||"admin",f=Xl(s,l,t),S=hi(e,n??"production",{uiRoot:c.uiRoot,build:c.build,domain:i,username:l,password:f.password,realm:process.env.TS_CLOUD_UI_REALM?.trim()||void 0,live:!1,port:d});if(S.length===0)return t.info("Management dashboard: no domain resolved (set TS_CLOUD_UI_DOMAIN or configure a site domain) — skipping."),e;let T=f.source==="public"?"NO AUTH — TS_CLOUD_UI_PUBLIC is set (dashboard is publicly reachable)":f.source==="env"?"htpasswd-protected (TS_CLOUD_UI_PASSWORD)":`htpasswd-protected (auto-generated — see ${La()})`;t.warn("Management dashboard: static mode — one shared password, and no per-site collaborators. Unset TS_CLOUD_UI_STATIC for the live dashboard.");for(let{name:g,site:p}of S)o[g]=p,t.info(`Management dashboard → https://${p.domain} (${T})`);return e.sites=o,e}function oo(e){return Object.keys(e.sites??{}).filter(Cr)}function ms(e,r){if(!e?.root)return null;let t=r.cwd??process.cwd(),s=r.logger??I;try{if(typeof e.build==="string"&&e.build.trim())s.info(`Management dashboard: building UI (${e.build})`),D(e.build,{cwd:t,stdio:"inherit"});let n=O(e.root)?e.root:a(t,e.root);if(!u(n))return s.warn(`Management dashboard: build output not found at ${n} — skipping dashboard artifact.`),null;let i=a(E(),`${r.slug}-${r.siteName??Jl}-${r.sha}.tar.gz`);return D(`tar czf "${i}" -C "${n}" .`,{stdio:"inherit"}),i}catch(n){return s.warn(`Management dashboard: failed to build artifact — ${n?.message??n}. Skipping dashboard deploy.`),null}}
|
|
6
|
+
export{Jl,La,Xl,no,io,oo,ms};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{_o}from"./chunk-94cfdvrn.js";export{_o as encodeDashboardPayload};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Cl,Al,Il,Rl,du,uu}from"./chunk-dbmk60r7.js";import"./chunk-ngav845g.js";import"./chunk-yhxpmk29.js";import"./chunk-vymg9ywg.js";import"./chunk-57w9nsjk.js";import"./chunk-80zkjpfz.js";import"./chunk-bckm6fre.js";export{du as deleteStaticSite,Al as deployStaticSite,uu as deployStaticSiteFull,Cl as generateStaticSiteTemplate,Rl as invalidateCache,Il as uploadStaticFiles};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{F}from"./chunk-dhxwmkhz.js";import"./chunk-bckm6fre.js";export{F as SQSClient};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{h}from"./chunk-wr6a423y.js";var y=(e)=>e==null?void 0:String(e),w=(e)=>Number(e)===1,C=(e,r)=>{try{return e==null?r:JSON.parse(String(e))}catch{return r}};function b(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),scope:{type:String(e.scope_type),id:String(e.scope_id),environmentId:y(e.environment_id),resourceId:y(e.resource_id),previewId:y(e.preview_id)},key:String(e.key),kind:String(e.kind),value:y(e.value),valueFingerprint:String(e.value_fingerprint),secretRef:y(e.secret_ref),backend:String(e.backend),backendVersion:y(e.backend_version),origin:String(e.origin),required:w(e.required),metadata:C(e.metadata,{}),lastUsedAt:y(e.last_used_at),rotatedAt:y(e.rotated_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function I(e){return{entryId:String(e.entry_id),resourceId:String(e.resource_id),injectionTarget:String(e.injection_target),required:w(e.required),requiresRedeploy:w(e.requires_redeploy),lastDeployedVersion:e.last_deployed_version==null?void 0:Number(e.last_deployed_version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}class hr{controlPlane;now;constructor(e,r=()=>new Date){this.controlPlane=e;this.now=r}get(e){let r=this.controlPlane.database.query("SELECT * FROM configuration_entries WHERE id=?").get(e);return r?b(r):void 0}find(e,r,n){let t=this.controlPlane.database.query("SELECT * FROM configuration_entries WHERE project_id=? AND scope_type=? AND scope_id=? AND key=?").get(e,r.type,r.id,n);return t?b(t):void 0}list(e){let r=["project_id=?"],n=[e.projectId];if(e.scope)r.push("scope_type=?","scope_id=?"),n.push(e.scope.type,e.scope.id);if(e.kind)r.push("kind=?"),n.push(e.kind);return this.controlPlane.database.query(`SELECT * FROM configuration_entries WHERE ${r.join(" AND ")} ORDER BY key,scope_type,scope_id`).all(...n).map(b)}create(e){this.validateScope(e),this.validateEntry(e);let r=crypto.randomUUID(),n=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO configuration_entries (id,organization_id,project_id,scope_type,scope_id,environment_id,resource_id,preview_id,key,kind,value,value_fingerprint,secret_ref,backend,backend_version,origin,required,metadata,last_used_at,rotated_at,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[r,e.organizationId,e.projectId,e.scope.type,e.scope.id,e.scope.environmentId??null,e.scope.resourceId??null,e.scope.previewId??null,e.key,e.kind,e.value??null,e.valueFingerprint,e.secretRef??null,e.backend,e.backendVersion??null,e.origin,e.required?1:0,JSON.stringify(e.metadata),e.lastUsedAt??null,e.rotatedAt??null,1,n,n]),this.get(r)}update(e,r,n){let t=this.get(e);if(!t)throw Error("Configuration entry was not found.");if(this.validateEntry({...t,...n}),this.controlPlane.database.run("UPDATE configuration_entries SET value=?,value_fingerprint=?,secret_ref=?,backend=?,backend_version=?,required=?,metadata=?,rotated_at=?,version=version+1,updated_at=? WHERE id=? AND version=?",[n.value??null,n.valueFingerprint,n.secretRef??null,n.backend,n.backendVersion??null,n.required?1:0,JSON.stringify(n.metadata),n.rotatedAt??null,this.now().toISOString(),e,r]).changes!==1)throw Error("Configuration entry changed; refresh and retry.");return this.get(e)}remove(e,r){let n=this.get(e);if(!n)throw Error("Configuration entry was not found.");if(n.version!==r)throw Error("Configuration entry changed; refresh and retry.");if(this.controlPlane.database.run("DELETE FROM configuration_entries WHERE id=? AND version=?",[e,r]).changes<1)throw Error("Configuration entry changed; refresh and retry.");return n}setDependency(e){let r=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO configuration_dependencies (entry_id,resource_id,injection_target,required,requires_redeploy,last_deployed_version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?) ON CONFLICT(entry_id,resource_id) DO UPDATE SET injection_target=excluded.injection_target,required=excluded.required,requires_redeploy=excluded.requires_redeploy,last_deployed_version=excluded.last_deployed_version,updated_at=excluded.updated_at",[e.entryId,e.resourceId,e.injectionTarget,e.required?1:0,e.requiresRedeploy?1:0,e.lastDeployedVersion??null,r,r]),this.dependencies(e.entryId).find((n)=>n.resourceId===e.resourceId)}dependencies(e){return this.controlPlane.database.query("SELECT * FROM configuration_dependencies WHERE entry_id=? ORDER BY resource_id").all(e).map(I)}dependenciesForResource(e){return this.controlPlane.database.query("SELECT * FROM configuration_dependencies WHERE resource_id=? ORDER BY entry_id").all(e).map(I)}mutation(e){let r=this.controlPlane.database.query("SELECT request_hash,result FROM configuration_mutations WHERE idempotency_key=?").get(e);return r?{requestHash:r.request_hash,result:C(r.result,{})}:void 0}recordMutation(e){this.controlPlane.database.run("INSERT INTO configuration_mutations (id,project_id,idempotency_key,request_hash,result,actor_id,created_at) VALUES (?,?,?,?,?,?,?)",[crypto.randomUUID(),e.projectId,e.idempotencyKey,e.requestHash,JSON.stringify(e.result),e.actorId??null,this.now().toISOString()])}validateEntry(e){if(!/^[A-Za-z_][A-Za-z0-9_]{0,255}$/.test(e.key))throw Error(`Invalid configuration key: ${e.key}`);if(e.kind==="variable"&&(e.value==null||e.secretRef||e.backend!=="plaintext"))throw Error("Variables require a plaintext value and cannot use a secret backend.");if(e.kind==="secret"&&(e.value!=null||!e.secretRef||e.backend==="plaintext"))throw Error("Secrets require a non-plaintext backend reference and cannot store a plaintext value.")}validateScope(e){let r=this.controlPlane.getProject(e.projectId);if(!r||r.organizationId!==e.organizationId)throw Error("Configuration project does not belong to the organization.");let n=e.scope;if(n.type==="project"){if(n.id!==e.projectId||n.environmentId||n.resourceId||n.previewId)throw Error("Project configuration scope must reference only its project.");return}if(n.type==="environment"){let i=this.controlPlane.database.query("SELECT project_id FROM environments WHERE id=?").get(n.id);if(!i||i.project_id!==e.projectId||n.environmentId&&n.environmentId!==n.id||n.resourceId||n.previewId)throw Error("Environment configuration scope does not belong to the project.");return}if(n.type==="service"||n.type==="function"){let i=this.controlPlane.getResource(n.id);if(!i||i.projectId!==e.projectId||n.type==="function"&&i.kind!=="function"||n.resourceId&&n.resourceId!==n.id||n.environmentId&&i.environmentId!==n.environmentId||n.previewId)throw Error(`${n.type==="function"?"Function":"Service"} configuration scope does not belong to the project.`);return}let t=this.controlPlane.database.query("SELECT project_id,base_environment_id,resource_id FROM preview_instances WHERE id=?").get(n.id);if(!t||t.project_id!==e.projectId||n.previewId&&n.previewId!==n.id||n.environmentId&&n.environmentId!==t.base_environment_id||n.resourceId&&n.resourceId!==t.resource_id)throw Error("Preview configuration scope does not belong to the project.")}}var E=/^[A-Za-z_][A-Za-z0-9_]{0,255}$/;function j(e){let r={n:`
|
|
2
|
+
`,r:"\r",t:"\t","\\":"\\",'"':'"',$:"$"};return e.replace(/\\(n|r|t|\\|"|\$)/g,(n,t)=>r[t])}function qa(e){let r={},n=[],t=e.replace(/\r\n?/g,`
|
|
3
|
+
`).split(`
|
|
4
|
+
`);for(let i=0;i<t.length;i++){let s=i+1,c=t[i];if(!c.trim()||c.trimStart().startsWith("#"))continue;if(/^\s*export\s+/.test(c))c=c.replace(/^\s*export\s+/,"");let u=c.match(/^\s*([^=\s]+)\s*=\s*(.*)$/);if(!u){n.push({line:s,severity:"error",code:"invalid_line",message:"Expected KEY=VALUE."});continue}let o=u[1],a=u[2];if(!E.test(o)){n.push({line:s,key:o,severity:"error",code:"invalid_key",message:`Invalid environment variable name: ${o}`});continue}let d=a;if(a.startsWith('"')||a.startsWith("'")){let g=a[0],l=[a.slice(1)],v=!1;while(!0){let f=l[l.length-1],m=!1,S=-1;for(let k=0;k<f.length;k++){if(g==='"'&&f[k]==="\\"&&!m){m=!0;continue}if(f[k]===g&&!m){S=k;break}m=!1}if(S>=0){l[l.length-1]=f.slice(0,S),v=!0;break}if(++i>=t.length)break;l.push(t[i])}if(!v){n.push({line:s,key:o,severity:"error",code:"unterminated_quote",message:`Unterminated quoted value for ${o}.`});continue}if(d=l.join(`
|
|
5
|
+
`),g==='"')d=j(d)}else d=a.replace(/\s+#.*$/,"").trim();if(Object.hasOwn(r,o)){let g=r[o]!==d;if(n.push({line:s,key:o,severity:g?"error":"warning",code:g?"conflict":"duplicate",message:g?`${o} has conflicting values.`:`${o} is duplicated with the same value.`}),g)continue}r[o]=d}return{values:r,diagnostics:n,valid:!n.some((i)=>i.severity==="error")}}function Ha(e){return Object.entries(e).sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>{if(!E.test(r))throw Error(`Invalid environment variable name: ${r}`);return`${r}=${JSON.stringify(n)}`}).join(`
|
|
6
|
+
`)+(Object.keys(e).length?`
|
|
7
|
+
`:"")}import{createCipheriv as x,createDecipheriv as P,createHash as _,randomBytes as q}from"node:crypto";class St{controlPlane;now;kind="local_encrypted";key;constructor(e,r,n=()=>new Date){this.controlPlane=e;this.now=n;if(!r)throw Error("Configuration encryption key is required.");this.key=_("sha256").update(`ts-cloud:configuration:${r}`).digest()}encrypt(e){let r=q(12),n=x("aes-256-gcm",this.key,r),t=Buffer.concat([n.update(e,"utf8"),n.final()]);return`v1.${r.toString("base64url")}.${n.getAuthTag().toString("base64url")}.${t.toString("base64url")}`}decrypt(e){let[r,n,t,i]=e.split(".");if(r!=="v1"||!n||!t||!i)throw Error("Encrypted configuration secret is unavailable.");try{let s=P("aes-256-gcm",this.key,Buffer.from(n,"base64url"));return s.setAuthTag(Buffer.from(t,"base64url")),Buffer.concat([s.update(Buffer.from(i,"base64url")),s.final()]).toString("utf8")}catch{throw Error("Encrypted configuration secret could not be decrypted.")}}async put(e){if(!e.value)throw Error("Configuration secrets cannot be empty.");let r=e.reference??`secret://configuration/${e.name}/${crypto.randomUUID()}`;if(!/^secret:\/\/configuration\/[A-Za-z0-9._/-]+$/.test(r))throw Error("Invalid local configuration secret reference.");let t=(this.controlPlane.database.query("SELECT version FROM configuration_secret_values WHERE reference=?").get(r)?.version??0)+1,i=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO configuration_secret_values (reference,ciphertext,fingerprint,version,created_at,updated_at) VALUES (?,?,?,?,?,?) ON CONFLICT(reference) DO UPDATE SET ciphertext=excluded.ciphertext,fingerprint=excluded.fingerprint,version=excluded.version,updated_at=excluded.updated_at",[r,this.encrypt(e.value),_("sha256").update(e.value).digest("hex"),t,i,i]),{reference:r,version:String(t)}}async resolve(e){let r=this.controlPlane.database.query("SELECT ciphertext FROM configuration_secret_values WHERE reference=?").get(e);if(!r)throw Error("Configuration secret was not found.");return this.decrypt(r.ciphertext)}async remove(e){this.controlPlane.database.run("DELETE FROM configuration_secret_values WHERE reference=?",[e])}async validate(e){return!!this.controlPlane.database.query("SELECT 1 AS found FROM configuration_secret_values WHERE reference=?").get(e)}}class yr{client;region;kind="aws_secrets_manager";constructor(e,r){this.client=e;this.region=r}async put(e){if(e.reference){let n=this.id(e.reference),t=await this.client.putSecretValue({SecretId:n,SecretString:e.value,ClientRequestToken:e.idempotencyKey});return{reference:e.reference,version:t.VersionId??e.idempotencyKey}}let r=await this.client.createSecret({Name:e.name,SecretString:e.value,ClientRequestToken:e.idempotencyKey,Tags:[{Key:"managed-by",Value:"ts-cloud"}]});return{reference:`aws-sm://${this.region}/${encodeURIComponent(r.ARN??r.Name??e.name)}`,version:r.VersionId??e.idempotencyKey}}async resolve(e){let r=await this.client.getSecretValue({SecretId:this.id(e)});if(r.SecretString==null)throw Error("AWS Secrets Manager value is unavailable.");return r.SecretString}async remove(e){await this.client.deleteSecret({SecretId:this.id(e),RecoveryWindowInDays:7})}async validate(e){try{return await this.client.describeSecret(this.id(e)),!0}catch{return!1}}id(e){let r=new URL(e);if(r.protocol!=="aws-sm:"||r.hostname!==this.region)throw Error("Invalid AWS Secrets Manager reference.");return decodeURIComponent(r.pathname.slice(1))}}class Sr{client;region;kind="aws_ssm";constructor(e,r){this.client=e;this.region=r}async put(e){let r=e.reference?this.name(e.reference):`/${e.name.replace(/^\/+/,"")}`,n=await this.client.putParameter({Name:r,Value:e.value,Type:"SecureString",Overwrite:!!e.reference,Description:"Managed by ts-cloud"});return{reference:`aws-ssm://${this.region}${r}`,version:String(n.Version??1)}}async resolve(e){let r=await this.client.getParameter({Name:this.name(e),WithDecryption:!0});if(r.Parameter?.Value==null)throw Error("AWS SSM parameter value is unavailable.");return r.Parameter.Value}async remove(e){await this.client.deleteParameter({Name:this.name(e)})}async validate(e){try{return!!(await this.client.getParameter({Name:this.name(e),WithDecryption:!1})).Parameter}catch{return!1}}name(e){let r=new URL(e);if(r.protocol!=="aws-ssm:"||r.hostname!==this.region||!r.pathname.startsWith("/"))throw Error("Invalid AWS SSM reference.");return r.pathname}}class br{kind="external";async put(){throw Error("External secret references cannot be written by ts-cloud.")}async resolve(){throw Error("External secrets must be resolved by the deployment provider.")}async remove(){}async validate(e){return/^(?:vault|doppler|op|external):\/\//.test(e)}}import{createHmac as A}from"node:crypto";var D=/^(?:secret|aws-sm|aws-ssm|vault|doppler|op|external):\/\//,O=/^(?:AWS_|TS_CLOUD_|PORT$|HOST$)/;function p(e){return[...new Set(e)].sort()}function R(e,r={}){let n=e.kind==="secret";return{id:e.id,key:e.key,kind:e.kind,scope:e.scope,inherited:!!r.inherited,overridden:!!r.overridden,required:e.required,backend:!n||r.canReadSecretMetadata?e.backend:void 0,backendVersion:!n||r.canReadSecretMetadata?e.backendVersion:void 0,reference:n&&r.canReadSecretMetadata?e.secretRef:void 0,value:!n?e.value:void 0,lastUsedAt:e.lastUsedAt,rotatedAt:e.rotatedAt,version:e.version,updatedAt:e.updatedAt}}class vr{store;backends=new Map;fingerprintKey;now;constructor(e,r){if(this.store=e,this.fingerprintKey=r.fingerprintKey??r.encryptionKey,this.now=r.now??(()=>new Date),!this.fingerprintKey)throw Error("Configuration fingerprint key is required.");let n=r.backends??[new St(e.controlPlane,r.encryptionKey,this.now)];for(let t of n)this.backends.set(t.kind,t)}list(e){let r=e.search?.toLowerCase();return this.store.list(e).filter((n)=>!r||n.key.toLowerCase().includes(r)).map((n)=>R(n,{canReadSecretMetadata:e.canReadSecretMetadata}))}plan(e){let r=this.store.list({projectId:e.projectId,scope:e.scope}),n=new Map(r.map((o)=>[o.key,o])),t=[],i=[],s=[],c=[];for(let[o,a]of Object.entries(e.values)){t.push(...this.warnings(o,a));let d=n.get(o);if(!d)i.push(o);else if(d.valueFingerprint!==this.fingerprint(a))s.push(o);else c.push(o)}let u=e.removeMissing?r.filter((o)=>!Object.hasOwn(e.values,o.key)).map((o)=>o.key):[];return{added:p(i),changed:p(s),removed:p(u),unchanged:p(c),affectedResourceIds:this.affectedResources(e.projectId,e.scope,[...i,...s,...u]),warnings:t}}async set(e){let r=this.requestHash(e),n=e.idempotencyKey;if(n){let f=this.store.mutation(n);if(f){if(f.requestHash!==r)throw Error("Idempotency key was already used for a different configuration mutation.");let m=this.store.get(String(f.result.entryId??""));if(!m)throw Error("Idempotent configuration result is no longer available.");return{entry:m,mutation:f.result.mutation,warnings:[]}}}if(e.value!=null&&D.test(e.value))throw Error("Secret references must use the reference field, not a plaintext value field.");let t=this.store.find(e.projectId,e.scope,e.key),i=this.fingerprint(e.value??e.reference??"");if(t&&e.expectedVersion!=null&&t.version!==e.expectedVersion)throw Error("Configuration entry changed; refresh and retry.");if(t&&t.kind!==e.kind)throw Error("Delete the existing entry before changing between variable and secret kinds.");let s=e.kind==="variable"?"plaintext":e.backend??(e.reference?"external":"local_encrypted");if(!!t&&(t.valueFingerprint!==i||t.backend!==s||t.required!==!!e.required)&&(this.isProduction(t)||this.store.dependencies(t.id).length>0)&&!e.confirmed)throw Error("Confirmation is required because this replacement affects production or dependent services.");let u=e.reference,o;if(e.kind==="secret"){let f=this.backend(s);if(e.reference&&e.value==null){if(!await f.validate(e.reference))throw Error("Secret backend reference is unavailable or invalid.");o=t?.backendVersion??"external"}else{if(e.value==null)throw Error("A secret value or external reference is required.");let m=await f.put({reference:t?.backend===s?t.secretRef:void 0,name:this.backendName(e),value:e.value,idempotencyKey:n??crypto.randomUUID()});u=m.reference,o=m.version}}let a=e.kind==="variable"?e.value:void 0;if(e.kind==="variable"&&a==null)throw Error("A variable value is required.");let d=!t||t.valueFingerprint!==i||t.backend!==s||t.secretRef!==u||t.backendVersion!==o||t.required!==!!e.required,g=t?d?this.store.update(t.id,t.version,{value:a,valueFingerprint:i,secretRef:u,backend:s,backendVersion:o,required:!!e.required,metadata:h(e.metadata??t.metadata),rotatedAt:e.kind==="secret"?this.now().toISOString():t.rotatedAt}):t:this.store.create({organizationId:e.organizationId,projectId:e.projectId,scope:e.scope,key:e.key,kind:e.kind,value:a,valueFingerprint:i,secretRef:u,backend:s,backendVersion:o,origin:e.origin??"managed",required:!!e.required,metadata:h(e.metadata??{}),rotatedAt:e.kind==="secret"?this.now().toISOString():void 0}),l=this.affectedResources(e.projectId,e.scope,[e.key]),v={added:t?[]:[e.key],changed:t&&d?[e.key]:[],removed:[],unchanged:t&&!d?[e.key]:[],affectedResourceIds:l,versions:{[e.key]:g.version}};if(n)this.store.recordMutation({projectId:e.projectId,idempotencyKey:n,requestHash:r,actorId:e.actorId,result:{entryId:g.id,mutation:v}});return this.audit(e.projectId,e.actorId,t&&d?"configuration.updated":t?"configuration.unchanged":"configuration.created",g,l),{entry:g,mutation:v,warnings:this.warnings(e.key,e.value??"")}}async importDotenv(e){let r=qa(e.source);if(!r.valid)return{document:r,warnings:[]};let n=new Set(e.secretKeys??[]),t={added:[],changed:[],removed:[],unchanged:[],affectedResourceIds:[],versions:{}},i=[];for(let[s,c]of Object.entries(r.values)){let u=await this.set({...e,source:void 0,key:s,value:c,kind:n.has(s)?"secret":"variable",idempotencyKey:e.idempotencyKey?`${e.idempotencyKey}:${s}`:void 0});t.added.push(...u.mutation.added),t.changed.push(...u.mutation.changed),t.unchanged.push(...u.mutation.unchanged),t.affectedResourceIds.push(...u.mutation.affectedResourceIds),Object.assign(t.versions,u.mutation.versions),i.push(...u.warnings)}return t.added=p(t.added),t.changed=p(t.changed),t.unchanged=p(t.unchanged),t.affectedResourceIds=p(t.affectedResourceIds),{document:r,mutation:t,warnings:i}}exportVariables(e){return Ha(Object.fromEntries(this.store.list({projectId:e.projectId,scope:e.scope,kind:"variable"}).map((r)=>[r.key,r.value??""])))}async transfer(e){let r=this.store.get(e.entryId);if(!r)throw Error("Configuration entry was not found.");if(r.scope.type===e.targetScope.type&&r.scope.id===e.targetScope.id)throw Error("Choose a different destination scope.");let n=r.kind==="variable"?r.value:r.backend==="external"?void 0:await this.backend(r.backend).resolve(r.secretRef),t=r.kind==="secret"?r.backend:void 0,i=await this.set({organizationId:r.organizationId,projectId:r.projectId,scope:e.targetScope,key:r.key,kind:r.kind,value:n,reference:r.backend==="external"?r.secretRef:void 0,backend:t,required:r.required,metadata:r.metadata,confirmed:e.confirmed,actorId:e.actorId,idempotencyKey:e.idempotencyKey?`${e.idempotencyKey}:copy`:void 0,origin:r.origin});if(e.mode==="move")await this.remove({entryId:r.id,expectedVersion:r.version,confirmed:e.confirmed,actorId:e.actorId});let s={added:i.mutation.added,changed:i.mutation.changed,removed:e.mode==="move"?[r.key]:[],unchanged:i.mutation.unchanged,affectedResourceIds:p([...i.mutation.affectedResourceIds,...this.affectedResources(r.projectId,r.scope,[r.key])]),versions:i.mutation.versions};return{entry:i.entry,mutation:s}}async resolve(e){let r=this.store.list({projectId:e.projectId}),n=r.filter((a)=>this.applies(a,e)).sort((a,d)=>this.rank(a.scope.type)-this.rank(d.scope.type)),t=new Map,i=new Set;for(let a of n){if(t.has(a.key))i.add(a.key);t.set(a.key,a)}let s={},c={},u=[],o=new Set(e.allowedPreviewSecrets??[]);for(let[a,d]of t){if(e.previewId&&d.kind==="secret"&&d.scope.type!=="preview"&&(!e.trustedPreview||!o.has(a)))continue;if(d.kind==="variable")s[a]=d.value??"";else if(e.nativeReferences)s[a]=d.secretRef;else{let g=this.backend(d.backend);if(!await g.validate(d.secretRef)){if(u.push({key:a,code:"stale_reference",message:`${a} points to an unavailable secret.`}),d.required)u.push({key:a,code:"missing_required",message:`${a} is required but unavailable.`});continue}s[a]=await g.resolve(d.secretRef)}c[a]=R(d,{inherited:d.scope.type!==(e.previewId?"preview":e.functionId?"function":e.resourceId?"service":e.environmentId?"environment":"project"),overridden:i.has(a),canReadSecretMetadata:e.canReadSecretMetadata}),this.store.controlPlane.database.run("UPDATE configuration_entries SET last_used_at=? WHERE id=?",[this.now().toISOString(),d.id])}return{values:s,entries:c,warnings:u,configurationHash:this.fingerprint([...t.values()].map((a)=>`${a.key}:${a.valueFingerprint}:${a.version}`).sort().join(`
|
|
8
|
+
`))}}async reveal(e){let r=this.store.get(e.entryId);if(!r||r.kind!=="secret")throw Error("Configuration secret was not found.");if(!e.canRevealSecrets)throw Error("Secret reveal permission is required.");if(!e.recentlyAuthenticated)throw Error("Recent authentication is required to reveal a secret.");let n=await this.backend(r.backend).resolve(r.secretRef);return this.audit(r.projectId,e.actorId,"configuration.secret.revealed",r,[]),n}async remove(e){let r=this.store.get(e.entryId);if(!r)throw Error("Configuration entry was not found.");let n=this.store.dependencies(r.id);if(((r.scope.environmentId?this.store.controlPlane.listEnvironments(r.projectId).some((c)=>c.id===r.scope.environmentId&&c.kind==="production"):r.scope.type==="project")||n.length)&&!e.confirmed)throw Error("Confirmation is required because this configuration affects production or dependent services.");if(r.kind==="secret"&&r.backend!=="external")await this.backend(r.backend).remove(r.secretRef);this.store.remove(r.id,e.expectedVersion);let i=p(n.map((c)=>c.resourceId)),s={added:[],changed:[],removed:[r.key],unchanged:[],affectedResourceIds:i,versions:{}};return this.audit(r.projectId,e.actorId,"configuration.deleted",r,i),s}applies(e,r){if(e.scope.type==="project")return!0;if(e.scope.type==="environment")return e.scope.id===r.environmentId;if(e.scope.type==="service")return e.scope.id===r.resourceId;if(e.scope.type==="function")return e.scope.id===r.functionId;return e.scope.id===r.previewId}rank(e){return{project:0,environment:1,service:2,function:3,preview:4}[e]}fingerprint(e){return`hmac-sha256:${A("sha256",this.fingerprintKey).update(e).digest("hex")}`}requestHash(e){return this.fingerprint(JSON.stringify({...e,idempotencyKey:void 0,actorId:void 0}))}backend(e){let r=this.backends.get(e);if(!r)throw Error(`Configuration secret backend is not configured: ${e}`);return r}backendName(e){return`ts-cloud/${e.projectId}/${e.scope.type}/${e.scope.id}/${e.key}`.replace(/[^A-Za-z0-9/_+=.@-]/g,"-")}isProduction(e){return e.scope.type==="project"||!!e.scope.environmentId&&this.store.controlPlane.listEnvironments(e.projectId).some((r)=>r.id===e.scope.environmentId&&r.kind==="production")}warnings(e,r){let n=[];if(O.test(e))n.push({key:e,code:"reserved",message:`${e} may be reserved by the runtime or provider.`});if(Buffer.byteLength(r)>65536)n.push({key:e,code:"limit",message:`${e} exceeds the portable 64 KiB value limit.`});return n}affectedResources(e,r,n){let t=this.store.list({projectId:e,scope:r}).filter((i)=>n.includes(i.key)).flatMap((i)=>this.store.dependencies(i.id).map((s)=>s.resourceId));if(r.type==="service"||r.type==="function")return p([...t,r.id]);if(r.type==="environment")return p([...t,...this.store.controlPlane.listResources(e,r.id).map((i)=>i.id)]);if(r.type==="preview"){let i=this.store.controlPlane.database.query("SELECT resource_id FROM preview_instances WHERE id=?").get(r.id);return p([...t,...i?[i.resource_id]:[]])}return p([...t,...this.store.controlPlane.listResources(e).map((i)=>i.id)])}audit(e,r,n,t,i){this.store.controlPlane.appendEvent({projectId:e,actorId:r,type:n,payload:{entryId:t.id,key:t.key,kind:t.kind,scopeType:t.scope.type,scopeId:t.scope.id,backend:t.backend,version:t.version,affectedResourceIds:i}})}}async function Yr(e,r,n,t){let i={added:0,changed:0,removed:0,overridden:0},s=async(c,u)=>{let o=e.store.list({projectId:r.project.id,scope:c,kind:"variable"}),a=new Set(Object.keys(u));for(let d of o.filter((g)=>g.origin==="config"&&!a.has(g.key)))await e.remove({entryId:d.id,expectedVersion:d.version,confirmed:!0,actorId:t}),i.removed++;for(let[d,g]of Object.entries(u)){let l=e.store.find(r.project.id,c,d);if(l?.origin!=="config"){if(l)i.overridden++;else await e.set({organizationId:r.organization.id,projectId:r.project.id,scope:c,key:d,kind:"variable",value:String(g),origin:"config",confirmed:!0,actorId:t}),i.added++;continue}if(l.value===String(g))continue;await e.set({organizationId:r.organization.id,projectId:r.project.id,scope:c,key:d,kind:"variable",value:String(g),origin:"config",confirmed:!0,actorId:t,expectedVersion:l.version}),i.changed++}};for(let[c,u]of Object.entries(n.environments??{})){let o=r.environments.get(c);if(!o)continue;let a=u,d={...a.variables??{},...a.app?.env??{}};await s({type:"environment",id:o.id,environmentId:o.id},d);for(let[g,l]of Object.entries(n.sites??{})){let v=r.store.listResources(r.project.id,o.id).find((f)=>f.kind==="application"&&f.slug===g);if(v)await s({type:"service",id:v.id,environmentId:o.id,resourceId:v.id},{...l.env??{}})}for(let[g,l]of Object.entries(n.infrastructure?.functions??{})){let v=r.store.listResources(r.project.id,o.id).find((f)=>f.kind==="function"&&f.slug===g);if(v)await s({type:"function",id:v.id,environmentId:o.id,resourceId:v.id},{...l.environment??{}})}}return i}export{hr,qa,Ha,St,yr,Sr,br,vr,Yr};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{dt,zl,Yo,Vi,Pu,Zo,es,zi,_t,Nu,ql,ku,Du,j,ts,xu}from"./chunk-w637s5q0.js";import"./chunk-4zbnwt9b.js";import"./chunk-vymg9ywg.js";import"./chunk-80zkjpfz.js";import"./chunk-2paqksap.js";import"./chunk-bckm6fre.js";import"./chunk-bj5nq0kn.js";export{Vi as assertEnvWithinLimit,Yo as buildFunctionEnv,Pu as deployServerlessApp,ku as getCommandRecord,zl as infraEnvFromOutputs,ql as listCommandHistory,Zo as redeployServerlessApp,dt as resolveServerlessFunctions,xu as restoreServerlessDatabase,es as rollbackServerlessApp,Nu as runAndRecordCommand,Du as runDbQuery,_t as runRemoteCommand,ts as scaleServerlessDatabase,j as serverlessInfo,zi as setMaintenance};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{Ql}from"./chunk-wge61ccr.js";var g={};Ql(g,{ProgressBar:()=>v,Spinner:()=>o,box:()=>he,checkAwsCli:()=>As,checkAwsCredentials:()=>Is,colorize:()=>Lt,colors:()=>T,confirm:()=>d,error:()=>r,formatBytes:()=>tn,formatDuration:()=>b,getAwsAccountId:()=>Rs,getAwsRegions:()=>Ps,header:()=>i,info:()=>e,prompt:()=>I,select:()=>fo,step:()=>m,success:()=>n,table:()=>c,warn:()=>a,warning:()=>Er});var T={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m"};function Lt(t,s){return`${T[s]}${t}${T.reset}`}function n(t){console.log(`${T.green}✓${T.reset} ${t}`)}function r(t){console.error(`${T.red}✗${T.reset} ${t}`)}function a(t){console.warn(`${T.yellow}⚠${T.reset} ${t}`)}var Er=a;function e(t){console.log(`${T.blue}ℹ${T.reset} ${t}`)}function m(t){console.log(`${T.cyan}→${T.reset} ${t}`)}function i(t){console.log(`
|
|
2
|
+
${T.bright}${T.cyan}${t}${T.reset}
|
|
3
|
+
`)}var x=!!(process.env.CI||process.env.GITHUB_ACTIONS||process.env.BUILDKITE||process.env.CIRCLECI||process.env.GITLAB_CI);class o{frames=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];interval=null;currentFrame=0;message;constructor(t){this.message=t}get text(){return this.message}set text(t){if(this.message=t,x&&this.interval)console.log(` ${t}`)}start(){if(x){console.log(` ${this.message}`),this.interval=!0;return}this.interval=setInterval(()=>{process.stdout.write(`\r${T.cyan}${this.frames[this.currentFrame]}${T.reset} ${this.message}`),this.currentFrame=(this.currentFrame+1)%this.frames.length},80)}succeed(t){this.stop(),n(t||this.message)}fail(t){this.stop(),r(t||this.message)}warn(t){this.stop(),Er(t||this.message)}stop(){if(this.interval){if(!x)process.stdout.write("\r");if(typeof this.interval==="object")clearInterval(this.interval);this.interval=null}}}class v{total;current=0;width=40;constructor(t){this.total=t}update(t){this.current=t,this.render()}increment(){this.current++,this.render()}render(){let t=Math.floor(this.current/this.total*100),s=Math.floor(this.current/this.total*this.width),l=this.width-s,u=`${"█".repeat(s)}${"░".repeat(l)}`;if(process.stdout.write(`\r${T.cyan}${u}${T.reset} ${t}% (${this.current}/${this.total})`),this.current>=this.total)process.stdout.write(`
|
|
4
|
+
`)}}async function I(t,s){let l=await import("node:readline"),u=l.createInterface({input:process.stdin,output:process.stdout});return new Promise((p)=>{let h=s?`${T.cyan}?${T.reset} ${t} ${T.gray}(${s})${T.reset}: `:`${T.cyan}?${T.reset} ${t}: `;u.question(h,(f)=>{u.close(),p(f||s||"")})})}async function d(t,s=!1){let l=await I(`${t} (y/n)`,s?"y":"n");return l.toLowerCase()==="y"||l.toLowerCase()==="yes"}async function fo(t,s){console.log(`${T.cyan}?${T.reset} ${t}`),s.forEach((p,h)=>{console.log(` ${T.gray}${h+1}.${T.reset} ${p}`)});let l=await I("Select","1"),u=Number.parseInt(l)-1;if(u>=0&&u<s.length)return s[u];return s[0]}function c(t,s){let l=t.map((p,h)=>{let f=Math.max(...s.map((w)=>(w[h]||"").length));return Math.max(p.length,f)}),u=t.map((p,h)=>p.padEnd(l[h])).join(" ");console.log(Lt(u,"bright")),console.log(Lt("─".repeat(u.length),"gray")),s.forEach((p)=>{let h=p.map((f,w)=>(f||"").padEnd(l[w])).join(" ");console.log(h)})}function tn(t){if(t===0)return"0 B";let s=1024,l=["B","KB","MB","GB","TB"],u=Math.floor(Math.log(t)/Math.log(s));return`${Number.parseFloat((t/s**u).toFixed(2))} ${l[u]}`}function b(t){if(t<1000)return`${t}ms`;let s=Math.floor(t/1000);if(s<60)return`${s}s`;let l=Math.floor(s/60),u=s%60;if(l<60)return`${l}m ${u}s`;let p=Math.floor(l/60),h=l%60;return`${p}h ${h}m`}function he(t,s="cyan"){let l=t.split(`
|
|
5
|
+
`),u=Math.max(...l.map((h)=>h.length)),p="─".repeat(u+2);console.log(Lt(`┌${p}┐`,s)),l.forEach((h)=>{console.log(Lt(`│ ${h.padEnd(u)} │`,s))}),console.log(Lt(`└${p}┘`,s))}async function As(){return!0}async function Is(){try{let{AWSClient:t}=await import("./chunk-c51xp8f7.js");return await new t().request({service:"sts",region:"us-east-1",method:"POST",path:"/",body:new URLSearchParams({Action:"GetCallerIdentity",Version:"2011-06-15"}).toString()}),!0}catch{return!1}}async function Rs(){try{let{AWSClient:t}=await import("./chunk-c51xp8f7.js"),l=await new t().request({service:"sts",region:"us-east-1",method:"POST",path:"/",body:new URLSearchParams({Action:"GetCallerIdentity",Version:"2011-06-15"}).toString()});return l.Account||l.GetCallerIdentityResult?.Account||null}catch{return null}}async function Ps(){try{let{AWSClient:t}=await import("./chunk-c51xp8f7.js"),l=await new t().request({service:"ec2",region:"us-east-1",method:"POST",path:"/",body:new URLSearchParams({Action:"DescribeRegions",Version:"2016-11-15"}).toString()}),u=[];if(l.regionInfo){let p=Array.isArray(l.regionInfo)?l.regionInfo:[l.regionInfo];u.push(...p.map((h)=>h.regionName))}return u.length>0?u:y()}catch{return y()}}function y(){return["us-east-1","us-east-2","us-west-1","us-west-2","eu-west-1","eu-central-1","ap-southeast-1","ap-northeast-1"]}
|
|
6
|
+
export{T,Lt,n,r,a,Er,e,m,i,o,I,d,fo,c,tn,he,As,Is,Rs,Ps,g};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{hr,qa,Ha,St,yr,Sr,br,vr,Yr}from"./chunk-1wvrtg42.js";import"./chunk-wr6a423y.js";import"./chunk-bj5nq0kn.js";export{yr as AwsSecretsManagerConfigurationBackend,Sr as AwsSsmConfigurationBackend,vr as ConfigurationService,hr as ConfigurationStore,br as ExternalConfigurationBackend,St as LocalEncryptedConfigurationBackend,qa as parseDotenv,Ha as serializeDotenv,Yr as synchronizeConfiguredConfiguration};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{Ao,sn,Ks,bi,Po,No}from"./chunk-bj5nq0kn.js";import{e}from"./chunk-2paqksap.js";import{bt}from"./chunk-ynr22ma8.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 Lu(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){Po({projectRoot:r,app:t,skipBuild:s.skipBuild,onStep:n}),n("staging application tree");let i=No(r);E(h,i),E(o(a,"runtime"),bi().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=Ao(i.map((c)=>`${c.name}:${c.data.length}`).join("|"))}else{n("bundling application");let i=await sn({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"),Ks({kind:t.kind??"node",phpVersion:t.phpVersion,architecture:x}));let k=new bt(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
|
+
export{Lu};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{u,N}from"./chunk-bckm6fre.js";class le{client;region;constructor(e="us-east-1"){this.region=e,this.client=new u}async describeDBInstances(e){let r={Action:"DescribeDBInstances",Version:"2014-10-31"};if(e?.DBInstanceIdentifier)r.DBInstanceIdentifier=e.DBInstanceIdentifier;if(e?.MaxRecords)r.MaxRecords=e.MaxRecords;if(e?.Marker)r.Marker=e.Marker;if(e?.Filters)e.Filters.forEach((a,o)=>{r[`Filters.Filter.${o+1}.Name`]=a.Name,a.Values.forEach((c,d)=>{r[`Filters.Filter.${o+1}.Values.Value.${d+1}`]=c})});let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t}),i=n.DescribeDBInstancesResult||n,s=i.DBInstances?.DBInstance||[];if(!Array.isArray(s))s=s?[s]:[];return{DBInstances:s,Marker:i.Marker}}async describeDBInstance(e){return(await this.describeDBInstances({DBInstanceIdentifier:e})).DBInstances?.[0]}async describeDBClusters(e){let r={Action:"DescribeDBClusters",Version:"2014-10-31"};if(e?.DBClusterIdentifier)r.DBClusterIdentifier=e.DBClusterIdentifier;if(e?.MaxRecords)r.MaxRecords=e.MaxRecords;if(e?.Marker)r.Marker=e.Marker;if(e?.Filters)e.Filters.forEach((a,o)=>{r[`Filters.Filter.${o+1}.Name`]=a.Name,a.Values.forEach((c,d)=>{r[`Filters.Filter.${o+1}.Values.Value.${d+1}`]=c})});let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t}),i=n.DescribeDBClustersResult||n,s=i.DBClusters?.DBCluster||[];if(!Array.isArray(s))s=s?[s]:[];return{DBClusters:s,Marker:i.Marker}}async describeDBSnapshots(e){let r={Action:"DescribeDBSnapshots",Version:"2014-10-31"};if(e?.DBInstanceIdentifier)r.DBInstanceIdentifier=e.DBInstanceIdentifier;if(e?.DBSnapshotIdentifier)r.DBSnapshotIdentifier=e.DBSnapshotIdentifier;if(e?.SnapshotType)r.SnapshotType=e.SnapshotType;if(e?.MaxRecords)r.MaxRecords=e.MaxRecords;if(e?.Marker)r.Marker=e.Marker;let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t}),i=n.DescribeDBSnapshotsResult||n,s=i.DBSnapshots?.DBSnapshot||[];if(!Array.isArray(s))s=s?[s]:[];return{DBSnapshots:s,Marker:i.Marker}}async describeDBSubnetGroups(e){let r={Action:"DescribeDBSubnetGroups",Version:"2014-10-31"};if(e?.DBSubnetGroupName)r.DBSubnetGroupName=e.DBSubnetGroupName;if(e?.MaxRecords)r.MaxRecords=e.MaxRecords;if(e?.Marker)r.Marker=e.Marker;let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t}),i=n.DescribeDBSubnetGroupsResult||n,s=i.DBSubnetGroups?.DBSubnetGroup||[];if(!Array.isArray(s))s=s?[s]:[];return{DBSubnetGroups:s,Marker:i.Marker}}async createDBInstance(e){let r={Action:"CreateDBInstance",Version:"2014-10-31",DBInstanceIdentifier:e.DBInstanceIdentifier,DBInstanceClass:e.DBInstanceClass,Engine:e.Engine};if(e.DBClusterIdentifier)r.DBClusterIdentifier=e.DBClusterIdentifier;if(e.MasterUsername)r.MasterUsername=e.MasterUsername;if(e.MasterUserPassword)r.MasterUserPassword=e.MasterUserPassword;if(e.DBName)r.DBName=e.DBName;if(e.AllocatedStorage)r.AllocatedStorage=e.AllocatedStorage;if(e.DBSubnetGroupName)r.DBSubnetGroupName=e.DBSubnetGroupName;if(e.AvailabilityZone)r.AvailabilityZone=e.AvailabilityZone;if(e.PreferredMaintenanceWindow)r.PreferredMaintenanceWindow=e.PreferredMaintenanceWindow;if(e.PreferredBackupWindow)r.PreferredBackupWindow=e.PreferredBackupWindow;if(e.BackupRetentionPeriod!==void 0)r.BackupRetentionPeriod=e.BackupRetentionPeriod;if(e.MultiAZ!==void 0)r.MultiAZ=e.MultiAZ;if(e.EngineVersion)r.EngineVersion=e.EngineVersion;if(e.AutoMinorVersionUpgrade!==void 0)r.AutoMinorVersionUpgrade=e.AutoMinorVersionUpgrade;if(e.LicenseModel)r.LicenseModel=e.LicenseModel;if(e.PubliclyAccessible!==void 0)r.PubliclyAccessible=e.PubliclyAccessible;if(e.StorageType)r.StorageType=e.StorageType;if(e.StorageEncrypted!==void 0)r.StorageEncrypted=e.StorageEncrypted;if(e.KmsKeyId)r.KmsKeyId=e.KmsKeyId;if(e.DeletionProtection!==void 0)r.DeletionProtection=e.DeletionProtection;if(e.VpcSecurityGroupIds)e.VpcSecurityGroupIds.forEach((s,a)=>{r[`VpcSecurityGroupIds.VpcSecurityGroupId.${a+1}`]=s});if(e.Tags)e.Tags.forEach((s,a)=>{r[`Tags.Tag.${a+1}.Key`]=s.Key,r[`Tags.Tag.${a+1}.Value`]=s.Value});let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t});return{DBInstance:(n.CreateDBInstanceResult||n).DBInstance}}async createDBCluster(e){let r={Action:"CreateDBCluster",Version:"2014-10-31",DBClusterIdentifier:e.DBClusterIdentifier,Engine:e.Engine};if(e.EngineVersion)r.EngineVersion=e.EngineVersion;if(e.MasterUsername)r.MasterUsername=e.MasterUsername;if(e.MasterUserPassword)r.MasterUserPassword=e.MasterUserPassword;if(e.DatabaseName)r.DatabaseName=e.DatabaseName;if(e.DBSubnetGroupName)r.DBSubnetGroupName=e.DBSubnetGroupName;if(e.BackupRetentionPeriod!==void 0)r.BackupRetentionPeriod=e.BackupRetentionPeriod;if(e.StorageEncrypted!==void 0)r.StorageEncrypted=e.StorageEncrypted;if(e.KmsKeyId)r.KmsKeyId=e.KmsKeyId;if(e.DeletionProtection!==void 0)r.DeletionProtection=e.DeletionProtection;if(e.ServerlessV2ScalingConfiguration)r["ServerlessV2ScalingConfiguration.MinCapacity"]=e.ServerlessV2ScalingConfiguration.MinCapacity,r["ServerlessV2ScalingConfiguration.MaxCapacity"]=e.ServerlessV2ScalingConfiguration.MaxCapacity;e.VpcSecurityGroupIds?.forEach((i,s)=>{r[`VpcSecurityGroupIds.VpcSecurityGroupId.${s+1}`]=i});let t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(N(r)).toString()});return{DBCluster:(t.CreateDBClusterResult||t).DBCluster}}async deleteDBInstance(e){let r={Action:"DeleteDBInstance",Version:"2014-10-31",DBInstanceIdentifier:e.DBInstanceIdentifier};if(e.SkipFinalSnapshot!==void 0)r.SkipFinalSnapshot=e.SkipFinalSnapshot;if(e.FinalDBSnapshotIdentifier)r.FinalDBSnapshotIdentifier=e.FinalDBSnapshotIdentifier;if(e.DeleteAutomatedBackups!==void 0)r.DeleteAutomatedBackups=e.DeleteAutomatedBackups;let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t});return{DBInstance:(n.DeleteDBInstanceResult||n).DBInstance}}async modifyDBInstance(e){let r={Action:"ModifyDBInstance",Version:"2014-10-31",DBInstanceIdentifier:e.DBInstanceIdentifier};if(e.DBInstanceClass)r.DBInstanceClass=e.DBInstanceClass;if(e.AllocatedStorage)r.AllocatedStorage=e.AllocatedStorage;if(e.MasterUserPassword)r.MasterUserPassword=e.MasterUserPassword;if(e.BackupRetentionPeriod!==void 0)r.BackupRetentionPeriod=e.BackupRetentionPeriod;if(e.PreferredBackupWindow)r.PreferredBackupWindow=e.PreferredBackupWindow;if(e.PreferredMaintenanceWindow)r.PreferredMaintenanceWindow=e.PreferredMaintenanceWindow;if(e.MultiAZ!==void 0)r.MultiAZ=e.MultiAZ;if(e.EngineVersion)r.EngineVersion=e.EngineVersion;if(e.AutoMinorVersionUpgrade!==void 0)r.AutoMinorVersionUpgrade=e.AutoMinorVersionUpgrade;if(e.PubliclyAccessible!==void 0)r.PubliclyAccessible=e.PubliclyAccessible;if(e.ApplyImmediately!==void 0)r.ApplyImmediately=e.ApplyImmediately;if(e.StorageType)r.StorageType=e.StorageType;if(e.DeletionProtection!==void 0)r.DeletionProtection=e.DeletionProtection;if(e.VpcSecurityGroupIds)e.VpcSecurityGroupIds.forEach((s,a)=>{r[`VpcSecurityGroupIds.VpcSecurityGroupId.${a+1}`]=s});let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t});return{DBInstance:(n.ModifyDBInstanceResult||n).DBInstance}}async modifyDBCluster(e){let r={Action:"ModifyDBCluster",Version:"2014-10-31",DBClusterIdentifier:e.DBClusterIdentifier};if(e.ServerlessV2ScalingConfiguration)r["ServerlessV2ScalingConfiguration.MinCapacity"]=e.ServerlessV2ScalingConfiguration.MinCapacity,r["ServerlessV2ScalingConfiguration.MaxCapacity"]=e.ServerlessV2ScalingConfiguration.MaxCapacity;if(e.BackupRetentionPeriod!==void 0)r.BackupRetentionPeriod=e.BackupRetentionPeriod;if(e.EngineVersion)r.EngineVersion=e.EngineVersion;if(e.MasterUserPassword)r.MasterUserPassword=e.MasterUserPassword;if(e.DeletionProtection!==void 0)r.DeletionProtection=e.DeletionProtection;if(e.ApplyImmediately!==void 0)r.ApplyImmediately=e.ApplyImmediately;let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t});return{DBCluster:(n.ModifyDBClusterResult||n).DBCluster}}async rebootDBCluster(e){let r={Action:"FailoverDBCluster",Version:"2014-10-31",DBClusterIdentifier:e},t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(N(r)).toString()});return{DBCluster:(t.FailoverDBClusterResult||t).DBCluster}}async createDBClusterSnapshot(e,r){let t={Action:"CreateDBClusterSnapshot",Version:"2014-10-31",DBClusterIdentifier:e,DBClusterSnapshotIdentifier:r};return this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(N(t)).toString()})}async describeDBClusterSnapshots(e={}){let r={Action:"DescribeDBClusterSnapshots",Version:"2014-10-31",...e},t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(N(r)).toString()}),n=t.DescribeDBClusterSnapshotsResult||t,i=n.DBClusterSnapshots?.DBClusterSnapshot??n.DBClusterSnapshots??[];return{DBClusterSnapshots:Array.isArray(i)?i:[i]}}async deleteDBClusterSnapshot(e){await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(N({Action:"DeleteDBClusterSnapshot",Version:"2014-10-31",DBClusterSnapshotIdentifier:e})).toString()})}async deleteDBCluster(e,r){let t={Action:"DeleteDBCluster",Version:"2014-10-31",DBClusterIdentifier:e,SkipFinalSnapshot:!r};if(r)t.FinalDBSnapshotIdentifier=r;let n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(N(t)).toString()});return{DBCluster:(n.DeleteDBClusterResult||n).DBCluster}}async restoreDBClusterToPointInTime(e){let r={Action:"RestoreDBClusterToPointInTime",Version:"2014-10-31",DBClusterIdentifier:e.DBClusterIdentifier,SourceDBClusterIdentifier:e.SourceDBClusterIdentifier};if(e.RestoreToTime)r.RestoreToTime=e.RestoreToTime.toISOString();if(e.UseLatestRestorableTime)r.UseLatestRestorableTime=!0;if(e.DBSubnetGroupName)r.DBSubnetGroupName=e.DBSubnetGroupName;if(e.VpcSecurityGroupIds)e.VpcSecurityGroupIds.forEach((s,a)=>{r[`VpcSecurityGroupIds.VpcSecurityGroupId.${a+1}`]=s});let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t});return{DBCluster:(n.RestoreDBClusterToPointInTimeResult||n).DBCluster}}async restoreDBClusterFromSnapshot(e){let r={Action:"RestoreDBClusterFromSnapshot",Version:"2014-10-31",DBClusterIdentifier:e.DBClusterIdentifier,SnapshotIdentifier:e.SnapshotIdentifier,Engine:e.Engine};if(e.EngineVersion)r.EngineVersion=e.EngineVersion;if(e.DBSubnetGroupName)r.DBSubnetGroupName=e.DBSubnetGroupName;if(e.DeletionProtection!==void 0)r.DeletionProtection=e.DeletionProtection;if(e.VpcSecurityGroupIds?.forEach((i,s)=>{r[`VpcSecurityGroupIds.VpcSecurityGroupId.${s+1}`]=i}),e.ServerlessV2ScalingConfiguration)r["ServerlessV2ScalingConfiguration.MinCapacity"]=e.ServerlessV2ScalingConfiguration.MinCapacity,r["ServerlessV2ScalingConfiguration.MaxCapacity"]=e.ServerlessV2ScalingConfiguration.MaxCapacity;let t=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(N(r)).toString()});return{DBCluster:(t.RestoreDBClusterFromSnapshotResult||t).DBCluster}}async startDBInstance(e){let t=new URLSearchParams(N({Action:"StartDBInstance",Version:"2014-10-31",DBInstanceIdentifier:e})).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t});return{DBInstance:(n.StartDBInstanceResult||n).DBInstance}}async stopDBInstance(e){let r={Action:"StopDBInstance",Version:"2014-10-31",DBInstanceIdentifier:e.DBInstanceIdentifier};if(e.DBSnapshotIdentifier)r.DBSnapshotIdentifier=e.DBSnapshotIdentifier;let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t});return{DBInstance:(n.StopDBInstanceResult||n).DBInstance}}async rebootDBInstance(e){let r={Action:"RebootDBInstance",Version:"2014-10-31",DBInstanceIdentifier:e.DBInstanceIdentifier};if(e.ForceFailover!==void 0)r.ForceFailover=e.ForceFailover;let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t});return{DBInstance:(n.RebootDBInstanceResult||n).DBInstance}}async createDBSnapshot(e){let r={Action:"CreateDBSnapshot",Version:"2014-10-31",DBInstanceIdentifier:e.DBInstanceIdentifier,DBSnapshotIdentifier:e.DBSnapshotIdentifier};if(e.Tags)e.Tags.forEach((s,a)=>{r[`Tags.Tag.${a+1}.Key`]=s.Key,r[`Tags.Tag.${a+1}.Value`]=s.Value});let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t});return{DBSnapshot:(n.CreateDBSnapshotResult||n).DBSnapshot}}async deleteDBSnapshot(e){let t=new URLSearchParams(N({Action:"DeleteDBSnapshot",Version:"2014-10-31",DBSnapshotIdentifier:e})).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t});return{DBSnapshot:(n.DeleteDBSnapshotResult||n).DBSnapshot}}async restoreDBInstanceFromDBSnapshot(e){let r={Action:"RestoreDBInstanceFromDBSnapshot",Version:"2014-10-31",DBInstanceIdentifier:e.DBInstanceIdentifier,DBSnapshotIdentifier:e.DBSnapshotIdentifier};if(e.DBInstanceClass)r.DBInstanceClass=e.DBInstanceClass;if(e.Port)r.Port=e.Port;if(e.AvailabilityZone)r.AvailabilityZone=e.AvailabilityZone;if(e.DBSubnetGroupName)r.DBSubnetGroupName=e.DBSubnetGroupName;if(e.MultiAZ!==void 0)r.MultiAZ=e.MultiAZ;if(e.PubliclyAccessible!==void 0)r.PubliclyAccessible=e.PubliclyAccessible;if(e.AutoMinorVersionUpgrade!==void 0)r.AutoMinorVersionUpgrade=e.AutoMinorVersionUpgrade;if(e.StorageType)r.StorageType=e.StorageType;if(e.DeletionProtection!==void 0)r.DeletionProtection=e.DeletionProtection;if(e.VpcSecurityGroupIds)e.VpcSecurityGroupIds.forEach((s,a)=>{r[`VpcSecurityGroupIds.VpcSecurityGroupId.${a+1}`]=s});if(e.Tags)e.Tags.forEach((s,a)=>{r[`Tags.Tag.${a+1}.Key`]=s.Key,r[`Tags.Tag.${a+1}.Value`]=s.Value});let t=new URLSearchParams(N(r)).toString(),n=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t});return{DBInstance:(n.RestoreDBInstanceFromDBSnapshotResult||n).DBInstance}}async waitForDBInstanceAvailable(e,r=60,t=30000){for(let n=0;n<r;n++){let i=await this.describeDBInstance(e);if(i?.DBInstanceStatus==="available")return i;if(["deleted","failed","incompatible-restore","incompatible-parameters"].includes(i?.DBInstanceStatus||""))throw Error(`DB instance ${e} is in terminal state: ${i?.DBInstanceStatus}`);await new Promise((s)=>setTimeout(s,t))}throw Error(`Timeout waiting for DB instance ${e} to become available`)}async waitForDBInstanceDeleted(e,r=60,t=30000){for(let n=0;n<r;n++)try{let i=await this.describeDBInstance(e);if(i?.DBInstanceStatus==="deleting"){await new Promise((s)=>setTimeout(s,t));continue}throw Error(`DB instance ${e} is in state: ${i?.DBInstanceStatus}`)}catch(i){if(i.code==="DBInstanceNotFound"||i.code==="DBInstanceNotFoundFault")return;throw i}throw Error(`Timeout waiting for DB instance ${e} to be deleted`)}}
|
|
2
|
+
export{le};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{v}from"./chunk-vymg9ywg.js";import"./chunk-bckm6fre.js";export{v as CloudFormationClient};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{u}from"./chunk-bckm6fre.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
|
+
export{R};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{u}from"./chunk-bckm6fre.js";class O{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+=`
|
|
@@ -46,5 +46,5 @@ import{tj as a}from"./chunk-ac87ds1k.js";class d{client;region;constructor(e="us
|
|
|
46
46
|
</Change>`}o+=`
|
|
47
47
|
</Changes>
|
|
48
48
|
</ChangeBatch>
|
|
49
|
-
</ChangeResourceRecordSetsRequest>`;let n=await this.client.request({service:"route53",region:this.region,method:"POST",path:`/2013-04-01/hostedzone/${t}/rrset`,headers:{"content-type":"application/xml"},body:o});return this.parseChangeResourceRecordSetsResponse(n)}escapeXml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}parseCreateHostedZoneResponse(e){let t=e.CreateHostedZoneResponse||e;return{HostedZone:this.parseHostedZone(t.HostedZone),ChangeInfo:{Id:t.ChangeInfo?.Id||"",Status:t.ChangeInfo?.Status||"",SubmittedAt:t.ChangeInfo?.SubmittedAt||""},DelegationSet:this.parseDelegationSet(t.DelegationSet),Location:t.Location||""}}parseListHostedZonesResponse(e){let t=e.ListHostedZonesResponse||e.ListHostedZonesByNameResponse||e,o=t.HostedZones?.HostedZone||t.HostedZones||[];if(!Array.isArray(o))o=o?[o]:[];return{HostedZones:o.map((n)=>this.parseHostedZone(n)),IsTruncated:t.IsTruncated==="true"||t.IsTruncated===!0,MaxItems:t.MaxItems||"100",Marker:t.Marker,NextMarker:t.NextMarker}}parseGetHostedZoneResponse(e){let t=e.GetHostedZoneResponse||e;return{HostedZone:this.parseHostedZone(t.HostedZone),DelegationSet:this.parseDelegationSet(t.DelegationSet),VPCs:t.VPCs?.VPC?Array.isArray(t.VPCs.VPC)?t.VPCs.VPC:[t.VPCs.VPC]:void 0}}parseListResourceRecordSetsResponse(e){let t=e.ListResourceRecordSetsResponse||e,o=t.ResourceRecordSets?.ResourceRecordSet||t.ResourceRecordSets||[];if(!Array.isArray(o))o=o?[o]:[];return{ResourceRecordSets:o.map((n)=>this.parseResourceRecordSet(n)),IsTruncated:t.IsTruncated==="true"||t.IsTruncated===!0,MaxItems:t.MaxItems||"100",NextRecordName:t.NextRecordName,NextRecordType:t.NextRecordType,NextRecordIdentifier:t.NextRecordIdentifier}}parseChangeResourceRecordSetsResponse(e){let t=e.ChangeResourceRecordSetsResponse||e;return{ChangeInfo:{Id:t.ChangeInfo?.Id||"",Status:t.ChangeInfo?.Status||"",SubmittedAt:t.ChangeInfo?.SubmittedAt||"",Comment:t.ChangeInfo?.Comment}}}parseHostedZone(e){if(!e)return{Id:"",Name:""};return{Id:e.Id||"",Name:e.Name||"",CallerReference:e.CallerReference,Config:e.Config?{Comment:e.Config.Comment,PrivateZone:e.Config.PrivateZone==="true"||e.Config.PrivateZone===!0}:void 0,ResourceRecordSetCount:e.ResourceRecordSetCount?Number(e.ResourceRecordSetCount):void 0}}parseDelegationSet(e){if(!e)return{NameServers:[]};let t=e.NameServers?.NameServer||e.NameServers||[];if(!Array.isArray(t))t=t?[t]:[];return{Id:e.Id,CallerReference:e.CallerReference,NameServers:t}}parseResourceRecordSet(e){if(!e)return{Name:"",Type:""};let t=e.ResourceRecords?.ResourceRecord||e.ResourceRecords||[];if(!Array.isArray(t))t=t?[t]:[];return{Name:e.Name||"",Type:e.Type||"",TTL:e.TTL?Number(e.TTL):void 0,ResourceRecords:t.map((o)=>({Value:o.Value||o})),AliasTarget:e.AliasTarget?{HostedZoneId:e.AliasTarget.HostedZoneId,DNSName:e.AliasTarget.DNSName,EvaluateTargetHealth:e.AliasTarget.EvaluateTargetHealth==="true"||e.AliasTarget.EvaluateTargetHealth===!0}:void 0,SetIdentifier:e.SetIdentifier,Weight:e.Weight?Number(e.Weight):void 0,Region:e.Region,GeoLocation:e.GeoLocation,Failover:e.Failover,HealthCheckId:e.HealthCheckId}}async findHostedZoneByName(e){let t=e.endsWith(".")?e:`${e}.`;return(await this.listHostedZonesByName({DNSName:t})).HostedZones.find((s)=>s.Name===t)||null}async createARecord(e){let t=Array.isArray(e.Value)?e.Value:[e.Value];return this.changeResourceRecordSets({HostedZoneId:e.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:e.Name,Type:"A",TTL:e.TTL||300,ResourceRecords:t.map((o)=>({Value:o}))}}]}})}async createCnameRecord(e){return this.changeResourceRecordSets({HostedZoneId:e.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:e.Name,Type:"CNAME",TTL:e.TTL||300,ResourceRecords:[{Value:e.Value}]}}]}})}async createAliasRecord(e){return this.changeResourceRecordSets({HostedZoneId:e.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:e.Name,Type:e.Type||"A",AliasTarget:{HostedZoneId:e.TargetHostedZoneId,DNSName:e.TargetDNSName,EvaluateTargetHealth:e.EvaluateTargetHealth??!1}}}]}})}async createTxtRecord(e){let o=(Array.isArray(e.Value)?e.Value:[e.Value]).map((n)=>{if(!n.startsWith('"'))return`"${n}"`;return n});return this.changeResourceRecordSets({HostedZoneId:e.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:e.Name,Type:"TXT",TTL:e.TTL||300,ResourceRecords:o.map((n)=>({Value:n}))}}]}})}async createMxRecord(e){return this.changeResourceRecordSets({HostedZoneId:e.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:e.Name,Type:"MX",TTL:e.TTL||300,ResourceRecords:e.Values.map((t)=>({Value:`${t.priority} ${t.mailServer}`}))}}]}})}async deleteRecord(e){return this.changeResourceRecordSets({HostedZoneId:e.HostedZoneId,ChangeBatch:{Changes:[{Action:"DELETE",ResourceRecordSet:e.RecordSet}]}})}async waitForChange(e,t=60,o=5000){let n=e.replace("/change/","");for(let s=0;s<t;s++){let r=await this.client.request({service:"route53",region:this.region,method:"GET",path:`/2013-04-01/change/${n}`});if((r.GetChangeResponse?.ChangeInfo?.Status||r.ChangeInfo?.Status)==="INSYNC")return!0;await new Promise((
|
|
50
|
-
export{
|
|
49
|
+
</ChangeResourceRecordSetsRequest>`;let n=await this.client.request({service:"route53",region:this.region,method:"POST",path:`/2013-04-01/hostedzone/${t}/rrset`,headers:{"content-type":"application/xml"},body:o});return this.parseChangeResourceRecordSetsResponse(n)}escapeXml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}parseCreateHostedZoneResponse(e){let t=e.CreateHostedZoneResponse||e;return{HostedZone:this.parseHostedZone(t.HostedZone),ChangeInfo:{Id:t.ChangeInfo?.Id||"",Status:t.ChangeInfo?.Status||"",SubmittedAt:t.ChangeInfo?.SubmittedAt||""},DelegationSet:this.parseDelegationSet(t.DelegationSet),Location:t.Location||""}}parseListHostedZonesResponse(e){let t=e.ListHostedZonesResponse||e.ListHostedZonesByNameResponse||e,o=t.HostedZones?.HostedZone||t.HostedZones||[];if(!Array.isArray(o))o=o?[o]:[];return{HostedZones:o.map((n)=>this.parseHostedZone(n)),IsTruncated:t.IsTruncated==="true"||t.IsTruncated===!0,MaxItems:t.MaxItems||"100",Marker:t.Marker,NextMarker:t.NextMarker}}parseGetHostedZoneResponse(e){let t=e.GetHostedZoneResponse||e;return{HostedZone:this.parseHostedZone(t.HostedZone),DelegationSet:this.parseDelegationSet(t.DelegationSet),VPCs:t.VPCs?.VPC?Array.isArray(t.VPCs.VPC)?t.VPCs.VPC:[t.VPCs.VPC]:void 0}}parseListResourceRecordSetsResponse(e){let t=e.ListResourceRecordSetsResponse||e,o=t.ResourceRecordSets?.ResourceRecordSet||t.ResourceRecordSets||[];if(!Array.isArray(o))o=o?[o]:[];return{ResourceRecordSets:o.map((n)=>this.parseResourceRecordSet(n)),IsTruncated:t.IsTruncated==="true"||t.IsTruncated===!0,MaxItems:t.MaxItems||"100",NextRecordName:t.NextRecordName,NextRecordType:t.NextRecordType,NextRecordIdentifier:t.NextRecordIdentifier}}parseChangeResourceRecordSetsResponse(e){let t=e.ChangeResourceRecordSetsResponse||e;return{ChangeInfo:{Id:t.ChangeInfo?.Id||"",Status:t.ChangeInfo?.Status||"",SubmittedAt:t.ChangeInfo?.SubmittedAt||"",Comment:t.ChangeInfo?.Comment}}}parseHostedZone(e){if(!e)return{Id:"",Name:""};return{Id:e.Id||"",Name:e.Name||"",CallerReference:e.CallerReference,Config:e.Config?{Comment:e.Config.Comment,PrivateZone:e.Config.PrivateZone==="true"||e.Config.PrivateZone===!0}:void 0,ResourceRecordSetCount:e.ResourceRecordSetCount?Number(e.ResourceRecordSetCount):void 0}}parseDelegationSet(e){if(!e)return{NameServers:[]};let t=e.NameServers?.NameServer||e.NameServers||[];if(!Array.isArray(t))t=t?[t]:[];return{Id:e.Id,CallerReference:e.CallerReference,NameServers:t}}parseResourceRecordSet(e){if(!e)return{Name:"",Type:""};let t=e.ResourceRecords?.ResourceRecord||e.ResourceRecords||[];if(!Array.isArray(t))t=t?[t]:[];return{Name:e.Name||"",Type:e.Type||"",TTL:e.TTL?Number(e.TTL):void 0,ResourceRecords:t.map((o)=>({Value:o.Value||o})),AliasTarget:e.AliasTarget?{HostedZoneId:e.AliasTarget.HostedZoneId,DNSName:e.AliasTarget.DNSName,EvaluateTargetHealth:e.AliasTarget.EvaluateTargetHealth==="true"||e.AliasTarget.EvaluateTargetHealth===!0}:void 0,SetIdentifier:e.SetIdentifier,Weight:e.Weight?Number(e.Weight):void 0,Region:e.Region,GeoLocation:e.GeoLocation,Failover:e.Failover,HealthCheckId:e.HealthCheckId}}async findHostedZoneByName(e){let t=e.endsWith(".")?e:`${e}.`;return(await this.listHostedZonesByName({DNSName:t})).HostedZones.find((s)=>s.Name===t)||null}async createARecord(e){let t=Array.isArray(e.Value)?e.Value:[e.Value];return this.changeResourceRecordSets({HostedZoneId:e.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:e.Name,Type:"A",TTL:e.TTL||300,ResourceRecords:t.map((o)=>({Value:o}))}}]}})}async createCnameRecord(e){return this.changeResourceRecordSets({HostedZoneId:e.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:e.Name,Type:"CNAME",TTL:e.TTL||300,ResourceRecords:[{Value:e.Value}]}}]}})}async createAliasRecord(e){return this.changeResourceRecordSets({HostedZoneId:e.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:e.Name,Type:e.Type||"A",AliasTarget:{HostedZoneId:e.TargetHostedZoneId,DNSName:e.TargetDNSName,EvaluateTargetHealth:e.EvaluateTargetHealth??!1}}}]}})}async createTxtRecord(e){let o=(Array.isArray(e.Value)?e.Value:[e.Value]).map((n)=>{if(!n.startsWith('"'))return`"${n}"`;return n});return this.changeResourceRecordSets({HostedZoneId:e.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:e.Name,Type:"TXT",TTL:e.TTL||300,ResourceRecords:o.map((n)=>({Value:n}))}}]}})}async createMxRecord(e){return this.changeResourceRecordSets({HostedZoneId:e.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:e.Name,Type:"MX",TTL:e.TTL||300,ResourceRecords:e.Values.map((t)=>({Value:`${t.priority} ${t.mailServer}`}))}}]}})}async deleteRecord(e){return this.changeResourceRecordSets({HostedZoneId:e.HostedZoneId,ChangeBatch:{Changes:[{Action:"DELETE",ResourceRecordSet:e.RecordSet}]}})}async waitForChange(e,t=60,o=5000){let n=e.replace("/change/","");for(let s=0;s<t;s++){let r=await this.client.request({service:"route53",region:this.region,method:"GET",path:`/2013-04-01/change/${n}`});if((r.GetChangeResponse?.ChangeInfo?.Status||r.ChangeInfo?.Status)==="INSYNC")return!0;await new Promise((a)=>setTimeout(a,o))}return!1}async findOrCreateHostedZone(e){let t=e.domainName.endsWith(".")?e.domainName:`${e.domainName}.`,o=await this.findHostedZoneByName(t);if(o){let s=await this.getHostedZone({Id:o.Id});return{hostedZone:o,nameServers:s.DelegationSet.NameServers,isNew:!1}}let n=await this.createHostedZone({Name:t,HostedZoneConfig:{Comment:e.comment||`Hosted zone for ${e.domainName}`,PrivateZone:e.privateZone},VPC:e.vpc});return{hostedZone:n.HostedZone,nameServers:n.DelegationSet.NameServers,isNew:!0}}static getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length<=2)return e;return t.slice(-2).join(".")}async findHostedZoneForDomain(e){let o=e.replace(/\.$/,"").split(".");for(let n=0;n<o.length-1;n++){let s=o.slice(n).join("."),r=await this.findHostedZoneByName(s);if(r)return r}return null}async ensureHostedZone(e){let t=await this.findOrCreateHostedZone({domainName:e.domainName,comment:e.comment});return{hostedZoneId:t.hostedZone.Id.replace("/hostedzone/",""),nameServers:t.nameServers,isNew:t.isNew,action:t.isNew?"created":"found"}}async setupDomainDns(e){let{domain:t,createIfNotExists:o=!0}=e,n=await this.findHostedZoneByName(t);if(n){let r=await this.getHostedZone({Id:n.Id});return{success:!0,hostedZoneId:n.Id.replace("/hostedzone/",""),nameServers:r.DelegationSet.NameServers,isNew:!1,message:`Found existing hosted zone for ${t}`}}if(!o)return{success:!1,hostedZoneId:null,nameServers:[],isNew:!1,message:`No hosted zone found for ${t} and createIfNotExists is false`};let s=await this.createHostedZone({Name:t,HostedZoneConfig:{Comment:`Created automatically by ts-cloud for ${t}`}});return{success:!0,hostedZoneId:s.HostedZone.Id.replace("/hostedzone/",""),nameServers:s.DelegationSet.NameServers,isNew:!0,message:`Created new hosted zone for ${t}. Please update your domain registrar with these name servers: ${s.DelegationSet.NameServers.join(", ")}`}}static CloudFrontHostedZoneId="Z2FDTNDATAQYW2";static S3WebsiteHostedZoneIds={"us-east-1":"Z3AQBSTGFYJSTF","us-east-2":"Z2O1EMRO9K5GLX","us-west-1":"Z2F56UZL2M1ACD","us-west-2":"Z3BJ6K6RIION7M","ap-east-1":"ZNB98KWMFR0R6","ap-south-1":"Z11RGJOFQNVJUP","ap-northeast-1":"Z2M4EHUR26P7ZW","ap-northeast-2":"Z3W03O7B5YMIYP","ap-northeast-3":"Z2YQB5RD63NC85","ap-southeast-1":"Z3O0J2DXBE1FTB","ap-southeast-2":"Z1WCIGYICN2BYD","ca-central-1":"Z1QDHH18159H29","eu-central-1":"Z21DNDUVLTQW6Q","eu-west-1":"Z1BKCTXD74EZPE","eu-west-2":"Z3GKZC51ZF0DB4","eu-west-3":"Z3R1K369G5AVDG","eu-north-1":"Z3BAZG2TWCNX0D","sa-east-1":"Z7KQH4QJS55SO"};static ALBHostedZoneIds={"us-east-1":"Z35SXDOTRQ7X7K","us-east-2":"Z3AADJGX6KTTL2","us-west-1":"Z368ELLRRE2KJ0","us-west-2":"Z1H1FL5HABSF5","ap-east-1":"Z3DQVH9N71FHZ0","ap-south-1":"ZP97RAFLXTNZK","ap-northeast-1":"Z14GRHDCWA56QT","ap-northeast-2":"ZWKZPGTI48KDX","ap-northeast-3":"Z5LXEBD8Y73MNV","ap-southeast-1":"Z1LMS91P8CMLE5","ap-southeast-2":"Z1GM3OXH4ZPM65","ca-central-1":"ZQSVJUPU6J1EY","eu-central-1":"Z215JYRZR1TBD5","eu-west-1":"Z32O12XQLNTSW2","eu-west-2":"ZHURV8PSTC4K8","eu-west-3":"Z3Q77PNBQS71R4","eu-north-1":"Z23TAZ6LKFMNIO","sa-east-1":"Z2P70J7HTTTPLU"};static APIGatewayHostedZoneIds={"us-east-1":"Z1UJRXOUMOOFQ8","us-east-2":"ZOJJZC49E0EPZ","us-west-1":"Z2MUQ32089INYE","us-west-2":"Z2OJLYMUO9EFXC","ap-east-1":"Z3FD1VL90ND7K5","ap-south-1":"Z3VO1THU9YC4UR","ap-northeast-1":"Z1YSHQZHG15GKL","ap-northeast-2":"Z20JF4UZKIW1U8","ap-northeast-3":"Z2YQB5RD63NC85","ap-southeast-1":"ZL327KTPIQFUL","ap-southeast-2":"Z2RPCDW04V8134","ca-central-1":"Z19DQILCV0OWEC","eu-central-1":"Z1U9ULNL0V5AJ3","eu-west-1":"ZLY8HYME6SFDD","eu-west-2":"ZJ5UAJN8Y3Z2Q","eu-west-3":"Z3KY65QIEKYHQQ","eu-north-1":"Z3UWIKFBOOGXPP","sa-east-1":"ZCMLWB8V5SYIT"}}
|
|
50
|
+
export{O};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{ti}from"./chunk-9q8zjavc.js";import"./chunk-7a7n6p2m.js";import"./chunk-16rs9egs.js";import"./chunk-6vay4ggv.js";import"./chunk-vymg9ywg.js";import"./chunk-80zkjpfz.js";import"./chunk-bckm6fre.js";import"./chunk-bj5nq0kn.js";export{ti as resolveServerDashboardData};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{V,wr}from"./chunk-bj5nq0kn.js";function W(e,t){return`/var/www/${e}-${t}`}var _e=new Set(["laravel","php","statamic","wordpress"]);function ni(e){return e.type!=null&&_e.has(e.type)}function gs(e){let t=e.proxyTo;if(t==null)return[];return(Array.isArray(t)?t:[t]).map((n)=>String(n).trim()).filter((n)=>n.length>0)}function Se(e){return gs(e).length>0}function ee(e){if(e.deploy)return e.deploy;if(ni(e))return"server";if(e.start)return"server";return"bucket"}function P(e){if(e.redirect)return"redirect";if(Se(e))return"proxy";if(ni(e))return"server-php";if(ee(e)==="bucket")return"bucket";return e.start?"server-app":"server-static"}function so(e){return e.infrastructure?.compute!=null||Boolean(e.cloud?.attachTo?.trim())}function fs(e,t={}){let r=[],n=[],i=e.sites||{},s=so(e),c=wr(e);if(c)r.push(c);let d=new Map;for(let[l,o]of Object.entries(i)){if(!o)continue;let f=ee(o),E=P(o);if(E==="redirect"){if(!o.domain)r.push(`Site '${l}' is a redirect site but has no \`domain\` to redirect from.`);if(!(typeof o.redirect==="string"?o.redirect:o.redirect?.to))r.push(`Site '${l}' is a redirect site but has no redirect target (\`redirect\` / \`redirect.to\`).`);if(!s)r.push(`Site '${l}' is a redirect site but no \`infrastructure.compute\` is configured to host the gateway that serves the redirect.`);let a=[];if(o.start)a.push("start");if(o.root)a.push("root");if(o.proxyTo)a.push("proxyTo");if(a.length>0)n.push(`Site '${l}' is a redirect site but also sets ${a.join(", ")}. These are ignored.`);continue}if(E==="proxy"){if(!o.domain)r.push(`Site '${l}' is a proxy site but has no \`domain\` to route from.`);if(!s)r.push(`Site '${l}' is a proxy site but no \`infrastructure.compute\` is configured to host the gateway that forwards it.`);let p=[];if(o.start)p.push("start");if(o.root)p.push("root");if(typeof o.port==="number")p.push("port");if(o.build)p.push("build");if(o.preStart&&o.preStart.length>0)p.push("preStart");if(p.length>0)n.push(`Site '${l}' sets \`proxyTo\`, so ts-cloud ships and supervises nothing for it. ${p.join(", ")} ${p.length===1?"is":"are"} ignored — remove ${p.length===1?"it":"them"}, or drop \`proxyTo\` to let ts-cloud own the service.`);continue}if(f==="server"&&!o.start&&!o.root){r.push(`Site '${l}' sets deploy:'server' but declares neither \`start\` (dynamic app) nor \`root\` (static site to serve). Add one.`);continue}if(E==="server-php"){if(!s)r.push(`Site '${l}' is a PHP site (type:'${o.type}') but no \`infrastructure.compute\` is configured. Add a server (infrastructure.compute) with PHP provisioning.`);if(!o.repository?.url)r.push(`Site '${l}' is a PHP site (type:'${o.type}') but has no \`repository.url\` to clone. PHP sites deploy via git.`)}else if(E==="server-app"){if(!s)r.push(`Site '${l}' deploys to a server (deploy:'server'${o.deploy?"":" inferred from `start`"}) but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`);if(typeof o.port==="number"){let p=t.occupiedPorts?.get(o.port);if(p)r.push(`Site '${l}' wants port ${o.port}, which project '${p}' already serves on this box. Attached projects share one port namespace. Give '${l}' a free port, or let the attach allocate one.`);let a=d.get(o.port);if(a)r.push(`Sites '${a}' and '${l}' both use port ${o.port}. Server apps sharing a box must use distinct ports.`);else d.set(o.port,l)}}else if(E==="server-static"){if(!o.root)r.push(`Site '${l}' is a server static site (deploy:'server', no \`start\`) but has no \`root\` directory to serve.`);if(!s)r.push(`Site '${l}' deploys to a server (deploy:'server') but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`)}else{if(!o.root)r.push(`Site '${l}' deploys to a bucket but has no \`root\` directory to upload.`);let p=[];if(o.start)p.push("start");if(typeof o.port==="number")p.push("port");if(o.preStart&&o.preStart.length>0)p.push("preStart");if(p.length>0)n.push(`Site '${l}' deploys to a bucket but sets server-only field(s): ${p.join(", ")}. These are ignored. Set deploy:'server' to use them.`)}}return{errors:r,warnings:n}}function hs(e){let t=P(e);return t!=="bucket"&&t!=="redirect"&&t!=="proxy"}function Ma(e){return P(e)==="bucket"}function Ua(e,t){if(V(e)==="serverless")return!0;let r=Object.entries(e.sites??{}).filter(([,i])=>i!=null),n=t?r.filter(([i])=>i===t):r;if(n.length===0)return!0;return!n.every(([,i])=>{let s=P(i);return s==="redirect"||s==="proxy"})}var O={php:"php.net",nginx:"nginx.org",composer:"getcomposer.org",mysql:"mysql.com",mariadb:"mariadb.com/server",postgres:"postgresql.org",vitess:"vitess.io",etcd:"etcd.io",redis:"redis.io",memcached:"memcached.org",meilisearch:"meilisearch.com",mail:"github.com/mail-os/mail",git:"git-scm.com",certbot:"certbot.eff.org",bun:"bun.sh",node:"nodejs.org",deno:"deno.land"};var M="/opt/pantry";function N(e){return`'${e.split("'").join("'\\''")}'`}function gr(e={}){return["export DEBIAN_FRONTEND=noninteractive","export PANTRY_SERVICE_SCOPE=system","export PANTRY_INSTALL_DIR=/usr/local/bin",e.version?`export PANTRY_VERSION=${N(e.version)}`:'export PANTRY_VERSION="${PANTRY_VERSION:-latest}"',"command -v curl >/dev/null 2>&1 || (apt-get update -y && apt-get install -y curl ca-certificates)","command -v unzip >/dev/null 2>&1 || (apt-get update -y && apt-get install -y unzip)",'OS=$(uname -s | tr \'[:upper:]\' \'[:lower:]\'); ARCH=$(uname -m); case "$ARCH" in x86_64|amd64) ARCH=x64 ;; arm64|aarch64) ARCH=arm64 ;; esac; ZIP="pantry-${OS}-${ARCH}.zip"; if [ "${PANTRY_VERSION:-latest}" = latest ]; then REL=\'latest/download\'; else REL="download/v${PANTRY_VERSION}"; fi; TMP=$(mktemp -d); curl -fsSL -o "${TMP}/${ZIP}" "https://github.com/pantry-pm/pantry/releases/${REL}/${ZIP}"; unzip -o "${TMP}/${ZIP}" -d /usr/local/bin; chmod +x /usr/local/bin/pantry; rm -rf "${TMP}"','export PATH="/usr/local/bin:$PATH"',"mkdir -p /opt/pantry"]}function ft(){return'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true'}function Ge(e){if(e.length===0)return[];return[`(cd /opt/pantry && pantry install ${[...new Set(e)].map(N).join(" ")})`]}function ao(e){return[...new Set(e)].flatMap((t)=>[`(cd /opt/pantry && pantry start ${N(t)})`,`(cd /opt/pantry && pantry enable ${N(t)})`])}var S="/etc/mail",T="mail-server",F="mail",G=`${M}/pantry/.bin`;function h(e){return`'${String(e).split("'").join("'\\''")}'`}function b(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function fe(e){return[e.version?`${O.mail}@${e.version}`:O.mail]}function Y(e,t){return`${S}/dkim/${t}.${e.dkim.selector}.pem`}function te(e){return`${e.storagePath}/smtp.db`}function ge(e){let t=["# Generated by ts-cloud. Edits are overwritten on the next deploy —","# change `services.mail` in the cloud config instead.","","[server]",`host = ${b(e.bindAddress)}`,`port = ${e.ports.smtp}`,`hostname = ${b(e.hostname)}`];if(e.domains.length>0)t.push(`local_domains = ${b(e.domains.join(", "))}`);if(e.mode==="catcher")t.push("catch_all = true");if(t.push(`max_message_size = ${e.maxMessageSize}`,"","[tls]",`enabled = ${e.tls.enabled}`),e.tls.certPath)t.push(`cert_path = ${b(e.tls.certPath)}`);if(e.tls.keyPath)t.push(`key_path = ${b(e.tls.keyPath)}`);if(t.push("","[auth]",`enabled = ${e.mode==="server"}`,"","[antispam]",`dnsbl = ${e.spam.dnsbl}`,`greylist = ${e.spam.greylist}`,`spam_filter = ${e.spam.enabled}`,`junk_score = ${e.spam.junkScore}`,`reject_score = ${e.spam.rejectScore}`,"","[dkim]",`rotation_enabled = ${e.dkim.enabled&&e.dkim.rotate}`,`rotation_interval_days = ${e.dkim.rotateIntervalDays}`,"","[acme]",`enabled = ${e.tls.acme}`),e.tls.acmeEmail)t.push(`email = ${b(e.tls.acmeEmail)}`);if(t.push("","[webhook]",`enabled = ${!!e.webhookUrl}`),e.webhookUrl)t.push(`url = ${b(e.webhookUrl)}`);return t.push(""),t.join(`
|
|
2
|
+
`)}function Te(e){let t=["# Generated by ts-cloud. See /etc/mail/config.toml for the rest.",`SMTP_DB_PATH=${te(e)}`,`SMTP_DELIVERY_METHOD=${e.delivery==="ses"?"ses":"direct"}`];if(e.delivery==="ses")t.push(`SMTP_SES_REGION=${e.sesRegion}`);if(e.ports.submission)t.push(`SUBMISSION_PORT=${e.ports.submission}`);if(e.ports.submissions)t.push(`SMTPS_PORT=${e.ports.submissions}`);if(e.ports.imap)t.push("IMAP_ENABLED=1",`IMAP_PORT=${e.ports.imap}`);if(e.webmail.enabled)t.push("SMTP_ENABLE_WEBMAIL=true",`SMTP_WEBMAIL_PORT=${e.webmail.port}`,`SMTP_WEBMAIL_SECURE_COOKIES=${e.tls.enabled}`);if(e.tls.requireForAuth)t.push("SMTP_REQUIRE_TLS_FOR_AUTH=true");if(e.dkim.enabled&&e.domains.length>0){let[r,...n]=e.domains;if(t.push(`DKIM_DOMAIN=${r}`,`DKIM_SELECTOR=${e.dkim.selector}`,`DKIM_PRIVATE_KEY_PATH=${Y(e,r)}`),n.length>0){let i=n.map((s)=>`${s}:${e.dkim.selector}:${Y(e,s)}`);t.push(`DKIM_EXTRA_KEYS=${i.join(",")}`)}}return t.push(""),t.join(`
|
|
3
|
+
`)}function he(e){let t=[e.ports.smtp,e.ports.submission,e.ports.submissions,e.ports.imap,e.ports.imaps].some((r)=>typeof r==="number"&&r<1024);return["[Unit]","Description=Mail server (SMTP/IMAP + webmail)","After=network-online.target","Wants=network-online.target","","[Service]","Type=simple",`User=${T}`,`Group=${T}`,`WorkingDirectory=${e.storagePath}`,`EnvironmentFile=${S}/mail.env`,`Environment="PATH=${G}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"`,`ExecStart=${G}/mail serve --config ${S}/config.toml`,"Restart=always","RestartSec=5","LimitNOFILE=65536",...t?["AmbientCapabilities=CAP_NET_BIND_SERVICE","CapabilityBoundingSet=CAP_NET_BIND_SERVICE"]:[],"NoNewPrivileges=true","PrivateTmp=true","ProtectSystem=strict","ProtectHome=true","ProtectKernelTunables=true","ProtectKernelModules=true","ProtectControlGroups=true",`ReadWritePaths=${e.storagePath} ${S}`,"","[Install]","WantedBy=multi-user.target",""].join(`
|
|
4
|
+
`)}function ve(e){if(!e.dkim.enabled||e.domains.length===0)return[];let t=[`mkdir -p ${S}/dkim`];for(let r of e.domains){let n=Y(e,r);t.push(`if [ ! -f ${h(n)} ]; then openssl genrsa -out ${h(n)} 2048; fi`,`chmod 0600 ${h(n)}`,`echo "DKIM ${e.dkim.selector}._domainkey.${r} IN TXT v=DKIM1; k=rsa; p=$(openssl rsa -in ${h(n)} -pubout -outform PEM 2>/dev/null | grep -v '^-----' | tr -d '\\n')"`)}return t.push(`chown -R ${T}:${T} ${S}/dkim`),t}function ye(e){if(e.accounts.length===0)return[];let t=(r)=>`runuser -u ${T} -- env SMTP_DB_PATH="$TS_CLOUD_MAIL_DB" ${G}/mail user:local ${r} || true`;return e.accounts.flatMap((r)=>[t(`create ${h(r.address)} ${h(r.password)} ${h(r.address)}`),t(`change-password ${h(r.address)} ${h(r.password)}`)])}function re(e){if(!e.enabled)return[];return[...Ge(fe(e)),`id -u ${T} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin ${T}`,`mkdir -p ${e.storagePath} ${S}`,`chown -R ${T}:${T} ${e.storagePath}`,`TS_CLOUD_MAIL_DB="$(grep -sE '^SMTP_DB_PATH=' ${S}/mail.env | head -1 | cut -d= -f2- || true)"`,`[ -n "$TS_CLOUD_MAIL_DB" ] || TS_CLOUD_MAIL_DB=${h(te(e))}`,`cat > ${S}/config.toml <<'TS_CLOUD_MAIL_CONF_EOF'`,ge(e),"TS_CLOUD_MAIL_CONF_EOF",`cat > ${S}/mail.env <<'TS_CLOUD_MAIL_ENV_EOF'`,Te(e),"TS_CLOUD_MAIL_ENV_EOF",`sed -i "s|^SMTP_DB_PATH=.*|SMTP_DB_PATH=$TS_CLOUD_MAIL_DB|" ${S}/mail.env`,`chmod 0640 ${S}/mail.env`,`chown root:${T} ${S}/mail.env`,...ve(e),`cat > /etc/systemd/system/${F}.service <<'TS_CLOUD_MAIL_UNIT_EOF'`,he(e),"TS_CLOUD_MAIL_UNIT_EOF","systemctl daemon-reload",`systemctl enable ${F}`,`systemctl restart ${F}`,...ye(e)]}var g=`${M}/pantry/.bin`,X=15306,K=15991,w=15999,ne=16101,B=2379,v="/var/lib/vitess",z=100;function ii(e){return e===!0||typeof e==="object"&&e!==null}function Ee(e){return typeof e==="object"&&e!==null?e:{}}function m(e){return`'${String(e).split("'").join("'\\''")}'`}function Pe(e){let r=[e.version?`vitess.io@${e.version}`:"vitess.io"];if(e.mode!=="combo"&&!e.etcdEndpoint)r.push("etcd.io");return r.push("mysql.com@8.0.43"),r}var _="vitess",be=`${g}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`,ae="/usr/local/lib/vitess",Q=new Map;function j(e){return`${ae}/${e}.sh`}function D(e,t){return Q.set(e,Ce(t)),`/bin/sh ${j(e)}`}function se(){let e=[`mkdir -p ${ae}`];for(let[t,r]of Q)e.push(`cat > ${j(t)} <<'TS_CLOUD_VITESS_LAUNCHER_EOF'`,r,"TS_CLOUD_VITESS_LAUNCHER_EOF",`chmod 0755 ${j(t)}`);return e}function Ce(e){return["#!/bin/sh","set -e",`cd ${M}`,`PANTRY_ENV="$(pantry env 2>/dev/null | grep -E '^(export [A-Za-z_]|[A-Za-z_][A-Za-z0-9_]*=)' || true)"`,'if [ -n "$PANTRY_ENV" ]; then eval "$PANTRY_ENV"; fi',`VT_MYSQL_ROOT="$(dirname "$(dirname "$(readlink -f ${g}/mysqld 2>/dev/null)")")"`,`VTROOT="$(dirname "$(dirname "$(readlink -f ${g}/mysqlctld 2>/dev/null)")")"`,"export VT_MYSQL_ROOT VTROOT",'LD_LIBRARY_PATH="$VT_MYSQL_ROOT/lib:$VTROOT/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"',"export LD_LIBRARY_PATH",`exec ${e.join(" ")}`].join(`
|
|
5
|
+
`)}function A(e){let t=["[Unit]",`Description=${e.description}`,`After=network.target${e.after?.length?` ${e.after.join(" ")}`:""}`];if(e.requires?.length)t.push(`Requires=${e.requires.join(" ")}`);return t.push("","[Service]","Type=simple",`User=${_}`,`Group=${_}`,`Environment="PATH=${be}"`,`Environment="VTDATAROOT=${v}"`,...Object.entries(e.environment??{}).map(([r,n])=>`Environment="${r}=${n}"`),...(e.execStartPre??[]).map((r)=>`ExecStartPre=${r}`),`ExecStart=${e.execStart}`,"Restart=always","RestartSec=5","LimitNOFILE=65535","","[Install]","WantedBy=multi-user.target"),t.join(`
|
|
6
|
+
`)}function oe(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_VITESS_UNIT_EOF'`,t,"TS_CLOUD_VITESS_UNIT_EOF"]}function Re(e){let t=e.cell??"zone1",r=e.vtgatePort??X,i=`${((e.keyspaces?.length)?e.keyspaces:[{name:"app"}]).map((s)=>{let c=(s.sharded?["-80","80-"]:["0"]).map((d)=>`shards:{name:"${d}"}`).join(" ");return`keyspaces:{name:"${s.name}" ${c}}`}).join(" ")} cells:"${t}"`;return A({description:"Vitess (vtcombo, single-process development stack)",execStart:D("vtcombo",[`${g}/vtcombo`,`--cell ${t}`,`--proto-topo ${m(i)}`,`--mysql-server-port ${r}`,"--mysql-server-bind-address 127.0.0.1","--mysql-auth-server-impl none","--start-mysql",`--port ${K}`,`--grpc-port ${w}`])})}function De(){return A({description:"etcd (Vitess topology store)",execStart:D("etcd",[`${g}/etcd`,`--data-dir ${v}/etcd`,`--listen-client-urls http://127.0.0.1:${B}`,`--advertise-client-urls http://127.0.0.1:${B}`]),execStartPre:[`+/bin/mkdir -p ${v}/etcd`,`+/bin/chown ${_}:${_} ${v}/etcd`]})}function J(e){return["--topo-implementation etcd2",`--topo-global-server-address ${e.etcdEndpoint??`http://127.0.0.1:${B}`}`,"--topo-global-root /vitess/global"]}function Ae(e){let t=!e.etcdEndpoint;return A({description:"Vitess vtctld (control plane)",after:t?["vitess-etcd.service"]:[],requires:t?["vitess-etcd.service"]:[],execStart:D("vtctld",[`${g}/vtctld`,...J(e),`--cell ${e.cell??"zone1"}`,"--service-map grpc-vtctl,grpc-vtctld",`--grpc-port ${w}`,`--port ${w+1}`])})}function Le(e,t,r){let n=e.cell??"zone1";return A({description:`Vitess vttablet (${t}/${r})`,after:["vitess-vtctld.service","vitess-mysqlctld.service"],requires:["vitess-mysqlctld.service"],execStart:D("vttablet",[`${g}/vttablet`,...J(e),`--tablet-path ${n}-${String(z).padStart(10,"0")}`,`--init-keyspace ${t}`,`--init-shard ${r}`,"--init-tablet-type replica",`--service-map ${m("grpc-queryservice,grpc-tabletmanager,grpc-updatestream")}`,`--port ${ne}`,`--grpc-port ${ne+1}`,`--db-port ${e.mysqlPort??3306}`,`--mycnf-mysql-port ${e.mysqlPort??3306}`])})}function Oe(e){return A({description:"Vitess mysqlctld (managed mysqld)",execStart:D("mysqlctld",[`${g}/mysqlctld`,`--tablet-uid ${z}`,`--mysql-port ${e.mysqlPort??3306}`,'--init-db-sql-file "$VTROOT/config/init_db.sql"',"--wait-time 2m"]),execStartPre:[`+/bin/mkdir -p ${v}`,`+/bin/chown ${_}:${_} ${v}`]})}var ce="/etc/vitess/auth.json",x="/var/lib/vitess/vtgate-auth.sha256";function xe(e){let t=e.username??"vitess",r=e.password??"";return["mkdir -p /etc/vitess",'VTESS_AUTH_TMP="$(mktemp)"',`cat > "$VTESS_AUTH_TMP" <<'TS_CLOUD_VITESS_AUTH_EOF'`,JSON.stringify({[t]:[{Password:r,UserData:t}]}),"TS_CLOUD_VITESS_AUTH_EOF",`VTESS_VTGATE_AUTH_SHA="$(sha256sum "$VTESS_AUTH_TMP" | awk '{print $1}')"`,"VTESS_VTGATE_AUTH_CHANGED=1",`if [ -f ${x} ] && [ "$(cat ${x})" = "$VTESS_VTGATE_AUTH_SHA" ]; then VTESS_VTGATE_AUTH_CHANGED=0; fi`,`install -o ${_} -g ${_} -m 0600 "$VTESS_AUTH_TMP" ${ce}`,'rm -f "$VTESS_AUTH_TMP"']}function Ue(e){let t=e.cell??"zone1";return A({description:"Vitess vtgate (query router)",after:["vitess-vtctld.service"],execStart:D("vtgate",[`${g}/vtgate`,...J(e),`--cell ${t}`,`--cells-to-watch ${t}`,"--tablet-types-to-wait PRIMARY,REPLICA",`--service-map ${m("grpc-vtgateservice")}`,`--mysql-server-port ${e.vtgatePort??X}`,`--mysql-server-bind-address ${e.bindAddress??"127.0.0.1"}`,"--mysql-auth-server-impl static",`--mysql-auth-server-static-file ${ce}`,`--port ${K}`,`--grpc-port ${K+1}`])})}function Ie(e){let t=e.cell??"zone1",r=e.etcdEndpoint??`http://127.0.0.1:${B}`,n=`${g}/vtctldclient --server 127.0.0.1:${w}`,i=[`for i in $(seq 1 30); do ${n} GetCellInfoNames >/dev/null 2>&1 && break; sleep 2; done`,`if ! ${n} GetCellInfoNames 2>/dev/null | grep -qx ${m(t)}; then`,` ${n} AddCellInfo --root ${m(`/vitess/${t}`)} --server-address ${m(r)} ${m(t)}`,"fi"];for(let s of e.keyspaces??[]){let c=s.sharded?" --sharded":"";i.push(`if ! ${n} GetKeyspace ${m(s.name)} >/dev/null 2>&1; then`,` ${n} CreateKeyspace${c} ${m(s.name)}`,"fi");let d=`${t}-${String(z).padStart(10,"0")}`;for(let l of s.sharded?["-80","80-"]:["0"]){let o=`${s.name}/${l}`;i.push("for i in $(seq 1 90); do",` if ${n} GetShard ${m(o)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then break; fi`,` ${n} PlannedReparentShard ${m(o)} --new-primary ${m(d)} >/dev/null 2>&1 && break`,` ${n} InitShardPrimary --force ${m(o)} ${m(d)} >/dev/null 2>&1 && break`," sleep 2","done",`if ! ${n} GetShard ${m(o)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then`,` echo "no primary could be elected for ${o}" >&2; exit 1`,"fi")}i.push(`${n} RebuildKeyspaceGraph ${m(s.name)} >/dev/null`)}return i}function ie(e){let t=e.vtgatePort??X;return["for i in $(seq 1 60); do",` if (cd ${M} && eval "$(pantry env 2>/dev/null)"; MYSQL_PWD=${m(e.password??"")} ${g}/mysql -h 127.0.0.1 -P ${t} -u ${m(e.username??"vitess")} --connect-timeout=2 -e 'SHOW KEYSPACES') >/dev/null 2>&1; then`,` echo "vtgate is serving on ${t}"; exit 0`," fi"," sleep 2","done",`echo "vtgate did not become ready on port ${t}" >&2`,"exit 1"]}function co(e){if(!ii(e))return[];let t=Ee(e),r=t.mode==="combo";Q.clear();let n=['if [ "$(uname -m)" != "x86_64" ]; then',' echo "vitess: Vitess publishes only x86_64 release tarballs; this box is $(uname -m). Drop managedServices.vitess or use an x86_64 host." >&2'," exit 1","fi",...Ge(Pe(t)),`VT_MYSQL_LIB="$(dirname "$(dirname "$(readlink -f ${g}/mysqld)")")/lib"`,'if [ -d "$VT_MYSQL_LIB" ]; then',` printf '%s\\n' "$VT_MYSQL_LIB" > /etc/ld.so.conf.d/vitess-mysql.conf`," ldconfig","else",' echo "mysqld library directory not found under $VT_MYSQL_LIB" >&2; exit 1',"fi",`id -u ${_} >/dev/null 2>&1 || useradd --system --home-dir ${v} --shell /usr/sbin/nologin ${_}`,`mkdir -p ${v}`,`chown -R ${_}:${_} ${v}`];if(r)return n.push(...oe("vitess-vtcombo",Re(t)),...se(),"systemctl daemon-reload","systemctl enable --now vitess-vtcombo.service",...ie(t)),n;n.push(...xe(t));let i=[];if(!t.etcdEndpoint)i.push(["vitess-etcd",De()]);i.push(["vitess-vtctld",Ae(t)],["vitess-mysqlctld",Oe(t)],["vitess-vtgate",Ue(t)]);for(let s of t.keyspaces??[])for(let c of s.sharded?["-80","80-"]:["0"])i.push([`vitess-vttablet-${s.name}-${c.replace(/-/g,"x")}`,Le(t,s.name,c)]);for(let[s,c]of i)n.push(...oe(s,c));n.push(...se()),n.push("systemctl daemon-reload");for(let[s]of i)n.push(`systemctl enable --now ${s}.service`);return n.push(`if [ "$VTESS_VTGATE_AUTH_CHANGED" = 1 ]; then systemctl restart vitess-vtgate.service; printf '%s\\n' "$VTESS_VTGATE_AUTH_SHA" > ${x}; chown ${_}:${_} ${x}; chmod 0600 ${x}; fi`,...Ie(t),...ie(t)),n}var ke=new Set(["singlestore","vitess"]);function oi(e){if(e?.engine&&ke.has(e.engine))return!1;return!e?.host||e.host==="127.0.0.1"||e.host==="localhost"}function fr(e,t="psql"){let r=e?.port??5432;if(oi(e))return`${t} -p ${r} -U postgres`;let n=e?.username||"postgres";return`${e?.password?`PGPASSWORD='${e.password.replace(/'/g,"'\\''")}' `:""}${t} -h ${e.host} -p ${r} -U ${n} -w`}function y(e){return e===!0||typeof e==="object"&&e!=null}function Ne(e){let t=[],r=[];if(y(e.mysql))t.push(typeof e.mysql==="object"&&e.mysql.version?`mysql.com@${e.mysql.version}`:"mysql.com@8.0.43"),r.push("mysql");else if(y(e.mariadb))t.push(O.mariadb),r.push("mariadb");if(y(e.postgres))t.push("postgresql.org"),r.push("postgres");if(y(e.redis))t.push("redis.io"),r.push("redis");if(y(e.memcached))t.push("memcached.org"),r.push("memcached");if(y(e.meilisearch))t.push("meilisearch.com"),r.push("meilisearch");return{packages:t,services:r}}function lo(e={},t={}){let r=Ne(e),n=co(e.vitess),i=t.mail?re(t.mail):[];if(r.packages.length===0)return[...n,...i];return[...Ge(r.packages),...ao(r.services),...n,...i]}function ht(e,t={}){if(!e?.name)return[];if(!oi(e))return[];let r=e.name,n=e.username||r,i=e.password||"",s=y(t.postgres)||e.engine==="postgres",c=y(t.mariadb)||e.engine==="mariadb",d=y(t.mysql)||e.engine==="mysql";if(s&&!d&&!c){let a=(u)=>`"${u.replace(/"/g,'""')}"`,R=(u)=>`'${u.replace(/'/g,"''")}'`,L=(u,k)=>["DO $$ BEGIN",` IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${R(u)}) THEN`,` CREATE ROLE ${a(u)} LOGIN PASSWORD ${R(k)};`," ELSE",` ALTER ROLE ${a(u)} LOGIN PASSWORD ${R(k)};`," END IF;","END $$;"],U=(u)=>{let k=u.databases&&u.databases.length>0?u.databases:[r],H=[];for(let q of k)if(u.access==="readonly")H.push(`GRANT CONNECT ON DATABASE ${a(q)} TO ${a(u.username)};`,`\\connect ${a(q)}`,`GRANT USAGE ON SCHEMA public TO ${a(u.username)};`,`GRANT SELECT ON ALL TABLES IN SCHEMA public TO ${a(u.username)};`,`ALTER DEFAULT PRIVILEGES FOR ROLE ${a(n)} IN SCHEMA public GRANT SELECT ON TABLES TO ${a(u.username)};`,"\\connect postgres");else H.push(`GRANT ALL PRIVILEGES ON DATABASE ${a(q)} TO ${a(u.username)};`);return H},I=e.users||[],me=e.port??5432;return[ft(),`for i in $(seq 1 30); do pg_isready -p ${me} -q && break; sleep 2; done`,`${fr(e)} <<'TS_CLOUD_PG_EOF'`,...L(n,i),`SELECT 'CREATE DATABASE ${a(r)} OWNER ${a(n)}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = ${R(r)})\\gexec`,...I.flatMap((u)=>[...L(u.username,u.password),...U(u)]),"TS_CLOUD_PG_EOF",...Me(e)]}let l=c?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock",o=(a)=>a.replace(/`/g,"``"),f=(a)=>a.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),E=(a)=>{let R=a.databases&&a.databases.length>0?a.databases:[r],L=a.access==="readonly"?"SELECT":"ALL PRIVILEGES",U=[`CREATE USER IF NOT EXISTS '${f(a.username)}'@'%' IDENTIFIED BY '${f(a.password)}';`,`CREATE USER IF NOT EXISTS '${f(a.username)}'@'localhost' IDENTIFIED BY '${f(a.password)}';`,`ALTER USER '${f(a.username)}'@'%' IDENTIFIED BY '${f(a.password)}';`,`ALTER USER '${f(a.username)}'@'localhost' IDENTIFIED BY '${f(a.password)}';`];for(let I of R)U.push(`GRANT ${L} ON \`${o(I)}\`.* TO '${f(a.username)}'@'%';`,`GRANT ${L} ON \`${o(I)}\`.* TO '${f(a.username)}'@'localhost';`);return U},p=e.users||[];return[ft(),`for i in $(seq 1 30); do mysqladmin --socket=${l} -u root ping 2>/dev/null | grep -q alive && break; sleep 2; done`,`mysql --socket=${l} -u root <<'TS_CLOUD_SQL_EOF'`,`CREATE DATABASE IF NOT EXISTS \`${o(r)}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`,...E({username:n,password:i}),...p.flatMap(E),"FLUSH PRIVILEGES;","TS_CLOUD_SQL_EOF"]}function Me(e){return[`${fr(e)} -tA <<'TS_CLOUD_PG_CAP_EOF' || true`,"\\set QUIET on","SELECT CASE WHEN used::float / NULLIF(cap, 0) >= 0.8"," THEN '[ts-cloud] postgres is at ' || used || '/' || cap || ' connections on this server.'"," || ' Raise max_connections (ALTER SYSTEM SET max_connections = ...; then restart) or'"," || ' set idle_session_timeout so abandoned pools are reclaimed.'"," ELSE NULL END","FROM (SELECT (SELECT count(*) FROM pg_stat_activity) AS used,"," (SELECT setting::int FROM pg_settings WHERE name = 'max_connections') AS cap) c","WHERE CASE WHEN used::float / NULLIF(cap, 0) >= 0.8 THEN true ELSE false END;","SELECT '[ts-cloud] ' || coalesce(datname, '(background)') || ': ' || count(*) || ' connection(s), oldest idle ' ||"," coalesce(round(extract(epoch from max(now() - state_change)) / 60)::text || 'm', 'n/a')","FROM pg_stat_activity","WHERE (SELECT count(*)::float / NULLIF((SELECT setting::int FROM pg_settings WHERE name = 'max_connections'), 0) FROM pg_stat_activity) >= 0.8","GROUP BY datname ORDER BY count(*) DESC;","TS_CLOUD_PG_CAP_EOF"]}function Ba(e){if(!e?.name)return{};let t=e.engine==="singlestore",r=e.engine==="vitess",n=e.engine==="postgres"?"pgsql":t?"singlestore":r?"vitess":"mysql",i=e.port??(e.engine==="postgres"?5432:r?15306:3306),s={DB_CONNECTION:n,DB_HOST:e.host||"127.0.0.1",DB_PORT:String(i),DB_DATABASE:e.name};if(e.username)s.DB_USERNAME=e.username;if(e.password)s.DB_PASSWORD=e.password;if((t||r)&&e.ssl!==!1)s.DB_SSL="true";return s}var Z="/var/backups/ts-cloud",Ve="/etc/ts-cloud/backups.config.ts",le="/etc/cron.d/ts-cloud-backups",Kr="/usr/local/bin/ts-cloud-backup.sh";function we(e){if(!e.name)return null;let t=e.host||"127.0.0.1",r=e.engine==="postgres",n=r?"postgresql":"mysql",i=e.port??(r?5432:3306),s=(c)=>c.replace(/\\/g,"\\\\").replace(/'/g,"\\'");return[" {",` type: '${n}',`,` name: '${s(e.name)}',`," connection: {",` hostname: '${s(t)}',`,` port: ${i},`,` database: '${s(e.name)}',`,` username: '${s(e.username||e.name)}',`,` password: '${s(e.password||"")}',`," ssl: false,"," },"," includeSchema: true,"," includeData: true,"," },"].join(`
|
|
7
|
+
`)}function Be(e,t){let r=e?we(e):null,n=t.bucket?[" destinations: ["," {"," type: 's3',",` bucket: '${t.bucket}',`," prefix: 'db-backups',",...t.endpoint?[` endpoint: '${t.endpoint}',`]:[]," optional: false,"," },"," ],"]:[];return["import type { BackupConfig } from 'ts-backups'","","const config: BackupConfig = {"," verbose: true,",` outputPath: '${Z}',`," retention: {",` count: ${t.retentionCount??5},`,` maxAge: ${t.retentionDays??30},`," },"," databases: [",...r?[r]:[]," ],",...n,"}","","export default config",""].join(`
|
|
8
|
+
`)}function uo(e){let{database:t,backups:r}=e;if(!r.enabled)return[];let n=r.schedule||"0 2 * * *",i=Be(t,r);return["export DEBIAN_FRONTEND=noninteractive",`mkdir -p /etc/ts-cloud ${Z}`,"command -v bun >/dev/null 2>&1 || (curl -fsSL https://bun.sh/install | bash && ln -sf /root/.bun/bin/bun /usr/local/bin/bun)","bun add -g ts-backups || true",`cat > ${Ve} <<'TS_CLOUD_BACKUP_CFG_EOF'`,i.replace(/\n$/,""),"TS_CLOUD_BACKUP_CFG_EOF",`cat > ${Kr} <<'TS_CLOUD_BACKUP_RUN_EOF'`,"#!/bin/bash","set -uo pipefail",'export PATH="/root/.bun/bin:/usr/local/bin:$PATH"','notify() { [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "$1" || true; }',"cd /etc/ts-cloud",'if ! ts-backups backup --config /etc/ts-cloud/backups.config.ts; then notify "❌ ts-cloud backup failed"; exit 1; fi',"TS_CLOUD_BACKUP_RUN_EOF",`chmod +x ${Kr}`,`cat > ${le} <<'TS_CLOUD_BACKUP_CRON_EOF'`,`${n} root ${Kr} >> /var/log/ts-cloud-backup.log 2>&1`,"TS_CLOUD_BACKUP_CRON_EOF",`chmod 644 ${le}`]}function He(e){return e==="mariadb"?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock"}function si(e,t={}){if(!e?.name)return[];let r=e.name,n=e.engine==="postgres",i=t.from?`TS_CLOUD_DUMP="${t.from}"`:`TS_CLOUD_DUMP="$(find ${Z} -type f -name '*${r}*.sql' -o -type f -name '*${r}*.sql.gz' 2>/dev/null | xargs -r ls -1t 2>/dev/null | head -1)"`,s=n?`${fr(e)} -d "${r}"`:`mysql --socket=${He(e.engine)} -u root "${r}"`;return["set -uo pipefail",'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true',i,'[ -n "$TS_CLOUD_DUMP" ] && [ -f "$TS_CLOUD_DUMP" ] || { echo "no backup dump found to restore" >&2; exit 1; }','echo "[ts-cloud] restoring '+r+' from $TS_CLOUD_DUMP"',`case "$TS_CLOUD_DUMP" in *.gz) gunzip -c "$TS_CLOUD_DUMP" ;; *) cat "$TS_CLOUD_DUMP" ;; esac | ${s}`,'echo "restore complete"']}var po=["storage",".env"],ai=4;function C(e){return`${e.replace(/\/+$/,"")}/.ts-cloud`}function ys(e){return`${C(e)}/deploy-history.log`}function qe(e,t){return`${C(e)}/deploys/${t}.log`}function ue(e){return`${C(e)}/shared-paths`}function Ot(e,t){let r=e.replace(/\/+$/,"");return{base:r,releases:`${r}/releases`,shared:`${r}/shared`,current:`${r}/current`,release:`${r}/releases/${t}`}}function de(e){let t=e.split("/").pop()||e;if(t===".env"||t.startsWith(".env."))return!0;return/\.[a-z0-9]+$/i.test(t)}function Ss(e){return typeof e==="string"?e:e.path}function Fa(e){let t=new Map;for(let r of e)t.set(Ss(r),r);return[...t.values()]}function $e(e,t){if(typeof t==="string")return{path:t,target:`${e.shared}/${t}`,seed:!0};return{path:t.path,target:t.target??`${e.shared}/${t.path}`,seed:t.seed!==!1}}function Fe(e){return["ts_cloud_adopt_shared() {",' TS_CLOUD_SP="$1"',' TS_CLOUD_DST="$2"',` TS_CLOUD_SRC="${e.current}/$TS_CLOUD_SP"`,' if [ -e "$TS_CLOUD_DST" ]; then return 0; fi',' if [ -L "$TS_CLOUD_SRC" ] || [ ! -e "$TS_CLOUD_SRC" ]; then return 0; fi',' mkdir -p "$(dirname "$TS_CLOUD_DST")"',' cp -a "$TS_CLOUD_SRC" "$TS_CLOUD_DST"'," for TS_CLOUD_SIDECAR in -wal -shm; do",' if [ -f "$TS_CLOUD_SRC$TS_CLOUD_SIDECAR" ]; then cp -a "$TS_CLOUD_SRC$TS_CLOUD_SIDECAR" "$TS_CLOUD_DST$TS_CLOUD_SIDECAR"; fi'," done",' echo "[ts-cloud] adopted $TS_CLOUD_SP from the live release into shared/ — it now survives deploys"'," return 0","}"]}function ci(e,t=po){let r=[`mkdir -p ${e.releases} ${e.shared}`,...Fe(e)],n=t.map((s)=>$e(e,s));for(let{path:s,target:c,seed:d}of n){if(!d)continue;if(r.push(`ts_cloud_adopt_shared '${s}' '${c}'`),de(s))r.push(`mkdir -p "$(dirname ${c})"`,`touch ${c}`);else if(s==="storage")r.push(`mkdir -p ${c}/app/public`,`mkdir -p ${c}/framework/cache/data`,`mkdir -p ${c}/framework/sessions`,`mkdir -p ${c}/framework/testing`,`mkdir -p ${c}/framework/views`,`mkdir -p ${c}/logs`);else r.push(`mkdir -p ${c}`)}let i=ue(e.base);return r.push(`mkdir -p ${C(e.base)}`,`cat > ${i} <<'TS_CLOUD_SHARED_PATHS_EOF'`,...n.map((s)=>`${s.path} ${s.target}`),"TS_CLOUD_SHARED_PATHS_EOF"),r}function bs(e,t=900){let r=`${C(e.base)}/deploy.lock`;return[`mkdir -p "$(dirname ${r})"`,`exec 9>${r}`,`flock -w ${t} 9 || { echo "[ts-cloud] another deploy of this site has held the lock for ${t}s — refusing to race it" >&2; exit 1; }`]}function vs(e){let t=`${e.release}.incoming`;return[`rm -rf ${t}`,`mkdir -p ${t}`,...Ye(e),'if [ "$TS_CLOUD_IS_LIVE" = "yes" ]; then',` TS_CLOUD_STAGED=${t}`,"else",` rm -rf ${e.release}`,` mkdir -p ${e.release}`,` rmdir ${t}`,` TS_CLOUD_STAGED=${e.release}`,"fi"]}function Ts(e){let t=`TS_CLOUD_TRAP_LIVE="$(readlink -f ${e.current} 2>/dev/null || true)"`,r=`TS_CLOUD_TRAP_TARGET="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`;return`trap '${`if [ $? -ne 0 ]; then ${t}; ${r}; [ "$TS_CLOUD_TRAP_LIVE" = "$TS_CLOUD_TRAP_TARGET" ] || rm -rf ${e.release}; fi`}' EXIT`}function Ye(e){return[`TS_CLOUD_LIVE_PATH="$(readlink -f ${e.current} 2>/dev/null || true)"`,`TS_CLOUD_RELEASE_PATH="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`,'if [ -n "$TS_CLOUD_LIVE_PATH" ] && [ "$TS_CLOUD_LIVE_PATH" = "$TS_CLOUD_RELEASE_PATH" ]; then TS_CLOUD_IS_LIVE=yes; else TS_CLOUD_IS_LIVE=no; fi']}function Es(e){let t=`${e.release}.incoming`;return[`if [ "$TS_CLOUD_STAGED" = "${t}" ]; then`,` rm -rf ${e.release}.previous`,` mv ${e.release} ${e.release}.previous`,` mv ${t} ${e.release}`,` rm -rf ${e.release}.previous`,"fi"]}function Ke(e,t){return[`if [ -f ${e} ] && [ ! -L ${e} ] && [ -s ${e} ] && [ ! -s ${t} ]; then`,` cp -a ${e} ${t}`,` echo "[ts-cloud] seeded shared/ from the release's own copy of the file"`,"fi"]}function mo(e,t=po){let r=[];for(let n of t){let{path:i,target:s,seed:c}=$e(e,n),d=`${e.release}/${i}`,l=[`rm -rf ${d}`,`mkdir -p "$(dirname ${d})"`,`ln -sfn ${s} ${d}`];if(c){if(i!==".env"&&de(i))r.push(...Ke(d,s));r.push(...l);continue}r.push(`if [ -e ${s} ]; then`,...l.map((o)=>` ${o}`),"fi")}return r}function pe(e,t){let r=ue(e.base);return[`if [ -f ${r} ]; then`,' while IFS="\t" read -r TS_CLOUD_SP TS_CLOUD_TGT; do',' [ -n "$TS_CLOUD_SP" ] || continue',` [ -n "$TS_CLOUD_TGT" ] || TS_CLOUD_TGT="${e.shared}/$TS_CLOUD_SP"`,' [ -e "$TS_CLOUD_TGT" ] || continue',` rm -rf ${t}/"$TS_CLOUD_SP"`,` mkdir -p "$(dirname ${t}/"$TS_CLOUD_SP")"`,` ln -sfn "$TS_CLOUD_TGT" ${t}/"$TS_CLOUD_SP"`,` done < ${r}`,"fi"]}function Jr(e){return[`ln -sfn ${e.release} ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`]}function ja(e,t={}){let r=t.to?[`[ -d ${e.releases}/${t.to} ] || { echo "rollback target ${e.releases}/${t.to} not found" >&2; exit 1; }`,...pe(e,`${e.releases}/${t.to}`),`ln -sfn ${e.releases}/${t.to} ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`]:[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,`TS_CLOUD_PREV=$(ls -1dt ${e.releases}/*/ 2>/dev/null | sed 's#/$##' | while read -r r; do [ "$(readlink -f "$r")" != "$TS_CLOUD_CURRENT" ] && { echo "$r"; break; }; done)`,'[ -n "$TS_CLOUD_PREV" ] || { echo "no previous release to roll back to" >&2; exit 1; }',...pe(e,'"$TS_CLOUD_PREV"'),`ln -sfn "$TS_CLOUD_PREV" ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`,'echo "rolled back to $TS_CLOUD_PREV"'];if(!t.unitBase)return r;let n=t.unitBase;return[...r,`TS_CLOUD_RB_ID=$(basename "$(readlink -f ${e.current})")`,`if [ -f /etc/systemd/system/${n}@.service ]; then systemctl start "${n}@\${TS_CLOUD_RB_ID}.service"; sleep 2; systemctl is-active --quiet "${n}@\${TS_CLOUD_RB_ID}.service" || { echo "rolled-back release failed to start" >&2; exit 1; }; systemctl enable "${n}@\${TS_CLOUD_RB_ID}.service" 2>/dev/null || true; systemctl list-units --plain --no-legend --type=service "${n}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v "^${n}@\${TS_CLOUD_RB_ID}.service$" || true; } | while read -r TS_CLOUD_U; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done; elif [ -f /etc/systemd/system/${n}.service ]; then systemctl restart ${n}.service; fi`]}function Xr(e,t=4){let r=Math.max(1,t);return[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,`ls -1dt ${e.releases}/*/ 2>/dev/null | sed 's#/$##' | tail -n +${r+1} | while read -r TS_CLOUD_OLD; do`,' [ "$(readlink -f "$TS_CLOUD_OLD")" = "$TS_CLOUD_CURRENT" ] || rm -rf "$TS_CLOUD_OLD"',"done"]}function je(e){return`${C(e)}/owner`}function ws(e,t){let r=je(e);return[`if [ -f "${r}" ]; then`,` TS_CLOUD_OWNER=$(cat "${r}")`,` if [ "$TS_CLOUD_OWNER" != "${t}" ]; then`,` echo "[ts-cloud] REFUSING deploy: ${e} belongs to project '$TS_CLOUD_OWNER', not '${t}'. Another project on this box derives the same site key — give one of them a distinct site name/domain, or remove ${r} to transfer ownership." >&2`," exit 1"," fi","else",` mkdir -p "$(dirname "${r}")"`,` printf '%s\\n' "${t}" > "${r}"`,"fi"]}function go(e,t){let r=C(e),n=qe(e,t.releaseId),i=ys(e),s=Math.max(1,t.keepLogs??20),c=t.commit||"",d=t.branch||"";return[`mkdir -p ${r}/deploys`,`exec > >(tee -a ${n}) 2>&1`,`echo "[ts-cloud] deploy ${t.releaseId} commit=${c} branch=${d} starting $(date -u +%Y-%m-%dT%H:%M:%SZ)"`,"ts_cloud_record_deploy() {"," TS_CLOUD_RC=$?",' if [ "$TS_CLOUD_RC" -eq 0 ]; then TS_CLOUD_ST=success; else TS_CLOUD_ST=failed; fi',` printf '%s\\t%s\\t%s\\t%s\\trc=%s\\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "${t.releaseId}" "${c}" "$TS_CLOUD_ST" "$TS_CLOUD_RC" >> ${i}`,"}","trap ts_cloud_record_deploy EXIT",`ls -1t ${r}/deploys/*.log 2>/dev/null | tail -n +${s+1} | while read -r TS_CLOUD_OLDLOG; do rm -f "$TS_CLOUD_OLDLOG"; done`]}
|
|
9
|
+
export{W,ni,gs,P,so,fs,hs,Ma,Ua,M,gr,ft,Ge,ao,ii,co,oi,fr,lo,ht,Ba,Kr,uo,si,po,ai,ys,Ot,Ss,Fa,ci,bs,vs,Ts,Es,mo,Jr,ja,Xr,ws,go};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{u}from"./chunk-bckm6fre.js";class K{client;region;constructor(e="us-east-1"){this.region=e,this.client=new u}async describeInstances(e){let t={Action:"DescribeInstances",Version:"2016-11-15"};if(e?.InstanceIds)e.InstanceIds.forEach((r,a)=>{t[`InstanceId.${a+1}`]=r});if(e?.Filters)e.Filters.forEach((r,a)=>{t[`Filter.${a+1}.Name`]=r.Name,r.Values.forEach((i,c)=>{t[`Filter.${a+1}.Value.${c+1}`]=i})});if(e?.MaxResults)t.MaxResults=String(e.MaxResults);if(e?.NextToken)t.NextToken=e.NextToken;let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),n=s.DescribeInstancesResponse||s;return{Reservations:this.parseReservations(n.reservationSet?.item),NextToken:n.nextToken}}async getInstance(e){return(await this.describeInstances({InstanceIds:[e]})).Reservations?.[0]?.Instances?.[0]}async getConsoleOutput(e,t){let s={Action:"GetConsoleOutput",Version:"2016-11-15",InstanceId:e};if(t)s.Latest="true";let n=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(s).toString()}),r=n.GetConsoleOutputResponse||n;return{InstanceId:r.instanceId,Output:r.output,Timestamp:r.timestamp}}async getConsoleOutputDecoded(e,t){let s=await this.getConsoleOutput(e,t?.latest);if(!s.Output)return"No console output available yet";let n=Buffer.from(s.Output,"base64").toString("utf-8");if(t?.tailLines)return n.split(`
|
|
2
2
|
`).slice(-t.tailLines).join(`
|
|
3
3
|
`);return n}async describeInstanceStatus(e){let t={Action:"DescribeInstanceStatus",Version:"2016-11-15"};if(e?.InstanceIds)e.InstanceIds.forEach((n,r)=>{t[`InstanceId.${r+1}`]=n});if(e?.IncludeAllInstances)t.IncludeAllInstances="true";if(e?.Filters)e.Filters.forEach((n,r)=>{t[`Filter.${r+1}.Name`]=n.Name,n.Values.forEach((a,i)=>{t[`Filter.${r+1}.Value.${i+1}`]=a})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{InstanceStatuses:this.parseArray(s.instanceStatusSet?.item).map((n)=>({InstanceId:n.instanceId,InstanceState:n.instanceState?{Code:Number.parseInt(n.instanceState.code),Name:n.instanceState.name}:void 0,InstanceStatus:n.instanceStatus?{Status:n.instanceStatus.status,Details:this.parseArray(n.instanceStatus.details?.item).map((r)=>({Name:r.name,Status:r.status}))}:void 0,SystemStatus:n.systemStatus?{Status:n.systemStatus.status,Details:this.parseArray(n.systemStatus.details?.item).map((r)=>({Name:r.name,Status:r.status}))}:void 0}))}}async startInstances(e){let t={Action:"StartInstances",Version:"2016-11-15"};e.forEach((n,r)=>{t[`InstanceId.${r+1}`]=n});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{StartingInstances:this.parseArray(s.instancesSet?.item).map((n)=>({InstanceId:n.instanceId,CurrentState:n.currentState?{Name:n.currentState.name}:void 0,PreviousState:n.previousState?{Name:n.previousState.name}:void 0}))}}async stopInstances(e,t){let s={Action:"StopInstances",Version:"2016-11-15"};if(e.forEach((r,a)=>{s[`InstanceId.${a+1}`]=r}),t)s.Force="true";let n=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(s).toString()});return{StoppingInstances:this.parseArray(n.instancesSet?.item).map((r)=>({InstanceId:r.instanceId,CurrentState:r.currentState?{Name:r.currentState.name}:void 0,PreviousState:r.previousState?{Name:r.previousState.name}:void 0}))}}async rebootInstances(e){let t={Action:"RebootInstances",Version:"2016-11-15"};e.forEach((s,n)=>{t[`InstanceId.${n+1}`]=s}),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async terminateInstances(e){let t={Action:"TerminateInstances",Version:"2016-11-15"};e.forEach((n,r)=>{t[`InstanceId.${r+1}`]=n});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{TerminatingInstances:this.parseArray(s.instancesSet?.item).map((n)=>({InstanceId:n.instanceId,CurrentState:n.currentState?{Name:n.currentState.name}:void 0,PreviousState:n.previousState?{Name:n.previousState.name}:void 0}))}}async createImage(e){let t={Action:"CreateImage",Version:"2016-11-15",InstanceId:e.InstanceId,Name:e.Name};if(e.Description)t.Description=e.Description;if(e.NoReboot!==void 0)t.NoReboot=String(e.NoReboot);if(e.TagSpecifications)e.TagSpecifications.forEach((r,a)=>{t[`TagSpecification.${a+1}.ResourceType`]=r.ResourceType,r.Tags.forEach((i,c)=>{t[`TagSpecification.${a+1}.Tag.${c+1}.Key`]=i.Key,t[`TagSpecification.${a+1}.Tag.${c+1}.Value`]=i.Value})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{ImageId:(s.CreateImageResponse||s).imageId}}async deregisterImage(e){await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({Action:"DeregisterImage",Version:"2016-11-15",ImageId:e}).toString()})}async describeVpcs(e){let t={Action:"DescribeVpcs",Version:"2016-11-15"};if(e?.VpcIds)e.VpcIds.forEach((n,r)=>{t[`VpcId.${r+1}`]=n});if(e?.Filters)e.Filters.forEach((n,r)=>{t[`Filter.${r+1}.Name`]=n.Name,n.Values.forEach((a,i)=>{t[`Filter.${r+1}.Value.${i+1}`]=a})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{Vpcs:this.parseArray(s.vpcSet?.item).map((n)=>({VpcId:n.vpcId,CidrBlock:n.cidrBlock,State:n.state,DhcpOptionsId:n.dhcpOptionsId,InstanceTenancy:n.instanceTenancy,IsDefault:n.isDefault==="true",Tags:this.parseTags(n.tagSet?.item)}))}}async describeSubnets(e){let t={Action:"DescribeSubnets",Version:"2016-11-15"};if(e?.SubnetIds)e.SubnetIds.forEach((n,r)=>{t[`SubnetId.${r+1}`]=n});if(e?.Filters)e.Filters.forEach((n,r)=>{t[`Filter.${r+1}.Name`]=n.Name,n.Values.forEach((a,i)=>{t[`Filter.${r+1}.Value.${i+1}`]=a})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{Subnets:this.parseArray(s.subnetSet?.item).map((n)=>({SubnetId:n.subnetId,VpcId:n.vpcId,CidrBlock:n.cidrBlock,AvailabilityZone:n.availabilityZone,AvailableIpAddressCount:Number.parseInt(n.availableIpAddressCount),State:n.state,MapPublicIpOnLaunch:n.mapPublicIpOnLaunch==="true",Tags:this.parseTags(n.tagSet?.item)}))}}async describeSecurityGroups(e){let t={Action:"DescribeSecurityGroups",Version:"2016-11-15"};if(e?.GroupIds)e.GroupIds.forEach((n,r)=>{t[`GroupId.${r+1}`]=n});if(e?.GroupNames)e.GroupNames.forEach((n,r)=>{t[`GroupName.${r+1}`]=n});if(e?.Filters)e.Filters.forEach((n,r)=>{t[`Filter.${r+1}.Name`]=n.Name,n.Values.forEach((a,i)=>{t[`Filter.${r+1}.Value.${i+1}`]=a})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{SecurityGroups:this.parseArray(s.securityGroupInfo?.item).map((n)=>({GroupId:n.groupId,GroupName:n.groupName,Description:n.groupDescription,VpcId:n.vpcId,IpPermissions:this.parseIpPermissions(n.ipPermissions?.item),IpPermissionsEgress:this.parseIpPermissions(n.ipPermissionsEgress?.item),Tags:this.parseTags(n.tagSet?.item)}))}}async describeInternetGateways(e){let t={Action:"DescribeInternetGateways",Version:"2016-11-15"};if(e?.InternetGatewayIds)e.InternetGatewayIds.forEach((n,r)=>{t[`InternetGatewayId.${r+1}`]=n});if(e?.Filters)e.Filters.forEach((n,r)=>{t[`Filter.${r+1}.Name`]=n.Name,n.Values.forEach((a,i)=>{t[`Filter.${r+1}.Value.${i+1}`]=a})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{InternetGateways:this.parseArray(s.internetGatewaySet?.item).map((n)=>({InternetGatewayId:n.internetGatewayId,Attachments:this.parseArray(n.attachmentSet?.item).map((r)=>({VpcId:r.vpcId,State:r.state})),Tags:this.parseTags(n.tagSet?.item)}))}}async describeAddresses(e){let t={Action:"DescribeAddresses",Version:"2016-11-15"};if(e?.AllocationIds)e.AllocationIds.forEach((n,r)=>{t[`AllocationId.${r+1}`]=n});if(e?.PublicIps)e.PublicIps.forEach((n,r)=>{t[`PublicIp.${r+1}`]=n});if(e?.Filters)e.Filters.forEach((n,r)=>{t[`Filter.${r+1}.Name`]=n.Name,n.Values.forEach((a,i)=>{t[`Filter.${r+1}.Value.${i+1}`]=a})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{Addresses:this.parseArray(s.addressesSet?.item).map((n)=>({PublicIp:n.publicIp,AllocationId:n.allocationId,AssociationId:n.associationId,InstanceId:n.instanceId,NetworkInterfaceId:n.networkInterfaceId,PrivateIpAddress:n.privateIpAddress,Domain:n.domain,Tags:this.parseTags(n.tagSet?.item)}))}}async allocateAddress(e){let t={Action:"AllocateAddress",Version:"2016-11-15"};if(e?.Domain)t.Domain=e.Domain;if(e?.TagSpecifications)e.TagSpecifications.forEach((n,r)=>{t[`TagSpecification.${r+1}.ResourceType`]=n.ResourceType,n.Tags.forEach((a,i)=>{t[`TagSpecification.${r+1}.Tag.${i+1}.Key`]=a.Key,t[`TagSpecification.${r+1}.Tag.${i+1}.Value`]=a.Value})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{AllocationId:s.allocationId,PublicIp:s.publicIp,Domain:s.domain}}async associateAddress(e){let t={Action:"AssociateAddress",Version:"2016-11-15"};if(e.AllocationId)t.AllocationId=e.AllocationId;if(e.PublicIp)t.PublicIp=e.PublicIp;if(e.InstanceId)t.InstanceId=e.InstanceId;if(e.NetworkInterfaceId)t.NetworkInterfaceId=e.NetworkInterfaceId;if(e.PrivateIpAddress)t.PrivateIpAddress=e.PrivateIpAddress;if(e.AllowReassociation)t.AllowReassociation="true";return{AssociationId:(await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})).associationId}}async createTags(e){let t={Action:"CreateTags",Version:"2016-11-15"};e.Resources.forEach((s,n)=>{t[`ResourceId.${n+1}`]=s}),e.Tags.forEach((s,n)=>{t[`Tag.${n+1}.Key`]=s.Key,t[`Tag.${n+1}.Value`]=s.Value}),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async waitForInstanceState(e,t,s){let n=s?.maxWaitMs||300000,r=s?.pollIntervalMs||5000,a=Date.now();while(Date.now()-a<n){let i;try{i=await this.getInstance(e)}catch{i=void 0}if(i?.State?.Name===t)return i;await new Promise((c)=>setTimeout(c,r))}return}async createVpc(e){let t={Action:"CreateVpc",Version:"2016-11-15",CidrBlock:e.CidrBlock};if(e.InstanceTenancy)t.InstanceTenancy=e.InstanceTenancy;if(e.TagSpecifications)e.TagSpecifications.forEach((a,i)=>{t[`TagSpecification.${i+1}.ResourceType`]=a.ResourceType,a.Tags.forEach((c,o)=>{t[`TagSpecification.${i+1}.Tag.${o+1}.Key`]=c.Key,t[`TagSpecification.${i+1}.Tag.${o+1}.Value`]=c.Value})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),r=(s.CreateVpcResponse||s).vpc;return{Vpc:r?{VpcId:r.vpcId,CidrBlock:r.cidrBlock,State:r.state,DhcpOptionsId:r.dhcpOptionsId,InstanceTenancy:r.instanceTenancy,IsDefault:r.isDefault==="true",Tags:this.parseTags(r.tagSet?.item)}:void 0}}async createSubnet(e){let t={Action:"CreateSubnet",Version:"2016-11-15",VpcId:e.VpcId,CidrBlock:e.CidrBlock};if(e.AvailabilityZone)t.AvailabilityZone=e.AvailabilityZone;if(e.TagSpecifications)e.TagSpecifications.forEach((a,i)=>{t[`TagSpecification.${i+1}.ResourceType`]=a.ResourceType,a.Tags.forEach((c,o)=>{t[`TagSpecification.${i+1}.Tag.${o+1}.Key`]=c.Key,t[`TagSpecification.${i+1}.Tag.${o+1}.Value`]=c.Value})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),r=(s.CreateSubnetResponse||s).subnet;return{Subnet:r?{SubnetId:r.subnetId,VpcId:r.vpcId,CidrBlock:r.cidrBlock,AvailabilityZone:r.availabilityZone,AvailableIpAddressCount:r.availableIpAddressCount?Number.parseInt(r.availableIpAddressCount):void 0,State:r.state,MapPublicIpOnLaunch:r.mapPublicIpOnLaunch==="true",Tags:this.parseTags(r.tagSet?.item)}:void 0}}async modifySubnetAttribute(e){let t={Action:"ModifySubnetAttribute",Version:"2016-11-15",SubnetId:e.SubnetId};if(e.MapPublicIpOnLaunch!==void 0)t["MapPublicIpOnLaunch.Value"]=String(e.MapPublicIpOnLaunch.Value);await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async createSecurityGroup(e){let t={Action:"CreateSecurityGroup",Version:"2016-11-15",GroupName:e.GroupName,GroupDescription:e.Description};if(e.VpcId)t.VpcId=e.VpcId;if(e.TagSpecifications)e.TagSpecifications.forEach((r,a)=>{t[`TagSpecification.${a+1}.ResourceType`]=r.ResourceType,r.Tags.forEach((i,c)=>{t[`TagSpecification.${a+1}.Tag.${c+1}.Key`]=i.Key,t[`TagSpecification.${a+1}.Tag.${c+1}.Value`]=i.Value})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{GroupId:(s.CreateSecurityGroupResponse||s).groupId}}async authorizeSecurityGroupIngress(e){let t={Action:"AuthorizeSecurityGroupIngress",Version:"2016-11-15",GroupId:e.GroupId};this.encodeIpPermissions(t,e.IpPermissions),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async authorizeSecurityGroupEgress(e){let t={Action:"AuthorizeSecurityGroupEgress",Version:"2016-11-15",GroupId:e.GroupId};this.encodeIpPermissions(t,e.IpPermissions),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async describeRouteTables(e){let t={Action:"DescribeRouteTables",Version:"2016-11-15"};if(e?.RouteTableIds)e.RouteTableIds.forEach((r,a)=>{t[`RouteTableId.${a+1}`]=r});if(e?.Filters)e.Filters.forEach((r,a)=>{t[`Filter.${a+1}.Name`]=r.Name,r.Values.forEach((i,c)=>{t[`Filter.${a+1}.Value.${c+1}`]=i})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),n=s.DescribeRouteTablesResponse||s;return{RouteTables:this.parseArray(n.routeTableSet?.item).map((r)=>({RouteTableId:r.routeTableId,VpcId:r.vpcId,Routes:this.parseArray(r.routeSet?.item).map((a)=>({DestinationCidrBlock:a.destinationCidrBlock,GatewayId:a.gatewayId,NatGatewayId:a.natGatewayId,State:a.state})),Associations:this.parseArray(r.associationSet?.item).map((a)=>({RouteTableAssociationId:a.routeTableAssociationId,SubnetId:a.subnetId,Main:a.main==="true"||a.main===!0})),Tags:this.parseTags(r.tagSet?.item)}))}}async deleteVpc(e){let t={Action:"DeleteVpc",Version:"2016-11-15",VpcId:e};await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async deleteSubnet(e){let t={Action:"DeleteSubnet",Version:"2016-11-15",SubnetId:e};await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async deleteSecurityGroup(e){await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({Action:"DeleteSecurityGroup",Version:"2016-11-15",GroupId:e}).toString()})}async describeNetworkInterfaces(e){let t={Action:"DescribeNetworkInterfaces",Version:"2016-11-15"};if(e?.NetworkInterfaceIds)e.NetworkInterfaceIds.forEach((r,a)=>{t[`NetworkInterfaceId.${a+1}`]=r});if(e?.Filters)e.Filters.forEach((r,a)=>{t[`Filter.${a+1}.Name`]=r.Name,r.Values.forEach((i,c)=>{t[`Filter.${a+1}.Value.${c+1}`]=i})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),n=s.DescribeNetworkInterfacesResponse||s;return{NetworkInterfaces:this.parseArray(n.networkInterfaceSet?.item).map((r)=>({NetworkInterfaceId:r.networkInterfaceId,SubnetId:r.subnetId,VpcId:r.vpcId,Status:r.status,Attachment:r.attachment?{AttachmentId:r.attachment.attachmentId,InstanceId:r.attachment.instanceId,Status:r.attachment.status}:void 0}))}}async detachNetworkInterface(e,t){let s={Action:"DetachNetworkInterface",Version:"2016-11-15",AttachmentId:e};if(t)s.Force="true";await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(s).toString()})}async deleteNetworkInterface(e){let t={Action:"DeleteNetworkInterface",Version:"2016-11-15",NetworkInterfaceId:e};await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async describeRegions(){let e={Action:"DescribeRegions",Version:"2016-11-15"},t=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(e).toString()}),s=t.DescribeRegionsResponse||t;return{Regions:this.parseArray(s.regionInfo?.item).map((n)=>({RegionName:n.regionName,Endpoint:n.regionEndpoint}))}}async runInstances(e){let t={Action:"RunInstances",Version:"2016-11-15",ImageId:e.ImageId,InstanceType:e.InstanceType,MinCount:String(e.MinCount),MaxCount:String(e.MaxCount)};if(e.SecurityGroupIds)e.SecurityGroupIds.forEach((r,a)=>{t[`SecurityGroupId.${a+1}`]=r});if(e.SubnetId)t.SubnetId=e.SubnetId;if(e.UserData)t.UserData=e.UserData;if(e.IamInstanceProfile){if(e.IamInstanceProfile.Name)t["IamInstanceProfile.Name"]=e.IamInstanceProfile.Name;if(e.IamInstanceProfile.Arn)t["IamInstanceProfile.Arn"]=e.IamInstanceProfile.Arn}if(e.TagSpecifications)e.TagSpecifications.forEach((r,a)=>{t[`TagSpecification.${a+1}.ResourceType`]=r.ResourceType,r.Tags.forEach((i,c)=>{t[`TagSpecification.${a+1}.Tag.${c+1}.Key`]=i.Key,t[`TagSpecification.${a+1}.Tag.${c+1}.Value`]=i.Value})});let s=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),n=s.RunInstancesResponse||s;return{Instances:this.parseInstances(n.instancesSet?.item||n.instancesSet)}}encodeIpPermissions(e,t){t.forEach((s,n)=>{let r=`IpPermissions.${n+1}`;if(s.IpProtocol!==void 0)e[`${r}.IpProtocol`]=s.IpProtocol;if(s.FromPort!==void 0)e[`${r}.FromPort`]=String(s.FromPort);if(s.ToPort!==void 0)e[`${r}.ToPort`]=String(s.ToPort);if(s.IpRanges)s.IpRanges.forEach((a,i)=>{if(a.CidrIp)e[`${r}.IpRanges.${i+1}.CidrIp`]=a.CidrIp;if(a.Description)e[`${r}.IpRanges.${i+1}.Description`]=a.Description});if(s.Ipv6Ranges)s.Ipv6Ranges.forEach((a,i)=>{if(a.CidrIpv6)e[`${r}.Ipv6Ranges.${i+1}.CidrIpv6`]=a.CidrIpv6;if(a.Description)e[`${r}.Ipv6Ranges.${i+1}.Description`]=a.Description});if(s.UserIdGroupPairs)s.UserIdGroupPairs.forEach((a,i)=>{if(a.GroupId)e[`${r}.Groups.${i+1}.GroupId`]=a.GroupId;if(a.UserId)e[`${r}.Groups.${i+1}.UserId`]=a.UserId;if(a.Description)e[`${r}.Groups.${i+1}.Description`]=a.Description})})}parseArray(e){if(!e)return[];return Array.isArray(e)?e:[e]}parseFirstIpv6Address(e){for(let t of this.parseArray(e))for(let s of this.parseArray(t?.ipv6AddressesSet?.item))if(s?.ipv6Address)return s.ipv6Address;return}parseTags(e){return this.parseArray(e).map((t)=>({Key:t.key,Value:t.value}))}parseReservations(e){return this.parseArray(e).map((t)=>({ReservationId:t.reservationId,Instances:this.parseInstances(t.instancesSet?.item||t.instancesSet)}))}parseInstances(e){return this.parseArray(e).map((t)=>({InstanceId:t.instanceId,ImageId:t.imageId,InstanceType:t.instanceType,State:t.instanceState?{Code:Number.parseInt(t.instanceState.code),Name:t.instanceState.name}:void 0,PrivateIpAddress:t.privateIpAddress,PublicIpAddress:t.ipAddress,Ipv6Address:this.parseFirstIpv6Address(t.networkInterfaceSet?.item),SubnetId:t.subnetId,VpcId:t.vpcId,SecurityGroups:this.parseArray(t.groupSet?.item).map((s)=>({GroupId:s.groupId,GroupName:s.groupName})),Tags:this.parseTags(t.tagSet?.item),LaunchTime:t.launchTime,Placement:t.placement?{AvailabilityZone:t.placement.availabilityZone,Tenancy:t.placement.tenancy}:void 0,Architecture:t.architecture,RootDeviceType:t.rootDeviceType,RootDeviceName:t.rootDeviceName,BlockDeviceMappings:this.parseArray(t.blockDeviceMapping?.item).map((s)=>({DeviceName:s.deviceName,Ebs:s.ebs?{VolumeId:s.ebs.volumeId,Status:s.ebs.status,AttachTime:s.ebs.attachTime,DeleteOnTermination:s.ebs.deleteOnTermination==="true"}:void 0})),IamInstanceProfile:t.iamInstanceProfile?{Arn:t.iamInstanceProfile.arn,Id:t.iamInstanceProfile.id}:void 0}))}parseIpPermissions(e){return this.parseArray(e).map((t)=>({IpProtocol:t.ipProtocol,FromPort:t.fromPort?Number.parseInt(t.fromPort):void 0,ToPort:t.toPort?Number.parseInt(t.toPort):void 0,IpRanges:this.parseArray(t.ipRanges?.item).map((s)=>({CidrIp:s.cidrIp,Description:s.description})),Ipv6Ranges:this.parseArray(t.ipv6Ranges?.item).map((s)=>({CidrIpv6:s.cidrIpv6,Description:s.description})),UserIdGroupPairs:this.parseArray(t.groups?.item).map((s)=>({GroupId:s.groupId,UserId:s.userId,Description:s.description}))}))}}
|
|
4
|
-
export{
|
|
4
|
+
export{K};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{le}from"./chunk-49sthm4q.js";import"./chunk-bckm6fre.js";export{le as RDSClient};
|