@stacksjs/ts-cloud 0.16.80 → 0.16.82

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (180) hide show
  1. package/dist/aws/index.js +1 -1
  2. package/dist/bin/{chunk-nbffypj8.js → chunk-08sws53b.js} +3 -3
  3. package/dist/bin/{chunk-6xx24qev.js → chunk-19mhwmfp.js} +1 -1
  4. package/dist/bin/chunk-1qez75tb.js +1 -0
  5. package/dist/bin/chunk-1rrmswhq.js +1 -0
  6. package/dist/bin/{chunk-gqstb8zn.js → chunk-1wgyq50e.js} +1 -1
  7. package/dist/bin/{chunk-0r8k7qth.js → chunk-20rfyk4x.js} +4 -4
  8. package/dist/bin/{chunk-jhydr9dp.js → chunk-33xqndrp.js} +91 -90
  9. package/dist/bin/{chunk-rdqcr78z.js → chunk-35325988.js} +2 -2
  10. package/dist/bin/chunk-3rjer1mp.js +1 -0
  11. package/dist/bin/{chunk-06hwds44.js → chunk-3wvpgb8m.js} +3 -3
  12. package/dist/bin/{chunk-jcehsvnm.js → chunk-462swbg5.js} +13 -13
  13. package/dist/bin/chunk-4c4q96vm.js +1 -0
  14. package/dist/bin/chunk-5hmrqjmq.js +1 -0
  15. package/dist/bin/chunk-5tzygzdy.js +1 -0
  16. package/dist/bin/{chunk-e12679p1.js → chunk-69mejej3.js} +1 -1
  17. package/dist/bin/{chunk-hyrvmjq0.js → chunk-6b6yr784.js} +2 -2
  18. package/dist/bin/chunk-6ybjfjbc.js +1 -0
  19. package/dist/bin/chunk-7848wre2.js +1 -0
  20. package/dist/bin/chunk-7haewmr7.js +1 -0
  21. package/dist/bin/chunk-7yhy2a7h.js +1 -0
  22. package/dist/bin/{chunk-k3cyh23p.js → chunk-83tt2t15.js} +5 -5
  23. package/dist/bin/{chunk-y5gx3dq2.js → chunk-89v3ec9n.js} +1 -1
  24. package/dist/bin/{chunk-33shhgye.js → chunk-8rkfwgb4.js} +7 -7
  25. package/dist/bin/{chunk-p35e4j11.js → chunk-9gp8p8hv.js} +2 -2
  26. package/dist/bin/chunk-9nen8018.js +1 -0
  27. package/dist/bin/chunk-9zwvysdn.js +1 -0
  28. package/dist/bin/chunk-abt0636a.js +1 -0
  29. package/dist/bin/{chunk-hhbmtgkq.js → chunk-b1cb27m8.js} +6 -6
  30. package/dist/bin/chunk-b9ersj22.js +1 -0
  31. package/dist/bin/{chunk-gbbcp2bw.js → chunk-bkx2kapc.js} +2 -2
  32. package/dist/bin/{chunk-540wkkhs.js → chunk-btrxye8p.js} +5 -5
  33. package/dist/bin/{chunk-9ktyfegk.js → chunk-cgyk48s5.js} +1 -1
  34. package/dist/bin/{chunk-th05q1gs.js → chunk-cxf9pmmw.js} +2 -2
  35. package/dist/bin/{chunk-0zydd9s4.js → chunk-d0m01m6d.js} +5 -5
  36. package/dist/bin/{chunk-eyzdhtp4.js → chunk-f7jzs1h1.js} +4 -4
  37. package/dist/bin/{chunk-ma0d990n.js → chunk-gn7rdyz7.js} +2 -2
  38. package/dist/bin/{chunk-f0djc6da.js → chunk-gy29teqh.js} +3 -3
  39. package/dist/bin/chunk-haezjam0.js +1 -0
  40. package/dist/bin/chunk-hp1cqk45.js +1 -0
  41. package/dist/bin/{chunk-tf5tf414.js → chunk-jqs2ywj2.js} +2 -2
  42. package/dist/bin/{chunk-c1znyyca.js → chunk-jx062xpq.js} +1 -1
  43. package/dist/bin/chunk-k9s81q0g.js +1 -0
  44. package/dist/bin/{chunk-0v5q5sh0.js → chunk-nzg624aj.js} +3 -3
  45. package/dist/bin/chunk-q3mtvtem.js +1 -0
  46. package/dist/bin/{chunk-s076q9sj.js → chunk-qmwqntnx.js} +2 -2
  47. package/dist/bin/{chunk-4m2k5mvd.js → chunk-qpasspad.js} +4 -4
  48. package/dist/bin/chunk-qpd51n1j.js +1 -0
  49. package/dist/bin/chunk-rtpc6djg.js +1 -0
  50. package/dist/bin/chunk-s9k81gq6.js +1 -0
  51. package/dist/bin/{chunk-wayhpmn7.js → chunk-sacx9p6f.js} +86 -86
  52. package/dist/bin/{chunk-fhqjr3ba.js → chunk-ssnvdxh4.js} +3 -3
  53. package/dist/bin/{chunk-kq526rgc.js → chunk-t0r1rdj2.js} +1 -1
  54. package/dist/bin/chunk-tpy9t3cv.js +1 -0
  55. package/dist/bin/{chunk-by7dtwtj.js → chunk-w40r35vn.js} +1 -1
  56. package/dist/bin/chunk-w9jfrf3v.js +11 -0
  57. package/dist/bin/chunk-wm0rq725.js +1 -0
  58. package/dist/bin/chunk-y9qdpwa6.js +1 -0
  59. package/dist/bin/chunk-ybekawxv.js +1 -0
  60. package/dist/bin/{chunk-4vtyjj7c.js → chunk-yf2drw7r.js} +1 -1
  61. package/dist/bin/{chunk-gq4htm3f.js → chunk-z9g7fa1w.js} +1 -1
  62. package/dist/bin/{chunk-0e7y7q0t.js → chunk-zfn3a9sx.js} +1 -1
  63. package/dist/bin/chunk-zg8nnq7k.js +1 -0
  64. package/dist/bin/{chunk-6kx0fddd.js → chunk-zn2efqcr.js} +46 -46
  65. package/dist/bin/{chunk-kyqe19mh.js → chunk-zn9wmqd1.js} +2 -2
  66. package/dist/bin/cli.js +215 -215
  67. package/dist/bin/dashboard-server.js +1 -1
  68. package/dist/bin/stacks-queue-worker.js +1 -1
  69. package/dist/bin/stacks-scheduler.js +1 -1
  70. package/dist/chunk-18dqxyz5.js +1 -0
  71. package/dist/{chunk-etv0rcjd.js → chunk-1h95atas.js} +1 -1
  72. package/dist/{chunk-nxj8pwa7.js → chunk-3wh3hsvp.js} +1 -1
  73. package/dist/{chunk-t7qgvz8z.js → chunk-5rds38z9.js} +55 -55
  74. package/dist/chunk-5v2wpf1k.js +1 -0
  75. package/dist/{chunk-tp37gyhc.js → chunk-7ea0q5tg.js} +1 -1
  76. package/dist/{chunk-dvma06m5.js → chunk-9w8qtr4p.js} +1 -1
  77. package/dist/{chunk-hg93a2g9.js → chunk-c71hhcsb.js} +2 -2
  78. package/dist/{chunk-w8sctn7m.js → chunk-cf274f07.js} +1 -1
  79. package/dist/{chunk-v6s9k1mp.js → chunk-cz4dw2hk.js} +1 -1
  80. package/dist/{chunk-0cgrk9g3.js → chunk-dh5m9b05.js} +1 -1
  81. package/dist/{chunk-z5c5amm1.js → chunk-dvw5dy32.js} +4 -4
  82. package/dist/{chunk-b6wsc7jp.js → chunk-eyc2tvze.js} +1 -1
  83. package/dist/{chunk-kjkkh11z.js → chunk-k8xv271s.js} +4 -4
  84. package/dist/{chunk-z52n96sa.js → chunk-n5qbdsbj.js} +89 -88
  85. package/dist/{chunk-8k44kaz0.js → chunk-pk8ppz98.js} +1 -1
  86. package/dist/{chunk-f4fggc5f.js → chunk-tb5hy7rm.js} +1 -1
  87. package/dist/deploy/index.js +1 -1
  88. package/dist/dns/index.js +1 -1
  89. package/dist/drivers/hetzner/driver.d.ts +1 -0
  90. package/dist/drivers/index.js +1 -1
  91. package/dist/drivers/shared/compute-provision.d.ts +2 -0
  92. package/dist/index.js +2 -2
  93. package/dist/mail/index.js +2 -2
  94. package/dist/operations/index.js +1 -1
  95. package/dist/protection/index.js +1 -1
  96. package/dist/spend/index.js +1 -1
  97. package/dist/ui/404.html +1 -1
  98. package/dist/ui/accept-invitation.html +1 -1
  99. package/dist/ui/access-denied.html +1 -1
  100. package/dist/ui/account/automation.html +6 -6
  101. package/dist/ui/account/security.html +2 -2
  102. package/dist/ui/applications/compose.html +6 -6
  103. package/dist/ui/applications/new.html +1 -1
  104. package/dist/ui/data/backups.html +5 -5
  105. package/dist/ui/data/services.html +5 -5
  106. package/dist/ui/data/volumes.html +6 -6
  107. package/dist/ui/index.html +6 -6
  108. package/dist/ui/infrastructure/topology.html +6 -6
  109. package/dist/ui/integrations.html +1 -1
  110. package/dist/ui/operations/alerts.html +5 -5
  111. package/dist/ui/operations/configuration.html +6 -6
  112. package/dist/ui/operations/jobs.html +5 -5
  113. package/dist/ui/operations/maintenance.html +6 -6
  114. package/dist/ui/operations/observability.html +6 -6
  115. package/dist/ui/operations/previews.html +6 -6
  116. package/dist/ui/operations/queue.html +6 -6
  117. package/dist/ui/operations/regions.html +6 -6
  118. package/dist/ui/operations/releases.html +6 -6
  119. package/dist/ui/operations/spend.html +6 -6
  120. package/dist/ui/operations/workloads.html +6 -6
  121. package/dist/ui/security.html +1 -1
  122. package/dist/ui/server/actions.html +6 -6
  123. package/dist/ui/server/activity.html +1 -1
  124. package/dist/ui/server/capacity.html +5 -5
  125. package/dist/ui/server/database.html +6 -6
  126. package/dist/ui/server/deployments.html +5 -5
  127. package/dist/ui/server/diagnostics.html +2 -2
  128. package/dist/ui/server/firewall.html +5 -5
  129. package/dist/ui/server/fleet.html +6 -6
  130. package/dist/ui/server/logs.html +5 -5
  131. package/dist/ui/server/metrics.html +5 -5
  132. package/dist/ui/server/security.html +2 -2
  133. package/dist/ui/server/services.html +2 -2
  134. package/dist/ui/server/sites.html +6 -6
  135. package/dist/ui/server/ssh-keys.html +6 -6
  136. package/dist/ui/server/team.html +6 -6
  137. package/dist/ui/server/terminal.html +2 -2
  138. package/dist/ui/serverless/alarms.html +6 -6
  139. package/dist/ui/serverless/assets.html +1 -1
  140. package/dist/ui/serverless/cost.html +2 -2
  141. package/dist/ui/serverless/data.html +6 -6
  142. package/dist/ui/serverless/deployments.html +2 -2
  143. package/dist/ui/serverless/firewall.html +1 -1
  144. package/dist/ui/serverless/functions.html +6 -6
  145. package/dist/ui/serverless/logs.html +6 -6
  146. package/dist/ui/serverless/metrics.html +2 -2
  147. package/dist/ui/serverless/queues.html +6 -6
  148. package/dist/ui/serverless/secrets.html +6 -6
  149. package/dist/ui/serverless/traces.html +6 -6
  150. package/dist/ui/serverless.html +5 -5
  151. package/package.json +3 -3
  152. package/dist/bin/chunk-00j7xxxg.js +0 -1
  153. package/dist/bin/chunk-1xfn93bc.js +0 -1
  154. package/dist/bin/chunk-413nb697.js +0 -1
  155. package/dist/bin/chunk-8esaawk6.js +0 -1
  156. package/dist/bin/chunk-8zc4kx6k.js +0 -1
  157. package/dist/bin/chunk-9t6wztvn.js +0 -1
  158. package/dist/bin/chunk-b074y2np.js +0 -1
  159. package/dist/bin/chunk-b77qsk6r.js +0 -1
  160. package/dist/bin/chunk-d73xkm0k.js +0 -1
  161. package/dist/bin/chunk-dmj5xv74.js +0 -1
  162. package/dist/bin/chunk-dnswjyen.js +0 -1
  163. package/dist/bin/chunk-h28tfah9.js +0 -1
  164. package/dist/bin/chunk-k1bdndgj.js +0 -1
  165. package/dist/bin/chunk-kkrp8100.js +0 -1
  166. package/dist/bin/chunk-m1w3p30q.js +0 -1
  167. package/dist/bin/chunk-nwcpck34.js +0 -1
  168. package/dist/bin/chunk-p96975b7.js +0 -1
  169. package/dist/bin/chunk-qssb91v3.js +0 -11
  170. package/dist/bin/chunk-rgwwr6x2.js +0 -1
  171. package/dist/bin/chunk-sky689gw.js +0 -1
  172. package/dist/bin/chunk-tx56y5qk.js +0 -1
  173. package/dist/bin/chunk-v0fkhtgq.js +0 -1
  174. package/dist/bin/chunk-v7dk21w9.js +0 -1
  175. package/dist/bin/chunk-ww4r3r7x.js +0 -1
  176. package/dist/bin/chunk-x9dep4ew.js +0 -1
  177. package/dist/bin/chunk-y5hsmt17.js +0 -1
  178. package/dist/bin/chunk-zfy6f6ph.js +0 -1
  179. package/dist/chunk-fmhqz3eg.js +0 -1
  180. package/dist/chunk-pev4cpbd.js +0 -1
