@stacksjs/ts-cloud 0.11.7 → 0.12.0

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 (102) hide show
  1. package/dist/aws/index.js +1 -1
  2. package/dist/bin/{chunk-znnawt0k.js → chunk-71t1gmsq.js} +1 -1
  3. package/dist/bin/{chunk-4xhj37nj.js → chunk-8ewncfce.js} +1 -1
  4. package/dist/bin/{chunk-8khgprf6.js → chunk-9kf0np8j.js} +1 -1
  5. package/dist/bin/chunk-cxt74wsj.js +1 -0
  6. package/dist/bin/{chunk-j447p8t4.js → chunk-g6baf9c5.js} +84 -84
  7. package/dist/bin/{chunk-zsf6pccz.js → chunk-q5cmfpzt.js} +1 -1
  8. package/dist/bin/{chunk-r6b3pq31.js → chunk-rtecnmts.js} +1 -1
  9. package/dist/bin/{chunk-5nsqz5n3.js → chunk-rv18092e.js} +1 -1
  10. package/dist/bin/{chunk-yw6f160x.js → chunk-ta7sh0cc.js} +1 -1
  11. package/dist/bin/{chunk-cbsys5v8.js → chunk-tfbs8k8v.js} +1 -1
  12. package/dist/bin/{chunk-g0fm1xcs.js → chunk-xkfrqqcs.js} +1 -1
  13. package/dist/bin/cli.js +99 -93
  14. package/dist/bin/dashboard-server.js +1 -1
  15. package/dist/chunk-13qjvbqh.js +2 -0
  16. package/dist/{chunk-nk7sav4r.js → chunk-152he7m3.js} +1 -1
  17. package/dist/{chunk-dr4pj8hp.js → chunk-3mgj3hrh.js} +1 -1
  18. package/dist/chunk-6kpbveb8.js +5 -0
  19. package/dist/{chunk-aw0cgv5w.js → chunk-86ss83s2.js} +1 -1
  20. package/dist/chunk-a84gmpyh.js +1 -0
  21. package/dist/{chunk-ywjkyg8p.js → chunk-b087qsyf.js} +99 -99
  22. package/dist/{chunk-zam6ecam.js → chunk-h42zck7h.js} +2 -2
  23. package/dist/{chunk-zz52xje8.js → chunk-jm5mg890.js} +1 -1
  24. package/dist/{chunk-kasdm9tx.js → chunk-m8fs0233.js} +1 -1
  25. package/dist/chunk-nms5q44e.js +1 -0
  26. package/dist/{chunk-aw0spg20.js → chunk-nzqxdkch.js} +2 -2
  27. package/dist/{chunk-rd38qdnf.js → chunk-qm32ytbr.js} +1 -1
  28. package/dist/{chunk-q0rc1ax9.js → chunk-t0xgmhd6.js} +1 -1
  29. package/dist/{chunk-q9q6cmt0.js → chunk-t3t9ymec.js} +1 -1
  30. package/dist/{chunk-5vt93kxx.js → chunk-y2v22hkv.js} +1 -1
  31. package/dist/deploy/index.js +1 -1
  32. package/dist/dns/index.js +1 -1
  33. package/dist/drivers/index.js +1 -1
  34. package/dist/index.d.ts +1 -0
  35. package/dist/index.js +52 -52
  36. package/dist/operations/drained-sites.d.ts +56 -0
  37. package/dist/operations/drained-sites.test.d.ts +1 -0
  38. package/dist/pages/cloudflare-pages.d.ts +227 -0
  39. package/dist/pages/cloudflare-pages.test.d.ts +1 -0
  40. package/dist/pages/index.d.ts +2 -0
  41. package/dist/protection/index.js +1 -1
  42. package/dist/push/index.js +1 -1
  43. package/dist/spend/index.js +1 -1
  44. package/dist/ui/404.html +1 -1
  45. package/dist/ui/accept-invitation.html +1 -1
  46. package/dist/ui/access-denied.html +1 -1
  47. package/dist/ui/account/automation.html +5 -5
  48. package/dist/ui/account/security.html +2 -2
  49. package/dist/ui/applications/compose.html +6 -6
  50. package/dist/ui/applications/new.html +2 -2
  51. package/dist/ui/data/backups.html +6 -6
  52. package/dist/ui/data/services.html +6 -6
  53. package/dist/ui/data/volumes.html +6 -6
  54. package/dist/ui/index.html +6 -6
  55. package/dist/ui/infrastructure/topology.html +5 -5
  56. package/dist/ui/integrations.html +1 -1
  57. package/dist/ui/operations/alerts.html +6 -6
  58. package/dist/ui/operations/configuration.html +6 -6
  59. package/dist/ui/operations/jobs.html +6 -6
  60. package/dist/ui/operations/maintenance.html +6 -6
  61. package/dist/ui/operations/observability.html +6 -6
  62. package/dist/ui/operations/previews.html +6 -6
  63. package/dist/ui/operations/queue.html +5 -5
  64. package/dist/ui/operations/regions.html +6 -6
  65. package/dist/ui/operations/releases.html +6 -6
  66. package/dist/ui/operations/spend.html +6 -6
  67. package/dist/ui/operations/workloads.html +6 -6
  68. package/dist/ui/security.html +2 -2
  69. package/dist/ui/server/actions.html +6 -6
  70. package/dist/ui/server/activity.html +2 -2
  71. package/dist/ui/server/capacity.html +6 -6
  72. package/dist/ui/server/database.html +6 -6
  73. package/dist/ui/server/deployments.html +6 -6
  74. package/dist/ui/server/diagnostics.html +2 -2
  75. package/dist/ui/server/firewall.html +6 -6
  76. package/dist/ui/server/fleet.html +6 -6
  77. package/dist/ui/server/logs.html +6 -6
  78. package/dist/ui/server/metrics.html +6 -6
  79. package/dist/ui/server/security.html +2 -2
  80. package/dist/ui/server/services.html +1 -1
  81. package/dist/ui/server/sites.html +6 -6
  82. package/dist/ui/server/ssh-keys.html +6 -6
  83. package/dist/ui/server/team.html +6 -6
  84. package/dist/ui/server/terminal.html +2 -2
  85. package/dist/ui/serverless/alarms.html +5 -5
  86. package/dist/ui/serverless/assets.html +1 -1
  87. package/dist/ui/serverless/cost.html +2 -2
  88. package/dist/ui/serverless/data.html +5 -5
  89. package/dist/ui/serverless/deployments.html +1 -1
  90. package/dist/ui/serverless/firewall.html +2 -2
  91. package/dist/ui/serverless/functions.html +6 -6
  92. package/dist/ui/serverless/logs.html +6 -6
  93. package/dist/ui/serverless/metrics.html +1 -1
  94. package/dist/ui/serverless/queues.html +6 -6
  95. package/dist/ui/serverless/secrets.html +6 -6
  96. package/dist/ui/serverless/traces.html +6 -6
  97. package/dist/ui/serverless.html +6 -6
  98. package/package.json +4 -3
  99. package/dist/bin/chunk-wkx799z2.js +0 -1
  100. package/dist/chunk-95e6aeqz.js +0 -1
  101. package/dist/chunk-p10xt3jb.js +0 -1
  102. package/dist/chunk-z2qqwy7e.js +0 -2
