@stacksjs/ts-cloud 0.16.36 → 0.16.37

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 (153) hide show
  1. package/dist/aws/index.js +1 -1
  2. package/dist/bin/{chunk-c8439azc.js → chunk-017cjgwt.js} +2 -2
  3. package/dist/bin/{chunk-kcsjaam6.js → chunk-0ffqbgbs.js} +3 -3
  4. package/dist/bin/{chunk-4f5hhqh9.js → chunk-1fjhc7w7.js} +4 -4
  5. package/dist/bin/{chunk-2ax1rm70.js → chunk-2bkxxset.js} +2 -2
  6. package/dist/bin/chunk-2gygs4xw.js +1 -0
  7. package/dist/bin/chunk-3gc8y0ta.js +1 -0
  8. package/dist/bin/{chunk-twmeg17s.js → chunk-4zxwtvvf.js} +1 -1
  9. package/dist/bin/{chunk-cnwncp50.js → chunk-5keq8y15.js} +4 -4
  10. package/dist/bin/{chunk-8p2v1gat.js → chunk-6dm7x6g2.js} +12 -12
  11. package/dist/bin/{chunk-71jh460j.js → chunk-6r35j09y.js} +2 -2
  12. package/dist/bin/{chunk-vkdw6sxn.js → chunk-6sdffc79.js} +1 -1
  13. package/dist/bin/{chunk-exc2mqcc.js → chunk-71z22p71.js} +7 -7
  14. package/dist/bin/{chunk-9n3wmdd6.js → chunk-7xj986z7.js} +2 -2
  15. package/dist/bin/{chunk-bfzdbe4g.js → chunk-8gay06gq.js} +6 -6
  16. package/dist/bin/chunk-cdzas02w.js +1 -0
  17. package/dist/bin/{chunk-0870bs4x.js → chunk-dvyd4bxh.js} +12 -12
  18. package/dist/bin/chunk-excjyrfx.js +1 -0
  19. package/dist/bin/chunk-fawjv4dc.js +1 -0
  20. package/dist/bin/{chunk-v3prk467.js → chunk-fxyr2wkt.js} +3 -3
  21. package/dist/bin/{chunk-r8e263ne.js → chunk-gd94501z.js} +5 -5
  22. package/dist/bin/chunk-gewxhd5z.js +1 -0
  23. package/dist/bin/chunk-gjadvs6y.js +1 -0
  24. package/dist/bin/{chunk-qbagghsb.js → chunk-hsek7hvh.js} +93 -116
  25. package/dist/bin/{chunk-svrgx20b.js → chunk-kj4gm2hk.js} +3 -3
  26. package/dist/bin/chunk-n84pv5ns.js +1 -0
  27. package/dist/bin/{chunk-5yv95sqs.js → chunk-na2j5twe.js} +1 -1
  28. package/dist/bin/{chunk-h42xsxhm.js → chunk-nhz2az7v.js} +2 -2
  29. package/dist/bin/chunk-r263q1aa.js +1 -0
  30. package/dist/bin/chunk-rbjj0bcn.js +1 -0
  31. package/dist/bin/chunk-sp78dh4p.js +1 -0
  32. package/dist/bin/chunk-t844fst8.js +1 -0
  33. package/dist/bin/chunk-tkz95bkg.js +1 -0
  34. package/dist/bin/{chunk-bpw8m7rw.js → chunk-vg9et0kb.js} +2 -2
  35. package/dist/bin/{chunk-ar6bxdv4.js → chunk-w663zt0w.js} +3 -3
  36. package/dist/bin/chunk-xpzkwgb4.js +1 -0
  37. package/dist/bin/chunk-zswkrc34.js +1 -0
  38. package/dist/bin/cli.js +29 -29
  39. package/dist/bin/dashboard-server.js +1 -1
  40. package/dist/{chunk-mhv7dbr1.js → chunk-0fhz75e0.js} +3 -3
  41. package/dist/{chunk-tez0qfv9.js → chunk-1kfagk30.js} +1 -1
  42. package/dist/chunk-1mrqpf8e.js +1 -0
  43. package/dist/chunk-2bbm2q0s.js +1 -0
  44. package/dist/{chunk-kcj92xx7.js → chunk-2bvmp0br.js} +2 -2
  45. package/dist/{chunk-n4z75mk8.js → chunk-3bsf7585.js} +1 -1
  46. package/dist/chunk-46jnzd0d.js +1 -0
  47. package/dist/{chunk-7gvnrx46.js → chunk-5np6w0g7.js} +2 -2
  48. package/dist/{chunk-pdjap529.js → chunk-78r4k21k.js} +1 -1
  49. package/dist/{chunk-0kddm2mt.js → chunk-98xzqtnw.js} +1 -1
  50. package/dist/{chunk-k3mazfb2.js → chunk-a74kqzne.js} +12 -12
  51. package/dist/{chunk-hvwqct5q.js → chunk-aqxp4s43.js} +1 -1
  52. package/dist/{chunk-ajn6xp8v.js → chunk-azt6sm0r.js} +1 -1
  53. package/dist/{chunk-q9rdxpmg.js → chunk-fsdd2cj8.js} +2 -2
  54. package/dist/chunk-j5v7fgxz.js +1 -0
  55. package/dist/chunk-jfqm2c9q.js +1 -0
  56. package/dist/{chunk-mxw5gkd8.js → chunk-k92sywmh.js} +1 -1
  57. package/dist/{chunk-2x636sgn.js → chunk-mbs6pr03.js} +6 -6
  58. package/dist/{chunk-fszn9rnn.js → chunk-mce0cpgf.js} +10 -10
  59. package/dist/{chunk-yzns0k2b.js → chunk-n0vz557v.js} +1 -1
  60. package/dist/{chunk-3nqtbyfp.js → chunk-n3p8vr8s.js} +3 -3
  61. package/dist/{chunk-p0ksat08.js → chunk-pjhag27y.js} +1 -1
  62. package/dist/chunk-ppr0bkgd.js +1 -0
  63. package/dist/{chunk-nr6z3e1p.js → chunk-rkjnr9fp.js} +3 -3
  64. package/dist/{chunk-ncsb3sdn.js → chunk-svzmsd7g.js} +1 -1
  65. package/dist/{chunk-ctkzxq0d.js → chunk-t0azf37g.js} +2 -2
  66. package/dist/{chunk-9aaj9a0s.js → chunk-vmhfc7nk.js} +91 -114
  67. package/dist/{chunk-78shfb0z.js → chunk-x7pnt65y.js} +55 -55
  68. package/dist/{chunk-my6yn5sd.js → chunk-ybdxrf42.js} +1 -1
  69. package/dist/{chunk-sekw1nyx.js → chunk-zg589zg1.js} +10 -10
  70. package/dist/deploy/index.js +1 -1
  71. package/dist/dns/index.js +1 -1
  72. package/dist/drivers/index.js +1 -1
  73. package/dist/generators/infrastructure.d.ts +7 -0
  74. package/dist/index.js +17 -17
  75. package/dist/operations/index.js +1 -1
  76. package/dist/protection/index.js +1 -1
  77. package/dist/spend/index.js +1 -1
  78. package/dist/ui/404.html +1 -1
  79. package/dist/ui/accept-invitation.html +1 -1
  80. package/dist/ui/access-denied.html +1 -1
  81. package/dist/ui/account/automation.html +5 -5
  82. package/dist/ui/account/security.html +1 -1
  83. package/dist/ui/applications/compose.html +6 -6
  84. package/dist/ui/applications/new.html +2 -2
  85. package/dist/ui/data/backups.html +6 -6
  86. package/dist/ui/data/services.html +6 -6
  87. package/dist/ui/data/volumes.html +6 -6
  88. package/dist/ui/index.html +5 -5
  89. package/dist/ui/infrastructure/topology.html +5 -5
  90. package/dist/ui/integrations.html +2 -2
  91. package/dist/ui/operations/alerts.html +6 -6
  92. package/dist/ui/operations/configuration.html +5 -5
  93. package/dist/ui/operations/jobs.html +5 -5
  94. package/dist/ui/operations/maintenance.html +5 -5
  95. package/dist/ui/operations/observability.html +6 -6
  96. package/dist/ui/operations/previews.html +6 -6
  97. package/dist/ui/operations/queue.html +6 -6
  98. package/dist/ui/operations/regions.html +5 -5
  99. package/dist/ui/operations/releases.html +5 -5
  100. package/dist/ui/operations/spend.html +6 -6
  101. package/dist/ui/operations/workloads.html +6 -6
  102. package/dist/ui/security.html +1 -1
  103. package/dist/ui/server/actions.html +6 -6
  104. package/dist/ui/server/activity.html +1 -1
  105. package/dist/ui/server/capacity.html +6 -6
  106. package/dist/ui/server/database.html +6 -6
  107. package/dist/ui/server/deployments.html +5 -5
  108. package/dist/ui/server/diagnostics.html +2 -2
  109. package/dist/ui/server/firewall.html +6 -6
  110. package/dist/ui/server/fleet.html +6 -6
  111. package/dist/ui/server/logs.html +6 -6
  112. package/dist/ui/server/metrics.html +5 -5
  113. package/dist/ui/server/security.html +1 -1
  114. package/dist/ui/server/services.html +2 -2
  115. package/dist/ui/server/sites.html +6 -6
  116. package/dist/ui/server/ssh-keys.html +6 -6
  117. package/dist/ui/server/team.html +6 -6
  118. package/dist/ui/server/terminal.html +2 -2
  119. package/dist/ui/serverless/alarms.html +6 -6
  120. package/dist/ui/serverless/assets.html +2 -2
  121. package/dist/ui/serverless/cost.html +2 -2
  122. package/dist/ui/serverless/data.html +6 -6
  123. package/dist/ui/serverless/deployments.html +2 -2
  124. package/dist/ui/serverless/firewall.html +2 -2
  125. package/dist/ui/serverless/functions.html +6 -6
  126. package/dist/ui/serverless/logs.html +5 -5
  127. package/dist/ui/serverless/metrics.html +1 -1
  128. package/dist/ui/serverless/queues.html +6 -6
  129. package/dist/ui/serverless/secrets.html +6 -6
  130. package/dist/ui/serverless/traces.html +5 -5
  131. package/dist/ui/serverless.html +6 -6
  132. package/package.json +3 -3
  133. package/dist/bin/chunk-3gg55dkc.js +0 -1
  134. package/dist/bin/chunk-691k55nw.js +0 -1
  135. package/dist/bin/chunk-7n84q4np.js +0 -1
  136. package/dist/bin/chunk-7s3wtq40.js +0 -1
  137. package/dist/bin/chunk-8bb6kyhm.js +0 -1
  138. package/dist/bin/chunk-9pvkb6br.js +0 -1
  139. package/dist/bin/chunk-e9mkg5dn.js +0 -1
  140. package/dist/bin/chunk-h5darb19.js +0 -1
  141. package/dist/bin/chunk-h6n5v6rf.js +0 -1
  142. package/dist/bin/chunk-hfswzdzj.js +0 -1
  143. package/dist/bin/chunk-w68hker6.js +0 -1
  144. package/dist/bin/chunk-x8wvsf1k.js +0 -1
  145. package/dist/bin/chunk-y1qk3df2.js +0 -1
  146. package/dist/bin/chunk-y4pfvx0x.js +0 -1
  147. package/dist/bin/chunk-zjw9sdr5.js +0 -1
  148. package/dist/chunk-0my5jwq8.js +0 -1
  149. package/dist/chunk-fxk29btr.js +0 -1
  150. package/dist/chunk-fz62nas4.js +0 -1
  151. package/dist/chunk-gyp7jcgw.js +0 -1
  152. package/dist/chunk-wxtr8sv8.js +0 -1
  153. package/dist/chunk-yhjagaff.js +0 -1