@@ -1,4 +1,4 @@
1
- import{I}from"./chunk-wayhpmn7.js";var l=40,K=[{version:1,name:"core_control_plane",sql:`
1
+ import{I}from"./chunk-sacx9p6f.js";var l=40,K=[{version:1,name:"core_control_plane",sql:`
2
2
  CREATE TABLE projects (
3
3
  id TEXT PRIMARY KEY,
4
4
  slug TEXT NOT NULL UNIQUE,
@@ -1475,7 +1475,7 @@ import{I}from"./chunk-wayhpmn7.js";var l=40,K=[{version:1,name:"core_control_pla
1475
1475
  -- once a minute, forever.
1476
1476
  CREATE INDEX telemetry_kind_scope_time_idx
1477
1477
  ON telemetry_records(project_id, kind, timestamp);
1478
- `}];import{createHash as S,randomBytes as oe}from"node:crypto";import{chmodSync as H,existsSync as Z,mkdirSync as Te,statSync as se}from"node:fs";import{dirname as ee}from"node:path";import{Database as de}from"bun:sqlite";var ce=["project:read","config:read","config:write","deployments:read","deployments:create","deployments:cancel","deployments:rollback","runtime:read","runtime:restart","runtime:logs","runtime:terminal","data:read","data:write","data:admin","backups:read","backups:create","backups:restore","secrets:read","secrets:write","fleet:read","fleet:manage","users:read","users:manage","users:transfer-ownership","audit:read","billing:read","billing:manage","security:read","security:manage","security:waive","sources:read","sources:manage","applications:read","applications:manage","automation:read","automation:manage","tags:manage"],P=["project:read","config:read","deployments:read","runtime:read","runtime:logs","data:read","backups:read","security:read","sources:read","applications:read","billing:read"],Ee={owner:new Set(ce),admin:new Set(ce.filter((e)=>e!=="users:transfer-ownership")),deployer:new Set([...P,"deployments:create","deployments:cancel","deployments:rollback","sources:manage","applications:manage"]),operator:new Set([...P,"runtime:restart","backups:create","security:manage","sources:manage","applications:manage"]),viewer:new Set(P),auditor:new Set(["project:read","config:read","deployments:read","runtime:read","data:read","backups:read","audit:read","security:read","sources:read","applications:read"])};function Tn(e){return Ee[e]}function j(e,t){if(e.type==="organization")return e.id===void 0||e.id===t.organizationId;if(!e.id)return!1;if(e.type==="project")return e.id===t.projectId;if(e.type==="environment")return e.id===t.environmentId;return e.id===t.resourceId}function re(e){let{membership:t,capability:r,target:i}=e;if(!t||t.status!=="active"||t.organizationId!==i.organizationId)return{allowed:!1,reason:"inactive-membership"};let a=e.grants.filter((s)=>s.organizationId===i.organizationId&&s.membershipId===t.id&&s.capability===r&&j(s.scope,i)),E=a.find((s)=>s.effect==="deny");if(E)return{allowed:!1,reason:"explicit-deny",inheritedFrom:{kind:"grant",id:E.id,scope:E.scope}};let T=a.find((s)=>s.effect==="allow");if(T)return{allowed:!0,reason:"explicit-allow",inheritedFrom:{kind:"grant",id:T.id,scope:T.scope}};if(!j(t.scope,i))return{allowed:!1,reason:"scope-mismatch"};if(Tn(t.roleTemplate).has(r))return{allowed:!0,reason:"role-template",inheritedFrom:{kind:"membership",id:t.id,scope:t.scope}};return{allowed:!1,reason:"missing-capability"}}function En(e){return ce.filter((t)=>re({...e,capability:t}).allowed)}class p extends Error{constructor(e,t,r){super(`${e} ${t} changed since version ${r}`);this.name="OptimisticConcurrencyError"}}class x extends Error{constructor(e,t){super(`Operation cannot transition from ${e} to ${t}`);this.name="InvalidOperationTransitionError"}}class X extends Error{constructor(e,t){super(`Control-plane schema version ${e} is newer than supported version ${t}`);this.name="UnsupportedSchemaVersionError"}}var te=65536,q=16384,Ne=["succeeded","failed","cancelled","timed_out"],Le={queued:["running","cancelled","timed_out"],running:["queued","succeeded","failed","cancelled","timed_out"],succeeded:[],failed:["queued"],cancelled:["queued"],timed_out:["queued"]},_e=/(?:^|_)(?:authorization|cookie|credential|password|passwd|secret|token|api_?key|private_?key|access_?key)(?:$|_)/i,ie=/(?:authorization|password|secret|token|api[_-]?key|private[_-]?key|access[_-]?key)\s*[=:]\s*[^\s,;]+/gi;function _(e){if(typeof e!=="string")return{};try{return JSON.parse(e)}catch{return{}}}function d(e){return typeof e==="string"?e:void 0}function G(e,t){if(t&&_e.test(t))return"[REDACTED]";if(e===null||typeof e==="boolean"||typeof e==="number")return e;if(typeof e==="string")return e.replace(ie,"[REDACTED]");if(Array.isArray(e))return e.map((r)=>G(r));if(e&&typeof e==="object"){let r={};for(let[i,a]of Object.entries(e))r[i]=G(a,i);return r}return String(e??"")}function h(e,t=te){let r=G(e),i=JSON.stringify(r);if(Buffer.byteLength(i)<=t)return r;return{truncated:!0,originalBytes:Buffer.byteLength(i),preview:i.slice(0,Math.max(0,t-128))}}function N(e){return JSON.stringify(h(e))}function M(e){if(!e)return;let t=e.replace(ie,"[REDACTED]");return Buffer.byteLength(t)<=q?t:`${t.slice(0,q-24)}
1478
+ `}];import{createHash as S,randomBytes as oe}from"node:crypto";import{chmodSync as H,existsSync as Z,mkdirSync as Te,statSync as se}from"node:fs";import{dirname as ee}from"node:path";import{Database as de}from"bun:sqlite";var ce=["project:read","config:read","config:write","deployments:read","deployments:create","deployments:cancel","deployments:rollback","runtime:read","runtime:restart","runtime:logs","runtime:terminal","data:read","data:write","data:admin","backups:read","backups:create","backups:restore","secrets:read","secrets:write","fleet:read","fleet:manage","users:read","users:manage","users:transfer-ownership","audit:read","billing:read","billing:manage","security:read","security:manage","security:waive","sources:read","sources:manage","applications:read","applications:manage","automation:read","automation:manage","tags:manage"],P=["project:read","config:read","deployments:read","runtime:read","runtime:logs","data:read","backups:read","security:read","sources:read","applications:read","billing:read"],Ee={owner:new Set(ce),admin:new Set(ce.filter((e)=>e!=="users:transfer-ownership")),deployer:new Set([...P,"deployments:create","deployments:cancel","deployments:rollback","sources:manage","applications:manage"]),operator:new Set([...P,"runtime:restart","backups:create","security:manage","sources:manage","applications:manage"]),viewer:new Set(P),auditor:new Set(["project:read","config:read","deployments:read","runtime:read","data:read","backups:read","audit:read","security:read","sources:read","applications:read"])};function Tn(e){return Ee[e]}function j(e,t){if(e.type==="organization")return e.id===void 0||e.id===t.organizationId;if(!e.id)return!1;if(e.type==="project")return e.id===t.projectId;if(e.type==="environment")return e.id===t.environmentId;return e.id===t.resourceId}function ne(e){let{membership:t,capability:r,target:i}=e;if(!t||t.status!=="active"||t.organizationId!==i.organizationId)return{allowed:!1,reason:"inactive-membership"};let a=e.grants.filter((s)=>s.organizationId===i.organizationId&&s.membershipId===t.id&&s.capability===r&&j(s.scope,i)),E=a.find((s)=>s.effect==="deny");if(E)return{allowed:!1,reason:"explicit-deny",inheritedFrom:{kind:"grant",id:E.id,scope:E.scope}};let T=a.find((s)=>s.effect==="allow");if(T)return{allowed:!0,reason:"explicit-allow",inheritedFrom:{kind:"grant",id:T.id,scope:T.scope}};if(!j(t.scope,i))return{allowed:!1,reason:"scope-mismatch"};if(Tn(t.roleTemplate).has(r))return{allowed:!0,reason:"role-template",inheritedFrom:{kind:"membership",id:t.id,scope:t.scope}};return{allowed:!1,reason:"missing-capability"}}function En(e){return ce.filter((t)=>ne({...e,capability:t}).allowed)}class p extends Error{constructor(e,t,r){super(`${e} ${t} changed since version ${r}`);this.name="OptimisticConcurrencyError"}}class x extends Error{constructor(e,t){super(`Operation cannot transition from ${e} to ${t}`);this.name="InvalidOperationTransitionError"}}class X extends Error{constructor(e,t){super(`Control-plane schema version ${e} is newer than supported version ${t}`);this.name="UnsupportedSchemaVersionError"}}var te=65536,q=16384,Ne=["succeeded","failed","cancelled","timed_out"],Le={queued:["running","cancelled","timed_out"],running:["queued","succeeded","failed","cancelled","timed_out"],succeeded:[],failed:["queued"],cancelled:["queued"],timed_out:["queued"]},_e=/(?:^|_)(?:authorization|cookie|credential|password|passwd|secret|token|api_?key|private_?key|access_?key)(?:$|_)/i,ie=/(?:authorization|password|secret|token|api[_-]?key|private[_-]?key|access[_-]?key)\s*[=:]\s*[^\s,;]+/gi;function _(e){if(typeof e!=="string")return{};try{return JSON.parse(e)}catch{return{}}}function d(e){return typeof e==="string"?e:void 0}function G(e,t){if(t&&_e.test(t))return"[REDACTED]";if(e===null||typeof e==="boolean"||typeof e==="number")return e;if(typeof e==="string")return e.replace(ie,"[REDACTED]");if(Array.isArray(e))return e.map((r)=>G(r));if(e&&typeof e==="object"){let r={};for(let[i,a]of Object.entries(e))r[i]=G(a,i);return r}return String(e??"")}function h(e,t=te){let r=G(e),i=JSON.stringify(r);if(Buffer.byteLength(i)<=t)return r;return{truncated:!0,originalBytes:Buffer.byteLength(i),preview:i.slice(0,Math.max(0,t-128))}}function N(e){return JSON.stringify(h(e))}function M(e){if(!e)return;let t=e.replace(ie,"[REDACTED]");return Buffer.byteLength(t)<=q?t:`${t.slice(0,q-24)}
1479
1479
  [output truncated]`}function v(e){return{id:String(e.id),slug:String(e.slug),name:String(e.name),description:d(e.description),organizationId:d(e.organization_id),desiredConfigHash:d(e.desired_config_hash),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function D(e){return{id:String(e.id),projectId:String(e.project_id),slug:String(e.slug),name:String(e.name),kind:String(e.kind),region:d(e.region),desiredState:_(e.desired_state),discoveredState:_(e.discovered_state),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function y(e){return{id:String(e.id),projectId:String(e.project_id),environmentId:d(e.environment_id),kind:String(e.kind),slug:String(e.slug),name:String(e.name),provider:d(e.provider),providerId:d(e.provider_id),desiredState:_(e.desired_state),discoveredState:_(e.discovered_state),metadata:_(e.metadata),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function f(e){return{id:String(e.id),kind:String(e.kind),externalId:d(e.external_id),displayName:String(e.display_name),metadata:_(e.metadata),disabledAt:d(e.disabled_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function u(e){return{id:String(e.id),projectId:d(e.project_id),environmentId:d(e.environment_id),resourceId:d(e.resource_id),actorId:d(e.actor_id),kind:String(e.kind),state:String(e.state),correlationId:String(e.correlation_id),idempotencyKey:d(e.idempotency_key),input:_(e.input),output:_(e.output),error:d(e.error),attempt:Number(e.attempt),priority:Number(e.priority),leaseOwner:d(e.lease_owner),leaseExpiresAt:d(e.lease_expires_at),cancelRequestedAt:d(e.cancel_requested_at),startedAt:d(e.started_at),finishedAt:d(e.finished_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Y(e){return{id:String(e.id),sequence:Number(e.sequence),organizationId:d(e.organization_id),projectId:d(e.project_id),operationId:d(e.operation_id),resourceId:d(e.resource_id),actorId:d(e.actor_id),correlationId:String(e.correlation_id),type:String(e.type),level:String(e.level),payload:_(e.payload),createdAt:String(e.created_at)}}function O(e){return{id:String(e.id),projectId:String(e.project_id),name:String(e.name),normalizedName:String(e.normalized_name),color:String(e.color),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function b(e){return{id:String(e.id),actorKey:String(e.actor_key),name:String(e.name),routeId:String(e.route_id),query:_(e.query),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function F(e){return{actorKey:String(e.actor_key),entityType:String(e.entity_type),entityId:String(e.entity_id),favorite:Number(e.favorite)===1,lastVisitedAt:String(e.last_visited_at),visitCount:Number(e.visit_count)}}function z(e){return{id:String(e.id),slug:String(e.slug),name:String(e.name),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function B(e){let t=String(e.scope_type);return{type:t,...t==="organization"?{}:{id:String(e.scope_id)}}}function k(e){return{id:String(e.id),organizationId:String(e.organization_id),actorId:String(e.actor_id),roleTemplate:String(e.role_template),scope:B(e),source:String(e.source??"manual"),status:String(e.status),sessionVersion:Number(e.session_version),lastActiveAt:d(e.last_active_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function R(e,t){let r=d(e.accepted_at),i=d(e.revoked_at),a=String(e.expires_at),E=i?"revoked":r?"accepted":a<=t?"expired":"pending";return{id:String(e.id),organizationId:String(e.organization_id),email:String(e.email),roleTemplate:String(e.role_template),scope:B(e),invitedByActorId:d(e.invited_by_actor_id),acceptedByActorId:d(e.accepted_by_actor_id),expiresAt:a,acceptedAt:r,revokedAt:i,state:E,createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function w(e){return{id:String(e.id),organizationId:String(e.organization_id),membershipId:String(e.membership_id),effect:String(e.effect),capability:String(e.capability),scope:B(e),source:String(e.source??"manual"),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function g(e){return{type:e.type,id:e.id??null}}function le(e){return Array.from({length:e},()=>"?").join(", ")}function o(e,t,r){return e.run(t,r)}class Br{path;database;nowFn;idFn;constructor(e={}){this.path=e.path??I(e.cwd??process.cwd(),"control-plane.sqlite"),this.nowFn=e.now??(()=>new Date),this.idFn=e.id??(()=>crypto.randomUUID());let t=this.path===":memory:";if(!t){Te(ee(this.path),{recursive:!0,mode:448});try{H(ee(this.path),448)}catch{}}if(this.database=new de(this.path,{create:!0,strict:!0}),this.database.run("PRAGMA foreign_keys = ON"),this.database.run(`PRAGMA busy_timeout = ${Math.max(100,e.busyTimeoutMs??5000)}`),!t)this.database.run("PRAGMA journal_mode = WAL"),this.database.run("PRAGMA synchronous = NORMAL");if(this.migrate(),!t)this.secureDatabaseFiles()}now(){return this.nowFn().toISOString()}secureDatabaseFiles(){for(let e of[this.path,`${this.path}-wal`,`${this.path}-shm`]){if(!Z(e))continue;try{H(e,384)}catch{}}}backupTo(e){this.database.run("VACUUM INTO ?",[e]);try{H(e,384)}catch{}}migrate(){let e=this.database.query("PRAGMA user_version").get(),t=Number(e?.user_version??0);if(t>l)throw new X(t,l);if(t===l)return;let r;if(t>0&&this.path!==":memory:")r=`${this.path}.v${t}.${Date.now()}.bak`,this.backupTo(r);try{if(this.database.transaction(()=>{for(let a of K){if(a.version<=t)continue;this.database.run(a.sql),o(this.database,"INSERT INTO schema_migrations (version, name, applied_at) VALUES (?, ?, ?)",[a.version,a.name,this.now()]),this.database.run(`PRAGMA user_version = ${a.version}`)}}).exclusive(),r)this.setSetting("storage.last_backup",{path:r,createdAt:this.now(),reason:"pre-migration"})}catch(i){let a=r?` Restore from ${r}.`:"";throw Error(`Control-plane migration from schema ${t} failed.${a} ${i instanceof Error?i.message:String(i)}`)}}close(){if(this.path!==":memory:")this.secureDatabaseFiles();this.database.close()}transaction(e){return this.database.transaction(e).immediate()}createProject(e){let t=e.id??this.idFn(),r=this.now();return o(this.database,"INSERT INTO projects (id, slug, name, description, organization_id, desired_config_hash, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",[t,e.slug,e.name,e.description??null,e.organizationId??null,e.desiredConfigHash??null,r,r]),this.getProject(t)}getProject(e){let t=this.database.query("SELECT * FROM projects WHERE id = ?").get(e);return t?v(t):void 0}getProjectBySlug(e){let t=this.database.query("SELECT * FROM projects WHERE slug = ?").get(e);return t?v(t):void 0}listProjects(){return this.database.query("SELECT * FROM projects ORDER BY name COLLATE NOCASE, id").all().map(v)}updateProject(e,t,r){let i=this.getProject(e);if(!i||i.version!==t)throw new p("Project",e,t);if(o(this.database,`UPDATE projects SET name = ?, description = ?, organization_id = ?, desired_config_hash = ?, version = version + 1, updated_at = ?
1480
1480
  WHERE id = ? AND version = ?`,[r.name??i.name,r.description===null?null:r.description??i.description??null,r.organizationId===null?null:r.organizationId??i.organizationId??null,r.desiredConfigHash===null?null:r.desiredConfigHash??i.desiredConfigHash??null,this.now(),e,t]).changes!==1)throw new p("Project",e,t);return this.getProject(e)}createEnvironment(e){let t=e.id??this.idFn(),r=this.now();return o(this.database,`INSERT INTO environments (id, project_id, slug, name, kind, region, desired_state, discovered_state, created_at, updated_at)
1481
1481
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[t,e.projectId,e.slug,e.name,e.kind,e.region??null,N(e.desiredState??{}),N(e.discoveredState??{}),r,r]),D(this.database.query("SELECT * FROM environments WHERE id = ?").get(t))}listEnvironments(e){return this.database.query("SELECT * FROM environments WHERE project_id = ? ORDER BY name COLLATE NOCASE, id").all(e).map(D)}getEnvironmentBySlug(e,t){let r=this.database.query("SELECT * FROM environments WHERE project_id = ? AND slug = ?").get(e,t);return r?D(r):void 0}createResource(e){let t=e.id??this.idFn(),r=this.now();return o(this.database,`INSERT INTO resources (id, project_id, environment_id, kind, slug, name, provider, provider_id, desired_state, discovered_state, metadata, created_at, updated_at)
@@ -1504,4 +1504,4 @@ import{I}from"./chunk-wayhpmn7.js";var l=40,K=[{version:1,name:"core_control_pla
1504
1504
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i.id,i.organizationId,i.membershipId,i.effect,i.capability,i.scope.type,i.scope.id??null,i.source??"manual",i.createdAt,i.updatedAt]);for(let i of e.operations)o(this.database,`INSERT INTO operations (id, project_id, environment_id, resource_id, actor_id, kind, state, correlation_id, idempotency_key,
1505
1505
  input, output, error, attempt, priority, lease_owner, lease_expires_at, cancel_requested_at, started_at, finished_at, version, created_at, updated_at)
1506
1506
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i.id,i.projectId??null,i.environmentId??null,i.resourceId??null,i.actorId??null,i.kind,i.state,i.correlationId,i.idempotencyKey??null,N(i.input),N(i.output),M(i.error)??null,i.attempt,i.priority,i.leaseOwner??null,i.leaseExpiresAt??null,i.cancelRequestedAt??null,i.startedAt??null,i.finishedAt??null,i.version,i.createdAt,i.updatedAt]);for(let i of e.events)o(this.database,`INSERT INTO events (sequence, id, organization_id, project_id, operation_id, resource_id, actor_id, correlation_id, type, level, payload, created_at)
1507
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i.sequence,i.id,i.organizationId??null,i.projectId??null,i.operationId??null,i.resourceId??null,i.actorId??null,i.correlationId,i.type,i.level,N(i.payload),i.createdAt]);for(let[i,a]of Object.entries(e.settings))o(this.database,"INSERT INTO settings (key, value, updated_at) VALUES (?, ?, ?)",[i,N(a),this.now()]);for(let i of e.tags??[])o(this.database,"INSERT INTO tags (id, project_id, name, normalized_name, color, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[i.id,i.projectId,i.name,i.normalizedName,i.color,i.createdAt,i.updatedAt]);for(let i of e.resourceTags??[])o(this.database,"INSERT INTO resource_tags (resource_id, tag_id, created_at) VALUES (?, ?, ?)",[i.resourceId,i.tagId,i.createdAt]);for(let i of e.savedFilters??[])o(this.database,"INSERT INTO saved_filters (id, actor_key, name, route_id, query, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[i.id,i.actorKey,i.name,i.routeId,N(i.query),i.createdAt,i.updatedAt]);for(let i of e.navigationItems??[])o(this.database,"INSERT INTO navigation_items (actor_key, entity_type, entity_id, favorite, last_visited_at, visit_count) VALUES (?, ?, ?, ?, ?, ?)",[i.actorKey,i.entityType,i.entityId,i.favorite?1:0,i.lastVisitedAt,i.visitCount])})}}var pe=new Set(["domain","domains","hostname","hostnames","url","repository","repo","image","label","labels"]),ue=new Set(["sha","commit","commitsha","release","releaseid"]);function ae(e,t){if(!e||typeof e!=="object"||Array.isArray(e))return[];let r=[];for(let[i,a]of Object.entries(e)){if(!t.has(i.toLowerCase()))continue;if(typeof a==="string")r.push(a);else if(Array.isArray(a))r.push(...a.filter((E)=>typeof E==="string"))}return r}function Q(e){return e.toLowerCase().trim().replace(/[^a-z0-9._:/@-]+/g," ")}function W(e,t,r){let i=Q(e),a=Q(t),E=Q(r);if(!i)return 0;if(a===i)return 1000;if(a.startsWith(i))return 800-Math.min(100,a.length-i.length);if(a.includes(i))return 650-Math.min(100,a.indexOf(i));let T=i.split(/\s+/).filter(Boolean);if(T.every((c)=>E.includes(c)))return 400+T.length*10;let s=0;for(let c of i){if(s=E.indexOf(c,s),s<0)return 0;s++}return Math.max(1,180-Math.floor(E.length/20))}function Ce(e,t){let r=e.kind.toLowerCase();if(r==="server"||r==="compute")return{type:"server",href:`/server/metrics?env=${encodeURIComponent(t)}`};if(r.includes("database")||["mysql","postgres","postgresql","sqlite","redis"].includes(r))return{type:"database",href:`/server/database?env=${encodeURIComponent(t)}&database=${encodeURIComponent(e.slug)}`};return{type:"service",href:`/server/sites?env=${encodeURIComponent(t)}&service=${encodeURIComponent(e.slug)}`}}function la(e,t){let r=e.getProject(t.projectId);if(!r)return[];let i=e.listEnvironments(r.id),a=new Map(i.map((n)=>[n.id,n])),E=e.listResourceTags(r.id),T=new Map;for(let n of E){let L=T.get(n.resourceId)??[];L.push({id:n.tag.id,name:n.tag.name,color:n.tag.color}),T.set(n.resourceId,L)}let s=[],c=t.allowedResourceSlugs!==void 0;if(!c){s.push({type:"project",id:r.id,title:r.name,subtitle:r.slug,href:`/?project=${encodeURIComponent(r.slug)}`,tags:[],score:0});for(let n of i)s.push({type:"environment",id:n.id,title:n.name,subtitle:`${r.name} · ${n.kind}`,href:`/?env=${encodeURIComponent(n.slug)}`,environment:n.slug,tags:[],score:0})}let V=e.listResources(r.id).filter((n)=>!t.allowedResourceSlugs||t.allowedResourceSlugs.has(n.slug));for(let n of V){let L=n.environmentId?a.get(n.environmentId):void 0,C=T.get(n.id)??[],U=ae(n.desiredState,pe),A=[n.name,n.slug,n.kind,n.provider,n.providerId,L?.slug,...U,...C.map((ne)=>ne.name)].filter(Boolean).join(" "),m=Ce(n,L?.slug??i[0]?.slug??"");s.push({type:m.type,id:n.id,title:n.name,subtitle:[n.kind,...U.slice(0,2)].join(" · "),href:m.href,environment:L?.slug,provider:n.provider,tags:C,score:W(t.query,n.name,A)})}if(!c)for(let n of e.listOperations({projectId:r.id,limit:500})){let L=n.environmentId?a.get(n.environmentId):void 0,C=ae(n.input,ue),U=n.kind.includes("deploy"),A=C[0]??n.kind,m=[n.kind,n.id,n.correlationId,n.state,...C].join(" ");s.push({type:U?"deployment":"operation",id:n.id,title:A,subtitle:`${n.kind} · ${n.state}`,href:`/server/activity?env=${encodeURIComponent(L?.slug??i[0]?.slug??"")}&operation=${encodeURIComponent(n.id)}`,environment:L?.slug,status:n.state,tags:[],score:W(t.query,A,m)})}for(let n of s)if(n.score===0)n.score=W(t.query,n.title,`${n.title} ${n.subtitle} ${n.environment??""} ${n.provider??""}`);let J={service:0,server:1,database:2,deployment:3,environment:4,project:5,operation:6};return s.filter((n)=>n.score>0).sort((n,L)=>L.score-n.score||J[n.type]-J[L.type]||n.title.localeCompare(L.title)||n.id.localeCompare(L.id)).slice(0,Math.min(50,Math.max(1,t.limit??20)))}export{ce,Tn,re,En,h,Br,la};
1507
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i.sequence,i.id,i.organizationId??null,i.projectId??null,i.operationId??null,i.resourceId??null,i.actorId??null,i.correlationId,i.type,i.level,N(i.payload),i.createdAt]);for(let[i,a]of Object.entries(e.settings))o(this.database,"INSERT INTO settings (key, value, updated_at) VALUES (?, ?, ?)",[i,N(a),this.now()]);for(let i of e.tags??[])o(this.database,"INSERT INTO tags (id, project_id, name, normalized_name, color, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[i.id,i.projectId,i.name,i.normalizedName,i.color,i.createdAt,i.updatedAt]);for(let i of e.resourceTags??[])o(this.database,"INSERT INTO resource_tags (resource_id, tag_id, created_at) VALUES (?, ?, ?)",[i.resourceId,i.tagId,i.createdAt]);for(let i of e.savedFilters??[])o(this.database,"INSERT INTO saved_filters (id, actor_key, name, route_id, query, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[i.id,i.actorKey,i.name,i.routeId,N(i.query),i.createdAt,i.updatedAt]);for(let i of e.navigationItems??[])o(this.database,"INSERT INTO navigation_items (actor_key, entity_type, entity_id, favorite, last_visited_at, visit_count) VALUES (?, ?, ?, ?, ?, ?)",[i.actorKey,i.entityType,i.entityId,i.favorite?1:0,i.lastVisitedAt,i.visitCount])})}}var pe=new Set(["domain","domains","hostname","hostnames","url","repository","repo","image","label","labels"]),ue=new Set(["sha","commit","commitsha","release","releaseid"]);function re(e,t){if(!e||typeof e!=="object"||Array.isArray(e))return[];let r=[];for(let[i,a]of Object.entries(e)){if(!t.has(i.toLowerCase()))continue;if(typeof a==="string")r.push(a);else if(Array.isArray(a))r.push(...a.filter((E)=>typeof E==="string"))}return r}function Q(e){return e.toLowerCase().trim().replace(/[^a-z0-9._:/@-]+/g," ")}function W(e,t,r){let i=Q(e),a=Q(t),E=Q(r);if(!i)return 0;if(a===i)return 1000;if(a.startsWith(i))return 800-Math.min(100,a.length-i.length);if(a.includes(i))return 650-Math.min(100,a.indexOf(i));let T=i.split(/\s+/).filter(Boolean);if(T.every((c)=>E.includes(c)))return 400+T.length*10;let s=0;for(let c of i){if(s=E.indexOf(c,s),s<0)return 0;s++}return Math.max(1,180-Math.floor(E.length/20))}function Ce(e,t){let r=e.kind.toLowerCase();if(r==="server"||r==="compute")return{type:"server",href:`/server/metrics?env=${encodeURIComponent(t)}`};if(r.includes("database")||["mysql","postgres","postgresql","sqlite","redis"].includes(r))return{type:"database",href:`/server/database?env=${encodeURIComponent(t)}&database=${encodeURIComponent(e.slug)}`};return{type:"service",href:`/server/sites?env=${encodeURIComponent(t)}&service=${encodeURIComponent(e.slug)}`}}function da(e,t){let r=e.getProject(t.projectId);if(!r)return[];let i=e.listEnvironments(r.id),a=new Map(i.map((n)=>[n.id,n])),E=e.listResourceTags(r.id),T=new Map;for(let n of E){let L=T.get(n.resourceId)??[];L.push({id:n.tag.id,name:n.tag.name,color:n.tag.color}),T.set(n.resourceId,L)}let s=[],c=t.allowedResourceSlugs!==void 0;if(!c){s.push({type:"project",id:r.id,title:r.name,subtitle:r.slug,href:`/?project=${encodeURIComponent(r.slug)}`,tags:[],score:0});for(let n of i)s.push({type:"environment",id:n.id,title:n.name,subtitle:`${r.name} · ${n.kind}`,href:`/?env=${encodeURIComponent(n.slug)}`,environment:n.slug,tags:[],score:0})}let V=e.listResources(r.id).filter((n)=>!t.allowedResourceSlugs||t.allowedResourceSlugs.has(n.slug));for(let n of V){let L=n.environmentId?a.get(n.environmentId):void 0,C=T.get(n.id)??[],U=re(n.desiredState,pe),A=[n.name,n.slug,n.kind,n.provider,n.providerId,L?.slug,...U,...C.map((ae)=>ae.name)].filter(Boolean).join(" "),m=Ce(n,L?.slug??i[0]?.slug??"");s.push({type:m.type,id:n.id,title:n.name,subtitle:[n.kind,...U.slice(0,2)].join(" · "),href:m.href,environment:L?.slug,provider:n.provider,tags:C,score:W(t.query,n.name,A)})}if(!c)for(let n of e.listOperations({projectId:r.id,limit:500})){let L=n.environmentId?a.get(n.environmentId):void 0,C=re(n.input,ue),U=n.kind.includes("deploy"),A=C[0]??n.kind,m=[n.kind,n.id,n.correlationId,n.state,...C].join(" ");s.push({type:U?"deployment":"operation",id:n.id,title:A,subtitle:`${n.kind} · ${n.state}`,href:`/server/activity?env=${encodeURIComponent(L?.slug??i[0]?.slug??"")}&operation=${encodeURIComponent(n.id)}`,environment:L?.slug,status:n.state,tags:[],score:W(t.query,A,m)})}for(let n of s)if(n.score===0)n.score=W(t.query,n.title,`${n.title} ${n.subtitle} ${n.environment??""} ${n.provider??""}`);let J={service:0,server:1,database:2,deployment:3,environment:4,project:5,operation:6};return s.filter((n)=>n.score>0).sort((n,L)=>L.score-n.score||J[n.type]-J[L.type]||n.title.localeCompare(L.title)||n.id.localeCompare(L.id)).slice(0,Math.min(50,Math.max(1,t.limit??20)))}export{ce,Tn,ne,En,h,Br,da};
@@ -1,2 +1,2 @@
1
- import{p}from"./chunk-540wkkhs.js";class bt{client;region;constructor(t="us-east-1",e){this.region=t,this.client=new p(void 0,{profile:e})}async getCallerIdentity(){let t=await this.client.request({service:"sts",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetCallerIdentity&Version=2011-06-15"});if(typeof t==="string"){let n=t.match(/<Account>(\d+)<\/Account>/),r=t.match(/<UserId>([^<]+)<\/UserId>/),i=t.match(/<Arn>([^<]+)<\/Arn>/);return{Account:n?.[1],UserId:r?.[1],Arn:i?.[1]}}let e=t?.GetCallerIdentityResponse?.GetCallerIdentityResult||t?.GetCallerIdentityResult;if(e)return{Account:String(e.Account),UserId:e.UserId,Arn:e.Arn};if(t?.Account)return{Account:String(t.Account),UserId:t.UserId,Arn:t.Arn};return{Account:void 0,UserId:void 0,Arn:void 0}}}
1
+ import{p}from"./chunk-btrxye8p.js";class bt{client;region;constructor(t="us-east-1",e){this.region=t,this.client=new p(void 0,{profile:e})}async getCallerIdentity(){let t=await this.client.request({service:"sts",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetCallerIdentity&Version=2011-06-15"});if(typeof t==="string"){let n=t.match(/<Account>(\d+)<\/Account>/),r=t.match(/<UserId>([^<]+)<\/UserId>/),i=t.match(/<Arn>([^<]+)<\/Arn>/);return{Account:n?.[1],UserId:r?.[1],Arn:i?.[1]}}let e=t?.GetCallerIdentityResponse?.GetCallerIdentityResult||t?.GetCallerIdentityResult;if(e)return{Account:String(e.Account),UserId:e.UserId,Arn:e.Arn};if(t?.Account)return{Account:String(t.Account),UserId:t.UserId,Arn:t.Arn};return{Account:void 0,UserId:void 0,Arn:void 0}}}
2
2
  export{bt};
@@ -0,0 +1 @@
1
+ import{Ti}from"./chunk-3wvpgb8m.js";import"./chunk-89v3ec9n.js";import"./chunk-nzg624aj.js";import"./chunk-19mhwmfp.js";import"./chunk-qpasspad.js";import"./chunk-yf2drw7r.js";import"./chunk-1wgyq50e.js";import"./chunk-btrxye8p.js";import"./chunk-sacx9p6f.js";import"./chunk-8rkfwgb4.js";export{Ti as resolveDashboardData};
@@ -1 +1 @@
1
- import{wo}from"./chunk-hhbmtgkq.js";var Fp="\x00";function Id(t,i){if(t==="*"||t==="**")return!0;let e=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*");return new RegExp(`^${e}$`).test(i)}function g(t,i){if(t.startsWith("*.")){let e=t.slice(1);return i.endsWith(e)&&i.length>e.length}return t===i}function uc(t,i){if(t.enabled===!1)return!1;if(t.methods?.length&&!t.methods.some((e)=>e.toUpperCase()===i.method.toUpperCase()))return!1;if(t.path&&!Id(t.path,i.path))return!1;if(t.host&&!g(t.host,i.host??""))return!1;return!0}function pc(t,i){let e=t.key??{source:"ip"},o=e.fallbackToIp!==!1,r;if(e.source==="ip")r=i.ip;else if(e.source==="global")r="global";else if(e.source==="host")r=i.host??"";else if(e.source==="path")r=i.path;else if(e.source==="header")r=e.name?i.headers?.[e.name.toLowerCase()]:void 0;else if(e.source==="cookie")r=e.name?i.cookies?.[e.name]:void 0;if(!r&&e.source!=="global")r=o?i.ip:"__missing__";return`${t.id}\x00${r}`}class Pd{clock;maxTrackedKeys;buckets=new Map;windows=new Map;rules;constructor(t,i=()=>Date.now(),e=1e5){this.clock=i;this.maxTrackedKeys=e;this.rules=[...t].sort((o,r)=>(o.priority??0)-(r.priority??0))}check(t){let i=this.clock(),e=this.rules.filter((n)=>uc(n,t)),o;for(let n of e){let s=this.test(n,t,i);if(s.allowed)continue;if(!o||d(s.action)>d(o.action))o=s}if(o)return o;let r={action:"allow",allowed:!0};for(let n of e){let s=this.consume(n,t,i);if(s.remaining!=null&&(r.remaining??1/0)>s.remaining)r=s}return r}test(t,i,e){let o=pc(t,i);if((t.algorithm??"token_bucket")==="token_bucket"){let n=t.burst??t.limit,s=this.buckets.get(o),a=s?Math.min(n,s.tokens+this.refill(t,e-s.updatedAt)):n;if(a>=1)return{action:"allow",allowed:!0};return this.blocked(t,o,0,this.msPerToken(t)*(1-a),e)}let r=(this.windows.get(o)?.hits??[]).filter((n)=>n>e-t.windowMs);if(r.length<t.limit)return{action:"allow",allowed:!0};return this.blocked(t,o,0,r[0]+t.windowMs-e,e)}peek(t){let i=this.clock();for(let e of this.rules){if(!uc(e,t))continue;let o=this.test(e,t,i);if(!o.allowed)return o}return{action:"allow",allowed:!0}}msPerToken(t){return t.windowMs/Math.max(1,t.limit)}refill(t,i){return Math.max(0,i)/this.msPerToken(t)}blocked(t,i,e,o,r){let n=t.action??"deny";return{action:n,allowed:n==="allow"||n==="log",ruleId:t.id,limit:t.limit,remaining:e,retryAfterMs:Math.max(0,Math.ceil(o)),resetAt:r+Math.max(0,o),key:i}}consume(t,i,e){let o=pc(t,i);if((t.algorithm??"token_bucket")==="token_bucket"){let l=t.burst??t.limit,u=this.buckets.get(o)??{tokens:l,updatedAt:e},c=Math.min(l,u.tokens+this.refill(t,e-u.updatedAt));if(c<1)return this.buckets.set(o,{tokens:c,updatedAt:e}),this.blocked(t,o,0,this.msPerToken(t)*(1-c),e);return this.evictIfNeeded(this.buckets),this.buckets.set(o,{tokens:c-1,updatedAt:e}),{action:"allow",allowed:!0,ruleId:t.id,limit:l,remaining:Math.floor(c-1),resetAt:e+this.msPerToken(t)*(l-(c-1)),key:o}}let n=this.windows.get(o)??{hits:[]},s=e-t.windowMs,a=n.hits.filter((l)=>l>s);if(a.length>=t.limit)return this.windows.set(o,{hits:a}),this.blocked(t,o,0,a[0]+t.windowMs-e,e);return a.push(e),this.evictIfNeeded(this.windows),this.windows.set(o,{hits:a}),{action:"allow",allowed:!0,ruleId:t.id,limit:t.limit,remaining:t.limit-a.length,resetAt:a[0]+t.windowMs,key:o}}evictIfNeeded(t){if(t.size<this.maxTrackedKeys)return;let i=t.size-this.maxTrackedKeys+1,e=0;for(let o of t.keys())if(t.delete(o),++e>=i)break}sweep(){let t=this.clock(),i=0;for(let[e,o]of this.windows){let r=e.split("\x00")[0],n=this.rules.find((s)=>s.id===r);if(!n){this.windows.delete(e),i++;continue}if(o.hits.every((s)=>s<=t-n.windowMs))this.windows.delete(e),i++}for(let[e,o]of this.buckets){let r=e.split("\x00")[0],n=this.rules.find((s)=>s.id===r);if(!n||t-o.updatedAt>n.windowMs*2)this.buckets.delete(e),i++}return i}get trackedKeys(){return this.buckets.size+this.windows.size}}function d(t){return{allow:0,log:1,throttle:2,challenge:3,deny:4}[t]}function jp(t){let i={};if(t.limit!=null)i["ratelimit-limit"]=String(t.limit);if(t.remaining!=null)i["ratelimit-remaining"]=String(t.remaining);if(t.resetAt!=null)i["ratelimit-reset"]=String(Math.max(0,Math.ceil((t.resetAt-Date.now())/1000)));if(!t.allowed&&t.retryAfterMs!=null)i["retry-after"]=String(Math.max(1,Math.ceil(t.retryAfterMs/1000)));return i}function Vp(){return[{id:"global-ip",limit:600,windowMs:60000,burst:100,key:{source:"ip"},action:"deny",priority:100},{id:"api-ip",limit:120,windowMs:60000,burst:30,path:"/api/**",key:{source:"ip"},action:"deny",priority:50},{id:"auth-ip",limit:10,windowMs:60000,algorithm:"sliding_window",path:"/auth/**",methods:["POST"],key:{source:"ip"},action:"challenge",priority:10}]}var m="protection.controls",ir=24,_n=4,R={ipRules:{allow:[],block:[]}};function p(t,i){if(!t?.enabled)return;return new Date(t.expiresAt).getTime()>i.getTime()?t:void 0}function h(t,i){let e=Number.isFinite(t)?Number(t):i;return Math.min(ir,Math.max(0.25,e))}var f=500;class or{controlPlane;options;constructor(t,i={}){this.controlPlane=t;this.options=i}now(){return this.options.now?.()??new Date}read(){let t=this.controlPlane.getSetting(m);if(!t||typeof t!=="object"||Array.isArray(t))return{...R,ipRules:{allow:[],block:[]}};let i=t;return{attackMode:i.attackMode,mitigationPause:i.mitigationPause,ipRules:{allow:Array.isArray(i.ipRules?.allow)?i.ipRules.allow:[],block:Array.isArray(i.ipRules?.block)?i.ipRules.block:[]},updatedAt:i.updatedAt}}write(t){let i={...t,updatedAt:this.now().toISOString()};return this.controlPlane.setSetting(m,i),i}raw(){return this.read()}current(){let t=this.now(),i=this.read();return{attackMode:p(i.attackMode,t),mitigationPause:p(i.mitigationPause,t),ipRules:i.ipRules}}enableAttackMode(t){let i=this.now(),e={enabled:!0,startedAt:i.toISOString(),expiresAt:new Date(i.getTime()+h(t.hours,_n)*3600000).toISOString(),reason:t.reason.trim()||"Attack mode enabled by an operator.",actorId:t.actorId};return this.write({...this.read(),attackMode:e}),e}disableAttackMode(){let t=this.read();if(!t.attackMode?.enabled)return!1;return this.write({...t,attackMode:{...t.attackMode,enabled:!1}}),!0}pauseMitigations(t){let i=t.reason.trim();if(!i)throw Error("Pausing mitigations requires a reason: you are liable for the traffic it admits.");let e=this.now(),o={enabled:!0,startedAt:e.toISOString(),expiresAt:new Date(e.getTime()+h(t.hours,ir)*3600000).toISOString(),reason:i,actorId:t.actorId};return this.write({...this.read(),mitigationPause:o}),o}resumeMitigations(){let t=this.read();if(!t.mitigationPause?.enabled)return!1;return this.write({...t,mitigationPause:{...t.mitigationPause,enabled:!1}}),!0}addIpRule(t,i){let e=i.trim();if(!wo(e))throw Error(`Not a valid IP or CIDR: ${i}`);let o=this.read(),r={...o.ipRules,[t]:[...new Set([...o.ipRules[t],e])]};if(r[t].length>f)throw Error(`At most ${f} ${t} rules are supported.`);let n=t==="allow"?"block":"allow";return r[n]=r[n].filter((s)=>s!==e),this.write({...o,ipRules:r}),r}removeIpRule(t,i){let e=this.read(),o={...e.ipRules,[t]:e.ipRules[t].filter((r)=>r!==i.trim())};return this.write({...e,ipRules:o}),o}}function Xi(t){if(t.mitigationPause)return{attackMode:!!t.attackMode,mitigationPaused:!0,summary:`Automatic mitigation is paused until ${t.mitigationPause.expiresAt}. All traffic is being served and billed.`,expiresAt:t.mitigationPause.expiresAt};if(t.attackMode)return{attackMode:!0,mitigationPaused:!1,summary:`Attack mode is on until ${t.attackMode.expiresAt}. Every visitor is being challenged.`,expiresAt:t.attackMode.expiresAt};return{attackMode:!1,mitigationPaused:!1,summary:"Protection is in its normal posture."}}function zp(t,i){if(i.mitigationPause)return t.map((e)=>({...e,enabled:!1}));if(!i.attackMode)return[...t];return t.map((e)=>({...e,action:e.action==="deny"?"deny":"challenge",burst:Math.max(1,Math.min(e.burst??e.limit,5))}))}function On(t,i){let e=[...new Set([...t.allowlist??[],...i.ipRules.allow])],o=[...new Set([...t.blocklist??[],...i.ipRules.block])];if(i.mitigationPause)return{...t,allowlist:e,blocklist:o,monitorOnly:!0};if(!i.attackMode)return{...t,allowlist:e,blocklist:o};let r=t.thresholds??{};return{...t,allowlist:e,blocklist:o,thresholds:{...r,newConnectionsPerSecond:Math.max(1,Math.floor((r.newConnectionsPerSecond??50)/5)),concurrentPerSource:Math.max(1,Math.floor((r.concurrentPerSource??100)/5))}}}function ls(t,i){let e=t?.infrastructure?.compute;if(!e||e.ddos===!1)return t;let o=typeof e.ddos==="object"&&e.ddos!==null?e.ddos:{};return{...t,infrastructure:{...t.infrastructure,compute:{...e,ddos:On(o,i)}}}}export{Fp,Id,uc,pc,Pd,jp,Vp,ir,_n,or,Xi,zp,On,ls};
1
+ import{Ao}from"./chunk-b1cb27m8.js";var jp="\x00";function Pd(t,i){if(t==="*"||t==="**")return!0;let e=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*");return new RegExp(`^${e}$`).test(i)}function g(t,i){if(t.startsWith("*.")){let e=t.slice(1);return i.endsWith(e)&&i.length>e.length}return t===i}function pc(t,i){if(t.enabled===!1)return!1;if(t.methods?.length&&!t.methods.some((e)=>e.toUpperCase()===i.method.toUpperCase()))return!1;if(t.path&&!Pd(t.path,i.path))return!1;if(t.host&&!g(t.host,i.host??""))return!1;return!0}function mc(t,i){let e=t.key??{source:"ip"},o=e.fallbackToIp!==!1,r;if(e.source==="ip")r=i.ip;else if(e.source==="global")r="global";else if(e.source==="host")r=i.host??"";else if(e.source==="path")r=i.path;else if(e.source==="header")r=e.name?i.headers?.[e.name.toLowerCase()]:void 0;else if(e.source==="cookie")r=e.name?i.cookies?.[e.name]:void 0;if(!r&&e.source!=="global")r=o?i.ip:"__missing__";return`${t.id}\x00${r}`}class Dd{clock;maxTrackedKeys;buckets=new Map;windows=new Map;rules;constructor(t,i=()=>Date.now(),e=1e5){this.clock=i;this.maxTrackedKeys=e;this.rules=[...t].sort((o,r)=>(o.priority??0)-(r.priority??0))}check(t){let i=this.clock(),e=this.rules.filter((n)=>pc(n,t)),o;for(let n of e){let s=this.test(n,t,i);if(s.allowed)continue;if(!o||d(s.action)>d(o.action))o=s}if(o)return o;let r={action:"allow",allowed:!0};for(let n of e){let s=this.consume(n,t,i);if(s.remaining!=null&&(r.remaining??1/0)>s.remaining)r=s}return r}test(t,i,e){let o=mc(t,i);if((t.algorithm??"token_bucket")==="token_bucket"){let n=t.burst??t.limit,s=this.buckets.get(o),a=s?Math.min(n,s.tokens+this.refill(t,e-s.updatedAt)):n;if(a>=1)return{action:"allow",allowed:!0};return this.blocked(t,o,0,this.msPerToken(t)*(1-a),e)}let r=(this.windows.get(o)?.hits??[]).filter((n)=>n>e-t.windowMs);if(r.length<t.limit)return{action:"allow",allowed:!0};return this.blocked(t,o,0,r[0]+t.windowMs-e,e)}peek(t){let i=this.clock();for(let e of this.rules){if(!pc(e,t))continue;let o=this.test(e,t,i);if(!o.allowed)return o}return{action:"allow",allowed:!0}}msPerToken(t){return t.windowMs/Math.max(1,t.limit)}refill(t,i){return Math.max(0,i)/this.msPerToken(t)}blocked(t,i,e,o,r){let n=t.action??"deny";return{action:n,allowed:n==="allow"||n==="log",ruleId:t.id,limit:t.limit,remaining:e,retryAfterMs:Math.max(0,Math.ceil(o)),resetAt:r+Math.max(0,o),key:i}}consume(t,i,e){let o=mc(t,i);if((t.algorithm??"token_bucket")==="token_bucket"){let l=t.burst??t.limit,u=this.buckets.get(o)??{tokens:l,updatedAt:e},c=Math.min(l,u.tokens+this.refill(t,e-u.updatedAt));if(c<1)return this.buckets.set(o,{tokens:c,updatedAt:e}),this.blocked(t,o,0,this.msPerToken(t)*(1-c),e);return this.evictIfNeeded(this.buckets),this.buckets.set(o,{tokens:c-1,updatedAt:e}),{action:"allow",allowed:!0,ruleId:t.id,limit:l,remaining:Math.floor(c-1),resetAt:e+this.msPerToken(t)*(l-(c-1)),key:o}}let n=this.windows.get(o)??{hits:[]},s=e-t.windowMs,a=n.hits.filter((l)=>l>s);if(a.length>=t.limit)return this.windows.set(o,{hits:a}),this.blocked(t,o,0,a[0]+t.windowMs-e,e);return a.push(e),this.evictIfNeeded(this.windows),this.windows.set(o,{hits:a}),{action:"allow",allowed:!0,ruleId:t.id,limit:t.limit,remaining:t.limit-a.length,resetAt:a[0]+t.windowMs,key:o}}evictIfNeeded(t){if(t.size<this.maxTrackedKeys)return;let i=t.size-this.maxTrackedKeys+1,e=0;for(let o of t.keys())if(t.delete(o),++e>=i)break}sweep(){let t=this.clock(),i=0;for(let[e,o]of this.windows){let r=e.split("\x00")[0],n=this.rules.find((s)=>s.id===r);if(!n){this.windows.delete(e),i++;continue}if(o.hits.every((s)=>s<=t-n.windowMs))this.windows.delete(e),i++}for(let[e,o]of this.buckets){let r=e.split("\x00")[0],n=this.rules.find((s)=>s.id===r);if(!n||t-o.updatedAt>n.windowMs*2)this.buckets.delete(e),i++}return i}get trackedKeys(){return this.buckets.size+this.windows.size}}function d(t){return{allow:0,log:1,throttle:2,challenge:3,deny:4}[t]}function Vp(t){let i={};if(t.limit!=null)i["ratelimit-limit"]=String(t.limit);if(t.remaining!=null)i["ratelimit-remaining"]=String(t.remaining);if(t.resetAt!=null)i["ratelimit-reset"]=String(Math.max(0,Math.ceil((t.resetAt-Date.now())/1000)));if(!t.allowed&&t.retryAfterMs!=null)i["retry-after"]=String(Math.max(1,Math.ceil(t.retryAfterMs/1000)));return i}function zp(){return[{id:"global-ip",limit:600,windowMs:60000,burst:100,key:{source:"ip"},action:"deny",priority:100},{id:"api-ip",limit:120,windowMs:60000,burst:30,path:"/api/**",key:{source:"ip"},action:"deny",priority:50},{id:"auth-ip",limit:10,windowMs:60000,algorithm:"sliding_window",path:"/auth/**",methods:["POST"],key:{source:"ip"},action:"challenge",priority:10}]}var m="protection.controls",ir=24,_n=4,R={ipRules:{allow:[],block:[]}};function p(t,i){if(!t?.enabled)return;return new Date(t.expiresAt).getTime()>i.getTime()?t:void 0}function h(t,i){let e=Number.isFinite(t)?Number(t):i;return Math.min(ir,Math.max(0.25,e))}var f=500;class or{controlPlane;options;constructor(t,i={}){this.controlPlane=t;this.options=i}now(){return this.options.now?.()??new Date}read(){let t=this.controlPlane.getSetting(m);if(!t||typeof t!=="object"||Array.isArray(t))return{...R,ipRules:{allow:[],block:[]}};let i=t;return{attackMode:i.attackMode,mitigationPause:i.mitigationPause,ipRules:{allow:Array.isArray(i.ipRules?.allow)?i.ipRules.allow:[],block:Array.isArray(i.ipRules?.block)?i.ipRules.block:[]},updatedAt:i.updatedAt}}write(t){let i={...t,updatedAt:this.now().toISOString()};return this.controlPlane.setSetting(m,i),i}raw(){return this.read()}current(){let t=this.now(),i=this.read();return{attackMode:p(i.attackMode,t),mitigationPause:p(i.mitigationPause,t),ipRules:i.ipRules}}enableAttackMode(t){let i=this.now(),e={enabled:!0,startedAt:i.toISOString(),expiresAt:new Date(i.getTime()+h(t.hours,_n)*3600000).toISOString(),reason:t.reason.trim()||"Attack mode enabled by an operator.",actorId:t.actorId};return this.write({...this.read(),attackMode:e}),e}disableAttackMode(){let t=this.read();if(!t.attackMode?.enabled)return!1;return this.write({...t,attackMode:{...t.attackMode,enabled:!1}}),!0}pauseMitigations(t){let i=t.reason.trim();if(!i)throw Error("Pausing mitigations requires a reason: you are liable for the traffic it admits.");let e=this.now(),o={enabled:!0,startedAt:e.toISOString(),expiresAt:new Date(e.getTime()+h(t.hours,ir)*3600000).toISOString(),reason:i,actorId:t.actorId};return this.write({...this.read(),mitigationPause:o}),o}resumeMitigations(){let t=this.read();if(!t.mitigationPause?.enabled)return!1;return this.write({...t,mitigationPause:{...t.mitigationPause,enabled:!1}}),!0}addIpRule(t,i){let e=i.trim();if(!Ao(e))throw Error(`Not a valid IP or CIDR: ${i}`);let o=this.read(),r={...o.ipRules,[t]:[...new Set([...o.ipRules[t],e])]};if(r[t].length>f)throw Error(`At most ${f} ${t} rules are supported.`);let n=t==="allow"?"block":"allow";return r[n]=r[n].filter((s)=>s!==e),this.write({...o,ipRules:r}),r}removeIpRule(t,i){let e=this.read(),o={...e.ipRules,[t]:e.ipRules[t].filter((r)=>r!==i.trim())};return this.write({...e,ipRules:o}),o}}function Qi(t){if(t.mitigationPause)return{attackMode:!!t.attackMode,mitigationPaused:!0,summary:`Automatic mitigation is paused until ${t.mitigationPause.expiresAt}. All traffic is being served and billed.`,expiresAt:t.mitigationPause.expiresAt};if(t.attackMode)return{attackMode:!0,mitigationPaused:!1,summary:`Attack mode is on until ${t.attackMode.expiresAt}. Every visitor is being challenged.`,expiresAt:t.attackMode.expiresAt};return{attackMode:!1,mitigationPaused:!1,summary:"Protection is in its normal posture."}}function Hp(t,i){if(i.mitigationPause)return t.map((e)=>({...e,enabled:!1}));if(!i.attackMode)return[...t];return t.map((e)=>({...e,action:e.action==="deny"?"deny":"challenge",burst:Math.max(1,Math.min(e.burst??e.limit,5))}))}function On(t,i){let e=[...new Set([...t.allowlist??[],...i.ipRules.allow])],o=[...new Set([...t.blocklist??[],...i.ipRules.block])];if(i.mitigationPause)return{...t,allowlist:e,blocklist:o,monitorOnly:!0};if(!i.attackMode)return{...t,allowlist:e,blocklist:o};let r=t.thresholds??{};return{...t,allowlist:e,blocklist:o,thresholds:{...r,newConnectionsPerSecond:Math.max(1,Math.floor((r.newConnectionsPerSecond??50)/5)),concurrentPerSource:Math.max(1,Math.floor((r.concurrentPerSource??100)/5))}}}function ds(t,i){let e=t?.infrastructure?.compute;if(!e||e.ddos===!1)return t;let o=typeof e.ddos==="object"&&e.ddos!==null?e.ddos:{};return{...t,infrastructure:{...t.infrastructure,compute:{...e,ddos:On(o,i)}}}}export{jp,Pd,pc,mc,Dd,Vp,zp,ir,_n,or,Qi,Hp,On,ds};
@@ -0,0 +1,11 @@
1
+ import{H,Fr}from"./chunk-sacx9p6f.js";function W(e,t){return`/var/www/${e}-${t}`}var fe=new Set(["laravel","php","statamic","wordpress"]);function ki(e){return e.type!=null&&fe.has(e.type)}function Bs(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 me(e){return Bs(e).length>0}function re(e){if(e.deploy)return e.deploy;if(ki(e))return"server";if(e.start)return"server";return"bucket"}function A(e){if(e.redirect)return"redirect";if(me(e))return"proxy";if(ki(e))return"server-php";if(re(e)==="bucket")return"bucket";return e.start?"server-app":"server-static"}function Io(e){return e.infrastructure?.compute!=null||Boolean(e.cloud?.attachTo?.trim())}function Fs(e,t={}){let r=[],n=[],o=e.sites||{},s=Io(e),l=Fr(e);if(l)r.push(l);let p=new Map;for(let[c,i]of Object.entries(o)){if(!i)continue;let m=re(i),C=A(i);if(C==="redirect"){if(!i.domain)r.push(`Site '${c}' is a redirect site but has no \`domain\` to redirect from.`);if(!(typeof i.redirect==="string"?i.redirect:i.redirect?.to))r.push(`Site '${c}' is a redirect site but has no redirect target (\`redirect\` / \`redirect.to\`).`);if(!s)r.push(`Site '${c}' is a redirect site but no \`infrastructure.compute\` is configured to host the gateway that serves the redirect.`);let a=[];if(i.start)a.push("start");if(i.root)a.push("root");if(i.proxyTo)a.push("proxyTo");if(a.length>0)n.push(`Site '${c}' is a redirect site but also sets ${a.join(", ")}. These are ignored.`);continue}if(C==="proxy"){if(!i.domain)r.push(`Site '${c}' is a proxy site but has no \`domain\` to route from.`);if(!s)r.push(`Site '${c}' is a proxy site but no \`infrastructure.compute\` is configured to host the gateway that forwards it.`);let u=[];if(i.start)u.push("start");if(i.root)u.push("root");if(typeof i.port==="number")u.push("port");if(i.build)u.push("build");if(i.preStart&&i.preStart.length>0)u.push("preStart");if(u.length>0)n.push(`Site '${c}' sets \`proxyTo\`, so ts-cloud ships and supervises nothing for it. ${u.join(", ")} ${u.length===1?"is":"are"} ignored — remove ${u.length===1?"it":"them"}, or drop \`proxyTo\` to let ts-cloud own the service.`);continue}if(m==="server"&&!i.start&&!i.root){r.push(`Site '${c}' sets deploy:'server' but declares neither \`start\` (dynamic app) nor \`root\` (static site to serve). Add one.`);continue}if(C==="server-php"){if(!s)r.push(`Site '${c}' is a PHP site (type:'${i.type}') but no \`infrastructure.compute\` is configured. Add a server (infrastructure.compute) with PHP provisioning.`);if(!i.repository?.url)r.push(`Site '${c}' is a PHP site (type:'${i.type}') but has no \`repository.url\` to clone. PHP sites deploy via git.`)}else if(C==="server-app"){if(!s)r.push(`Site '${c}' deploys to a server (deploy:'server'${i.deploy?"":" inferred from `start`"}) but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`);if(typeof i.port==="number"){let u=t.occupiedPorts?.get(i.port);if(u)r.push(`Site '${c}' wants port ${i.port}, which project '${u}' already serves on this box. Attached projects share one port namespace. Give '${c}' a free port, or let the attach allocate one.`);let a=p.get(i.port);if(a)r.push(`Sites '${a}' and '${c}' both use port ${i.port}. Server apps sharing a box must use distinct ports.`);else p.set(i.port,c)}}else if(C==="server-static"){if(!i.root)r.push(`Site '${c}' is a server static site (deploy:'server', no \`start\`) but has no \`root\` directory to serve.`);if(!s)r.push(`Site '${c}' deploys to a server (deploy:'server') but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`)}else{if(!i.root)r.push(`Site '${c}' deploys to a bucket but has no \`root\` directory to upload.`);let u=[];if(i.start)u.push("start");if(typeof i.port==="number")u.push("port");if(i.preStart&&i.preStart.length>0)u.push("preStart");if(u.length>0)n.push(`Site '${c}' deploys to a bucket but sets server-only field(s): ${u.join(", ")}. These are ignored. Set deploy:'server' to use them.`)}}return{errors:r,warnings:n}}function js(e){let t=A(e);return t!=="bucket"&&t!=="redirect"&&t!=="proxy"}function Wc(e){return A(e)==="bucket"}function Kc(e,t){if(H(e)==="serverless")return!0;let r=Object.entries(e.sites??{}).filter(([,o])=>o!=null),n=t?r.filter(([o])=>o===t):r;if(n.length===0)return!0;return!n.every(([,o])=>{let s=A(o);return s==="redirect"||s==="proxy"})}var U={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 R="/opt/pantry";function N(e){return`'${e.split("'").join("'\\''")}'`}function Tt(e={}){let t=e.installDir??"/usr/local/bin",r=e.version?`export PANTRY_VERSION=${N(e.version)}`:'export PANTRY_VERSION="${PANTRY_VERSION:-latest}"';return["export DEBIAN_FRONTEND=noninteractive","export PANTRY_SERVICE_SCOPE=system",`export PANTRY_INSTALL_DIR=${t}`,r,"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}"; mkdir -p ${t}; unzip -o "\${TMP}/\${ZIP}" -d ${t}; chmod +x ${t}/pantry; rm -rf "\${TMP}"`,`export PATH="${t}:$PATH"`,"mkdir -p /opt/pantry"]}function Ve(){return'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true'}function it(e){if(e.length===0)return[];return[`(cd /opt/pantry && pantry install ${[...new Set(e)].map(N).join(" ")})`]}function Po(e){return[...new Set(e)].flatMap((t)=>[`(cd /opt/pantry && pantry start ${N(t)})`,`(cd /opt/pantry && pantry enable ${N(t)})`])}var f="/etc/mail",T="mail-server",F="mail",Y=`${R}/pantry/.bin`;function h(e){return`'${String(e).split("'").join("'\\''")}'`}function P(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function ge(e){return[e.version?`${U.mail}@${e.version}`:U.mail]}function K(e,t){return`${f}/dkim/${t}.${e.dkim.selector}.pem`}function ne(e){return`${e.storagePath}/smtp.db`}function Te(e){let t=["# Generated by ts-cloud. Edits are overwritten on the next deploy —","# change `services.mail` in the cloud config instead.","","[server]",`host = ${P(e.bindAddress)}`,`port = ${e.ports.smtp}`,`hostname = ${P(e.hostname)}`];if(e.domains.length>0)t.push(`local_domains = ${P(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 = ${P(e.tls.certPath)}`);if(e.tls.keyPath)t.push(`key_path = ${P(e.tls.keyPath)}`);if(t.push("","[auth]",`enabled = ${e.mode==="server"}`,"","[antispam]",`dnsbl = ${e.spam.dnsbl}`,`dnsbl_reject = ${e.spam.dnsblReject}`,`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 = ${P(e.tls.acmeEmail)}`);if(t.push("","[webhook]",`enabled = ${!!e.webhookUrl}`),e.webhookUrl)t.push(`url = ${P(e.webhookUrl)}`);return t.push(""),t.join(`
2
+ `)}function he(e){let t=["# Generated by ts-cloud. See /etc/mail/config.toml for the rest.",`SMTP_DB_PATH=${ne(e)}`,`SMTP_DNSBL_REJECT=${e.spam.dnsblReject}`,`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_TLS=${e.webmail.tls}`,`SMTP_WEBMAIL_SECURE_COOKIES=${e.webmail.secureCookies}`,`SMTP_WEBMAIL_ATTACHMENT_MAX_FILE=${e.webmail.attachmentMaxFileBytes}`,`SMTP_WEBMAIL_ATTACHMENT_MAX_TOTAL=${e.webmail.attachmentMaxTotalBytes}`,`SMTP_WEBMAIL_ATTACHMENT_MAX_COUNT=${e.webmail.attachmentMaxCount}`,`SMTP_WEBMAIL_UNDO_SEND_SECONDS=${e.webmail.undoSendSeconds}`);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=${K(e,r)}`),n.length>0){let o=n.map((s)=>`${s}:${e.dkim.selector}:${K(e,s)}`);t.push(`DKIM_EXTRA_KEYS=${o.join(",")}`)}}return t.push(""),t.join(`
3
+ `)}function Ee(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=${f}/mail.env`,`Environment="PATH=${Y}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"`,`ExecStart=${Y}/mail serve --config ${f}/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} ${f}`,"","[Install]","WantedBy=multi-user.target",""].join(`
4
+ `)}function ye(e){if(!e.dkim.enabled||e.domains.length===0)return[];let t=[`mkdir -p ${f}/dkim`];for(let r of e.domains){let n=K(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} ${f}/dkim`),t}function ve(e){if(e.accounts.length===0)return[];let t=(r)=>`runuser -u ${T} -- env SMTP_DB_PATH="$TS_CLOUD_MAIL_DB" ${Y}/mail user:local ${r}`;return e.accounts.flatMap((r)=>[t(`create ${h(r.address)} ${h(r.password)} ${h(r.address)}`),...r.passwordPolicy==="managed"?[t(`change-password ${h(r.address)} ${h(r.password)}`)]:[]])}function Do(e){if(!e.enabled)return[];return[...it(ge(e)),`id -u ${T} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin ${T}`,`mkdir -p ${e.storagePath} ${f}`,`chown -R ${T}:${T} ${e.storagePath}`,`TS_CLOUD_MAIL_DB="$(grep -sE '^SMTP_DB_PATH=' ${f}/mail.env | head -1 | cut -d= -f2- || true)"`,`[ -n "$TS_CLOUD_MAIL_DB" ] || TS_CLOUD_MAIL_DB=${h(ne(e))}`,`cat > ${f}/config.toml <<'TS_CLOUD_MAIL_CONF_EOF'`,Te(e),"TS_CLOUD_MAIL_CONF_EOF",`cat > ${f}/mail.env <<'TS_CLOUD_MAIL_ENV_EOF'`,he(e),"TS_CLOUD_MAIL_ENV_EOF",`sed -i "s|^SMTP_DB_PATH=.*|SMTP_DB_PATH=$TS_CLOUD_MAIL_DB|" ${f}/mail.env`,`chmod 0640 ${f}/mail.env`,`chown root:${T} ${f}/mail.env`,...ye(e),`cat > /etc/systemd/system/${F}.service <<'TS_CLOUD_MAIL_UNIT_EOF'`,Ee(e),"TS_CLOUD_MAIL_UNIT_EOF","systemctl daemon-reload",`systemctl enable ${F}`,`systemctl restart ${F}`,...ve(e)]}var g=`${R}/pantry/.bin`,z=15306,j=15991,w=15999,se=16101,B=2379,E="/var/lib/vitess",Q=100;function Ni(e){return e===!0||typeof e==="object"&&e!==null}function Ce(e){return typeof e==="object"&&e!==null?e:{}}function _(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 S="vitess",Re=`${g}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`,ce="/usr/local/lib/vitess",J=new Map;function X(e){return`${ce}/${e}.sh`}function b(e,t){return J.set(e,De(t)),`/bin/sh ${X(e)}`}function oe(){let e=[`mkdir -p ${ce}`];for(let[t,r]of J)e.push(`cat > ${X(t)} <<'TS_CLOUD_VITESS_LAUNCHER_EOF'`,r,"TS_CLOUD_VITESS_LAUNCHER_EOF",`chmod 0755 ${X(t)}`);return e}function De(e){return["#!/bin/sh","set -e",`cd ${R}`,`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 L(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=${S}`,`Group=${S}`,`Environment="PATH=${Re}"`,`Environment="VTDATAROOT=${E}"`,...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 ie(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_VITESS_UNIT_EOF'`,t,"TS_CLOUD_VITESS_UNIT_EOF"]}function be(e){let t=e.cell??"zone1",r=e.vtgatePort??z,o=`${((e.keyspaces?.length)?e.keyspaces:[{name:"app"}]).map((s)=>{let l=(s.sharded?["-80","80-"]:["0"]).map((p)=>`shards:{name:"${p}"}`).join(" ");return`keyspaces:{name:"${s.name}" ${l}}`}).join(" ")} cells:"${t}"`;return L({description:"Vitess (vtcombo, single-process development stack)",execStart:b("vtcombo",[`${g}/vtcombo`,`--cell ${t}`,`--proto-topo ${_(o)}`,`--mysql-server-port ${r}`,"--mysql-server-bind-address 127.0.0.1","--mysql-auth-server-impl none","--start-mysql",`--port ${j}`,`--grpc-port ${w}`])})}function Ae(){return L({description:"etcd (Vitess topology store)",execStart:b("etcd",[`${g}/etcd`,`--data-dir ${E}/etcd`,`--listen-client-urls http://127.0.0.1:${B}`,`--advertise-client-urls http://127.0.0.1:${B}`]),execStartPre:[`+/bin/mkdir -p ${E}/etcd`,`+/bin/chown ${S}:${S} ${E}/etcd`]})}function Z(e){return["--topo-implementation etcd2",`--topo-global-server-address ${e.etcdEndpoint??`http://127.0.0.1:${B}`}`,"--topo-global-root /vitess/global"]}function Le(e){let t=!e.etcdEndpoint;return L({description:"Vitess vtctld (control plane)",after:t?["vitess-etcd.service"]:[],requires:t?["vitess-etcd.service"]:[],execStart:b("vtctld",[`${g}/vtctld`,...Z(e),`--cell ${e.cell??"zone1"}`,"--service-map grpc-vtctl,grpc-vtctld",`--grpc-port ${w}`,`--port ${w+1}`])})}function Oe(e,t,r){let n=e.cell??"zone1";return L({description:`Vitess vttablet (${t}/${r})`,after:["vitess-vtctld.service","vitess-mysqlctld.service"],requires:["vitess-mysqlctld.service"],execStart:b("vttablet",[`${g}/vttablet`,...Z(e),`--tablet-path ${n}-${String(Q).padStart(10,"0")}`,`--init-keyspace ${t}`,`--init-shard ${r}`,"--init-tablet-type replica",`--service-map ${_("grpc-queryservice,grpc-tabletmanager,grpc-updatestream")}`,`--port ${se}`,`--grpc-port ${se+1}`,`--db-port ${e.mysqlPort??3306}`,`--mycnf-mysql-port ${e.mysqlPort??3306}`])})}function Ue(e){return L({description:"Vitess mysqlctld (managed mysqld)",execStart:b("mysqlctld",[`${g}/mysqlctld`,`--tablet-uid ${Q}`,`--mysql-port ${e.mysqlPort??3306}`,'--init-db-sql-file "$VTROOT/config/init_db.sql"',"--wait-time 2m"]),execStartPre:[`+/bin/mkdir -p ${E}`,`+/bin/chown ${S}:${S} ${E}`]})}var le="/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 ${S} -g ${S} -m 0600 "$VTESS_AUTH_TMP" ${le}`,'rm -f "$VTESS_AUTH_TMP"']}function ke(e){let t=e.cell??"zone1";return L({description:"Vitess vtgate (query router)",after:["vitess-vtctld.service"],execStart:b("vtgate",[`${g}/vtgate`,...Z(e),`--cell ${t}`,`--cells-to-watch ${t}`,"--tablet-types-to-wait PRIMARY,REPLICA",`--service-map ${_("grpc-vtgateservice")}`,`--mysql-server-port ${e.vtgatePort??z}`,`--mysql-server-bind-address ${e.bindAddress??"127.0.0.1"}`,"--mysql-auth-server-impl static",`--mysql-auth-server-static-file ${le}`,`--port ${j}`,`--grpc-port ${j+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}`,o=[`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 ${_(t)}; then`,` ${n} AddCellInfo --root ${_(`/vitess/${t}`)} --server-address ${_(r)} ${_(t)}`,"fi"];for(let s of e.keyspaces??[]){let l=s.sharded?" --sharded":"";o.push(`if ! ${n} GetKeyspace ${_(s.name)} >/dev/null 2>&1; then`,` ${n} CreateKeyspace${l} ${_(s.name)}`,"fi");let p=`${t}-${String(Q).padStart(10,"0")}`;for(let c of s.sharded?["-80","80-"]:["0"]){let i=`${s.name}/${c}`;o.push("for i in $(seq 1 90); do",` if ${n} GetShard ${_(i)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then break; fi`,` ${n} PlannedReparentShard ${_(i)} --new-primary ${_(p)} >/dev/null 2>&1 && break`,` ${n} InitShardPrimary --force ${_(i)} ${_(p)} >/dev/null 2>&1 && break`," sleep 2","done",`if ! ${n} GetShard ${_(i)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then`,` echo "no primary could be elected for ${i}" >&2; exit 1`,"fi")}o.push(`${n} RebuildKeyspaceGraph ${_(s.name)} >/dev/null`)}return o}function ae(e){let t=e.vtgatePort??z;return["for i in $(seq 1 60); do",` if (cd ${R} && eval "$(pantry env 2>/dev/null)"; MYSQL_PWD=${_(e.password??"")} ${g}/mysql -h 127.0.0.1 -P ${t} -u ${_(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 ko(e){if(!Ni(e))return[];let t=Ce(e),r=t.mode==="combo";J.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",...it(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 ${S} >/dev/null 2>&1 || useradd --system --home-dir ${E} --shell /usr/sbin/nologin ${S}`,`mkdir -p ${E}`,`chown -R ${S}:${S} ${E}`];if(r)return n.push(...ie("vitess-vtcombo",be(t)),...oe(),"systemctl daemon-reload","systemctl enable --now vitess-vtcombo.service",...ae(t)),n;n.push(...xe(t));let o=[];if(!t.etcdEndpoint)o.push(["vitess-etcd",Ae()]);o.push(["vitess-vtctld",Le(t)],["vitess-mysqlctld",Ue(t)],["vitess-vtgate",ke(t)]);for(let s of t.keyspaces??[])for(let l of s.sharded?["-80","80-"]:["0"])o.push([`vitess-vttablet-${s.name}-${l.replace(/-/g,"x")}`,Oe(t,s.name,l)]);for(let[s,l]of o)n.push(...ie(s,l));n.push(...oe()),n.push("systemctl daemon-reload");for(let[s]of o)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 ${S}:${S} ${x}; chmod 0600 ${x}; fi`,...Ie(t),...ae(t)),n}var Me=new Set(["singlestore","vitess"]);function gn(e){if(e?.engine&&Me.has(e.engine))return!1;return!e?.host||e.host==="127.0.0.1"||e.host==="localhost"}function Et(e,t="psql"){let r=e?.port??5432;if(gn(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(U.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 No(e={},t={}){let r=Ne(e),n=ko(e.vitess),o=t.mail?Do(t.mail):[];if(r.packages.length===0)return[...n,...o];return[...it(r.packages),...Po(r.services),...n,...o]}function wt(e,t={}){if(e?.requireLocalPasswordAuth&&(e.engine!=="postgres"||!gn(e)||!e.name||!e.username||!e.password||e.users?.some((a)=>!a.password)))throw Error("Password authentication requires a named local PostgreSQL database and nonempty login passwords");if(!e?.name)return[];if(!gn(e))return[];let r=e.name,n=e.username||r,o=e.password||"",s=y(t.postgres)||e.engine==="postgres",l=y(t.mariadb)||e.engine==="mariadb",p=y(t.mysql)||e.engine==="mysql";if(s&&!p&&!l){let a=(d)=>`"${d.replace(/"/g,'""')}"`,D=(d)=>`'${d.replace(/'/g,"''")}'`,O=(d,M)=>[...e.requireLocalPasswordAuth?["SET password_encryption = 'scram-sha-256';"]:[],"DO $$ BEGIN",` IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${D(d)}) THEN`,` CREATE ROLE ${a(d)} LOGIN PASSWORD ${D(M)};`," ELSE",` ALTER ROLE ${a(d)} LOGIN PASSWORD ${D(M)};`," END IF;","END $$;"],k=(d)=>{let M=d.databases&&d.databases.length>0?d.databases:[r],G=[];for(let q of M)if(d.access==="readonly")G.push(`GRANT CONNECT ON DATABASE ${a(q)} TO ${a(d.username)};`,`\\connect ${a(q)}`,`GRANT USAGE ON SCHEMA public TO ${a(d.username)};`,`GRANT SELECT ON ALL TABLES IN SCHEMA public TO ${a(d.username)};`,`ALTER DEFAULT PRIVILEGES FOR ROLE ${a(n)} IN SCHEMA public GRANT SELECT ON TABLES TO ${a(d.username)};`,"\\connect postgres");else G.push(`GRANT ALL PRIVILEGES ON DATABASE ${a(q)} TO ${a(d.username)};`);return G},I=e.users||[],Se=e.port??5432;return[Ve(),`for i in $(seq 1 30); do pg_isready -p ${Se} -q && break; sleep 2; done`,`${Et(e)}${e.requireLocalPasswordAuth?" -v ON_ERROR_STOP=1":""} <<'TS_CLOUD_PG_EOF'`,...O(n,o),`SELECT 'CREATE DATABASE ${a(r)} OWNER ${a(n)}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = ${D(r)})\\gexec`,...I.flatMap((d)=>[...O(d.username,d.password),...k(d)]),"TS_CLOUD_PG_EOF",...e.requireLocalPasswordAuth?[`TS_CLOUD_PG_HBA=$(${Et(e)} -Atc 'SHOW hba_file')`,'case "$TS_CLOUD_PG_HBA" in /*) ;; *) echo "Invalid PostgreSQL authentication path" >&2; exit 1 ;; esac','[ -f "$TS_CLOUD_PG_HBA.before-ts-cloud-password-auth" ] || cp -p "$TS_CLOUD_PG_HBA" "$TS_CLOUD_PG_HBA.before-ts-cloud-password-auth"','TS_CLOUD_PG_AUTH=$(mktemp "$TS_CLOUD_PG_HBA.ts-cloud.XXXXXXXX")',"{"," printf '%s\\n' '# BEGIN ts-cloud password authentication' 'host all all 127.0.0.1/32 scram-sha-256' 'host all all ::1/128 scram-sha-256' 'host replication all 127.0.0.1/32 scram-sha-256' 'host replication all ::1/128 scram-sha-256' '# END ts-cloud password authentication'",` sed '/^# BEGIN ts-cloud password authentication$/,/^# END ts-cloud password authentication$/d' "$TS_CLOUD_PG_HBA"`,'} > "$TS_CLOUD_PG_AUTH"','chown --reference="$TS_CLOUD_PG_HBA" "$TS_CLOUD_PG_AUTH"','chmod --reference="$TS_CLOUD_PG_HBA" "$TS_CLOUD_PG_AUTH"','mv -f "$TS_CLOUD_PG_AUTH" "$TS_CLOUD_PG_HBA"',`${Et(e)} -v ON_ERROR_STOP=1 -c 'SELECT pg_reload_conf()'`]:[],...we(e)]}let c=l?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock",i=(a)=>a.replace(/`/g,"``"),m=(a)=>a.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),C=(a)=>{let D=a.databases&&a.databases.length>0?a.databases:[r],O=a.access==="readonly"?"SELECT":"ALL PRIVILEGES",k=[`CREATE USER IF NOT EXISTS '${m(a.username)}'@'%' IDENTIFIED BY '${m(a.password)}';`,`CREATE USER IF NOT EXISTS '${m(a.username)}'@'localhost' IDENTIFIED BY '${m(a.password)}';`,`ALTER USER '${m(a.username)}'@'%' IDENTIFIED BY '${m(a.password)}';`,`ALTER USER '${m(a.username)}'@'localhost' IDENTIFIED BY '${m(a.password)}';`];for(let I of D)k.push(`GRANT ${O} ON \`${i(I)}\`.* TO '${m(a.username)}'@'%';`,`GRANT ${O} ON \`${i(I)}\`.* TO '${m(a.username)}'@'localhost';`);return k},u=e.users||[];return[Ve(),`for i in $(seq 1 30); do mysqladmin --socket=${c} -u root ping 2>/dev/null | grep -q alive && break; sleep 2; done`,`mysql --socket=${c} -u root <<'TS_CLOUD_SQL_EOF'`,`CREATE DATABASE IF NOT EXISTS \`${i(r)}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`,...C({username:n,password:o}),...u.flatMap(C),"FLUSH PRIVILEGES;","TS_CLOUD_SQL_EOF"]}function we(e){return[`${Et(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 Jc(e){if(!e?.name)return{};let t=e.engine==="singlestore",r=e.engine==="vitess",n=e.engine==="postgres"?"pgsql":t?"singlestore":r?"vitess":"mysql",o=e.port??(e.engine==="postgres"?5432:r?15306:3306),s={DB_CONNECTION:n,DB_HOST:e.host||"127.0.0.1",DB_PORT:String(o),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 V="/var/backups/ts-cloud",ee="/etc/ts-cloud/backups.config.ts",pe="/etc/cron.d/ts-cloud-backups",fn="/usr/local/bin/ts-cloud-backup.sh";function Be(e){if(!e.name)return null;if(!["postgres","mysql","mariadb"].includes(e.engine||""))throw Error("Unsupported scheduled SQL backup engine");return JSON.stringify({type:e.engine==="postgres"?"postgresql":"mysql",name:e.name,connection:{hostname:e.host||"127.0.0.1",port:e.port??(e.engine==="postgres"?5432:3306),database:e.name,username:e.username||e.name,password:e.password||"",ssl:!1},includeSchema:!0,includeData:!0})}function He(e,t){let r=e?Be(e):null,n=t.bucket?{type:"s3",bucket:t.bucket,prefix:t.prefix||"db-backups",...t.endpoint?{endpoint:t.endpoint}:{},...t.region?{region:t.region}:{},keepDays:t.retentionDays??30,optional:!1,...t.encryptionKey?{encryption:{keyEnv:"TS_CLOUD_BACKUP_ENCRYPTION_KEY"}}:{}}:void 0,o={verbose:!0,outputPath:V,retention:{count:t.retentionCount??5,maxAge:t.retentionDays??30},databases:[],files:t.files||[],destinations:n?[n]:[]};return["import type { BackupConfig } from 'ts-backups'",`const config: BackupConfig = ${JSON.stringify(o,null,2)}`,`config.databases = [
7
+ ${r||""}
8
+ ]`,...t.credentials?["config.destinations![0]!.credentials = { accessKeyId: process.env.TS_CLOUD_BACKUP_ACCESS_KEY!, secretAccessKey: process.env.TS_CLOUD_BACKUP_SECRET_KEY! }"]:[],"export default config",""].join(`
9
+ `)}function xi(e){let{database:t,backups:r}=e;if(!r.enabled)return[];if(r.credentials&&(!r.bucket||!r.credentials.accessKeyId||!r.credentials.secretAccessKey))throw Error("Scheduled backups require complete destination credentials and a bucket");if(r.encryptionKey&&(r.encryptionKey.length<32||!r.bucket))throw Error("Encrypted offsite backups require a bucket and a separate recovery key of at least 32 characters");let n=r.version||"0.1.6";if(!/^\d+\.\d+\.\d+$/.test(n))throw Error("Pin a released ts-backups version");let o=r.schedule||"0 2 * * *";if(!/^[0-9*,/ -]+$/.test(o)||o.trim().split(/\s+/).length!==5)throw Error("Invalid backup schedule");let s=(c)=>`'${c.replace(/'/g,"'\\''")}'`;if(r.archive){let c=new URL(r.archive.url);if(c.protocol!=="https:"||c.username||c.password||!/^[a-f0-9]{64}$/i.test(r.archive.sha256))throw Error("Backup archives require an HTTPS URL and SHA-256 checksum")}let l=Object.entries({...r.credentials?{TS_CLOUD_BACKUP_ACCESS_KEY:r.credentials.accessKeyId,TS_CLOUD_BACKUP_SECRET_KEY:r.credentials.secretAccessKey}:{},...r.encryptionKey?{TS_CLOUD_BACKUP_ENCRYPTION_KEY:r.encryptionKey}:{}}).map(([c,i])=>`${c}=${s(i)}`).join(`
10
+ `),p="/opt/ts-cloud/backups";return["umask 077",`mkdir -p /etc/ts-cloud ${V} ${p}`,`chmod 700 ${V} ${p}`,'export PATH="/opt/ts-cloud/bun/bin:/opt/pantry/pantry/.bin:/usr/local/bin:/usr/bin:/bin"',`test -f ${p}/package.json || printf '%s' '{"private":true}' > ${p}/package.json`,...r.archive?[`curl --fail --silent --show-error --location ${s(r.archive.url)} --output ${p}/release.tgz`,`printf '%s\\n' ${s(`${r.archive.sha256.toLowerCase()} ${p}/release.tgz`)} | sha256sum --check --status`,`bun add --cwd ${p} --no-save ${p}/release.tgz`,`test "$(cd ${p} && bun -e 'console.log((await Bun.file("node_modules/ts-backups/package.json").json()).version)')" = ${s(n)}`]:[`bun add --cwd ${p} --no-save ts-backups@${n}`],`printf '%s' ${s(He(t,r))} > ${ee}`,`printf '%s\\n' ${s(l)} > /etc/ts-cloud/backups.env`,`chmod 600 ${ee} /etc/ts-cloud/backups.env`,`cat > ${fn} <<'TS_CLOUD_BACKUP_RUN_EOF'`,"#!/bin/bash","set -euo pipefail","umask 077","exec 9>/run/lock/ts-cloud-backups.lock","flock -n 9 || exit 0",'export PATH="/opt/ts-cloud/bun/bin:/opt/pantry/pantry/.bin:/usr/local/bin:/usr/bin:/bin"','eval "$(cd /opt/pantry && pantry env)"',"set -a",". /etc/ts-cloud/backups.env","set +a",'notify() { [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "$1" || true; }',"cd /etc/ts-cloud",`if ! ${p}/node_modules/.bin/ts-backups start --config ${ee}; then notify "ts-cloud backup failed"; exit 1; fi`,"date -u +%FT%TZ > /var/backups/ts-cloud/last-success","TS_CLOUD_BACKUP_RUN_EOF",`chmod 700 ${fn}`,`printf '%s\\n' ${s(`${o} root ${fn} >> /var/log/ts-cloud-backup.log 2>&1`)} > ${pe}`,`chmod 644 ${pe}`]}function Ge(e){return e==="mariadb"?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock"}function _i(e,t={}){if(!e?.name)return[];let r=e.name,n=e.engine==="postgres",o=t.from?`TS_CLOUD_DUMP="${t.from}"`:`TS_CLOUD_DUMP="$(find ${V} -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?`${Et(e)} -d "${r}"`:`mysql --socket=${Ge(e.engine)} -u root "${r}"`;return["set -uo pipefail",'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true',o,'[ -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 xo=["storage",".env"],Oi=4;function v(e){return`${e.replace(/\/+$/,"")}/.ts-cloud`}function Vs(e){return`${v(e)}/deploy-history.log`}function qe(e,t){return`${v(e)}/deploys/${t}.log`}function ue(e){return`${v(e)}/shared-paths`}function _o(e){return`${e.shared}/stx-images`}function $i(e){return`${e.shared}/stx-bundles`}function Ht(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 zs(e){return typeof e==="string"?e:e.path}function Xc(e){let t=new Map;for(let r of e)t.set(zs(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 Li(e,t=xo){let r=[`mkdir -p ${e.releases} ${e.shared} ${_o(e)} ${$i(e)}`,...Fe(e)],n=t.map((s)=>$e(e,s));for(let{path:s,target:l,seed:p}of n){if(!p)continue;if(r.push(`ts_cloud_adopt_shared '${s}' '${l}'`),de(s))r.push(`mkdir -p "$(dirname ${l})"`,`touch ${l}`);else if(s==="storage")r.push(`mkdir -p ${l}/app/public`,`mkdir -p ${l}/framework/cache/data`,`mkdir -p ${l}/framework/sessions`,`mkdir -p ${l}/framework/testing`,`mkdir -p ${l}/framework/views`,`mkdir -p ${l}/logs`);else r.push(`mkdir -p ${l}`)}let o=ue(e.base);return r.push(`mkdir -p ${v(e.base)}`,`cat > ${o} <<'TS_CLOUD_SHARED_PATHS_EOF'`,...n.map((s)=>`${s.path} ${s.target}`),"TS_CLOUD_SHARED_PATHS_EOF"),r}function Hs(e,t=900){let r=`${v(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 Gs(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 qs(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 Ws(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 Oo(e,t=xo){let r=[];for(let n of t){let{path:o,target:s,seed:l}=$e(e,n),p=`${e.release}/${o}`,c=[`rm -rf ${p}`,`mkdir -p "$(dirname ${p})"`,`ln -sfn ${s} ${p}`];if(l){if(o!==".env"&&de(o))r.push(...Ke(p,s));r.push(...c);continue}r.push(`if [ -e ${s} ]; then`,...c.map((i)=>` ${i}`),"fi")}return r}function je(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 hn(e){return[`ln -sfn ${e.release} ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`]}function te(e){return`${v(e)}/previous-release`}function Ks(e,t="TS_CLOUD_PREV_CURRENT"){let r=te(e.base);return[`if [ -n "\${${t}:-}" ] && [ -d "$${t}" ] && [ "$(readlink -f "$${t}")" != "$(readlink -f ${e.release})" ]; then mkdir -p ${v(e.base)}; basename "$${t}" > ${r}; fi`]}function _e(e,t){let r=te(e.base);return[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,...t?[`TS_CLOUD_RB_TARGET=${e.releases}/${t}`]:["TS_CLOUD_RB_TARGET=",`if [ -f ${r} ]; then TS_CLOUD_REC="${e.releases}/$(cat ${r})"; if [ -d "$TS_CLOUD_REC" ] && [ "$(readlink -f "$TS_CLOUD_REC")" != "$TS_CLOUD_CURRENT" ]; then TS_CLOUD_RB_TARGET="$TS_CLOUD_REC"; fi; fi`,`[ -n "$TS_CLOUD_RB_TARGET" ] || TS_CLOUD_RB_TARGET=$(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_RB_TARGET" ] && [ -d "$TS_CLOUD_RB_TARGET" ] || { echo "no release to roll back to (looked for ${TS_CLOUD_RB_TARGET:-a previous release})" >&2; exit 1; }','[ "$(readlink -f "$TS_CLOUD_RB_TARGET")" != "$TS_CLOUD_CURRENT" ] || { echo "$(basename "$TS_CLOUD_RB_TARGET") is already the live release" >&2; exit 1; }','TS_CLOUD_RB_ID=$(basename "$TS_CLOUD_RB_TARGET")']}function Qc(e,t={}){return[..._e(e,t.to),'echo "would roll back from $(basename "${TS_CLOUD_CURRENT:-none}") to $TS_CLOUD_RB_ID (dry run: nothing changed)"']}function Yc(e,t={}){let r=Math.max(1,t.gateSeconds??5),n=t.systemdDir??"/etc/systemd/system",o=[`ln -sfn "$TS_CLOUD_RB_TARGET" ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`,`rm -f ${te(e.base)}`,'echo "rolled back to $TS_CLOUD_RB_ID"'],s=[..._e(e,t.to),...je(e,'"$TS_CLOUD_RB_TARGET"')];if(!t.unitBase)return[...s,...o];let l=t.unitBase,p=`${l}@\${TS_CLOUD_RB_ID}.service`;return[...s,`if [ -f ${n}/${l}@.service ]; then`,` systemctl start "${p}"`,` for TS_CLOUD_I in $(seq 1 ${r}); do sleep 1; systemctl is-active --quiet "${p}" || { echo "the release rolled back to, $TS_CLOUD_RB_ID, did not stay up; the current release keeps serving" >&2; journalctl -u "${p}" -n 30 --no-pager >&2 || true; systemctl stop "${p}" 2>/dev/null || true; exit 1; }; done`,...o.map((c)=>` ${c}`),` systemctl enable "${p}" 2>/dev/null || true`,` systemctl list-units --plain --no-legend --type=service "${l}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v "^${l}@\${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 ${n}/${l}.service ]; then`,...o.map((c)=>` ${c}`),` systemctl restart ${l}.service`,"else",...o.map((c)=>` ${c}`),"fi"]}function yn(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 We(e){return`${v(e)}/owner`}function Js(e,t){let r=We(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 $o(e,t){let r=v(e),n=qe(e,t.releaseId),o=Vs(e),s=Math.max(1,t.keepLogs??20),l=t.commit||"",p=t.branch||"";return[`mkdir -p ${r}/deploys`,`exec > >(tee -a ${n}) 2>&1`,`echo "[ts-cloud] deploy ${t.releaseId} commit=${l} branch=${p} 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}" "${l}" "$TS_CLOUD_ST" "$TS_CLOUD_RC" >> ${o}`,"}","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`]}
11
+ export{W,ki,Bs,A,Io,Fs,js,Wc,Kc,R,Tt,Ve,it,Po,Do,Ni,ko,gn,Et,No,wt,Jc,fn,xi,_i,xo,Oi,Vs,_o,$i,Ht,zs,Xc,Li,Hs,Gs,qs,Ws,Oo,hn,Ks,Qc,Yc,yn,Js,$o};
@@ -0,0 +1 @@
1
+ import{eu,el,tu,zo,Ho,Go,Zs}from"./chunk-20rfyk4x.js";import"./chunk-sacx9p6f.js";import"./chunk-8rkfwgb4.js";export{eu as MANAGEMENT_DASHBOARD_SITE,Zs as buildManagementDashboardArtifact,el as dashboardCredentialsFile,Ho as ensureManagementDashboard,Go as managementDashboardSiteNames,tu as resolveDashboardAuth,zo as resolveUiSource};
@@ -0,0 +1 @@
1
+ import{Zp,sn,io,se,em,Tc,Od,fs,tm,rm,nm,Ec,oo,hs,wc,an,br,im,bi,om,Ac,$d,Ld,ys,Rc,Ic,Sr,so,vr,Pc,bs,Si,Md,ao,Dc,kc,co,Ud,Nc,xc,_c,Oc,Ss,Bd,Fd,sm,jd,$c,lo,Vd,zd,vs,jt,Cs,Ts,Es,Lc,Hd,Mc,ws,am,yt,cm,Uc,Vt,Bc,lm,Fc,Gd,dm,ee,qd,As,um,uo,vi,Ci,Rs,Wd,Kd,pm,Is,Ps}from"./chunk-462swbg5.js";import"./chunk-ssnvdxh4.js";import"./chunk-sacx9p6f.js";import"./chunk-8rkfwgb4.js";export{vs as AnomalyConfigStore,Wd as AwsSpendTransport,Kd as ComputeSpendTransport,ys as CounterTracker,Ac as DEFAULT_METER_MAPPINGS,Ec as DEFAULT_PRICE_BOOK,so as DEFAULT_THRESHOLDS,jt as DETECTABLE_SIGNALS,io as ENFORCEMENT_ACTIONS,co as ENFORCEMENT_DESCRIPTIONS,se as ENFORCEMENT_SEVERITY,Hd as FOCUS_VERSION,sn as METERS,Zp as METER_KEYS,em as MICRO_CENTS,Md as MIN_PROJECTION_CONFIDENCE,Gd as RecordingSpendTransport,Vd as SENSITIVITY_THRESHOLDS,Ci as SPEND_CYCLE_SECONDS,Uc as SPEND_GATE_SETTING,um as SPEND_LEASE_SETTING,Ts as SignalSource,Bc as SpendCapError,Vt as SpendGate,uo as SpendLoopLease,As as SpendNotificationRouter,vi as SpendRunner,yt as SpendService,vr as SpendStore,dm as URGENT_SPEND_EVENTS,Ud as USER_VISIBLE_ACTIONS,Ic as aggregateDeltas,lo as anomalyOptionsForSignal,lm as assertSpendAllows,br as budgetWindow,pm as compositeSpendTransport,Fc as createEnforcementHandlers,jd as detectAnomalies,$c as detectLatestAnomaly,Dc as evaluateBudget,sm as ewma,$d as findMapping,Od as findPriceEntry,ee as formatCents,Si as formatTimeToExhaustion,ao as governingLimitCents,Is as handleSpendRequest,bi as hourBucket,om as hourBucketsBetween,Oc as isOperationAllowed,oo as isValidTimeZone,Lc as lookbackHoursForSignal,Ss as median,Bd as medianAbsoluteDeviation,kc as mergeDecisions,nm as mergePriceBooks,Rc as meterTelemetry,Es as optionsForSignal,bs as percentOfLimit,Nc as planEnforcement,im as previousBudgetWindow,fs as priceUsage,tm as priceUsageLines,Pc as projectSpend,Fd as robustZScore,rm as roundCents,zd as routeMatches,xc as runEnforcement,Sr as scopeKey,Cs as signalDefinition,qd as spendNotificationText,Ps as spendOpenApiPaths,Rs as startSpendLoop,am as streamFocusJsonl,_c as strongestActiveAction,Tc as tieredMicroCents,ws as toFocusJsonl,Mc as toFocusRecords,Ld as usageDeltaKey,an as utcInstantOfLocal,cm as zeroFill,wc as zoneOffsetMs,hs as zonedParts};
@@ -0,0 +1 @@
1
+ import{v}from"./chunk-yf2drw7r.js";import"./chunk-btrxye8p.js";export{v as CloudFormationClient};
@@ -1,2 +1,2 @@
1
- import{p}from"./chunk-540wkkhs.js";import{L}from"./chunk-gbbcp2bw.js";class v{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new p(void 0,{profile:t})}async createStack(e){let t={Action:"CreateStack",StackName:e.stackName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;else throw Error("Either templateBody or templateUrl must be provided");if(e.parameters)e.parameters.forEach((a,r)=>{t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.roleArn)t.RoleARN=e.roleArn;if(e.tags)e.tags.forEach((a,r)=>{t[`Tags.member.${r+1}.Key`]=a.Key,t[`Tags.member.${r+1}.Value`]=a.Value});if(e.timeoutInMinutes)t.TimeoutInMinutes=e.timeoutInMinutes;if(e.onFailure)t.OnFailure=e.onFailure;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackId:s.StackId||s.CreateStackResult?.StackId}}async updateStack(e){let t={Action:"UpdateStack",StackName:e.stackName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;if(e.parameters)e.parameters.forEach((a,r)=>{if(t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,a.UsePreviousValue)t[`Parameters.member.${r+1}.UsePreviousValue`]="true";else t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.roleArn)t.RoleARN=e.roleArn;if(e.tags)e.tags.forEach((a,r)=>{t[`Tags.member.${r+1}.Key`]=a.Key,t[`Tags.member.${r+1}.Value`]=a.Value});let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackId:s.StackId||s.UpdateStackResult?.StackId}}async deleteStack(e,t,s){let a={Action:"DeleteStack",StackName:e,Version:"2010-05-15"};if(t)a.RoleARN=t;if(s&&s.length>0)s.forEach((r,m)=>{a[`RetainResources.member.${m+1}`]=r});await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(a).toString()})}async describeStacks(e={}){let t={Action:"DescribeStacks",Version:"2010-05-15"};if(e.stackName)t.StackName=e.stackName;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{Stacks:this.parseStacksResponse(s)}}async describeStackEvents(e){let t={Action:"DescribeStackEvents",StackName:e,Version:"2010-05-15"},s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackEvents:this.parseStackEvents(s)}}async listStackResources(e){let t={Action:"ListStackResources",StackName:e,Version:"2010-05-15"},a=(await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}))?.ListStackResourcesResult?.StackResourceSummaries?.member,r=[];if(a)r=Array.isArray(a)?a:[a];return{StackResourceSummaries:r}}async waitForStack(e,t){let s={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},a=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],r=s[t],m=360,i=0;while(i<360)try{let c=await this.describeStacks({stackName:e});if(c.Stacks.length===0){if(t==="stack-delete-complete")return;if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Stack not visible yet`);await new Promise((o)=>setTimeout(o,2000)),i++;continue}let n=c.Stacks[0];if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Status = ${n.StackStatus}${n.StackStatusReason?` (${n.StackStatusReason})`:""}`);if(r.includes(n.StackStatus))return;if((t==="stack-create-complete"||t==="stack-update-complete")&&(n.StackStatus==="DELETE_IN_PROGRESS"||n.StackStatus==="DELETE_COMPLETE")){console.log("[waitForStack] Stack is being deleted (creation/update failed)");let o="";try{let u=await this.describeStackEvents(e);console.log("[waitForStack] Stack events (most recent first):");for(let l of u.StackEvents.slice(0,15))if(l.ResourceStatus.includes("FAILED")||l.ResourceStatusReason){if(console.log(` ${l.LogicalResourceId}: ${l.ResourceStatus} - ${l.ResourceStatusReason||"No reason provided"}`),l.ResourceStatus.includes("FAILED")&&l.ResourceStatusReason&&!o)o=l.ResourceStatusReason}}catch{}let S=o||n.StackStatusReason||"Check CloudFormation console for details.";throw Error(`Stack creation/update failed - stack is being deleted. Reason: ${S}`)}if(n.StackStatus==="DELETE_FAILED"&&t==="stack-delete-complete"){let o=Error("Stack deletion failed - may have resources that need to be retained");throw o.code="DELETE_FAILED",o.stackStatus=n.StackStatus,o.statusReason=n.StackStatusReason,o}if(a.includes(n.StackStatus))throw Error(`Stack reached failure status: ${n.StackStatus}`);await new Promise((o)=>setTimeout(o,5000)),i++}catch(c){if(t==="stack-delete-complete"&&c.message?.includes("does not exist"))return;if(t==="stack-create-complete"&&c.message?.includes("does not exist")){if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Stack does not exist (error), retrying...`);await new Promise((n)=>setTimeout(n,2000)),i++;continue}throw console.log(`[waitForStack] Unexpected error: ${c.message}`),c}throw console.log(`[waitForStack] Timeout after ${i} attempts`),Error(`Timeout waiting for stack to reach ${t}`)}async validateTemplate(e){let t={Action:"ValidateTemplate",TemplateBody:e,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()})}async listStacks(e){let t={Action:"ListStacks",Version:"2010-05-15"};if(e)e.forEach((c,n)=>{t[`StackStatusFilter.member.${n+1}`]=c});let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}),a=s.ListStacksResponse||s,r=a.ListStacksResult||a,m=r.StackSummaries?.member||r.StackSummaries||[];return{StackSummaries:(Array.isArray(m)?m:m?[m]:[]).map((c)=>({StackId:c.StackId||"",StackName:c.StackName||"",TemplateDescription:c.TemplateDescription,CreationTime:c.CreationTime||"",LastUpdatedTime:c.LastUpdatedTime,DeletionTime:c.DeletionTime,StackStatus:c.StackStatus||""}))}}async createChangeSet(e){let t={Action:"CreateChangeSet",StackName:e.stackName,ChangeSetName:e.changeSetName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;if(e.parameters)e.parameters.forEach((r,m)=>{t[`Parameters.member.${m+1}.ParameterKey`]=r.ParameterKey,t[`Parameters.member.${m+1}.ParameterValue`]=r.ParameterValue});if(e.capabilities)e.capabilities.forEach((r,m)=>{t[`Capabilities.member.${m+1}`]=r});if(e.changeSetType)t.ChangeSetType=e.changeSetType;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}),a=L(s,"CreateChangeSet");return{Id:a?.Id,StackId:a?.StackId}}async describeChangeSet(e,t){let s={Action:"DescribeChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async executeChangeSet(e,t){let s={Action:"ExecuteChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async deleteChangeSet(e,t){let s={Action:"DeleteChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async getStackOutputs(e){let t=await this.describeStacks({stackName:e});if(!t.Stacks||t.Stacks.length===0)throw Error(`Stack ${e} not found`);let s=t.Stacks[0],a={};if(s.Outputs)for(let r of s.Outputs)a[r.OutputKey]=r.OutputValue;return a}async getTemplate(e){let t={Action:"GetTemplate",StackName:e,Version:"2010-05-15"},s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{TemplateBody:s?.GetTemplateResult?.TemplateBody||s?.TemplateBody||""}}parseStacksResponse(e){let t=[],s=e?.DescribeStacksResult?.Stacks?.member||e?.Stacks?.member||e?.Stacks||e;if(s&&!Array.isArray(s))s=[s];if(Array.isArray(s)){for(let a of s)if(a.StackId||a.StackName){let r;if(a.Outputs?.member)r=(Array.isArray(a.Outputs.member)?a.Outputs.member:[a.Outputs.member]).map((i)=>({OutputKey:i.OutputKey,OutputValue:i.OutputValue,Description:i.Description,ExportName:i.ExportName}));t.push({StackId:a.StackId,StackName:a.StackName,StackStatus:a.StackStatus,CreationTime:a.CreationTime,LastUpdatedTime:a.LastUpdatedTime,StackStatusReason:a.StackStatusReason,Outputs:r})}}else if(e.StackId)t.push({StackId:e.StackId,StackName:e.StackName,StackStatus:e.StackStatus,CreationTime:e.CreationTime,LastUpdatedTime:e.LastUpdatedTime});return t}parseStackEvents(e){let t=[],s=e?.DescribeStackEventsResult?.StackEvents?.member||e?.StackEvents?.member||e?.StackEvents||[];if(s&&!Array.isArray(s))s=[s];for(let a of s)if(a.LogicalResourceId)t.push({Timestamp:a.Timestamp,ResourceType:a.ResourceType,LogicalResourceId:a.LogicalResourceId,ResourceStatus:a.ResourceStatus,ResourceStatusReason:a.ResourceStatusReason});return t}async waitForStackWithProgress(e,t,s){let a={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},r=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],m=a[t],i=360,c=0,n=new Set;while(c<360)try{if(s)try{let l=[...(await this.describeStackEvents(e)).StackEvents||[]].reverse();for(let k of l){let d=`${k.LogicalResourceId}-${k.ResourceStatus}-${k.Timestamp}`;if(!n.has(d))n.add(d),s({resourceId:k.LogicalResourceId,resourceType:k.ResourceType,status:k.ResourceStatus,reason:k.ResourceStatusReason,timestamp:k.Timestamp})}}catch{}let o=await this.describeStacks({stackName:e});if(o.Stacks.length===0){if(t==="stack-delete-complete")return;await new Promise((u)=>setTimeout(u,2000)),c++;continue}let S=o.Stacks[0];if(m.includes(S.StackStatus))return;if(S.StackStatus==="DELETE_FAILED"&&t==="stack-delete-complete"){let u=Error("Stack deletion failed - may have resources that need to be retained");throw u.code="DELETE_FAILED",u.stackStatus=S.StackStatus,u.statusReason=S.StackStatusReason,u}if(r.includes(S.StackStatus))throw Error(`Stack reached failure status: ${S.StackStatus}`);await new Promise((u)=>setTimeout(u,3000)),c++}catch(o){if(t==="stack-delete-complete"&&o.message?.includes("does not exist"))return;if(t==="stack-create-complete"&&o.message?.includes("does not exist")){await new Promise((S)=>setTimeout(S,2000)),c++;continue}throw o}throw Error(`Timeout waiting for stack to reach ${t}`)}async waitForStackComplete(e,t=120,s=5000){let a=["CREATE_COMPLETE","UPDATE_COMPLETE","DELETE_COMPLETE"],r=["CREATE_FAILED","UPDATE_FAILED","DELETE_FAILED","ROLLBACK_COMPLETE","ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED"];for(let m=0;m<t;m++)try{let i=await this.describeStacks({stackName:e});if(i.Stacks.length===0)return{success:!0,status:"DELETE_COMPLETE"};let c=i.Stacks[0],n=c.StackStatus;if(a.includes(n))return{success:!0,status:n};if(r.includes(n))return{success:!1,status:n,reason:c.StackStatusReason};await new Promise((o)=>setTimeout(o,s))}catch(i){if(i.message?.includes("does not exist"))return{success:!0,status:"DELETE_COMPLETE"};throw i}return{success:!1,status:"TIMEOUT",reason:"Timeout waiting for stack operation"}}}
1
+ import{p}from"./chunk-btrxye8p.js";import{L}from"./chunk-bkx2kapc.js";class v{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new p(void 0,{profile:t})}async createStack(e){let t={Action:"CreateStack",StackName:e.stackName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;else throw Error("Either templateBody or templateUrl must be provided");if(e.parameters)e.parameters.forEach((a,r)=>{t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.roleArn)t.RoleARN=e.roleArn;if(e.tags)e.tags.forEach((a,r)=>{t[`Tags.member.${r+1}.Key`]=a.Key,t[`Tags.member.${r+1}.Value`]=a.Value});if(e.timeoutInMinutes)t.TimeoutInMinutes=e.timeoutInMinutes;if(e.onFailure)t.OnFailure=e.onFailure;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackId:s.StackId||s.CreateStackResult?.StackId}}async updateStack(e){let t={Action:"UpdateStack",StackName:e.stackName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;if(e.parameters)e.parameters.forEach((a,r)=>{if(t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,a.UsePreviousValue)t[`Parameters.member.${r+1}.UsePreviousValue`]="true";else t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.roleArn)t.RoleARN=e.roleArn;if(e.tags)e.tags.forEach((a,r)=>{t[`Tags.member.${r+1}.Key`]=a.Key,t[`Tags.member.${r+1}.Value`]=a.Value});let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackId:s.StackId||s.UpdateStackResult?.StackId}}async deleteStack(e,t,s){let a={Action:"DeleteStack",StackName:e,Version:"2010-05-15"};if(t)a.RoleARN=t;if(s&&s.length>0)s.forEach((r,m)=>{a[`RetainResources.member.${m+1}`]=r});await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(a).toString()})}async describeStacks(e={}){let t={Action:"DescribeStacks",Version:"2010-05-15"};if(e.stackName)t.StackName=e.stackName;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{Stacks:this.parseStacksResponse(s)}}async describeStackEvents(e){let t={Action:"DescribeStackEvents",StackName:e,Version:"2010-05-15"},s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackEvents:this.parseStackEvents(s)}}async listStackResources(e){let t={Action:"ListStackResources",StackName:e,Version:"2010-05-15"},a=(await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}))?.ListStackResourcesResult?.StackResourceSummaries?.member,r=[];if(a)r=Array.isArray(a)?a:[a];return{StackResourceSummaries:r}}async waitForStack(e,t){let s={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},a=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],r=s[t],m=360,i=0;while(i<360)try{let c=await this.describeStacks({stackName:e});if(c.Stacks.length===0){if(t==="stack-delete-complete")return;if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Stack not visible yet`);await new Promise((o)=>setTimeout(o,2000)),i++;continue}let n=c.Stacks[0];if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Status = ${n.StackStatus}${n.StackStatusReason?` (${n.StackStatusReason})`:""}`);if(r.includes(n.StackStatus))return;if((t==="stack-create-complete"||t==="stack-update-complete")&&(n.StackStatus==="DELETE_IN_PROGRESS"||n.StackStatus==="DELETE_COMPLETE")){console.log("[waitForStack] Stack is being deleted (creation/update failed)");let o="";try{let u=await this.describeStackEvents(e);console.log("[waitForStack] Stack events (most recent first):");for(let l of u.StackEvents.slice(0,15))if(l.ResourceStatus.includes("FAILED")||l.ResourceStatusReason){if(console.log(` ${l.LogicalResourceId}: ${l.ResourceStatus} - ${l.ResourceStatusReason||"No reason provided"}`),l.ResourceStatus.includes("FAILED")&&l.ResourceStatusReason&&!o)o=l.ResourceStatusReason}}catch{}let S=o||n.StackStatusReason||"Check CloudFormation console for details.";throw Error(`Stack creation/update failed - stack is being deleted. Reason: ${S}`)}if(n.StackStatus==="DELETE_FAILED"&&t==="stack-delete-complete"){let o=Error("Stack deletion failed - may have resources that need to be retained");throw o.code="DELETE_FAILED",o.stackStatus=n.StackStatus,o.statusReason=n.StackStatusReason,o}if(a.includes(n.StackStatus))throw Error(`Stack reached failure status: ${n.StackStatus}`);await new Promise((o)=>setTimeout(o,5000)),i++}catch(c){if(t==="stack-delete-complete"&&c.message?.includes("does not exist"))return;if(t==="stack-create-complete"&&c.message?.includes("does not exist")){if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Stack does not exist (error), retrying...`);await new Promise((n)=>setTimeout(n,2000)),i++;continue}throw console.log(`[waitForStack] Unexpected error: ${c.message}`),c}throw console.log(`[waitForStack] Timeout after ${i} attempts`),Error(`Timeout waiting for stack to reach ${t}`)}async validateTemplate(e){let t={Action:"ValidateTemplate",TemplateBody:e,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()})}async listStacks(e){let t={Action:"ListStacks",Version:"2010-05-15"};if(e)e.forEach((c,n)=>{t[`StackStatusFilter.member.${n+1}`]=c});let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}),a=s.ListStacksResponse||s,r=a.ListStacksResult||a,m=r.StackSummaries?.member||r.StackSummaries||[];return{StackSummaries:(Array.isArray(m)?m:m?[m]:[]).map((c)=>({StackId:c.StackId||"",StackName:c.StackName||"",TemplateDescription:c.TemplateDescription,CreationTime:c.CreationTime||"",LastUpdatedTime:c.LastUpdatedTime,DeletionTime:c.DeletionTime,StackStatus:c.StackStatus||""}))}}async createChangeSet(e){let t={Action:"CreateChangeSet",StackName:e.stackName,ChangeSetName:e.changeSetName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;if(e.parameters)e.parameters.forEach((r,m)=>{t[`Parameters.member.${m+1}.ParameterKey`]=r.ParameterKey,t[`Parameters.member.${m+1}.ParameterValue`]=r.ParameterValue});if(e.capabilities)e.capabilities.forEach((r,m)=>{t[`Capabilities.member.${m+1}`]=r});if(e.changeSetType)t.ChangeSetType=e.changeSetType;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}),a=L(s,"CreateChangeSet");return{Id:a?.Id,StackId:a?.StackId}}async describeChangeSet(e,t){let s={Action:"DescribeChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async executeChangeSet(e,t){let s={Action:"ExecuteChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async deleteChangeSet(e,t){let s={Action:"DeleteChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async getStackOutputs(e){let t=await this.describeStacks({stackName:e});if(!t.Stacks||t.Stacks.length===0)throw Error(`Stack ${e} not found`);let s=t.Stacks[0],a={};if(s.Outputs)for(let r of s.Outputs)a[r.OutputKey]=r.OutputValue;return a}async getTemplate(e){let t={Action:"GetTemplate",StackName:e,Version:"2010-05-15"},s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{TemplateBody:s?.GetTemplateResult?.TemplateBody||s?.TemplateBody||""}}parseStacksResponse(e){let t=[],s=e?.DescribeStacksResult?.Stacks?.member||e?.Stacks?.member||e?.Stacks||e;if(s&&!Array.isArray(s))s=[s];if(Array.isArray(s)){for(let a of s)if(a.StackId||a.StackName){let r;if(a.Outputs?.member)r=(Array.isArray(a.Outputs.member)?a.Outputs.member:[a.Outputs.member]).map((i)=>({OutputKey:i.OutputKey,OutputValue:i.OutputValue,Description:i.Description,ExportName:i.ExportName}));t.push({StackId:a.StackId,StackName:a.StackName,StackStatus:a.StackStatus,CreationTime:a.CreationTime,LastUpdatedTime:a.LastUpdatedTime,StackStatusReason:a.StackStatusReason,Outputs:r})}}else if(e.StackId)t.push({StackId:e.StackId,StackName:e.StackName,StackStatus:e.StackStatus,CreationTime:e.CreationTime,LastUpdatedTime:e.LastUpdatedTime});return t}parseStackEvents(e){let t=[],s=e?.DescribeStackEventsResult?.StackEvents?.member||e?.StackEvents?.member||e?.StackEvents||[];if(s&&!Array.isArray(s))s=[s];for(let a of s)if(a.LogicalResourceId)t.push({Timestamp:a.Timestamp,ResourceType:a.ResourceType,LogicalResourceId:a.LogicalResourceId,ResourceStatus:a.ResourceStatus,ResourceStatusReason:a.ResourceStatusReason});return t}async waitForStackWithProgress(e,t,s){let a={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},r=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],m=a[t],i=360,c=0,n=new Set;while(c<360)try{if(s)try{let l=[...(await this.describeStackEvents(e)).StackEvents||[]].reverse();for(let k of l){let d=`${k.LogicalResourceId}-${k.ResourceStatus}-${k.Timestamp}`;if(!n.has(d))n.add(d),s({resourceId:k.LogicalResourceId,resourceType:k.ResourceType,status:k.ResourceStatus,reason:k.ResourceStatusReason,timestamp:k.Timestamp})}}catch{}let o=await this.describeStacks({stackName:e});if(o.Stacks.length===0){if(t==="stack-delete-complete")return;await new Promise((u)=>setTimeout(u,2000)),c++;continue}let S=o.Stacks[0];if(m.includes(S.StackStatus))return;if(S.StackStatus==="DELETE_FAILED"&&t==="stack-delete-complete"){let u=Error("Stack deletion failed - may have resources that need to be retained");throw u.code="DELETE_FAILED",u.stackStatus=S.StackStatus,u.statusReason=S.StackStatusReason,u}if(r.includes(S.StackStatus))throw Error(`Stack reached failure status: ${S.StackStatus}`);await new Promise((u)=>setTimeout(u,3000)),c++}catch(o){if(t==="stack-delete-complete"&&o.message?.includes("does not exist"))return;if(t==="stack-create-complete"&&o.message?.includes("does not exist")){await new Promise((S)=>setTimeout(S,2000)),c++;continue}throw o}throw Error(`Timeout waiting for stack to reach ${t}`)}async waitForStackComplete(e,t=120,s=5000){let a=["CREATE_COMPLETE","UPDATE_COMPLETE","DELETE_COMPLETE"],r=["CREATE_FAILED","UPDATE_FAILED","DELETE_FAILED","ROLLBACK_COMPLETE","ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED"];for(let m=0;m<t;m++)try{let i=await this.describeStacks({stackName:e});if(i.Stacks.length===0)return{success:!0,status:"DELETE_COMPLETE"};let c=i.Stacks[0],n=c.StackStatus;if(a.includes(n))return{success:!0,status:n};if(r.includes(n))return{success:!1,status:n,reason:c.StackStatusReason};await new Promise((o)=>setTimeout(o,s))}catch(i){if(i.message?.includes("does not exist"))return{success:!0,status:"DELETE_COMPLETE"};throw i}return{success:!1,status:"TIMEOUT",reason:"Timeout waiting for stack operation"}}}
2
2
  export{v};
@@ -1,2 +1,2 @@
1
- import{p}from"./chunk-540wkkhs.js";class At{client;region;constructor(e="us-east-1",r){this.region=e,this.client=new p(void 0,{profile:r})}async createRepository(e){let r={repositoryName:e.repositoryName};if(e.imageTagMutability)r.imageTagMutability=e.imageTagMutability;if(e.imageScanningConfiguration)r.imageScanningConfiguration=e.imageScanningConfiguration;if(e.encryptionConfiguration)r.encryptionConfiguration=e.encryptionConfiguration;if(e.tags&&e.tags.length>0)r.tags=e.tags;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.CreateRepository","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{repository:t.repository?this.parseRepository(t.repository):void 0}}async describeRepositories(e){let r={};if(e?.repositoryNames&&e.repositoryNames.length>0)r.repositoryNames=e.repositoryNames;if(e?.registryId)r.registryId=e.registryId;if(e?.maxResults)r.maxResults=e.maxResults;if(e?.nextToken)r.nextToken=e.nextToken;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.DescribeRepositories","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{repositories:t.repositories?.map((i)=>this.parseRepository(i)),nextToken:t.nextToken}}async getAuthorizationToken(e){let r={};if(e&&e.length>0)r.registryIds=e;return{authorizationData:(await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.GetAuthorizationToken","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)})).authorizationData?.map((i)=>({authorizationToken:i.authorizationToken,expiresAt:i.expiresAt,proxyEndpoint:i.proxyEndpoint}))}}async deleteRepository(e){let r={repositoryName:e.repositoryName};if(e.registryId)r.registryId=e.registryId;if(e.force!==void 0)r.force=e.force;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.DeleteRepository","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{repository:t.repository?this.parseRepository(t.repository):void 0}}async describeImages(e){let r={repositoryName:e.repositoryName};if(e.registryId)r.registryId=e.registryId;if(e.imageIds&&e.imageIds.length>0)r.imageIds=e.imageIds;if(e.filter)r.filter=e.filter;if(e.maxResults)r.maxResults=e.maxResults;if(e.nextToken)r.nextToken=e.nextToken;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.DescribeImages","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{imageDetails:t.imageDetails?.map((i)=>this.parseImageDetail(i)),nextToken:t.nextToken}}async batchDeleteImage(e){let r={repositoryName:e.repositoryName,imageIds:e.imageIds};if(e.registryId)r.registryId=e.registryId;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.BatchDeleteImage","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{imageIds:t.imageIds,failures:t.failures}}async putLifecyclePolicy(e){let r={repositoryName:e.repositoryName,lifecyclePolicyText:e.lifecyclePolicyText};if(e.registryId)r.registryId=e.registryId;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.PutLifecyclePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{registryId:t.registryId,repositoryName:t.repositoryName,lifecyclePolicyText:t.lifecyclePolicyText}}async getLifecyclePolicy(e){let r={repositoryName:e.repositoryName};if(e.registryId)r.registryId=e.registryId;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.GetLifecyclePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{registryId:t.registryId,repositoryName:t.repositoryName,lifecyclePolicyText:t.lifecyclePolicyText,lastEvaluatedAt:t.lastEvaluatedAt}}async setRepositoryPolicy(e){let r={repositoryName:e.repositoryName,policyText:e.policyText};if(e.registryId)r.registryId=e.registryId;if(e.force!==void 0)r.force=e.force;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.SetRepositoryPolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{registryId:t.registryId,repositoryName:t.repositoryName,policyText:t.policyText}}async getRepositoryPolicy(e){let r={repositoryName:e.repositoryName};if(e.registryId)r.registryId=e.registryId;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.GetRepositoryPolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{registryId:t.registryId,repositoryName:t.repositoryName,policyText:t.policyText}}async tagResource(e){let r={resourceArn:e.resourceArn,tags:e.tags};await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.TagResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)})}async listTagsForResource(e){let r={resourceArn:e};return{tags:(await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.ListTagsForResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)})).tags}}createLifecyclePolicyText(e){return JSON.stringify({rules:e.map((r)=>({rulePriority:r.rulePriority,description:r.description,selection:r.selection,action:r.action}))})}async getDockerLoginCommand(){let e=await this.getAuthorizationToken();if(!e.authorizationData?.[0])throw Error("Failed to get authorization token");let r=e.authorizationData[0],t=r.authorizationToken||"",i=r.proxyEndpoint||"";return`echo "${Buffer.from(t,"base64").toString("utf8").split(":")[1]}" | docker login --username AWS --password-stdin ${i}`}getRegistryUri(e){return`${e}.dkr.ecr.${this.region}.amazonaws.com`}parseRepository(e){return{repositoryArn:e.repositoryArn,registryId:e.registryId,repositoryName:e.repositoryName,repositoryUri:e.repositoryUri,createdAt:e.createdAt,imageTagMutability:e.imageTagMutability,imageScanningConfiguration:e.imageScanningConfiguration,encryptionConfiguration:e.encryptionConfiguration}}parseImageDetail(e){return{registryId:e.registryId,repositoryName:e.repositoryName,imageDigest:e.imageDigest,imageTags:e.imageTags,imageSizeInBytes:e.imageSizeInBytes,imagePushedAt:e.imagePushedAt,imageScanStatus:e.imageScanStatus,imageScanFindingsSummary:e.imageScanFindingsSummary}}}
1
+ import{p}from"./chunk-btrxye8p.js";class At{client;region;constructor(e="us-east-1",r){this.region=e,this.client=new p(void 0,{profile:r})}async createRepository(e){let r={repositoryName:e.repositoryName};if(e.imageTagMutability)r.imageTagMutability=e.imageTagMutability;if(e.imageScanningConfiguration)r.imageScanningConfiguration=e.imageScanningConfiguration;if(e.encryptionConfiguration)r.encryptionConfiguration=e.encryptionConfiguration;if(e.tags&&e.tags.length>0)r.tags=e.tags;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.CreateRepository","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{repository:t.repository?this.parseRepository(t.repository):void 0}}async describeRepositories(e){let r={};if(e?.repositoryNames&&e.repositoryNames.length>0)r.repositoryNames=e.repositoryNames;if(e?.registryId)r.registryId=e.registryId;if(e?.maxResults)r.maxResults=e.maxResults;if(e?.nextToken)r.nextToken=e.nextToken;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.DescribeRepositories","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{repositories:t.repositories?.map((i)=>this.parseRepository(i)),nextToken:t.nextToken}}async getAuthorizationToken(e){let r={};if(e&&e.length>0)r.registryIds=e;return{authorizationData:(await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.GetAuthorizationToken","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)})).authorizationData?.map((i)=>({authorizationToken:i.authorizationToken,expiresAt:i.expiresAt,proxyEndpoint:i.proxyEndpoint}))}}async deleteRepository(e){let r={repositoryName:e.repositoryName};if(e.registryId)r.registryId=e.registryId;if(e.force!==void 0)r.force=e.force;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.DeleteRepository","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{repository:t.repository?this.parseRepository(t.repository):void 0}}async describeImages(e){let r={repositoryName:e.repositoryName};if(e.registryId)r.registryId=e.registryId;if(e.imageIds&&e.imageIds.length>0)r.imageIds=e.imageIds;if(e.filter)r.filter=e.filter;if(e.maxResults)r.maxResults=e.maxResults;if(e.nextToken)r.nextToken=e.nextToken;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.DescribeImages","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{imageDetails:t.imageDetails?.map((i)=>this.parseImageDetail(i)),nextToken:t.nextToken}}async batchDeleteImage(e){let r={repositoryName:e.repositoryName,imageIds:e.imageIds};if(e.registryId)r.registryId=e.registryId;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.BatchDeleteImage","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{imageIds:t.imageIds,failures:t.failures}}async putLifecyclePolicy(e){let r={repositoryName:e.repositoryName,lifecyclePolicyText:e.lifecyclePolicyText};if(e.registryId)r.registryId=e.registryId;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.PutLifecyclePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{registryId:t.registryId,repositoryName:t.repositoryName,lifecyclePolicyText:t.lifecyclePolicyText}}async getLifecyclePolicy(e){let r={repositoryName:e.repositoryName};if(e.registryId)r.registryId=e.registryId;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.GetLifecyclePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{registryId:t.registryId,repositoryName:t.repositoryName,lifecyclePolicyText:t.lifecyclePolicyText,lastEvaluatedAt:t.lastEvaluatedAt}}async setRepositoryPolicy(e){let r={repositoryName:e.repositoryName,policyText:e.policyText};if(e.registryId)r.registryId=e.registryId;if(e.force!==void 0)r.force=e.force;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.SetRepositoryPolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{registryId:t.registryId,repositoryName:t.repositoryName,policyText:t.policyText}}async getRepositoryPolicy(e){let r={repositoryName:e.repositoryName};if(e.registryId)r.registryId=e.registryId;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.GetRepositoryPolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{registryId:t.registryId,repositoryName:t.repositoryName,policyText:t.policyText}}async tagResource(e){let r={resourceArn:e.resourceArn,tags:e.tags};await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.TagResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)})}async listTagsForResource(e){let r={resourceArn:e};return{tags:(await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.ListTagsForResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)})).tags}}createLifecyclePolicyText(e){return JSON.stringify({rules:e.map((r)=>({rulePriority:r.rulePriority,description:r.description,selection:r.selection,action:r.action}))})}async getDockerLoginCommand(){let e=await this.getAuthorizationToken();if(!e.authorizationData?.[0])throw Error("Failed to get authorization token");let r=e.authorizationData[0],t=r.authorizationToken||"",i=r.proxyEndpoint||"";return`echo "${Buffer.from(t,"base64").toString("utf8").split(":")[1]}" | docker login --username AWS --password-stdin ${i}`}getRegistryUri(e){return`${e}.dkr.ecr.${this.region}.amazonaws.com`}parseRepository(e){return{repositoryArn:e.repositoryArn,registryId:e.registryId,repositoryName:e.repositoryName,repositoryUri:e.repositoryUri,createdAt:e.createdAt,imageTagMutability:e.imageTagMutability,imageScanningConfiguration:e.imageScanningConfiguration,encryptionConfiguration:e.encryptionConfiguration}}parseImageDetail(e){return{registryId:e.registryId,repositoryName:e.repositoryName,imageDigest:e.imageDigest,imageTags:e.imageTags,imageSizeInBytes:e.imageSizeInBytes,imagePushedAt:e.imagePushedAt,imageScanStatus:e.imageScanStatus,imageScanFindingsSummary:e.imageScanFindingsSummary}}}
2
2
  export{At};
@@ -1,2 +1,2 @@
1
- import{p,k}from"./chunk-540wkkhs.js";import{x}from"./chunk-gbbcp2bw.js";class fe{client;region;constructor(e="us-east-1"){this.region=e,this.client=new p}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,u)=>{r[`Filters.Filter.${o+1}.Values.Value.${u+1}`]=c})});let t=new URLSearchParams(k(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,u)=>{r[`Filters.Filter.${o+1}.Values.Value.${u+1}`]=c})});let t=new URLSearchParams(k(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(k(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(k(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(k(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(k(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(k(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(k(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(k(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(k(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(k(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(k(r)).toString()}),n=t.DescribeDBClusterSnapshotsResult||t;return{DBClusterSnapshots:x(n.DBClusterSnapshots?.DBClusterSnapshot)}}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(k({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(k(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(k(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(k(r)).toString()});return{DBCluster:(t.RestoreDBClusterFromSnapshotResult||t).DBCluster}}async startDBInstance(e){let t=new URLSearchParams(k({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(k(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(k(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(k(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(k({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(k(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`)}}
1
+ import{p,k}from"./chunk-btrxye8p.js";import{x}from"./chunk-bkx2kapc.js";class fe{client;region;constructor(e="us-east-1"){this.region=e,this.client=new p}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,u)=>{r[`Filters.Filter.${o+1}.Values.Value.${u+1}`]=c})});let t=new URLSearchParams(k(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,u)=>{r[`Filters.Filter.${o+1}.Values.Value.${u+1}`]=c})});let t=new URLSearchParams(k(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(k(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(k(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(k(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(k(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(k(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(k(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(k(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(k(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(k(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(k(r)).toString()}),n=t.DescribeDBClusterSnapshotsResult||t;return{DBClusterSnapshots:x(n.DBClusterSnapshots?.DBClusterSnapshot)}}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(k({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(k(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(k(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(k(r)).toString()});return{DBCluster:(t.RestoreDBClusterFromSnapshotResult||t).DBCluster}}async startDBInstance(e){let t=new URLSearchParams(k({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(k(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(k(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(k(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(k({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(k(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
2
  export{fe};
@@ -0,0 +1 @@
1
+ import{Jp,Xp,Qp,Yp}from"./chunk-cxf9pmmw.js";import"./chunk-1wgyq50e.js";import"./chunk-btrxye8p.js";import"./chunk-sacx9p6f.js";import"./chunk-8rkfwgb4.js";export{Yp as deleteFailoverReplicaBuckets,Jp as ensureFailoverReplicaBuckets,Xp as grantFailoverReplicaAccess,Qp as seedFailoverReplicas};