@stacksjs/actions 0.75.72 → 0.75.74
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/database/seed.js +1 -1
- package/dist/deploy/index.js +8 -8
- package/dist/domains/purchase.js +1 -1
- package/dist/domains/remove.js +1 -1
- package/dist/generate/index.js +1 -1
- package/dist/helpers/utils.js +1 -1
- package/dist/lint/lint.d.ts +8 -0
- package/dist/lint/lint.js +1 -1
- package/dist/stacks.js +1 -1
- package/dist/upgrade/shell.js +2 -2
- package/dist/upgrade.js +1 -1
- package/package.json +44 -44
- package/dist/ai/request-model-access.d.ts +0 -1
- package/dist/ai/request-model-access.js +0 -1
- package/dist/generate/pantry-file.d.ts +0 -1
- package/dist/generate/pantry-file.js +0 -1
package/dist/database/seed.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import process from"node:process";import{log}from"@stacksjs/cli";import{seed}from"@stacksjs/database";const argv=process.argv.slice(2),allowProtected=argv.includes("--allow-protected")||argv.includes("--allowProtected"),fresh=argv.includes("--fresh"),startTime=Date.now();try{const result=await seed({verbose:!0,fresh,allowProtected}),duration=Date.now()-startTime;if(result.failed>0){log.warn("");log.warn(`Seeding completed with ${result.failed} failure(s):`);for(const r of result.results)if(!r.success)log.error(` - ${r.model}: ${r.error}`);log.info("");log.info("Note: Failed models may have schema mismatches or invalid factory functions.");log.info("Tip: Run `./buddy migrate:fresh` to ensure schema is up to date.")}log.info("");log.success(`Seeding completed in ${duration}ms`);log.info(` Total models: ${result.total}`);log.info(` Successful: ${result.successful}`);log.info(` Failed: ${result.failed}`);await log.flush();process.exit(0)}catch(err){await log.error("Seeding failed catastrophically:",err);process.exit(1)}
|
|
1
|
+
import process from"node:process";import{log}from"@stacksjs/cli";import{seed}from"@stacksjs/database";const argv=process.argv.slice(2),allowProtected=argv.includes("--allow-protected")||argv.includes("--allowProtected"),attachAccounts=argv.includes("--attach-accounts")||argv.includes("--attachAccounts"),fresh=argv.includes("--fresh"),startTime=Date.now();try{const result=await seed({verbose:!0,fresh,allowProtected,attachAccounts}),duration=Date.now()-startTime;if(result.failed>0){log.warn("");log.warn(`Seeding completed with ${result.failed} failure(s):`);for(const r of result.results)if(!r.success)log.error(` - ${r.model}: ${r.error}`);log.info("");log.info("Note: Failed models may have schema mismatches or invalid factory functions.");log.info("Tip: Run `./buddy migrate:fresh` to ensure schema is up to date.")}log.info("");log.success(`Seeding completed in ${duration}ms`);log.info(` Total models: ${result.total}`);log.info(` Successful: ${result.successful}`);log.info(` Failed: ${result.failed}`);await log.flush();process.exit(0)}catch(err){await log.error("Seeding failed catastrophically:",err);process.exit(1)}
|
package/dist/deploy/index.js
CHANGED
|
@@ -7,8 +7,8 @@ ${children}${indent}</${name}>
|
|
|
7
7
|
<DistributionConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
|
|
8
8
|
${Object.entries(config).filter(([key])=>!key.startsWith("@_")).map(([key,val])=>buildCloudFrontXmlElement(key,val," ")).join("")}</DistributionConfig>
|
|
9
9
|
`}function firewallOpenCommand(ports){const uniquePorts=[...new Set(ports)].filter((port)=>Number.isFinite(port)&&port>0).sort((a,b)=>a-b);if(uniquePorts.length===0)return"true";return`if command -v firewall-cmd >/dev/null 2>&1; then firewall-cmd --permanent ${uniquePorts.map((port)=>`--add-port=${port}/tcp`).join(" ")} && firewall-cmd --reload; fi`}async function ensureSecurityGroupPort(ec2,securityGroupId,port){if(!securityGroupId)return;if(((await ec2.describeSecurityGroups({GroupIds:[securityGroupId]}))?.SecurityGroups?.[0]?.IpPermissions||[]).some((permission)=>{return permission.IpProtocol==="tcp"&&Number(permission.FromPort)<=port&&Number(permission.ToPort)>=port&&normalizeArray(permission.IpRanges).some((range)=>range.CidrIp==="0.0.0.0/0")}))return;try{await ec2.authorizeSecurityGroupIngress({GroupId:securityGroupId,IpPermissions:[{IpProtocol:"tcp",FromPort:port,ToPort:port,IpRanges:[{CidrIp:"0.0.0.0/0",Description:`Stacks API port ${port}`}]}]})}catch(error){if(!String(error?.message||"").includes("InvalidPermission.Duplicate"))throw error}}async function ensureCloudFrontApiOriginPort(awsClient,distributionId,port){if(!distributionId)return;const getResult=await awsClient.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${distributionId}/config`,returnHeaders:!0}),etag=getResult.headers?.etag||getResult.headers?.ETag||"",currentConfig=getResult.body?.DistributionConfig||getResult.DistributionConfig||getResult.body;if(!etag||!currentConfig?.Origins?.Items)return;const apiOrigin=normalizeArray(currentConfig.Origins.Items.Origin).find((origin)=>String(origin.Id||"").includes("-api"));if(!apiOrigin?.CustomOriginConfig)return;if(Number(apiOrigin.CustomOriginConfig.HTTPPort)===port)return;apiOrigin.CustomOriginConfig.HTTPPort=port;await awsClient.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${distributionId}/config`,body:buildCloudFrontDistributionConfigXml(currentConfig),headers:{"Content-Type":"application/xml","If-Match":etag}})}const frameworkBuildSpinner=spinner("Building framework...");frameworkBuildSpinner.start();const frameworkBuilt=await runCommand("bun run build",{cwd:p.frameworkPath("core"),quiet:!1});if(frameworkBuilt.isErr){frameworkBuildSpinner.fail("Framework build failed - see the output above");process.exit(ExitCode.FatalError)}frameworkBuildSpinner.succeed("Framework built");const docsDir=p.projectPath("docs"),docsBuildDir=p.projectPath("dist/docs/.bunpress");if(storage.hasFiles(docsDir)){const docsSpinner=spinner("Building documentation with BunPress...");docsSpinner.start();try{const{rm}=await import("node:fs/promises"),localBunpressCli=`${process.env.HOME}/Code/Tools/bunpress/packages/bunpress/bin/cli.ts`,installedBunpressCli=p.projectPath("node_modules/@stacksjs/bunpress/dist/bin/cli.js"),hasLocalBunpress=await Bun.file(localBunpressCli).exists(),hasInstalledBunpress=await Bun.file(installedBunpressCli).exists(),command=hasLocalBunpress?`bun ${localBunpressCli} build --dir ${docsDir} --outdir ${p.projectPath("dist/docs")}`:hasInstalledBunpress?`bun ${installedBunpressCli} build --dir ${docsDir} --outdir ${p.projectPath("dist/docs")}`:"bunx @stacksjs/bunpress@0.1.5 build --dir ./docs --outdir ./dist/docs";await rm(docsBuildDir,{recursive:!0,force:!0});await runCommand(command,{cwd:p.projectPath(),quiet:!isVerbose});docsSpinner.succeed(`Documentation built with BunPress${hasLocalBunpress?" (local checkout)":""}`)}catch(docsError){docsSpinner.stop();console.log(`\u26A0 Documentation build skipped: ${docsError.message}`);if(isVerbose)log.debug("To build docs manually: cd ~/Code/Tools/bunpress && bun packages/bunpress/bin/cli.ts build --dir /path/to/docs --outdir /path/to/dist/docs")}}else if(isVerbose)log.debug("No docs directory found, skipping documentation build");const blogDistExists=storage.hasFiles(p.projectPath("dist/blog")),blogFontAssetsExist=["CampmateScript-Regular.woff2","SequoiaSans-Regular.woff2","Switchback-Regular.woff2"].every((file)=>existsSync(p.projectPath(`dist/blog/assets/fonts/nps/${file}`))),blogImageAssetsExist=["topography.svg","park-ridge.svg"].every((file)=>existsSync(p.projectPath(`dist/blog/assets/images/${file}`))),blogIndexPath=p.projectPath("dist/blog/index.html"),blogIndexHtml=existsSync(blogIndexPath)?readFileSync(blogIndexPath,"utf8"):"",blogHtmlUsesCurrentFontFormat=blogIndexHtml.length>0&&!blogIndexHtml.includes("woff2-variations"),blogHtmlUsesCurrentParkTheme=blogIndexHtml.includes("--on-primary")&&blogIndexHtml.includes("--newsletter-bg"),blogHtmlUsesCurrentParkImages=blogIndexHtml.includes("topography.svg")&&blogIndexHtml.includes("park-ridge.svg"),blogHtmlOmitsRetiredDecorations=!blogIndexHtml.includes("stamp-trail")&&!blogIndexHtml.includes("blog-sign-tree.svg"),blogBuilderPath=p.frameworkPath("core/cms/src/build.ts"),blogConfigPath=p.projectPath("config/blog.ts"),blogHtmlIsFresh=existsSync(blogIndexPath)&&[blogBuilderPath,blogConfigPath].filter((path)=>existsSync(path)).every((path)=>statSync(blogIndexPath).mtimeMs>=statSync(path).mtimeMs);if(!blogDistExists||!blogFontAssetsExist||!blogImageAssetsExist||!blogHtmlUsesCurrentFontFormat||!blogHtmlUsesCurrentParkTheme||!blogHtmlUsesCurrentParkImages||!blogHtmlOmitsRetiredDecorations||!blogHtmlIsFresh){const blogBuildSpinner=spinner("Building blog...");blogBuildSpinner.start();try{const blogConfig=(await import(p.projectPath("config/blog"))).default,{buildBlogSite}=await import(p.frameworkPath("core/cms/src/build"));await buildBlogSite({config:blogConfig,outDir:p.projectPath("dist/blog")});blogBuildSpinner.succeed("Blog built successfully")}catch(blogBuildError){blogBuildSpinner.stop();console.log(`\u26A0 Blog build skipped: ${blogBuildError.message}`);if(isVerbose)log.debug(`Blog build error: ${blogBuildError.stack}`)}}else if(isVerbose)log.debug("Pre-built blog found at dist/blog, skipping build");if(isVerbose)log.debug("Skipping views build (vite-config not configured)");const earlyCloudConfig=await import(p.projectPath("config/cloud")),earlyDeploymentMode=earlyCloudConfig?.tsCloud?.mode||"server";if(earlyDeploymentMode==="serverless"){const serverSpinner=spinner("Building server...");serverSpinner.start();if((await runCommand("bun build.ts",{cwd:p.frameworkPath("server"),quiet:!isVerbose})).isErr){serverSpinner.fail("Server build failed - rerun with --verbose to see its output");process.exit(ExitCode.FatalError)}serverSpinner.succeed("Server built");const packageSpinner=spinner("Packaging for deployment...");packageSpinner.start();if((await runCommand("bun zip.ts",{cwd:p.corePath("cloud"),quiet:!isVerbose})).isErr){packageSpinner.fail("Packaging failed - rerun with --verbose to see its output");process.exit(ExitCode.FatalError)}packageSpinner.succeed("Package ready")}else if(isVerbose)log.debug("Skipping server build and packaging (server mode)");if(!process.env.AWS_ACCESS_KEY_ID||!process.env.AWS_SECRET_ACCESS_KEY){const{existsSync,readFileSync}=await import("node:fs"),environment=process.env.APP_ENV||process.env.NODE_ENV||"production",envFiles=[p.projectPath(`.env.${environment}`),p.projectPath(".env")];for(const envPath of envFiles)if(existsSync(envPath)){const content=readFileSync(envPath,"utf-8");for(const line of content.split(`
|
|
10
|
-
`)){const trimmed=line.trim();if(trimmed.startsWith("#")||!trimmed.includes("="))continue;const eqIndex=trimmed.indexOf("="),key=trimmed.slice(0,eqIndex).trim();let value=trimmed.slice(eqIndex+1).trim();if(value.startsWith('"')&&value.endsWith('"')||value.startsWith("'")&&value.endsWith("'"))value=value.slice(1,-1);if(key==="AWS_ACCESS_KEY_ID"&&value)process.env.AWS_ACCESS_KEY_ID=value;else if(key==="AWS_SECRET_ACCESS_KEY"&&value)process.env.AWS_SECRET_ACCESS_KEY=value;else if(key==="AWS_REGION"&&value&&!process.env.AWS_REGION)process.env.AWS_REGION=value;else if(key==="AWS_ACCOUNT_ID"&&value&&!process.env.AWS_ACCOUNT_ID)process.env.AWS_ACCOUNT_ID=value;else if(key.startsWith("MAIL_PASSWORD_")&&value&&!process.env[key])process.env[key]=value}if(isVerbose)log.debug(`Loaded AWS credentials from ${envPath}`);break}}try{const{deployStack,deployFrontend:_deployFrontend}=await import("../../deploy"),environment=process.env.APP_ENV||process.env.NODE_ENV||"production",
|
|
11
|
-
Set AWS_ACCOUNT_ID in your .env file or ensure valid AWS credentials are configured.`);const ecrRepository=`${accountId}.dkr.ecr.${region}.amazonaws.com/${projectName}-${environment}-api`,imageTag=`${ecrRepository}:latest`;if(isVerbose)log.debug(`ECR repository: ${ecrRepository}`);if(isVerbose)log.debug("ECR credentials will be validated before push...");const buildSpinner=spinner("Building Docker image...");buildSpinner.start();try{const{exec}=await import("node:child_process"),{promisify}=await import("node:util"),execAsync=promisify(exec),buildCmd=`docker build --platform linux/amd64 -t ${imageTag} -f Dockerfile .`,{stdout,stderr}=await execAsync(buildCmd,{cwd:p.projectPath(),env:process.env,maxBuffer:10485760,timeout:900000});if(isVerbose&&stdout)log.debug(stdout);if(isVerbose&&stderr)log.debug(stderr);buildSpinner.succeed(`Docker image built: ${imageTag}`)}catch(error){buildSpinner.fail("Docker build failed");if(isVerbose)log.debug(`Docker build error: ${error.message}`);throw error}const repoSpinner=spinner("Checking ECR repository...");repoSpinner.start();try{const{ECRClient}=await import("@stacksjs/ts-cloud"),ecr=new ECRClient(region),repoName=`${projectName}-${environment}-api`;try{await ecr.describeRepositories({repositoryNames:[repoName]});repoSpinner.succeed(`ECR repository exists: ${repoName}`)}catch(err){if(err.code==="RepositoryNotFoundException"||err.message?.includes("RepositoryNotFoundException")){repoSpinner.text=`Creating ECR repository: ${repoName}...`;await ecr.createRepository({repositoryName:repoName,imageScanningConfiguration:{scanOnPush:!0},imageTagMutability:"MUTABLE"});repoSpinner.succeed(`ECR repository created: ${repoName}`)}else throw err}}catch(error){repoSpinner.fail("ECR repository check failed");if(isVerbose)log.debug(`ECR repository error: ${error.message}`);throw error}const authSpinner=spinner("Authenticating to ECR...");authSpinner.start();try{const{ECRClient}=await import("@stacksjs/ts-cloud"),token=(await new ECRClient(region).getAuthorizationToken()).authorizationData?.[0];if(!token?.authorizationToken)throw Error("No authorization token received from ECR");const decoded=Buffer.from(token.authorizationToken,"base64").toString("utf-8"),colonIndex=decoded.indexOf(":");if(colonIndex===-1)throw Error("ECR authorization token has unexpected format (missing colon separator)");const password=decoded.slice(colonIndex+1),loginResult=Bun.spawnSync(["docker","login","--username","AWS","--password-stdin",`${accountId}.dkr.ecr.${region}.amazonaws.com`],{stdin:new TextEncoder().encode(password),stdout:"pipe",stderr:"pipe"});if(loginResult.exitCode!==0){const loginError=new TextDecoder().decode(loginResult.stderr);throw Error(`Docker login failed: ${loginError}`)}authSpinner.succeed("Authenticated to ECR")}catch(error){authSpinner.fail("ECR authentication failed");if(isVerbose)log.debug(`ECR auth error: ${error.message}`);throw error}console.log("");const pushSpinner=spinner("Pushing image to ECR...");pushSpinner.start();try{const{exec}=await import("node:child_process"),{promisify}=await import("node:util"),execAsync=promisify(exec),pushCmd=`docker push ${imageTag}`;await execAsync(pushCmd,{env:process.env});pushSpinner.succeed(`Image pushed: ${imageTag}`)}catch(error){pushSpinner.fail("Docker push failed");if(isVerbose)log.debug(`Push error: ${error.message}`);throw error}console.log("");console.log("Container image ready in ECR. CloudFormation will use this image.");console.log("")}else{console.log("");console.log("Server deployment mode detected");console.log("Deploying EC2 infrastructure via CloudFormation...");console.log("")}async function getAwsAccountId(region){try{const{STSClient}=await import("@stacksjs/ts-cloud"),accountId=(await new STSClient(region).getCallerIdentity()).Account||process.env.AWS_ACCOUNT_ID||"";if(isVerbose)log.debug(`Retrieved AWS Account ID: ${accountId||"(empty)"}`);return accountId}catch(error){if(isVerbose)log.debug(`Failed to get AWS Account ID: ${error.message}`);return process.env.AWS_ACCOUNT_ID||""}}try{const deployScript=await import(p.projectPath("cloud/deploy-script"));if(typeof deployScript.beforeDeploy==="function")await deployScript.beforeDeploy({environment,region})}catch(hookError){if(hookError.code==="ERR_MODULE_NOT_FOUND"||hookError.code==="MODULE_NOT_FOUND"){if(isVerbose)log.debug("No beforeDeploy hook found (cloud/deploy-script not found)")}else{console.warn(`\u26A0 beforeDeploy hook failed: ${hookError.message}`);if(isVerbose)log.debug(`beforeDeploy error stack: ${hookError.stack}`)}}await deployStack({environment,region,waitForCompletion:!0,verbose:isVerbose});try{const deployScript=await import(p.projectPath("cloud/deploy-script"));if(typeof deployScript.afterDeploy==="function"){const{CloudFormationClient}=await import("@stacksjs/ts-cloud"),cf=new CloudFormationClient(region),stackName
|
|
10
|
+
`)){const trimmed=line.trim();if(trimmed.startsWith("#")||!trimmed.includes("="))continue;const eqIndex=trimmed.indexOf("="),key=trimmed.slice(0,eqIndex).trim();let value=trimmed.slice(eqIndex+1).trim();if(value.startsWith('"')&&value.endsWith('"')||value.startsWith("'")&&value.endsWith("'"))value=value.slice(1,-1);if(key==="AWS_ACCESS_KEY_ID"&&value)process.env.AWS_ACCESS_KEY_ID=value;else if(key==="AWS_SECRET_ACCESS_KEY"&&value)process.env.AWS_SECRET_ACCESS_KEY=value;else if(key==="AWS_REGION"&&value&&!process.env.AWS_REGION)process.env.AWS_REGION=value;else if(key==="AWS_ACCOUNT_ID"&&value&&!process.env.AWS_ACCOUNT_ID)process.env.AWS_ACCOUNT_ID=value;else if(key.startsWith("MAIL_PASSWORD_")&&value&&!process.env[key])process.env[key]=value}if(isVerbose)log.debug(`Loaded AWS credentials from ${envPath}`);break}}try{const{deployStack,deployFrontend:_deployFrontend}=await import("../../deploy"),environment=process.env.APP_ENV||process.env.NODE_ENV||"production",{stacksCloudName,stacksCloudRegion}=await import("@stacksjs/cloud"),region=await stacksCloudRegion(void 0,environment),cloudStackName=await stacksCloudName(),cloudConfigModule=await import(p.projectPath("config/cloud")),deploymentMode=cloudConfigModule?.tsCloud?.mode||"server",projectName=cloudConfigModule?.tsCloud?.project?.name||cloudConfigModule?.tsCloud?.project?.slug||"stacks";if(deploymentMode==="serverless"){console.log("");console.log("Serverless deployment mode detected");console.log("Building and pushing container image...");console.log("");const accountId=process.env.AWS_ACCOUNT_ID||await getAwsAccountId(region);if(!accountId||accountId.length<10)throw Error(`Invalid AWS Account ID: "${accountId||"(empty)"}"
|
|
11
|
+
Set AWS_ACCOUNT_ID in your .env file or ensure valid AWS credentials are configured.`);const ecrRepository=`${accountId}.dkr.ecr.${region}.amazonaws.com/${projectName}-${environment}-api`,imageTag=`${ecrRepository}:latest`;if(isVerbose)log.debug(`ECR repository: ${ecrRepository}`);if(isVerbose)log.debug("ECR credentials will be validated before push...");const buildSpinner=spinner("Building Docker image...");buildSpinner.start();try{const{exec}=await import("node:child_process"),{promisify}=await import("node:util"),execAsync=promisify(exec),buildCmd=`docker build --platform linux/amd64 -t ${imageTag} -f Dockerfile .`,{stdout,stderr}=await execAsync(buildCmd,{cwd:p.projectPath(),env:process.env,maxBuffer:10485760,timeout:900000});if(isVerbose&&stdout)log.debug(stdout);if(isVerbose&&stderr)log.debug(stderr);buildSpinner.succeed(`Docker image built: ${imageTag}`)}catch(error){buildSpinner.fail("Docker build failed");if(isVerbose)log.debug(`Docker build error: ${error.message}`);throw error}const repoSpinner=spinner("Checking ECR repository...");repoSpinner.start();try{const{ECRClient}=await import("@stacksjs/ts-cloud"),ecr=new ECRClient(region),repoName=`${projectName}-${environment}-api`;try{await ecr.describeRepositories({repositoryNames:[repoName]});repoSpinner.succeed(`ECR repository exists: ${repoName}`)}catch(err){if(err.code==="RepositoryNotFoundException"||err.message?.includes("RepositoryNotFoundException")){repoSpinner.text=`Creating ECR repository: ${repoName}...`;await ecr.createRepository({repositoryName:repoName,imageScanningConfiguration:{scanOnPush:!0},imageTagMutability:"MUTABLE"});repoSpinner.succeed(`ECR repository created: ${repoName}`)}else throw err}}catch(error){repoSpinner.fail("ECR repository check failed");if(isVerbose)log.debug(`ECR repository error: ${error.message}`);throw error}const authSpinner=spinner("Authenticating to ECR...");authSpinner.start();try{const{ECRClient}=await import("@stacksjs/ts-cloud"),token=(await new ECRClient(region).getAuthorizationToken()).authorizationData?.[0];if(!token?.authorizationToken)throw Error("No authorization token received from ECR");const decoded=Buffer.from(token.authorizationToken,"base64").toString("utf-8"),colonIndex=decoded.indexOf(":");if(colonIndex===-1)throw Error("ECR authorization token has unexpected format (missing colon separator)");const password=decoded.slice(colonIndex+1),loginResult=Bun.spawnSync(["docker","login","--username","AWS","--password-stdin",`${accountId}.dkr.ecr.${region}.amazonaws.com`],{stdin:new TextEncoder().encode(password),stdout:"pipe",stderr:"pipe"});if(loginResult.exitCode!==0){const loginError=new TextDecoder().decode(loginResult.stderr);throw Error(`Docker login failed: ${loginError}`)}authSpinner.succeed("Authenticated to ECR")}catch(error){authSpinner.fail("ECR authentication failed");if(isVerbose)log.debug(`ECR auth error: ${error.message}`);throw error}console.log("");const pushSpinner=spinner("Pushing image to ECR...");pushSpinner.start();try{const{exec}=await import("node:child_process"),{promisify}=await import("node:util"),execAsync=promisify(exec),pushCmd=`docker push ${imageTag}`;await execAsync(pushCmd,{env:process.env});pushSpinner.succeed(`Image pushed: ${imageTag}`)}catch(error){pushSpinner.fail("Docker push failed");if(isVerbose)log.debug(`Push error: ${error.message}`);throw error}console.log("");console.log("Container image ready in ECR. CloudFormation will use this image.");console.log("")}else{console.log("");console.log("Server deployment mode detected");console.log("Deploying EC2 infrastructure via CloudFormation...");console.log("")}async function getAwsAccountId(region){try{const{STSClient}=await import("@stacksjs/ts-cloud"),accountId=(await new STSClient(region).getCallerIdentity()).Account||process.env.AWS_ACCOUNT_ID||"";if(isVerbose)log.debug(`Retrieved AWS Account ID: ${accountId||"(empty)"}`);return accountId}catch(error){if(isVerbose)log.debug(`Failed to get AWS Account ID: ${error.message}`);return process.env.AWS_ACCOUNT_ID||""}}try{const deployScript=await import(p.projectPath("cloud/deploy-script"));if(typeof deployScript.beforeDeploy==="function")await deployScript.beforeDeploy({environment,region})}catch(hookError){if(hookError.code==="ERR_MODULE_NOT_FOUND"||hookError.code==="MODULE_NOT_FOUND"){if(isVerbose)log.debug("No beforeDeploy hook found (cloud/deploy-script not found)")}else{console.warn(`\u26A0 beforeDeploy hook failed: ${hookError.message}`);if(isVerbose)log.debug(`beforeDeploy error stack: ${hookError.stack}`)}}await deployStack({environment,region,waitForCompletion:!0,verbose:isVerbose});try{const deployScript=await import(p.projectPath("cloud/deploy-script"));if(typeof deployScript.afterDeploy==="function"){const{CloudFormationClient}=await import("@stacksjs/ts-cloud"),cf=new CloudFormationClient(region),stackName=cloudStackName;let stackOutputs={};try{stackOutputs=await cf.getStackOutputs(stackName)}catch(e){if(isVerbose)log.debug(`Failed to get stack outputs: ${e instanceof Error?e.message:String(e)}`)}await deployScript.afterDeploy({environment,region,outputs:stackOutputs})}}catch(hookError){if(hookError.code==="ERR_MODULE_NOT_FOUND"||hookError.code==="MODULE_NOT_FOUND"){if(isVerbose)log.debug("No afterDeploy hook found (cloud/deploy-script not found)")}else{console.warn(`\u26A0 afterDeploy hook failed: ${hookError.message}`);if(isVerbose)log.debug(`afterDeploy error stack: ${hookError.stack}`)}}const migrateSpinner=spinner("Running database migrations...");migrateSpinner.start();try{const{generateMigrations,runDatabaseMigration}=await import("@stacksjs/database");await generateMigrations();await runDatabaseMigration();migrateSpinner.succeed("Database migrations completed")}catch(migrationError){migrateSpinner.stop();console.log(`\u26A0 Database migrations skipped: ${migrationError.message}`);if(isVerbose)log.debug(`Migration error: ${migrationError.stack}`)}const frameworkTablesSpinner=spinner("Ensuring framework tables (auth, notifications, RBAC, traits)...");frameworkTablesSpinner.start();try{const{ensureUtcDatetimeColumns,migrateAuthTables,migrateNotificationTables,migrateRbacTables,migrateTraitTables}=await import("@stacksjs/database"),failures=[],steps=[["auth",migrateAuthTables],["notification",migrateNotificationTables],["RBAC",migrateRbacTables],["trait",migrateTraitTables],["utc-datetime",ensureUtcDatetimeColumns]];for(const[name,migrateTables]of steps){const result=await migrateTables({verbose:isVerbose});if(!result.success)failures.push(`${name}: ${result.error}`)}if(failures.length>0){frameworkTablesSpinner.stop();console.log(`\u26A0 Some framework tables could not be migrated: ${failures.join("; ")}`)}else frameworkTablesSpinner.succeed("Framework tables ensured (auth, notifications, RBAC, traits)")}catch(frameworkTablesError){frameworkTablesSpinner.stop();console.log(`\u26A0 Framework table migrations skipped: ${frameworkTablesError.message}`);if(isVerbose)log.debug(`Framework table migration error: ${frameworkTablesError.stack}`)}if(deploymentMode==="server"){const serverOutputSpinner=spinner("Retrieving server instance details...");serverOutputSpinner.start();try{const{CloudFormationClient}=await import("@stacksjs/ts-cloud"),cf=new CloudFormationClient(region),stackName=cloudStackName,outputs=await cf.getStackOutputs(stackName);serverOutputSpinner.succeed("Server instances deployed");console.log("");console.log("Server instances:");for(const[key,value]of Object.entries(outputs)){if(key.endsWith("PublicIp"))console.log(` ${key}: ${value}`);if(key.endsWith("InstanceId"))console.log(` ${key}: ${value}`)}console.log("")}catch(outputError){serverOutputSpinner.stop();console.log(`\u26A0 Could not retrieve server details: ${outputError.message}`);if(isVerbose)log.debug(`Output retrieval error: ${outputError.stack}`)}const serverDeploySpinner=spinner("Deploying API server to EC2...");serverDeploySpinner.start();try{const{S3Client,CloudFormationClient,AWSClient}=await import("@stacksjs/ts-cloud"),{readFileSync:readServerFile,existsSync:serverFileExists}=await import("node:fs"),{resolve}=await import("node:path"),s3=new S3Client(region),cf=new CloudFormationClient(region),awsClient=new AWSClient,stackName=cloudStackName,outputs=await cf.getStackOutputs(stackName),bucketName=outputs.FrontendBucketName,apiServerPort=Number(config.ports?.api||3008);let instanceId;for(const[key,value]of Object.entries(outputs))if(key.endsWith("InstanceId")&&typeof value==="string"){instanceId=value;break}let securityGroupId;if(instanceId){const{EC2Client}=await import("@stacksjs/ts-cloud"),ec2=new EC2Client(region);securityGroupId=(await ec2.describeInstances({Filters:[{Name:"instance-id",Values:[instanceId]}]}))?.Reservations?.[0]?.Instances?.[0]?.SecurityGroups?.[0]?.GroupId;await ensureSecurityGroupPort(ec2,securityGroupId,apiServerPort)}if(!instanceId||!bucketName){serverDeploySpinner.stop();if(!instanceId)console.log("\u26A0 No EC2 instance found in stack outputs, skipping server deploy");if(!bucketName)console.log("\u26A0 No S3 bucket found for staging server artifacts")}else{const publicDistributionId=outputs.publicCloudFrontDistributionId||outputs.CloudFrontDistributionId;await ensureCloudFrontApiOriginPort(awsClient,publicDistributionId,apiServerPort);const tsCloudDistPath=resolve(p.projectPath("node_modules/@stacksjs/ts-cloud/dist/index.js"));if(serverFileExists(tsCloudDistPath)){const tsCloudDist=readServerFile(tsCloudDistPath);await withS3Retry(()=>s3.putObject({bucket:bucketName,key:"_deploy/ts-cloud-dist.js",body:tsCloudDist,contentType:"application/javascript"}),"upload ts-cloud dist");if(isVerbose)log.debug(" Uploaded ts-cloud dist to S3")}const serverCode=`import { Database } from "bun:sqlite";
|
|
12
12
|
import { SESClient } from "./ts-cloud-dist.js";
|
|
13
13
|
|
|
14
14
|
const db = new Database("/var/www/api/stacks.db");
|
|
@@ -146,7 +146,7 @@ Environment=NODE_ENV=production
|
|
|
146
146
|
WantedBy=multi-user.target
|
|
147
147
|
SERVICEFILE
|
|
148
148
|
systemctl daemon-reload
|
|
149
|
-
systemctl enable stacks-api`,"systemctl reset-failed stacks-api || true","systemctl restart stacks-api",`for i in $(seq 1 20); do curl -fsS http://127.0.0.1:${apiServerPort}/api/health && break; sleep 1; done`,`curl -fsS http://127.0.0.1:${apiServerPort}/api/health`,`echo "API server deployed and restarted on port ${apiServerPort}"`].join(" && "),commandId=(await awsClient.request({service:"ssm",region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"AmazonSSM.SendCommand"},body:JSON.stringify({InstanceIds:[instanceId],DocumentName:"AWS-RunShellScript",Parameters:{commands:[ssmCommand]},TimeoutSeconds:120})}))?.Command?.CommandId;if(commandId){let attempts=0;while(attempts<30){await new Promise((resolve)=>setTimeout(resolve,3000));try{const invocation=await awsClient.request({service:"ssm",region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"AmazonSSM.GetCommandInvocation"},body:JSON.stringify({CommandId:commandId,InstanceId:instanceId})}),status=invocation?.Status;if(status==="Success"){serverDeploySpinner.succeed("API server deployed to EC2");break}else if(status==="Failed"||status==="Cancelled"||status==="TimedOut"){const errOutput=invocation?.StandardErrorContent||"Unknown error";serverDeploySpinner.fail(`API server deploy failed: ${errOutput}`);break}}catch{}attempts++}if(attempts>=30)serverDeploySpinner.fail("API server deploy timed out waiting for SSM command")}else serverDeploySpinner.fail("Failed to send SSM command");try{await s3.deleteObject(bucketName,"_deploy/ts-cloud-dist.js");await s3.deleteObject(bucketName,"_deploy/server.ts")}catch{}}}catch(serverDeployError){serverDeploySpinner.fail(`API server deployment failed: ${serverDeployError.message}`);if(isVerbose)log.debug(`Server deploy error: ${serverDeployError.stack}`)}const emailConfig=config.email;if(emailConfig?.server?.enabled){const mailServerMode=emailConfig?.server?.mode||"server",smtpSpinner=spinner(`Deploying mail server (${mailServerMode} mode) to EC2...`);smtpSpinner.start();try{const{S3Client,AWSClient,EC2Client}=await import("@stacksjs/ts-cloud"),{readFileSync:readSmtpFile,existsSync:smtpFileExists}=await import("node:fs"),{resolve:resolvePath,join:joinPath}=await import("node:path"),{execSync}=await import("node:child_process"),s3=new S3Client(region),awsClient=new AWSClient,ec2=new EC2Client(region),stackName
|
|
149
|
+
systemctl enable stacks-api`,"systemctl reset-failed stacks-api || true","systemctl restart stacks-api",`for i in $(seq 1 20); do curl -fsS http://127.0.0.1:${apiServerPort}/api/health && break; sleep 1; done`,`curl -fsS http://127.0.0.1:${apiServerPort}/api/health`,`echo "API server deployed and restarted on port ${apiServerPort}"`].join(" && "),commandId=(await awsClient.request({service:"ssm",region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"AmazonSSM.SendCommand"},body:JSON.stringify({InstanceIds:[instanceId],DocumentName:"AWS-RunShellScript",Parameters:{commands:[ssmCommand]},TimeoutSeconds:120})}))?.Command?.CommandId;if(commandId){let attempts=0;while(attempts<30){await new Promise((resolve)=>setTimeout(resolve,3000));try{const invocation=await awsClient.request({service:"ssm",region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"AmazonSSM.GetCommandInvocation"},body:JSON.stringify({CommandId:commandId,InstanceId:instanceId})}),status=invocation?.Status;if(status==="Success"){serverDeploySpinner.succeed("API server deployed to EC2");break}else if(status==="Failed"||status==="Cancelled"||status==="TimedOut"){const errOutput=invocation?.StandardErrorContent||"Unknown error";serverDeploySpinner.fail(`API server deploy failed: ${errOutput}`);break}}catch{}attempts++}if(attempts>=30)serverDeploySpinner.fail("API server deploy timed out waiting for SSM command")}else serverDeploySpinner.fail("Failed to send SSM command");try{await s3.deleteObject(bucketName,"_deploy/ts-cloud-dist.js");await s3.deleteObject(bucketName,"_deploy/server.ts")}catch{}}}catch(serverDeployError){serverDeploySpinner.fail(`API server deployment failed: ${serverDeployError.message}`);if(isVerbose)log.debug(`Server deploy error: ${serverDeployError.stack}`)}const emailConfig=config.email;if(emailConfig?.server?.enabled){const mailServerMode=emailConfig?.server?.mode||"server",smtpSpinner=spinner(`Deploying mail server (${mailServerMode} mode) to EC2...`);smtpSpinner.start();try{const{S3Client,AWSClient,EC2Client}=await import("@stacksjs/ts-cloud"),{readFileSync:readSmtpFile,existsSync:smtpFileExists}=await import("node:fs"),{resolve:resolvePath,join:joinPath}=await import("node:path"),{execSync}=await import("node:child_process"),s3=new S3Client(region),awsClient=new AWSClient,ec2=new EC2Client(region),stackName=cloudStackName;let smtpInstanceId,smtpBucketName,emailBucketName,securityGroupId;try{const{AWSCloudFormationClient:CfnClient}=await import("@stacksjs/ts-cloud"),cfnOutputs=await new CfnClient(region).getStackOutputs(stackName);for(const[key,value]of Object.entries(cfnOutputs)){if(key.endsWith("InstanceId")&&typeof value==="string")smtpInstanceId=value;if(key==="FrontendBucketName"&&typeof value==="string")smtpBucketName=value;if(key==="emailBucketName"&&typeof value==="string")emailBucketName=value}}catch{}if(!emailBucketName)emailBucketName=`${projectName}-production-s3-email`;if(smtpInstanceId&&smtpBucketName){const mailPorts=[25,80,110,143,465,587,993,995];try{const sgs=(await ec2.describeInstances({Filters:[{Name:"instance-id",Values:[smtpInstanceId]}]}))?.Reservations?.[0]?.Instances?.[0]?.SecurityGroups;if(sgs?.[0]?.GroupId)securityGroupId=sgs[0].GroupId}catch{if(isVerbose)log.debug("Could not get security group for instance")}if(securityGroupId)for(const port of mailPorts)try{await ec2.authorizeSecurityGroupIngress({GroupId:securityGroupId,IpPermissions:[{IpProtocol:"tcp",FromPort:port,ToPort:port,IpRanges:[{CidrIp:"0.0.0.0/0",Description:`Mail port ${port}`}]}]});if(isVerbose)log.debug(` Opened port ${port} on security group ${securityGroupId}`)}catch(e){if(!e.message?.includes("already exists")){if(isVerbose)log.debug(` Port ${port}: ${e.message}`)}}const domain=emailConfig.domain||"stacksjs.com",mailSubdomain=emailConfig?.server?.subdomain||"mail";if(mailServerMode==="server"){if(isVerbose)log.debug("Deploying Zig mail server binary...");try{await installMailBinaryWithPantry()}catch(error){if(isVerbose)log.debug(` Pantry mail install failed: ${error.message}`)}const linuxBinaryPath=await findPantryMailBinary();if(linuxBinaryPath&&smtpFileExists(linuxBinaryPath)){if(!await isElfBinary(linuxBinaryPath)){smtpSpinner.fail(`Pantry installed ${MAIL_PACKAGE_DOMAIN}, but the ${MAIL_TARGET_PLATFORM} binary is not an ELF file.`);throw Error("Linux binary is not a valid ELF file")}const binaryContent=readSmtpFile(linuxBinaryPath);await s3.putObject({bucket:emailBucketName,key:"mail-server/smtp-server",body:binaryContent,contentType:"application/octet-stream"});if(isVerbose)log.debug(` Uploaded Zig binary (${(binaryContent.length/1024/1024).toFixed(1)}MB) to S3`);const zigSsmCommand=["systemctl stop stacks-mail 2>/dev/null || true","systemctl disable stacks-mail 2>/dev/null || true","systemctl stop stacks-smtp 2>/dev/null || true","systemctl disable stacks-smtp 2>/dev/null || true","systemctl stop smtp-server 2>/dev/null || true","mkdir -p /opt/smtp-server /var/lib/smtp-server /var/log/smtp-server /var/spool/mail /etc/smtp-server /var/lib/smtp-server/backups",`aws s3 cp s3://${emailBucketName}/mail-server/smtp-server /opt/smtp-server/smtp-server --region ${region}`,"chmod +x /opt/smtp-server/smtp-server",'file /opt/smtp-server/smtp-server | grep -q ELF || { echo "Binary is not ELF"; exit 1; }',firewallOpenCommand(mailPorts),`cat > /etc/smtp-server/smtp-server.env << 'ENVEOF'
|
|
150
150
|
SMTP_PROFILE=production
|
|
151
151
|
SMTP_HOST=0.0.0.0
|
|
152
152
|
SMTP_PORT=25
|
|
@@ -212,7 +212,7 @@ Environment=AWS_REGION=${region}
|
|
|
212
212
|
${envLines}
|
|
213
213
|
[Install]
|
|
214
214
|
WantedBy=multi-user.target
|
|
215
|
-
SERVICEFILE`,"systemctl daemon-reload","systemctl enable stacks-smtp","systemctl restart stacks-smtp"].join(" && "),cmdId=(await awsClient.request({service:"ssm",region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"AmazonSSM.SendCommand"},body:JSON.stringify({InstanceIds:[smtpInstanceId],DocumentName:"AWS-RunShellScript",Parameters:{commands:[smtpSsmCommand]},TimeoutSeconds:180})}))?.Command?.CommandId;if(cmdId){let ssmAttempts=0;while(ssmAttempts<60){await new Promise((resolve)=>setTimeout(resolve,3000));try{const invocation=await awsClient.request({service:"ssm",region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"AmazonSSM.GetCommandInvocation"},body:JSON.stringify({CommandId:cmdId,InstanceId:smtpInstanceId})}),status=invocation?.Status;if(status==="Success"){smtpSpinner.succeed("SMTP proxy deployed to EC2");break}else if(status==="Failed"||status==="Cancelled"||status==="TimedOut"){smtpSpinner.fail(`SMTP proxy deploy failed: ${invocation?.StandardErrorContent||"Unknown"}`);break}}catch{}ssmAttempts++}if(ssmAttempts>=60)smtpSpinner.fail("SMTP proxy deploy timed out")}else smtpSpinner.fail("Failed to send SSM command for SMTP proxy");try{await s3.deleteObject(smtpBucketName,"_deploy/smtp-server.js");await s3.deleteObject(smtpBucketName,"_deploy/smtp-entry.ts")}catch{}}else{smtpSpinner.stop();if(isVerbose)log.debug("SMTP server bundle not found, skipping")}}}else{smtpSpinner.stop();if(isVerbose)log.debug("No EC2 instance or bucket found, skipping mail server deploy")}}catch(smtpDeployError){smtpSpinner.fail(`Mail server deployment failed: ${smtpDeployError.message}`);if(isVerbose)log.debug(`Mail server deploy error: ${smtpDeployError.stack}`)}}}const frontendSpinner=spinner("Deploying frontend to S3...");frontendSpinner.start();try{const{S3Client,CloudFormationClient}=await import("@stacksjs/ts-cloud"),{readFileSync}=await import("node:fs"),{buildFrontendStatic}=await import("../build/frontend-static"),s3=new S3Client(region),cf=new CloudFormationClient(region),stackName
|
|
215
|
+
SERVICEFILE`,"systemctl daemon-reload","systemctl enable stacks-smtp","systemctl restart stacks-smtp"].join(" && "),cmdId=(await awsClient.request({service:"ssm",region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"AmazonSSM.SendCommand"},body:JSON.stringify({InstanceIds:[smtpInstanceId],DocumentName:"AWS-RunShellScript",Parameters:{commands:[smtpSsmCommand]},TimeoutSeconds:180})}))?.Command?.CommandId;if(cmdId){let ssmAttempts=0;while(ssmAttempts<60){await new Promise((resolve)=>setTimeout(resolve,3000));try{const invocation=await awsClient.request({service:"ssm",region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"AmazonSSM.GetCommandInvocation"},body:JSON.stringify({CommandId:cmdId,InstanceId:smtpInstanceId})}),status=invocation?.Status;if(status==="Success"){smtpSpinner.succeed("SMTP proxy deployed to EC2");break}else if(status==="Failed"||status==="Cancelled"||status==="TimedOut"){smtpSpinner.fail(`SMTP proxy deploy failed: ${invocation?.StandardErrorContent||"Unknown"}`);break}}catch{}ssmAttempts++}if(ssmAttempts>=60)smtpSpinner.fail("SMTP proxy deploy timed out")}else smtpSpinner.fail("Failed to send SSM command for SMTP proxy");try{await s3.deleteObject(smtpBucketName,"_deploy/smtp-server.js");await s3.deleteObject(smtpBucketName,"_deploy/smtp-entry.ts")}catch{}}else{smtpSpinner.stop();if(isVerbose)log.debug("SMTP server bundle not found, skipping")}}}else{smtpSpinner.stop();if(isVerbose)log.debug("No EC2 instance or bucket found, skipping mail server deploy")}}catch(smtpDeployError){smtpSpinner.fail(`Mail server deployment failed: ${smtpDeployError.message}`);if(isVerbose)log.debug(`Mail server deploy error: ${smtpDeployError.stack}`)}}}const frontendSpinner=spinner("Deploying frontend to S3...");frontendSpinner.start();try{const{S3Client,CloudFormationClient}=await import("@stacksjs/ts-cloud"),{readFileSync}=await import("node:fs"),{buildFrontendStatic}=await import("../build/frontend-static"),s3=new S3Client(region),cf=new CloudFormationClient(region),stackName=cloudStackName,stackOutputs=await cf.getStackOutputs(stackName),bucketName=stackOutputs.FrontendBucketName;if(!bucketName){frontendSpinner.stop();console.log("\u26A0 Frontend bucket not found in stack outputs (add storage.public to infrastructure config)")}else{const buildDir=await buildFrontendStatic();await(async(dir,_prefix="")=>{await traverseDirectory(dir,async(filePath,key)=>{const content=readFileSync(filePath),contentType=getMimeType(filePath),cacheControl=key==="index.html"||key.endsWith("/index.html")?"no-cache, no-store, must-revalidate":"public, max-age=31536000, immutable";await withS3Retry(()=>s3.putObject({bucket:bucketName,key,body:content,contentType,cacheControl}),`upload ${key}`);if(isVerbose)log.debug(` Uploaded: ${key}`)})})(buildDir);const bootstrapPath=p.projectPath("bootstrap");if(existsSync(bootstrapPath)){const bootstrapContent=readFileSync(bootstrapPath);await withS3Retry(()=>s3.putObject({bucket:bucketName,key:"install",body:bootstrapContent,contentType:"text/plain",cacheControl:"no-cache, no-store, must-revalidate"}),"upload bootstrap install script");if(isVerbose)log.debug(" Uploaded bootstrap install script")}const distributionId=stackOutputs.publicCloudFrontDistributionId||stackOutputs.CloudFrontDistributionId;if(distributionId){if(isVerbose)log.debug(" Invalidating CloudFront cache...");const{AWSClient}=await import("@stacksjs/ts-cloud");await new AWSClient().request({service:"cloudfront",region:"us-east-1",method:"POST",path:`/2020-05-31/distribution/${distributionId}/invalidation`,headers:{"Content-Type":"application/xml"},body:`<?xml version="1.0" encoding="UTF-8"?>
|
|
216
216
|
<InvalidationBatch xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
|
|
217
217
|
<CallerReference>${Date.now()}</CallerReference>
|
|
218
218
|
<Paths>
|
|
@@ -221,7 +221,7 @@ SERVICEFILE`,"systemctl daemon-reload","systemctl enable stacks-smtp","systemctl
|
|
|
221
221
|
<Path>/*</Path>
|
|
222
222
|
</Items>
|
|
223
223
|
</Paths>
|
|
224
|
-
</InvalidationBatch>`})}frontendSpinner.succeed(`Frontend deployed to S3 (${bucketName})`)}}catch(frontendError){frontendSpinner.fail(`Frontend deployment failed: ${frontendError.message}`);if(isVerbose)log.debug(`Frontend error: ${frontendError.stack}`)}const docsDistPath=p.projectPath("dist/docs/.bunpress"),{existsSync:docsExists}=await import("node:fs");if(docsExists(docsDistPath)){const docsDeploySpinner=spinner("Deploying documentation to S3...");docsDeploySpinner.start();try{const{S3Client,CloudFormationClient}=await import("@stacksjs/ts-cloud"),{readFileSync}=await import("node:fs"),s3=new S3Client(region),cf=new CloudFormationClient(region),stackName
|
|
224
|
+
</InvalidationBatch>`})}frontendSpinner.succeed(`Frontend deployed to S3 (${bucketName})`)}}catch(frontendError){frontendSpinner.fail(`Frontend deployment failed: ${frontendError.message}`);if(isVerbose)log.debug(`Frontend error: ${frontendError.stack}`)}const docsDistPath=p.projectPath("dist/docs/.bunpress"),{existsSync:docsExists}=await import("node:fs");if(docsExists(docsDistPath)){const docsDeploySpinner=spinner("Deploying documentation to S3...");docsDeploySpinner.start();try{const{S3Client,CloudFormationClient}=await import("@stacksjs/ts-cloud"),{readFileSync}=await import("node:fs"),s3=new S3Client(region),cf=new CloudFormationClient(region),stackName=cloudStackName,docsOutputs=await cf.getStackOutputs(stackName),docsBucketName=docsOutputs.DocsBucketName;if(!docsBucketName){docsDeploySpinner.stop();console.log("\u26A0 Docs bucket not found in stack outputs (infrastructure may not be updated yet)")}else{await(async(dir,_prefix="")=>{await traverseDirectory(dir,async(filePath,key)=>{const content=readFileSync(filePath),contentType=getMimeType(filePath),cacheControl=key.endsWith(".html")?"no-cache, no-store, must-revalidate":"public, max-age=31536000, immutable";await withS3Retry(()=>s3.putObject({bucket:docsBucketName,key,body:content,contentType,cacheControl}),`upload docs ${key}`);if(isVerbose)log.debug(` Uploaded docs: ${key}`)},"",[".DS_Store",".bunpress"])})(docsDistPath);const docsDistributionId=docsOutputs.docsCloudFrontDistributionId||docsOutputs.publicCloudFrontDistributionId||docsOutputs.CloudFrontDistributionId;if(docsDistributionId){if(isVerbose)log.debug(" Invalidating CloudFront cache for docs...");const{AWSClient}=await import("@stacksjs/ts-cloud"),client=new AWSClient,docsInvalidationPaths=docsOutputs.docsCloudFrontDistributionId?["/*"]:["/docs","/docs/*"];await client.request({service:"cloudfront",region:"us-east-1",method:"POST",path:`/2020-05-31/distribution/${docsDistributionId}/invalidation`,headers:{"Content-Type":"application/xml"},body:`<?xml version="1.0" encoding="UTF-8"?>
|
|
225
225
|
<InvalidationBatch xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
|
|
226
226
|
<CallerReference>docs-${Date.now()}</CallerReference>
|
|
227
227
|
<Paths>
|
|
@@ -231,7 +231,7 @@ SERVICEFILE`,"systemctl daemon-reload","systemctl enable stacks-smtp","systemctl
|
|
|
231
231
|
`)}
|
|
232
232
|
</Items>
|
|
233
233
|
</Paths>
|
|
234
|
-
</InvalidationBatch>`})}docsDeploySpinner.succeed(`Documentation deployed to S3 (${docsBucketName})`)}}catch(docsDeployError){docsDeploySpinner.fail(`Documentation deployment failed: ${docsDeployError.message}`);if(isVerbose)log.debug(`Docs deploy error: ${docsDeployError.stack}`)}}else if(isVerbose)log.debug("No docs build found at dist/docs, skipping docs deployment");const blogDistPath=p.projectPath("dist/blog"),{existsSync:blogExists}=await import("node:fs");if(blogExists(blogDistPath)){const blogDeploySpinner=spinner("Deploying blog to S3...");blogDeploySpinner.start();try{const{S3Client:BlogS3Client,CloudFormationClient:BlogCFClient}=await import("@stacksjs/ts-cloud"),{readFileSync:readBlogFile}=await import("node:fs"),blogS3=new BlogS3Client(region),blogCf=new BlogCFClient(region),stackName
|
|
234
|
+
</InvalidationBatch>`})}docsDeploySpinner.succeed(`Documentation deployed to S3 (${docsBucketName})`)}}catch(docsDeployError){docsDeploySpinner.fail(`Documentation deployment failed: ${docsDeployError.message}`);if(isVerbose)log.debug(`Docs deploy error: ${docsDeployError.stack}`)}}else if(isVerbose)log.debug("No docs build found at dist/docs, skipping docs deployment");const blogDistPath=p.projectPath("dist/blog"),{existsSync:blogExists}=await import("node:fs");if(blogExists(blogDistPath)){const blogDeploySpinner=spinner("Deploying blog to S3...");blogDeploySpinner.start();try{const{S3Client:BlogS3Client,CloudFormationClient:BlogCFClient}=await import("@stacksjs/ts-cloud"),{readFileSync:readBlogFile}=await import("node:fs"),blogS3=new BlogS3Client(region),blogCf=new BlogCFClient(region),stackName=cloudStackName,outputs=await blogCf.getStackOutputs(stackName),blogBucketName=outputs.BlogBucketName;if(!blogBucketName){blogDeploySpinner.stop();console.log("\u26A0 Blog bucket not found in stack outputs")}else{await traverseDirectory(blogDistPath,async(filePath,key)=>{const content=readBlogFile(filePath),contentType=getMimeType(filePath),cacheControl=key.endsWith(".html")?"no-cache, no-store, must-revalidate":"public, max-age=31536000, immutable";await withS3Retry(()=>blogS3.putObject({bucket:blogBucketName,key,body:content,contentType,cacheControl}),`upload blog ${key}`);if(isVerbose)log.debug(` Uploaded blog: ${key}`)},"",[".DS_Store"]);const blogDistributionId=outputs.blogCloudFrontDistributionId||outputs.publicCloudFrontDistributionId||outputs.CloudFrontDistributionId;if(blogDistributionId){if(isVerbose)log.debug(" Invalidating CloudFront cache for blog...");const{AWSClient:BlogAWSClient}=await import("@stacksjs/ts-cloud"),blogClient=new BlogAWSClient,blogInvalidationPaths=outputs.blogCloudFrontDistributionId?["/*"]:["/blog","/blog/*"];await blogClient.request({service:"cloudfront",region:"us-east-1",method:"POST",path:`/2020-05-31/distribution/${blogDistributionId}/invalidation`,headers:{"Content-Type":"application/xml"},body:`<?xml version="1.0" encoding="UTF-8"?>
|
|
235
235
|
<InvalidationBatch xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
|
|
236
236
|
<CallerReference>blog-${Date.now()}</CallerReference>
|
|
237
237
|
<Paths>
|
|
@@ -241,7 +241,7 @@ SERVICEFILE`,"systemctl daemon-reload","systemctl enable stacks-smtp","systemctl
|
|
|
241
241
|
`)}
|
|
242
242
|
</Items>
|
|
243
243
|
</Paths>
|
|
244
|
-
</InvalidationBatch>`})}blogDeploySpinner.succeed(`Blog deployed to S3 (${blogBucketName})`)}}catch(blogDeployError){blogDeploySpinner.fail(`Blog deployment failed: ${blogDeployError.message}`);if(isVerbose)log.debug(`Blog deploy error: ${blogDeployError.stack}`)}}else if(isVerbose)log.debug("No blog build found at dist/blog, skipping blog deployment");const errorPageSpinner=spinner("Configuring 404 error page...");errorPageSpinner.start();try{const{S3Client,CloudFormationClient,AWSClient}=await import("@stacksjs/ts-cloud"),{existsSync:exists404,readFileSync:read404}=await import("node:fs"),s3=new S3Client(region),cf=new CloudFormationClient(region),awsClient=new AWSClient,stackName
|
|
244
|
+
</InvalidationBatch>`})}blogDeploySpinner.succeed(`Blog deployed to S3 (${blogBucketName})`)}}catch(blogDeployError){blogDeploySpinner.fail(`Blog deployment failed: ${blogDeployError.message}`);if(isVerbose)log.debug(`Blog deploy error: ${blogDeployError.stack}`)}}else if(isVerbose)log.debug("No blog build found at dist/blog, skipping blog deployment");const errorPageSpinner=spinner("Configuring 404 error page...");errorPageSpinner.start();try{const{S3Client,CloudFormationClient,AWSClient}=await import("@stacksjs/ts-cloud"),{existsSync:exists404,readFileSync:read404}=await import("node:fs"),s3=new S3Client(region),cf=new CloudFormationClient(region),awsClient=new AWSClient,stackName=cloudStackName,outputs=await cf.getStackOutputs(stackName),{FrontendBucketName:frontendBucket,DocsBucketName:docsBucket}=outputs,distributionId=outputs.publicCloudFrontDistributionId||outputs.CloudFrontDistributionId,docs404Path=p.projectPath("dist/docs/.bunpress/404.html");let html404Content;if(exists404(docs404Path)){html404Content=read404(docs404Path,"utf-8");if(isVerbose)log.debug(" Using BunPress-generated 404.html")}else{html404Content=`<!DOCTYPE html>
|
|
245
245
|
<html lang="en">
|
|
246
246
|
<head>
|
|
247
247
|
<meta charset="UTF-8">
|
|
@@ -296,4 +296,4 @@ ${children}${indent}</${name}>
|
|
|
296
296
|
`}return""},xml=`<?xml version="1.0" encoding="UTF-8"?>
|
|
297
297
|
<DistributionConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
|
|
298
298
|
${Object.entries(currentConfig).filter(([key])=>!key.startsWith("@_")).map(([key,val])=>buildXmlElement(key,val," ")).join("")}</DistributionConfig>
|
|
299
|
-
`;await awsClient.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${distributionId}/config`,body:xml,headers:{"Content-Type":"application/xml","If-Match":etag}});if(isVerbose)log.debug(" CloudFront custom error responses configured")}else if(isVerbose)log.debug(" CloudFront custom error responses already configured")}}errorPageSpinner.succeed("404 error page configured")}catch(errorPageError){errorPageSpinner.stop();console.log(`\u26A0 404 page configuration skipped: ${errorPageError.message}`);if(isVerbose)log.debug(`Error page config error: ${errorPageError.stack}`)}try{const tunnelCloudConfig=await import(p.projectPath("config/cloud")),tunnelConfig=tunnelCloudConfig?.tsCloud?.infrastructure?.tunnel;if(tunnelConfig?.enabled){const tunnelDomain=tunnelConfig.domain||"";if(!tunnelDomain||tunnelDomain==="localtunnel.dev"||tunnelDomain==="api.localtunnel.dev")console.log("\u2139 Tunnel: Using shared localtunnel.dev (no custom tunnel deployment needed)");else{const tunnelSpinner=spinner(`Deploying tunnel server to ${tunnelDomain}...`);tunnelSpinner.start();try{const{deployTunnelServer}=await import("@stacksjs/tunnel");await deployTunnelServer({domain:tunnelDomain,region:tunnelConfig.region||tunnelCloudConfig?.tsCloud?.project?.region||"us-east-1",instanceType:tunnelConfig.instanceType,prefix:tunnelConfig.prefix,enableSsl:tunnelConfig.ssl?.enabled,porkbunApiKey:tunnelConfig.ssl?.porkbunApiKey,porkbunSecretKey:tunnelConfig.ssl?.porkbunSecretKey,verbose:isVerbose});tunnelSpinner.succeed(`Tunnel server deployed to ${tunnelDomain}`)}catch(tunnelError){tunnelSpinner.stop();console.log(`\u26A0 Tunnel deployment skipped: ${tunnelError.message}`);if(isVerbose)log.debug(`Tunnel deploy error: ${tunnelError.stack}`)}}}}catch{}const dnsSpinner=spinner("Reconciling DNS records...");dnsSpinner.start();try{const{Route53Client,CloudFormationClient:DnsCfClient}=await import("@stacksjs/ts-cloud"),dnsCf=new DnsCfClient(region),dnsStackName
|
|
299
|
+
`;await awsClient.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${distributionId}/config`,body:xml,headers:{"Content-Type":"application/xml","If-Match":etag}});if(isVerbose)log.debug(" CloudFront custom error responses configured")}else if(isVerbose)log.debug(" CloudFront custom error responses already configured")}}errorPageSpinner.succeed("404 error page configured")}catch(errorPageError){errorPageSpinner.stop();console.log(`\u26A0 404 page configuration skipped: ${errorPageError.message}`);if(isVerbose)log.debug(`Error page config error: ${errorPageError.stack}`)}try{const tunnelCloudConfig=await import(p.projectPath("config/cloud")),tunnelConfig=tunnelCloudConfig?.tsCloud?.infrastructure?.tunnel;if(tunnelConfig?.enabled){const tunnelDomain=tunnelConfig.domain||"";if(!tunnelDomain||tunnelDomain==="localtunnel.dev"||tunnelDomain==="api.localtunnel.dev")console.log("\u2139 Tunnel: Using shared localtunnel.dev (no custom tunnel deployment needed)");else{const tunnelSpinner=spinner(`Deploying tunnel server to ${tunnelDomain}...`);tunnelSpinner.start();try{const{deployTunnelServer}=await import("@stacksjs/tunnel");await deployTunnelServer({domain:tunnelDomain,region:tunnelConfig.region||tunnelCloudConfig?.tsCloud?.project?.region||"us-east-1",instanceType:tunnelConfig.instanceType,prefix:tunnelConfig.prefix,enableSsl:tunnelConfig.ssl?.enabled,porkbunApiKey:tunnelConfig.ssl?.porkbunApiKey,porkbunSecretKey:tunnelConfig.ssl?.porkbunSecretKey,verbose:isVerbose});tunnelSpinner.succeed(`Tunnel server deployed to ${tunnelDomain}`)}catch(tunnelError){tunnelSpinner.stop();console.log(`\u26A0 Tunnel deployment skipped: ${tunnelError.message}`);if(isVerbose)log.debug(`Tunnel deploy error: ${tunnelError.stack}`)}}}}catch{}const dnsSpinner=spinner("Reconciling DNS records...");dnsSpinner.start();try{const{Route53Client,CloudFormationClient:DnsCfClient}=await import("@stacksjs/ts-cloud"),dnsCf=new DnsCfClient(region),dnsStackName=cloudStackName,dnsOutputs=await dnsCf.getStackOutputs(dnsStackName),dnsCloudConfig=await import(p.projectPath("config/cloud")),hostedZoneId=dnsCloudConfig?.tsCloud?.infrastructure?.dns?.hostedZoneId,siteDomain=dnsCloudConfig?.tsCloud?.infrastructure?.dns?.domain||"stacksjs.com";if(hostedZoneId){const route53=new Route53Client(region),cfHostedZoneId="Z2FDTNDATAQYW2",domainMappings=[{domain:siteDomain,cfDomain:dnsOutputs.publicCloudFrontDomain},{domain:`www.${siteDomain}`,cfDomain:dnsOutputs.publicCloudFrontDomain},{domain:`docs.${siteDomain}`,cfDomain:dnsOutputs.docsCloudFrontDomain},{domain:`blog.${siteDomain}`,cfDomain:dnsOutputs.blogCloudFrontDomain}];let recordsCreated=0;for(const{domain,cfDomain}of domainMappings){if(!cfDomain)continue;try{if(!((await route53.listResourceRecordSets({HostedZoneId:hostedZoneId,StartRecordName:domain,StartRecordType:"A",MaxItems:"1"}))?.ResourceRecordSets||[]).some((r)=>r.Name===`${domain}.`&&r.Type==="A")){await route53.changeResourceRecordSets({HostedZoneId:hostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:domain,Type:"A",AliasTarget:{HostedZoneId:cfHostedZoneId,DNSName:cfDomain,EvaluateTargetHealth:!1}}},{Action:"UPSERT",ResourceRecordSet:{Name:domain,Type:"AAAA",AliasTarget:{HostedZoneId:cfHostedZoneId,DNSName:cfDomain,EvaluateTargetHealth:!1}}}]}});recordsCreated++;if(isVerbose)log.debug(` Created DNS records: ${domain} -> ${cfDomain}`)}else if(isVerbose)log.debug(` DNS record exists: ${domain}`)}catch(dnsErr){if(isVerbose)log.debug(` DNS check/create failed for ${domain}: ${dnsErr.message}`)}}if(recordsCreated>0)dnsSpinner.succeed(`DNS records reconciled (${recordsCreated} created)`);else dnsSpinner.succeed("DNS records verified")}else{dnsSpinner.stop();if(isVerbose)log.debug("No hosted zone ID configured, skipping DNS reconciliation")}}catch(dnsError){dnsSpinner.stop();console.log(`\u26A0 DNS reconciliation skipped: ${dnsError.message}`);if(isVerbose)log.debug(`DNS error: ${dnsError.stack}`)}console.log("");log.success("Deployment completed successfully!")}catch(error){log.error("Deployment failed:",error);process.exit(ExitCode.FatalError)}
|
package/dist/domains/purchase.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import process from"node:process";import{log,parseOptions}from"@stacksjs/cli";import{purchaseDomain}from"@stacksjs/cloud";import{
|
|
1
|
+
import process from"node:process";import{log,parseOptions}from"@stacksjs/cli";import{applyPurchaseFlags,purchaseDomain,purchaseOptionsFromContactInfo}from"@stacksjs/cloud";import{awaitConfig}from"@stacksjs/config";import{handleError}from"@stacksjs/error-handling";import{ExitCode}from"@stacksjs/types";const{dns}=await awaitConfig(),contactInfo=dns?.contactInfo;if(!contactInfo||Object.keys(contactInfo).length===0){handleError("You must provide contact info in config/dns.ts (`contactInfo`) to register a domain.");process.exit(ExitCode.FatalError)}const options=applyPurchaseFlags(purchaseOptionsFromContactInfo(contactInfo),parseOptions());if(!options.domain){handleError("You must provide a domain name to purchase.");process.exit(ExitCode.FatalError)}const result=await purchaseDomain(options.domain,options);if(result.isErr){handleError(result.error);process.exit(ExitCode.FatalError)}log.success(`Route 53 accepted the registration of ${options.domain} (operation ${result.value.OperationId}). It completes at AWS within minutes to hours; the registrant email receives a confirmation.`);await log.flush();process.exit(ExitCode.Success);
|
package/dist/domains/remove.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import process from"node:process";import{parseOptions}from"@stacksjs/cli";import{
|
|
1
|
+
import process from"node:process";import{parseOptions}from"@stacksjs/cli";import{deleteHostedZoneRecords}from"@stacksjs/dns";import{handleError}from"@stacksjs/error-handling";import{log}from"@stacksjs/logging";const parsedOptions=parseOptions(),options={domain:parsedOptions.domain,verbose:parsedOptions.verbose};if(!options.domain){handleError("No domain was given to remove. Run `buddy domains:remove <domain>`.");process.exit(1)}if(options.verbose)log.info(`Removing domain: ${options.domain}`);const result=await deleteHostedZoneRecords(options.domain);if(result.isErr){handleError(result.error);process.exit(1)}
|
package/dist/generate/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as fs from"node:fs";import process from"node:process";import{
|
|
1
|
+
import*as fs from"node:fs";import process from"node:process";import{Action,NpmScript}from"@stacksjs/enums";import{log}from"@stacksjs/logging";import{frameworkPath,projectPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{runNpmScript}from"@stacksjs/utils";import{runAction}from"../helpers";import{generateVsCodeCustomData as genVsCodeCustomData,generateWebTypes as genWebTypes}from"../helpers/vscode-custom-data";import{generateProjectImages}from"./images";import{generateRouteNames}from"./action-types";export{generateProjectImages}from"./images";export{generateErd,wrapForTarget}from"./erd";export{generateVSchema}from"./vschema";export async function invoke(options){if(options?.types)await generateTypes(options);else if(options?.entries)await generateLibEntries(options);else if(options?.webTypes)await generateWebTypes();else if(options?.customData)await generateVsCodeCustomData();else if(options?.ideHelpers)await generateIdeHelpers();else if(options?.componentMeta)await generateComponentMeta();else if(options?.coreSymlink)await generateCoreSymlink();else if(options?.openApiSpec)await generateOpenApiSpec();else if(options?.images)await generateProjectImages({verbose:options?.verbose});else await generateEverything(options)}async function generateEverything(options){log.info("Generating types, entry points, component meta and the OpenAPI spec...");try{const{discoverPackages}=await import("../discover-packages");await discoverPackages()}catch{}await generateTypes({...options,types:!0});await generateLibEntries({...options,entries:!0});await generateOpenApiSpec();log.success("Generated")}export function generate(options){return invoke(options)}export async function generateLibEntries(options){const result=await runAction(Action.GenerateLibraryEntries,{...options,cwd:projectPath()});if(result.isErr){await log.error("There was an error generating your library entry points",result.error);process.exit(ExitCode.FatalError)}log.success("Library entry points generated successfully")}export async function generateWebTypes(){await genWebTypes()}export async function generateVsCodeCustomData(){const result=await genVsCodeCustomData();if(result.isErr){await log.error("There was an error generating the custom-elements.json file.",result.error);process.exit(ExitCode.FatalError)}await runAction(Action.LintFix,{verbose:!0,cwd:projectPath()});log.success("Successfully generated the custom-elements.json file")}export async function generateIdeHelpers(){await genWebTypes();await genVsCodeCustomData();await runAction(Action.LintFix,{verbose:!0,cwd:projectPath()});log.success("Successfully generated IDE helpers")}export async function generateComponentMeta(){const result=await genVsCodeCustomData();if(result.isErr){await log.error("There was an error generating your component meta information.",result.error);process.exit(ExitCode.FatalError)}await runAction(Action.LintFix,{verbose:!0,cwd:projectPath()});log.success("Successfully generated component meta information")}export async function generateTypes(options){try{const{generateAutoImportFiles}=await import("@stacksjs/server");await generateAutoImportFiles()}catch(error){log.debug("[generate:types] Could not refresh the auto-import registries",{error})}await generateRouteNames();try{const previous=process.env.STACKS_CANONICAL_FEATURES;process.env.STACKS_CANONICAL_FEATURES="1";try{const{generateServerAutoImportTypes}=await import("@stacksjs/server");await generateServerAutoImportTypes()}finally{if(previous===void 0)delete process.env.STACKS_CANONICAL_FEATURES;else process.env.STACKS_CANONICAL_FEATURES=previous}}catch(error){log.debug("[generate:types] Could not refresh server auto-import declarations",{error})}const entry=frameworkPath("core/actions/src/generate/types.ts");if(!fs.existsSync(entry)){await import(`./types?t=${Date.now()}`);return}const result=await runNpmScript(NpmScript.GenerateTypes,{cwd:frameworkPath(),...options});if(result.isErr){log.error("There was an error generating your types.",result.error);throw result.error instanceof Error?result.error:Error(String(result.error))}log.success("Types were generated successfully")}export async function watchTypes(options){try{const manifestPath=`${frameworkPath()}/package.json`,text=fs.existsSync(manifestPath)?fs.readFileSync(manifestPath,"utf-8"):"";if(!(text?JSON.parse(text):{})?.scripts?.["generate:types"]){log.warn("[generate:types --watch] no `generate:types` script in framework package.json - type regeneration disabled. dev:api will keep running, but type definitions won't auto-refresh on model/config changes.");return}}catch{}const watched=[...await(async()=>{try{const{autoImportSourceDirs}=await import("@stacksjs/server");return autoImportSourceDirs()}catch{return[]}})(),projectPath("config"),projectPath("database/migrations"),projectPath("app"),projectPath("routes")].filter((dir,index,all)=>all.indexOf(dir)===index);log.info(`[generate:types --watch] watching ${watched.length} directories`);let pending=null,inflight=!1;const trigger=()=>{if(pending)clearTimeout(pending);pending=setTimeout(async()=>{if(inflight)return;inflight=!0;try{log.info("[generate:types --watch] change detected, regenerating\u2026");await generateTypes(options);log.success("[generate:types --watch] types up to date")}catch(err){log.error("[generate:types --watch] regeneration failed:",err)}finally{inflight=!1}},200)},watchers=[];for(const dir of watched)try{if(!fs.existsSync(dir))continue;const w=fs.watch(dir,{recursive:!0},()=>trigger());watchers.push(w)}catch(err){log.warn(`[generate:types --watch] cannot watch ${dir}: ${err}`)}if(watchers.length===0){log.warn("[generate:types --watch] no directories to watch - exiting");return}await new Promise((resolve)=>{process.once("SIGINT",()=>{log.info("[generate:types --watch] stopping");for(const w of watchers)try{w.close()}catch{}resolve()})})}export function generatePantryConfig(){log.success("Successfully generated `./pantry.yaml` based on your config")}export async function generateSeeder(){}export async function generateCoreSymlink(){const link=projectPath(".framework");try{if(!fs.lstatSync(link).isSymbolicLink())return;fs.unlinkSync(link)}catch{}fs.symlinkSync(frameworkPath(),link)}export async function generateOpenApiSpec(){const{generateOpenApi}=await import("@stacksjs/api");await generateOpenApi();log.success("Successfully generated Open API Spec")}
|
package/dist/helpers/utils.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var {require}=import.meta;import{existsSync}from"node:fs";import{delimiter,join}from"node:path";import process from"node:process";import{
|
|
1
|
+
var {require}=import.meta;import{existsSync}from"node:fs";import{delimiter,join}from"node:path";import process from"node:process";import{buddyOptionArgs,runCommand}from"@stacksjs/cli";import{app}from"@stacksjs/config";import{Action as ActionEnum}from"@stacksjs/enums";import{err,handleError,ok}from"@stacksjs/error-handling";import{log}from"@stacksjs/logging";import*as p from"@stacksjs/path";export function publishedActionCandidates(action,packageRoot){let root=packageRoot;if(!root)try{const pkgUrl=import.meta.resolve("@stacksjs/actions/package.json");if(pkgUrl){const pkgPath=new URL(pkgUrl).pathname;root=pkgPath.slice(0,pkgPath.lastIndexOf("/"))}}catch{return[]}if(!root)return[];return[`${root}/dist/${action}.js`,`${root}/dist/src/${action}.js`,`${root}/src/${action}.ts`]}export function developmentConditionForProject(projectRoot){return existsSync(join(projectRoot,"storage/framework/core"))&&existsSync(join(projectRoot,"node_modules/@stacksjs/env/src/index.ts"))?"--conditions development":""}export function actionNodePath(projectRoot,existingNodePath){const nodeModulesPath=join(projectRoot,"node_modules"),pantryPath=join(projectRoot,"pantry"),paths=[nodeModulesPath];for(const entry of existingNodePath?.split(delimiter)??[])if(entry&&entry!==nodeModulesPath&&entry!==pantryPath&&!paths.includes(entry))paths.push(entry);paths.push(pantryPath);return paths.join(delimiter)}async function resolveActionFile(action,projectRoot){const candidates=[];if(projectRoot)candidates.push(join(projectRoot,`storage/framework/core/actions/src/${action}.ts`));candidates.push(p.actionsPath(`src/${action}.ts`));candidates.push(...publishedActionCandidates(action));for(const candidate of candidates)if(await Bun.file(candidate).exists())return candidate;return null}export async function runAction(action,options){log.debug(`[action] Running: ${action}`);if(action==="dev/views")try{const nodePath=actionNodePath(p.projectPath(),process.env.NODE_PATH);if(process.env.NODE_PATH!==nodePath){process.env.NODE_PATH=nodePath;require("module").Module._initPaths?.()}const viewsEntries=[p.projectPath("storage/framework/core/actions/src/dev/views.ts"),p.frameworkPath("actions/src/dev/views.ts"),...publishedActionCandidates("dev/views")];for(const entry of viewsEntries)if(existsSync(entry)){await import(entry);return ok({})}return err(Error("dev/views entry not found"))}catch(error){return err(Error(`Failed to start dev server: ${error}`))}const isLikelyCoreAction=action.includes("/")||["dev","build","install","upgrade","migrate"].some((prefix)=>action.startsWith(prefix)),userActionsBase=options?.cwd?join(String(options.cwd),"app/Actions"):p.userActionsPath();if(!isLikelyCoreAction&&existsSync(userActionsBase)){const glob=new Bun.Glob("**/*.{ts,js}"),scanOptions={cwd:userActionsBase,onlyFiles:!0,absolute:!0},matchingFiles=[],basePath=userActionsBase;for await(const file of glob.scan(scanOptions)){if(file.replace(`${basePath}/`,"").replace(/\.(ts|js)$/,"")===action||file.endsWith(`${action}.ts`)||file.endsWith(`${action}.js`)){log.debug(`[action] Resolved: ${action} \u2192 ${file}`);return await(await import(file)).default.handle(void 0)}matchingFiles.push(file)}for(const file of matchingFiles)try{const a=await import(file);if(a.name===action){log.debug(`[action] Resolved: ${action} \u2192 ${file}`);return await a.handle()}}catch(error){}}const path=await resolveActionFile(action,options?.cwd?String(options.cwd):void 0);if(!path)return err(Error(`Action '${action}' not found in storage/framework/core/actions/src or @stacksjs/actions`));log.debug(`[action] Resolved: ${action} \u2192 ${path}`);const isDevAction=action.startsWith("dev/"),watchFlag=developmentWatchFlag(action),developmentCondition=developmentConditionForProject(p.projectPath()),opts=isDevAction||!options?[]:buddyOptionArgs(options),cmd=["bun",developmentCondition,watchFlag,path,...opts].filter(Boolean),nodePath=actionNodePath(p.projectPath(),process.env.NODE_PATH),shouldInherit=options?.verbose||isDevAction&&!options?.quiet,optionsWithCwd={cwd:options?.cwd||p.projectPath(),...options,stdout:shouldInherit?"inherit":void 0,stderr:shouldInherit?"inherit":void 0,env:{...options?.env,NODE_PATH:nodePath,...isDevAction?{STACKS_DEV_SERVER:"1"}:{}}},result=await runCommand(cmd,optionsWithCwd);log.debug(`[action] Completed: ${action}`);return result}export function developmentWatchFlag(action){if(!action.startsWith("dev/"))return"";return action==="dev/dashboard"||action==="dev/desktop"?"":"--watch"}export async function runActions(actions,options){if(!actions.length)return err("No actions were specified");for(const action of actions)if(!hasAction(action))return err(`The specified action "${action}" does not exist`);return await runActionSequence(actions,options)}export async function runActionSequence(actions,options,runner=runAction){let result;for(const action of actions){result=await runner(action,options);if(result?.isErr)return result}return result}export function hasAction(action){const userActionPatterns=[`${action}.ts`,`${action}`,`Dashboard/${action}.ts`,`Dashboard/${action}`,`Buddy/${action}.ts`,`Buddy/${action}`],actionPatterns=[`src/${action}.ts`,`src/${action}`,`${action}.ts`,`${action}`];return[...userActionPatterns.map((pattern)=>p.userActionsPath(pattern)),...actionPatterns.map((pattern)=>p.actionsPath(pattern)),...publishedActionCandidates(action)].some((candidate)=>existsSync(candidate))}export async function initProject(){if(app.env!=="production")log.info("Project not yet initialized, generating application key...");else handleError("Please run `buddy key:generate` to generate an application key");const result=await runAction(ActionEnum.KeyGenerate,{cwd:p.projectPath()});if(result.isErr)return err(handleError(result.error));log.info("Application key generated.");return ok(result.value)}
|
package/dist/lint/lint.d.ts
CHANGED
|
@@ -8,6 +8,14 @@
|
|
|
8
8
|
* file, `buddy lint` says the project is clean because it never opened it, you
|
|
9
9
|
* commit, and CI fails on the file you just linted. `--exclude-standard` keeps
|
|
10
10
|
* .gitignore honoured, so build output and dependencies stay out.
|
|
11
|
+
*
|
|
12
|
+
* Outside a git repository there is no .gitignore to honour, so the directory
|
|
13
|
+
* is walked under the same {@link isLintablePath} rules.
|
|
14
|
+
*
|
|
15
|
+
* Any other git failure THROWS. It used to return an empty list, which
|
|
16
|
+
* `lintProject` reported as a clean project: a broken `git` on the PATH (a
|
|
17
|
+
* toolchain shim pointing at a deleted directory was enough) made `buddy lint`
|
|
18
|
+
* print "Linted" in 0.02s, having opened nothing, on a tree with problems.
|
|
11
19
|
*/
|
|
12
20
|
export declare function lintableFiles(cwd: string): string[];
|
|
13
21
|
/**
|
package/dist/lint/lint.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import process from"node:process";import{log}from"@stacksjs/cli";import{
|
|
1
|
+
import process from"node:process";import{log}from"@stacksjs/cli";import{spawnSync}from"node:child_process";import{existsSync}from"node:fs";import{join}from"node:path";import{runFormat,runLint}from"pickier";import{isLintablePath}from"./files";export function lintableFiles(cwd){const listed=spawnSync("git",["ls-files","-z","--cached","--others","--exclude-standard"],{cwd,encoding:"utf8",maxBuffer:268435456});if(listed.status===0)return listed.stdout.split("\x00").filter(isLintablePath);const notInstalled=listed.error?.code==="ENOENT",stderr=(listed.stderr??"").trim();if(notInstalled&&!existsSync(join(cwd,".git"))||/not a git repository/i.test(stderr))return walkLintableFiles(cwd);const reason=listed.error?.message||stderr||`exit code ${listed.status??listed.signal}`;throw Error(`Could not list the files to lint: \`git ls-files\` failed in ${cwd} (${reason})`)}function walkLintableFiles(cwd){return Array.from(new Bun.Glob("**/*").scanSync({cwd,onlyFiles:!0,dot:!0})).map((file)=>file.split("\\").join("/")).filter(isLintablePath).sort()}export async function lintProject(options={}){const cwd=options.cwd??process.cwd();log.info(options.fix?"Ensuring Code Style...":"Checking Code Style...");let files;try{files=lintableFiles(cwd)}catch(error){await log.error(error instanceof Error?error.message:String(error));return{ok:!1}}if(!files.length){log.success("Linted: no lintable files");return{ok:!0}}const ok=await runLint(files,{maxWarnings:9999,fix:options.fix})===0;if(ok)log.success("Linted");return{ok}}export function lintFix(options={}){return lintProject({...options,fix:!0})}export async function formatProject(options={}){const cwd=options.cwd??process.cwd();let files;try{files=lintableFiles(cwd)}catch(error){await log.error(error instanceof Error?error.message:String(error));return{ok:!1}}if(!files.length)return{ok:!0};return{ok:await runFormat(files,{write:options.write,check:options.check})===0}}
|
package/dist/stacks.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{mkdtempSync,rmSync}from"node:fs";import{tmpdir}from"node:os";import{dirname,isAbsolute,join,relative,resolve}from"node:path";import process from"node:process";import{log}from"@stacksjs/logging";import{registry}from"@stacksjs/registry";import{copyFile,createFolder,deleteFile,deleteEmptyFolders,doesFolderExist,fs}from"@stacksjs/storage";const STACK_DIRS=["app","config","database","resources","routes","public","locales","docs"];function stackLockPath(projectRoot){return join(projectRoot,"storage","framework","stacks.lock.json")}function stackBackupPath(projectRoot,stackName){return join(projectRoot,"storage","framework","stacks","backups",stackName)}async function readStackLock(projectRoot){const lockPath=stackLockPath(projectRoot);try{if(fs.existsSync(lockPath)){const content=await Bun.file(lockPath).text();return JSON.parse(content)}}catch{}return{version:1,generatedAt:new Date().toISOString(),stacks:{}}}async function writeStackLock(projectRoot,lock){const lockPath=stackLockPath(projectRoot),lockDir=dirname(lockPath);if(!fs.existsSync(lockDir))await createFolder(lockDir);lock.generatedAt=new Date().toISOString();await Bun.write(lockPath,JSON.stringify(lock,null,2))}function resolveProjectRoot(project){return resolve(project||process.cwd())}function resolveRegistryEntry(name){const entry=registry.find((candidate)=>{if(typeof candidate==="string")return candidate===name;return candidate.name===name||candidate.package===name});if(!entry||typeof entry==="string")return null;if(!entry.github)return null;return{name:entry.name,github:entry.github,package:entry.package}}async function checkoutRegistryStack(github){const tempRoot=mkdtempSync(join(tmpdir(),"stacks-stack-")),checkoutPath=join(tempRoot,"source"),source=`https://github.com/${github}.git`;if(await Bun.spawn(["git","clone","--depth","1","--quiet",source,checkoutPath],{stdout:"inherit",stderr:"inherit"}).exited!==0){rmSync(tempRoot,{recursive:!0,force:!0});throw Error(`Could not pull ${source}`)}return{path:checkoutPath,cleanup:()=>rmSync(tempRoot,{recursive:!0,force:!0})}}function isSafeStackDirectory(directory){return directory.length>0&&!isAbsolute(directory)&&!directory.includes("..")&&!directory.includes("\\")}function fileChecksum(path){return new Bun.CryptoHasher("sha256").update(fs.readFileSync(path)).digest("hex")}function collectFiles(dir,baseDir){const files=[];if(!fs.existsSync(dir))return files;const entries=fs.readdirSync(dir,{withFileTypes:!0});for(const entry of entries){const fullPath=join(dir,entry.name);if(entry.isDirectory())files.push(...collectFiles(fullPath,baseDir));else if(entry.isSymbolicLink())throw Error(`Stack contains an unsupported symbolic link: ${relative(baseDir,fullPath)}`);else{const relPath=relative(baseDir,fullPath);if(!isSafeStackDirectory(relPath))throw Error(`Stack contains an unsafe path: ${relPath}`);files.push(relPath)}}return files}export async function installStack(options){const{name,force=!1,dryRun=!1,verbose=!1}=options,conflict=force?"overwrite":options.conflict??"skip",projectRoot=resolveProjectRoot(options.project);log.info(`Installing stack "${name}"...`);if(!fs.existsSync(join(projectRoot,"package.json"))){log.error(`No Stacks project found at "${projectRoot}"`);return null}const registryEntry=resolveRegistryEntry(name);if(!registryEntry){log.error(`Stack "${name}" is not in the Stacks registry. Run "buddy stack:list" to see available stacks.`);return null}let checkout;try{checkout=await checkoutRegistryStack(registryEntry.github)}catch(error){log.error(error instanceof Error?error.message:String(error));return null}try{const stackPath=checkout.path;let pkg,meta;try{const pkgContent=await Bun.file(join(stackPath,"package.json")).text();pkg=JSON.parse(pkgContent);meta=pkg.stacks;if(!meta?.name||meta.name!==registryEntry.name){log.error(`Registry source "${registryEntry.github}" does not declare stacks.name as "${registryEntry.name}"`);return null}}catch(error){log.error(`Failed to read stack metadata: ${error}`);return null}const lock=await readStackLock(projectRoot),packageName=pkg.name||registryEntry.package||name;if(lock.stacks[packageName]&&!force){log.warn(`Stack "${meta.name}" is already installed. Use --force to reinstall.`);return lock.stacks[packageName]}const dirsToScan=meta.directories??STACK_DIRS;if(dirsToScan.some((directory)=>!isSafeStackDirectory(directory))){log.error(`Stack "${meta.name}" declares an unsafe project directory`);return null}const allFiles=[];try{for(const dir of dirsToScan){const dirPath=join(stackPath,dir);if(fs.existsSync(dirPath))allFiles.push(...collectFiles(dirPath,stackPath))}}catch(error){log.error(error instanceof Error?error.message:String(error));return null}if(allFiles.length===0){log.warn(`Stack "${meta.name}" has no project files to install`);return null}if(verbose)log.info(`Pulled ${registryEntry.github} and found ${allFiles.length} project file(s)`);const copiedFiles=[],skippedFiles=[],checksums={};for(const relPath of allFiles){const src=join(stackPath,relPath),dest=join(projectRoot,relPath);if(dryRun){if(fs.existsSync(dest)){log.info(`[dry-run] Would ${conflict}: ${relPath}`);if(conflict==="skip")skippedFiles.push(relPath);else copiedFiles.push(relPath)}else{log.info(`[dry-run] Would copy: ${relPath}`);copiedFiles.push(relPath)}continue}if(fs.existsSync(dest))switch(conflict){case"skip":if(verbose)log.warn(`Skipping (file exists): ${relPath}`);skippedFiles.push(relPath);continue;case"backup":{const backupDir=stackBackupPath(projectRoot,meta.name),backupDest=join(backupDir,relPath),backupDestDir=dirname(backupDest);if(!fs.existsSync(backupDestDir))await createFolder(backupDestDir);copyFile(dest,backupDest);if(verbose)log.info(`Backed up: ${relPath}`);break}case"overwrite":if(verbose)log.warn(`Overwriting: ${relPath}`);break}const destDir=dirname(dest);if(!fs.existsSync(destDir))await createFolder(destDir);copyFile(src,dest);copiedFiles.push(relPath);checksums[relPath]=fileChecksum(dest);if(verbose)log.info(`Copied: ${relPath}`)}const entry={packageName,name:meta.name,version:pkg.version||"0.0.0",installedAt:new Date().toISOString(),files:copiedFiles,checksums,source:registryEntry.github,skipped:skippedFiles,conflictStrategy:conflict};if(dryRun){log.info(`[dry-run] Would install ${copiedFiles.length} file(s), skip ${skippedFiles.length} file(s)`);return entry}lock.stacks[packageName]=entry;await writeStackLock(projectRoot,lock);log.success(`Installed stack "${meta.name}" from ${registryEntry.github} (${copiedFiles.length} file(s) copied, ${skippedFiles.length} skipped)`);return entry}finally{checkout.cleanup()}}export async function uninstallStack(options){const{name,force=!1,verbose=!1}=options,projectRoot=resolveProjectRoot(options.project);log.info(`Uninstalling stack "${name}"...`);const lock=await readStackLock(projectRoot);let entryKey=null,entry=null;for(const[key,value]of Object.entries(lock.stacks))if(value.name===name||key===name){entryKey=key;entry=value;break}if(!entry||!entryKey){log.error(`Stack "${name}" is not installed`);return!1}let removedCount=0;const remainingFiles=[];for(const relPath of entry.files){const filePath=join(projectRoot,relPath);if(!fs.existsSync(filePath)){if(verbose)log.info(`Already removed: ${relPath}`);continue}if(!force){const installedChecksum=entry.checksums?.[relPath];if(!installedChecksum||fileChecksum(filePath)!==installedChecksum){log.warn(`Skipping modified file: ${relPath} (use --force to remove)`);remainingFiles.push(relPath);continue}}await deleteFile(filePath);removedCount++;if(verbose)log.info(`Removed: ${relPath}`)}if(remainingFiles.length>0){entry.files=remainingFiles;entry.checksums=Object.fromEntries(remainingFiles.map((file)=>[file,entry.checksums?.[file]]).filter((item)=>typeof item[1]==="string"));lock.stacks[entryKey]=entry;await writeStackLock(projectRoot,lock);log.warn(`Stack "${entry.name}" is still tracked because ${remainingFiles.length} modified file(s) remain`);return!1}const backupDir=stackBackupPath(projectRoot,entry.name);if(fs.existsSync(backupDir)&&doesFolderExist(backupDir)){const backupFiles=collectFiles(backupDir,backupDir);for(const relPath of backupFiles){const backupSrc=join(backupDir,relPath),dest=join(projectRoot,relPath),destDir=dirname(dest);if(!fs.existsSync(destDir))await createFolder(destDir);copyFile(backupSrc,dest);if(verbose)log.info(`Restored from backup: ${relPath}`)}fs.rmSync(backupDir,{recursive:!0,force:!0})}for(const dir of STACK_DIRS){const dirPath=join(projectRoot,dir);if(fs.existsSync(dirPath))await deleteEmptyFolders(dirPath)}delete lock.stacks[entryKey];await writeStackLock(projectRoot,lock);log.success(`Uninstalled stack "${entry.name}" (${removedCount} file(s) removed)`);return!0}export async function listStacks(project){const entries=[],projectRoot=resolveProjectRoot(project),lock=await readStackLock(projectRoot);for(const candidate of registry){if(typeof candidate==="string")continue;const packageName=candidate.package||candidate.name,lockEntry=lock.stacks[packageName];entries.push({name:candidate.name,packageName,version:lockEntry?.version||"latest",description:candidate.description,installed:Boolean(lockEntry),installedAt:lockEntry?.installedAt,fileCount:lockEntry?.files.length})}for(const[packageName,entry]of Object.entries(lock.stacks))if(!entries.some((e)=>e.packageName===packageName))entries.push({name:entry.name,packageName,version:entry.version,installed:!0,installedAt:entry.installedAt,fileCount:entry.files.length});return entries}
|
|
1
|
+
import{mkdtempSync,rmSync}from"node:fs";import{tmpdir}from"node:os";import{dirname,isAbsolute,join,relative,resolve}from"node:path";import process from"node:process";import{log}from"@stacksjs/logging";import{registry}from"@stacksjs/registry";import{copyFile,createFolder,deleteFile,deleteEmptyFolders,doesFolderExist,fs}from"@stacksjs/storage";const STACK_DIRS=["app","config","database","resources","routes","public","locales","docs"];function stackLockPath(projectRoot){return join(projectRoot,"storage","framework","stacks.lock.json")}function stackBackupPath(projectRoot,stackName){return join(projectRoot,"storage","framework","stacks","backups",stackName)}async function readStackLock(projectRoot){const lockPath=stackLockPath(projectRoot);try{if(fs.existsSync(lockPath)){const content=await Bun.file(lockPath).text();return JSON.parse(content)}}catch{}return{version:1,generatedAt:new Date().toISOString(),stacks:{}}}async function writeStackLock(projectRoot,lock){const lockPath=stackLockPath(projectRoot),lockDir=dirname(lockPath);if(!fs.existsSync(lockDir))await createFolder(lockDir);lock.generatedAt=new Date().toISOString();await Bun.write(lockPath,JSON.stringify(lock,null,2))}function resolveProjectRoot(project){return resolve(project||process.cwd())}function resolveRegistryEntry(name){const entry=registry.find((candidate)=>{if(typeof candidate==="string")return candidate===name;return candidate.name===name||candidate.package===name});if(!entry||typeof entry==="string")return null;if(!entry.github)return null;return{name:entry.name,github:entry.github,package:entry.package}}async function checkoutRegistryStack(github){const tempRoot=mkdtempSync(join(tmpdir(),"stacks-stack-")),checkoutPath=join(tempRoot,"source"),source=`https://github.com/${github}.git`;if(await Bun.spawn(["git","clone","--depth","1","--quiet",source,checkoutPath],{stdout:"inherit",stderr:"inherit"}).exited!==0){rmSync(tempRoot,{recursive:!0,force:!0});throw Error(`Could not pull ${source}`)}return{path:checkoutPath,cleanup:()=>rmSync(tempRoot,{recursive:!0,force:!0})}}function isSafeStackDirectory(directory){return directory.length>0&&!isAbsolute(directory)&&!directory.includes("..")&&!directory.includes("\\")}function fileChecksum(path){return new Bun.CryptoHasher("sha256").update(fs.readFileSync(path)).digest("hex")}function collectFiles(dir,baseDir){const files=[];if(!fs.existsSync(dir))return files;const entries=fs.readdirSync(dir,{withFileTypes:!0});for(const entry of entries){const fullPath=join(dir,entry.name);if(entry.isDirectory())files.push(...collectFiles(fullPath,baseDir));else if(entry.isSymbolicLink())throw Error(`Stack contains an unsupported symbolic link: ${relative(baseDir,fullPath)}`);else{const relPath=relative(baseDir,fullPath);if(!isSafeStackDirectory(relPath))throw Error(`Stack contains an unsafe path: ${relPath}`);files.push(relPath)}}return files}export async function installStack(options){const{name,force=!1,dryRun=!1,verbose=!1}=options,conflict=force?"overwrite":options.conflict??"skip",projectRoot=resolveProjectRoot(options.project);log.info(`Installing stack "${name}"...`);if(!fs.existsSync(join(projectRoot,"package.json"))){log.error(`No Stacks project found at "${projectRoot}"`);return null}const registryEntry=resolveRegistryEntry(name);if(!registryEntry){log.error(`Stack "${name}" is not in the Stacks registry. Run "buddy stack:list" to see available stacks.`);return null}let checkout;try{checkout=await checkoutRegistryStack(registryEntry.github)}catch(error){log.error(error instanceof Error?error.message:String(error));return null}try{const stackPath=checkout.path;let pkg,meta;try{const pkgContent=await Bun.file(join(stackPath,"package.json")).text();pkg=JSON.parse(pkgContent);meta=pkg.stacks;if(!meta?.name||meta.name!==registryEntry.name){log.error(`Registry source "${registryEntry.github}" does not declare stacks.name as "${registryEntry.name}"`);return null}}catch(error){log.error(`Failed to read stack metadata: ${error}`);return null}const lock=await readStackLock(projectRoot),packageName=pkg.name||registryEntry.package||name;if(lock.stacks[packageName]&&!force){log.warn(`Stack "${meta.name}" is already installed. Use --force to reinstall.`);return lock.stacks[packageName]}const dirsToScan=meta.directories??STACK_DIRS;if(dirsToScan.some((directory)=>!isSafeStackDirectory(directory))){log.error(`Stack "${meta.name}" declares an unsafe project directory`);return null}const allFiles=[];try{for(const dir of dirsToScan){const dirPath=join(stackPath,dir);if(fs.existsSync(dirPath))allFiles.push(...collectFiles(dirPath,stackPath))}}catch(error){log.error(error instanceof Error?error.message:String(error));return null}if(allFiles.length===0){log.warn(`Stack "${meta.name}" has no project files to install`);return null}if(verbose)log.info(`Pulled ${registryEntry.github} and found ${allFiles.length} project file(s)`);const copiedFiles=[],skippedFiles=[],checksums={};for(const relPath of allFiles){const src=join(stackPath,relPath),dest=join(projectRoot,relPath);if(dryRun){if(fs.existsSync(dest)){log.info(`[dry-run] Would ${conflict}: ${relPath}`);if(conflict==="skip")skippedFiles.push(relPath);else copiedFiles.push(relPath)}else{log.info(`[dry-run] Would copy: ${relPath}`);copiedFiles.push(relPath)}continue}if(fs.existsSync(dest))switch(conflict){case"skip":if(verbose)log.warn(`Skipping (file exists): ${relPath}`);skippedFiles.push(relPath);continue;case"backup":{const backupDir=stackBackupPath(projectRoot,meta.name),backupDest=join(backupDir,relPath),backupDestDir=dirname(backupDest);if(!fs.existsSync(backupDestDir))await createFolder(backupDestDir);copyFile(dest,backupDest);if(verbose)log.info(`Backed up: ${relPath}`);break}case"overwrite":if(verbose)log.warn(`Overwriting: ${relPath}`);break}const destDir=dirname(dest);if(!fs.existsSync(destDir))await createFolder(destDir);copyFile(src,dest);copiedFiles.push(relPath);checksums[relPath]=fileChecksum(dest);if(verbose)log.info(`Copied: ${relPath}`)}const entry={packageName,name:meta.name,version:pkg.version||"0.0.0",installedAt:new Date().toISOString(),files:copiedFiles,checksums,source:registryEntry.github,skipped:skippedFiles,conflictStrategy:conflict};if(dryRun){log.info(`[dry-run] Would install ${copiedFiles.length} file(s), skip ${skippedFiles.length} file(s)`);return entry}lock.stacks[packageName]=entry;await writeStackLock(projectRoot,lock);log.success(`Installed stack "${meta.name}" from ${registryEntry.github} (${copiedFiles.length} file(s) copied, ${skippedFiles.length} skipped)`);return entry}finally{checkout.cleanup()}}export async function uninstallStack(options){const{name,force=!1,verbose=!1}=options,projectRoot=resolveProjectRoot(options.project);log.info(`Uninstalling stack "${name}"...`);const lock=await readStackLock(projectRoot);let entryKey=null,entry=null;for(const[key,value]of Object.entries(lock.stacks))if(value.name===name||key===name){entryKey=key;entry=value;break}if(!entry||!entryKey){log.error(`Stack "${name}" is not installed`);return!1}let removedCount=0;const remainingFiles=[];for(const relPath of entry.files){const filePath=join(projectRoot,relPath);if(!fs.existsSync(filePath)){if(verbose)log.info(`Already removed: ${relPath}`);continue}if(!force){const installedChecksum=entry.checksums?.[relPath];if(!installedChecksum||fileChecksum(filePath)!==installedChecksum){log.warn(`Skipping modified file: ${relPath} (use --force to remove)`);remainingFiles.push(relPath);continue}}const removed=await deleteFile(filePath);if(removed.isErr){log.warn(`Could not remove ${relPath}: ${removed.error.message}`);remainingFiles.push(relPath);continue}removedCount++;if(verbose)log.info(`Removed: ${relPath}`)}if(remainingFiles.length>0){entry.files=remainingFiles;entry.checksums=Object.fromEntries(remainingFiles.map((file)=>[file,entry.checksums?.[file]]).filter((item)=>typeof item[1]==="string"));lock.stacks[entryKey]=entry;await writeStackLock(projectRoot,lock);log.warn(`Stack "${entry.name}" is still tracked because ${remainingFiles.length} modified or undeletable file(s) remain`);return!1}const backupDir=stackBackupPath(projectRoot,entry.name);if(fs.existsSync(backupDir)&&doesFolderExist(backupDir)){const backupFiles=collectFiles(backupDir,backupDir);for(const relPath of backupFiles){const backupSrc=join(backupDir,relPath),dest=join(projectRoot,relPath),destDir=dirname(dest);if(!fs.existsSync(destDir))await createFolder(destDir);copyFile(backupSrc,dest);if(verbose)log.info(`Restored from backup: ${relPath}`)}fs.rmSync(backupDir,{recursive:!0,force:!0})}for(const dir of STACK_DIRS){const dirPath=join(projectRoot,dir);if(fs.existsSync(dirPath))await deleteEmptyFolders(dirPath)}delete lock.stacks[entryKey];await writeStackLock(projectRoot,lock);log.success(`Uninstalled stack "${entry.name}" (${removedCount} file(s) removed)`);return!0}export async function listStacks(project){const entries=[],projectRoot=resolveProjectRoot(project),lock=await readStackLock(projectRoot);for(const candidate of registry){if(typeof candidate==="string")continue;const packageName=candidate.package||candidate.name,lockEntry=lock.stacks[packageName];entries.push({name:candidate.name,packageName,version:lockEntry?.version||"latest",description:candidate.description,installed:Boolean(lockEntry),installedAt:lockEntry?.installedAt,fileCount:lockEntry?.files.length})}for(const[packageName,entry]of Object.entries(lock.stacks))if(!entries.some((e)=>e.packageName===packageName))entries.push({name:entry.name,packageName,version:entry.version,installed:!0,installedAt:entry.installedAt,fileCount:entry.files.length});return entries}
|
package/dist/upgrade/shell.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$}from"bun";import process from"node:process";import{italic
|
|
1
|
+
import{$}from"bun";import process from"node:process";import{italic}from"@stacksjs/cli";import{log}from"@stacksjs/logging";import{path as p}from"@stacksjs/path";import{writeFile}from"@stacksjs/storage";import{ExitCode}from"@stacksjs/types";const homePath=(await $`echo $HOME`.text()).trim(),zshrcPath=p.join(homePath,".zshrc"),pluginPath=p.shellPath("src/buddy.plugin.zsh"),customPath=p.join(homePath,".oh-my-zsh/custom/plugins/buddy/");log.info(`Setting up Oh My Zsh via ${zshrcPath}...`);$.cwd(p.dirname(zshrcPath));let data=await $`cat ${p.basename(zshrcPath)}`.text();const pluginLineRegex=/^(?!#).*plugins=\(([^)]+)\)/m,match=data.match(pluginLineRegex);if(match){const plugins=match[1]?.split(/\s+/).filter(Boolean);if(!plugins){await log.error("Maybe the plugins line in your .zshrc file could not be found? If this continues being an issue, please reach out to us on Discord.");process.exit(ExitCode.FatalError)}if(!plugins.includes("buddy")){plugins.push("buddy");const newPluginLine=`plugins=(
|
|
2
2
|
${plugins.map((plugin)=>plugin.trim()).join(`
|
|
3
3
|
`)}
|
|
4
|
-
)`;data=data.replace(pluginLineRegex,newPluginLine);await writeFile(zshrcPath,data);log.info(`Copying buddy zsh plugin ${pluginPath} to ${customPath}...`);await
|
|
4
|
+
)`;data=data.replace(pluginLineRegex,newPluginLine);await writeFile(zshrcPath,data);log.info(`Copying buddy zsh plugin ${pluginPath} to ${customPath}...`);await $`mkdir -p ${customPath}`;await $`cp -rf ${pluginPath} ${customPath}`;log.success("Copied buddy zsh plugin")}else{log.info("Buddy is already set up");log.info("Ensuring `buddy` is updated...");await $`cp -rf ${pluginPath} ${customPath}`;log.success("Updated buddy zsh plugin to latest version")}}log.success("Oh My Zsh Setup Complete");log.info(italic("To see changes reflect, you may need to open a new terminal window"));if(process.env.TERM_PROGRAM==="vscode")log.info("\u2318\u21E7P terminal.create.new.terminal");
|
package/dist/upgrade.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFileSync}from"node:fs";import process from"node:process";import{intro,outro,runCommand}from"@stacksjs/cli";import{NpmScript}from"@stacksjs/enums";import{log}from"@stacksjs/logging";import{projectPath}from"@stacksjs/path";import*as storage from"@stacksjs/storage";import{ExitCode}from"@stacksjs/types";const{version}=JSON.parse(readFileSync(new URL("../package.json",import.meta.url),"utf8"));export function checkForUncommittedChanges(options){try{console.log("checkForUncommittedChanges",options)}catch(error){console.error(error)}}export async function downloadFrameworkUpdate(options){const tempFolderName="updates",tempUpdatePath=projectPath(tempFolderName);if(storage.doesFolderExist(tempUpdatePath))await storage.deleteFolder(tempUpdatePath);log.info("Downloading framework updates...");await runCommand(`giget stacks ${tempFolderName}`,options);log.success(`Your framework updated correctly to version: v${version}`)}export async function updateDependencies(){const perf=await intro("buddy upgrade:dependencies"),result=await runCommand(NpmScript.UpgradeDependencies,{cwd:projectPath()});if(result.isErr){await outro("While running the upgrade:dependencies command, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await outro("Freshly updated your dependencies.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}
|
|
1
|
+
import{readFileSync}from"node:fs";import process from"node:process";import{intro,outro,runCommand}from"@stacksjs/cli";import{NpmScript}from"@stacksjs/enums";import{log}from"@stacksjs/logging";import{projectPath}from"@stacksjs/path";import*as storage from"@stacksjs/storage";import{ExitCode}from"@stacksjs/types";const{version}=JSON.parse(readFileSync(new URL("../package.json",import.meta.url),"utf8"));export function checkForUncommittedChanges(options){try{console.log("checkForUncommittedChanges",options)}catch(error){console.error(error)}}export async function downloadFrameworkUpdate(options){const tempFolderName="updates",tempUpdatePath=projectPath(tempFolderName);if(storage.doesFolderExist(tempUpdatePath)){const cleared=await storage.deleteFolder(tempUpdatePath);if(cleared.isErr)throw Error(`Could not clear ${tempUpdatePath} before downloading the update: ${cleared.error.message}`)}log.info("Downloading framework updates...");await runCommand(`giget stacks ${tempFolderName}`,options);log.success(`Your framework updated correctly to version: v${version}`)}export async function updateDependencies(){const perf=await intro("buddy upgrade:dependencies"),result=await runCommand(NpmScript.UpgradeDependencies,{cwd:projectPath()});if(result.isErr){await outro("While running the upgrade:dependencies command, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await outro("Freshly updated your dependencies.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/actions",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.75.
|
|
5
|
+
"version": "0.75.74",
|
|
6
6
|
"description": "The Stacks actions.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -66,58 +66,58 @@
|
|
|
66
66
|
"prepublishOnly": "bun run build"
|
|
67
67
|
},
|
|
68
68
|
"dependencies": {
|
|
69
|
-
"@stacksjs/action-runner": "0.75.
|
|
70
|
-
"@stacksjs/ai": "0.75.
|
|
71
|
-
"@stacksjs/analytics": "0.75.
|
|
72
|
-
"@stacksjs/api": "0.75.
|
|
73
|
-
"@stacksjs/auth": "0.75.
|
|
74
|
-
"@stacksjs/build": "0.75.
|
|
69
|
+
"@stacksjs/action-runner": "0.75.74",
|
|
70
|
+
"@stacksjs/ai": "0.75.74",
|
|
71
|
+
"@stacksjs/analytics": "0.75.74",
|
|
72
|
+
"@stacksjs/api": "0.75.74",
|
|
73
|
+
"@stacksjs/auth": "0.75.74",
|
|
74
|
+
"@stacksjs/build": "0.75.74",
|
|
75
75
|
"@stacksjs/bumpx": "^0.2.18",
|
|
76
76
|
"@stacksjs/bunpress": "^0.2.14",
|
|
77
|
-
"@stacksjs/cli": "0.75.
|
|
78
|
-
"@stacksjs/cloud": "0.75.
|
|
79
|
-
"@stacksjs/cms": "0.75.
|
|
80
|
-
"@stacksjs/components": "^0.2.
|
|
81
|
-
"@stacksjs/config": "0.75.
|
|
82
|
-
"@stacksjs/database": "0.75.
|
|
83
|
-
"@stacksjs/desktop-build": "0.75.
|
|
84
|
-
"@stacksjs/dns": "0.75.
|
|
85
|
-
"@stacksjs/enums": "0.75.
|
|
86
|
-
"@stacksjs/env": "0.75.
|
|
87
|
-
"@stacksjs/error-handling": "0.75.
|
|
77
|
+
"@stacksjs/cli": "0.75.74",
|
|
78
|
+
"@stacksjs/cloud": "0.75.74",
|
|
79
|
+
"@stacksjs/cms": "0.75.74",
|
|
80
|
+
"@stacksjs/components": "^0.2.374",
|
|
81
|
+
"@stacksjs/config": "0.75.74",
|
|
82
|
+
"@stacksjs/database": "0.75.74",
|
|
83
|
+
"@stacksjs/desktop-build": "0.75.74",
|
|
84
|
+
"@stacksjs/dns": "0.75.74",
|
|
85
|
+
"@stacksjs/enums": "0.75.74",
|
|
86
|
+
"@stacksjs/env": "0.75.74",
|
|
87
|
+
"@stacksjs/error-handling": "0.75.74",
|
|
88
88
|
"@stacksjs/gitit": "^0.2.5",
|
|
89
|
-
"@stacksjs/i18n": "0.75.
|
|
90
|
-
"@stacksjs/image": "0.75.
|
|
91
|
-
"@stacksjs/logging": "0.75.
|
|
89
|
+
"@stacksjs/i18n": "0.75.74",
|
|
90
|
+
"@stacksjs/image": "0.75.74",
|
|
91
|
+
"@stacksjs/logging": "0.75.74",
|
|
92
92
|
"@stacksjs/logsmith": "^0.2.11",
|
|
93
|
-
"@stacksjs/mobile": "0.75.
|
|
94
|
-
"@stacksjs/orm": "0.75.
|
|
95
|
-
"@stacksjs/path": "0.75.
|
|
96
|
-
"@stacksjs/payments": "0.75.
|
|
97
|
-
"@stacksjs/queue": "0.75.
|
|
98
|
-
"@stacksjs/registry": "0.75.
|
|
99
|
-
"@stacksjs/router": "0.75.
|
|
93
|
+
"@stacksjs/mobile": "0.75.74",
|
|
94
|
+
"@stacksjs/orm": "0.75.74",
|
|
95
|
+
"@stacksjs/path": "0.75.74",
|
|
96
|
+
"@stacksjs/payments": "0.75.74",
|
|
97
|
+
"@stacksjs/queue": "0.75.74",
|
|
98
|
+
"@stacksjs/registry": "0.75.74",
|
|
99
|
+
"@stacksjs/router": "0.75.74",
|
|
100
100
|
"@stacksjs/rpx": "^0.11.54",
|
|
101
|
-
"@stacksjs/scheduler": "0.75.
|
|
102
|
-
"@stacksjs/search-engine": "0.75.
|
|
103
|
-
"@stacksjs/security": "0.75.
|
|
104
|
-
"@stacksjs/server": "0.75.
|
|
105
|
-
"@stacksjs/sites": "0.75.
|
|
106
|
-
"@stacksjs/storage": "0.75.
|
|
107
|
-
"@stacksjs/strings": "0.75.
|
|
108
|
-
"@stacksjs/stx": "^0.2.
|
|
101
|
+
"@stacksjs/scheduler": "0.75.74",
|
|
102
|
+
"@stacksjs/search-engine": "0.75.74",
|
|
103
|
+
"@stacksjs/security": "0.75.74",
|
|
104
|
+
"@stacksjs/server": "0.75.74",
|
|
105
|
+
"@stacksjs/sites": "0.75.74",
|
|
106
|
+
"@stacksjs/storage": "0.75.74",
|
|
107
|
+
"@stacksjs/strings": "0.75.74",
|
|
108
|
+
"@stacksjs/stx": "^0.2.374",
|
|
109
109
|
"@stacksjs/tlsx": "^0.13.19",
|
|
110
|
-
"@stacksjs/ts-cloud": "^0.16.
|
|
110
|
+
"@stacksjs/ts-cloud": "^0.16.39",
|
|
111
111
|
"@stacksjs/ts-md": "^0.1.1",
|
|
112
|
-
"@stacksjs/tunnel": "0.75.
|
|
113
|
-
"@stacksjs/types": "0.75.
|
|
114
|
-
"@stacksjs/utils": "0.75.
|
|
115
|
-
"@stacksjs/whois": "0.75.
|
|
116
|
-
"bun-plugin-stx": "^0.2.
|
|
112
|
+
"@stacksjs/tunnel": "0.75.74",
|
|
113
|
+
"@stacksjs/types": "0.75.74",
|
|
114
|
+
"@stacksjs/utils": "0.75.74",
|
|
115
|
+
"@stacksjs/whois": "0.75.74",
|
|
116
|
+
"bun-plugin-stx": "^0.2.374"
|
|
117
117
|
},
|
|
118
118
|
"peerDependencies": {
|
|
119
119
|
"craft-native": ">=0.0.111",
|
|
120
|
-
"pickier": "^0.1.
|
|
120
|
+
"pickier": "^0.1.68"
|
|
121
121
|
},
|
|
122
122
|
"peerDependenciesMeta": {
|
|
123
123
|
"pickier": {
|
|
@@ -128,7 +128,7 @@
|
|
|
128
128
|
}
|
|
129
129
|
},
|
|
130
130
|
"devDependencies": {
|
|
131
|
-
"@stacksjs/validation": "0.75.
|
|
131
|
+
"@stacksjs/validation": "0.75.74",
|
|
132
132
|
"better-dx": "^0.2.24"
|
|
133
133
|
}
|
|
134
134
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var {require}=import.meta;import{requestModelAccess}from"@stacksjs/ai";async function main(){try{await requestModelAccess()}catch(error){console.error("Error requesting model access:",error)}}if(import.meta.main)main();
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{log,runCommand}from"@stacksjs/cli";import{config}from"@stacksjs/config";const pantryFile=Bun.file(new URL("../../../../../pantry.yaml",import.meta.url));if(!await pantryFile.exists())throw Error("pantry.yaml file not found");const data=Bun.YAML.parse(await pantryFile.text());if(data.dependencies["aws.amazon.com/cdk"]===void 0){log.info("aws.amazon.com/cdk dependency not found in pantry.yaml.");if((await runCommand("which cdk")).isErr)throw Error("aws.amazon.com/cdk dependency not found in pantry.yaml. To confirm, run `which cdk`")}if(data.dependencies["aws.amazon.com/cli"]===void 0){log.info("aws.amazon.com/cli dependency not found in pantry.yaml.");if((await runCommand("which aws")).isErr)throw Error("aws.amazon.com/cli dependency not found in pantry.yaml. To confirm, run `which aws`")}if(data.dependencies["bun.sh"]===void 0){log.info("bun.sh dependency not found in pantry.yaml.");if((await runCommand("which bun")).isErr)throw Error("bun.sh dependency not found in pantry.yaml. To confirm, run `which bun`")}if(data.dependencies["info-zip.org/zip"]===void 0){log.info("info-zip.org/zip dependency not found in pantry.yaml.");if((await runCommand("which zip")).isErr)throw Error("info-zip.org/zip dependency not found in pantry.yaml. To confirm, run `which zip`")}if(data.dependencies["info-zip.org/unzip"]===void 0){log.info("info-zip.org/unzip dependency not found in pantry.yaml.");if((await runCommand("which unzip")).isErr)throw Error("info-zip.org/unzip dependency not found in pantry.yaml. To confirm, run `which unzip`")}if(data.dependencies["github.com/mail-os/mail"]===void 0){log.info("github.com/mail-os/mail dependency not found in pantry.yaml.");if((await runCommand("which mail")).isErr)throw Error("github.com/mail-os/mail dependency not found in pantry.yaml. To confirm, run `which mail`")}if(data.dependencies["redis.io"]===void 0){log.info("redis.io dependency not found in pantry.yaml.");if((await runCommand("which redis")).isErr)throw Error("redis.io dependency not found in pantry.yaml. To confirm, run `which redis`")}if(config.database.default==="sqlite"&&data.dependencies["sqlite.org"]===void 0){log.info("sqlite.org dependency not found in pantry.yaml.");if((await runCommand("which sqlite")).isErr)throw Error("sqlite.org dependency not found in pantry.yaml. To confirm, run `which sqlite`")}
|