@@ -0,0 +1 @@
1
+ import{cm,lm,Zo,Wc,ea,ta,gn,Ue,A,ra,Kc,H,xr,w,Gd,Ri,na,ia,B,$s,Wd,Kd,Jd,Xd,l,s,dm,um,T,sa,oa,aa,pm,mm,ke,ca,Ii,Qd,gm,fm,Fe,Et,la,Jc,Xc,hm,Qc,Yc,Zc,Ls,da,tt,Ms,fn,Pi,hn,Be,Yd,Us,Fs,ua,pa,ma,ga,fa,ha,Te,j,Zd,eu,el,b,L,rt,N,tl,wt,ge,Ht,ym,rl,Ee,Bs,je,qt,Di,we,js,xe,tu,Ni,Ae,Re,ne,ki,X,Gt,At,Ie,t,yn,bm,nl,ya,Sm,vm,Cm,Tm,ba,Em,wm,Am,Rm,Im,Pm,Dm,Nm,km,xm,_m,Om,ru,nu,iu,su,ou,au,cu,Wt,il,sl,_r,xi,$m,ol,Lm,Mm,bn,Um,Fm,Bm,jm,Vm,zm,lu,du,uu,pu,mu,_i,Hm,Sn,gu,al,fu,Sa,fe,hu,yu,Rt,Vs,Kt,bu,cl,Su,vu,Cu,ll,he,qm,Gm,Wm,Km,Tu,Jm,Pe,Xm,Qm,Ym,va,Ca,Eu,dl,ul,Zm,eg,tg,rg,ng,wu,Ta,ig,sg,og,ag,cg,Au,Ru,lg,dg,ug,pg,mg,gg,fg,Iu,hg,pl,Ea,yg,bg,Sg,vg,ml,gl,fl,Cg,wa,Pu,Du,Nu,ku,Aa,xu,Tg,Eg,wg,Ag,Rg,Ig,Pg,_u,Ou,$u,Lu,hl,Dg,Ng,kg,xg,_g,Og,$g,Lg,Mg,Mu,Uu,Fu,Bu,Ug,Fg,yl,Bg,bl,Sl,vl,Cl,jg,Vg,zg,Hg,nt,Oi,qg,Gg,Wg,Kg,Jg,Xg,Qg,Yg,ju,Zg,ef,Tl,El,tf,rf,Vu,nf,sf,of,af,cf,lf,df,uf,pf,mf,gf,ff,hf,yf,bf,Sf,vf,Cf,Tf,Ef,wf,Ra,zu,Ia,Hu,Pa,qu,Da,Gu,Na,Wu,Or,Ku,ka,Ju,$i,Xu,xa,Qu,_a,Yu,wl,Af,Al,Rf,Oa,Zu,$r,ep,Rl,If,$a,tp,Il,Pf,Pl,Df,Dl,Nf,La,rp,Nl,kf,kl,xf,xl,_f,_l,Of,Ma,np,Ua,ip,Ol,$f,$l,Lf,Ll,Mf,Ml,Uf,Ul,Ff,Fl,Bf,Fa,sp,Bl,jf,jl,Vf,Vl,zf,zl,Hf,Hl,qf,ql,Gf,Gl,Wl,Kl,Jl,Xl,Wf,Ql,Kf,Yl,Jf,Zl,Xf,It,ed,op,zs,Ba,vn,ap,Li,Jt,ja,Va,cp,lp,za,td,Ha,rd,Qf,Yf,qa,Ga,Wa,nd,Mi,id,sd,Hs,Ka,Ja,od,dp,up,pp,Zf,ad,cd,eh,mp,ld,gp,fp,hp,th,dd,Cn,Xa,ud,rh,yp,qs,Gs,Qa,pd,nh,Ya,bp,md,ih,gd,sh,fd,oh}from"./chunk-hsek7hvh.js";import{Za,Y,ec,Ws,Sp,Pt,vp,Cp,Tn,Tp,Ep,wp,Ap,Rp}from"./chunk-kj4gm2hk.js";export{xa as ABTestManager,je as AI,Su as AWSAPIError,Pa as AWSConfigManager,bm as AWS_PSEUDO_PARAMETERS,nt as AWS_REGIONS,js as ApiGateway,yn as Arn,ne as AssetHasher,Ae as Auth,Ra as BackupManager,Yl as BatchProcessingManager,ka as BlueGreenManager,Vl as BounceComplaintHandler,_l as BuildOptimizationManager,Be as CDN,Ga as CHAIN_HEADER,la as CLOUDFRONT_FAILOVER_STATUS_CODES,sf as COMMON_CROSS_ACCOUNT_ROLES,Di as Cache,$i as CanaryManager,Nl as CertificateManager,Rt as CloudError,nl as CloudFormationBuilder,fu as CloudFormationClient,yu as CloudFrontClient,Da as CloudTrailManager,Bu as CommandHistory,Ie as Communication,b as Compute,Vs as ConfigurationError,Ma as ContainerRegistryManager,Kt as CredentialError,bl as CrossRegionReferenceManager,nu as DASHBOARD_ENTRY,iu as DASHBOARD_PORT_BASE,su as DASHBOARD_PORT_SPAN,ru as DASHBOARD_STATE_DIR,Jc as DEFAULT_FAILOVER_STATUS_CODES,Mi as DEFAULT_RECURSION_LIMITS,Pe as DEFAULT_SERVICE_LIMITS,Zo as DEFAULT_STATE_DIR,Yd as DEFAULT_STORAGE_FAILOVER_STATUS_CODES,qa as DEPTH_HEADER,Ql as DLQMonitoringManager,Te as DNS,Bl as DNSSECManager,qt as Database,Pl as DatabaseUserManager,he as DebugLogger,Qd as DependencyGraph,Re as Deployment,bu as DeploymentError,Ia as DisasterRecoveryManager,N as Email,Gl as EmailAdvanced,zl as EmailAnalyticsManager,Wl as EmailHandlers,ql as EmailTemplateManager,vu as ErrorCodes,Fs as FAILOVER_REPLICA_POLICY_SID,Xl as FIFOQueueManager,va as FileCache,rt as FileSystem,t as Fn,Sl as GlobalResourceManager,Na as GuardDutyManager,wu as HashCache,md as HealthCheckManager,xl as ImageScanningManager,Ht as JobLoader,ud as LARAVEL_SERVERLESS_BUILD_STEPS,Ll as LambdaConcurrencyManager,Fl as LambdaDLQManager,Ml as LambdaDestinationsManager,Ol as LambdaLayersManager,Ul as LambdaVPCManager,$l as LambdaVersionsManager,Oa as LogsManager,ap as MANAGED_NODE_VERSIONS,il as MANAGEMENT_DASHBOARD_SITE_PREFIX,xe as Messaging,Al as MetricsManager,Rl as MigrationManager,ml as MockCloudFormation,fl as MockDynamoDB,gl as MockS3,Ni as Monitoring,Tl as MultiAccountManager,yl as MultiRegionManager,Ou as MultiStepProgress,L as Network,gd as NetworkSecurityManager,Yc as ORIGIN_CONNECTION_ATTEMPTS,Zc as ORIGIN_CONNECTION_TIMEOUT,Xc as ORIGIN_GROUP_ALLOWED_METHODS,hm as ORIGIN_GROUP_ID_SUFFIX,Qc as ORIGIN_GROUP_SELECTION_CRITERIA,El as OrganizationManager,yp as PHP_DEFAULT_EXCLUDES,cp as PHP_LAYER_EXTENSIONS,X as ParameterStore,Il as PerformanceManager,we as Permissions,wt as Phone,Kl as PhoneAdvanced,tl as PhoneHandlers,wa as PreviewEnvironmentManager,Aa as PreviewNotificationService,_u as ProgressBar,_a as ProgressiveDeploymentManager,Xd as Pseudo,ge as Queue,Zl as QueueManagementManager,cm as QueuePresets,Vu as RECOMMENDED_ACCOUNT_STRUCTURES,nf as RECOMMENDED_SCPS,Mu as REPL,Fu as REPLCommandBuilder,Uu as REPLContext,Au as RateLimiter,lm as RealtimePresets,Hs as RecursionGuard,At as Redirects,vl as RegionPairManager,Et as Registry,$a as ReplicaManager,fd as ResourceManagementManager,jl as Route53ResolverManager,Fa as Route53RoutingManager,Sa as S3Client,fe as S3Error,Ee as SMS,Wc as STATE_DIR_ENV_VAR,Us as STORAGE_FAILOVER_METADATA_KEY,Gt as Search,ki as Secrets,La as SecretsManager,Dl as SecretsRotationManager,j as Security,Or as SecurityHubManager,kl as SecurityScanningManager,Hl as SenderReputationManager,Ua as ServiceMeshManager,Bs as Sftp,Jl as SmsAdvanced,rl as SmsHandlers,$u as Spinner,Cl as StackDependencyManager,ym as StacksIntegration,pd as StaticSiteManager,Fe as Storage,Ya as StorageAdvancedManager,$r as SyntheticsManager,Wa as TRACE_HEADER,Lu as TaskList,$s as TemplateBuilder,Ca as TemplateCache,cl as ValidationError,tu as Workflow,wl as XRayManager,Qu as abTestManager,el as amazonLinuxImageId,eu as amazonLinuxImageParameter,gm as analyzeStackDiff,Ba as artifactKey,fn as assertOriginGroupMethods,_g as autocomplete,qu as awsConfigManager,zu as backupManager,ig as batch,Jf as batchProcessingManager,Ju as blueGreenManager,zf as bounceComplaintHandler,Yf as buildBunRuntimeLayerZip,ya as buildCloudFormationTemplate,fa as buildFailoverReplicaPolicyStatement,ia as buildMailEnv,Qf as buildNodeRuntimeLayerZip,Of as buildOptimizationManager,da as buildOriginGroup,Ms as buildOriginGroups,rh as buildPhpRuntimeLayerZip,ga as buildReplicationConfiguration,ma as buildReplicationRole,Xu as canaryManager,mg as categorizeChanges,kf as certificateManager,Km as checkIAMPermissions,ad as checkInvocation,Xm as checkServiceQuotas,Ru as chunk,Ep as clearSigningKeyCache,Iu as cloudConfigSchema,Gu as cloudTrailManager,Gs as collectPhpAppEntries,Lm as composePresets,Va as composeServerlessAppTemplate,np as containerRegistryManager,wm as createApiBackendPreset,hp as createCliHandler,Hm as createCredentialProvider,Om as createDashboardSite,Dm as createDataPipelinePreset,ll as createError,ba as createExistingStaticFullStackPreset,Em as createFullStackAppPreset,th as createHandlers,gp as createHttpHandler,Rm as createJamstackPreset,xm as createLaravelPreset,Nm as createMLApiPreset,Im as createMicroservicesPreset,Cg as createMockAWS,vm as createNodeJsServerPreset,Cm as createNodeJsServerlessPreset,Mm as createPreset,Ws as createPresignedUrl,Sp as createPresignedUrlAsync,fp as createQueueHandler,Pm as createRealtimeAppPreset,hu as createS3Client,_m as createServerlessLaravelPreset,Tm as createServerlessNodePreset,Sm as createStaticSitePreset,km as createTraditionalWebAppPreset,Am as createWordPressPreset,It as createZip,jg as crossRegionReferenceManager,Df as databaseUserManager,pl as defaultLocalConfig,xr as deploymentCoexistenceError,ou as deriveManagementDashboardPort,Kc as detectDeploymentTargets,Gm as detectMisconfigurations,Za as detectServiceRegion,dg as diffTemplates,Kf as dlqMonitoringManager,jf as dnssecManager,Hu as drManager,Hf as emailAnalyticsManager,Gf as emailTemplateManager,mp as eventToRequest,ol as extendPreset,Wf as fifoQueueManager,ng as findChangedFiles,lf as formatAccountStructure,Ag as formatBytes,fm as formatDiff,Rg as formatDuration,$g as formatFlagSuggestions,Ug as formatHistory,Fg as formatHistoryStats,Pg as formatKeyValue,Ig as formatList,wg as formatProgressBar,ju as formatRegion,Zg as formatRegionList,Dg as formatSuggestion,Tg as formatTable,Eg as formatTree,uu as fromEC2Metadata,pu as fromECSMetadata,lu as fromEnvironment,du as fromSharedCredentials,mu as fromWebIdentity,nd as functionFingerprint,Ha as generateAppImageDockerfile,Ef as generateApprovalConfig,ed as generateBootstrap,Nu as generateCleanupWorkflow,ku as generateCostReportWorkflow,af as generateCrossAccountRoleCF,vf as generateDeploymentConfig,ff as generateDeploymentPipeline,df as generateDeploymentWorkflow,s as generateLogicalId,Sf as generateManualPipeline,gf as generateMatrixWorkflow,Cf as generateMultiEnvConfig,hf as generateMultiEnvPipeline,uf as generateMultiEnvWorkflow,pf as generatePRPreviewWorkflow,wf as generateParallelConfig,dd as generatePhpFpmConfig,td as generatePhpLayerDockerfile,yf as generatePreviewPipeline,Du as generatePreviewWorkflow,l as generateResourceName,Tf as generateScheduledConfig,bf as generateScheduledPipeline,mf as generateScheduledWorkflow,al as getAccountId,qg as getAllRegions,Xg as getClosestRegion,Lg as getCommandUsage,kg as getContextualHelp,_i as getCredentials,gg as getDeploymentStrategy,fg as getDiffStats,ug as getDiffSummary,Cu as getErrorDetails,Ea as getLocalConfig,Sg as getLocalCredentials,bg as getLocalEndpoint,vg as getLocalEnvVars,Qm as getQuotaUsageSummary,of as getRecommendedStructure,Oi as getRegion,ef as getRegionStats,Wg as getRegionsByCompliance,Gg as getRegionsByLocation,Kg as getRegionsByPricingTier,Tu as getRequiredPermissions,wp as getSigningKeyCacheSize,dm as getTimestamp,Vg as globalResourceManager,Wu as guardDutyManager,Wt as hasManagementDashboardSite,Zm as hashBuffer,eg as hashDirectory,dl as hashFile,tg as hashManifest,ul as hashString,ih as healthCheckManager,_f as imageScanningManager,sd as inspectInvocation,up as installRecursionFetch,od as invocationContext,Zd as isArmInstanceType,Ng as isLikelyTypo,yg as isLocalDevelopment,_r as isManagementDashboardSiteName,Ap as isNodeCryptoAvailable,Pi as isS3RestEndpoint,ta as isStateDirConfigured,ra as isStatePath,Jg as isValidRegion,Rp as isWebCryptoAvailable,Mf as lambdaConcurrencyManager,Bf as lambdaDLQManager,Uf as lambdaDestinationsManager,$f as lambdaLayersManager,Ff as lambdaVPCManager,Lf as lambdaVersionsManager,Xa as laravelServerlessEnvDefaults,Zu as logsManager,Gd as mailEnabled,na as mailFirewallPorts,Pt as makeAWSRequest,Cp as makeAWSRequestAsync,vp as makeAWSRequestOnce,sl as managementDashboardSiteName,bn as mergeInfrastructure,Rf as metricsManager,If as migrationManager,tf as multiAccountManager,Bg as multiRegionManager,sh as networkSecurityManager,rf as organizationManager,Qa as packagePhpApp,vn as packageServerlessApp,Ta as parallel,sg as parallelMap,og as parallelWithRetry,id as parseChain,Tp as parseJSONResponse,Tn as parseXMLResponse,Pf as performanceManager,za as phpLayerBuildStage,lp as phpLayerPackages,Cn as phpRuntimeLayerAssets,Pu as previewManager,xu as previewNotifications,lg as processInChunks,Yu as progressiveDeploymentManager,Ka as propagationHeaders,Xf as queueManagementManager,rg as quickHash,Ja as recursionBlockedResponse,zg as regionPairManager,tp as replicaManager,pg as requiresReplacement,Zf as resetRecursionRuntime,eh as resolveApp,w as resolveAppDatabase,B as resolveCloudProvider,Sn as resolveCredentials,au as resolveDashboardDomain,cu as resolveDashboardDomains,mm as resolveDeployBucketName,H as resolveDeploymentMode,Ls as resolveFailoverStatusCodes,Ri as resolveMailService,$m as resolveManagementDashboardSite,xi as resolveManagementDashboardSites,tt as resolveOriginConnection,T as resolveProjectStackName,ja as resolveQueueNames,Jt as resolveQueues,dp as resolveRecursionConfig,gu as resolveRegion,ke as resolveServerlessAppStackName,ca as resolveServerlessArtifactBucketName,Ii as resolveServerlessAssetBucketName,Li as resolveServerlessRuntime,aa as resolveSiteBucketName,oa as resolveSiteResourceName,sa as resolveSiteStackName,A as resolveStatePath,pm as resolveStorageBucketName,ua as resolveStorageFailover,oh as resourceManagementManager,ld as responseToResult,Vf as route53ResolverManager,sp as route53RoutingManager,op as runBuildHooks,qs as runPhpBuildHooks,pa as s3RegionalDomain,um as sanitizeName,xg as searchCommands,rp as secretsManager,Nf as secretsRotationManager,Ku as securityHubManager,xf as securityScanningManager,qf as senderReputationManager,ag as sequence,ip as serviceMeshManager,ea as setStateDir,zs as sha256,pp as sharedRecursionGuard,rd as sharedRuntimeLoop,Y as signRequest,ec as signRequestAsync,Hg as stackDependencyManager,gn as stateDir,Ue as statePath,nh as staticSiteManager,bp as storageAdvancedManager,ha as storageFailoverReplicasFromTemplate,hl as suggestCommand,Og as suggestFlags,Jm as suggestIAMPolicy,Ym as suggestQuotaIncrease,Yg as suggestRegionPairs,Qg as suggestRegions,ep as syntheticsManager,Eu as templateCache,cf as validateAccountStructure,hg as validateAgainstSchema,Mg as validateCommand,qm as validateConfiguration,Wm as validateCredentials,hn as validateOriginGroups,Jd as validateResourceLimits,Wd as validateTemplate,Kd as validateTemplateSize,Vm as withCDN,jm as withCache,Bm as withDatabase,cd as withInvocation,Um as withMonitoring,zm as withQueue,Fm as withSecurity,cg as withTimeout,Af as xrayManager};
@@ -0,0 +1 @@
1
+ import{Hc,am}from"./chunk-vg9et0kb.js";import"./chunk-ymfnqae6.js";import"./chunk-f76wtb7d.js";import"./chunk-7rwc5bvv.js";export{Hc as EmailClient,am as email};
@@ -1,9 +1,9 @@
1
- import{H,xr}from"./chunk-qbagghsb.js";function J(e,t){return`/var/www/${e}-${t}`}var me=new Set(["laravel","php","statamic","wordpress"]);function Si(e){return e.type!=null&&me.has(e.type)}function Fo(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 fe(e){return Fo(e).length>0}function te(e){if(e.deploy)return e.deploy;if(Si(e))return"server";if(e.start)return"server";return"bucket"}function P(e){if(e.redirect)return"redirect";if(fe(e))return"proxy";if(Si(e))return"server-php";if(te(e)==="bucket")return"bucket";return e.start?"server-app":"server-static"}function As(e){return e.infrastructure?.compute!=null||Boolean(e.cloud?.attachTo?.trim())}function Bo(e,t={}){let r=[],n=[],o=e.sites||{},s=As(e),c=xr(e);if(c)r.push(c);let p=new Map;for(let[l,i]of Object.entries(o)){if(!i)continue;let f=te(i),R=P(i);if(R==="redirect"){if(!i.domain)r.push(`Site '${l}' is a redirect site but has no \`domain\` to redirect from.`);if(!(typeof i.redirect==="string"?i.redirect:i.redirect?.to))r.push(`Site '${l}' is a redirect site but has no redirect target (\`redirect\` / \`redirect.to\`).`);if(!s)r.push(`Site '${l}' is a redirect site but no \`infrastructure.compute\` is configured to host the gateway that serves the redirect.`);let a=[];if(i.start)a.push("start");if(i.root)a.push("root");if(i.proxyTo)a.push("proxyTo");if(a.length>0)n.push(`Site '${l}' is a redirect site but also sets ${a.join(", ")}. These are ignored.`);continue}if(R==="proxy"){if(!i.domain)r.push(`Site '${l}' is a proxy site but has no \`domain\` to route from.`);if(!s)r.push(`Site '${l}' is a proxy site but no \`infrastructure.compute\` is configured to host the gateway that forwards it.`);let u=[];if(i.start)u.push("start");if(i.root)u.push("root");if(typeof i.port==="number")u.push("port");if(i.build)u.push("build");if(i.preStart&&i.preStart.length>0)u.push("preStart");if(u.length>0)n.push(`Site '${l}' 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(f==="server"&&!i.start&&!i.root){r.push(`Site '${l}' sets deploy:'server' but declares neither \`start\` (dynamic app) nor \`root\` (static site to serve). Add one.`);continue}if(R==="server-php"){if(!s)r.push(`Site '${l}' is a PHP site (type:'${i.type}') but no \`infrastructure.compute\` is configured. Add a server (infrastructure.compute) with PHP provisioning.`);if(!i.repository?.url)r.push(`Site '${l}' is a PHP site (type:'${i.type}') but has no \`repository.url\` to clone. PHP sites deploy via git.`)}else if(R==="server-app"){if(!s)r.push(`Site '${l}' deploys to a server (deploy:'server'${i.deploy?"":" inferred from `start`"}) but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`);if(typeof i.port==="number"){let u=t.occupiedPorts?.get(i.port);if(u)r.push(`Site '${l}' wants port ${i.port}, which project '${u}' already serves on this box. Attached projects share one port namespace. Give '${l}' a free port, or let the attach allocate one.`);let a=p.get(i.port);if(a)r.push(`Sites '${a}' and '${l}' both use port ${i.port}. Server apps sharing a box must use distinct ports.`);else p.set(i.port,l)}}else if(R==="server-static"){if(!i.root)r.push(`Site '${l}' is a server static site (deploy:'server', no \`start\`) but has no \`root\` directory to serve.`);if(!s)r.push(`Site '${l}' deploys to a server (deploy:'server') but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`)}else{if(!i.root)r.push(`Site '${l}' deploys to a bucket but has no \`root\` directory to upload.`);let u=[];if(i.start)u.push("start");if(typeof i.port==="number")u.push("port");if(i.preStart&&i.preStart.length>0)u.push("preStart");if(u.length>0)n.push(`Site '${l}' 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 jo(e){let t=P(e);return t!=="bucket"&&t!=="redirect"&&t!=="proxy"}function Uc(e){return P(e)==="bucket"}function Fc(e,t){if(H(e)==="serverless")return!0;let r=Object.entries(e.sites??{}).filter(([,o])=>o!=null),n=t?r.filter(([o])=>o===t):r;if(n.length===0)return!0;return!n.every(([,o])=>{let s=P(o);return s==="redirect"||s==="proxy"})}var A={php:"php.net",nginx:"nginx.org",composer:"getcomposer.org",mysql:"mysql.com",mariadb:"mariadb.com/server",postgres:"postgresql.org",vitess:"vitess.io",etcd:"etcd.io",redis:"redis.io",memcached:"memcached.org",meilisearch:"meilisearch.com",mail:"github.com/mail-os/mail",git:"git-scm.com",certbot:"certbot.eff.org",bun:"bun.sh",node:"nodejs.org",deno:"deno.land"};var U="/opt/pantry";function M(e){return`'${e.split("'").join("'\\''")}'`}function wr(e={}){return["export DEBIAN_FRONTEND=noninteractive","export PANTRY_SERVICE_SCOPE=system","export PANTRY_INSTALL_DIR=/usr/local/bin",e.version?`export PANTRY_VERSION=${M(e.version)}`:'export PANTRY_VERSION="${PANTRY_VERSION:-latest}"',"command -v curl >/dev/null 2>&1 || (apt-get update -y && apt-get install -y curl ca-certificates)","command -v unzip >/dev/null 2>&1 || (apt-get update -y && apt-get install -y unzip)",'OS=$(uname -s | tr \'[:upper:]\' \'[:lower:]\'); ARCH=$(uname -m); case "$ARCH" in x86_64|amd64) ARCH=x64 ;; arm64|aarch64) ARCH=arm64 ;; esac; ZIP="pantry-${OS}-${ARCH}.zip"; if [ "${PANTRY_VERSION:-latest}" = latest ]; then REL=\'latest/download\'; else REL="download/v${PANTRY_VERSION}"; fi; TMP=$(mktemp -d); curl -fsSL -o "${TMP}/${ZIP}" "https://github.com/pantry-pm/pantry/releases/${REL}/${ZIP}"; unzip -o "${TMP}/${ZIP}" -d /usr/local/bin; chmod +x /usr/local/bin/pantry; rm -rf "${TMP}"','export PATH="/usr/local/bin:$PATH"',"mkdir -p /opt/pantry"]}function St(){return'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true'}function et(e){if(e.length===0)return[];return[`(cd /opt/pantry && pantry install ${[...new Set(e)].map(M).join(" ")})`]}function Rs(e){return[...new Set(e)].flatMap((t)=>[`(cd /opt/pantry && pantry start ${M(t)})`,`(cd /opt/pantry && pantry enable ${M(t)})`])}var m="/etc/mail",T="mail-server",q="mail",F=`${U}/pantry/.bin`;function h(e){return`'${String(e).split("'").join("'\\''")}'`}function C(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function ge(e){return[e.version?`${A.mail}@${e.version}`:A.mail]}function Y(e,t){return`${m}/dkim/${t}.${e.dkim.selector}.pem`}function re(e){return`${e.storagePath}/smtp.db`}function Te(e){let t=["# Generated by ts-cloud. Edits are overwritten on the next deploy —","# change `services.mail` in the cloud config instead.","","[server]",`host = ${C(e.bindAddress)}`,`port = ${e.ports.smtp}`,`hostname = ${C(e.hostname)}`];if(e.domains.length>0)t.push(`local_domains = ${C(e.domains.join(", "))}`);if(e.mode==="catcher")t.push("catch_all = true");if(t.push(`max_message_size = ${e.maxMessageSize}`,"","[tls]",`enabled = ${e.tls.enabled}`),e.tls.certPath)t.push(`cert_path = ${C(e.tls.certPath)}`);if(e.tls.keyPath)t.push(`key_path = ${C(e.tls.keyPath)}`);if(t.push("","[auth]",`enabled = ${e.mode==="server"}`,"","[antispam]",`dnsbl = ${e.spam.dnsbl}`,`greylist = ${e.spam.greylist}`,`spam_filter = ${e.spam.enabled}`,`junk_score = ${e.spam.junkScore}`,`reject_score = ${e.spam.rejectScore}`,"","[dkim]",`rotation_enabled = ${e.dkim.enabled&&e.dkim.rotate}`,`rotation_interval_days = ${e.dkim.rotateIntervalDays}`,"","[acme]",`enabled = ${e.tls.acme}`),e.tls.acmeEmail)t.push(`email = ${C(e.tls.acmeEmail)}`);if(t.push("","[webhook]",`enabled = ${!!e.webhookUrl}`),e.webhookUrl)t.push(`url = ${C(e.webhookUrl)}`);return t.push(""),t.join(`
1
+ import{H,xr}from"./chunk-hsek7hvh.js";function J(e,t){return`/var/www/${e}-${t}`}var me=new Set(["laravel","php","statamic","wordpress"]);function Si(e){return e.type!=null&&me.has(e.type)}function Fo(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 fe(e){return Fo(e).length>0}function te(e){if(e.deploy)return e.deploy;if(Si(e))return"server";if(e.start)return"server";return"bucket"}function P(e){if(e.redirect)return"redirect";if(fe(e))return"proxy";if(Si(e))return"server-php";if(te(e)==="bucket")return"bucket";return e.start?"server-app":"server-static"}function As(e){return e.infrastructure?.compute!=null||Boolean(e.cloud?.attachTo?.trim())}function Bo(e,t={}){let r=[],n=[],o=e.sites||{},s=As(e),c=xr(e);if(c)r.push(c);let p=new Map;for(let[l,i]of Object.entries(o)){if(!i)continue;let f=te(i),R=P(i);if(R==="redirect"){if(!i.domain)r.push(`Site '${l}' is a redirect site but has no \`domain\` to redirect from.`);if(!(typeof i.redirect==="string"?i.redirect:i.redirect?.to))r.push(`Site '${l}' is a redirect site but has no redirect target (\`redirect\` / \`redirect.to\`).`);if(!s)r.push(`Site '${l}' is a redirect site but no \`infrastructure.compute\` is configured to host the gateway that serves the redirect.`);let a=[];if(i.start)a.push("start");if(i.root)a.push("root");if(i.proxyTo)a.push("proxyTo");if(a.length>0)n.push(`Site '${l}' is a redirect site but also sets ${a.join(", ")}. These are ignored.`);continue}if(R==="proxy"){if(!i.domain)r.push(`Site '${l}' is a proxy site but has no \`domain\` to route from.`);if(!s)r.push(`Site '${l}' is a proxy site but no \`infrastructure.compute\` is configured to host the gateway that forwards it.`);let u=[];if(i.start)u.push("start");if(i.root)u.push("root");if(typeof i.port==="number")u.push("port");if(i.build)u.push("build");if(i.preStart&&i.preStart.length>0)u.push("preStart");if(u.length>0)n.push(`Site '${l}' 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(f==="server"&&!i.start&&!i.root){r.push(`Site '${l}' sets deploy:'server' but declares neither \`start\` (dynamic app) nor \`root\` (static site to serve). Add one.`);continue}if(R==="server-php"){if(!s)r.push(`Site '${l}' is a PHP site (type:'${i.type}') but no \`infrastructure.compute\` is configured. Add a server (infrastructure.compute) with PHP provisioning.`);if(!i.repository?.url)r.push(`Site '${l}' is a PHP site (type:'${i.type}') but has no \`repository.url\` to clone. PHP sites deploy via git.`)}else if(R==="server-app"){if(!s)r.push(`Site '${l}' deploys to a server (deploy:'server'${i.deploy?"":" inferred from `start`"}) but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`);if(typeof i.port==="number"){let u=t.occupiedPorts?.get(i.port);if(u)r.push(`Site '${l}' wants port ${i.port}, which project '${u}' already serves on this box. Attached projects share one port namespace. Give '${l}' a free port, or let the attach allocate one.`);let a=p.get(i.port);if(a)r.push(`Sites '${a}' and '${l}' both use port ${i.port}. Server apps sharing a box must use distinct ports.`);else p.set(i.port,l)}}else if(R==="server-static"){if(!i.root)r.push(`Site '${l}' is a server static site (deploy:'server', no \`start\`) but has no \`root\` directory to serve.`);if(!s)r.push(`Site '${l}' deploys to a server (deploy:'server') but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`)}else{if(!i.root)r.push(`Site '${l}' deploys to a bucket but has no \`root\` directory to upload.`);let u=[];if(i.start)u.push("start");if(typeof i.port==="number")u.push("port");if(i.preStart&&i.preStart.length>0)u.push("preStart");if(u.length>0)n.push(`Site '${l}' 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 jo(e){let t=P(e);return t!=="bucket"&&t!=="redirect"&&t!=="proxy"}function Uc(e){return P(e)==="bucket"}function Fc(e,t){if(H(e)==="serverless")return!0;let r=Object.entries(e.sites??{}).filter(([,o])=>o!=null),n=t?r.filter(([o])=>o===t):r;if(n.length===0)return!0;return!n.every(([,o])=>{let s=P(o);return s==="redirect"||s==="proxy"})}var A={php:"php.net",nginx:"nginx.org",composer:"getcomposer.org",mysql:"mysql.com",mariadb:"mariadb.com/server",postgres:"postgresql.org",vitess:"vitess.io",etcd:"etcd.io",redis:"redis.io",memcached:"memcached.org",meilisearch:"meilisearch.com",mail:"github.com/mail-os/mail",git:"git-scm.com",certbot:"certbot.eff.org",bun:"bun.sh",node:"nodejs.org",deno:"deno.land"};var U="/opt/pantry";function M(e){return`'${e.split("'").join("'\\''")}'`}function wr(e={}){return["export DEBIAN_FRONTEND=noninteractive","export PANTRY_SERVICE_SCOPE=system","export PANTRY_INSTALL_DIR=/usr/local/bin",e.version?`export PANTRY_VERSION=${M(e.version)}`:'export PANTRY_VERSION="${PANTRY_VERSION:-latest}"',"command -v curl >/dev/null 2>&1 || (apt-get update -y && apt-get install -y curl ca-certificates)","command -v unzip >/dev/null 2>&1 || (apt-get update -y && apt-get install -y unzip)",'OS=$(uname -s | tr \'[:upper:]\' \'[:lower:]\'); ARCH=$(uname -m); case "$ARCH" in x86_64|amd64) ARCH=x64 ;; arm64|aarch64) ARCH=arm64 ;; esac; ZIP="pantry-${OS}-${ARCH}.zip"; if [ "${PANTRY_VERSION:-latest}" = latest ]; then REL=\'latest/download\'; else REL="download/v${PANTRY_VERSION}"; fi; TMP=$(mktemp -d); curl -fsSL -o "${TMP}/${ZIP}" "https://github.com/pantry-pm/pantry/releases/${REL}/${ZIP}"; unzip -o "${TMP}/${ZIP}" -d /usr/local/bin; chmod +x /usr/local/bin/pantry; rm -rf "${TMP}"','export PATH="/usr/local/bin:$PATH"',"mkdir -p /opt/pantry"]}function St(){return'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true'}function et(e){if(e.length===0)return[];return[`(cd /opt/pantry && pantry install ${[...new Set(e)].map(M).join(" ")})`]}function Rs(e){return[...new Set(e)].flatMap((t)=>[`(cd /opt/pantry && pantry start ${M(t)})`,`(cd /opt/pantry && pantry enable ${M(t)})`])}var m="/etc/mail",T="mail-server",q="mail",F=`${U}/pantry/.bin`;function h(e){return`'${String(e).split("'").join("'\\''")}'`}function C(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function ge(e){return[e.version?`${A.mail}@${e.version}`:A.mail]}function Y(e,t){return`${m}/dkim/${t}.${e.dkim.selector}.pem`}function re(e){return`${e.storagePath}/smtp.db`}function Te(e){let t=["# Generated by ts-cloud. Edits are overwritten on the next deploy —","# change `services.mail` in the cloud config instead.","","[server]",`host = ${C(e.bindAddress)}`,`port = ${e.ports.smtp}`,`hostname = ${C(e.hostname)}`];if(e.domains.length>0)t.push(`local_domains = ${C(e.domains.join(", "))}`);if(e.mode==="catcher")t.push("catch_all = true");if(t.push(`max_message_size = ${e.maxMessageSize}`,"","[tls]",`enabled = ${e.tls.enabled}`),e.tls.certPath)t.push(`cert_path = ${C(e.tls.certPath)}`);if(e.tls.keyPath)t.push(`key_path = ${C(e.tls.keyPath)}`);if(t.push("","[auth]",`enabled = ${e.mode==="server"}`,"","[antispam]",`dnsbl = ${e.spam.dnsbl}`,`greylist = ${e.spam.greylist}`,`spam_filter = ${e.spam.enabled}`,`junk_score = ${e.spam.junkScore}`,`reject_score = ${e.spam.rejectScore}`,"","[dkim]",`rotation_enabled = ${e.dkim.enabled&&e.dkim.rotate}`,`rotation_interval_days = ${e.dkim.rotateIntervalDays}`,"","[acme]",`enabled = ${e.tls.acme}`),e.tls.acmeEmail)t.push(`email = ${C(e.tls.acmeEmail)}`);if(t.push("","[webhook]",`enabled = ${!!e.webhookUrl}`),e.webhookUrl)t.push(`url = ${C(e.webhookUrl)}`);return t.push(""),t.join(`
2
2
  `)}function he(e){let t=["# Generated by ts-cloud. See /etc/mail/config.toml for the rest.",`SMTP_DB_PATH=${re(e)}`,`SMTP_DELIVERY_METHOD=${e.delivery==="ses"?"ses":"direct"}`];if(e.delivery==="ses")t.push(`SMTP_SES_REGION=${e.sesRegion}`);if(e.ports.submission)t.push(`SUBMISSION_PORT=${e.ports.submission}`);if(e.ports.submissions)t.push(`SMTPS_PORT=${e.ports.submissions}`);if(e.ports.imap)t.push("IMAP_ENABLED=1",`IMAP_PORT=${e.ports.imap}`);if(e.webmail.enabled)t.push("SMTP_ENABLE_WEBMAIL=true",`SMTP_WEBMAIL_PORT=${e.webmail.port}`,`SMTP_WEBMAIL_SECURE_COOKIES=${e.tls.enabled}`);if(e.tls.requireForAuth)t.push("SMTP_REQUIRE_TLS_FOR_AUTH=true");if(e.dkim.enabled&&e.domains.length>0){let[r,...n]=e.domains;if(t.push(`DKIM_DOMAIN=${r}`,`DKIM_SELECTOR=${e.dkim.selector}`,`DKIM_PRIVATE_KEY_PATH=${Y(e,r)}`),n.length>0){let o=n.map((s)=>`${s}:${e.dkim.selector}:${Y(e,s)}`);t.push(`DKIM_EXTRA_KEYS=${o.join(",")}`)}}return t.push(""),t.join(`
3
3
  `)}function Ee(e){let t=[e.ports.smtp,e.ports.submission,e.ports.submissions,e.ports.imap,e.ports.imaps].some((r)=>typeof r==="number"&&r<1024);return["[Unit]","Description=Mail server (SMTP/IMAP + webmail)","After=network-online.target","Wants=network-online.target","","[Service]","Type=simple",`User=${T}`,`Group=${T}`,`WorkingDirectory=${e.storagePath}`,`EnvironmentFile=${m}/mail.env`,`Environment="PATH=${F}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"`,`ExecStart=${F}/mail serve --config ${m}/config.toml`,"Restart=always","RestartSec=5","LimitNOFILE=65536",...t?["AmbientCapabilities=CAP_NET_BIND_SERVICE","CapabilityBoundingSet=CAP_NET_BIND_SERVICE"]:[],"NoNewPrivileges=true","PrivateTmp=true","ProtectSystem=strict","ProtectHome=true","ProtectKernelTunables=true","ProtectKernelModules=true","ProtectControlGroups=true",`ReadWritePaths=${e.storagePath} ${m}`,"","[Install]","WantedBy=multi-user.target",""].join(`
4
4
  `)}function ve(e){if(!e.dkim.enabled||e.domains.length===0)return[];let t=[`mkdir -p ${m}/dkim`];for(let r of e.domains){let n=Y(e,r);t.push(`if [ ! -f ${h(n)} ]; then openssl genrsa -out ${h(n)} 2048; fi`,`chmod 0600 ${h(n)}`,`echo "DKIM ${e.dkim.selector}._domainkey.${r} IN TXT v=DKIM1; k=rsa; p=$(openssl rsa -in ${h(n)} -pubout -outform PEM 2>/dev/null | grep -v '^-----' | tr -d '\\n')"`)}return t.push(`chown -R ${T}:${T} ${m}/dkim`),t}function ye(e){if(e.accounts.length===0)return[];let t=(r)=>`runuser -u ${T} -- env SMTP_DB_PATH="$TS_CLOUD_MAIL_DB" ${F}/mail user:local ${r} || true`;return e.accounts.flatMap((r)=>[t(`create ${h(r.address)} ${h(r.password)} ${h(r.address)}`),t(`change-password ${h(r.address)} ${h(r.password)}`)])}function ne(e){if(!e.enabled)return[];return[...et(ge(e)),`id -u ${T} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin ${T}`,`mkdir -p ${e.storagePath} ${m}`,`chown -R ${T}:${T} ${e.storagePath}`,`TS_CLOUD_MAIL_DB="$(grep -sE '^SMTP_DB_PATH=' ${m}/mail.env | head -1 | cut -d= -f2- || true)"`,`[ -n "$TS_CLOUD_MAIL_DB" ] || TS_CLOUD_MAIL_DB=${h(re(e))}`,`cat > ${m}/config.toml <<'TS_CLOUD_MAIL_CONF_EOF'`,Te(e),"TS_CLOUD_MAIL_CONF_EOF",`cat > ${m}/mail.env <<'TS_CLOUD_MAIL_ENV_EOF'`,he(e),"TS_CLOUD_MAIL_ENV_EOF",`sed -i "s|^SMTP_DB_PATH=.*|SMTP_DB_PATH=$TS_CLOUD_MAIL_DB|" ${m}/mail.env`,`chmod 0640 ${m}/mail.env`,`chown root:${T} ${m}/mail.env`,...ve(e),`cat > /etc/systemd/system/${q}.service <<'TS_CLOUD_MAIL_UNIT_EOF'`,Ee(e),"TS_CLOUD_MAIL_UNIT_EOF","systemctl daemon-reload",`systemctl enable ${q}`,`systemctl restart ${q}`,...ye(e)]}var g=`${U}/pantry/.bin`,W=15306,K=15991,B=15999,se=16101,V=2379,E="/var/lib/vitess",X=100;function vi(e){return e===!0||typeof e==="object"&&e!==null}function Re(e){return typeof e==="object"&&e!==null?e:{}}function _(e){return`'${String(e).split("'").join("'\\''")}'`}function Ce(e){let r=[e.version?`vitess.io@${e.version}`:"vitess.io"];if(e.mode!=="combo"&&!e.etcdEndpoint)r.push("etcd.io");return r.push("mysql.com@8.0.43"),r}var S="vitess",Pe=`${g}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`,ce="/usr/local/lib/vitess",z=new Map;function j(e){return`${ce}/${e}.sh`}function D(e,t){return z.set(e,be(t)),`/bin/sh ${j(e)}`}function oe(){let e=[`mkdir -p ${ce}`];for(let[t,r]of z)e.push(`cat > ${j(t)} <<'TS_CLOUD_VITESS_LAUNCHER_EOF'`,r,"TS_CLOUD_VITESS_LAUNCHER_EOF",`chmod 0755 ${j(t)}`);return e}function be(e){return["#!/bin/sh","set -e",`cd ${U}`,`PANTRY_ENV="$(pantry env 2>/dev/null | grep -E '^(export [A-Za-z_]|[A-Za-z_][A-Za-z0-9_]*=)' || true)"`,'if [ -n "$PANTRY_ENV" ]; then eval "$PANTRY_ENV"; fi',`VT_MYSQL_ROOT="$(dirname "$(dirname "$(readlink -f ${g}/mysqld 2>/dev/null)")")"`,`VTROOT="$(dirname "$(dirname "$(readlink -f ${g}/mysqlctld 2>/dev/null)")")"`,"export VT_MYSQL_ROOT VTROOT",'LD_LIBRARY_PATH="$VT_MYSQL_ROOT/lib:$VTROOT/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"',"export LD_LIBRARY_PATH",`exec ${e.join(" ")}`].join(`
5
5
  `)}function L(e){let t=["[Unit]",`Description=${e.description}`,`After=network.target${e.after?.length?` ${e.after.join(" ")}`:""}`];if(e.requires?.length)t.push(`Requires=${e.requires.join(" ")}`);return t.push("","[Service]","Type=simple",`User=${S}`,`Group=${S}`,`Environment="PATH=${Pe}"`,`Environment="VTDATAROOT=${E}"`,...Object.entries(e.environment??{}).map(([r,n])=>`Environment="${r}=${n}"`),...(e.execStartPre??[]).map((r)=>`ExecStartPre=${r}`),`ExecStart=${e.execStart}`,"Restart=always","RestartSec=5","LimitNOFILE=65535","","[Install]","WantedBy=multi-user.target"),t.join(`
6
6
  `)}function ie(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_VITESS_UNIT_EOF'`,t,"TS_CLOUD_VITESS_UNIT_EOF"]}function De(e){let t=e.cell??"zone1",r=e.vtgatePort??W,o=`${((e.keyspaces?.length)?e.keyspaces:[{name:"app"}]).map((s)=>{let c=(s.sharded?["-80","80-"]:["0"]).map((p)=>`shards:{name:"${p}"}`).join(" ");return`keyspaces:{name:"${s.name}" ${c}}`}).join(" ")} cells:"${t}"`;return L({description:"Vitess (vtcombo, single-process development stack)",execStart:D("vtcombo",[`${g}/vtcombo`,`--cell ${t}`,`--proto-topo ${_(o)}`,`--mysql-server-port ${r}`,"--mysql-server-bind-address 127.0.0.1","--mysql-auth-server-impl none","--start-mysql",`--port ${K}`,`--grpc-port ${B}`])})}function Le(){return L({description:"etcd (Vitess topology store)",execStart:D("etcd",[`${g}/etcd`,`--data-dir ${E}/etcd`,`--listen-client-urls http://127.0.0.1:${V}`,`--advertise-client-urls http://127.0.0.1:${V}`]),execStartPre:[`+/bin/mkdir -p ${E}/etcd`,`+/bin/chown ${S}:${S} ${E}/etcd`]})}function Q(e){return["--topo-implementation etcd2",`--topo-global-server-address ${e.etcdEndpoint??`http://127.0.0.1:${V}`}`,"--topo-global-root /vitess/global"]}function Oe(e){let t=!e.etcdEndpoint;return L({description:"Vitess vtctld (control plane)",after:t?["vitess-etcd.service"]:[],requires:t?["vitess-etcd.service"]:[],execStart:D("vtctld",[`${g}/vtctld`,...Q(e),`--cell ${e.cell??"zone1"}`,"--service-map grpc-vtctl,grpc-vtctld",`--grpc-port ${B}`,`--port ${B+1}`])})}function Ae(e,t,r){let n=e.cell??"zone1";return L({description:`Vitess vttablet (${t}/${r})`,after:["vitess-vtctld.service","vitess-mysqlctld.service"],requires:["vitess-mysqlctld.service"],execStart:D("vttablet",[`${g}/vttablet`,...Q(e),`--tablet-path ${n}-${String(X).padStart(10,"0")}`,`--init-keyspace ${t}`,`--init-shard ${r}`,"--init-tablet-type replica",`--service-map ${_("grpc-queryservice,grpc-tabletmanager,grpc-updatestream")}`,`--port ${se}`,`--grpc-port ${se+1}`,`--db-port ${e.mysqlPort??3306}`,`--mycnf-mysql-port ${e.mysqlPort??3306}`])})}function Ue(e){return L({description:"Vitess mysqlctld (managed mysqld)",execStart:D("mysqlctld",[`${g}/mysqlctld`,`--tablet-uid ${X}`,`--mysql-port ${e.mysqlPort??3306}`,'--init-db-sql-file "$VTROOT/config/init_db.sql"',"--wait-time 2m"]),execStartPre:[`+/bin/mkdir -p ${E}`,`+/bin/chown ${S}:${S} ${E}`]})}var le="/etc/vitess/auth.json",x="/var/lib/vitess/vtgate-auth.sha256";function xe(e){let t=e.username??"vitess",r=e.password??"";return["mkdir -p /etc/vitess",'VTESS_AUTH_TMP="$(mktemp)"',`cat > "$VTESS_AUTH_TMP" <<'TS_CLOUD_VITESS_AUTH_EOF'`,JSON.stringify({[t]:[{Password:r,UserData:t}]}),"TS_CLOUD_VITESS_AUTH_EOF",`VTESS_VTGATE_AUTH_SHA="$(sha256sum "$VTESS_AUTH_TMP" | awk '{print $1}')"`,"VTESS_VTGATE_AUTH_CHANGED=1",`if [ -f ${x} ] && [ "$(cat ${x})" = "$VTESS_VTGATE_AUTH_SHA" ]; then VTESS_VTGATE_AUTH_CHANGED=0; fi`,`install -o ${S} -g ${S} -m 0600 "$VTESS_AUTH_TMP" ${le}`,'rm -f "$VTESS_AUTH_TMP"']}function Ie(e){let t=e.cell??"zone1";return L({description:"Vitess vtgate (query router)",after:["vitess-vtctld.service"],execStart:D("vtgate",[`${g}/vtgate`,...Q(e),`--cell ${t}`,`--cells-to-watch ${t}`,"--tablet-types-to-wait PRIMARY,REPLICA",`--service-map ${_("grpc-vtgateservice")}`,`--mysql-server-port ${e.vtgatePort??W}`,`--mysql-server-bind-address ${e.bindAddress??"127.0.0.1"}`,"--mysql-auth-server-impl static",`--mysql-auth-server-static-file ${le}`,`--port ${K}`,`--grpc-port ${K+1}`])})}function ke(e){let t=e.cell??"zone1",r=e.etcdEndpoint??`http://127.0.0.1:${V}`,n=`${g}/vtctldclient --server 127.0.0.1:${B}`,o=[`for i in $(seq 1 30); do ${n} GetCellInfoNames >/dev/null 2>&1 && break; sleep 2; done`,`if ! ${n} GetCellInfoNames 2>/dev/null | grep -qx ${_(t)}; then`,` ${n} AddCellInfo --root ${_(`/vitess/${t}`)} --server-address ${_(r)} ${_(t)}`,"fi"];for(let s of e.keyspaces??[]){let c=s.sharded?" --sharded":"";o.push(`if ! ${n} GetKeyspace ${_(s.name)} >/dev/null 2>&1; then`,` ${n} CreateKeyspace${c} ${_(s.name)}`,"fi");let p=`${t}-${String(X).padStart(10,"0")}`;for(let l of s.sharded?["-80","80-"]:["0"]){let i=`${s.name}/${l}`;o.push("for i in $(seq 1 90); do",` if ${n} GetShard ${_(i)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then break; fi`,` ${n} PlannedReparentShard ${_(i)} --new-primary ${_(p)} >/dev/null 2>&1 && break`,` ${n} InitShardPrimary --force ${_(i)} ${_(p)} >/dev/null 2>&1 && break`," sleep 2","done",`if ! ${n} GetShard ${_(i)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then`,` echo "no primary could be elected for ${i}" >&2; exit 1`,"fi")}o.push(`${n} RebuildKeyspaceGraph ${_(s.name)} >/dev/null`)}return o}function ae(e){let t=e.vtgatePort??W;return["for i in $(seq 1 60); do",` if (cd ${U} && eval "$(pantry env 2>/dev/null)"; MYSQL_PWD=${_(e.password??"")} ${g}/mysql -h 127.0.0.1 -P ${t} -u ${_(e.username??"vitess")} --connect-timeout=2 -e 'SHOW KEYSPACES') >/dev/null 2>&1; then`,` echo "vtgate is serving on ${t}"; exit 0`," fi"," sleep 2","done",`echo "vtgate did not become ready on port ${t}" >&2`,"exit 1"]}function Is(e){if(!vi(e))return[];let t=Re(e),r=t.mode==="combo";z.clear();let n=['if [ "$(uname -m)" != "x86_64" ]; then',' echo "vitess: Vitess publishes only x86_64 release tarballs; this box is $(uname -m). Drop managedServices.vitess or use an x86_64 host." >&2'," exit 1","fi",...et(Ce(t)),`VT_MYSQL_LIB="$(dirname "$(dirname "$(readlink -f ${g}/mysqld)")")/lib"`,'if [ -d "$VT_MYSQL_LIB" ]; then',` printf '%s\\n' "$VT_MYSQL_LIB" > /etc/ld.so.conf.d/vitess-mysql.conf`," ldconfig","else",' echo "mysqld library directory not found under $VT_MYSQL_LIB" >&2; exit 1',"fi",`id -u ${S} >/dev/null 2>&1 || useradd --system --home-dir ${E} --shell /usr/sbin/nologin ${S}`,`mkdir -p ${E}`,`chown -R ${S}:${S} ${E}`];if(r)return n.push(...ie("vitess-vtcombo",De(t)),...oe(),"systemctl daemon-reload","systemctl enable --now vitess-vtcombo.service",...ae(t)),n;n.push(...xe(t));let o=[];if(!t.etcdEndpoint)o.push(["vitess-etcd",Le()]);o.push(["vitess-vtctld",Oe(t)],["vitess-mysqlctld",Ue(t)],["vitess-vtgate",Ie(t)]);for(let s of t.keyspaces??[])for(let c of s.sharded?["-80","80-"]:["0"])o.push([`vitess-vttablet-${s.name}-${c.replace(/-/g,"x")}`,Ae(t,s.name,c)]);for(let[s,c]of o)n.push(...ie(s,c));n.push(...oe()),n.push("systemctl daemon-reload");for(let[s]of o)n.push(`systemctl enable --now ${s}.service`);return n.push(`if [ "$VTESS_VTGATE_AUTH_CHANGED" = 1 ]; then systemctl restart vitess-vtgate.service; printf '%s\\n' "$VTESS_VTGATE_AUTH_SHA" > ${x}; chown ${S}:${S} ${x}; chmod 0600 ${x}; fi`,...ke(t),...ae(t)),n}var Ne=new Set(["singlestore","vitess"]);function Ci(e){if(e?.engine&&Ne.has(e.engine))return!1;return!e?.host||e.host==="127.0.0.1"||e.host==="localhost"}function Ar(e,t="psql"){let r=e?.port??5432;if(Ci(e))return`${t} -p ${r} -U postgres`;let n=e?.username||"postgres";return`${e?.password?`PGPASSWORD='${e.password.replace(/'/g,"'\\''")}' `:""}${t} -h ${e.host} -p ${r} -U ${n} -w`}function v(e){return e===!0||typeof e==="object"&&e!=null}function Me(e){let t=[],r=[];if(v(e.mysql))t.push(typeof e.mysql==="object"&&e.mysql.version?`mysql.com@${e.mysql.version}`:"mysql.com@8.0.43"),r.push("mysql");else if(v(e.mariadb))t.push(A.mariadb),r.push("mariadb");if(v(e.postgres))t.push("postgresql.org"),r.push("postgres");if(v(e.redis))t.push("redis.io"),r.push("redis");if(v(e.memcached))t.push("memcached.org"),r.push("memcached");if(v(e.meilisearch))t.push("meilisearch.com"),r.push("meilisearch");return{packages:t,services:r}}function Ps(e={},t={}){let r=Me(e),n=Is(e.vitess),o=t.mail?ne(t.mail):[];if(r.packages.length===0)return[...n,...o];return[...et(r.packages),...Rs(r.services),...n,...o]}function vt(e,t={}){if(!e?.name)return[];if(!Ci(e))return[];let r=e.name,n=e.username||r,o=e.password||"",s=v(t.postgres)||e.engine==="postgres",c=v(t.mariadb)||e.engine==="mariadb",p=v(t.mysql)||e.engine==="mysql";if(s&&!p&&!c){let a=(d)=>`"${d.replace(/"/g,'""')}"`,b=(d)=>`'${d.replace(/'/g,"''")}'`,O=(d,N)=>["DO $$ BEGIN",` IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${b(d)}) THEN`,` CREATE ROLE ${a(d)} LOGIN PASSWORD ${b(N)};`," ELSE",` ALTER ROLE ${a(d)} LOGIN PASSWORD ${b(N)};`," END IF;","END $$;"],I=(d)=>{let N=d.databases&&d.databases.length>0?d.databases:[r],w=[];for(let G of N)if(d.access==="readonly")w.push(`GRANT CONNECT ON DATABASE ${a(G)} TO ${a(d.username)};`,`\\connect ${a(G)}`,`GRANT USAGE ON SCHEMA public TO ${a(d.username)};`,`GRANT SELECT ON ALL TABLES IN SCHEMA public TO ${a(d.username)};`,`ALTER DEFAULT PRIVILEGES FOR ROLE ${a(n)} IN SCHEMA public GRANT SELECT ON TABLES TO ${a(d.username)};`,"\\connect postgres");else w.push(`GRANT ALL PRIVILEGES ON DATABASE ${a(G)} TO ${a(d.username)};`);return w},k=e.users||[],Se=e.port??5432;return[St(),`for i in $(seq 1 30); do pg_isready -p ${Se} -q && break; sleep 2; done`,`${Ar(e)} <<'TS_CLOUD_PG_EOF'`,...O(n,o),`SELECT 'CREATE DATABASE ${a(r)} OWNER ${a(n)}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = ${b(r)})\\gexec`,...k.flatMap((d)=>[...O(d.username,d.password),...I(d)]),"TS_CLOUD_PG_EOF",...Be(e)]}let l=c?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock",i=(a)=>a.replace(/`/g,"``"),f=(a)=>a.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),R=(a)=>{let b=a.databases&&a.databases.length>0?a.databases:[r],O=a.access==="readonly"?"SELECT":"ALL PRIVILEGES",I=[`CREATE USER IF NOT EXISTS '${f(a.username)}'@'%' IDENTIFIED BY '${f(a.password)}';`,`CREATE USER IF NOT EXISTS '${f(a.username)}'@'localhost' IDENTIFIED BY '${f(a.password)}';`,`ALTER USER '${f(a.username)}'@'%' IDENTIFIED BY '${f(a.password)}';`,`ALTER USER '${f(a.username)}'@'localhost' IDENTIFIED BY '${f(a.password)}';`];for(let k of b)I.push(`GRANT ${O} ON \`${i(k)}\`.* TO '${f(a.username)}'@'%';`,`GRANT ${O} ON \`${i(k)}\`.* TO '${f(a.username)}'@'localhost';`);return I},u=e.users||[];return[St(),`for i in $(seq 1 30); do mysqladmin --socket=${l} -u root ping 2>/dev/null | grep -q alive && break; sleep 2; done`,`mysql --socket=${l} -u root <<'TS_CLOUD_SQL_EOF'`,`CREATE DATABASE IF NOT EXISTS \`${i(r)}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`,...R({username:n,password:o}),...u.flatMap(R),"FLUSH PRIVILEGES;","TS_CLOUD_SQL_EOF"]}function Be(e){return[`${Ar(e)} -tA <<'TS_CLOUD_PG_CAP_EOF' || true`,"\\set QUIET on","SELECT CASE WHEN used::float / NULLIF(cap, 0) >= 0.8"," THEN '[ts-cloud] postgres is at ' || used || '/' || cap || ' connections on this server.'"," || ' Raise max_connections (ALTER SYSTEM SET max_connections = ...; then restart) or'"," || ' set idle_session_timeout so abandoned pools are reclaimed.'"," ELSE NULL END","FROM (SELECT (SELECT count(*) FROM pg_stat_activity) AS used,"," (SELECT setting::int FROM pg_settings WHERE name = 'max_connections') AS cap) c","WHERE CASE WHEN used::float / NULLIF(cap, 0) >= 0.8 THEN true ELSE false END;","SELECT '[ts-cloud] ' || coalesce(datname, '(background)') || ': ' || count(*) || ' connection(s), oldest idle ' ||"," coalesce(round(extract(epoch from max(now() - state_change)) / 60)::text || 'm', 'n/a')","FROM pg_stat_activity","WHERE (SELECT count(*)::float / NULLIF((SELECT setting::int FROM pg_settings WHERE name = 'max_connections'), 0) FROM pg_stat_activity) >= 0.8","GROUP BY datname ORDER BY count(*) DESC;","TS_CLOUD_PG_CAP_EOF"]}function Bc(e){if(!e?.name)return{};let t=e.engine==="singlestore",r=e.engine==="vitess",n=e.engine==="postgres"?"pgsql":t?"singlestore":r?"vitess":"mysql",o=e.port??(e.engine==="postgres"?5432:r?15306:3306),s={DB_CONNECTION:n,DB_HOST:e.host||"127.0.0.1",DB_PORT:String(o),DB_DATABASE:e.name};if(e.username)s.DB_USERNAME=e.username;if(e.password)s.DB_PASSWORD=e.password;if((t||r)&&e.ssl!==!1)s.DB_SSL="true";return s}var Z="/var/backups/ts-cloud",Ve="/etc/ts-cloud/backups.config.ts",pe="/etc/cron.d/ts-cloud-backups",cn="/usr/local/bin/ts-cloud-backup.sh";function we(e){if(!e.name)return null;let t=e.host||"127.0.0.1",r=e.engine==="postgres",n=r?"postgresql":"mysql",o=e.port??(r?5432:3306),s=(c)=>c.replace(/\\/g,"\\\\").replace(/'/g,"\\'");return[" {",` type: '${n}',`,` name: '${s(e.name)}',`," connection: {",` hostname: '${s(t)}',`,` port: ${o},`,` database: '${s(e.name)}',`,` username: '${s(e.username||e.name)}',`,` password: '${s(e.password||"")}',`," ssl: false,"," },"," includeSchema: true,"," includeData: true,"," },"].join(`
7
7
  `)}function He(e,t){let r=e?we(e):null,n=t.bucket?[" destinations: ["," {"," type: 's3',",` bucket: '${t.bucket}',`," prefix: 'db-backups',",...t.endpoint?[` endpoint: '${t.endpoint}',`]:[]," optional: false,"," },"," ],"]:[];return["import type { BackupConfig } from 'ts-backups'","","const config: BackupConfig = {"," verbose: true,",` outputPath: '${Z}',`," retention: {",` count: ${t.retentionCount??5},`,` maxAge: ${t.retentionDays??30},`," },"," databases: [",...r?[r]:[]," ],",...n,"}","","export default config",""].join(`
8
- `)}function Ds(e){let{database:t,backups:r}=e;if(!r.enabled)return[];let n=r.schedule||"0 2 * * *",o=He(t,r);return["export DEBIAN_FRONTEND=noninteractive",`mkdir -p /etc/ts-cloud ${Z}`,"command -v bun >/dev/null 2>&1 || (curl -fsSL https://bun.sh/install | bash && ln -sf /root/.bun/bin/bun /usr/local/bin/bun)","bun add -g ts-backups || true",`cat > ${Ve} <<'TS_CLOUD_BACKUP_CFG_EOF'`,o.replace(/\n$/,""),"TS_CLOUD_BACKUP_CFG_EOF",`cat > ${cn} <<'TS_CLOUD_BACKUP_RUN_EOF'`,"#!/bin/bash","set -uo pipefail",'export PATH="/root/.bun/bin:/usr/local/bin:$PATH"','notify() { [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "$1" || true; }',"cd /etc/ts-cloud",'if ! ts-backups start --config /etc/ts-cloud/backups.config.ts; then notify "❌ ts-cloud backup failed"; exit 1; fi',"TS_CLOUD_BACKUP_RUN_EOF",`chmod +x ${cn}`,`cat > ${pe} <<'TS_CLOUD_BACKUP_CRON_EOF'`,`${n} root ${cn} >> /var/log/ts-cloud-backup.log 2>&1`,"TS_CLOUD_BACKUP_CRON_EOF",`chmod 644 ${pe}`]}function Ge(e){return e==="mariadb"?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock"}function Ti(e,t={}){if(!e?.name)return[];let r=e.name,n=e.engine==="postgres",o=t.from?`TS_CLOUD_DUMP="${t.from}"`:`TS_CLOUD_DUMP="$(find ${Z} -type f -name '*${r}*.sql' -o -type f -name '*${r}*.sql.gz' 2>/dev/null | xargs -r ls -1t 2>/dev/null | head -1)"`,s=n?`${Ar(e)} -d "${r}"`:`mysql --socket=${Ge(e.engine)} -u root "${r}"`;return["set -uo pipefail",'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true',o,'[ -n "$TS_CLOUD_DUMP" ] && [ -f "$TS_CLOUD_DUMP" ] || { echo "no backup dump found to restore" >&2; exit 1; }','echo "[ts-cloud] restoring '+r+' from $TS_CLOUD_DUMP"',`case "$TS_CLOUD_DUMP" in *.gz) gunzip -c "$TS_CLOUD_DUMP" ;; *) cat "$TS_CLOUD_DUMP" ;; esac | ${s}`,'echo "restore complete"']}var Ns=["storage",".env"],Ei=4;function y(e){return`${e.replace(/\/+$/,"")}/.ts-cloud`}function Vo(e){return`${y(e)}/deploy-history.log`}function qe(e,t){return`${y(e)}/deploys/${t}.log`}function ue(e){return`${y(e)}/shared-paths`}function ks(e){return`${e.shared}/stx-images`}function Vt(e,t){let r=e.replace(/\/+$/,"");return{base:r,releases:`${r}/releases`,shared:`${r}/shared`,current:`${r}/current`,release:`${r}/releases/${t}`}}function de(e){let t=e.split("/").pop()||e;if(t===".env"||t.startsWith(".env."))return!0;return/\.[a-z0-9]+$/i.test(t)}function zo(e){return typeof e==="string"?e:e.path}function jc(e){let t=new Map;for(let r of e)t.set(zo(r),r);return[...t.values()]}function $e(e,t){if(typeof t==="string")return{path:t,target:`${e.shared}/${t}`,seed:!0};return{path:t.path,target:t.target??`${e.shared}/${t.path}`,seed:t.seed!==!1}}function Fe(e){return["ts_cloud_adopt_shared() {",' TS_CLOUD_SP="$1"',' TS_CLOUD_DST="$2"',` TS_CLOUD_SRC="${e.current}/$TS_CLOUD_SP"`,' if [ -e "$TS_CLOUD_DST" ]; then return 0; fi',' if [ -L "$TS_CLOUD_SRC" ] || [ ! -e "$TS_CLOUD_SRC" ]; then return 0; fi',' mkdir -p "$(dirname "$TS_CLOUD_DST")"',' cp -a "$TS_CLOUD_SRC" "$TS_CLOUD_DST"'," for TS_CLOUD_SIDECAR in -wal -shm; do",' if [ -f "$TS_CLOUD_SRC$TS_CLOUD_SIDECAR" ]; then cp -a "$TS_CLOUD_SRC$TS_CLOUD_SIDECAR" "$TS_CLOUD_DST$TS_CLOUD_SIDECAR"; fi'," done",' echo "[ts-cloud] adopted $TS_CLOUD_SP from the live release into shared/ — it now survives deploys"'," return 0","}"]}function wi(e,t=Ns){let r=[`mkdir -p ${e.releases} ${e.shared} ${ks(e)}`,...Fe(e)],n=t.map((s)=>$e(e,s));for(let{path:s,target:c,seed:p}of n){if(!p)continue;if(r.push(`ts_cloud_adopt_shared '${s}' '${c}'`),de(s))r.push(`mkdir -p "$(dirname ${c})"`,`touch ${c}`);else if(s==="storage")r.push(`mkdir -p ${c}/app/public`,`mkdir -p ${c}/framework/cache/data`,`mkdir -p ${c}/framework/sessions`,`mkdir -p ${c}/framework/testing`,`mkdir -p ${c}/framework/views`,`mkdir -p ${c}/logs`);else r.push(`mkdir -p ${c}`)}let o=ue(e.base);return r.push(`mkdir -p ${y(e.base)}`,`cat > ${o} <<'TS_CLOUD_SHARED_PATHS_EOF'`,...n.map((s)=>`${s.path} ${s.target}`),"TS_CLOUD_SHARED_PATHS_EOF"),r}function Ho(e,t=900){let r=`${y(e.base)}/deploy.lock`;return[`mkdir -p "$(dirname ${r})"`,`exec 9>${r}`,`flock -w ${t} 9 || { echo "[ts-cloud] another deploy of this site has held the lock for ${t}s — refusing to race it" >&2; exit 1; }`]}function Go(e){let t=`${e.release}.incoming`;return[`rm -rf ${t}`,`mkdir -p ${t}`,...Ye(e),'if [ "$TS_CLOUD_IS_LIVE" = "yes" ]; then',` TS_CLOUD_STAGED=${t}`,"else",` rm -rf ${e.release}`,` mkdir -p ${e.release}`,` rmdir ${t}`,` TS_CLOUD_STAGED=${e.release}`,"fi"]}function qo(e){let t=`TS_CLOUD_TRAP_LIVE="$(readlink -f ${e.current} 2>/dev/null || true)"`,r=`TS_CLOUD_TRAP_TARGET="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`;return`trap '${`if [ $? -ne 0 ]; then ${t}; ${r}; [ "$TS_CLOUD_TRAP_LIVE" = "$TS_CLOUD_TRAP_TARGET" ] || rm -rf ${e.release}; fi`}' EXIT`}function Ye(e){return[`TS_CLOUD_LIVE_PATH="$(readlink -f ${e.current} 2>/dev/null || true)"`,`TS_CLOUD_RELEASE_PATH="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`,'if [ -n "$TS_CLOUD_LIVE_PATH" ] && [ "$TS_CLOUD_LIVE_PATH" = "$TS_CLOUD_RELEASE_PATH" ]; then TS_CLOUD_IS_LIVE=yes; else TS_CLOUD_IS_LIVE=no; fi']}function Wo(e){let t=`${e.release}.incoming`;return[`if [ "$TS_CLOUD_STAGED" = "${t}" ]; then`,` rm -rf ${e.release}.previous`,` mv ${e.release} ${e.release}.previous`,` mv ${t} ${e.release}`,` rm -rf ${e.release}.previous`,"fi"]}function Ke(e,t){return[`if [ -f ${e} ] && [ ! -L ${e} ] && [ -s ${e} ] && [ ! -s ${t} ]; then`,` cp -a ${e} ${t}`,` echo "[ts-cloud] seeded shared/ from the release's own copy of the file"`,"fi"]}function xs(e,t=Ns){let r=[];for(let n of t){let{path:o,target:s,seed:c}=$e(e,n),p=`${e.release}/${o}`,l=[`rm -rf ${p}`,`mkdir -p "$(dirname ${p})"`,`ln -sfn ${s} ${p}`];if(c){if(o!==".env"&&de(o))r.push(...Ke(p,s));r.push(...l);continue}r.push(`if [ -e ${s} ]; then`,...l.map((i)=>` ${i}`),"fi")}return r}function je(e,t){let r=ue(e.base);return[`if [ -f ${r} ]; then`,' while IFS="\t" read -r TS_CLOUD_SP TS_CLOUD_TGT; do',' [ -n "$TS_CLOUD_SP" ] || continue',` [ -n "$TS_CLOUD_TGT" ] || TS_CLOUD_TGT="${e.shared}/$TS_CLOUD_SP"`,' [ -e "$TS_CLOUD_TGT" ] || continue',` rm -rf ${t}/"$TS_CLOUD_SP"`,` mkdir -p "$(dirname ${t}/"$TS_CLOUD_SP")"`,` ln -sfn "$TS_CLOUD_TGT" ${t}/"$TS_CLOUD_SP"`,` done < ${r}`,"fi"]}function ln(e){return[`ln -sfn ${e.release} ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`]}function ee(e){return`${y(e)}/previous-release`}function Ko(e,t="TS_CLOUD_PREV_CURRENT"){let r=ee(e.base);return[`if [ -n "\${${t}:-}" ] && [ -d "$${t}" ] && [ "$(readlink -f "$${t}")" != "$(readlink -f ${e.release})" ]; then mkdir -p ${y(e.base)}; basename "$${t}" > ${r}; fi`]}function _e(e,t){let r=ee(e.base);return[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,...t?[`TS_CLOUD_RB_TARGET=${e.releases}/${t}`]:["TS_CLOUD_RB_TARGET=",`if [ -f ${r} ]; then TS_CLOUD_REC="${e.releases}/$(cat ${r})"; if [ -d "$TS_CLOUD_REC" ] && [ "$(readlink -f "$TS_CLOUD_REC")" != "$TS_CLOUD_CURRENT" ]; then TS_CLOUD_RB_TARGET="$TS_CLOUD_REC"; fi; fi`,`[ -n "$TS_CLOUD_RB_TARGET" ] || TS_CLOUD_RB_TARGET=$(ls -1dt ${e.releases}/*/ 2>/dev/null | sed 's#/$##' | while read -r r; do [ "$(readlink -f "$r")" != "$TS_CLOUD_CURRENT" ] && { echo "$r"; break; }; done)`],'[ -n "$TS_CLOUD_RB_TARGET" ] && [ -d "$TS_CLOUD_RB_TARGET" ] || { echo "no release to roll back to (looked for ${TS_CLOUD_RB_TARGET:-a previous release})" >&2; exit 1; }','[ "$(readlink -f "$TS_CLOUD_RB_TARGET")" != "$TS_CLOUD_CURRENT" ] || { echo "$(basename "$TS_CLOUD_RB_TARGET") is already the live release" >&2; exit 1; }','TS_CLOUD_RB_ID=$(basename "$TS_CLOUD_RB_TARGET")']}function Vc(e,t={}){return[..._e(e,t.to),'echo "would roll back from $(basename "${TS_CLOUD_CURRENT:-none}") to $TS_CLOUD_RB_ID (dry run: nothing changed)"']}function zc(e,t={}){let r=Math.max(1,t.gateSeconds??5),n=t.systemdDir??"/etc/systemd/system",o=[`ln -sfn "$TS_CLOUD_RB_TARGET" ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`,`rm -f ${ee(e.base)}`,'echo "rolled back to $TS_CLOUD_RB_ID"'],s=[..._e(e,t.to),...je(e,'"$TS_CLOUD_RB_TARGET"')];if(!t.unitBase)return[...s,...o];let c=t.unitBase,p=`${c}@\${TS_CLOUD_RB_ID}.service`;return[...s,`if [ -f ${n}/${c}@.service ]; then`,` systemctl start "${p}"`,` for TS_CLOUD_I in $(seq 1 ${r}); do sleep 1; systemctl is-active --quiet "${p}" || { echo "the release rolled back to, $TS_CLOUD_RB_ID, did not stay up; the current release keeps serving" >&2; journalctl -u "${p}" -n 30 --no-pager >&2 || true; systemctl stop "${p}" 2>/dev/null || true; exit 1; }; done`,...o.map((l)=>` ${l}`),` systemctl enable "${p}" 2>/dev/null || true`,` systemctl list-units --plain --no-legend --type=service "${c}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v "^${c}@\${TS_CLOUD_RB_ID}.service$" || true; } | while read -r TS_CLOUD_U; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done`,`elif [ -f ${n}/${c}.service ]; then`,...o.map((l)=>` ${l}`),` systemctl restart ${c}.service`,"else",...o.map((l)=>` ${l}`),"fi"]}function dn(e,t=4){let r=Math.max(1,t);return[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,`ls -1dt ${e.releases}/*/ 2>/dev/null | sed 's#/$##' | tail -n +${r+1} | while read -r TS_CLOUD_OLD; do`,' [ "$(readlink -f "$TS_CLOUD_OLD")" = "$TS_CLOUD_CURRENT" ] || rm -rf "$TS_CLOUD_OLD"',"done"]}function We(e){return`${y(e)}/owner`}function Jo(e,t){let r=We(e);return[`if [ -f "${r}" ]; then`,` TS_CLOUD_OWNER=$(cat "${r}")`,` if [ "$TS_CLOUD_OWNER" != "${t}" ]; then`,` echo "[ts-cloud] REFUSING deploy: ${e} belongs to project '$TS_CLOUD_OWNER', not '${t}'. Another project on this box derives the same site key — give one of them a distinct site name/domain, or remove ${r} to transfer ownership." >&2`," exit 1"," fi","else",` mkdir -p "$(dirname "${r}")"`,` printf '%s\\n' "${t}" > "${r}"`,"fi"]}function _s(e,t){let r=y(e),n=qe(e,t.releaseId),o=Vo(e),s=Math.max(1,t.keepLogs??20),c=t.commit||"",p=t.branch||"";return[`mkdir -p ${r}/deploys`,`exec > >(tee -a ${n}) 2>&1`,`echo "[ts-cloud] deploy ${t.releaseId} commit=${c} branch=${p} starting $(date -u +%Y-%m-%dT%H:%M:%SZ)"`,"ts_cloud_record_deploy() {"," TS_CLOUD_RC=$?",' if [ "$TS_CLOUD_RC" -eq 0 ]; then TS_CLOUD_ST=success; else TS_CLOUD_ST=failed; fi',` printf '%s\\t%s\\t%s\\t%s\\trc=%s\\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "${t.releaseId}" "${c}" "$TS_CLOUD_ST" "$TS_CLOUD_RC" >> ${o}`,"}","trap ts_cloud_record_deploy EXIT",`ls -1t ${r}/deploys/*.log 2>/dev/null | tail -n +${s+1} | while read -r TS_CLOUD_OLDLOG; do rm -f "$TS_CLOUD_OLDLOG"; done`]}
9
- export{J,Si,Fo,P,As,Bo,jo,Uc,Fc,U,wr,St,et,Rs,vi,Is,Ci,Ar,Ps,vt,Bc,cn,Ds,Ti,Ns,Ei,Vo,ks,Vt,zo,jc,wi,Ho,Go,qo,Wo,xs,ln,Ko,Vc,zc,dn,Jo,_s};
8
+ `)}function Ds(e){let{database:t,backups:r}=e;if(!r.enabled)return[];let n=r.schedule||"0 2 * * *",o=He(t,r);return["export DEBIAN_FRONTEND=noninteractive",`mkdir -p /etc/ts-cloud ${Z}`,"command -v bun >/dev/null 2>&1 || (curl -fsSL https://bun.sh/install | bash && ln -sf /root/.bun/bin/bun /usr/local/bin/bun)","bun add -g ts-backups || true",`cat > ${Ve} <<'TS_CLOUD_BACKUP_CFG_EOF'`,o.replace(/\n$/,""),"TS_CLOUD_BACKUP_CFG_EOF",`cat > ${cn} <<'TS_CLOUD_BACKUP_RUN_EOF'`,"#!/bin/bash","set -uo pipefail",'export PATH="/root/.bun/bin:/usr/local/bin:$PATH"','notify() { [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "$1" || true; }',"cd /etc/ts-cloud",'if ! ts-backups start --config /etc/ts-cloud/backups.config.ts; then notify "❌ ts-cloud backup failed"; exit 1; fi',"TS_CLOUD_BACKUP_RUN_EOF",`chmod +x ${cn}`,`cat > ${pe} <<'TS_CLOUD_BACKUP_CRON_EOF'`,`${n} root ${cn} >> /var/log/ts-cloud-backup.log 2>&1`,"TS_CLOUD_BACKUP_CRON_EOF",`chmod 644 ${pe}`]}function Ge(e){return e==="mariadb"?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock"}function Ti(e,t={}){if(!e?.name)return[];let r=e.name,n=e.engine==="postgres",o=t.from?`TS_CLOUD_DUMP="${t.from}"`:`TS_CLOUD_DUMP="$(find ${Z} -type f -name '*${r}*.sql' -o -type f -name '*${r}*.sql.gz' 2>/dev/null | xargs -r ls -1t 2>/dev/null | head -1)"`,s=n?`${Ar(e)} -d "${r}"`:`mysql --socket=${Ge(e.engine)} -u root "${r}"`;return["set -uo pipefail",'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true',o,'[ -n "$TS_CLOUD_DUMP" ] && [ -f "$TS_CLOUD_DUMP" ] || { echo "no backup dump found to restore" >&2; exit 1; }','echo "[ts-cloud] restoring '+r+' from $TS_CLOUD_DUMP"',`case "$TS_CLOUD_DUMP" in *.gz) gunzip -c "$TS_CLOUD_DUMP" ;; *) cat "$TS_CLOUD_DUMP" ;; esac | ${s}`,'echo "restore complete"']}var Ns=["storage",".env"],Ei=4;function y(e){return`${e.replace(/\/+$/,"")}/.ts-cloud`}function Vo(e){return`${y(e)}/deploy-history.log`}function qe(e,t){return`${y(e)}/deploys/${t}.log`}function ue(e){return`${y(e)}/shared-paths`}function ks(e){return`${e.shared}/stx-images`}function Vt(e,t){let r=e.replace(/\/+$/,"");return{base:r,releases:`${r}/releases`,shared:`${r}/shared`,current:`${r}/current`,release:`${r}/releases/${t}`}}function de(e){let t=e.split("/").pop()||e;if(t===".env"||t.startsWith(".env."))return!0;return/\.[a-z0-9]+$/i.test(t)}function zo(e){return typeof e==="string"?e:e.path}function jc(e){let t=new Map;for(let r of e)t.set(zo(r),r);return[...t.values()]}function $e(e,t){if(typeof t==="string")return{path:t,target:`${e.shared}/${t}`,seed:!0};return{path:t.path,target:t.target??`${e.shared}/${t.path}`,seed:t.seed!==!1}}function Fe(e){return["ts_cloud_adopt_shared() {",' TS_CLOUD_SP="$1"',' TS_CLOUD_DST="$2"',` TS_CLOUD_SRC="${e.current}/$TS_CLOUD_SP"`,' if [ -e "$TS_CLOUD_DST" ]; then return 0; fi',' if [ -L "$TS_CLOUD_SRC" ] || [ ! -e "$TS_CLOUD_SRC" ]; then return 0; fi',' mkdir -p "$(dirname "$TS_CLOUD_DST")"',' cp -a "$TS_CLOUD_SRC" "$TS_CLOUD_DST"'," for TS_CLOUD_SIDECAR in -wal -shm; do",' if [ -f "$TS_CLOUD_SRC$TS_CLOUD_SIDECAR" ]; then cp -a "$TS_CLOUD_SRC$TS_CLOUD_SIDECAR" "$TS_CLOUD_DST$TS_CLOUD_SIDECAR"; fi'," done",' echo "[ts-cloud] adopted $TS_CLOUD_SP from the live release into shared/ — it now survives deploys"'," return 0","}"]}function wi(e,t=Ns){let r=[`mkdir -p ${e.releases} ${e.shared} ${ks(e)}`,...Fe(e)],n=t.map((s)=>$e(e,s));for(let{path:s,target:c,seed:p}of n){if(!p)continue;if(r.push(`ts_cloud_adopt_shared '${s}' '${c}'`),de(s))r.push(`mkdir -p "$(dirname ${c})"`,`touch ${c}`);else if(s==="storage")r.push(`mkdir -p ${c}/app/public`,`mkdir -p ${c}/framework/cache/data`,`mkdir -p ${c}/framework/sessions`,`mkdir -p ${c}/framework/testing`,`mkdir -p ${c}/framework/views`,`mkdir -p ${c}/logs`);else r.push(`mkdir -p ${c}`)}let o=ue(e.base);return r.push(`mkdir -p ${y(e.base)}`,`cat > ${o} <<'TS_CLOUD_SHARED_PATHS_EOF'`,...n.map((s)=>`${s.path} ${s.target}`),"TS_CLOUD_SHARED_PATHS_EOF"),r}function Ho(e,t=900){let r=`${y(e.base)}/deploy.lock`;return[`mkdir -p "$(dirname ${r})"`,`exec 9>${r}`,`flock -w ${t} 9 || { echo "[ts-cloud] another deploy of this site has held the lock for ${t}s — refusing to race it" >&2; exit 1; }`]}function qo(e){let t=`${e.release}.incoming`;return[`rm -rf ${t}`,`mkdir -p ${t}`,...Ye(e),'if [ "$TS_CLOUD_IS_LIVE" = "yes" ]; then',` TS_CLOUD_STAGED=${t}`,"else",` rm -rf ${e.release}`,` mkdir -p ${e.release}`,` rmdir ${t}`,` TS_CLOUD_STAGED=${e.release}`,"fi"]}function Go(e){let t=`TS_CLOUD_TRAP_LIVE="$(readlink -f ${e.current} 2>/dev/null || true)"`,r=`TS_CLOUD_TRAP_TARGET="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`;return`trap '${`if [ $? -ne 0 ]; then ${t}; ${r}; [ "$TS_CLOUD_TRAP_LIVE" = "$TS_CLOUD_TRAP_TARGET" ] || rm -rf ${e.release}; fi`}' EXIT`}function Ye(e){return[`TS_CLOUD_LIVE_PATH="$(readlink -f ${e.current} 2>/dev/null || true)"`,`TS_CLOUD_RELEASE_PATH="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`,'if [ -n "$TS_CLOUD_LIVE_PATH" ] && [ "$TS_CLOUD_LIVE_PATH" = "$TS_CLOUD_RELEASE_PATH" ]; then TS_CLOUD_IS_LIVE=yes; else TS_CLOUD_IS_LIVE=no; fi']}function Wo(e){let t=`${e.release}.incoming`;return[`if [ "$TS_CLOUD_STAGED" = "${t}" ]; then`,` rm -rf ${e.release}.previous`,` mv ${e.release} ${e.release}.previous`,` mv ${t} ${e.release}`,` rm -rf ${e.release}.previous`,"fi"]}function Ke(e,t){return[`if [ -f ${e} ] && [ ! -L ${e} ] && [ -s ${e} ] && [ ! -s ${t} ]; then`,` cp -a ${e} ${t}`,` echo "[ts-cloud] seeded shared/ from the release's own copy of the file"`,"fi"]}function xs(e,t=Ns){let r=[];for(let n of t){let{path:o,target:s,seed:c}=$e(e,n),p=`${e.release}/${o}`,l=[`rm -rf ${p}`,`mkdir -p "$(dirname ${p})"`,`ln -sfn ${s} ${p}`];if(c){if(o!==".env"&&de(o))r.push(...Ke(p,s));r.push(...l);continue}r.push(`if [ -e ${s} ]; then`,...l.map((i)=>` ${i}`),"fi")}return r}function je(e,t){let r=ue(e.base);return[`if [ -f ${r} ]; then`,' while IFS="\t" read -r TS_CLOUD_SP TS_CLOUD_TGT; do',' [ -n "$TS_CLOUD_SP" ] || continue',` [ -n "$TS_CLOUD_TGT" ] || TS_CLOUD_TGT="${e.shared}/$TS_CLOUD_SP"`,' [ -e "$TS_CLOUD_TGT" ] || continue',` rm -rf ${t}/"$TS_CLOUD_SP"`,` mkdir -p "$(dirname ${t}/"$TS_CLOUD_SP")"`,` ln -sfn "$TS_CLOUD_TGT" ${t}/"$TS_CLOUD_SP"`,` done < ${r}`,"fi"]}function ln(e){return[`ln -sfn ${e.release} ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`]}function ee(e){return`${y(e)}/previous-release`}function Ko(e,t="TS_CLOUD_PREV_CURRENT"){let r=ee(e.base);return[`if [ -n "\${${t}:-}" ] && [ -d "$${t}" ] && [ "$(readlink -f "$${t}")" != "$(readlink -f ${e.release})" ]; then mkdir -p ${y(e.base)}; basename "$${t}" > ${r}; fi`]}function _e(e,t){let r=ee(e.base);return[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,...t?[`TS_CLOUD_RB_TARGET=${e.releases}/${t}`]:["TS_CLOUD_RB_TARGET=",`if [ -f ${r} ]; then TS_CLOUD_REC="${e.releases}/$(cat ${r})"; if [ -d "$TS_CLOUD_REC" ] && [ "$(readlink -f "$TS_CLOUD_REC")" != "$TS_CLOUD_CURRENT" ]; then TS_CLOUD_RB_TARGET="$TS_CLOUD_REC"; fi; fi`,`[ -n "$TS_CLOUD_RB_TARGET" ] || TS_CLOUD_RB_TARGET=$(ls -1dt ${e.releases}/*/ 2>/dev/null | sed 's#/$##' | while read -r r; do [ "$(readlink -f "$r")" != "$TS_CLOUD_CURRENT" ] && { echo "$r"; break; }; done)`],'[ -n "$TS_CLOUD_RB_TARGET" ] && [ -d "$TS_CLOUD_RB_TARGET" ] || { echo "no release to roll back to (looked for ${TS_CLOUD_RB_TARGET:-a previous release})" >&2; exit 1; }','[ "$(readlink -f "$TS_CLOUD_RB_TARGET")" != "$TS_CLOUD_CURRENT" ] || { echo "$(basename "$TS_CLOUD_RB_TARGET") is already the live release" >&2; exit 1; }','TS_CLOUD_RB_ID=$(basename "$TS_CLOUD_RB_TARGET")']}function Vc(e,t={}){return[..._e(e,t.to),'echo "would roll back from $(basename "${TS_CLOUD_CURRENT:-none}") to $TS_CLOUD_RB_ID (dry run: nothing changed)"']}function zc(e,t={}){let r=Math.max(1,t.gateSeconds??5),n=t.systemdDir??"/etc/systemd/system",o=[`ln -sfn "$TS_CLOUD_RB_TARGET" ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`,`rm -f ${ee(e.base)}`,'echo "rolled back to $TS_CLOUD_RB_ID"'],s=[..._e(e,t.to),...je(e,'"$TS_CLOUD_RB_TARGET"')];if(!t.unitBase)return[...s,...o];let c=t.unitBase,p=`${c}@\${TS_CLOUD_RB_ID}.service`;return[...s,`if [ -f ${n}/${c}@.service ]; then`,` systemctl start "${p}"`,` for TS_CLOUD_I in $(seq 1 ${r}); do sleep 1; systemctl is-active --quiet "${p}" || { echo "the release rolled back to, $TS_CLOUD_RB_ID, did not stay up; the current release keeps serving" >&2; journalctl -u "${p}" -n 30 --no-pager >&2 || true; systemctl stop "${p}" 2>/dev/null || true; exit 1; }; done`,...o.map((l)=>` ${l}`),` systemctl enable "${p}" 2>/dev/null || true`,` systemctl list-units --plain --no-legend --type=service "${c}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v "^${c}@\${TS_CLOUD_RB_ID}.service$" || true; } | while read -r TS_CLOUD_U; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done`,`elif [ -f ${n}/${c}.service ]; then`,...o.map((l)=>` ${l}`),` systemctl restart ${c}.service`,"else",...o.map((l)=>` ${l}`),"fi"]}function dn(e,t=4){let r=Math.max(1,t);return[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,`ls -1dt ${e.releases}/*/ 2>/dev/null | sed 's#/$##' | tail -n +${r+1} | while read -r TS_CLOUD_OLD; do`,' [ "$(readlink -f "$TS_CLOUD_OLD")" = "$TS_CLOUD_CURRENT" ] || rm -rf "$TS_CLOUD_OLD"',"done"]}function We(e){return`${y(e)}/owner`}function Jo(e,t){let r=We(e);return[`if [ -f "${r}" ]; then`,` TS_CLOUD_OWNER=$(cat "${r}")`,` if [ "$TS_CLOUD_OWNER" != "${t}" ]; then`,` echo "[ts-cloud] REFUSING deploy: ${e} belongs to project '$TS_CLOUD_OWNER', not '${t}'. Another project on this box derives the same site key — give one of them a distinct site name/domain, or remove ${r} to transfer ownership." >&2`," exit 1"," fi","else",` mkdir -p "$(dirname "${r}")"`,` printf '%s\\n' "${t}" > "${r}"`,"fi"]}function _s(e,t){let r=y(e),n=qe(e,t.releaseId),o=Vo(e),s=Math.max(1,t.keepLogs??20),c=t.commit||"",p=t.branch||"";return[`mkdir -p ${r}/deploys`,`exec > >(tee -a ${n}) 2>&1`,`echo "[ts-cloud] deploy ${t.releaseId} commit=${c} branch=${p} starting $(date -u +%Y-%m-%dT%H:%M:%SZ)"`,"ts_cloud_record_deploy() {"," TS_CLOUD_RC=$?",' if [ "$TS_CLOUD_RC" -eq 0 ]; then TS_CLOUD_ST=success; else TS_CLOUD_ST=failed; fi',` printf '%s\\t%s\\t%s\\t%s\\trc=%s\\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "${t.releaseId}" "${c}" "$TS_CLOUD_ST" "$TS_CLOUD_RC" >> ${o}`,"}","trap ts_cloud_record_deploy EXIT",`ls -1t ${r}/deploys/*.log 2>/dev/null | tail -n +${s+1} | while read -r TS_CLOUD_OLDLOG; do rm -f "$TS_CLOUD_OLDLOG"; done`]}
9
+ export{J,Si,Fo,P,As,Bo,jo,Uc,Fc,U,wr,St,et,Rs,vi,Is,Ci,Ar,Ps,vt,Bc,cn,Ds,Ti,Ns,Ei,Vo,ks,Vt,zo,jc,wi,Ho,qo,Go,Wo,xs,ln,Ko,Vc,zc,dn,Jo,_s};
@@ -1,8 +1,8 @@
1
- import{h}from"./chunk-twmeg17s.js";var y=(e)=>e==null?void 0:String(e),w=(e)=>Number(e)===1,C=(e,r)=>{try{return e==null?r:JSON.parse(String(e))}catch{return r}};function b(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),scope:{type:String(e.scope_type),id:String(e.scope_id),environmentId:y(e.environment_id),resourceId:y(e.resource_id),previewId:y(e.preview_id)},key:String(e.key),kind:String(e.kind),value:y(e.value),valueFingerprint:String(e.value_fingerprint),secretRef:y(e.secret_ref),backend:String(e.backend),backendVersion:y(e.backend_version),origin:String(e.origin),required:w(e.required),metadata:C(e.metadata,{}),lastUsedAt:y(e.last_used_at),rotatedAt:y(e.rotated_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function I(e){return{entryId:String(e.entry_id),resourceId:String(e.resource_id),injectionTarget:String(e.injection_target),required:w(e.required),requiresRedeploy:w(e.requires_redeploy),lastDeployedVersion:e.last_deployed_version==null?void 0:Number(e.last_deployed_version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}class Rr{controlPlane;now;constructor(e,r=()=>new Date){this.controlPlane=e;this.now=r}get(e){let r=this.controlPlane.database.query("SELECT * FROM configuration_entries WHERE id=?").get(e);return r?b(r):void 0}find(e,r,n){let t=this.controlPlane.database.query("SELECT * FROM configuration_entries WHERE project_id=? AND scope_type=? AND scope_id=? AND key=?").get(e,r.type,r.id,n);return t?b(t):void 0}list(e){let r=["project_id=?"],n=[e.projectId];if(e.scope)r.push("scope_type=?","scope_id=?"),n.push(e.scope.type,e.scope.id);if(e.kind)r.push("kind=?"),n.push(e.kind);return this.controlPlane.database.query(`SELECT * FROM configuration_entries WHERE ${r.join(" AND ")} ORDER BY key,scope_type,scope_id`).all(...n).map(b)}create(e){this.validateScope(e),this.validateEntry(e);let r=crypto.randomUUID(),n=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO configuration_entries (id,organization_id,project_id,scope_type,scope_id,environment_id,resource_id,preview_id,key,kind,value,value_fingerprint,secret_ref,backend,backend_version,origin,required,metadata,last_used_at,rotated_at,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[r,e.organizationId,e.projectId,e.scope.type,e.scope.id,e.scope.environmentId??null,e.scope.resourceId??null,e.scope.previewId??null,e.key,e.kind,e.value??null,e.valueFingerprint,e.secretRef??null,e.backend,e.backendVersion??null,e.origin,e.required?1:0,JSON.stringify(e.metadata),e.lastUsedAt??null,e.rotatedAt??null,1,n,n]),this.get(r)}update(e,r,n){let t=this.get(e);if(!t)throw Error("Configuration entry was not found.");if(this.validateEntry({...t,...n}),this.controlPlane.database.run("UPDATE configuration_entries SET value=?,value_fingerprint=?,secret_ref=?,backend=?,backend_version=?,required=?,metadata=?,rotated_at=?,version=version+1,updated_at=? WHERE id=? AND version=?",[n.value??null,n.valueFingerprint,n.secretRef??null,n.backend,n.backendVersion??null,n.required?1:0,JSON.stringify(n.metadata),n.rotatedAt??null,this.now().toISOString(),e,r]).changes!==1)throw Error("Configuration entry changed; refresh and retry.");return this.get(e)}remove(e,r){let n=this.get(e);if(!n)throw Error("Configuration entry was not found.");if(n.version!==r)throw Error("Configuration entry changed; refresh and retry.");if(this.controlPlane.database.run("DELETE FROM configuration_entries WHERE id=? AND version=?",[e,r]).changes<1)throw Error("Configuration entry changed; refresh and retry.");return n}setDependency(e){let r=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO configuration_dependencies (entry_id,resource_id,injection_target,required,requires_redeploy,last_deployed_version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?) ON CONFLICT(entry_id,resource_id) DO UPDATE SET injection_target=excluded.injection_target,required=excluded.required,requires_redeploy=excluded.requires_redeploy,last_deployed_version=excluded.last_deployed_version,updated_at=excluded.updated_at",[e.entryId,e.resourceId,e.injectionTarget,e.required?1:0,e.requiresRedeploy?1:0,e.lastDeployedVersion??null,r,r]),this.dependencies(e.entryId).find((n)=>n.resourceId===e.resourceId)}dependencies(e){return this.controlPlane.database.query("SELECT * FROM configuration_dependencies WHERE entry_id=? ORDER BY resource_id").all(e).map(I)}dependenciesForResource(e){return this.controlPlane.database.query("SELECT * FROM configuration_dependencies WHERE resource_id=? ORDER BY entry_id").all(e).map(I)}mutation(e){let r=this.controlPlane.database.query("SELECT request_hash,result FROM configuration_mutations WHERE idempotency_key=?").get(e);return r?{requestHash:r.request_hash,result:C(r.result,{})}:void 0}recordMutation(e){this.controlPlane.database.run("INSERT INTO configuration_mutations (id,project_id,idempotency_key,request_hash,result,actor_id,created_at) VALUES (?,?,?,?,?,?,?)",[crypto.randomUUID(),e.projectId,e.idempotencyKey,e.requestHash,JSON.stringify(e.result),e.actorId??null,this.now().toISOString()])}validateEntry(e){if(!/^[A-Za-z_][A-Za-z0-9_]{0,255}$/.test(e.key))throw Error(`Invalid configuration key: ${e.key}`);if(e.kind==="variable"&&(e.value==null||e.secretRef||e.backend!=="plaintext"))throw Error("Variables require a plaintext value and cannot use a secret backend.");if(e.kind==="secret"&&(e.value!=null||!e.secretRef||e.backend==="plaintext"))throw Error("Secrets require a non-plaintext backend reference and cannot store a plaintext value.")}validateScope(e){let r=this.controlPlane.getProject(e.projectId);if(!r||r.organizationId!==e.organizationId)throw Error("Configuration project does not belong to the organization.");let n=e.scope;if(n.type==="project"){if(n.id!==e.projectId||n.environmentId||n.resourceId||n.previewId)throw Error("Project configuration scope must reference only its project.");return}if(n.type==="environment"){let i=this.controlPlane.database.query("SELECT project_id FROM environments WHERE id=?").get(n.id);if(!i||i.project_id!==e.projectId||n.environmentId&&n.environmentId!==n.id||n.resourceId||n.previewId)throw Error("Environment configuration scope does not belong to the project.");return}if(n.type==="service"||n.type==="function"){let i=this.controlPlane.getResource(n.id);if(!i||i.projectId!==e.projectId||n.type==="function"&&i.kind!=="function"||n.resourceId&&n.resourceId!==n.id||n.environmentId&&i.environmentId!==n.environmentId||n.previewId)throw Error(`${n.type==="function"?"Function":"Service"} configuration scope does not belong to the project.`);return}let t=this.controlPlane.database.query("SELECT project_id,base_environment_id,resource_id FROM preview_instances WHERE id=?").get(n.id);if(!t||t.project_id!==e.projectId||n.previewId&&n.previewId!==n.id||n.environmentId&&n.environmentId!==t.base_environment_id||n.resourceId&&n.resourceId!==t.resource_id)throw Error("Preview configuration scope does not belong to the project.")}}var E=/^[A-Za-z_][A-Za-z0-9_]{0,255}$/;function j(e){let r={n:`
2
- `,r:"\r",t:"\t","\\":"\\",'"':'"',$:"$"};return e.replace(/\\(n|r|t|\\|"|\$)/g,(n,t)=>r[t])}function Gc(e){let r={},n=[],t=e.replace(/\r\n?/g,`
1
+ import{h}from"./chunk-4zxwtvvf.js";var y=(e)=>e==null?void 0:String(e),w=(e)=>Number(e)===1,C=(e,r)=>{try{return e==null?r:JSON.parse(String(e))}catch{return r}};function b(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),scope:{type:String(e.scope_type),id:String(e.scope_id),environmentId:y(e.environment_id),resourceId:y(e.resource_id),previewId:y(e.preview_id)},key:String(e.key),kind:String(e.kind),value:y(e.value),valueFingerprint:String(e.value_fingerprint),secretRef:y(e.secret_ref),backend:String(e.backend),backendVersion:y(e.backend_version),origin:String(e.origin),required:w(e.required),metadata:C(e.metadata,{}),lastUsedAt:y(e.last_used_at),rotatedAt:y(e.rotated_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function I(e){return{entryId:String(e.entry_id),resourceId:String(e.resource_id),injectionTarget:String(e.injection_target),required:w(e.required),requiresRedeploy:w(e.requires_redeploy),lastDeployedVersion:e.last_deployed_version==null?void 0:Number(e.last_deployed_version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}class Rr{controlPlane;now;constructor(e,r=()=>new Date){this.controlPlane=e;this.now=r}get(e){let r=this.controlPlane.database.query("SELECT * FROM configuration_entries WHERE id=?").get(e);return r?b(r):void 0}find(e,r,n){let t=this.controlPlane.database.query("SELECT * FROM configuration_entries WHERE project_id=? AND scope_type=? AND scope_id=? AND key=?").get(e,r.type,r.id,n);return t?b(t):void 0}list(e){let r=["project_id=?"],n=[e.projectId];if(e.scope)r.push("scope_type=?","scope_id=?"),n.push(e.scope.type,e.scope.id);if(e.kind)r.push("kind=?"),n.push(e.kind);return this.controlPlane.database.query(`SELECT * FROM configuration_entries WHERE ${r.join(" AND ")} ORDER BY key,scope_type,scope_id`).all(...n).map(b)}create(e){this.validateScope(e),this.validateEntry(e);let r=crypto.randomUUID(),n=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO configuration_entries (id,organization_id,project_id,scope_type,scope_id,environment_id,resource_id,preview_id,key,kind,value,value_fingerprint,secret_ref,backend,backend_version,origin,required,metadata,last_used_at,rotated_at,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[r,e.organizationId,e.projectId,e.scope.type,e.scope.id,e.scope.environmentId??null,e.scope.resourceId??null,e.scope.previewId??null,e.key,e.kind,e.value??null,e.valueFingerprint,e.secretRef??null,e.backend,e.backendVersion??null,e.origin,e.required?1:0,JSON.stringify(e.metadata),e.lastUsedAt??null,e.rotatedAt??null,1,n,n]),this.get(r)}update(e,r,n){let t=this.get(e);if(!t)throw Error("Configuration entry was not found.");if(this.validateEntry({...t,...n}),this.controlPlane.database.run("UPDATE configuration_entries SET value=?,value_fingerprint=?,secret_ref=?,backend=?,backend_version=?,required=?,metadata=?,rotated_at=?,version=version+1,updated_at=? WHERE id=? AND version=?",[n.value??null,n.valueFingerprint,n.secretRef??null,n.backend,n.backendVersion??null,n.required?1:0,JSON.stringify(n.metadata),n.rotatedAt??null,this.now().toISOString(),e,r]).changes!==1)throw Error("Configuration entry changed; refresh and retry.");return this.get(e)}remove(e,r){let n=this.get(e);if(!n)throw Error("Configuration entry was not found.");if(n.version!==r)throw Error("Configuration entry changed; refresh and retry.");if(this.controlPlane.database.run("DELETE FROM configuration_entries WHERE id=? AND version=?",[e,r]).changes<1)throw Error("Configuration entry changed; refresh and retry.");return n}setDependency(e){let r=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO configuration_dependencies (entry_id,resource_id,injection_target,required,requires_redeploy,last_deployed_version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?) ON CONFLICT(entry_id,resource_id) DO UPDATE SET injection_target=excluded.injection_target,required=excluded.required,requires_redeploy=excluded.requires_redeploy,last_deployed_version=excluded.last_deployed_version,updated_at=excluded.updated_at",[e.entryId,e.resourceId,e.injectionTarget,e.required?1:0,e.requiresRedeploy?1:0,e.lastDeployedVersion??null,r,r]),this.dependencies(e.entryId).find((n)=>n.resourceId===e.resourceId)}dependencies(e){return this.controlPlane.database.query("SELECT * FROM configuration_dependencies WHERE entry_id=? ORDER BY resource_id").all(e).map(I)}dependenciesForResource(e){return this.controlPlane.database.query("SELECT * FROM configuration_dependencies WHERE resource_id=? ORDER BY entry_id").all(e).map(I)}mutation(e){let r=this.controlPlane.database.query("SELECT request_hash,result FROM configuration_mutations WHERE idempotency_key=?").get(e);return r?{requestHash:r.request_hash,result:C(r.result,{})}:void 0}recordMutation(e){this.controlPlane.database.run("INSERT INTO configuration_mutations (id,project_id,idempotency_key,request_hash,result,actor_id,created_at) VALUES (?,?,?,?,?,?,?)",[crypto.randomUUID(),e.projectId,e.idempotencyKey,e.requestHash,JSON.stringify(e.result),e.actorId??null,this.now().toISOString()])}validateEntry(e){if(!/^[A-Za-z_][A-Za-z0-9_]{0,255}$/.test(e.key))throw Error(`Invalid configuration key: ${e.key}`);if(e.kind==="variable"&&(e.value==null||e.secretRef||e.backend!=="plaintext"))throw Error("Variables require a plaintext value and cannot use a secret backend.");if(e.kind==="secret"&&(e.value!=null||!e.secretRef||e.backend==="plaintext"))throw Error("Secrets require a non-plaintext backend reference and cannot store a plaintext value.")}validateScope(e){let r=this.controlPlane.getProject(e.projectId);if(!r||r.organizationId!==e.organizationId)throw Error("Configuration project does not belong to the organization.");let n=e.scope;if(n.type==="project"){if(n.id!==e.projectId||n.environmentId||n.resourceId||n.previewId)throw Error("Project configuration scope must reference only its project.");return}if(n.type==="environment"){let i=this.controlPlane.database.query("SELECT project_id FROM environments WHERE id=?").get(n.id);if(!i||i.project_id!==e.projectId||n.environmentId&&n.environmentId!==n.id||n.resourceId||n.previewId)throw Error("Environment configuration scope does not belong to the project.");return}if(n.type==="service"||n.type==="function"){let i=this.controlPlane.getResource(n.id);if(!i||i.projectId!==e.projectId||n.type==="function"&&i.kind!=="function"||n.resourceId&&n.resourceId!==n.id||n.environmentId&&i.environmentId!==n.environmentId||n.previewId)throw Error(`${n.type==="function"?"Function":"Service"} configuration scope does not belong to the project.`);return}let t=this.controlPlane.database.query("SELECT project_id,base_environment_id,resource_id FROM preview_instances WHERE id=?").get(n.id);if(!t||t.project_id!==e.projectId||n.previewId&&n.previewId!==n.id||n.environmentId&&n.environmentId!==t.base_environment_id||n.resourceId&&n.resourceId!==t.resource_id)throw Error("Preview configuration scope does not belong to the project.")}}var E=/^[A-Za-z_][A-Za-z0-9_]{0,255}$/;function j(e){let r={n:`
2
+ `,r:"\r",t:"\t","\\":"\\",'"':'"',$:"$"};return e.replace(/\\(n|r|t|\\|"|\$)/g,(n,t)=>r[t])}function qc(e){let r={},n=[],t=e.replace(/\r\n?/g,`
3
3
  `).split(`
4
4
  `);for(let i=0;i<t.length;i++){let s=i+1,c=t[i];if(!c.trim()||c.trimStart().startsWith("#"))continue;if(/^\s*export\s+/.test(c))c=c.replace(/^\s*export\s+/,"");let u=c.match(/^\s*([^=\s]+)\s*=\s*(.*)$/);if(!u){n.push({line:s,severity:"error",code:"invalid_line",message:"Expected KEY=VALUE."});continue}let o=u[1],a=u[2];if(!E.test(o)){n.push({line:s,key:o,severity:"error",code:"invalid_key",message:`Invalid environment variable name: ${o}`});continue}let d=a;if(a.startsWith('"')||a.startsWith("'")){let g=a[0],l=[a.slice(1)],v=!1;while(!0){let f=l[l.length-1],m=!1,S=-1;for(let k=0;k<f.length;k++){if(g==='"'&&f[k]==="\\"&&!m){m=!0;continue}if(f[k]===g&&!m){S=k;break}m=!1}if(S>=0){l[l.length-1]=f.slice(0,S),v=!0;break}if(++i>=t.length)break;l.push(t[i])}if(!v){n.push({line:s,key:o,severity:"error",code:"unterminated_quote",message:`Unterminated quoted value for ${o}.`});continue}if(d=l.join(`
5
- `),g==='"')d=j(d)}else d=a.replace(/\s+#.*$/,"").trim();if(Object.hasOwn(r,o)){let g=r[o]!==d;if(n.push({line:s,key:o,severity:g?"error":"warning",code:g?"conflict":"duplicate",message:g?`${o} has conflicting values.`:`${o} is duplicated with the same value.`}),g)continue}r[o]=d}return{values:r,diagnostics:n,valid:!n.some((i)=>i.severity==="error")}}function qc(e){return Object.entries(e).sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>{if(!E.test(r))throw Error(`Invalid environment variable name: ${r}`);return`${r}=${JSON.stringify(n)}`}).join(`
5
+ `),g==='"')d=j(d)}else d=a.replace(/\s+#.*$/,"").trim();if(Object.hasOwn(r,o)){let g=r[o]!==d;if(n.push({line:s,key:o,severity:g?"error":"warning",code:g?"conflict":"duplicate",message:g?`${o} has conflicting values.`:`${o} is duplicated with the same value.`}),g)continue}r[o]=d}return{values:r,diagnostics:n,valid:!n.some((i)=>i.severity==="error")}}function Gc(e){return Object.entries(e).sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>{if(!E.test(r))throw Error(`Invalid environment variable name: ${r}`);return`${r}=${JSON.stringify(n)}`}).join(`
6
6
  `)+(Object.keys(e).length?`
7
- `:"")}import{createCipheriv as x,createDecipheriv as P,createHash as _,randomBytes as q}from"node:crypto";class Tt{controlPlane;now;kind="local_encrypted";key;constructor(e,r,n=()=>new Date){this.controlPlane=e;this.now=n;if(!r)throw Error("Configuration encryption key is required.");this.key=_("sha256").update(`ts-cloud:configuration:${r}`).digest()}encrypt(e){let r=q(12),n=x("aes-256-gcm",this.key,r),t=Buffer.concat([n.update(e,"utf8"),n.final()]);return`v1.${r.toString("base64url")}.${n.getAuthTag().toString("base64url")}.${t.toString("base64url")}`}decrypt(e){let[r,n,t,i]=e.split(".");if(r!=="v1"||!n||!t||!i)throw Error("Encrypted configuration secret is unavailable.");try{let s=P("aes-256-gcm",this.key,Buffer.from(n,"base64url"));return s.setAuthTag(Buffer.from(t,"base64url")),Buffer.concat([s.update(Buffer.from(i,"base64url")),s.final()]).toString("utf8")}catch{throw Error("Encrypted configuration secret could not be decrypted.")}}async put(e){if(!e.value)throw Error("Configuration secrets cannot be empty.");let r=e.reference??`secret://configuration/${e.name}/${crypto.randomUUID()}`;if(!/^secret:\/\/configuration\/[A-Za-z0-9._/-]+$/.test(r))throw Error("Invalid local configuration secret reference.");let t=(this.controlPlane.database.query("SELECT version FROM configuration_secret_values WHERE reference=?").get(r)?.version??0)+1,i=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO configuration_secret_values (reference,ciphertext,fingerprint,version,created_at,updated_at) VALUES (?,?,?,?,?,?) ON CONFLICT(reference) DO UPDATE SET ciphertext=excluded.ciphertext,fingerprint=excluded.fingerprint,version=excluded.version,updated_at=excluded.updated_at",[r,this.encrypt(e.value),_("sha256").update(e.value).digest("hex"),t,i,i]),{reference:r,version:String(t)}}async resolve(e){let r=this.controlPlane.database.query("SELECT ciphertext FROM configuration_secret_values WHERE reference=?").get(e);if(!r)throw Error("Configuration secret was not found.");return this.decrypt(r.ciphertext)}async remove(e){this.controlPlane.database.run("DELETE FROM configuration_secret_values WHERE reference=?",[e])}async validate(e){return!!this.controlPlane.database.query("SELECT 1 AS found FROM configuration_secret_values WHERE reference=?").get(e)}}class Ir{client;region;kind="aws_secrets_manager";constructor(e,r){this.client=e;this.region=r}async put(e){if(e.reference){let n=this.id(e.reference),t=await this.client.putSecretValue({SecretId:n,SecretString:e.value,ClientRequestToken:e.idempotencyKey});return{reference:e.reference,version:t.VersionId??e.idempotencyKey}}let r=await this.client.createSecret({Name:e.name,SecretString:e.value,ClientRequestToken:e.idempotencyKey,Tags:[{Key:"managed-by",Value:"ts-cloud"}]});return{reference:`aws-sm://${this.region}/${encodeURIComponent(r.ARN??r.Name??e.name)}`,version:r.VersionId??e.idempotencyKey}}async resolve(e){let r=await this.client.getSecretValue({SecretId:this.id(e)});if(r.SecretString==null)throw Error("AWS Secrets Manager value is unavailable.");return r.SecretString}async remove(e){await this.client.deleteSecret({SecretId:this.id(e),RecoveryWindowInDays:7})}async validate(e){try{return await this.client.describeSecret(this.id(e)),!0}catch{return!1}}id(e){let r=new URL(e);if(r.protocol!=="aws-sm:"||r.hostname!==this.region)throw Error("Invalid AWS Secrets Manager reference.");return decodeURIComponent(r.pathname.slice(1))}}class Pr{client;region;kind="aws_ssm";constructor(e,r){this.client=e;this.region=r}async put(e){let r=e.reference?this.name(e.reference):`/${e.name.replace(/^\/+/,"")}`,n=await this.client.putParameter({Name:r,Value:e.value,Type:"SecureString",Overwrite:!!e.reference,Description:"Managed by ts-cloud"});return{reference:`aws-ssm://${this.region}${r}`,version:String(n.Version??1)}}async resolve(e){let r=await this.client.getParameter({Name:this.name(e),WithDecryption:!0});if(r.Parameter?.Value==null)throw Error("AWS SSM parameter value is unavailable.");return r.Parameter.Value}async remove(e){await this.client.deleteParameter({Name:this.name(e)})}async validate(e){try{return!!(await this.client.getParameter({Name:this.name(e),WithDecryption:!1})).Parameter}catch{return!1}}name(e){let r=new URL(e);if(r.protocol!=="aws-ssm:"||r.hostname!==this.region||!r.pathname.startsWith("/"))throw Error("Invalid AWS SSM reference.");return r.pathname}}class Dr{kind="external";async put(){throw Error("External secret references cannot be written by ts-cloud.")}async resolve(){throw Error("External secrets must be resolved by the deployment provider.")}async remove(){}async validate(e){return/^(?:vault|doppler|op|external):\/\//.test(e)}}import{createHmac as A}from"node:crypto";var D=/^(?:secret|aws-sm|aws-ssm|vault|doppler|op|external):\/\//,O=/^(?:AWS_|TS_CLOUD_|PORT$|HOST$)/;function p(e){return[...new Set(e)].sort()}function R(e,r={}){let n=e.kind==="secret";return{id:e.id,key:e.key,kind:e.kind,scope:e.scope,inherited:!!r.inherited,overridden:!!r.overridden,required:e.required,backend:!n||r.canReadSecretMetadata?e.backend:void 0,backendVersion:!n||r.canReadSecretMetadata?e.backendVersion:void 0,reference:n&&r.canReadSecretMetadata?e.secretRef:void 0,value:!n?e.value:void 0,lastUsedAt:e.lastUsedAt,rotatedAt:e.rotatedAt,version:e.version,updatedAt:e.updatedAt}}class Nr{store;backends=new Map;fingerprintKey;now;constructor(e,r){if(this.store=e,this.fingerprintKey=r.fingerprintKey??r.encryptionKey,this.now=r.now??(()=>new Date),!this.fingerprintKey)throw Error("Configuration fingerprint key is required.");let n=r.backends??[new Tt(e.controlPlane,r.encryptionKey,this.now)];for(let t of n)this.backends.set(t.kind,t)}list(e){let r=e.search?.toLowerCase();return this.store.list(e).filter((n)=>!r||n.key.toLowerCase().includes(r)).map((n)=>R(n,{canReadSecretMetadata:e.canReadSecretMetadata}))}plan(e){let r=this.store.list({projectId:e.projectId,scope:e.scope}),n=new Map(r.map((o)=>[o.key,o])),t=[],i=[],s=[],c=[];for(let[o,a]of Object.entries(e.values)){t.push(...this.warnings(o,a));let d=n.get(o);if(!d)i.push(o);else if(d.valueFingerprint!==this.fingerprint(a))s.push(o);else c.push(o)}let u=e.removeMissing?r.filter((o)=>!Object.hasOwn(e.values,o.key)).map((o)=>o.key):[];return{added:p(i),changed:p(s),removed:p(u),unchanged:p(c),affectedResourceIds:this.affectedResources(e.projectId,e.scope,[...i,...s,...u]),warnings:t}}async set(e){let r=this.requestHash(e),n=e.idempotencyKey;if(n){let f=this.store.mutation(n);if(f){if(f.requestHash!==r)throw Error("Idempotency key was already used for a different configuration mutation.");let m=this.store.get(String(f.result.entryId??""));if(!m)throw Error("Idempotent configuration result is no longer available.");return{entry:m,mutation:f.result.mutation,warnings:[]}}}if(e.value!=null&&D.test(e.value))throw Error("Secret references must use the reference field, not a plaintext value field.");let t=this.store.find(e.projectId,e.scope,e.key),i=this.fingerprint(e.value??e.reference??"");if(t&&e.expectedVersion!=null&&t.version!==e.expectedVersion)throw Error("Configuration entry changed; refresh and retry.");if(t&&t.kind!==e.kind)throw Error("Delete the existing entry before changing between variable and secret kinds.");let s=e.kind==="variable"?"plaintext":e.backend??(e.reference?"external":"local_encrypted");if(!!t&&(t.valueFingerprint!==i||t.backend!==s||t.required!==!!e.required)&&(this.isProduction(t)||this.store.dependencies(t.id).length>0)&&!e.confirmed)throw Error("Confirmation is required because this replacement affects production or dependent services.");let u=e.reference,o;if(e.kind==="secret"){let f=this.backend(s);if(e.reference&&e.value==null){if(!await f.validate(e.reference))throw Error("Secret backend reference is unavailable or invalid.");o=t?.backendVersion??"external"}else{if(e.value==null)throw Error("A secret value or external reference is required.");let m=await f.put({reference:t?.backend===s?t.secretRef:void 0,name:this.backendName(e),value:e.value,idempotencyKey:n??crypto.randomUUID()});u=m.reference,o=m.version}}let a=e.kind==="variable"?e.value:void 0;if(e.kind==="variable"&&a==null)throw Error("A variable value is required.");let d=!t||t.valueFingerprint!==i||t.backend!==s||t.secretRef!==u||t.backendVersion!==o||t.required!==!!e.required,g=t?d?this.store.update(t.id,t.version,{value:a,valueFingerprint:i,secretRef:u,backend:s,backendVersion:o,required:!!e.required,metadata:h(e.metadata??t.metadata),rotatedAt:e.kind==="secret"?this.now().toISOString():t.rotatedAt}):t:this.store.create({organizationId:e.organizationId,projectId:e.projectId,scope:e.scope,key:e.key,kind:e.kind,value:a,valueFingerprint:i,secretRef:u,backend:s,backendVersion:o,origin:e.origin??"managed",required:!!e.required,metadata:h(e.metadata??{}),rotatedAt:e.kind==="secret"?this.now().toISOString():void 0}),l=this.affectedResources(e.projectId,e.scope,[e.key]),v={added:t?[]:[e.key],changed:t&&d?[e.key]:[],removed:[],unchanged:t&&!d?[e.key]:[],affectedResourceIds:l,versions:{[e.key]:g.version}};if(n)this.store.recordMutation({projectId:e.projectId,idempotencyKey:n,requestHash:r,actorId:e.actorId,result:{entryId:g.id,mutation:v}});return this.audit(e.projectId,e.actorId,t&&d?"configuration.updated":t?"configuration.unchanged":"configuration.created",g,l),{entry:g,mutation:v,warnings:this.warnings(e.key,e.value??"")}}async importDotenv(e){let r=Gc(e.source);if(!r.valid)return{document:r,warnings:[]};let n=new Set(e.secretKeys??[]),t={added:[],changed:[],removed:[],unchanged:[],affectedResourceIds:[],versions:{}},i=[];for(let[s,c]of Object.entries(r.values)){let u=await this.set({...e,source:void 0,key:s,value:c,kind:n.has(s)?"secret":"variable",idempotencyKey:e.idempotencyKey?`${e.idempotencyKey}:${s}`:void 0});t.added.push(...u.mutation.added),t.changed.push(...u.mutation.changed),t.unchanged.push(...u.mutation.unchanged),t.affectedResourceIds.push(...u.mutation.affectedResourceIds),Object.assign(t.versions,u.mutation.versions),i.push(...u.warnings)}return t.added=p(t.added),t.changed=p(t.changed),t.unchanged=p(t.unchanged),t.affectedResourceIds=p(t.affectedResourceIds),{document:r,mutation:t,warnings:i}}exportVariables(e){return qc(Object.fromEntries(this.store.list({projectId:e.projectId,scope:e.scope,kind:"variable"}).map((r)=>[r.key,r.value??""])))}async transfer(e){let r=this.store.get(e.entryId);if(!r)throw Error("Configuration entry was not found.");if(r.scope.type===e.targetScope.type&&r.scope.id===e.targetScope.id)throw Error("Choose a different destination scope.");let n=r.kind==="variable"?r.value:r.backend==="external"?void 0:await this.backend(r.backend).resolve(r.secretRef),t=r.kind==="secret"?r.backend:void 0,i=await this.set({organizationId:r.organizationId,projectId:r.projectId,scope:e.targetScope,key:r.key,kind:r.kind,value:n,reference:r.backend==="external"?r.secretRef:void 0,backend:t,required:r.required,metadata:r.metadata,confirmed:e.confirmed,actorId:e.actorId,idempotencyKey:e.idempotencyKey?`${e.idempotencyKey}:copy`:void 0,origin:r.origin});if(e.mode==="move")await this.remove({entryId:r.id,expectedVersion:r.version,confirmed:e.confirmed,actorId:e.actorId});let s={added:i.mutation.added,changed:i.mutation.changed,removed:e.mode==="move"?[r.key]:[],unchanged:i.mutation.unchanged,affectedResourceIds:p([...i.mutation.affectedResourceIds,...this.affectedResources(r.projectId,r.scope,[r.key])]),versions:i.mutation.versions};return{entry:i.entry,mutation:s}}async resolve(e){let r=this.store.list({projectId:e.projectId}),n=r.filter((a)=>this.applies(a,e)).sort((a,d)=>this.rank(a.scope.type)-this.rank(d.scope.type)),t=new Map,i=new Set;for(let a of n){if(t.has(a.key))i.add(a.key);t.set(a.key,a)}let s={},c={},u=[],o=new Set(e.allowedPreviewSecrets??[]);for(let[a,d]of t){if(e.previewId&&d.kind==="secret"&&d.scope.type!=="preview"&&(!e.trustedPreview||!o.has(a)))continue;if(d.kind==="variable")s[a]=d.value??"";else if(e.nativeReferences)s[a]=d.secretRef;else{let g=this.backend(d.backend);if(!await g.validate(d.secretRef)){if(u.push({key:a,code:"stale_reference",message:`${a} points to an unavailable secret.`}),d.required)u.push({key:a,code:"missing_required",message:`${a} is required but unavailable.`});continue}s[a]=await g.resolve(d.secretRef)}c[a]=R(d,{inherited:d.scope.type!==(e.previewId?"preview":e.functionId?"function":e.resourceId?"service":e.environmentId?"environment":"project"),overridden:i.has(a),canReadSecretMetadata:e.canReadSecretMetadata}),this.store.controlPlane.database.run("UPDATE configuration_entries SET last_used_at=? WHERE id=?",[this.now().toISOString(),d.id])}return{values:s,entries:c,warnings:u,configurationHash:this.fingerprint([...t.values()].map((a)=>`${a.key}:${a.valueFingerprint}:${a.version}`).sort().join(`
8
- `))}}async reveal(e){let r=this.store.get(e.entryId);if(!r||r.kind!=="secret")throw Error("Configuration secret was not found.");if(!e.canRevealSecrets)throw Error("Secret reveal permission is required.");if(!e.recentlyAuthenticated)throw Error("Recent authentication is required to reveal a secret.");let n=await this.backend(r.backend).resolve(r.secretRef);return this.audit(r.projectId,e.actorId,"configuration.secret.revealed",r,[]),n}async remove(e){let r=this.store.get(e.entryId);if(!r)throw Error("Configuration entry was not found.");let n=this.store.dependencies(r.id);if(((r.scope.environmentId?this.store.controlPlane.listEnvironments(r.projectId).some((c)=>c.id===r.scope.environmentId&&c.kind==="production"):r.scope.type==="project")||n.length)&&!e.confirmed)throw Error("Confirmation is required because this configuration affects production or dependent services.");if(r.kind==="secret"&&r.backend!=="external")await this.backend(r.backend).remove(r.secretRef);this.store.remove(r.id,e.expectedVersion);let i=p(n.map((c)=>c.resourceId)),s={added:[],changed:[],removed:[r.key],unchanged:[],affectedResourceIds:i,versions:{}};return this.audit(r.projectId,e.actorId,"configuration.deleted",r,i),s}applies(e,r){if(e.scope.type==="project")return!0;if(e.scope.type==="environment")return e.scope.id===r.environmentId;if(e.scope.type==="service")return e.scope.id===r.resourceId;if(e.scope.type==="function")return e.scope.id===r.functionId;return e.scope.id===r.previewId}rank(e){return{project:0,environment:1,service:2,function:3,preview:4}[e]}fingerprint(e){return`hmac-sha256:${A("sha256",this.fingerprintKey).update(e).digest("hex")}`}requestHash(e){return this.fingerprint(JSON.stringify({...e,idempotencyKey:void 0,actorId:void 0}))}backend(e){let r=this.backends.get(e);if(!r)throw Error(`Configuration secret backend is not configured: ${e}`);return r}backendName(e){return`ts-cloud/${e.projectId}/${e.scope.type}/${e.scope.id}/${e.key}`.replace(/[^A-Za-z0-9/_+=.@-]/g,"-")}isProduction(e){return e.scope.type==="project"||!!e.scope.environmentId&&this.store.controlPlane.listEnvironments(e.projectId).some((r)=>r.id===e.scope.environmentId&&r.kind==="production")}warnings(e,r){let n=[];if(O.test(e))n.push({key:e,code:"reserved",message:`${e} may be reserved by the runtime or provider.`});if(Buffer.byteLength(r)>65536)n.push({key:e,code:"limit",message:`${e} exceeds the portable 64 KiB value limit.`});return n}affectedResources(e,r,n){let t=this.store.list({projectId:e,scope:r}).filter((i)=>n.includes(i.key)).flatMap((i)=>this.store.dependencies(i.id).map((s)=>s.resourceId));if(r.type==="service"||r.type==="function")return p([...t,r.id]);if(r.type==="environment")return p([...t,...this.store.controlPlane.listResources(e,r.id).map((i)=>i.id)]);if(r.type==="preview"){let i=this.store.controlPlane.database.query("SELECT resource_id FROM preview_instances WHERE id=?").get(r.id);return p([...t,...i?[i.resource_id]:[]])}return p([...t,...this.store.controlPlane.listResources(e).map((i)=>i.id)])}audit(e,r,n,t,i){this.store.controlPlane.appendEvent({projectId:e,actorId:r,type:n,payload:{entryId:t.id,key:t.key,kind:t.kind,scopeType:t.scope.type,scopeId:t.scope.id,backend:t.backend,version:t.version,affectedResourceIds:i}})}}async function un(e,r,n,t){let i={added:0,changed:0,removed:0,overridden:0},s=async(c,u)=>{let o=e.store.list({projectId:r.project.id,scope:c,kind:"variable"}),a=new Set(Object.keys(u));for(let d of o.filter((g)=>g.origin==="config"&&!a.has(g.key)))await e.remove({entryId:d.id,expectedVersion:d.version,confirmed:!0,actorId:t}),i.removed++;for(let[d,g]of Object.entries(u)){let l=e.store.find(r.project.id,c,d);if(l?.origin!=="config"){if(l)i.overridden++;else await e.set({organizationId:r.organization.id,projectId:r.project.id,scope:c,key:d,kind:"variable",value:String(g),origin:"config",confirmed:!0,actorId:t}),i.added++;continue}if(l.value===String(g))continue;await e.set({organizationId:r.organization.id,projectId:r.project.id,scope:c,key:d,kind:"variable",value:String(g),origin:"config",confirmed:!0,actorId:t,expectedVersion:l.version}),i.changed++}};for(let[c,u]of Object.entries(n.environments??{})){let o=r.environments.get(c);if(!o)continue;let a=u,d={...a.variables??{},...a.app?.env??{}};await s({type:"environment",id:o.id,environmentId:o.id},d);for(let[g,l]of Object.entries(n.sites??{})){let v=r.store.listResources(r.project.id,o.id).find((f)=>f.kind==="application"&&f.slug===g);if(v)await s({type:"service",id:v.id,environmentId:o.id,resourceId:v.id},{...l.env??{}})}for(let[g,l]of Object.entries(n.infrastructure?.functions??{})){let v=r.store.listResources(r.project.id,o.id).find((f)=>f.kind==="function"&&f.slug===g);if(v)await s({type:"function",id:v.id,environmentId:o.id,resourceId:v.id},{...l.environment??{}})}}return i}export{Rr,Gc,qc,Tt,Ir,Pr,Dr,Nr,un};
7
+ `:"")}import{createCipheriv as x,createDecipheriv as P,createHash as _,randomBytes as q}from"node:crypto";class Tt{controlPlane;now;kind="local_encrypted";key;constructor(e,r,n=()=>new Date){this.controlPlane=e;this.now=n;if(!r)throw Error("Configuration encryption key is required.");this.key=_("sha256").update(`ts-cloud:configuration:${r}`).digest()}encrypt(e){let r=q(12),n=x("aes-256-gcm",this.key,r),t=Buffer.concat([n.update(e,"utf8"),n.final()]);return`v1.${r.toString("base64url")}.${n.getAuthTag().toString("base64url")}.${t.toString("base64url")}`}decrypt(e){let[r,n,t,i]=e.split(".");if(r!=="v1"||!n||!t||!i)throw Error("Encrypted configuration secret is unavailable.");try{let s=P("aes-256-gcm",this.key,Buffer.from(n,"base64url"));return s.setAuthTag(Buffer.from(t,"base64url")),Buffer.concat([s.update(Buffer.from(i,"base64url")),s.final()]).toString("utf8")}catch{throw Error("Encrypted configuration secret could not be decrypted.")}}async put(e){if(!e.value)throw Error("Configuration secrets cannot be empty.");let r=e.reference??`secret://configuration/${e.name}/${crypto.randomUUID()}`;if(!/^secret:\/\/configuration\/[A-Za-z0-9._/-]+$/.test(r))throw Error("Invalid local configuration secret reference.");let t=(this.controlPlane.database.query("SELECT version FROM configuration_secret_values WHERE reference=?").get(r)?.version??0)+1,i=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO configuration_secret_values (reference,ciphertext,fingerprint,version,created_at,updated_at) VALUES (?,?,?,?,?,?) ON CONFLICT(reference) DO UPDATE SET ciphertext=excluded.ciphertext,fingerprint=excluded.fingerprint,version=excluded.version,updated_at=excluded.updated_at",[r,this.encrypt(e.value),_("sha256").update(e.value).digest("hex"),t,i,i]),{reference:r,version:String(t)}}async resolve(e){let r=this.controlPlane.database.query("SELECT ciphertext FROM configuration_secret_values WHERE reference=?").get(e);if(!r)throw Error("Configuration secret was not found.");return this.decrypt(r.ciphertext)}async remove(e){this.controlPlane.database.run("DELETE FROM configuration_secret_values WHERE reference=?",[e])}async validate(e){return!!this.controlPlane.database.query("SELECT 1 AS found FROM configuration_secret_values WHERE reference=?").get(e)}}class Ir{client;region;kind="aws_secrets_manager";constructor(e,r){this.client=e;this.region=r}async put(e){if(e.reference){let n=this.id(e.reference),t=await this.client.putSecretValue({SecretId:n,SecretString:e.value,ClientRequestToken:e.idempotencyKey});return{reference:e.reference,version:t.VersionId??e.idempotencyKey}}let r=await this.client.createSecret({Name:e.name,SecretString:e.value,ClientRequestToken:e.idempotencyKey,Tags:[{Key:"managed-by",Value:"ts-cloud"}]});return{reference:`aws-sm://${this.region}/${encodeURIComponent(r.ARN??r.Name??e.name)}`,version:r.VersionId??e.idempotencyKey}}async resolve(e){let r=await this.client.getSecretValue({SecretId:this.id(e)});if(r.SecretString==null)throw Error("AWS Secrets Manager value is unavailable.");return r.SecretString}async remove(e){await this.client.deleteSecret({SecretId:this.id(e),RecoveryWindowInDays:7})}async validate(e){try{return await this.client.describeSecret(this.id(e)),!0}catch{return!1}}id(e){let r=new URL(e);if(r.protocol!=="aws-sm:"||r.hostname!==this.region)throw Error("Invalid AWS Secrets Manager reference.");return decodeURIComponent(r.pathname.slice(1))}}class Pr{client;region;kind="aws_ssm";constructor(e,r){this.client=e;this.region=r}async put(e){let r=e.reference?this.name(e.reference):`/${e.name.replace(/^\/+/,"")}`,n=await this.client.putParameter({Name:r,Value:e.value,Type:"SecureString",Overwrite:!!e.reference,Description:"Managed by ts-cloud"});return{reference:`aws-ssm://${this.region}${r}`,version:String(n.Version??1)}}async resolve(e){let r=await this.client.getParameter({Name:this.name(e),WithDecryption:!0});if(r.Parameter?.Value==null)throw Error("AWS SSM parameter value is unavailable.");return r.Parameter.Value}async remove(e){await this.client.deleteParameter({Name:this.name(e)})}async validate(e){try{return!!(await this.client.getParameter({Name:this.name(e),WithDecryption:!1})).Parameter}catch{return!1}}name(e){let r=new URL(e);if(r.protocol!=="aws-ssm:"||r.hostname!==this.region||!r.pathname.startsWith("/"))throw Error("Invalid AWS SSM reference.");return r.pathname}}class Dr{kind="external";async put(){throw Error("External secret references cannot be written by ts-cloud.")}async resolve(){throw Error("External secrets must be resolved by the deployment provider.")}async remove(){}async validate(e){return/^(?:vault|doppler|op|external):\/\//.test(e)}}import{createHmac as A}from"node:crypto";var D=/^(?:secret|aws-sm|aws-ssm|vault|doppler|op|external):\/\//,O=/^(?:AWS_|TS_CLOUD_|PORT$|HOST$)/;function p(e){return[...new Set(e)].sort()}function R(e,r={}){let n=e.kind==="secret";return{id:e.id,key:e.key,kind:e.kind,scope:e.scope,inherited:!!r.inherited,overridden:!!r.overridden,required:e.required,backend:!n||r.canReadSecretMetadata?e.backend:void 0,backendVersion:!n||r.canReadSecretMetadata?e.backendVersion:void 0,reference:n&&r.canReadSecretMetadata?e.secretRef:void 0,value:!n?e.value:void 0,lastUsedAt:e.lastUsedAt,rotatedAt:e.rotatedAt,version:e.version,updatedAt:e.updatedAt}}class Nr{store;backends=new Map;fingerprintKey;now;constructor(e,r){if(this.store=e,this.fingerprintKey=r.fingerprintKey??r.encryptionKey,this.now=r.now??(()=>new Date),!this.fingerprintKey)throw Error("Configuration fingerprint key is required.");let n=r.backends??[new Tt(e.controlPlane,r.encryptionKey,this.now)];for(let t of n)this.backends.set(t.kind,t)}list(e){let r=e.search?.toLowerCase();return this.store.list(e).filter((n)=>!r||n.key.toLowerCase().includes(r)).map((n)=>R(n,{canReadSecretMetadata:e.canReadSecretMetadata}))}plan(e){let r=this.store.list({projectId:e.projectId,scope:e.scope}),n=new Map(r.map((o)=>[o.key,o])),t=[],i=[],s=[],c=[];for(let[o,a]of Object.entries(e.values)){t.push(...this.warnings(o,a));let d=n.get(o);if(!d)i.push(o);else if(d.valueFingerprint!==this.fingerprint(a))s.push(o);else c.push(o)}let u=e.removeMissing?r.filter((o)=>!Object.hasOwn(e.values,o.key)).map((o)=>o.key):[];return{added:p(i),changed:p(s),removed:p(u),unchanged:p(c),affectedResourceIds:this.affectedResources(e.projectId,e.scope,[...i,...s,...u]),warnings:t}}async set(e){let r=this.requestHash(e),n=e.idempotencyKey;if(n){let f=this.store.mutation(n);if(f){if(f.requestHash!==r)throw Error("Idempotency key was already used for a different configuration mutation.");let m=this.store.get(String(f.result.entryId??""));if(!m)throw Error("Idempotent configuration result is no longer available.");return{entry:m,mutation:f.result.mutation,warnings:[]}}}if(e.value!=null&&D.test(e.value))throw Error("Secret references must use the reference field, not a plaintext value field.");let t=this.store.find(e.projectId,e.scope,e.key),i=this.fingerprint(e.value??e.reference??"");if(t&&e.expectedVersion!=null&&t.version!==e.expectedVersion)throw Error("Configuration entry changed; refresh and retry.");if(t&&t.kind!==e.kind)throw Error("Delete the existing entry before changing between variable and secret kinds.");let s=e.kind==="variable"?"plaintext":e.backend??(e.reference?"external":"local_encrypted");if(!!t&&(t.valueFingerprint!==i||t.backend!==s||t.required!==!!e.required)&&(this.isProduction(t)||this.store.dependencies(t.id).length>0)&&!e.confirmed)throw Error("Confirmation is required because this replacement affects production or dependent services.");let u=e.reference,o;if(e.kind==="secret"){let f=this.backend(s);if(e.reference&&e.value==null){if(!await f.validate(e.reference))throw Error("Secret backend reference is unavailable or invalid.");o=t?.backendVersion??"external"}else{if(e.value==null)throw Error("A secret value or external reference is required.");let m=await f.put({reference:t?.backend===s?t.secretRef:void 0,name:this.backendName(e),value:e.value,idempotencyKey:n??crypto.randomUUID()});u=m.reference,o=m.version}}let a=e.kind==="variable"?e.value:void 0;if(e.kind==="variable"&&a==null)throw Error("A variable value is required.");let d=!t||t.valueFingerprint!==i||t.backend!==s||t.secretRef!==u||t.backendVersion!==o||t.required!==!!e.required,g=t?d?this.store.update(t.id,t.version,{value:a,valueFingerprint:i,secretRef:u,backend:s,backendVersion:o,required:!!e.required,metadata:h(e.metadata??t.metadata),rotatedAt:e.kind==="secret"?this.now().toISOString():t.rotatedAt}):t:this.store.create({organizationId:e.organizationId,projectId:e.projectId,scope:e.scope,key:e.key,kind:e.kind,value:a,valueFingerprint:i,secretRef:u,backend:s,backendVersion:o,origin:e.origin??"managed",required:!!e.required,metadata:h(e.metadata??{}),rotatedAt:e.kind==="secret"?this.now().toISOString():void 0}),l=this.affectedResources(e.projectId,e.scope,[e.key]),v={added:t?[]:[e.key],changed:t&&d?[e.key]:[],removed:[],unchanged:t&&!d?[e.key]:[],affectedResourceIds:l,versions:{[e.key]:g.version}};if(n)this.store.recordMutation({projectId:e.projectId,idempotencyKey:n,requestHash:r,actorId:e.actorId,result:{entryId:g.id,mutation:v}});return this.audit(e.projectId,e.actorId,t&&d?"configuration.updated":t?"configuration.unchanged":"configuration.created",g,l),{entry:g,mutation:v,warnings:this.warnings(e.key,e.value??"")}}async importDotenv(e){let r=qc(e.source);if(!r.valid)return{document:r,warnings:[]};let n=new Set(e.secretKeys??[]),t={added:[],changed:[],removed:[],unchanged:[],affectedResourceIds:[],versions:{}},i=[];for(let[s,c]of Object.entries(r.values)){let u=await this.set({...e,source:void 0,key:s,value:c,kind:n.has(s)?"secret":"variable",idempotencyKey:e.idempotencyKey?`${e.idempotencyKey}:${s}`:void 0});t.added.push(...u.mutation.added),t.changed.push(...u.mutation.changed),t.unchanged.push(...u.mutation.unchanged),t.affectedResourceIds.push(...u.mutation.affectedResourceIds),Object.assign(t.versions,u.mutation.versions),i.push(...u.warnings)}return t.added=p(t.added),t.changed=p(t.changed),t.unchanged=p(t.unchanged),t.affectedResourceIds=p(t.affectedResourceIds),{document:r,mutation:t,warnings:i}}exportVariables(e){return Gc(Object.fromEntries(this.store.list({projectId:e.projectId,scope:e.scope,kind:"variable"}).map((r)=>[r.key,r.value??""])))}async transfer(e){let r=this.store.get(e.entryId);if(!r)throw Error("Configuration entry was not found.");if(r.scope.type===e.targetScope.type&&r.scope.id===e.targetScope.id)throw Error("Choose a different destination scope.");let n=r.kind==="variable"?r.value:r.backend==="external"?void 0:await this.backend(r.backend).resolve(r.secretRef),t=r.kind==="secret"?r.backend:void 0,i=await this.set({organizationId:r.organizationId,projectId:r.projectId,scope:e.targetScope,key:r.key,kind:r.kind,value:n,reference:r.backend==="external"?r.secretRef:void 0,backend:t,required:r.required,metadata:r.metadata,confirmed:e.confirmed,actorId:e.actorId,idempotencyKey:e.idempotencyKey?`${e.idempotencyKey}:copy`:void 0,origin:r.origin});if(e.mode==="move")await this.remove({entryId:r.id,expectedVersion:r.version,confirmed:e.confirmed,actorId:e.actorId});let s={added:i.mutation.added,changed:i.mutation.changed,removed:e.mode==="move"?[r.key]:[],unchanged:i.mutation.unchanged,affectedResourceIds:p([...i.mutation.affectedResourceIds,...this.affectedResources(r.projectId,r.scope,[r.key])]),versions:i.mutation.versions};return{entry:i.entry,mutation:s}}async resolve(e){let r=this.store.list({projectId:e.projectId}),n=r.filter((a)=>this.applies(a,e)).sort((a,d)=>this.rank(a.scope.type)-this.rank(d.scope.type)),t=new Map,i=new Set;for(let a of n){if(t.has(a.key))i.add(a.key);t.set(a.key,a)}let s={},c={},u=[],o=new Set(e.allowedPreviewSecrets??[]);for(let[a,d]of t){if(e.previewId&&d.kind==="secret"&&d.scope.type!=="preview"&&(!e.trustedPreview||!o.has(a)))continue;if(d.kind==="variable")s[a]=d.value??"";else if(e.nativeReferences)s[a]=d.secretRef;else{let g=this.backend(d.backend);if(!await g.validate(d.secretRef)){if(u.push({key:a,code:"stale_reference",message:`${a} points to an unavailable secret.`}),d.required)u.push({key:a,code:"missing_required",message:`${a} is required but unavailable.`});continue}s[a]=await g.resolve(d.secretRef)}c[a]=R(d,{inherited:d.scope.type!==(e.previewId?"preview":e.functionId?"function":e.resourceId?"service":e.environmentId?"environment":"project"),overridden:i.has(a),canReadSecretMetadata:e.canReadSecretMetadata}),this.store.controlPlane.database.run("UPDATE configuration_entries SET last_used_at=? WHERE id=?",[this.now().toISOString(),d.id])}return{values:s,entries:c,warnings:u,configurationHash:this.fingerprint([...t.values()].map((a)=>`${a.key}:${a.valueFingerprint}:${a.version}`).sort().join(`
8
+ `))}}async reveal(e){let r=this.store.get(e.entryId);if(!r||r.kind!=="secret")throw Error("Configuration secret was not found.");if(!e.canRevealSecrets)throw Error("Secret reveal permission is required.");if(!e.recentlyAuthenticated)throw Error("Recent authentication is required to reveal a secret.");let n=await this.backend(r.backend).resolve(r.secretRef);return this.audit(r.projectId,e.actorId,"configuration.secret.revealed",r,[]),n}async remove(e){let r=this.store.get(e.entryId);if(!r)throw Error("Configuration entry was not found.");let n=this.store.dependencies(r.id);if(((r.scope.environmentId?this.store.controlPlane.listEnvironments(r.projectId).some((c)=>c.id===r.scope.environmentId&&c.kind==="production"):r.scope.type==="project")||n.length)&&!e.confirmed)throw Error("Confirmation is required because this configuration affects production or dependent services.");if(r.kind==="secret"&&r.backend!=="external")await this.backend(r.backend).remove(r.secretRef);this.store.remove(r.id,e.expectedVersion);let i=p(n.map((c)=>c.resourceId)),s={added:[],changed:[],removed:[r.key],unchanged:[],affectedResourceIds:i,versions:{}};return this.audit(r.projectId,e.actorId,"configuration.deleted",r,i),s}applies(e,r){if(e.scope.type==="project")return!0;if(e.scope.type==="environment")return e.scope.id===r.environmentId;if(e.scope.type==="service")return e.scope.id===r.resourceId;if(e.scope.type==="function")return e.scope.id===r.functionId;return e.scope.id===r.previewId}rank(e){return{project:0,environment:1,service:2,function:3,preview:4}[e]}fingerprint(e){return`hmac-sha256:${A("sha256",this.fingerprintKey).update(e).digest("hex")}`}requestHash(e){return this.fingerprint(JSON.stringify({...e,idempotencyKey:void 0,actorId:void 0}))}backend(e){let r=this.backends.get(e);if(!r)throw Error(`Configuration secret backend is not configured: ${e}`);return r}backendName(e){return`ts-cloud/${e.projectId}/${e.scope.type}/${e.scope.id}/${e.key}`.replace(/[^A-Za-z0-9/_+=.@-]/g,"-")}isProduction(e){return e.scope.type==="project"||!!e.scope.environmentId&&this.store.controlPlane.listEnvironments(e.projectId).some((r)=>r.id===e.scope.environmentId&&r.kind==="production")}warnings(e,r){let n=[];if(O.test(e))n.push({key:e,code:"reserved",message:`${e} may be reserved by the runtime or provider.`});if(Buffer.byteLength(r)>65536)n.push({key:e,code:"limit",message:`${e} exceeds the portable 64 KiB value limit.`});return n}affectedResources(e,r,n){let t=this.store.list({projectId:e,scope:r}).filter((i)=>n.includes(i.key)).flatMap((i)=>this.store.dependencies(i.id).map((s)=>s.resourceId));if(r.type==="service"||r.type==="function")return p([...t,r.id]);if(r.type==="environment")return p([...t,...this.store.controlPlane.listResources(e,r.id).map((i)=>i.id)]);if(r.type==="preview"){let i=this.store.controlPlane.database.query("SELECT resource_id FROM preview_instances WHERE id=?").get(r.id);return p([...t,...i?[i.resource_id]:[]])}return p([...t,...this.store.controlPlane.listResources(e).map((i)=>i.id)])}audit(e,r,n,t,i){this.store.controlPlane.appendEvent({projectId:e,actorId:r,type:n,payload:{entryId:t.id,key:t.key,kind:t.kind,scopeType:t.scope.type,scopeId:t.scope.id,backend:t.backend,version:t.version,affectedResourceIds:i}})}}async function un(e,r,n,t){let i={added:0,changed:0,removed:0,overridden:0},s=async(c,u)=>{let o=e.store.list({projectId:r.project.id,scope:c,kind:"variable"}),a=new Set(Object.keys(u));for(let d of o.filter((g)=>g.origin==="config"&&!a.has(g.key)))await e.remove({entryId:d.id,expectedVersion:d.version,confirmed:!0,actorId:t}),i.removed++;for(let[d,g]of Object.entries(u)){let l=e.store.find(r.project.id,c,d);if(l?.origin!=="config"){if(l)i.overridden++;else await e.set({organizationId:r.organization.id,projectId:r.project.id,scope:c,key:d,kind:"variable",value:String(g),origin:"config",confirmed:!0,actorId:t}),i.added++;continue}if(l.value===String(g))continue;await e.set({organizationId:r.organization.id,projectId:r.project.id,scope:c,key:d,kind:"variable",value:String(g),origin:"config",confirmed:!0,actorId:t,expectedVersion:l.version}),i.changed++}};for(let[c,u]of Object.entries(n.environments??{})){let o=r.environments.get(c);if(!o)continue;let a=u,d={...a.variables??{},...a.app?.env??{}};await s({type:"environment",id:o.id,environmentId:o.id},d);for(let[g,l]of Object.entries(n.sites??{})){let v=r.store.listResources(r.project.id,o.id).find((f)=>f.kind==="application"&&f.slug===g);if(v)await s({type:"service",id:v.id,environmentId:o.id,resourceId:v.id},{...l.env??{}})}for(let[g,l]of Object.entries(n.infrastructure?.functions??{})){let v=r.store.listResources(r.project.id,o.id).find((f)=>f.kind==="function"&&f.slug===g);if(v)await s({type:"function",id:v.id,environmentId:o.id,resourceId:v.id},{...l.environment??{}})}}return i}export{Rr,qc,Gc,Tt,Ir,Pr,Dr,Nr,un};
@@ -0,0 +1 @@
1
+ import{Rr,qc,Gc,Tt,Ir,Pr,Dr,Nr,un}from"./chunk-gd94501z.js";import"./chunk-4zxwtvvf.js";import"./chunk-hsek7hvh.js";import"./chunk-kj4gm2hk.js";export{Ir as AwsSecretsManagerConfigurationBackend,Pr as AwsSsmConfigurationBackend,Nr as ConfigurationService,Rr as ConfigurationStore,Dr as ExternalConfigurationBackend,Tt as LocalEncryptedConfigurationBackend,qc as parseDotenv,Gc as serializeDotenv,un as synchronizeConfiguredConfiguration};
@@ -0,0 +1 @@
1
+ import{Ip,hd,tc,rc,yd,Pp,Dp,Qt,En,Yt,Ui,Np,wn,Ks}from"./chunk-6sdffc79.js";import{We,oo,uc,ci,ao,Up}from"./chunk-7xj986z7.js";import{Md,ds,Ud,Fd,Bd,Cr,Zp,us}from"./chunk-8gay06gq.js";import{qa,Ga,Wa,nd,Mi,id,sd,Hs,Ka,Ja}from"./chunk-hsek7hvh.js";import"./chunk-kj4gm2hk.js";export{Ga as CHAIN_HEADER,En as DEFAULT_ATTACK_MODE_HOURS,Md as DEFAULT_DDOS_THRESHOLDS,Mi as DEFAULT_RECURSION_LIMITS,qa as DEPTH_HEADER,Qt as MAX_CONTROL_HOURS,Yt as ProtectionControlStore,Ip as RATE_LIMIT_KEY_SEPARATOR,yd as RateLimiter,Hs as RecursionGuard,Wa as TRACE_HEADER,wn as applyControlsToDdos,Np as applyControlsToRateLimits,us as applyMitigationFactor,Dp as defaultRateLimitRules,Ui as describePosture,We as escapeSecLang,nd as functionFingerprint,hd as globMatches,uc as globToRegex,sd as inspectInvocation,oo as isSafePattern,ds as isValidCidr,Ks as mergeControlsIntoConfig,id as parseChain,Zp as planMitigation,Ka as propagationHeaders,Pp as rateLimitHeaders,rc as rateLimitKey,Ja as recursionBlockedResponse,Cr as renderDdosInstallScript,Bd as renderNftablesRuleset,Fd as renderSysctlFile,ci as renderWafConfig,ao as renderWafInstallScript,tc as ruleMatches,Ud as sysctlHardening,Up as wafEventTelemetry};