@@ -1,4 +1,4 @@
1
- import{sf as U}from"./chunk-by2bwzk6.js";import{Ef as Z,Jf as _,Nf as K,Rf as L,Sf as Y}from"./chunk-tz9myq9a.js";import{Tf as M}from"./chunk-y4xkj2f1.js";import{Xh as W}from"./chunk-wavjkdb8.js";import{Zh as B}from"./chunk-nk7sav4r.js";import{Ct as j}from"./chunk-z2qqwy7e.js";function J(t){let{bucketName:s,domain:l,aliases:e,certificateArn:m,defaultRootObject:i="index.html",errorDocument:r="404.html",passthroughUrls:a=!1,singlePageApp:d=!1,dynamicApp:b=!1,computeOriginDomain:k,computeOriginPort:R=3008,computeOriginId:P="app-compute",retainOnStackDelete:x=!1}=t,A=x?{DeletionPolicy:"Retain",UpdateReplacePolicy:"Retain"}:{},y=b&&!!k,T=y?["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"]:["GET","HEAD"],F=y?["GET","HEAD"]:["GET","HEAD"],N={},O={};N.S3Bucket={Type:"AWS::S3::Bucket",...A,Properties:{BucketName:s,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:i,ErrorDocument:r}}},O.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},O.BucketArn={Description:"S3 Bucket ARN",Value:{"Fn::GetAtt":["S3Bucket","Arn"]}},N.CloudFrontOAC={Type:"AWS::CloudFront::OriginAccessControl",...A,Properties:{OriginAccessControlConfig:{Name:`OAC-${s}`,Description:`OAC for ${s}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}};let D;if(a&&y)D="InstallRootRedirectFunction",N[D]={Type:"AWS::CloudFront::Function",Properties:{Name:{"Fn::Sub":"${AWS::StackName}-install-root-redirect"},AutoPublish:!0,FunctionConfig:{Comment:"Redirect curl pantry.dev | bash (GET /) to /install.sh on S3",Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) {
1
+ import{sf as U}from"./chunk-by2bwzk6.js";import{Ef as Z,Jf as _,Nf as K,Rf as L,Sf as Y}from"./chunk-tz9myq9a.js";import{Tf as M}from"./chunk-y4xkj2f1.js";import{Xh as W}from"./chunk-wavjkdb8.js";import{Zh as B}from"./chunk-152he7m3.js";import{Et as j}from"./chunk-13qjvbqh.js";function J(t){let{bucketName:s,domain:l,aliases:e,certificateArn:m,defaultRootObject:i="index.html",errorDocument:r="404.html",passthroughUrls:a=!1,singlePageApp:d=!1,dynamicApp:b=!1,computeOriginDomain:k,computeOriginPort:R=3008,computeOriginId:P="app-compute",retainOnStackDelete:x=!1}=t,A=x?{DeletionPolicy:"Retain",UpdateReplacePolicy:"Retain"}:{},y=b&&!!k,T=y?["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"]:["GET","HEAD"],F=y?["GET","HEAD"]:["GET","HEAD"],N={},O={};N.S3Bucket={Type:"AWS::S3::Bucket",...A,Properties:{BucketName:s,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:i,ErrorDocument:r}}},O.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},O.BucketArn={Description:"S3 Bucket ARN",Value:{"Fn::GetAtt":["S3Bucket","Arn"]}},N.CloudFrontOAC={Type:"AWS::CloudFront::OriginAccessControl",...A,Properties:{OriginAccessControlConfig:{Name:`OAC-${s}`,Description:`OAC for ${s}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}};let D;if(a&&y)D="InstallRootRedirectFunction",N[D]={Type:"AWS::CloudFront::Function",Properties:{Name:{"Fn::Sub":"${AWS::StackName}-install-root-redirect"},AutoPublish:!0,FunctionConfig:{Comment:"Redirect curl pantry.dev | bash (GET /) to /install.sh on S3",Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) {
2
2
  var request = event.request;
3
3
  if (request.uri === '/' || request.uri === '') {
4
4
  return {
@@ -42,7 +42,7 @@ import{sf as U}from"./chunk-by2bwzk6.js";import{Ef as Z,Jf as _,Nf as K,Rf as L,
42
42
  │ │
43
43
  │ Verification typically takes 1-2 business days. │
44
44
  │ After verification, re-run: bunx bunpress deploy │
45
- └─────────────────────────────────────────────────────────────────────────────┘`),{success:!1,stackId:O,stackName:i,bucket:y,message:"CloudFront account verification required. Please contact AWS Support."}}return{success:!1,stackId:O,stackName:i,bucket:y,message:`Stack deployment failed: ${o.message}`}}let u=(await r.describeStacks({stackName:i})).Stacks[0]?.Outputs||[],C=(o)=>u.find((n)=>n.OutputKey===o)?.OutputValue,f=C("DistributionDomain");if(f&&d)console.log(`Creating DNS records via ${d.name}...`),await q(d,e,f);else if(f&&!d)console.log("Skipping DNS record creation (DNS verification was skipped)");return{success:!0,stackId:O,stackName:i,bucket:C("BucketName")||y,distributionId:C("DistributionId"),distributionDomain:f,domain:e,certificateArn:b,message:"Static site infrastructure deployed successfully with external DNS"}}async function q(t,s,l){if(!t){console.log("Skipping DNS record creation (DNS verification was skipped)");return}if(s.split(".").length===2)if(t instanceof Z){console.log(`Creating Route53 alias record for apex domain ${s} -> ${l}`);let i=await t.createCloudFrontAlias({domain:s,name:s,cloudFrontDomainName:l});if(!i.success)console.warn(`Warning: Could not create Route53 alias record: ${i.message}`),console.warn("Please manually create an A-record alias in Route53:"),console.warn(` ${s} -> ${l}`);else console.log(`Created Route53 alias record: ${s} -> ${l}`);let r=`www.${s}`;console.log(`Creating Route53 alias record for ${r} -> ${l}`);let a=await t.createCloudFrontAlias({domain:s,name:r,cloudFrontDomainName:l});if(!a.success)console.warn(`Warning: Could not create www Route53 alias: ${a.message}`),console.warn("Please manually create an A-record alias in Route53:"),console.warn(` ${r} -> ${l}`);else console.log(`Created Route53 alias record: ${r} -> ${l}`)}else{try{let d=await t.listRecords(s,"A");if(d.success)for(let b of d.records){let k=b.name.replace(/\.$/,"");if(k===s||k==="")console.log(`Removing existing root A record (${b.content}) to make room for ALIAS...`),await t.deleteRecord(s,{name:s,type:"A",content:b.content})}}catch(d){console.log(`Note: Could not check for conflicting A records: ${d instanceof Error?d.message:d}`)}console.log(`Creating ALIAS record for apex domain ${s} -> ${l}`);let i=await t.upsertRecord(s,{name:s,type:"ALIAS",content:l,ttl:600});if(!i.success)console.warn(`Warning: Could not create ALIAS record: ${i.message}`),console.warn("Please manually create an ALIAS record in your DNS provider:"),console.warn(` ${s} -> ${l}`);else console.log(`Created ALIAS record: ${s} -> ${l}`);let r=`www.${s}`;console.log(`Creating CNAME record for ${r} -> ${l}`);let a=await t.upsertRecord(s,{name:r,type:"CNAME",content:l,ttl:600});if(!a.success)console.warn(`Warning: Could not create www DNS record: ${a.message}`),console.warn("Please manually create a CNAME record:"),console.warn(` ${r} -> ${l}`);else console.log(`Created CNAME record: ${r} -> ${l}`)}else{console.log(`Creating CNAME record for ${s} -> ${l}`);let i=await t.upsertRecord(s,{name:s,type:"CNAME",content:l,ttl:600});if(!i.success)console.warn(`Warning: Could not create DNS record: ${i.message}`),console.warn("Please manually create a CNAME record:"),console.warn(` ${s} -> ${l}`);else console.log(`Created CNAME record: ${s} -> ${l}`)}}async function le(t){let{sourceDir:s,cleanBucket:l=!1,onProgress:e,...m}=t;e?.("infrastructure","Deploying CloudFormation stack...");let i=await G(m);if(!i.success)return i;if(l){e?.("clean","Cleaning old files from S3...");try{await new B(m.region||"us-east-1").emptyBucket(i.bucket)}catch(b){console.log(`Note: Could not clean bucket: ${b.message}`)}}e?.("upload","Uploading files to S3...");let{uploadStaticFiles:r}=await import("./chunk-rd38qdnf.js"),a=await r({sourceDir:s,bucket:i.bucket,region:m.region||"us-east-1",cacheControl:m.cacheControl,onProgress:(b,k,R)=>{e?.("upload",`${b}/${k}: ${R}`)}});if(a.errors.length>0)return{...i,success:!1,message:`Upload errors: ${a.errors.join(", ")}`,filesUploaded:a.uploaded};if(i.distributionId&&a.uploaded>0){e?.("invalidate","Invalidating CloudFront cache...");let{invalidateCache:b}=await import("./chunk-rd38qdnf.js");await b(i.distributionId)}e?.("complete","Deployment complete!");let d=a.skipped>0?`Deployed ${a.uploaded} files (${a.skipped} unchanged) with external DNS`:`Deployed ${a.uploaded} files successfully with external DNS`;return{...i,filesUploaded:a.uploaded,filesSkipped:a.skipped,message:d}}function Q(t){let{bucketName:s,domain:l,certificateArn:e,hostedZoneId:m,defaultRootObject:i="index.html",errorDocument:r="404.html"}=t,a={},d={};a.S3Bucket={Type:"AWS::S3::Bucket",Properties:{BucketName:s,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:i,ErrorDocument:r}}},d.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},d.BucketArn={Description:"S3 Bucket ARN",Value:{"Fn::GetAtt":["S3Bucket","Arn"]}},a.CloudFrontOAC={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`OAC-${s}`,Description:`OAC for ${s}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},a.UrlRewriteFunction={Type:"AWS::CloudFront::Function",Properties:{Name:{"Fn::Sub":"${AWS::StackName}-url-rewrite"},AutoPublish:!0,FunctionConfig:{Comment:"Append .html extension to URLs without extensions",Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) {
45
+ └─────────────────────────────────────────────────────────────────────────────┘`),{success:!1,stackId:O,stackName:i,bucket:y,message:"CloudFront account verification required. Please contact AWS Support."}}return{success:!1,stackId:O,stackName:i,bucket:y,message:`Stack deployment failed: ${o.message}`}}let u=(await r.describeStacks({stackName:i})).Stacks[0]?.Outputs||[],C=(o)=>u.find((n)=>n.OutputKey===o)?.OutputValue,f=C("DistributionDomain");if(f&&d)console.log(`Creating DNS records via ${d.name}...`),await q(d,e,f);else if(f&&!d)console.log("Skipping DNS record creation (DNS verification was skipped)");return{success:!0,stackId:O,stackName:i,bucket:C("BucketName")||y,distributionId:C("DistributionId"),distributionDomain:f,domain:e,certificateArn:b,message:"Static site infrastructure deployed successfully with external DNS"}}async function q(t,s,l){if(!t){console.log("Skipping DNS record creation (DNS verification was skipped)");return}if(s.split(".").length===2)if(t instanceof Z){console.log(`Creating Route53 alias record for apex domain ${s} -> ${l}`);let i=await t.createCloudFrontAlias({domain:s,name:s,cloudFrontDomainName:l});if(!i.success)console.warn(`Warning: Could not create Route53 alias record: ${i.message}`),console.warn("Please manually create an A-record alias in Route53:"),console.warn(` ${s} -> ${l}`);else console.log(`Created Route53 alias record: ${s} -> ${l}`);let r=`www.${s}`;console.log(`Creating Route53 alias record for ${r} -> ${l}`);let a=await t.createCloudFrontAlias({domain:s,name:r,cloudFrontDomainName:l});if(!a.success)console.warn(`Warning: Could not create www Route53 alias: ${a.message}`),console.warn("Please manually create an A-record alias in Route53:"),console.warn(` ${r} -> ${l}`);else console.log(`Created Route53 alias record: ${r} -> ${l}`)}else{try{let d=await t.listRecords(s,"A");if(d.success)for(let b of d.records){let k=b.name.replace(/\.$/,"");if(k===s||k==="")console.log(`Removing existing root A record (${b.content}) to make room for ALIAS...`),await t.deleteRecord(s,{name:s,type:"A",content:b.content})}}catch(d){console.log(`Note: Could not check for conflicting A records: ${d instanceof Error?d.message:d}`)}console.log(`Creating ALIAS record for apex domain ${s} -> ${l}`);let i=await t.upsertRecord(s,{name:s,type:"ALIAS",content:l,ttl:600});if(!i.success)console.warn(`Warning: Could not create ALIAS record: ${i.message}`),console.warn("Please manually create an ALIAS record in your DNS provider:"),console.warn(` ${s} -> ${l}`);else console.log(`Created ALIAS record: ${s} -> ${l}`);let r=`www.${s}`;console.log(`Creating CNAME record for ${r} -> ${l}`);let a=await t.upsertRecord(s,{name:r,type:"CNAME",content:l,ttl:600});if(!a.success)console.warn(`Warning: Could not create www DNS record: ${a.message}`),console.warn("Please manually create a CNAME record:"),console.warn(` ${r} -> ${l}`);else console.log(`Created CNAME record: ${r} -> ${l}`)}else{console.log(`Creating CNAME record for ${s} -> ${l}`);let i=await t.upsertRecord(s,{name:s,type:"CNAME",content:l,ttl:600});if(!i.success)console.warn(`Warning: Could not create DNS record: ${i.message}`),console.warn("Please manually create a CNAME record:"),console.warn(` ${s} -> ${l}`);else console.log(`Created CNAME record: ${s} -> ${l}`)}}async function le(t){let{sourceDir:s,cleanBucket:l=!1,onProgress:e,...m}=t;e?.("infrastructure","Deploying CloudFormation stack...");let i=await G(m);if(!i.success)return i;if(l){e?.("clean","Cleaning old files from S3...");try{await new B(m.region||"us-east-1").emptyBucket(i.bucket)}catch(b){console.log(`Note: Could not clean bucket: ${b.message}`)}}e?.("upload","Uploading files to S3...");let{uploadStaticFiles:r}=await import("./chunk-qm32ytbr.js"),a=await r({sourceDir:s,bucket:i.bucket,region:m.region||"us-east-1",cacheControl:m.cacheControl,onProgress:(b,k,R)=>{e?.("upload",`${b}/${k}: ${R}`)}});if(a.errors.length>0)return{...i,success:!1,message:`Upload errors: ${a.errors.join(", ")}`,filesUploaded:a.uploaded};if(i.distributionId&&a.uploaded>0){e?.("invalidate","Invalidating CloudFront cache...");let{invalidateCache:b}=await import("./chunk-qm32ytbr.js");await b(i.distributionId)}e?.("complete","Deployment complete!");let d=a.skipped>0?`Deployed ${a.uploaded} files (${a.skipped} unchanged) with external DNS`:`Deployed ${a.uploaded} files successfully with external DNS`;return{...i,filesUploaded:a.uploaded,filesSkipped:a.skipped,message:d}}function Q(t){let{bucketName:s,domain:l,certificateArn:e,hostedZoneId:m,defaultRootObject:i="index.html",errorDocument:r="404.html"}=t,a={},d={};a.S3Bucket={Type:"AWS::S3::Bucket",Properties:{BucketName:s,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:i,ErrorDocument:r}}},d.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},d.BucketArn={Description:"S3 Bucket ARN",Value:{"Fn::GetAtt":["S3Bucket","Arn"]}},a.CloudFrontOAC={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`OAC-${s}`,Description:`OAC for ${s}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},a.UrlRewriteFunction={Type:"AWS::CloudFront::Function",Properties:{Name:{"Fn::Sub":"${AWS::StackName}-url-rewrite"},AutoPublish:!0,FunctionConfig:{Comment:"Append .html extension to URLs without extensions",Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) {
46
46
  const request = event.request;
47
47
  var uri = request.uri;
48
48
 
@@ -1,4 +1,4 @@
1
- import{Ct as ye}from"./chunk-z2qqwy7e.js";import{createRequire as Ln}from"node:module";import{isAbsolute as Gt,join as St,relative as Jn}from"node:path";import{existsSync as je,readdirSync as li}from"node:fs";import{join as Ae}from"node:path";import{createHash as Ii}from"node:crypto";import{copyFileSync as Ri,existsSync as Lt,readdirSync as Ni,readFileSync as st,statSync as Di,writeFileSync as ot}from"node:fs";import{basename as ki,dirname as ma,extname as pa,join as Ke}from"node:path";import{existsSync as Ya,readFileSync as zt}from"node:fs";import{homedir as Za}from"node:os";import{join as Xa}from"node:path";import{createHash as ar}from"node:crypto";import{existsSync as lt,mkdirSync as qs,readdirSync as Aa,readFileSync as Ca,unlinkSync as He,writeFileSync as zs}from"node:fs";import{join as xt}from"node:path";import{createHash as Qt}from"node:crypto";import{createReadStream as Qs,readdirSync as Js,statSync as At}from"node:fs";import{join as Ys,relative as Zs}from"node:path";import{deflateRawSync as Po}from"node:zlib";import{execSync as $o}from"node:child_process";import{createHash as Lo}from"node:crypto";import{cpSync as Mo,mkdtempSync as xo,rmSync as Oo,writeFileSync as Bo}from"node:fs";import{tmpdir as _o}from"node:os";import{dirname as Wo,isAbsolute as Go,join as Le,resolve as Fo}from"node:path";import{fileURLToPath as Vo}from"node:url";import{execFileSync as It}from"node:child_process";import{mkdtempSync as mn,readFileSync as Rt,rmSync as pn}from"node:fs";import{tmpdir as gn}from"node:os";import{dirname as Xo,join as ve}from"node:path";import{fileURLToPath as ec}from"node:url";import{AsyncLocalStorage as ac}from"node:async_hooks";import{createHash as rc}from"node:crypto";import{readFileSync as wc}from"node:fs";import{dirname as Ec,join as Tn}from"node:path";import{fileURLToPath as Pc}from"node:url";import{execFileSync as ut}from"node:child_process";import{existsSync as Nc,mkdirSync as Dc,mkdtempSync as kc,readdirSync as $c,readFileSync as Lc,rmSync as Mc,statSync as vn,writeFileSync as xc}from"node:fs";import{tmpdir as Oc}from"node:os";import{join as Me,relative as Bc}from"node:path";import{execSync as _c}from"node:child_process";import{createHash as Wc}from"node:crypto";import{readdirSync as Gc,readFileSync as Fc,statSync as En}from"node:fs";import{join as Vc,relative as Pn,resolve as da}from"node:path";var Mn=Object.defineProperty,xn=(e)=>e;function On(e,t){this[e]=xn.bind(null,t)}var De=(e,t)=>{for(var a in t)Mn(e,a,{get:t[a],enumerable:!0,configurable:!0,set:On.bind(t,a)})},Bn=(e,t)=>()=>(e&&(t=e(e=0)),t),_n=Ln(import.meta.url),Na={};De(Na,{clearSigningKeyCache:()=>Hn,createPresignedUrl:()=>Da,createPresignedUrlAsync:()=>Fn,detectServiceRegion:()=>jt,getSigningKeyCacheSize:()=>qn,isNodeCryptoAvailable:()=>zn,isWebCryptoAvailable:()=>Qn,makeAWSRequest:()=>Ba,makeAWSRequestAsync:()=>Un,makeAWSRequestOnce:()=>Vn,parseJSONResponse:()=>Kn,parseXMLResponse:()=>jn,signRequest:()=>K,signRequestAsync:()=>Kt});function jt(e){let t=typeof e==="string"?new URL(e):e,{hostname:a,pathname:r}=t;if(a.endsWith(".on.aws")){let o=a.match(/^[^.]+\.lambda-url\.([^.]+)\.on\.aws$/);if(o)return{service:"lambda",region:o[1]};return{service:"",region:""}}if(a.endsWith(".r2.cloudflarestorage.com"))return{service:"s3",region:"auto"};if(a.endsWith(".backblazeb2.com")){let o=a.match(/^(?:[^.]+\.)?s3\.([^.]+)\.backblazeb2\.com$/);if(o)return{service:"s3",region:o[1]};return{service:"",region:""}}let n=a.replace("dualstack.","").match(/([^.]+)\.(?:([^.]+)\.)?amazonaws\.com(?:\.cn)?$/);if(!n)return{service:"",region:""};let i=n[1],s=n[2]||"";if(s==="us-gov")s="us-gov-west-1";else if(s==="s3"||s==="s3-accelerate")s="us-east-1",i="s3";else if(i==="iot")if(a.startsWith("iot."))i="execute-api";else if(a.startsWith("data.jobs.iot."))i="iot-jobs-data";else i=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(i==="autoscaling");else if(!s&&i.startsWith("s3-"))s=i.slice(3).replace(/^fips-|^external-1/,""),i="s3";else if(i.endsWith("-fips"))i=i.slice(0,-5);else if(s&&/-\d$/.test(i)&&!/-\d$/.test(s))[i,s]=[s,i];return i=Wa[i]||i,{service:i,region:s||"us-east-1"}}function K(e){let{method:t,url:a,body:r="",accessKeyId:n,secretAccessKey:i,sessionToken:s,signQuery:o=!1,expiresIn:c=86400,datetime:l}=e,u=new URL(a),m=u.hostname,p=jt(u),g=e.service||p.service,h=e.region||p.region;if(!g)throw Error("Could not detect service from URL. Please provide service explicitly.");if(!h)throw Error("Could not detect region from URL. Please provide region explicitly.");let y=l||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),b=y.substring(0,8),T=[b,h,g,"aws4_request"].join("/"),w="AWS4-HMAC-SHA256";if(o)return Wn({urlObj:u,method:t,body:r,accessKeyId:n,secretAccessKey:i,sessionToken:s,service:g,region:h,timestamp:y,date:b,credentialScope:T,algorithm:w,expiresIn:c,cache:e.cache});let S=u.pathname||"/",E=vt(u.searchParams),v={host:m,"x-amz-date":y,...e.headers};if(s)v["x-amz-security-token"]=s;let P=Object.keys(v).some((we)=>we.toLowerCase()==="content-type");if(r&&!P)v["content-type"]="application/x-amz-json-1.0";if(g==="s3"&&!v["x-amz-content-sha256"])v["x-amz-content-sha256"]=Ze(r);let N=ka(v),I=$a(v),D=v["x-amz-content-sha256"]||Ze(r),L=[t,wt(S),E,N,I,D].join(`
1
+ import{Et as ye}from"./chunk-13qjvbqh.js";import{createRequire as Ln}from"node:module";import{isAbsolute as Gt,join as St,relative as Jn}from"node:path";import{existsSync as je,readdirSync as li}from"node:fs";import{join as Ae}from"node:path";import{createHash as Ii}from"node:crypto";import{copyFileSync as Ri,existsSync as Lt,readdirSync as Ni,readFileSync as st,statSync as Di,writeFileSync as ot}from"node:fs";import{basename as ki,dirname as ma,extname as pa,join as Ke}from"node:path";import{existsSync as Ya,readFileSync as zt}from"node:fs";import{homedir as Za}from"node:os";import{join as Xa}from"node:path";import{createHash as ar}from"node:crypto";import{existsSync as lt,mkdirSync as qs,readdirSync as Aa,readFileSync as Ca,unlinkSync as He,writeFileSync as zs}from"node:fs";import{join as xt}from"node:path";import{createHash as Qt}from"node:crypto";import{createReadStream as Qs,readdirSync as Js,statSync as At}from"node:fs";import{join as Ys,relative as Zs}from"node:path";import{deflateRawSync as Po}from"node:zlib";import{execSync as $o}from"node:child_process";import{createHash as Lo}from"node:crypto";import{cpSync as Mo,mkdtempSync as xo,rmSync as Oo,writeFileSync as Bo}from"node:fs";import{tmpdir as _o}from"node:os";import{dirname as Wo,isAbsolute as Go,join as Le,resolve as Fo}from"node:path";import{fileURLToPath as Vo}from"node:url";import{execFileSync as It}from"node:child_process";import{mkdtempSync as mn,readFileSync as Rt,rmSync as pn}from"node:fs";import{tmpdir as gn}from"node:os";import{dirname as Xo,join as ve}from"node:path";import{fileURLToPath as ec}from"node:url";import{AsyncLocalStorage as ac}from"node:async_hooks";import{createHash as rc}from"node:crypto";import{readFileSync as wc}from"node:fs";import{dirname as Ec,join as Tn}from"node:path";import{fileURLToPath as Pc}from"node:url";import{execFileSync as ut}from"node:child_process";import{existsSync as Nc,mkdirSync as Dc,mkdtempSync as kc,readdirSync as $c,readFileSync as Lc,rmSync as Mc,statSync as vn,writeFileSync as xc}from"node:fs";import{tmpdir as Oc}from"node:os";import{join as Me,relative as Bc}from"node:path";import{execSync as _c}from"node:child_process";import{createHash as Wc}from"node:crypto";import{readdirSync as Gc,readFileSync as Fc,statSync as En}from"node:fs";import{join as Vc,relative as Pn,resolve as da}from"node:path";var Mn=Object.defineProperty,xn=(e)=>e;function On(e,t){this[e]=xn.bind(null,t)}var De=(e,t)=>{for(var a in t)Mn(e,a,{get:t[a],enumerable:!0,configurable:!0,set:On.bind(t,a)})},Bn=(e,t)=>()=>(e&&(t=e(e=0)),t),_n=Ln(import.meta.url),Na={};De(Na,{clearSigningKeyCache:()=>Hn,createPresignedUrl:()=>Da,createPresignedUrlAsync:()=>Fn,detectServiceRegion:()=>jt,getSigningKeyCacheSize:()=>qn,isNodeCryptoAvailable:()=>zn,isWebCryptoAvailable:()=>Qn,makeAWSRequest:()=>Ba,makeAWSRequestAsync:()=>Un,makeAWSRequestOnce:()=>Vn,parseJSONResponse:()=>Kn,parseXMLResponse:()=>jn,signRequest:()=>K,signRequestAsync:()=>Kt});function jt(e){let t=typeof e==="string"?new URL(e):e,{hostname:a,pathname:r}=t;if(a.endsWith(".on.aws")){let o=a.match(/^[^.]+\.lambda-url\.([^.]+)\.on\.aws$/);if(o)return{service:"lambda",region:o[1]};return{service:"",region:""}}if(a.endsWith(".r2.cloudflarestorage.com"))return{service:"s3",region:"auto"};if(a.endsWith(".backblazeb2.com")){let o=a.match(/^(?:[^.]+\.)?s3\.([^.]+)\.backblazeb2\.com$/);if(o)return{service:"s3",region:o[1]};return{service:"",region:""}}let n=a.replace("dualstack.","").match(/([^.]+)\.(?:([^.]+)\.)?amazonaws\.com(?:\.cn)?$/);if(!n)return{service:"",region:""};let i=n[1],s=n[2]||"";if(s==="us-gov")s="us-gov-west-1";else if(s==="s3"||s==="s3-accelerate")s="us-east-1",i="s3";else if(i==="iot")if(a.startsWith("iot."))i="execute-api";else if(a.startsWith("data.jobs.iot."))i="iot-jobs-data";else i=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(i==="autoscaling");else if(!s&&i.startsWith("s3-"))s=i.slice(3).replace(/^fips-|^external-1/,""),i="s3";else if(i.endsWith("-fips"))i=i.slice(0,-5);else if(s&&/-\d$/.test(i)&&!/-\d$/.test(s))[i,s]=[s,i];return i=Wa[i]||i,{service:i,region:s||"us-east-1"}}function K(e){let{method:t,url:a,body:r="",accessKeyId:n,secretAccessKey:i,sessionToken:s,signQuery:o=!1,expiresIn:c=86400,datetime:l}=e,u=new URL(a),m=u.hostname,p=jt(u),g=e.service||p.service,h=e.region||p.region;if(!g)throw Error("Could not detect service from URL. Please provide service explicitly.");if(!h)throw Error("Could not detect region from URL. Please provide region explicitly.");let y=l||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),b=y.substring(0,8),T=[b,h,g,"aws4_request"].join("/"),w="AWS4-HMAC-SHA256";if(o)return Wn({urlObj:u,method:t,body:r,accessKeyId:n,secretAccessKey:i,sessionToken:s,service:g,region:h,timestamp:y,date:b,credentialScope:T,algorithm:w,expiresIn:c,cache:e.cache});let S=u.pathname||"/",E=vt(u.searchParams),v={host:m,"x-amz-date":y,...e.headers};if(s)v["x-amz-security-token"]=s;let P=Object.keys(v).some((we)=>we.toLowerCase()==="content-type");if(r&&!P)v["content-type"]="application/x-amz-json-1.0";if(g==="s3"&&!v["x-amz-content-sha256"])v["x-amz-content-sha256"]=Ze(r);let N=ka(v),I=$a(v),D=v["x-amz-content-sha256"]||Ze(r),L=[t,wt(S),E,N,I,D].join(`
2
2
  `),O=Ze(L),ce=[w,y,T,O].join(`
3
3
  `),j=e.cache??ke,ae=Ma(i,b,h,g,ce,j),F=[`${w} Credential=${n}/${T}`,`SignedHeaders=${I}`,`Signature=${ae}`].join(", ");return v.authorization=F,{url:a,method:t,headers:v,body:r||void 0}}async function Kt(e){let{method:t,url:a,body:r="",accessKeyId:n,secretAccessKey:i,sessionToken:s,signQuery:o=!1,expiresIn:c=86400,datetime:l}=e,u=new URL(a),m=u.hostname,p=jt(u),g=e.service||p.service,h=e.region||p.region;if(!g)throw Error("Could not detect service from URL. Please provide service explicitly.");if(!h)throw Error("Could not detect region from URL. Please provide region explicitly.");let y=l||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),b=y.substring(0,8),T=[b,h,g,"aws4_request"].join("/"),w="AWS4-HMAC-SHA256";if(o)return Gn({urlObj:u,method:t,body:r,accessKeyId:n,secretAccessKey:i,sessionToken:s,service:g,region:h,timestamp:y,date:b,credentialScope:T,algorithm:w,expiresIn:c,cache:e.cache});let S=u.pathname||"/",E=vt(u.searchParams),v={host:m,"x-amz-date":y,...e.headers};if(s)v["x-amz-security-token"]=s;let P=Object.keys(v).some((Ge)=>Ge.toLowerCase()==="content-type");if(r&&!P)v["content-type"]="application/x-amz-json-1.0";let N=await ht(r);if(g==="s3"&&!v["x-amz-content-sha256"])v["x-amz-content-sha256"]=N;let I=ka(v),D=$a(v),L=v["x-amz-content-sha256"]||N,O=[t,wt(S),E,I,D,L].join(`
4
4
  `),ce=await ht(O),j=[w,y,T,ce].join(`
@@ -1,4 +1,4 @@
1
- import{Tf as P}from"./chunk-y4xkj2f1.js";import{Zh as A}from"./chunk-nk7sav4r.js";import{$h as d}from"./chunk-mz0dk78z.js";import{Ct as y}from"./chunk-z2qqwy7e.js";function I(e,t){let s=[`Action=${e}`,"Version=2010-05-08"];for(let[a,i]of Object.entries(t)){if(i===void 0||i===null)continue;if(Array.isArray(i))i.forEach((n,c)=>{if(typeof n==="object"&&n!==null)for(let[u,l]of Object.entries(n))s.push(`${a}.member.${c+1}.${u}=${encodeURIComponent(String(l))}`);else s.push(`${a}.member.${c+1}=${encodeURIComponent(String(n))}`)});else if(typeof i==="object"){for(let[n,c]of Object.entries(i))if(c!==void 0&&c!==null)s.push(`${a}.${n}=${encodeURIComponent(String(c))}`)}else s.push(`${a}=${encodeURIComponent(String(i))}`)}return s.join("&")}function r(e,t){let s=new RegExp(`<${t}>([^<]*)</${t}>`),a=e.match(s);return a?a[1]:void 0}function o(e,t,s){let a=new RegExp(`<${t}>([\\s\\S]*?)</${t}>`),i=e.match(a);if(!i)return[];let n=[],c=new RegExp(`<${s}>([\\s\\S]*?)</${s}>`,"g"),u;while((u=c.exec(i[1]))!==null)n.push(u[1]);return n}class g{client;region;constructor(e="us-east-1",t){this.client=new d(void 0,{profile:t}),this.region=e}async request(e,t={}){let s=I(e,t);return await this.client.request({service:"iam",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s})}async createUser(e){let t=await this.request("CreateUser",e);return this.parseUser(t)}async getUser(e={}){let t=await this.request("GetUser",e);return this.parseUser(t)}async listUsers(e={}){let t=await this.request("ListUsers",e),s=this.parseUsers(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Users:s,IsTruncated:a,Marker:i}}async updateUser(e){await this.request("UpdateUser",e)}async deleteUser(e){await this.request("DeleteUser",e)}parseUser(e){return{UserName:r(e,"UserName")||"",UserId:r(e,"UserId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate"),PasswordLastUsed:r(e,"PasswordLastUsed")}}parseUsers(e){return o(e,"Users","member").map((s)=>({UserName:r(s,"UserName")||"",UserId:r(s,"UserId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate"),PasswordLastUsed:r(s,"PasswordLastUsed")}))}async createGroup(e){let t=await this.request("CreateGroup",e);return this.parseGroup(t)}async getGroup(e){let t=await this.request("GetGroup",e),s=this.parseGroup(t),a=this.parseUsers(t),i=r(t,"IsTruncated")==="true",n=r(t,"Marker");return{Group:s,Users:a,IsTruncated:i,Marker:n}}async listGroups(e={}){let t=await this.request("ListGroups",e),s=this.parseGroups(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Groups:s,IsTruncated:a,Marker:i}}async updateGroup(e){await this.request("UpdateGroup",e)}async deleteGroup(e){await this.request("DeleteGroup",e)}async addUserToGroup(e){await this.request("AddUserToGroup",e)}async removeUserFromGroup(e){await this.request("RemoveUserFromGroup",e)}async listGroupsForUser(e){let t=await this.request("ListGroupsForUser",e),s=this.parseGroups(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Groups:s,IsTruncated:a,Marker:i}}parseGroup(e){return{GroupName:r(e,"GroupName")||"",GroupId:r(e,"GroupId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate")}}parseGroups(e){return o(e,"Groups","member").map((s)=>({GroupName:r(s,"GroupName")||"",GroupId:r(s,"GroupId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate")}))}async createRole(e){let t=await this.request("CreateRole",e);return this.parseRole(t)}async getRole(e){let t=await this.request("GetRole",e);return this.parseRole(t)}async listRoles(e={}){let t=await this.request("ListRoles",e),s=this.parseRoles(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Roles:s,IsTruncated:a,Marker:i}}async updateRole(e){await this.request("UpdateRole",e)}async updateRoleDescription(e){let t=await this.request("UpdateRoleDescription",e);return this.parseRole(t)}async updateAssumeRolePolicy(e){await this.request("UpdateAssumeRolePolicy",e)}async deleteRole(e){await this.request("DeleteRole",e)}async tagRole(e){await this.request("TagRole",e)}async untagRole(e){await this.request("UntagRole",e)}async listRoleTags(e){let t=await this.request("ListRoleTags",e),s=this.parseTags(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Tags:s,IsTruncated:a,Marker:i}}parseRole(e){return{RoleName:r(e,"RoleName")||"",RoleId:r(e,"RoleId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate"),AssumeRolePolicyDocument:r(e,"AssumeRolePolicyDocument"),Description:r(e,"Description"),MaxSessionDuration:r(e,"MaxSessionDuration")?Number.parseInt(r(e,"MaxSessionDuration"),10):void 0}}parseRoles(e){return o(e,"Roles","member").map((s)=>({RoleName:r(s,"RoleName")||"",RoleId:r(s,"RoleId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate"),AssumeRolePolicyDocument:r(s,"AssumeRolePolicyDocument"),Description:r(s,"Description"),MaxSessionDuration:r(s,"MaxSessionDuration")?Number.parseInt(r(s,"MaxSessionDuration"),10):void 0}))}parseTags(e){return o(e,"Tags","member").map((s)=>({Key:r(s,"Key")||"",Value:r(s,"Value")||""}))}async createPolicy(e){let t=await this.request("CreatePolicy",e);return this.parsePolicy(t)}async getPolicy(e){let t=await this.request("GetPolicy",e);return this.parsePolicy(t)}async getPolicyVersion(e){let t=await this.request("GetPolicyVersion",e);return{VersionId:r(t,"VersionId")||"",IsDefaultVersion:r(t,"IsDefaultVersion")==="true",CreateDate:r(t,"CreateDate"),Document:r(t,"Document")}}async listPolicies(e={}){let t=await this.request("ListPolicies",e),s=this.parsePolicies(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Policies:s,IsTruncated:a,Marker:i}}async listPolicyVersions(e){let t=await this.request("ListPolicyVersions",e),s=this.parsePolicyVersions(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Versions:s,IsTruncated:a,Marker:i}}async createPolicyVersion(e){let t=await this.request("CreatePolicyVersion",e);return{VersionId:r(t,"VersionId")||"",IsDefaultVersion:r(t,"IsDefaultVersion")==="true",CreateDate:r(t,"CreateDate")}}async deletePolicyVersion(e){await this.request("DeletePolicyVersion",e)}async setDefaultPolicyVersion(e){await this.request("SetDefaultPolicyVersion",e)}async deletePolicy(e){await this.request("DeletePolicy",e)}async attachUserPolicy(e){await this.request("AttachUserPolicy",e)}async detachUserPolicy(e){await this.request("DetachUserPolicy",e)}async attachGroupPolicy(e){await this.request("AttachGroupPolicy",e)}async detachGroupPolicy(e){await this.request("DetachGroupPolicy",e)}async attachRolePolicy(e){await this.request("AttachRolePolicy",e)}async detachRolePolicy(e){await this.request("DetachRolePolicy",e)}async listAttachedUserPolicies(e){let t=await this.request("ListAttachedUserPolicies",e),s=this.parseAttachedPolicies(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:a,Marker:i}}async listAttachedGroupPolicies(e){let t=await this.request("ListAttachedGroupPolicies",e),s=this.parseAttachedPolicies(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:a,Marker:i}}async listAttachedRolePolicies(e){let t=await this.request("ListAttachedRolePolicies",e),s=this.parseAttachedPolicies(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:a,Marker:i}}parsePolicy(e){return{PolicyName:r(e,"PolicyName")||"",PolicyId:r(e,"PolicyId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),DefaultVersionId:r(e,"DefaultVersionId"),AttachmentCount:r(e,"AttachmentCount")?Number.parseInt(r(e,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:r(e,"PermissionsBoundaryUsageCount")?Number.parseInt(r(e,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:r(e,"IsAttachable")==="true",Description:r(e,"Description"),CreateDate:r(e,"CreateDate"),UpdateDate:r(e,"UpdateDate")}}parsePolicies(e){return o(e,"Policies","member").map((s)=>({PolicyName:r(s,"PolicyName")||"",PolicyId:r(s,"PolicyId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),DefaultVersionId:r(s,"DefaultVersionId"),AttachmentCount:r(s,"AttachmentCount")?Number.parseInt(r(s,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:r(s,"PermissionsBoundaryUsageCount")?Number.parseInt(r(s,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:r(s,"IsAttachable")==="true",Description:r(s,"Description"),CreateDate:r(s,"CreateDate"),UpdateDate:r(s,"UpdateDate")}))}parsePolicyVersions(e){return o(e,"Versions","member").map((s)=>({VersionId:r(s,"VersionId")||"",IsDefaultVersion:r(s,"IsDefaultVersion")==="true",CreateDate:r(s,"CreateDate")}))}parseAttachedPolicies(e){return o(e,"AttachedPolicies","member").map((s)=>({PolicyName:r(s,"PolicyName")||"",PolicyArn:r(s,"PolicyArn")||""}))}async putUserPolicy(e){await this.request("PutUserPolicy",e)}async getUserPolicy(e){let t=await this.request("GetUserPolicy",e);return{UserName:r(t,"UserName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteUserPolicy(e){await this.request("DeleteUserPolicy",e)}async listUserPolicies(e){let t=await this.request("ListUserPolicies",e),s=o(t,"PolicyNames","member"),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:a,Marker:i}}async putGroupPolicy(e){await this.request("PutGroupPolicy",e)}async getGroupPolicy(e){let t=await this.request("GetGroupPolicy",e);return{GroupName:r(t,"GroupName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteGroupPolicy(e){await this.request("DeleteGroupPolicy",e)}async listGroupPolicies(e){let t=await this.request("ListGroupPolicies",e),s=o(t,"PolicyNames","member"),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:a,Marker:i}}async putRolePolicy(e){await this.request("PutRolePolicy",e)}async getRolePolicy(e){let t=await this.request("GetRolePolicy",e);return{RoleName:r(t,"RoleName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteRolePolicy(e){await this.request("DeleteRolePolicy",e)}async listRolePolicies(e){let t=await this.request("ListRolePolicies",e),s=o(t,"PolicyNames","member"),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:a,Marker:i}}async createAccessKey(e={}){let t=await this.request("CreateAccessKey",e);if(typeof t==="object"){let s=t?.CreateAccessKeyResult?.AccessKey||t?.AccessKey;if(s)return{AccessKey:{UserName:s.UserName||"",AccessKeyId:s.AccessKeyId||"",Status:s.Status||"Active",SecretAccessKey:s.SecretAccessKey||"",CreateDate:s.CreateDate}}}return{AccessKey:{UserName:r(t,"UserName")||"",AccessKeyId:r(t,"AccessKeyId")||"",Status:r(t,"Status")||"Active",SecretAccessKey:r(t,"SecretAccessKey")||"",CreateDate:r(t,"CreateDate")}}}async listAccessKeys(e={}){let t=await this.request("ListAccessKeys",e),s=this.parseAccessKeys(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AccessKeyMetadata:s,IsTruncated:a,Marker:i}}async updateAccessKey(e){await this.request("UpdateAccessKey",e)}async deleteAccessKey(e){await this.request("DeleteAccessKey",e)}async getAccessKeyLastUsed(e){let t=await this.request("GetAccessKeyLastUsed",e);return{UserName:r(t,"UserName")||"",AccessKeyLastUsed:{LastUsedDate:r(t,"LastUsedDate"),ServiceName:r(t,"ServiceName"),Region:r(t,"Region")}}}parseAccessKeys(e){return o(e,"AccessKeyMetadata","member").map((s)=>({UserName:r(s,"UserName"),AccessKeyId:r(s,"AccessKeyId")||"",Status:r(s,"Status")||"Active",CreateDate:r(s,"CreateDate")}))}async createInstanceProfile(e){let t=await this.request("CreateInstanceProfile",e);return this.parseInstanceProfile(t)}async getInstanceProfile(e){let t=await this.request("GetInstanceProfile",e);return this.parseInstanceProfile(t)}async listInstanceProfiles(e={}){let t=await this.request("ListInstanceProfiles",e),s=this.parseInstanceProfiles(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{InstanceProfiles:s,IsTruncated:a,Marker:i}}async listInstanceProfilesForRole(e){let t=await this.request("ListInstanceProfilesForRole",e),s=this.parseInstanceProfiles(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{InstanceProfiles:s,IsTruncated:a,Marker:i}}async addRoleToInstanceProfile(e){await this.request("AddRoleToInstanceProfile",e)}async removeRoleFromInstanceProfile(e){await this.request("RemoveRoleFromInstanceProfile",e)}async deleteInstanceProfile(e){await this.request("DeleteInstanceProfile",e)}parseInstanceProfile(e){return{InstanceProfileName:r(e,"InstanceProfileName")||"",InstanceProfileId:r(e,"InstanceProfileId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate")}}parseInstanceProfiles(e){return o(e,"InstanceProfiles","member").map((s)=>({InstanceProfileName:r(s,"InstanceProfileName")||"",InstanceProfileId:r(s,"InstanceProfileId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate")}))}async getAccountPasswordPolicy(){let e=await this.request("GetAccountPasswordPolicy");return{MinimumPasswordLength:r(e,"MinimumPasswordLength")?Number.parseInt(r(e,"MinimumPasswordLength"),10):void 0,RequireSymbols:r(e,"RequireSymbols")==="true",RequireNumbers:r(e,"RequireNumbers")==="true",RequireUppercaseCharacters:r(e,"RequireUppercaseCharacters")==="true",RequireLowercaseCharacters:r(e,"RequireLowercaseCharacters")==="true",AllowUsersToChangePassword:r(e,"AllowUsersToChangePassword")==="true",ExpirePasswords:r(e,"ExpirePasswords")==="true",MaxPasswordAge:r(e,"MaxPasswordAge")?Number.parseInt(r(e,"MaxPasswordAge"),10):void 0,PasswordReusePrevention:r(e,"PasswordReusePrevention")?Number.parseInt(r(e,"PasswordReusePrevention"),10):void 0,HardExpiry:r(e,"HardExpiry")==="true"}}async updateAccountPasswordPolicy(e){await this.request("UpdateAccountPasswordPolicy",e)}async deleteAccountPasswordPolicy(){await this.request("DeleteAccountPasswordPolicy")}async getAccountSummary(){let e=await this.request("GetAccountSummary"),t={},s=o(e,"SummaryMap","entry");for(let a of s){let i=r(a,"key"),n=r(a,"value");if(i&&n)t[i]=Number.parseInt(n,10)}return t}async listAccountAliases(){let e=await this.request("ListAccountAliases"),t=o(e,"AccountAliases","member"),s=r(e,"IsTruncated")==="true",a=r(e,"Marker");return{AccountAliases:t,IsTruncated:s,Marker:a}}async createAccountAlias(e){await this.request("CreateAccountAlias",e)}async deleteAccountAlias(e){await this.request("DeleteAccountAlias",e)}async simulatePrincipalPolicy(e){let t=await this.request("SimulatePrincipalPolicy",e);return this.parseSimulationResults(t)}parseSimulationResults(e){let s=o(e,"EvaluationResults","member").map((n)=>{let u=o(n,"MatchedStatements","member").map((l)=>({SourcePolicyId:r(l,"SourcePolicyId"),SourcePolicyType:r(l,"SourcePolicyType")}));return{EvalActionName:r(n,"EvalActionName")||"",EvalResourceName:r(n,"EvalResourceName"),EvalDecision:r(n,"EvalDecision")||"",MatchedStatements:u.length>0?u:void 0}}),a=r(e,"IsTruncated")==="true",i=r(e,"Marker");return{EvaluationResults:s,IsTruncated:a,Marker:i}}}class p{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new d(t)}async createEmailIdentity(e){return await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/identities",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async getEmailIdentity(e){let t=await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/identities/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}});return{IdentityType:t.IdentityType,IdentityName:e,SendingEnabled:t.VerifiedForSendingStatus,VerificationStatus:t.VerificationStatus,DkimAttributes:t.DkimAttributes,MailFromAttributes:t.MailFromAttributes}}async putEmailIdentityMailFromAttributes(e,t){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(e)}/mail-from`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async listEmailIdentities(e){let t="/v2/email/identities",s=[];if(e?.PageSize)s.push(`PageSize=${e.PageSize}`);if(e?.NextToken)s.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(s.length>0)t+=`?${s.join("&")}`;let a=await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}});return{EmailIdentities:a.EmailIdentities,NextToken:a.NextToken}}async deleteEmailIdentity(e){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/identities/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async putEmailIdentityDkimAttributes(e){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(e.EmailIdentity)}/dkim`,headers:{"Content-Type":"application/json"},body:JSON.stringify({SigningEnabled:e.SigningEnabled})})}async sendEmail(e){return{MessageId:(await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/outbound-emails",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).MessageId}}async sendBulkEmail(e){return{BulkEmailEntryResults:(await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/outbound-bulk-emails",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).BulkEmailEntryResults}}async createEmailTemplate(e){await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/templates",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async getEmailTemplate(e){return await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/templates/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async deleteEmailTemplate(e){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/templates/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async listEmailTemplates(e){let t="/v2/email/templates",s=[];if(e?.PageSize)s.push(`PageSize=${e.PageSize}`);if(e?.NextToken)s.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(s.length>0)t+=`?${s.join("&")}`;return await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}})}async getSendStatistics(){return{SendDataPoints:(await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendStatistics&Version=2010-12-01"})).GetSendStatisticsResponse?.GetSendStatisticsResult?.SendDataPoints?.member}}async getSendQuota(){let t=(await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendQuota&Version=2010-12-01"})).GetSendQuotaResponse?.GetSendQuotaResult;return{Max24HourSend:t?.Max24HourSend?Number(t.Max24HourSend):void 0,MaxSendRate:t?.MaxSendRate?Number(t.MaxSendRate):void 0,SentLast24Hours:t?.SentLast24Hours?Number(t.SentLast24Hours):void 0}}async verifyDomain(e){let t=await this.createEmailIdentity({EmailIdentity:e});return{dkimTokens:t.DkimAttributes?.Tokens,verificationStatus:t.DkimAttributes?.Status}}async sendSimpleEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],s=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0,a={};if(e.text)a.Text={Data:e.text};if(e.html)a.Html={Data:e.html};return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Simple:{Subject:{Data:e.subject},Body:a}},ReplyToAddresses:s})}async sendTemplatedEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],s=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0;return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Template:{TemplateName:e.templateName,TemplateData:JSON.stringify(e.templateData)}},ReplyToAddresses:s})}async getDkimRecords(e){let t=await this.getEmailIdentity(e);if(!t.DkimAttributes?.Tokens)return[];return t.DkimAttributes.Tokens.map((s)=>({name:`${s}._domainkey.${e}`,type:"CNAME",value:`${s}.dkim.amazonses.com`}))}async isDomainVerified(e){try{let t=await this.getEmailIdentity(e);return t.VerificationStatus==="SUCCESS"&&t.SendingEnabled===!0}catch{return!1}}async waitForDomainVerification(e,t=60,s=30000){for(let a=0;a<t;a++){if(await this.isDomainVerified(e))return!0;await new Promise((n)=>setTimeout(n,s))}return!1}buildFormBody(e){return Object.entries(e).filter(([,s])=>s!==void 0).map(([s,a])=>`${encodeURIComponent(s)}=${encodeURIComponent(a)}`).join("&")}async createReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"CreateReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async deleteReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async setActiveReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"SetActiveReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async listReceiptRuleSets(e){let t={Action:"ListReceiptRuleSets",Version:"2010-12-01"};if(e)t.NextToken=e;let s=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)}),a=s?.ListReceiptRuleSetsResponse?.ListReceiptRuleSetsResult||s?.ListReceiptRuleSetsResult,i=a?.RuleSets?.member;return{RuleSets:Array.isArray(i)?i:i?[i]:[],NextToken:a?.NextToken}}async describeReceiptRuleSet(e){let t=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DescribeReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})}),s=t?.DescribeReceiptRuleSetResponse?.DescribeReceiptRuleSetResult||t?.DescribeReceiptRuleSetResult,a=s?.Rules?.member;return{Metadata:s?.Metadata,Rules:Array.isArray(a)?a:a?[a]:[]}}async createReceiptRule(e){let t={Action:"CreateReceiptRule",Version:"2010-12-01",RuleSetName:e.RuleSetName,"Rule.Name":e.Rule.Name,"Rule.Enabled":e.Rule.Enabled!==!1?"true":"false"};if(e.Rule.TlsPolicy)t["Rule.TlsPolicy"]=e.Rule.TlsPolicy;if(e.Rule.ScanEnabled!==void 0)t["Rule.ScanEnabled"]=e.Rule.ScanEnabled?"true":"false";if(e.After)t.After=e.After;if(e.Rule.Recipients)e.Rule.Recipients.forEach((s,a)=>{t[`Rule.Recipients.member.${a+1}`]=s});e.Rule.Actions.forEach((s,a)=>{let i=a+1;if(s.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=s.S3Action.BucketName,s.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=s.S3Action.ObjectKeyPrefix;if(s.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=s.S3Action.KmsKeyArn}if(s.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=s.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=s.LambdaAction.InvocationType||"Event";if(s.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=s.SNSAction.TopicArn,s.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=s.SNSAction.Encoding}if(s.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=s.StopAction.Scope,s.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=s.StopAction.TopicArn}}),await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)})}async deleteReceiptRule(e,t){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteReceiptRule",Version:"2010-12-01",RuleSetName:e,RuleName:t})})}async receiptRuleSetExists(e){try{return await this.describeReceiptRuleSet(e),!0}catch(t){if(t.code==="RuleSetDoesNotExist"||t.statusCode===400)return!1;throw t}}async getActiveReceiptRuleSet(){let e=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DescribeActiveReceiptRuleSet",Version:"2010-12-01"})}),t=e?.DescribeActiveReceiptRuleSetResponse?.DescribeActiveReceiptRuleSetResult||e?.DescribeActiveReceiptRuleSetResult;if(!t?.Metadata)return null;let s=t?.Rules?.member;return{Metadata:t?.Metadata,Rules:Array.isArray(s)?s:s?[s]:[]}}async updateReceiptRule(e){let t={Action:"UpdateReceiptRule",Version:"2010-12-01",RuleSetName:e.RuleSetName,"Rule.Name":e.Rule.Name};if(e.Rule.Enabled!==void 0)t["Rule.Enabled"]=e.Rule.Enabled?"true":"false";if(e.Rule.TlsPolicy)t["Rule.TlsPolicy"]=e.Rule.TlsPolicy;if(e.Rule.ScanEnabled!==void 0)t["Rule.ScanEnabled"]=e.Rule.ScanEnabled?"true":"false";if(e.Rule.Recipients)e.Rule.Recipients.forEach((s,a)=>{t[`Rule.Recipients.member.${a+1}`]=s});e.Rule.Actions.forEach((s,a)=>{let i=a+1;if(s.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=s.S3Action.BucketName,s.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=s.S3Action.ObjectKeyPrefix;if(s.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=s.S3Action.KmsKeyArn}if(s.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=s.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=s.LambdaAction.InvocationType||"Event";if(s.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=s.SNSAction.TopicArn,s.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=s.SNSAction.Encoding}if(s.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=s.StopAction.Scope,s.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=s.StopAction.TopicArn}}),await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)})}async sendRawEmail(e){let t=Buffer.from(e.rawMessage).toString("base64"),s={Action:"SendRawEmail",Version:"2010-12-01",Source:e.source,"RawMessage.Data":t};e.destinations.forEach((n,c)=>{s[`Destinations.member.${c+1}`]=n});let a=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(s)});return{MessageId:(a?.SendRawEmailResponse?.SendRawEmailResult||a?.SendRawEmailResult)?.MessageId}}async getSuppressedDestination(e){try{return(await this.client.request({service:"ses",region:this.region,method:"GET",path:`/v2/email/suppression/addresses/${encodeURIComponent(e)}`}))?.SuppressedDestination||null}catch(t){if(t.message?.includes("404")||t.message?.includes("NotFoundException"))return null;throw t}}async deleteSuppressedDestination(e){await this.client.request({service:"ses",region:this.region,method:"DELETE",path:`/v2/email/suppression/addresses/${encodeURIComponent(e)}`})}}class h{ses;s3;iam;route53;region;domain;defaultFrom;constructor(e={}){this.region=e.region||"us-east-1",this.domain=e.domain,this.defaultFrom=e.defaultFrom,this.ses=new p(this.region),this.s3=new A(this.region),this.iam=new g(this.region),this.route53=new P(this.region)}async send(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required. Set defaultFrom in constructor or provide from in options.");let s=e.fromName?`${e.fromName} <${t}>`:t,a=Array.isArray(e.to)?e.to:[e.to];if(!e.attachments||e.attachments.length===0)return{messageId:(await this.ses.sendSimpleEmail({from:s,to:a,subject:e.subject,text:e.text,html:e.html,replyTo:e.replyTo})).MessageId||""};let i=this.buildRawEmail(e,s,a);return{messageId:(await this.ses.sendEmail({FromEmailAddress:s,Destination:{ToAddresses:a,CcAddresses:e.cc?Array.isArray(e.cc)?e.cc:[e.cc]:void 0,BccAddresses:e.bcc?Array.isArray(e.bcc)?e.bcc:[e.bcc]:void 0},Content:{Raw:{Data:Buffer.from(i).toString("base64")}}})).MessageId||""}}async sendTemplate(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required");let s=e.fromName?`${e.fromName} <${t}>`:t;return{messageId:(await this.ses.sendTemplatedEmail({from:s,to:e.to,templateName:e.templateName,templateData:e.templateData,replyTo:e.replyTo})).MessageId||""}}async sendBulk(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required");let s=e.recipients.map((i)=>({Destination:{ToAddresses:Array.isArray(i.to)?i.to:[i.to]},ReplacementEmailContent:i.templateData?{ReplacementTemplate:{ReplacementTemplateData:JSON.stringify(i.templateData)}}:void 0}));return{results:(await this.ses.sendBulkEmail({FromEmailAddress:t,BulkEmailEntries:s,DefaultContent:{Template:{TemplateName:e.templateName,TemplateData:JSON.stringify(e.defaultTemplateData)}}})).BulkEmailEntryResults?.map((i)=>({status:i.Status||"UNKNOWN",messageId:i.MessageId,error:i.Error}))||[]}}async setupDomain(e){let t;try{t=await this.ses.getEmailIdentity(e)}catch{let a=await this.ses.createEmailIdentity({EmailIdentity:e});t={VerificationStatus:a.DkimAttributes?.Status,DkimAttributes:a.DkimAttributes,SendingEnabled:a.VerifiedForSendingStatus}}try{await this.ses.putEmailIdentityDkimAttributes({EmailIdentity:e,SigningEnabled:!0})}catch{}try{await this.ses.putEmailIdentityMailFromAttributes(e,{MailFromDomain:`mail.${e}`,BehaviorOnMxFailure:"USE_DEFAULT_VALUE"})}catch{}let s=await this.ses.getDkimRecords(e);return{domainVerified:t.SendingEnabled===!0,dkimStatus:t.DkimAttributes?.Status||"UNKNOWN",dkimTokens:t.DkimAttributes?.Tokens,mailFromStatus:t.MailFromAttributes?.MailFromDomainStatus}}async getDnsRecords(e){let t=[],s=await this.ses.getDkimRecords(e);for(let a of s)t.push({type:a.type,name:a.name,value:a.value,ttl:1800});return t.push({type:"MX",name:e,value:`inbound-smtp.${this.region}.amazonaws.com`,priority:10,ttl:3600}),t.push({type:"MX",name:`mail.${e}`,value:`feedback-smtp.${this.region}.amazonses.com`,priority:10,ttl:3600}),t.push({type:"TXT",name:`mail.${e}`,value:"v=spf1 include:amazonses.com ~all",ttl:3600}),t.push({type:"TXT",name:`_dmarc.${e}`,value:`v=DMARC1;p=quarantine;pct=25;rua=mailto:dmarcreports@${e}`,ttl:3600}),t}async isDomainReady(e){try{let t=await this.ses.getEmailIdentity(e);return t.SendingEnabled===!0&&t.DkimAttributes?.Status==="SUCCESS"}catch{return!1}}async setupReceiving(e){let t={Version:"2012-10-17",Statement:[{Sid:"AllowSESPuts",Effect:"Allow",Principal:{Service:"ses.amazonaws.com"},Action:"s3:PutObject",Resource:`arn:aws:s3:::${e.bucketName}/*`,Condition:{StringEquals:{"AWS:SourceAccount":e.accountId}}}]};await this.s3.putBucketPolicy(e.bucketName,t);try{await this.ses.createReceiptRuleSet(e.ruleSetName)}catch(a){if(!a.message?.includes("already exists")&&a.code!=="AlreadyExists")throw a}let s=[{S3Action:{BucketName:e.bucketName,ObjectKeyPrefix:e.prefix||"inbox/"}}];if(e.lambdaArn)s.push({LambdaAction:{FunctionArn:e.lambdaArn,InvocationType:"Event"}});try{await this.ses.createReceiptRule({RuleSetName:e.ruleSetName,Rule:{Name:e.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:e.recipients||[e.domain],ScanEnabled:e.scanEnabled!==!1,Actions:s}})}catch(a){if(a.message?.includes("already exists"))await this.ses.deleteReceiptRule(e.ruleSetName,e.ruleName),await this.ses.createReceiptRule({RuleSetName:e.ruleSetName,Rule:{Name:e.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:e.recipients||[e.domain],ScanEnabled:e.scanEnabled!==!1,Actions:s}});else throw a}await this.ses.setActiveReceiptRuleSet(e.ruleSetName)}async getIncomingEmails(e){return(await this.s3.list({bucket:e.bucket,prefix:e.prefix||"incoming/",maxKeys:e.maxResults||100})).map((s)=>({key:s.Key||"",lastModified:s.LastModified||"",size:s.Size||0}))}async readEmail(e){return await this.s3.getObject(e.bucket,e.key)}async createSmtpCredentials(e){let t=`ses-smtp-${e.username.replace(/[^a-zA-Z0-9]/g,"-")}`,{AWSClient:s}=await import("./chunk-5vt93kxx.js"),a=new s,i=(m,S)=>{let f={Action:m,Version:"2010-05-08",...S};return Object.entries(f).map(([b,T])=>`${encodeURIComponent(b)}=${encodeURIComponent(T)}`).join("&")};try{await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateUser",{UserName:t})})}catch(m){if(!m.message?.includes("EntityAlreadyExists"))throw m}let n={Version:"2012-10-17",Statement:[{Effect:"Allow",Action:"ses:SendRawEmail",Resource:"*",Condition:{StringLike:{"ses:FromAddress":`*@${e.domain}`}}}]},c=`ses-smtp-policy-${e.domain.replace(/\./g,"-")}`;try{await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("PutUserPolicy",{UserName:t,PolicyName:c,PolicyDocument:JSON.stringify(n)})})}catch{}let l=(await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateAccessKey",{UserName:t})}))?.CreateAccessKeyResult?.AccessKey;if(!l?.AccessKeyId||!l?.SecretAccessKey)throw Error("Failed to create access key");let R=this.deriveSmtpPassword(l.SecretAccessKey);return{username:l.AccessKeyId,password:R,server:`email-smtp.${this.region}.amazonaws.com`,port:587}}deriveSmtpPassword(e){let t=y("node:crypto"),s="SendRawEmail",a=Buffer.from([4]),i=t.createHmac("sha256",`AWS4${e}`).update("11111111").digest();return i=t.createHmac("sha256",i).update(this.region).digest(),i=t.createHmac("sha256",i).update("ses").digest(),i=t.createHmac("sha256",i).update("aws4_request").digest(),i=t.createHmac("sha256",i).update("SendRawEmail").digest(),Buffer.concat([a,i]).toString("base64")}async createTemplate(e){await this.ses.createEmailTemplate({TemplateName:e.name,TemplateContent:{Subject:e.subject,Text:e.text,Html:e.html}})}async getTemplate(e){try{let t=await this.ses.getEmailTemplate(e);return{name:t.TemplateName||e,subject:t.TemplateContent?.Subject,text:t.TemplateContent?.Text,html:t.TemplateContent?.Html}}catch{return null}}async deleteTemplate(e){await this.ses.deleteEmailTemplate(e)}async listTemplates(){return(await this.ses.listEmailTemplates()).TemplatesMetadata?.map((t)=>({name:t.TemplateName||"",createdAt:t.CreatedTimestamp}))||[]}async deploy(e){let t=`${e.appName}-${e.environment}-email-rules`,s=`${e.appName}-inbound-email`,a=e.storage?.bucketName||`${e.appName}-${e.environment}-email`,i=await this.setupDomain(e.domain);if(!(await this.s3.listBuckets()).Buckets?.some((l)=>l.Name===a))await this.s3.createBucket(a);await this.setupReceiving({domain:e.domain,ruleSetName:t,ruleName:s,bucketName:a,prefix:e.storage?.prefix||"inbox/",accountId:e.accountId,recipients:e.catchAll?[e.domain]:e.mailboxes,scanEnabled:!0});let u=await this.getDnsRecords(e.domain);return{success:!0,domainVerified:i.domainVerified,dkimStatus:i.dkimStatus,receiptRuleSet:t,storageBucket:a,dnsRecords:u}}async undeploy(e){let t=`${e.appName}-${e.environment}-email-rules`,s=`${e.appName}-inbound-email`,a=`${e.appName}-${e.environment}-email`;try{await this.ses.deleteReceiptRule(t,s)}catch{}try{await this.ses.deleteReceiptRuleSet(t)}catch{}if(e.deleteBucket)try{await this.s3.emptyAndDeleteBucket(a)}catch{}}async getSendingStats(){let e=await this.ses.getSendQuota();return{sentLast24Hours:e.SentLast24Hours||0,maxSendRate:e.MaxSendRate||0,max24HourSend:e.Max24HourSend||0}}buildRawEmail(e,t,s){let a=`----=_Part_${Date.now()}_${Math.random().toString(36).substring(2)}`,i="";if(i+=`From: ${t}\r
1
+ import{Tf as P}from"./chunk-y4xkj2f1.js";import{Zh as A}from"./chunk-152he7m3.js";import{$h as d}from"./chunk-mz0dk78z.js";import{Et as y}from"./chunk-13qjvbqh.js";function I(e,t){let s=[`Action=${e}`,"Version=2010-05-08"];for(let[a,i]of Object.entries(t)){if(i===void 0||i===null)continue;if(Array.isArray(i))i.forEach((n,c)=>{if(typeof n==="object"&&n!==null)for(let[u,l]of Object.entries(n))s.push(`${a}.member.${c+1}.${u}=${encodeURIComponent(String(l))}`);else s.push(`${a}.member.${c+1}=${encodeURIComponent(String(n))}`)});else if(typeof i==="object"){for(let[n,c]of Object.entries(i))if(c!==void 0&&c!==null)s.push(`${a}.${n}=${encodeURIComponent(String(c))}`)}else s.push(`${a}=${encodeURIComponent(String(i))}`)}return s.join("&")}function r(e,t){let s=new RegExp(`<${t}>([^<]*)</${t}>`),a=e.match(s);return a?a[1]:void 0}function o(e,t,s){let a=new RegExp(`<${t}>([\\s\\S]*?)</${t}>`),i=e.match(a);if(!i)return[];let n=[],c=new RegExp(`<${s}>([\\s\\S]*?)</${s}>`,"g"),u;while((u=c.exec(i[1]))!==null)n.push(u[1]);return n}class g{client;region;constructor(e="us-east-1",t){this.client=new d(void 0,{profile:t}),this.region=e}async request(e,t={}){let s=I(e,t);return await this.client.request({service:"iam",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s})}async createUser(e){let t=await this.request("CreateUser",e);return this.parseUser(t)}async getUser(e={}){let t=await this.request("GetUser",e);return this.parseUser(t)}async listUsers(e={}){let t=await this.request("ListUsers",e),s=this.parseUsers(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Users:s,IsTruncated:a,Marker:i}}async updateUser(e){await this.request("UpdateUser",e)}async deleteUser(e){await this.request("DeleteUser",e)}parseUser(e){return{UserName:r(e,"UserName")||"",UserId:r(e,"UserId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate"),PasswordLastUsed:r(e,"PasswordLastUsed")}}parseUsers(e){return o(e,"Users","member").map((s)=>({UserName:r(s,"UserName")||"",UserId:r(s,"UserId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate"),PasswordLastUsed:r(s,"PasswordLastUsed")}))}async createGroup(e){let t=await this.request("CreateGroup",e);return this.parseGroup(t)}async getGroup(e){let t=await this.request("GetGroup",e),s=this.parseGroup(t),a=this.parseUsers(t),i=r(t,"IsTruncated")==="true",n=r(t,"Marker");return{Group:s,Users:a,IsTruncated:i,Marker:n}}async listGroups(e={}){let t=await this.request("ListGroups",e),s=this.parseGroups(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Groups:s,IsTruncated:a,Marker:i}}async updateGroup(e){await this.request("UpdateGroup",e)}async deleteGroup(e){await this.request("DeleteGroup",e)}async addUserToGroup(e){await this.request("AddUserToGroup",e)}async removeUserFromGroup(e){await this.request("RemoveUserFromGroup",e)}async listGroupsForUser(e){let t=await this.request("ListGroupsForUser",e),s=this.parseGroups(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Groups:s,IsTruncated:a,Marker:i}}parseGroup(e){return{GroupName:r(e,"GroupName")||"",GroupId:r(e,"GroupId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate")}}parseGroups(e){return o(e,"Groups","member").map((s)=>({GroupName:r(s,"GroupName")||"",GroupId:r(s,"GroupId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate")}))}async createRole(e){let t=await this.request("CreateRole",e);return this.parseRole(t)}async getRole(e){let t=await this.request("GetRole",e);return this.parseRole(t)}async listRoles(e={}){let t=await this.request("ListRoles",e),s=this.parseRoles(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Roles:s,IsTruncated:a,Marker:i}}async updateRole(e){await this.request("UpdateRole",e)}async updateRoleDescription(e){let t=await this.request("UpdateRoleDescription",e);return this.parseRole(t)}async updateAssumeRolePolicy(e){await this.request("UpdateAssumeRolePolicy",e)}async deleteRole(e){await this.request("DeleteRole",e)}async tagRole(e){await this.request("TagRole",e)}async untagRole(e){await this.request("UntagRole",e)}async listRoleTags(e){let t=await this.request("ListRoleTags",e),s=this.parseTags(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Tags:s,IsTruncated:a,Marker:i}}parseRole(e){return{RoleName:r(e,"RoleName")||"",RoleId:r(e,"RoleId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate"),AssumeRolePolicyDocument:r(e,"AssumeRolePolicyDocument"),Description:r(e,"Description"),MaxSessionDuration:r(e,"MaxSessionDuration")?Number.parseInt(r(e,"MaxSessionDuration"),10):void 0}}parseRoles(e){return o(e,"Roles","member").map((s)=>({RoleName:r(s,"RoleName")||"",RoleId:r(s,"RoleId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate"),AssumeRolePolicyDocument:r(s,"AssumeRolePolicyDocument"),Description:r(s,"Description"),MaxSessionDuration:r(s,"MaxSessionDuration")?Number.parseInt(r(s,"MaxSessionDuration"),10):void 0}))}parseTags(e){return o(e,"Tags","member").map((s)=>({Key:r(s,"Key")||"",Value:r(s,"Value")||""}))}async createPolicy(e){let t=await this.request("CreatePolicy",e);return this.parsePolicy(t)}async getPolicy(e){let t=await this.request("GetPolicy",e);return this.parsePolicy(t)}async getPolicyVersion(e){let t=await this.request("GetPolicyVersion",e);return{VersionId:r(t,"VersionId")||"",IsDefaultVersion:r(t,"IsDefaultVersion")==="true",CreateDate:r(t,"CreateDate"),Document:r(t,"Document")}}async listPolicies(e={}){let t=await this.request("ListPolicies",e),s=this.parsePolicies(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Policies:s,IsTruncated:a,Marker:i}}async listPolicyVersions(e){let t=await this.request("ListPolicyVersions",e),s=this.parsePolicyVersions(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Versions:s,IsTruncated:a,Marker:i}}async createPolicyVersion(e){let t=await this.request("CreatePolicyVersion",e);return{VersionId:r(t,"VersionId")||"",IsDefaultVersion:r(t,"IsDefaultVersion")==="true",CreateDate:r(t,"CreateDate")}}async deletePolicyVersion(e){await this.request("DeletePolicyVersion",e)}async setDefaultPolicyVersion(e){await this.request("SetDefaultPolicyVersion",e)}async deletePolicy(e){await this.request("DeletePolicy",e)}async attachUserPolicy(e){await this.request("AttachUserPolicy",e)}async detachUserPolicy(e){await this.request("DetachUserPolicy",e)}async attachGroupPolicy(e){await this.request("AttachGroupPolicy",e)}async detachGroupPolicy(e){await this.request("DetachGroupPolicy",e)}async attachRolePolicy(e){await this.request("AttachRolePolicy",e)}async detachRolePolicy(e){await this.request("DetachRolePolicy",e)}async listAttachedUserPolicies(e){let t=await this.request("ListAttachedUserPolicies",e),s=this.parseAttachedPolicies(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:a,Marker:i}}async listAttachedGroupPolicies(e){let t=await this.request("ListAttachedGroupPolicies",e),s=this.parseAttachedPolicies(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:a,Marker:i}}async listAttachedRolePolicies(e){let t=await this.request("ListAttachedRolePolicies",e),s=this.parseAttachedPolicies(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:a,Marker:i}}parsePolicy(e){return{PolicyName:r(e,"PolicyName")||"",PolicyId:r(e,"PolicyId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),DefaultVersionId:r(e,"DefaultVersionId"),AttachmentCount:r(e,"AttachmentCount")?Number.parseInt(r(e,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:r(e,"PermissionsBoundaryUsageCount")?Number.parseInt(r(e,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:r(e,"IsAttachable")==="true",Description:r(e,"Description"),CreateDate:r(e,"CreateDate"),UpdateDate:r(e,"UpdateDate")}}parsePolicies(e){return o(e,"Policies","member").map((s)=>({PolicyName:r(s,"PolicyName")||"",PolicyId:r(s,"PolicyId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),DefaultVersionId:r(s,"DefaultVersionId"),AttachmentCount:r(s,"AttachmentCount")?Number.parseInt(r(s,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:r(s,"PermissionsBoundaryUsageCount")?Number.parseInt(r(s,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:r(s,"IsAttachable")==="true",Description:r(s,"Description"),CreateDate:r(s,"CreateDate"),UpdateDate:r(s,"UpdateDate")}))}parsePolicyVersions(e){return o(e,"Versions","member").map((s)=>({VersionId:r(s,"VersionId")||"",IsDefaultVersion:r(s,"IsDefaultVersion")==="true",CreateDate:r(s,"CreateDate")}))}parseAttachedPolicies(e){return o(e,"AttachedPolicies","member").map((s)=>({PolicyName:r(s,"PolicyName")||"",PolicyArn:r(s,"PolicyArn")||""}))}async putUserPolicy(e){await this.request("PutUserPolicy",e)}async getUserPolicy(e){let t=await this.request("GetUserPolicy",e);return{UserName:r(t,"UserName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteUserPolicy(e){await this.request("DeleteUserPolicy",e)}async listUserPolicies(e){let t=await this.request("ListUserPolicies",e),s=o(t,"PolicyNames","member"),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:a,Marker:i}}async putGroupPolicy(e){await this.request("PutGroupPolicy",e)}async getGroupPolicy(e){let t=await this.request("GetGroupPolicy",e);return{GroupName:r(t,"GroupName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteGroupPolicy(e){await this.request("DeleteGroupPolicy",e)}async listGroupPolicies(e){let t=await this.request("ListGroupPolicies",e),s=o(t,"PolicyNames","member"),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:a,Marker:i}}async putRolePolicy(e){await this.request("PutRolePolicy",e)}async getRolePolicy(e){let t=await this.request("GetRolePolicy",e);return{RoleName:r(t,"RoleName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteRolePolicy(e){await this.request("DeleteRolePolicy",e)}async listRolePolicies(e){let t=await this.request("ListRolePolicies",e),s=o(t,"PolicyNames","member"),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:a,Marker:i}}async createAccessKey(e={}){let t=await this.request("CreateAccessKey",e);if(typeof t==="object"){let s=t?.CreateAccessKeyResult?.AccessKey||t?.AccessKey;if(s)return{AccessKey:{UserName:s.UserName||"",AccessKeyId:s.AccessKeyId||"",Status:s.Status||"Active",SecretAccessKey:s.SecretAccessKey||"",CreateDate:s.CreateDate}}}return{AccessKey:{UserName:r(t,"UserName")||"",AccessKeyId:r(t,"AccessKeyId")||"",Status:r(t,"Status")||"Active",SecretAccessKey:r(t,"SecretAccessKey")||"",CreateDate:r(t,"CreateDate")}}}async listAccessKeys(e={}){let t=await this.request("ListAccessKeys",e),s=this.parseAccessKeys(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AccessKeyMetadata:s,IsTruncated:a,Marker:i}}async updateAccessKey(e){await this.request("UpdateAccessKey",e)}async deleteAccessKey(e){await this.request("DeleteAccessKey",e)}async getAccessKeyLastUsed(e){let t=await this.request("GetAccessKeyLastUsed",e);return{UserName:r(t,"UserName")||"",AccessKeyLastUsed:{LastUsedDate:r(t,"LastUsedDate"),ServiceName:r(t,"ServiceName"),Region:r(t,"Region")}}}parseAccessKeys(e){return o(e,"AccessKeyMetadata","member").map((s)=>({UserName:r(s,"UserName"),AccessKeyId:r(s,"AccessKeyId")||"",Status:r(s,"Status")||"Active",CreateDate:r(s,"CreateDate")}))}async createInstanceProfile(e){let t=await this.request("CreateInstanceProfile",e);return this.parseInstanceProfile(t)}async getInstanceProfile(e){let t=await this.request("GetInstanceProfile",e);return this.parseInstanceProfile(t)}async listInstanceProfiles(e={}){let t=await this.request("ListInstanceProfiles",e),s=this.parseInstanceProfiles(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{InstanceProfiles:s,IsTruncated:a,Marker:i}}async listInstanceProfilesForRole(e){let t=await this.request("ListInstanceProfilesForRole",e),s=this.parseInstanceProfiles(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{InstanceProfiles:s,IsTruncated:a,Marker:i}}async addRoleToInstanceProfile(e){await this.request("AddRoleToInstanceProfile",e)}async removeRoleFromInstanceProfile(e){await this.request("RemoveRoleFromInstanceProfile",e)}async deleteInstanceProfile(e){await this.request("DeleteInstanceProfile",e)}parseInstanceProfile(e){return{InstanceProfileName:r(e,"InstanceProfileName")||"",InstanceProfileId:r(e,"InstanceProfileId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate")}}parseInstanceProfiles(e){return o(e,"InstanceProfiles","member").map((s)=>({InstanceProfileName:r(s,"InstanceProfileName")||"",InstanceProfileId:r(s,"InstanceProfileId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate")}))}async getAccountPasswordPolicy(){let e=await this.request("GetAccountPasswordPolicy");return{MinimumPasswordLength:r(e,"MinimumPasswordLength")?Number.parseInt(r(e,"MinimumPasswordLength"),10):void 0,RequireSymbols:r(e,"RequireSymbols")==="true",RequireNumbers:r(e,"RequireNumbers")==="true",RequireUppercaseCharacters:r(e,"RequireUppercaseCharacters")==="true",RequireLowercaseCharacters:r(e,"RequireLowercaseCharacters")==="true",AllowUsersToChangePassword:r(e,"AllowUsersToChangePassword")==="true",ExpirePasswords:r(e,"ExpirePasswords")==="true",MaxPasswordAge:r(e,"MaxPasswordAge")?Number.parseInt(r(e,"MaxPasswordAge"),10):void 0,PasswordReusePrevention:r(e,"PasswordReusePrevention")?Number.parseInt(r(e,"PasswordReusePrevention"),10):void 0,HardExpiry:r(e,"HardExpiry")==="true"}}async updateAccountPasswordPolicy(e){await this.request("UpdateAccountPasswordPolicy",e)}async deleteAccountPasswordPolicy(){await this.request("DeleteAccountPasswordPolicy")}async getAccountSummary(){let e=await this.request("GetAccountSummary"),t={},s=o(e,"SummaryMap","entry");for(let a of s){let i=r(a,"key"),n=r(a,"value");if(i&&n)t[i]=Number.parseInt(n,10)}return t}async listAccountAliases(){let e=await this.request("ListAccountAliases"),t=o(e,"AccountAliases","member"),s=r(e,"IsTruncated")==="true",a=r(e,"Marker");return{AccountAliases:t,IsTruncated:s,Marker:a}}async createAccountAlias(e){await this.request("CreateAccountAlias",e)}async deleteAccountAlias(e){await this.request("DeleteAccountAlias",e)}async simulatePrincipalPolicy(e){let t=await this.request("SimulatePrincipalPolicy",e);return this.parseSimulationResults(t)}parseSimulationResults(e){let s=o(e,"EvaluationResults","member").map((n)=>{let u=o(n,"MatchedStatements","member").map((l)=>({SourcePolicyId:r(l,"SourcePolicyId"),SourcePolicyType:r(l,"SourcePolicyType")}));return{EvalActionName:r(n,"EvalActionName")||"",EvalResourceName:r(n,"EvalResourceName"),EvalDecision:r(n,"EvalDecision")||"",MatchedStatements:u.length>0?u:void 0}}),a=r(e,"IsTruncated")==="true",i=r(e,"Marker");return{EvaluationResults:s,IsTruncated:a,Marker:i}}}class p{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new d(t)}async createEmailIdentity(e){return await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/identities",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async getEmailIdentity(e){let t=await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/identities/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}});return{IdentityType:t.IdentityType,IdentityName:e,SendingEnabled:t.VerifiedForSendingStatus,VerificationStatus:t.VerificationStatus,DkimAttributes:t.DkimAttributes,MailFromAttributes:t.MailFromAttributes}}async putEmailIdentityMailFromAttributes(e,t){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(e)}/mail-from`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async listEmailIdentities(e){let t="/v2/email/identities",s=[];if(e?.PageSize)s.push(`PageSize=${e.PageSize}`);if(e?.NextToken)s.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(s.length>0)t+=`?${s.join("&")}`;let a=await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}});return{EmailIdentities:a.EmailIdentities,NextToken:a.NextToken}}async deleteEmailIdentity(e){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/identities/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async putEmailIdentityDkimAttributes(e){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(e.EmailIdentity)}/dkim`,headers:{"Content-Type":"application/json"},body:JSON.stringify({SigningEnabled:e.SigningEnabled})})}async sendEmail(e){return{MessageId:(await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/outbound-emails",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).MessageId}}async sendBulkEmail(e){return{BulkEmailEntryResults:(await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/outbound-bulk-emails",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).BulkEmailEntryResults}}async createEmailTemplate(e){await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/templates",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async getEmailTemplate(e){return await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/templates/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async deleteEmailTemplate(e){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/templates/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async listEmailTemplates(e){let t="/v2/email/templates",s=[];if(e?.PageSize)s.push(`PageSize=${e.PageSize}`);if(e?.NextToken)s.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(s.length>0)t+=`?${s.join("&")}`;return await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}})}async getSendStatistics(){return{SendDataPoints:(await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendStatistics&Version=2010-12-01"})).GetSendStatisticsResponse?.GetSendStatisticsResult?.SendDataPoints?.member}}async getSendQuota(){let t=(await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendQuota&Version=2010-12-01"})).GetSendQuotaResponse?.GetSendQuotaResult;return{Max24HourSend:t?.Max24HourSend?Number(t.Max24HourSend):void 0,MaxSendRate:t?.MaxSendRate?Number(t.MaxSendRate):void 0,SentLast24Hours:t?.SentLast24Hours?Number(t.SentLast24Hours):void 0}}async verifyDomain(e){let t=await this.createEmailIdentity({EmailIdentity:e});return{dkimTokens:t.DkimAttributes?.Tokens,verificationStatus:t.DkimAttributes?.Status}}async sendSimpleEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],s=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0,a={};if(e.text)a.Text={Data:e.text};if(e.html)a.Html={Data:e.html};return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Simple:{Subject:{Data:e.subject},Body:a}},ReplyToAddresses:s})}async sendTemplatedEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],s=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0;return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Template:{TemplateName:e.templateName,TemplateData:JSON.stringify(e.templateData)}},ReplyToAddresses:s})}async getDkimRecords(e){let t=await this.getEmailIdentity(e);if(!t.DkimAttributes?.Tokens)return[];return t.DkimAttributes.Tokens.map((s)=>({name:`${s}._domainkey.${e}`,type:"CNAME",value:`${s}.dkim.amazonses.com`}))}async isDomainVerified(e){try{let t=await this.getEmailIdentity(e);return t.VerificationStatus==="SUCCESS"&&t.SendingEnabled===!0}catch{return!1}}async waitForDomainVerification(e,t=60,s=30000){for(let a=0;a<t;a++){if(await this.isDomainVerified(e))return!0;await new Promise((n)=>setTimeout(n,s))}return!1}buildFormBody(e){return Object.entries(e).filter(([,s])=>s!==void 0).map(([s,a])=>`${encodeURIComponent(s)}=${encodeURIComponent(a)}`).join("&")}async createReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"CreateReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async deleteReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async setActiveReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"SetActiveReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async listReceiptRuleSets(e){let t={Action:"ListReceiptRuleSets",Version:"2010-12-01"};if(e)t.NextToken=e;let s=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)}),a=s?.ListReceiptRuleSetsResponse?.ListReceiptRuleSetsResult||s?.ListReceiptRuleSetsResult,i=a?.RuleSets?.member;return{RuleSets:Array.isArray(i)?i:i?[i]:[],NextToken:a?.NextToken}}async describeReceiptRuleSet(e){let t=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DescribeReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})}),s=t?.DescribeReceiptRuleSetResponse?.DescribeReceiptRuleSetResult||t?.DescribeReceiptRuleSetResult,a=s?.Rules?.member;return{Metadata:s?.Metadata,Rules:Array.isArray(a)?a:a?[a]:[]}}async createReceiptRule(e){let t={Action:"CreateReceiptRule",Version:"2010-12-01",RuleSetName:e.RuleSetName,"Rule.Name":e.Rule.Name,"Rule.Enabled":e.Rule.Enabled!==!1?"true":"false"};if(e.Rule.TlsPolicy)t["Rule.TlsPolicy"]=e.Rule.TlsPolicy;if(e.Rule.ScanEnabled!==void 0)t["Rule.ScanEnabled"]=e.Rule.ScanEnabled?"true":"false";if(e.After)t.After=e.After;if(e.Rule.Recipients)e.Rule.Recipients.forEach((s,a)=>{t[`Rule.Recipients.member.${a+1}`]=s});e.Rule.Actions.forEach((s,a)=>{let i=a+1;if(s.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=s.S3Action.BucketName,s.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=s.S3Action.ObjectKeyPrefix;if(s.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=s.S3Action.KmsKeyArn}if(s.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=s.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=s.LambdaAction.InvocationType||"Event";if(s.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=s.SNSAction.TopicArn,s.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=s.SNSAction.Encoding}if(s.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=s.StopAction.Scope,s.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=s.StopAction.TopicArn}}),await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)})}async deleteReceiptRule(e,t){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteReceiptRule",Version:"2010-12-01",RuleSetName:e,RuleName:t})})}async receiptRuleSetExists(e){try{return await this.describeReceiptRuleSet(e),!0}catch(t){if(t.code==="RuleSetDoesNotExist"||t.statusCode===400)return!1;throw t}}async getActiveReceiptRuleSet(){let e=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DescribeActiveReceiptRuleSet",Version:"2010-12-01"})}),t=e?.DescribeActiveReceiptRuleSetResponse?.DescribeActiveReceiptRuleSetResult||e?.DescribeActiveReceiptRuleSetResult;if(!t?.Metadata)return null;let s=t?.Rules?.member;return{Metadata:t?.Metadata,Rules:Array.isArray(s)?s:s?[s]:[]}}async updateReceiptRule(e){let t={Action:"UpdateReceiptRule",Version:"2010-12-01",RuleSetName:e.RuleSetName,"Rule.Name":e.Rule.Name};if(e.Rule.Enabled!==void 0)t["Rule.Enabled"]=e.Rule.Enabled?"true":"false";if(e.Rule.TlsPolicy)t["Rule.TlsPolicy"]=e.Rule.TlsPolicy;if(e.Rule.ScanEnabled!==void 0)t["Rule.ScanEnabled"]=e.Rule.ScanEnabled?"true":"false";if(e.Rule.Recipients)e.Rule.Recipients.forEach((s,a)=>{t[`Rule.Recipients.member.${a+1}`]=s});e.Rule.Actions.forEach((s,a)=>{let i=a+1;if(s.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=s.S3Action.BucketName,s.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=s.S3Action.ObjectKeyPrefix;if(s.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=s.S3Action.KmsKeyArn}if(s.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=s.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=s.LambdaAction.InvocationType||"Event";if(s.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=s.SNSAction.TopicArn,s.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=s.SNSAction.Encoding}if(s.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=s.StopAction.Scope,s.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=s.StopAction.TopicArn}}),await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)})}async sendRawEmail(e){let t=Buffer.from(e.rawMessage).toString("base64"),s={Action:"SendRawEmail",Version:"2010-12-01",Source:e.source,"RawMessage.Data":t};e.destinations.forEach((n,c)=>{s[`Destinations.member.${c+1}`]=n});let a=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(s)});return{MessageId:(a?.SendRawEmailResponse?.SendRawEmailResult||a?.SendRawEmailResult)?.MessageId}}async getSuppressedDestination(e){try{return(await this.client.request({service:"ses",region:this.region,method:"GET",path:`/v2/email/suppression/addresses/${encodeURIComponent(e)}`}))?.SuppressedDestination||null}catch(t){if(t.message?.includes("404")||t.message?.includes("NotFoundException"))return null;throw t}}async deleteSuppressedDestination(e){await this.client.request({service:"ses",region:this.region,method:"DELETE",path:`/v2/email/suppression/addresses/${encodeURIComponent(e)}`})}}class h{ses;s3;iam;route53;region;domain;defaultFrom;constructor(e={}){this.region=e.region||"us-east-1",this.domain=e.domain,this.defaultFrom=e.defaultFrom,this.ses=new p(this.region),this.s3=new A(this.region),this.iam=new g(this.region),this.route53=new P(this.region)}async send(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required. Set defaultFrom in constructor or provide from in options.");let s=e.fromName?`${e.fromName} <${t}>`:t,a=Array.isArray(e.to)?e.to:[e.to];if(!e.attachments||e.attachments.length===0)return{messageId:(await this.ses.sendSimpleEmail({from:s,to:a,subject:e.subject,text:e.text,html:e.html,replyTo:e.replyTo})).MessageId||""};let i=this.buildRawEmail(e,s,a);return{messageId:(await this.ses.sendEmail({FromEmailAddress:s,Destination:{ToAddresses:a,CcAddresses:e.cc?Array.isArray(e.cc)?e.cc:[e.cc]:void 0,BccAddresses:e.bcc?Array.isArray(e.bcc)?e.bcc:[e.bcc]:void 0},Content:{Raw:{Data:Buffer.from(i).toString("base64")}}})).MessageId||""}}async sendTemplate(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required");let s=e.fromName?`${e.fromName} <${t}>`:t;return{messageId:(await this.ses.sendTemplatedEmail({from:s,to:e.to,templateName:e.templateName,templateData:e.templateData,replyTo:e.replyTo})).MessageId||""}}async sendBulk(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required");let s=e.recipients.map((i)=>({Destination:{ToAddresses:Array.isArray(i.to)?i.to:[i.to]},ReplacementEmailContent:i.templateData?{ReplacementTemplate:{ReplacementTemplateData:JSON.stringify(i.templateData)}}:void 0}));return{results:(await this.ses.sendBulkEmail({FromEmailAddress:t,BulkEmailEntries:s,DefaultContent:{Template:{TemplateName:e.templateName,TemplateData:JSON.stringify(e.defaultTemplateData)}}})).BulkEmailEntryResults?.map((i)=>({status:i.Status||"UNKNOWN",messageId:i.MessageId,error:i.Error}))||[]}}async setupDomain(e){let t;try{t=await this.ses.getEmailIdentity(e)}catch{let a=await this.ses.createEmailIdentity({EmailIdentity:e});t={VerificationStatus:a.DkimAttributes?.Status,DkimAttributes:a.DkimAttributes,SendingEnabled:a.VerifiedForSendingStatus}}try{await this.ses.putEmailIdentityDkimAttributes({EmailIdentity:e,SigningEnabled:!0})}catch{}try{await this.ses.putEmailIdentityMailFromAttributes(e,{MailFromDomain:`mail.${e}`,BehaviorOnMxFailure:"USE_DEFAULT_VALUE"})}catch{}let s=await this.ses.getDkimRecords(e);return{domainVerified:t.SendingEnabled===!0,dkimStatus:t.DkimAttributes?.Status||"UNKNOWN",dkimTokens:t.DkimAttributes?.Tokens,mailFromStatus:t.MailFromAttributes?.MailFromDomainStatus}}async getDnsRecords(e){let t=[],s=await this.ses.getDkimRecords(e);for(let a of s)t.push({type:a.type,name:a.name,value:a.value,ttl:1800});return t.push({type:"MX",name:e,value:`inbound-smtp.${this.region}.amazonaws.com`,priority:10,ttl:3600}),t.push({type:"MX",name:`mail.${e}`,value:`feedback-smtp.${this.region}.amazonses.com`,priority:10,ttl:3600}),t.push({type:"TXT",name:`mail.${e}`,value:"v=spf1 include:amazonses.com ~all",ttl:3600}),t.push({type:"TXT",name:`_dmarc.${e}`,value:`v=DMARC1;p=quarantine;pct=25;rua=mailto:dmarcreports@${e}`,ttl:3600}),t}async isDomainReady(e){try{let t=await this.ses.getEmailIdentity(e);return t.SendingEnabled===!0&&t.DkimAttributes?.Status==="SUCCESS"}catch{return!1}}async setupReceiving(e){let t={Version:"2012-10-17",Statement:[{Sid:"AllowSESPuts",Effect:"Allow",Principal:{Service:"ses.amazonaws.com"},Action:"s3:PutObject",Resource:`arn:aws:s3:::${e.bucketName}/*`,Condition:{StringEquals:{"AWS:SourceAccount":e.accountId}}}]};await this.s3.putBucketPolicy(e.bucketName,t);try{await this.ses.createReceiptRuleSet(e.ruleSetName)}catch(a){if(!a.message?.includes("already exists")&&a.code!=="AlreadyExists")throw a}let s=[{S3Action:{BucketName:e.bucketName,ObjectKeyPrefix:e.prefix||"inbox/"}}];if(e.lambdaArn)s.push({LambdaAction:{FunctionArn:e.lambdaArn,InvocationType:"Event"}});try{await this.ses.createReceiptRule({RuleSetName:e.ruleSetName,Rule:{Name:e.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:e.recipients||[e.domain],ScanEnabled:e.scanEnabled!==!1,Actions:s}})}catch(a){if(a.message?.includes("already exists"))await this.ses.deleteReceiptRule(e.ruleSetName,e.ruleName),await this.ses.createReceiptRule({RuleSetName:e.ruleSetName,Rule:{Name:e.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:e.recipients||[e.domain],ScanEnabled:e.scanEnabled!==!1,Actions:s}});else throw a}await this.ses.setActiveReceiptRuleSet(e.ruleSetName)}async getIncomingEmails(e){return(await this.s3.list({bucket:e.bucket,prefix:e.prefix||"incoming/",maxKeys:e.maxResults||100})).map((s)=>({key:s.Key||"",lastModified:s.LastModified||"",size:s.Size||0}))}async readEmail(e){return await this.s3.getObject(e.bucket,e.key)}async createSmtpCredentials(e){let t=`ses-smtp-${e.username.replace(/[^a-zA-Z0-9]/g,"-")}`,{AWSClient:s}=await import("./chunk-y2v22hkv.js"),a=new s,i=(m,S)=>{let f={Action:m,Version:"2010-05-08",...S};return Object.entries(f).map(([b,T])=>`${encodeURIComponent(b)}=${encodeURIComponent(T)}`).join("&")};try{await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateUser",{UserName:t})})}catch(m){if(!m.message?.includes("EntityAlreadyExists"))throw m}let n={Version:"2012-10-17",Statement:[{Effect:"Allow",Action:"ses:SendRawEmail",Resource:"*",Condition:{StringLike:{"ses:FromAddress":`*@${e.domain}`}}}]},c=`ses-smtp-policy-${e.domain.replace(/\./g,"-")}`;try{await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("PutUserPolicy",{UserName:t,PolicyName:c,PolicyDocument:JSON.stringify(n)})})}catch{}let l=(await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateAccessKey",{UserName:t})}))?.CreateAccessKeyResult?.AccessKey;if(!l?.AccessKeyId||!l?.SecretAccessKey)throw Error("Failed to create access key");let R=this.deriveSmtpPassword(l.SecretAccessKey);return{username:l.AccessKeyId,password:R,server:`email-smtp.${this.region}.amazonaws.com`,port:587}}deriveSmtpPassword(e){let t=y("node:crypto"),s="SendRawEmail",a=Buffer.from([4]),i=t.createHmac("sha256",`AWS4${e}`).update("11111111").digest();return i=t.createHmac("sha256",i).update(this.region).digest(),i=t.createHmac("sha256",i).update("ses").digest(),i=t.createHmac("sha256",i).update("aws4_request").digest(),i=t.createHmac("sha256",i).update("SendRawEmail").digest(),Buffer.concat([a,i]).toString("base64")}async createTemplate(e){await this.ses.createEmailTemplate({TemplateName:e.name,TemplateContent:{Subject:e.subject,Text:e.text,Html:e.html}})}async getTemplate(e){try{let t=await this.ses.getEmailTemplate(e);return{name:t.TemplateName||e,subject:t.TemplateContent?.Subject,text:t.TemplateContent?.Text,html:t.TemplateContent?.Html}}catch{return null}}async deleteTemplate(e){await this.ses.deleteEmailTemplate(e)}async listTemplates(){return(await this.ses.listEmailTemplates()).TemplatesMetadata?.map((t)=>({name:t.TemplateName||"",createdAt:t.CreatedTimestamp}))||[]}async deploy(e){let t=`${e.appName}-${e.environment}-email-rules`,s=`${e.appName}-inbound-email`,a=e.storage?.bucketName||`${e.appName}-${e.environment}-email`,i=await this.setupDomain(e.domain);if(!(await this.s3.listBuckets()).Buckets?.some((l)=>l.Name===a))await this.s3.createBucket(a);await this.setupReceiving({domain:e.domain,ruleSetName:t,ruleName:s,bucketName:a,prefix:e.storage?.prefix||"inbox/",accountId:e.accountId,recipients:e.catchAll?[e.domain]:e.mailboxes,scanEnabled:!0});let u=await this.getDnsRecords(e.domain);return{success:!0,domainVerified:i.domainVerified,dkimStatus:i.dkimStatus,receiptRuleSet:t,storageBucket:a,dnsRecords:u}}async undeploy(e){let t=`${e.appName}-${e.environment}-email-rules`,s=`${e.appName}-inbound-email`,a=`${e.appName}-${e.environment}-email`;try{await this.ses.deleteReceiptRule(t,s)}catch{}try{await this.ses.deleteReceiptRuleSet(t)}catch{}if(e.deleteBucket)try{await this.s3.emptyAndDeleteBucket(a)}catch{}}async getSendingStats(){let e=await this.ses.getSendQuota();return{sentLast24Hours:e.SentLast24Hours||0,maxSendRate:e.MaxSendRate||0,max24HourSend:e.Max24HourSend||0}}buildRawEmail(e,t,s){let a=`----=_Part_${Date.now()}_${Math.random().toString(36).substring(2)}`,i="";if(i+=`From: ${t}\r
2
2
  `,i+=`To: ${s.join(", ")}\r
3
3
  `,e.cc){let n=Array.isArray(e.cc)?e.cc:[e.cc];i+=`Cc: ${n.join(", ")}\r
4
4
  `}if(i+=`Subject: ${e.subject}\r
@@ -0,0 +1 @@
1
+ import{Id as a}from"./chunk-3mgj3hrh.js";import"./chunk-73ztr55z.js";import"./chunk-mz0dk78z.js";import"./chunk-jm5mg890.js";import"./chunk-13qjvbqh.js";export{a as buildAndPushServerlessImage};
@@ -1,4 +1,4 @@
1
- import{Vh as is,Wh as yr}from"./chunk-aj025v2s.js";import{Xh as ss}from"./chunk-wavjkdb8.js";import{Zh as ns}from"./chunk-nk7sav4r.js";import{rl as Bn}from"./chunk-hn40z11p.js";import{yl as Fn}from"./chunk-x3hay61c.js";import{$l as $e,Fn as pt,In as Us,Jn as Zr,Vl as rn,Wl as nn,Zl as An,_l as Ln,bm as wt,cm as Yn,dm as fi,em as Fe,lm as A}from"./chunk-zz52xje8.js";import{Ct as ho}from"./chunk-z2qqwy7e.js";import{readFileSync as os}from"node:fs";import{join as Ho}from"node:path";function qc(e={}){let t=new Set;for(let r of Object.values(e)){if(!r.domain)continue;if(r.redirect||r.deploy==="server"||r.start)t.add(r.domain)}return t}function qt(e){return e.replace(/\.$/,"").toLowerCase()}function yi(e,t,r){let n=qt(e.name),s=qt(t),i=qt(r),o=i===s?"@":i.endsWith(`.${s}`)?i.slice(0,-(s.length+1)):i;return n===i||n===o||o==="@"&&(n===""||n===s)}async function $i(e,t,r,n,s="A"){let i=await e.listRecords(t);if(!i.success)return[`could not list ${s} records: ${i.message||"unknown provider error"}`];let o=i.records.filter((l)=>l.type===s&&yi(l,t,r)),a=o.findIndex((l)=>l.content===n);if(o.length<=1||a===-1)return[];let c=[];for(let[l,d]of o.entries()){if(l===a)continue;let m=await e.deleteRecord(t,d);if(!m.success)c.push(`could not remove stale ${d.name} ${s} ${d.content}: ${m.message||"unknown provider error"}`)}return c}function me(e){if(!e)return;let t=e.trim();if(!t)return;if(!t.includes("/"))return t;let[r]=t.split("/");if(!r.endsWith("::"))return r||void 0;return`${r}1`}var bi=new Set(["mail","smtp","imap","mx"]);function _i(e){return!bi.has(e.split(".")[0]??"")}async function Wc(e){let{provider:t,zone:r,fqdn:n,ipv4:s,ipv6:i,ttl:o=600}=e,a={published:[],warnings:[]},c=[{type:"A",content:s}];if(i&&_i(n))c.push({type:"AAAA",content:i});for(let{type:l,content:d}of c){let m=await t.upsertRecord(r,{name:n,type:l,content:d,ttl:o});if(m?.success===!1){a.warnings.push(`${n} → ${d} failed: ${m.error||m.message||"unknown error"}`);continue}if(a.warnings.push(...(await $i(t,r,n,d,l)).map((u)=>`${n} cleanup: ${u}`)),await wi(t,r,n,d,l))a.published.push({fqdn:n,type:l,content:d});else a.warnings.push(`${n} → ${d} reported success at ${t.name} but no matching ${l} record exists — create it manually: ${l} ${n} → ${d}`)}return a}async function wi(e,t,r,n,s){try{if(typeof e?.listRecords!=="function")return!0;let i=await e.listRecords(t);if(!i?.success||!Array.isArray(i.records))return!0;return i.records.some((o)=>{let a=typeof o?.name==="string"?o.name.replace(/\.$/,""):"";return o?.type===s&&a===r&&o?.content===n})}catch{return!0}}function Ti(e){return e.length>4000?`…
1
+ import{Vh as is,Wh as yr}from"./chunk-aj025v2s.js";import{Xh as ss}from"./chunk-wavjkdb8.js";import{Zh as ns}from"./chunk-152he7m3.js";import{rl as Bn}from"./chunk-hn40z11p.js";import{yl as Fn}from"./chunk-x3hay61c.js";import{$l as $e,Fn as pt,In as Us,Jn as Zr,Vl as rn,Wl as nn,Zl as An,_l as Ln,bm as wt,cm as Yn,dm as fi,em as Fe,lm as A}from"./chunk-jm5mg890.js";import{Et as ho}from"./chunk-13qjvbqh.js";import{readFileSync as os}from"node:fs";import{join as Ho}from"node:path";function qc(e={}){let t=new Set;for(let r of Object.values(e)){if(!r.domain)continue;if(r.redirect||r.deploy==="server"||r.start)t.add(r.domain)}return t}function qt(e){return e.replace(/\.$/,"").toLowerCase()}function yi(e,t,r){let n=qt(e.name),s=qt(t),i=qt(r),o=i===s?"@":i.endsWith(`.${s}`)?i.slice(0,-(s.length+1)):i;return n===i||n===o||o==="@"&&(n===""||n===s)}async function $i(e,t,r,n,s="A"){let i=await e.listRecords(t);if(!i.success)return[`could not list ${s} records: ${i.message||"unknown provider error"}`];let o=i.records.filter((l)=>l.type===s&&yi(l,t,r)),a=o.findIndex((l)=>l.content===n);if(o.length<=1||a===-1)return[];let c=[];for(let[l,d]of o.entries()){if(l===a)continue;let m=await e.deleteRecord(t,d);if(!m.success)c.push(`could not remove stale ${d.name} ${s} ${d.content}: ${m.message||"unknown provider error"}`)}return c}function me(e){if(!e)return;let t=e.trim();if(!t)return;if(!t.includes("/"))return t;let[r]=t.split("/");if(!r.endsWith("::"))return r||void 0;return`${r}1`}var bi=new Set(["mail","smtp","imap","mx"]);function _i(e){return!bi.has(e.split(".")[0]??"")}async function Wc(e){let{provider:t,zone:r,fqdn:n,ipv4:s,ipv6:i,ttl:o=600}=e,a={published:[],warnings:[]},c=[{type:"A",content:s}];if(i&&_i(n))c.push({type:"AAAA",content:i});for(let{type:l,content:d}of c){let m=await t.upsertRecord(r,{name:n,type:l,content:d,ttl:o});if(m?.success===!1){a.warnings.push(`${n} → ${d} failed: ${m.error||m.message||"unknown error"}`);continue}if(a.warnings.push(...(await $i(t,r,n,d,l)).map((u)=>`${n} cleanup: ${u}`)),await wi(t,r,n,d,l))a.published.push({fqdn:n,type:l,content:d});else a.warnings.push(`${n} → ${d} reported success at ${t.name} but no matching ${l} record exists — create it manually: ${l} ${n} → ${d}`)}return a}async function wi(e,t,r,n,s){try{if(typeof e?.listRecords!=="function")return!0;let i=await e.listRecords(t);if(!i?.success||!Array.isArray(i.records))return!0;return i.records.some((o)=>{let a=typeof o?.name==="string"?o.name.replace(/\.$/,""):"";return o?.type===s&&a===r&&o?.content===n})}catch{return!0}}function Ti(e){return e.length>4000?`…
2
2
  ${e.slice(-4000)}`:e}function mt(e,t){let r=e.filter((o)=>o.status!=="Success");if(r.length===0)return t;let n=r.slice(0,3).map((o)=>{let a=(o.error||o.output||"").trim(),c=`${o.instanceId}: ${o.status}`;return a?`${c}
3
3
  ${Ti(a)}`:c}),s=r.length-n.length,i=s>0?[`(+${s} more instance${s===1?"":"s"} failed)`]:[];return[t,...n,...i].join(`
4
4
  `)}function Pi(e){let t=2166136261,r=16777619;for(let n=0;n<e.length;n++){let s=e.charCodeAt(n);t=Math.imul(t^s,16777619)>>>0,r=Math.imul(r+s,2246822507)>>>0}return`${t.toString(36)}${r.toString(36)}`.padEnd(12,"0").slice(0,12)}function xi(e,t,r={}){let n=r.mode??"testing",s=r.maxAge??604800,i=r.mx?.length?r.mx:[e.hostname],o=`${["version: STSv1",`mode: ${n}`,...i.map((c)=>`mx: ${c}`),`max_age: ${s}`].join(`\r
@@ -17,7 +17,7 @@ EOF`,`DISK_PCT=$(df -P / | awk 'NR==2{gsub("%","",$5); print $5}')`,"UPTIME_SEC=
17
17
  `)}
18
18
  `}return`${["server {"," listen 80;"," listen [::]:80;",` server_name ${r};`,...n,"}"].join(`
19
19
  `)}
20
- `}function ar(e){let t=`/etc/nginx/sites-available/${e.siteName}`,r=`/etc/nginx/sites-enabled/${e.siteName}`,n=go(e),s=[...cr()];if(e.auth){let i=Dn(e.siteName),o=(l)=>l.split("'").join("'\\''"),a=o(e.auth.password),c=o(e.auth.username);s.push(`TS_CLOUD_HTPASS=$(openssl passwd -apr1 '${a}')`,`printf '%s:%s\\n' '${c}' "$TS_CLOUD_HTPASS" > ${i}`,`chmod 640 ${i}`,`chown root:www-data ${i} 2>/dev/null || true`)}return s.push(`cat > ${t} <<'TS_CLOUD_NGINX_EOF'`,n.replace(/\n$/,""),"TS_CLOUD_NGINX_EOF",`ln -sf ${t} ${r}`,"rm -f /etc/nginx/sites-enabled/default",`${he} -t`,"systemctl reload ts-cloud-nginx 2>/dev/null || systemctl restart ts-cloud-nginx 2>/dev/null || true"),s}var he="/usr/local/bin/ts-cloud-nginx";function cr(e="/opt/pantry"){return[...gt(),...re(["nginx.org"]),"mkdir -p /etc/nginx/sites-available /etc/nginx/sites-enabled /var/log/nginx /var/lib/nginx/body /var/lib/nginx/proxy /var/lib/nginx/fastcgi /var/lib/nginx/uwsgi /var/lib/nginx/scgi","getent passwd www-data >/dev/null || useradd --system --no-create-home --shell /usr/sbin/nologin www-data","chown -R www-data:www-data /var/lib/nginx /var/log/nginx",`cat > ${he} <<'TS_CLOUD_NGINXBIN_EOF'`,"#!/bin/sh",`eval "$(cd ${e} && pantry env 2>/dev/null)"`,"NGINX_BIN=/opt/pantry/pantry/.bin/nginx",'if [ ! -x "$NGINX_BIN" ]; then NGINX_BIN=$(command -v nginx || true); fi','if [ -z "$NGINX_BIN" ]; then echo "nginx binary not found; run pantry install nginx.org or install nginx explicitly" >&2; exit 1; fi','exec "$NGINX_BIN" -c /etc/nginx/nginx.conf "$@"',"TS_CLOUD_NGINXBIN_EOF",`chmod +x ${he}`,"cat > /etc/nginx/fastcgi_params <<'TS_CLOUD_FCGI_EOF'","fastcgi_param QUERY_STRING $query_string;","fastcgi_param REQUEST_METHOD $request_method;","fastcgi_param CONTENT_TYPE $content_type;","fastcgi_param CONTENT_LENGTH $content_length;","fastcgi_param SCRIPT_NAME $fastcgi_script_name;","fastcgi_param REQUEST_URI $request_uri;","fastcgi_param DOCUMENT_URI $document_uri;","fastcgi_param DOCUMENT_ROOT $document_root;","fastcgi_param SERVER_PROTOCOL $server_protocol;","fastcgi_param REQUEST_SCHEME $scheme;","fastcgi_param HTTPS $https if_not_empty;","fastcgi_param GATEWAY_INTERFACE CGI/1.1;","fastcgi_param SERVER_SOFTWARE nginx/$nginx_version;","fastcgi_param REMOTE_ADDR $remote_addr;","fastcgi_param REMOTE_PORT $remote_port;","fastcgi_param SERVER_ADDR $server_addr;","fastcgi_param SERVER_PORT $server_port;","fastcgi_param SERVER_NAME $server_name;","fastcgi_param REDIRECT_STATUS 200;","TS_CLOUD_FCGI_EOF","cat > /etc/nginx/nginx.conf <<'TS_CLOUD_NGINXCONF_EOF'","user www-data;","worker_processes auto;","pid /run/nginx.pid;","error_log /var/log/nginx/error.log;","events { worker_connections 1024; }","http {"," default_type application/octet-stream;"," types {"," text/html html htm;"," text/css css;"," application/javascript js;"," application/json json;"," image/svg+xml svg;"," image/png png;"," image/jpeg jpg jpeg;"," image/gif gif;"," image/x-icon ico;"," image/webp webp;"," font/woff2 woff2;"," font/woff woff;"," text/plain txt;"," }"," access_log /var/log/nginx/access.log;"," sendfile on;"," tcp_nopush on;"," keepalive_timeout 65;"," server_tokens off;"," client_max_body_size 100m;"," client_body_temp_path /var/lib/nginx/body;"," proxy_temp_path /var/lib/nginx/proxy;"," fastcgi_temp_path /var/lib/nginx/fastcgi;"," uwsgi_temp_path /var/lib/nginx/uwsgi;"," scgi_temp_path /var/lib/nginx/scgi;"," server {"," listen 80 default_server;"," listen [::]:80 default_server;"," server_name _;"," return 444;"," }"," include /etc/nginx/sites-enabled/*;","}","TS_CLOUD_NGINXCONF_EOF","cat > /etc/systemd/system/ts-cloud-nginx.service <<'TS_CLOUD_NGINXUNIT_EOF'","[Unit]","Description=ts-cloud nginx (pantry)","After=network.target","","[Service]","Type=simple",`ExecStartPre=${he} -t`,`ExecStart=${he} -g 'daemon off;'`,`ExecReload=${he} -s reload`,"Restart=always","RestartSec=3","","[Install]","WantedBy=multi-user.target","TS_CLOUD_NGINXUNIT_EOF","systemctl daemon-reload","systemctl enable ts-cloud-nginx","ls /etc/nginx/sites-enabled/* >/dev/null 2>&1 && systemctl restart ts-cloud-nginx || true"]}function Ze(e,t){return!e.events||e.events.includes(t)}async function lr(e,t,r,n={}){if(!e)return[];let s=n.fetchImpl??globalThis.fetch,i=[],o=[],a=(c,l)=>s(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)}).catch(()=>{return});if(e.slack?.webhookUrl&&Ze(e,t))i.push("slack"),o.push(a(e.slack.webhookUrl,{text:r}));if(e.discord?.webhookUrl&&Ze(e,t))i.push("discord"),o.push(a(e.discord.webhookUrl,{content:r}));if(e.telegram?.botToken&&e.telegram.chatId&&Ze(e,t)){i.push("telegram");let c=`https://api.telegram.org/bot${e.telegram.botToken}/sendMessage`;o.push(a(c,{chat_id:e.telegram.chatId,text:r}))}if(e.webhook?.url&&Ze(e,t))if(i.push("webhook"),(e.webhook.method||"POST")==="GET"){let c=e.webhook.url.includes("?")?"&":"?",l=`${e.webhook.url}${c}event=${encodeURIComponent(t)}&message=${encodeURIComponent(r)}`;o.push(s(l,{method:"GET"}).catch(()=>{return}))}else o.push(a(e.webhook.url,{event:t,message:r}));if(e.email?.to&&Ze(e,t))i.push("email"),o.push(So(e.email,t,r));return await Promise.all(o),i}async function So(e,t,r){try{await(await import("./chunk-p10xt3jb.js")).email.send({to:e.to,from:e.from,subject:`[ts-cloud] ${t}`,text:r})}catch{}}function In(e,t){return t??e}function Ne(e){if(!e)return[];let t=[];if(e.slack?.webhookUrl)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"text\\":\\"$MSG\\"}" ${e.slack.webhookUrl} || true`);if(e.discord?.webhookUrl)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"content\\":\\"$MSG\\"}" ${e.discord.webhookUrl} || true`);if(e.telegram?.botToken&&e.telegram.chatId)t.push(`curl -fsS -X POST "https://api.telegram.org/bot${e.telegram.botToken}/sendMessage" --data-urlencode "chat_id=${e.telegram.chatId}" --data-urlencode "text=$MSG" || true`);if(e.webhook?.url)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"message\\":\\"$MSG\\"}" ${e.webhook.url} || true`);if(t.length===0)return[];return["cat > /usr/local/bin/ts-cloud-notify <<'TS_CLOUD_NOTIFY_EOF'","#!/bin/bash",'MSG="$1"',...t,"TS_CLOUD_NOTIFY_EOF","chmod +x /usr/local/bin/ts-cloud-notify"]}function ur(e,t){return`/var/www/${e}-${t}`}var vo=new Set(["laravel","php","statamic","wordpress"]);function et(e){return e.type!=null&&vo.has(e.type)}function pr(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 yo(e){return pr(e).length>0}function kn(e){if(e.deploy)return e.deploy;if(et(e))return"server";if(e.start)return"server";return"bucket"}function ie(e){if(e.redirect)return"redirect";if(yo(e))return"proxy";if(et(e))return"server-php";if(kn(e)==="bucket")return"bucket";return e.start?"server-app":"server-static"}function $o(e){return e.infrastructure?.compute!=null||Boolean(e.cloud?.attachTo?.trim())}function _l(e,t={}){let r=[],n=[],s=e.sites||{},i=$o(e),o=Ln(e);if(o)r.push(o);let a=new Map;for(let[c,l]of Object.entries(s)){if(!l)continue;let d=kn(l),m=ie(l);if(m==="redirect"){if(!l.domain)r.push(`Site '${c}' is a redirect site but has no \`domain\` to redirect from.`);if(!(typeof l.redirect==="string"?l.redirect:l.redirect?.to))r.push(`Site '${c}' is a redirect site but has no redirect target (\`redirect\` / \`redirect.to\`).`);if(!i)r.push(`Site '${c}' is a redirect site but no \`infrastructure.compute\` is configured to host the gateway that serves the redirect.`);let p=[];if(l.start)p.push("start");if(l.root)p.push("root");if(l.proxyTo)p.push("proxyTo");if(p.length>0)n.push(`Site '${c}' is a redirect site but also sets ${p.join(", ")}. These are ignored.`);continue}if(m==="proxy"){if(!l.domain)r.push(`Site '${c}' is a proxy site but has no \`domain\` to route from.`);if(!i)r.push(`Site '${c}' is a proxy site but no \`infrastructure.compute\` is configured to host the gateway that forwards it.`);let u=[];if(l.start)u.push("start");if(l.root)u.push("root");if(typeof l.port==="number")u.push("port");if(l.build)u.push("build");if(l.preStart&&l.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(d==="server"&&!l.start&&!l.root){r.push(`Site '${c}' sets deploy:'server' but declares neither \`start\` (dynamic app) nor \`root\` (static site to serve). Add one.`);continue}if(m==="server-php"){if(!i)r.push(`Site '${c}' is a PHP site (type:'${l.type}') but no \`infrastructure.compute\` is configured. Add a server (infrastructure.compute) with PHP provisioning.`);if(!l.repository?.url)r.push(`Site '${c}' is a PHP site (type:'${l.type}') but has no \`repository.url\` to clone. PHP sites deploy via git.`)}else if(m==="server-app"){if(!i)r.push(`Site '${c}' deploys to a server (deploy:'server'${l.deploy?"":" inferred from `start`"}) but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`);if(typeof l.port==="number"){let u=t.occupiedPorts?.get(l.port);if(u)r.push(`Site '${c}' wants port ${l.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 p=a.get(l.port);if(p)r.push(`Sites '${p}' and '${c}' both use port ${l.port}. Server apps sharing a box must use distinct ports.`);else a.set(l.port,c)}}else if(m==="server-static"){if(!l.root)r.push(`Site '${c}' is a server static site (deploy:'server', no \`start\`) but has no \`root\` directory to serve.`);if(!i)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(!l.root)r.push(`Site '${c}' deploys to a bucket but has no \`root\` directory to upload.`);let u=[];if(l.start)u.push("start");if(typeof l.port==="number")u.push("port");if(l.preStart&&l.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 wl(e){let t=ie(e);return t!=="bucket"&&t!=="redirect"&&t!=="proxy"}function Tl(e){return ie(e)==="bucket"}function Pl(e,t){if(An(e)==="serverless")return!0;let r=Object.entries(e.sites??{}).filter(([,s])=>s!=null),n=t?r.filter(([s])=>s===t):r;if(n.length===0)return!0;return!n.every(([,s])=>{let i=ie(s);return i==="redirect"||i==="proxy"})}var fr="/etc/rpx/certs";function gr(e){return e.split(".").length===2}function bo(e,t={}){let r=new Set;for(let n of Object.values(e)){if(!n?.domain)continue;if(ie(n)==="bucket")continue;r.add(n.domain)}if(t.autoWww!==!1)for(let n of[...r]){if(!gr(n))continue;r.add(`www.${n}`)}return[...r]}var _o=["1.1.1.1","8.8.8.8"],wo="/var/www/acme-challenge";function To(e){if(typeof e==="string")return{to:e};let t={to:e.to};if(e.status!=null)t.status=e.status;if(e.preservePath!=null)t.preservePath=e.preservePath;return t}function Po(e){let t=e.auth;if(!t||t.enabled===!1||!t.password)return;return{username:t.username||"admin",password:t.password,...t.realm?{realm:t.realm}:{}}}function Nn(e){if(!e||e==="/")return;let t=`/${e}`.replace(/\/+/g,"/").replace(/\/+$/,"");if(!t.startsWith("/"))t=`/${t}`;return t===""||t==="/"?void 0:t}function dr(e,t){let n=(t?`${e}${t}`:e).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return n.length>0?n:"rpx"}function xo(e,t){if(!t||t.length===0)return`localhost:${e}`;return t.map((r)=>`${r.privateIp??r.publicIp}:${e}`)}function Un(e,t,r){let n=(t.wwwRoot??"/var/www").replace(/\/+$/,""),s=t.slug??"app",i=t.proxy.certsDir??fr,o=t.proxy.loadBalancer,a=[],c=new Set;for(let[u,p]of Object.entries(e)){if(!p||!p.domain)continue;let f=ie(p);if(f==="bucket")continue;let y=Nn(p.path),v=dr(p.domain,y),h=Po(p);if(f==="redirect"){a.push({to:p.domain,path:y,redirect:To(p.redirect),id:v,...h?{auth:h}:{}}),c.add(p.domain);continue}if(f==="proxy"){let S=pr(p);if(S.length===0)continue;let g=S.length===1?S[0]:S;a.push({to:p.domain,path:y,from:g,id:v,...h?{auth:h}:{},...Array.isArray(g)&&o?{loadBalancer:o}:{}}),c.add(p.domain);continue}if(f==="server-app"){if(typeof p.port!=="number")continue;let S=xo(p.port,r);a.push({to:p.domain,path:y,from:S,id:v,...h?{auth:h}:{},...Array.isArray(S)&&o?{loadBalancer:o}:{}})}else a.push({to:p.domain,path:y,static:{dir:`${n}/${s}-${u}/current`,spa:p.spa??!1,pathRewriteStyle:p.pathRewriteStyle??"directory"},cleanUrls:p.pathRewriteStyle!=="flat",...h?{auth:h}:{},id:v});c.add(p.domain)}if(t.proxy.autoWww!==!1)for(let u of[...c]){if(!gr(u))continue;let p=`www.${u}`;if(c.has(p))continue;a.push({to:p,redirect:{to:`https://${u}`},id:dr(p)}),c.add(p)}a.sort((u,p)=>{if(u.to!==p.to)return u.to.localeCompare(p.to);return(p.path?.length??0)-(u.path?.length??0)});let l={proxies:a,productionCerts:{certsDir:i,certsDirServerNames:[...c]},https:!0,hostsManagement:!1,cleanup:{hosts:!1,certs:!1}};if(t.proxy.onDemandTls&&c.size>0)l.onDemandTls={enabled:!0,allowedSuffixes:[...c],email:t.proxy.onDemandTlsEmail,certsDir:i,staging:t.proxy.onDemandTlsStaging??!1};if(t.proxy.onDemandTls)l.acmeChallengeWebroot=t.proxy.acmeWebroot??wo;let d=t.proxy.cdn,m=d?.frontedHosts?.length?d.frontedHosts:[...c];if(d?.secret&&m.length>0)l.originGuard={header:d.secretHeader??"X-Origin-Verify",value:d.secret,hosts:m};return l}function ve(e,t){return Un(e,t)}function He(e,t,r){return Un(e,r,t)}function Co(e){return`// Generated by ts-cloud — rpx reverse-proxy gateway.
20
+ `}function ar(e){let t=`/etc/nginx/sites-available/${e.siteName}`,r=`/etc/nginx/sites-enabled/${e.siteName}`,n=go(e),s=[...cr()];if(e.auth){let i=Dn(e.siteName),o=(l)=>l.split("'").join("'\\''"),a=o(e.auth.password),c=o(e.auth.username);s.push(`TS_CLOUD_HTPASS=$(openssl passwd -apr1 '${a}')`,`printf '%s:%s\\n' '${c}' "$TS_CLOUD_HTPASS" > ${i}`,`chmod 640 ${i}`,`chown root:www-data ${i} 2>/dev/null || true`)}return s.push(`cat > ${t} <<'TS_CLOUD_NGINX_EOF'`,n.replace(/\n$/,""),"TS_CLOUD_NGINX_EOF",`ln -sf ${t} ${r}`,"rm -f /etc/nginx/sites-enabled/default",`${he} -t`,"systemctl reload ts-cloud-nginx 2>/dev/null || systemctl restart ts-cloud-nginx 2>/dev/null || true"),s}var he="/usr/local/bin/ts-cloud-nginx";function cr(e="/opt/pantry"){return[...gt(),...re(["nginx.org"]),"mkdir -p /etc/nginx/sites-available /etc/nginx/sites-enabled /var/log/nginx /var/lib/nginx/body /var/lib/nginx/proxy /var/lib/nginx/fastcgi /var/lib/nginx/uwsgi /var/lib/nginx/scgi","getent passwd www-data >/dev/null || useradd --system --no-create-home --shell /usr/sbin/nologin www-data","chown -R www-data:www-data /var/lib/nginx /var/log/nginx",`cat > ${he} <<'TS_CLOUD_NGINXBIN_EOF'`,"#!/bin/sh",`eval "$(cd ${e} && pantry env 2>/dev/null)"`,"NGINX_BIN=/opt/pantry/pantry/.bin/nginx",'if [ ! -x "$NGINX_BIN" ]; then NGINX_BIN=$(command -v nginx || true); fi','if [ -z "$NGINX_BIN" ]; then echo "nginx binary not found; run pantry install nginx.org or install nginx explicitly" >&2; exit 1; fi','exec "$NGINX_BIN" -c /etc/nginx/nginx.conf "$@"',"TS_CLOUD_NGINXBIN_EOF",`chmod +x ${he}`,"cat > /etc/nginx/fastcgi_params <<'TS_CLOUD_FCGI_EOF'","fastcgi_param QUERY_STRING $query_string;","fastcgi_param REQUEST_METHOD $request_method;","fastcgi_param CONTENT_TYPE $content_type;","fastcgi_param CONTENT_LENGTH $content_length;","fastcgi_param SCRIPT_NAME $fastcgi_script_name;","fastcgi_param REQUEST_URI $request_uri;","fastcgi_param DOCUMENT_URI $document_uri;","fastcgi_param DOCUMENT_ROOT $document_root;","fastcgi_param SERVER_PROTOCOL $server_protocol;","fastcgi_param REQUEST_SCHEME $scheme;","fastcgi_param HTTPS $https if_not_empty;","fastcgi_param GATEWAY_INTERFACE CGI/1.1;","fastcgi_param SERVER_SOFTWARE nginx/$nginx_version;","fastcgi_param REMOTE_ADDR $remote_addr;","fastcgi_param REMOTE_PORT $remote_port;","fastcgi_param SERVER_ADDR $server_addr;","fastcgi_param SERVER_PORT $server_port;","fastcgi_param SERVER_NAME $server_name;","fastcgi_param REDIRECT_STATUS 200;","TS_CLOUD_FCGI_EOF","cat > /etc/nginx/nginx.conf <<'TS_CLOUD_NGINXCONF_EOF'","user www-data;","worker_processes auto;","pid /run/nginx.pid;","error_log /var/log/nginx/error.log;","events { worker_connections 1024; }","http {"," default_type application/octet-stream;"," types {"," text/html html htm;"," text/css css;"," application/javascript js;"," application/json json;"," image/svg+xml svg;"," image/png png;"," image/jpeg jpg jpeg;"," image/gif gif;"," image/x-icon ico;"," image/webp webp;"," font/woff2 woff2;"," font/woff woff;"," text/plain txt;"," }"," access_log /var/log/nginx/access.log;"," sendfile on;"," tcp_nopush on;"," keepalive_timeout 65;"," server_tokens off;"," client_max_body_size 100m;"," client_body_temp_path /var/lib/nginx/body;"," proxy_temp_path /var/lib/nginx/proxy;"," fastcgi_temp_path /var/lib/nginx/fastcgi;"," uwsgi_temp_path /var/lib/nginx/uwsgi;"," scgi_temp_path /var/lib/nginx/scgi;"," server {"," listen 80 default_server;"," listen [::]:80 default_server;"," server_name _;"," return 444;"," }"," include /etc/nginx/sites-enabled/*;","}","TS_CLOUD_NGINXCONF_EOF","cat > /etc/systemd/system/ts-cloud-nginx.service <<'TS_CLOUD_NGINXUNIT_EOF'","[Unit]","Description=ts-cloud nginx (pantry)","After=network.target","","[Service]","Type=simple",`ExecStartPre=${he} -t`,`ExecStart=${he} -g 'daemon off;'`,`ExecReload=${he} -s reload`,"Restart=always","RestartSec=3","","[Install]","WantedBy=multi-user.target","TS_CLOUD_NGINXUNIT_EOF","systemctl daemon-reload","systemctl enable ts-cloud-nginx","ls /etc/nginx/sites-enabled/* >/dev/null 2>&1 && systemctl restart ts-cloud-nginx || true"]}function Ze(e,t){return!e.events||e.events.includes(t)}async function lr(e,t,r,n={}){if(!e)return[];let s=n.fetchImpl??globalThis.fetch,i=[],o=[],a=(c,l)=>s(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)}).catch(()=>{return});if(e.slack?.webhookUrl&&Ze(e,t))i.push("slack"),o.push(a(e.slack.webhookUrl,{text:r}));if(e.discord?.webhookUrl&&Ze(e,t))i.push("discord"),o.push(a(e.discord.webhookUrl,{content:r}));if(e.telegram?.botToken&&e.telegram.chatId&&Ze(e,t)){i.push("telegram");let c=`https://api.telegram.org/bot${e.telegram.botToken}/sendMessage`;o.push(a(c,{chat_id:e.telegram.chatId,text:r}))}if(e.webhook?.url&&Ze(e,t))if(i.push("webhook"),(e.webhook.method||"POST")==="GET"){let c=e.webhook.url.includes("?")?"&":"?",l=`${e.webhook.url}${c}event=${encodeURIComponent(t)}&message=${encodeURIComponent(r)}`;o.push(s(l,{method:"GET"}).catch(()=>{return}))}else o.push(a(e.webhook.url,{event:t,message:r}));if(e.email?.to&&Ze(e,t))i.push("email"),o.push(So(e.email,t,r));return await Promise.all(o),i}async function So(e,t,r){try{await(await import("./chunk-a84gmpyh.js")).email.send({to:e.to,from:e.from,subject:`[ts-cloud] ${t}`,text:r})}catch{}}function In(e,t){return t??e}function Ne(e){if(!e)return[];let t=[];if(e.slack?.webhookUrl)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"text\\":\\"$MSG\\"}" ${e.slack.webhookUrl} || true`);if(e.discord?.webhookUrl)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"content\\":\\"$MSG\\"}" ${e.discord.webhookUrl} || true`);if(e.telegram?.botToken&&e.telegram.chatId)t.push(`curl -fsS -X POST "https://api.telegram.org/bot${e.telegram.botToken}/sendMessage" --data-urlencode "chat_id=${e.telegram.chatId}" --data-urlencode "text=$MSG" || true`);if(e.webhook?.url)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"message\\":\\"$MSG\\"}" ${e.webhook.url} || true`);if(t.length===0)return[];return["cat > /usr/local/bin/ts-cloud-notify <<'TS_CLOUD_NOTIFY_EOF'","#!/bin/bash",'MSG="$1"',...t,"TS_CLOUD_NOTIFY_EOF","chmod +x /usr/local/bin/ts-cloud-notify"]}function ur(e,t){return`/var/www/${e}-${t}`}var vo=new Set(["laravel","php","statamic","wordpress"]);function et(e){return e.type!=null&&vo.has(e.type)}function pr(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 yo(e){return pr(e).length>0}function kn(e){if(e.deploy)return e.deploy;if(et(e))return"server";if(e.start)return"server";return"bucket"}function ie(e){if(e.redirect)return"redirect";if(yo(e))return"proxy";if(et(e))return"server-php";if(kn(e)==="bucket")return"bucket";return e.start?"server-app":"server-static"}function $o(e){return e.infrastructure?.compute!=null||Boolean(e.cloud?.attachTo?.trim())}function _l(e,t={}){let r=[],n=[],s=e.sites||{},i=$o(e),o=Ln(e);if(o)r.push(o);let a=new Map;for(let[c,l]of Object.entries(s)){if(!l)continue;let d=kn(l),m=ie(l);if(m==="redirect"){if(!l.domain)r.push(`Site '${c}' is a redirect site but has no \`domain\` to redirect from.`);if(!(typeof l.redirect==="string"?l.redirect:l.redirect?.to))r.push(`Site '${c}' is a redirect site but has no redirect target (\`redirect\` / \`redirect.to\`).`);if(!i)r.push(`Site '${c}' is a redirect site but no \`infrastructure.compute\` is configured to host the gateway that serves the redirect.`);let p=[];if(l.start)p.push("start");if(l.root)p.push("root");if(l.proxyTo)p.push("proxyTo");if(p.length>0)n.push(`Site '${c}' is a redirect site but also sets ${p.join(", ")}. These are ignored.`);continue}if(m==="proxy"){if(!l.domain)r.push(`Site '${c}' is a proxy site but has no \`domain\` to route from.`);if(!i)r.push(`Site '${c}' is a proxy site but no \`infrastructure.compute\` is configured to host the gateway that forwards it.`);let u=[];if(l.start)u.push("start");if(l.root)u.push("root");if(typeof l.port==="number")u.push("port");if(l.build)u.push("build");if(l.preStart&&l.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(d==="server"&&!l.start&&!l.root){r.push(`Site '${c}' sets deploy:'server' but declares neither \`start\` (dynamic app) nor \`root\` (static site to serve). Add one.`);continue}if(m==="server-php"){if(!i)r.push(`Site '${c}' is a PHP site (type:'${l.type}') but no \`infrastructure.compute\` is configured. Add a server (infrastructure.compute) with PHP provisioning.`);if(!l.repository?.url)r.push(`Site '${c}' is a PHP site (type:'${l.type}') but has no \`repository.url\` to clone. PHP sites deploy via git.`)}else if(m==="server-app"){if(!i)r.push(`Site '${c}' deploys to a server (deploy:'server'${l.deploy?"":" inferred from `start`"}) but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`);if(typeof l.port==="number"){let u=t.occupiedPorts?.get(l.port);if(u)r.push(`Site '${c}' wants port ${l.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 p=a.get(l.port);if(p)r.push(`Sites '${p}' and '${c}' both use port ${l.port}. Server apps sharing a box must use distinct ports.`);else a.set(l.port,c)}}else if(m==="server-static"){if(!l.root)r.push(`Site '${c}' is a server static site (deploy:'server', no \`start\`) but has no \`root\` directory to serve.`);if(!i)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(!l.root)r.push(`Site '${c}' deploys to a bucket but has no \`root\` directory to upload.`);let u=[];if(l.start)u.push("start");if(typeof l.port==="number")u.push("port");if(l.preStart&&l.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 wl(e){let t=ie(e);return t!=="bucket"&&t!=="redirect"&&t!=="proxy"}function Tl(e){return ie(e)==="bucket"}function Pl(e,t){if(An(e)==="serverless")return!0;let r=Object.entries(e.sites??{}).filter(([,s])=>s!=null),n=t?r.filter(([s])=>s===t):r;if(n.length===0)return!0;return!n.every(([,s])=>{let i=ie(s);return i==="redirect"||i==="proxy"})}var fr="/etc/rpx/certs";function gr(e){return e.split(".").length===2}function bo(e,t={}){let r=new Set;for(let n of Object.values(e)){if(!n?.domain)continue;if(ie(n)==="bucket")continue;r.add(n.domain)}if(t.autoWww!==!1)for(let n of[...r]){if(!gr(n))continue;r.add(`www.${n}`)}return[...r]}var _o=["1.1.1.1","8.8.8.8"],wo="/var/www/acme-challenge";function To(e){if(typeof e==="string")return{to:e};let t={to:e.to};if(e.status!=null)t.status=e.status;if(e.preservePath!=null)t.preservePath=e.preservePath;return t}function Po(e){let t=e.auth;if(!t||t.enabled===!1||!t.password)return;return{username:t.username||"admin",password:t.password,...t.realm?{realm:t.realm}:{}}}function Nn(e){if(!e||e==="/")return;let t=`/${e}`.replace(/\/+/g,"/").replace(/\/+$/,"");if(!t.startsWith("/"))t=`/${t}`;return t===""||t==="/"?void 0:t}function dr(e,t){let n=(t?`${e}${t}`:e).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return n.length>0?n:"rpx"}function xo(e,t){if(!t||t.length===0)return`localhost:${e}`;return t.map((r)=>`${r.privateIp??r.publicIp}:${e}`)}function Un(e,t,r){let n=(t.wwwRoot??"/var/www").replace(/\/+$/,""),s=t.slug??"app",i=t.proxy.certsDir??fr,o=t.proxy.loadBalancer,a=[],c=new Set;for(let[u,p]of Object.entries(e)){if(!p||!p.domain)continue;let f=ie(p);if(f==="bucket")continue;let y=Nn(p.path),v=dr(p.domain,y),h=Po(p);if(f==="redirect"){a.push({to:p.domain,path:y,redirect:To(p.redirect),id:v,...h?{auth:h}:{}}),c.add(p.domain);continue}if(f==="proxy"){let S=pr(p);if(S.length===0)continue;let g=S.length===1?S[0]:S;a.push({to:p.domain,path:y,from:g,id:v,...h?{auth:h}:{},...Array.isArray(g)&&o?{loadBalancer:o}:{}}),c.add(p.domain);continue}if(f==="server-app"){if(typeof p.port!=="number")continue;let S=xo(p.port,r);a.push({to:p.domain,path:y,from:S,id:v,...h?{auth:h}:{},...Array.isArray(S)&&o?{loadBalancer:o}:{}})}else a.push({to:p.domain,path:y,static:{dir:`${n}/${s}-${u}/current`,spa:p.spa??!1,pathRewriteStyle:p.pathRewriteStyle??"directory"},cleanUrls:p.pathRewriteStyle!=="flat",...h?{auth:h}:{},id:v});c.add(p.domain)}if(t.proxy.autoWww!==!1)for(let u of[...c]){if(!gr(u))continue;let p=`www.${u}`;if(c.has(p))continue;a.push({to:p,redirect:{to:`https://${u}`},id:dr(p)}),c.add(p)}a.sort((u,p)=>{if(u.to!==p.to)return u.to.localeCompare(p.to);return(p.path?.length??0)-(u.path?.length??0)});let l={proxies:a,productionCerts:{certsDir:i,certsDirServerNames:[...c]},https:!0,hostsManagement:!1,cleanup:{hosts:!1,certs:!1}};if(t.proxy.onDemandTls&&c.size>0)l.onDemandTls={enabled:!0,allowedSuffixes:[...c],email:t.proxy.onDemandTlsEmail,certsDir:i,staging:t.proxy.onDemandTlsStaging??!1};if(t.proxy.onDemandTls)l.acmeChallengeWebroot=t.proxy.acmeWebroot??wo;let d=t.proxy.cdn,m=d?.frontedHosts?.length?d.frontedHosts:[...c];if(d?.secret&&m.length>0)l.originGuard={header:d.secretHeader??"X-Origin-Verify",value:d.secret,hosts:m};return l}function ve(e,t){return Un(e,t)}function He(e,t,r){return Un(e,r,t)}function Co(e){return`// Generated by ts-cloud — rpx reverse-proxy gateway.
21
21
  // Routes are derived from the \`sites\` model on every \`buddy deploy\`.
22
22
  import { startProxies } from '@stacksjs/rpx'
23
23
 
@@ -1 +1 @@
1
- import{Ad as f,vd as a,wd as b,xd as c,yd as d,zd as e}from"./chunk-zam6ecam.js";import"./chunk-by2bwzk6.js";import"./chunk-tz9myq9a.js";import"./chunk-y4xkj2f1.js";import"./chunk-wavjkdb8.js";import"./chunk-nk7sav4r.js";import"./chunk-mz0dk78z.js";import"./chunk-z2qqwy7e.js";export{e as deleteStaticSite,b as deployStaticSite,f as deployStaticSiteFull,a as generateStaticSiteTemplate,d as invalidateCache,c as uploadStaticFiles};
1
+ import{Ad as f,vd as a,wd as b,xd as c,yd as d,zd as e}from"./chunk-h42zck7h.js";import"./chunk-by2bwzk6.js";import"./chunk-tz9myq9a.js";import"./chunk-y4xkj2f1.js";import"./chunk-wavjkdb8.js";import"./chunk-152he7m3.js";import"./chunk-mz0dk78z.js";import"./chunk-13qjvbqh.js";export{e as deleteStaticSite,b as deployStaticSite,f as deployStaticSiteFull,a as generateStaticSiteTemplate,d as invalidateCache,c as uploadStaticFiles};