@stacksjs/buddy 0.75.515 → 0.75.519
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/app-store-connect.js +2 -2
- package/dist/cli.js +4 -4
- package/dist/cloud-tenants.js +1 -1
- package/dist/commands/about.js +1 -1
- package/dist/commands/add.js +1 -1
- package/dist/commands/ai-access.js +2 -2
- package/dist/commands/ai-context.js +2 -2
- package/dist/commands/auth-prune-options.js +1 -1
- package/dist/commands/auth.js +1 -1
- package/dist/commands/build.js +1 -1
- package/dist/commands/cd.js +3 -3
- package/dist/commands/changelog.js +1 -1
- package/dist/commands/clean.js +1 -1
- package/dist/commands/cloud.js +7 -7
- package/dist/commands/comments.js +2 -2
- package/dist/commands/commerce-import.js +3 -3
- package/dist/commands/commit.js +1 -1
- package/dist/commands/completion.js +7 -7
- package/dist/commands/config-migrate.js +5 -5
- package/dist/commands/configure.js +2 -2
- package/dist/commands/create.js +1 -1
- package/dist/commands/db.js +1 -1
- package/dist/commands/deploy-fly.js +2 -2
- package/dist/commands/deploy-preview.js +1 -1
- package/dist/commands/deploy-ssh-target.js +1 -1
- package/dist/commands/deploy.js +588 -19
- package/dist/commands/desktop-apple.js +12 -12
- package/dist/commands/desktop-probe.js +1 -1
- package/dist/commands/dev.js +4 -4
- package/dist/commands/dns.js +2 -2
- package/dist/commands/docs/agent-counts.js +2 -2
- package/dist/commands/docs/buddy-commands.js +10 -10
- package/dist/commands/docs/capabilities.js +2 -2
- package/dist/commands/docs/desktop-matrix.js +2 -2
- package/dist/commands/docs/framework-repo.js +1 -1
- package/dist/commands/docs/generated-artifacts.js +2 -2
- package/dist/commands/docs/links.js +2 -2
- package/dist/commands/docs/native-skills.js +2 -2
- package/dist/commands/docs/snippets.js +6 -6
- package/dist/commands/doctor.js +3 -3
- package/dist/commands/domains.js +2 -2
- package/dist/commands/email.js +26 -26
- package/dist/commands/env.js +1 -1
- package/dist/commands/extension.js +3 -3
- package/dist/commands/features.js +3 -3
- package/dist/commands/feedback.js +3 -3
- package/dist/commands/fresh.js +1 -1
- package/dist/commands/gdpr.js +6 -6
- package/dist/commands/generate.js +5 -5
- package/dist/commands/http.js +1 -1
- package/dist/commands/install.js +1 -1
- package/dist/commands/integrations-probe.js +2 -2
- package/dist/commands/key.js +1 -1
- package/dist/commands/libs.js +1 -1
- package/dist/commands/link.js +2 -2
- package/dist/commands/lint.js +2 -2
- package/dist/commands/list.js +2 -2
- package/dist/commands/mail.js +13 -13
- package/dist/commands/maintenance.js +1 -1
- package/dist/commands/make.js +1 -1
- package/dist/commands/migrate-project.js +1 -1
- package/dist/commands/migrate.js +59 -59
- package/dist/commands/outdated.js +1 -1
- package/dist/commands/package.js +1 -1
- package/dist/commands/phone.js +13 -13
- package/dist/commands/ports.js +2 -2
- package/dist/commands/prepublish.js +1 -1
- package/dist/commands/preview-deploy.js +1 -1
- package/dist/commands/projects.js +1 -1
- package/dist/commands/publish.js +8 -8
- package/dist/commands/queue.js +1 -1
- package/dist/commands/release.js +7 -7
- package/dist/commands/route.js +1 -1
- package/dist/commands/saas.js +1 -1
- package/dist/commands/schedule.js +1 -1
- package/dist/commands/search.js +1 -1
- package/dist/commands/security.js +2 -2
- package/dist/commands/seed.js +1 -1
- package/dist/commands/serve.js +1 -1
- package/dist/commands/server-image.js +2 -2
- package/dist/commands/server-trust.js +2 -2
- package/dist/commands/server.js +10 -8
- package/dist/commands/setup-ai.js +2 -2
- package/dist/commands/setup.js +5 -5
- package/dist/commands/share.js +1 -1
- package/dist/commands/simulator.js +1 -1
- package/dist/commands/sms.js +25 -25
- package/dist/commands/socials.js +3 -3
- package/dist/commands/stacks.js +1 -1
- package/dist/commands/storage-backup.js +1 -1
- package/dist/commands/telemetry.js +1 -1
- package/dist/commands/test.js +1 -1
- package/dist/commands/tinker.js +1 -1
- package/dist/commands/types.js +1 -1
- package/dist/commands/upgrade.js +1 -1
- package/dist/commands/user.js +2 -2
- package/dist/config.js +1 -1
- package/dist/custom-cli.js +1 -1
- package/dist/database-backup.js +2 -2
- package/dist/database-preflight.js +1 -1
- package/dist/deploy-notify.js +3 -3
- package/dist/deployment-inputs.js +1 -1
- package/dist/deployment-revision.js +4 -4
- package/dist/dns-credentials.js +1 -1
- package/dist/email-reprocess.js +1 -1
- package/dist/feedback-links.js +1 -1
- package/dist/global-options.js +1 -1
- package/dist/lazy-commands.js +1 -1
- package/dist/mail-dns-health.js +1 -1
- package/dist/mail-users.js +1 -1
- package/dist/migrators/index.js +1 -1
- package/dist/migrators/laravel/index.js +1 -1
- package/dist/migrators/laravel/migrations.js +4 -4
- package/dist/migrators/laravel/models.js +4 -4
- package/dist/native-project.js +7 -7
- package/dist/native-site.js +2 -2
- package/dist/pantry-service-ports.js +2 -2
- package/dist/production-server.js +1 -1
- package/dist/project-setup.js +1 -1
- package/dist/publish-stx.js +1 -1
- package/dist/registry.js +1 -1
- package/dist/release-ios.js +1 -1
- package/dist/result.js +1 -1
- package/dist/scaffold-app.js +4 -4
- package/dist/scaffold-desktop.js +1 -1
- package/dist/scaffold-package-app.js +7 -7
- package/dist/scaffold-site.js +1 -1
- package/dist/storage-backup.js +1 -1
- package/dist/system-dependencies.js +1 -1
- package/dist/unbacked-data.js +1 -1
- package/dist/unvendor-rewrite.js +2 -2
- package/dist/version-info.js +1 -1
- package/dist/workflow-prune.js +3 -3
- package/package.json +55 -55
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
import{assertFrameworkRepo}from"./framework-repo";import{existsSync,mkdirSync,readFileSync,writeFileSync}from"node:fs";import{dirname,resolve}from"node:path";const root=resolve(import.meta.dir,"../../../../../../..")
|
|
2
|
-
`,"<br>")}function code(value){return`\`${String(value).replaceAll("`","\\`")}\``}function stablePath(value){if(typeof value!=="string"||!value.includes(root))return value;return value.replaceAll(root,"<project root>")}function optionFlags(option){return option.flags.map((flag)=>code(`${flag.length===1?"-":"--"}${flag}`)).join(", ")}function optionKind(option){
|
|
3
|
-
`)}export function renderBuddyCommandReference(inventory){const commands=[...inventory.commands].sort((a,b)=>a.name.localeCompare(b.name));if(inventory.total!==commands.length)throw Error(`Buddy inventory total ${inventory.total} does not match ${commands.length} commands`);if(new Set(commands.map((command)=>command.name)).size!==commands.length)throw Error("Buddy inventory contains duplicate canonical command names");const groups=new Map;for(const command of commands){const group=command.namespace||(command.name.includes(":")?command.name.split(":")[0]:"general")
|
|
4
|
-
`).split(`
|
|
1
|
+
import{assertFrameworkRepo}from"./framework-repo";import{existsSync,mkdirSync,readFileSync,writeFileSync}from"node:fs";import{dirname,resolve}from"node:path";const root=resolve(import.meta.dir,"../../../../../../..");const outputPath=resolve(root,"docs/guide/buddy/commands.md");const cliPath=resolve(root,"storage/framework/core/buddy/src/cli.ts");function markdown(value){return String(value).replaceAll("\\","\\\\").replaceAll("|","\\|").replaceAll(`
|
|
2
|
+
`,"<br>")}function code(value){return`\`${String(value).replaceAll("`","\\`")}\``}function stablePath(value){if(typeof value!=="string"||!value.includes(root))return value;return value.replaceAll(root,"<project root>")}function optionFlags(option){return option.flags.map((flag)=>code(`${flag.length===1?"-":"--"}${flag}`)).join(", ")}function optionKind(option){const traits=[option.boolean?"boolean":"value",option.required?"required":"optional",...option.negated?["negated"]:[]];return traits.join(", ")}function argumentSyntax(argument){const value=`${argument.name}${argument.variadic?"...":""}`;return code(argument.required?`<${value}>`:`[${value}]`)}function commandSection(command){const lines=[`### ${code(command.name)}`,"",command.description||"No description provided.","",`- Usage: ${code(command.usage)}`,`- Namespace: ${command.namespace?code(command.namespace):"none"}`,`- Aliases: ${command.aliases.length?command.aliases.map(code).join(", "):"none"}`,`- Arguments: ${command.arguments.length?command.arguments.map(argumentSyntax).join(", "):"none"}`];if(command.options.length){lines.push("","| Option | Description | Contract | Default |","| --- | --- | --- | --- |",...command.options.map((option)=>`| ${optionFlags(option)} | ${markdown(option.description||"-")} | ${optionKind(option)} | ${option.default===undefined?"-":code(JSON.stringify(stablePath(option.default)))} |`))}if(command.examples.length){lines.push("","Examples:","","```bash",...command.examples,"```")}return lines.join(`
|
|
3
|
+
`)}export function renderBuddyCommandReference(inventory){const commands=[...inventory.commands].sort((a,b)=>a.name.localeCompare(b.name));if(inventory.total!==commands.length)throw new Error(`Buddy inventory total ${inventory.total} does not match ${commands.length} commands`);if(new Set(commands.map((command)=>command.name)).size!==commands.length)throw new Error("Buddy inventory contains duplicate canonical command names");const groups=new Map;for(const command of commands){const group=command.namespace||(command.name.includes(":")?command.name.split(":")[0]:"general");const entries=groups.get(group)||[];entries.push(command);groups.set(group,entries)}const groupSummary=[...groups.entries()].sort(([a],[b])=>a.localeCompare(b)).map(([group,entries])=>`| ${code(group)} | ${entries.length} |`);const document=["---","title: Buddy Command Reference","description: Generated reference for every Buddy command, argument, option, alias, default, and example.","---","<!-- Generated by storage/framework/core/buddy/src/commands/docs/buddy-commands.ts. Do not edit by hand. -->","","# Buddy Command Reference","",`This reference is generated from Buddy's runtime command registry and currently contains **${commands.length} commands**. Run \`bun run docs:buddy\` after changing the registry; CI rejects stale output.`,"","## Command groups","","| Group | Commands |","| --- | ---: |",...groupSummary,"","## Commands","",...commands.flatMap((command)=>[commandSection(command),""])].join(`
|
|
4
|
+
`);return`${document.split(`
|
|
5
5
|
`).map((line)=>line.trimEnd()).join(`
|
|
6
6
|
`).trimEnd()}
|
|
7
|
-
`}export function loadBuddyInventory(){const result=Bun.spawnSync([process.execPath,cliPath,"list","--json"],{cwd:root,env:{...process.env,NO_COLOR:"1"},stdout:"pipe",stderr:"pipe"})
|
|
7
|
+
`}export function loadBuddyInventory(){const result=Bun.spawnSync([process.execPath,cliPath,"list","--json"],{cwd:root,env:{...process.env,NO_COLOR:"1"},stdout:"pipe",stderr:"pipe"});const stdout=result.stdout.toString();const stderr=result.stderr.toString().trim();if(result.exitCode!==0)throw new Error(`Buddy command inventory failed (${result.exitCode}): ${stderr}`);const start=stdout.indexOf("{");const end=stdout.lastIndexOf("}");if(start===-1||end<=start){const noise=(stdout.trim()||stderr||"(no output)").split(`
|
|
8
8
|
`).slice(0,10).join(`
|
|
9
|
-
`);throw Error(`Buddy command inventory printed no JSON payload. \`buddy list --json\` said:
|
|
10
|
-
${noise}`)}let inventory;try{inventory=JSON.parse(stdout.slice(start,end+1))}catch(error){throw Error(`Buddy command inventory returned unparseable JSON: ${error.message}`)}if(!Array.isArray(inventory.commands)||!Number.isInteger(inventory.total))throw Error("Buddy command inventory returned an invalid payload");return inventory}export async function run(){assertFrameworkRepo(root,"docs:buddy");const mode=process.argv.includes("--write")?"write":process.argv.includes("--check")?"check":null;if(!mode){console.error("usage: bun storage/framework/core/buddy/src/commands/docs/buddy-commands.ts --write | --check");process.exit(2)}const expected=renderBuddyCommandReference(loadBuddyInventory());if(mode==="write"){mkdirSync(dirname(outputPath),{recursive
|
|
11
|
-
`)
|
|
12
|
-
`)
|
|
9
|
+
`);throw new Error(`Buddy command inventory printed no JSON payload. \`buddy list --json\` said:
|
|
10
|
+
${noise}`)}let inventory;try{inventory=JSON.parse(stdout.slice(start,end+1))}catch(error){throw new Error(`Buddy command inventory returned unparseable JSON: ${error.message}`)}if(!Array.isArray(inventory.commands)||!Number.isInteger(inventory.total))throw new Error("Buddy command inventory returned an invalid payload");return inventory}export async function run(){assertFrameworkRepo(root,"docs:buddy");const mode=process.argv.includes("--write")?"write":process.argv.includes("--check")?"check":null;if(!mode){console.error("usage: bun storage/framework/core/buddy/src/commands/docs/buddy-commands.ts --write | --check");process.exit(2)}const expected=renderBuddyCommandReference(loadBuddyInventory());if(mode==="write"){mkdirSync(dirname(outputPath),{recursive:true});writeFileSync(outputPath,expected);console.log(`Wrote ${outputPath}`)}else{if(!existsSync(outputPath))throw new Error("Buddy command reference is missing; run bun run docs:buddy");const current=readFileSync(outputPath,"utf8");if(current!==expected){const currentLines=current.split(`
|
|
11
|
+
`);const expectedLines=expected.split(`
|
|
12
|
+
`);const differences=[];for(let i=0;i<Math.max(currentLines.length,expectedLines.length)&&differences.length<6;i++){if(currentLines[i]!==expectedLines[i])differences.push(` line ${i+1}:
|
|
13
13
|
committed: ${JSON.stringify(currentLines[i]??"<end of file>")}
|
|
14
|
-
generated: ${JSON.stringify(expectedLines[i]??"<end of file>")}`)
|
|
14
|
+
generated: ${JSON.stringify(expectedLines[i]??"<end of file>")}`)}throw new Error(`Buddy command reference is stale; run bun run docs:buddy
|
|
15
15
|
${differences.join(`
|
|
16
16
|
`)}`)}console.log("Buddy command reference matches the runtime registry")}}if(import.meta.main)await run();
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{readFileSync,writeFileSync}from"node:fs";import{join}from"node:path";import process from"node:process";import{capabilityRegistry}from"@stacksjs/config/capabilities";import{INTERACTIVE_BEGIN,INTERACTIVE_END,loadProbeRecords,renderInteractiveCapabilities}from"@stacksjs/desktop-build/probe";import{assertFrameworkRepo}from"./framework-repo";const root=new URL("../../../../../../../",import.meta.url).pathname
|
|
2
|
-
`)}export const blocks=[{begin:BEGIN,end:END,render},{begin:INTERACTIVE_BEGIN,end:INTERACTIVE_END,render:()=>renderInteractiveCapabilities(loadProbeRecords())}];function current(block){let contents;try{contents=readFileSync(page,"utf8")}catch{return null}const start=contents.indexOf(block.begin)
|
|
1
|
+
import{readFileSync,writeFileSync}from"node:fs";import{join}from"node:path";import process from"node:process";import{capabilityRegistry}from"@stacksjs/config/capabilities";import{INTERACTIVE_BEGIN,INTERACTIVE_END,loadProbeRecords,renderInteractiveCapabilities}from"@stacksjs/desktop-build/probe";import{assertFrameworkRepo}from"./framework-repo";const root=new URL("../../../../../../../",import.meta.url).pathname;const page=join(root,"docs/features/capabilities.md");const BEGIN="<!-- capability-matrix:begin -->";const END="<!-- capability-matrix:end -->";const CATEGORIES=[["database","Database"],["queue","Queue"],["cache","Cache"],["storage","Storage"],["mail","Mail"],["realtime","Realtime"],["deploy","Deploy"]];const STATUS_NOTE={supported:"Contract evidence runs in CI.",partial:"Works, with the gaps named below.",experimental:"Usable, but without retained evidence.",unsupported:"Cannot be selected; configuring it fails loudly."};function row(driver){const evidence=driver.testEvidence.length===0?"none retained":driver.testEvidence.map((path)=>`\`${path.split("/").pop()}\``).join("<br>");const live=driver.liveServiceContract?`${driver.liveServiceContract.service} ${driver.liveServiceContract.version}`:"-";return`| \`${driver.name}\` | **${driver.status}** | ${driver.topology} | ${live} | ${evidence} |`}function section(category,heading){const drivers=capabilityRegistry.filter((driver)=>driver.category===category);if(drivers.length===0)return[];const limitations=drivers.flatMap((driver)=>driver.limitations.map((limitation)=>`- **\`${driver.name}\`** - ${limitation}`));return[`### ${heading}`,"","| Driver | Status | Topology | Live service | Evidence |","|---|---|---|---|---|",...drivers.map(row),"",...limitations.length>0?["**Limitations**","",...limitations,""]:[]]}function verifiedLine(){return["> **How current is this?** This table is generated from `capabilityRegistry`","> in `@stacksjs/config`, and `docs:capabilities:check` fails CI when the two","> disagree - so it is verified at every commit, not as of some date.",">","> The claims themselves are checked by `capabilities.test.ts`: every cited","> file must exist, anything short of `supported` must give a reason, and a","> `supported` driver on a remote topology must name the provider version it","> was proven against.",""]}export function render(){const statuses=Object.entries(STATUS_NOTE).map(([status,note])=>`- **${status}** - ${note}`);return[BEGIN,"","<!-- Generated by `buddy docs:capabilities` from `@stacksjs/config`'s"," `capabilityRegistry`. Edit that, not this. -->","",...statuses,"",...verifiedLine(),...CATEGORIES.flatMap(([category,heading])=>section(category,heading)),END].join(`
|
|
2
|
+
`)}export const blocks=[{begin:BEGIN,end:END,render},{begin:INTERACTIVE_BEGIN,end:INTERACTIVE_END,render:()=>renderInteractiveCapabilities(loadProbeRecords())}];function current(block){let contents;try{contents=readFileSync(page,"utf8")}catch{return null}const start=contents.indexOf(block.begin);const end=contents.indexOf(block.end);if(start===-1||end===-1)return null;return contents.slice(start,end+block.end.length)}function write(){const original=readFileSync(page,"utf8");let contents=original;for(const block of blocks){const start=contents.indexOf(block.begin);const end=contents.indexOf(block.end);if(start===-1||end===-1)throw new Error(`[docs:capabilities] ${page} is missing the ${block.begin} / ${block.end} markers`);contents=contents.slice(0,start)+block.render()+contents.slice(end+block.end.length)}if(contents===original)return false;writeFileSync(page,contents);return true}export async function run(){assertFrameworkRepo(root,"docs:capabilities");if(process.argv.includes("--write")){console.log(write()?"✓ rewrote the generated sections of docs/features/capabilities.md":"✓ the capability matrix was already current");return}const stale=blocks.filter((block)=>current(block)!==block.render());if(stale.length===0){console.log(`✓ the capability matrix is current (${capabilityRegistry.length} drivers, ${loadProbeRecords().length} desktop probe records)`);return}for(const block of stale){const source=block.begin===BEGIN?"capabilityRegistry":"the desktop probe records";console.error(current(block)===null?`✗ docs/features/capabilities.md is missing its ${block.begin} section`:`✗ docs/features/capabilities.md no longer matches ${source}`)}console.error("\nRun `buddy docs:capabilities` to rewrite it from its sources.");if(process.argv.includes("--check"))process.exit(1)}if(import.meta.main)await run();
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{readFileSync,writeFileSync}from"node:fs";import{join}from"node:path";import process from"node:process";import{desktopSupportMatrix}from"@stacksjs/desktop-build/support";import{assertFrameworkRepo}from"./framework-repo";const root=new URL("../../../../../../../",import.meta.url).pathname
|
|
2
|
-
`)}function current(){let contents;try{contents=readFileSync(page,"utf8")}catch{return null}const start=contents.indexOf(BEGIN)
|
|
1
|
+
import{readFileSync,writeFileSync}from"node:fs";import{join}from"node:path";import process from"node:process";import{desktopSupportMatrix}from"@stacksjs/desktop-build/support";import{assertFrameworkRepo}from"./framework-repo";const root=new URL("../../../../../../../",import.meta.url).pathname;const page=join(root,"docs/packages/desktop.md");const BEGIN="<!-- desktop-support-matrix:begin -->";const END="<!-- desktop-support-matrix:end -->";const PLATFORM_NAMES={darwin:"macOS",linux:"Linux",win32:"Windows"};function link(url){const issue=url.match(/github\.com\/([^/]+\/[^/]+)\/issues\/(\d+)/);if(issue)return`[${issue[1]}#${issue[2]}](${url})`;const run=url.match(/actions\/runs\/(\d+)/);if(run)return`[run ${run[1]}](${url})`;return`[evidence](${url})`}function row(entry){const cells=[`${PLATFORM_NAMES[entry.platform]} ${entry.architecture}`,`**${entry.status}**`,entry.osVersions.join(", "),entry.packageFormat,entry.signing,entry.notarization,entry.installLaunchEvidence?link(entry.installLaunchEvidence):"none",entry.blockingIssues.map(link).join(", ")||"none"];return`| ${cells.join(" | ")} |`}export function render(){const header=["| Target | Status | Tested on | Package | Signing | Notarization | Install + launch | Blocked by |","|---|---|---|---|---|---|---|---|"];const limitations=desktopSupportMatrix.flatMap((entry)=>entry.limitations.map((limitation)=>`- **${PLATFORM_NAMES[entry.platform]} ${entry.architecture}** - ${limitation}`));const unique=[...new Set(limitations)];return[BEGIN,"","<!-- Generated by `buddy docs:desktop-matrix` from `@stacksjs/desktop-build`'s"," `desktopSupportMatrix`. Edit that, not this. -->","",...header,...desktopSupportMatrix.map(row),"","### Known limitations","",...unique,"",END].join(`
|
|
2
|
+
`)}function current(){let contents;try{contents=readFileSync(page,"utf8")}catch{return null}const start=contents.indexOf(BEGIN);const end=contents.indexOf(END);if(start===-1||end===-1)return null;return contents.slice(start,end+END.length)}function write(){const contents=readFileSync(page,"utf8");const start=contents.indexOf(BEGIN);const end=contents.indexOf(END);if(start===-1||end===-1)throw new Error(`[docs:desktop-matrix] ${page} is missing the ${BEGIN} / ${END} markers`);const next=contents.slice(0,start)+render()+contents.slice(end+END.length);if(next===contents)return false;writeFileSync(page,next);return true}export async function run(){assertFrameworkRepo(root,"docs:desktop-matrix");if(process.argv.includes("--write")){console.log(write()?"✓ rewrote the desktop support matrix in docs/packages/desktop.md":"✓ the desktop support matrix was already current");return}const published=current();if(published===render()){console.log(`✓ the desktop support matrix is current (${desktopSupportMatrix.length} targets)`);return}console.error(published===null?"✗ docs/packages/desktop.md is missing its generated support-matrix section":"✗ docs/packages/desktop.md no longer matches desktopSupportMatrix");console.error("\nRun `buddy docs:desktop-matrix` to rewrite it from the source.");if(process.argv.includes("--check"))process.exit(1)}if(import.meta.main)await run();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync}from"node:fs";import{isAbsolute,relative,resolve}from"node:path";export function isInsideRoot(root,cwd){const rel=relative(resolve(root),resolve(cwd));return rel===""||!rel.startsWith("..")&&!isAbsolute(rel)}export function looksLikeFrameworkRepo(root){return existsSync(resolve(root,"storage/framework/core/buddy"))}export function assertFrameworkRepo(root,command,cwd=process.cwd()){if(looksLikeFrameworkRepo(root)&&isInsideRoot(root,cwd))return;throw Error(`${command} operates on the Stacks framework repository and would write to ${root}, which is not where you are (${cwd}). Run it from a framework checkout; an application has no generated framework artifacts to check.`)}
|
|
1
|
+
import{existsSync}from"node:fs";import{isAbsolute,relative,resolve}from"node:path";export function isInsideRoot(root,cwd){const rel=relative(resolve(root),resolve(cwd));return rel===""||!rel.startsWith("..")&&!isAbsolute(rel)}export function looksLikeFrameworkRepo(root){return existsSync(resolve(root,"storage/framework/core/buddy"))}export function assertFrameworkRepo(root,command,cwd=process.cwd()){if(looksLikeFrameworkRepo(root)&&isInsideRoot(root,cwd))return;throw new Error(`${command} operates on the Stacks framework repository and would write to ${root}, `+`which is not where you are (${cwd}). `+`Run it from a framework checkout; an application has no generated framework artifacts to check.`)}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{readFileSync,writeFileSync}from"node:fs";import{resolve}from"node:path";import{assertFrameworkRepo}from"./framework-repo";async function generators(){const{renderApiClient,generateOpenApi,renderOpenApiTypes}=await import("@stacksjs/api");return{renderApiClient,generateOpenApi,renderOpenApiTypes}}const root=resolve(import.meta.dir,"../../../../../../..")
|
|
2
|
-
`));return{openApi:JSON.stringify(document,null,2),apiTypes:renderOpenApiTypes(document),client:renderApiClient(document,{name:document.info?.title})}}async function write(){const expected=await expectedArtifacts();writeFileSync(openApiPath,expected.openApi);writeFileSync(apiTypesPath,expected.apiTypes);writeFileSync(clientPath,expected.client);console.log("Generated OpenAPI, API type and client artifacts")}async function check(){const expected=await expectedArtifacts()
|
|
1
|
+
import{readFileSync,writeFileSync}from"node:fs";import{resolve}from"node:path";import{assertFrameworkRepo}from"./framework-repo";async function generators(){const{renderApiClient,generateOpenApi,renderOpenApiTypes}=await import("@stacksjs/api");return{renderApiClient,generateOpenApi,renderOpenApiTypes}}const root=resolve(import.meta.dir,"../../../../../../..");const openApiPath=resolve(root,"storage/framework/api/openapi.json");const apiTypesPath=resolve(root,"storage/framework/api/api-types.ts");const clientPath=resolve(root,"storage/framework/api/client.ts");export function validateOpenApi(document){const errors=[];const paths=Object.entries(document.paths||{});if(paths.length<10)errors.push("OpenAPI document has fewer than 10 registered paths");const operationIds=new Set;for(const[route,item]of paths){for(const method of["get","put","post","delete","options","head","patch","trace"]){const operation=item[method];if(!operation)continue;if(!operation.operationId)errors.push(`${method.toUpperCase()} ${route}: operationId is missing`);else if(operationIds.has(operation.operationId))errors.push(`${method.toUpperCase()} ${route}: duplicate operationId ${operation.operationId}`);else operationIds.add(operation.operationId);for(const parameter of[...item.parameters??[],...operation.parameters??[]]){if("in"in parameter&¶meter.in==="path"&&!parameter.required)errors.push(`${method.toUpperCase()} ${route}: path parameter ${parameter.name} must be required`)}}}return errors}async function expectedArtifacts(){process.env.STACKS_CANONICAL_FEATURES="1";const{renderApiClient,generateOpenApi,renderOpenApiTypes}=await generators();const document=await generateOpenApi({write:false});const errors=validateOpenApi(document);if(errors.length)throw new Error(errors.join(`
|
|
2
|
+
`));return{openApi:JSON.stringify(document,null,2),apiTypes:renderOpenApiTypes(document),client:renderApiClient(document,{name:document.info?.title})}}async function write(){const expected=await expectedArtifacts();writeFileSync(openApiPath,expected.openApi);writeFileSync(apiTypesPath,expected.apiTypes);writeFileSync(clientPath,expected.client);console.log("Generated OpenAPI, API type and client artifacts")}async function check(){const expected=await expectedArtifacts();const errors=[];if(readFileSync(openApiPath,"utf8")!==expected.openApi)errors.push("storage/framework/api/openapi.json is stale");if(readFileSync(apiTypesPath,"utf8")!==expected.apiTypes)errors.push("storage/framework/api/api-types.ts is stale");if(readFileSync(clientPath,"utf8")!==expected.client)errors.push("storage/framework/api/client.ts is stale");if(errors.length)throw new Error(`${errors.join(`
|
|
3
3
|
`)}
|
|
4
4
|
Run bun run docs:artifacts and review the generated diff.`);console.log(`Generated API artifacts are current (${Object.keys(JSON.parse(expected.openApi).paths).length} paths)`)}export async function run(){assertFrameworkRepo(root,"docs:artifacts");try{if(process.argv.includes("--write"))await write();else if(process.argv.includes("--check"))await check();else{console.error("usage: bun storage/framework/core/buddy/src/commands/docs/generated-artifacts.ts --write | --check");process.exit(2)}}catch(error){console.error(error instanceof Error?error.message:String(error));process.exit(1)}}if(import.meta.main)await run();
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{assertFrameworkRepo}from"./framework-repo";import{execFileSync}from"node:child_process";import{existsSync,readdirSync,readFileSync,statSync}from"node:fs";import{dirname,join,relative,resolve,sep}from"node:path";const root=resolve(import.meta.dir,"../../../../../../..")
|
|
2
|
-
`);let inFence
|
|
1
|
+
import{assertFrameworkRepo}from"./framework-repo";import{execFileSync}from"node:child_process";import{existsSync,readdirSync,readFileSync,statSync}from"node:fs";import{dirname,join,relative,resolve,sep}from"node:path";const root=resolve(import.meta.dir,"../../../../../../..");const docsDir=resolve(root,"docs");const INLINE_LINK=/\[[^\]]*\]\(([^)]+)\)/g;export function selfRepoPath(target){const match=target.match(/^https:\/\/github\.com\/stacksjs\/stacks\/(?:blob|tree|raw)\/[^/]+\/(.+)$/i);if(!match)return null;return match[1].split("#")[0].split("?")[0]}let tracked=null;function trackedFiles(){if(tracked)return tracked;try{const listing=execFileSync("git",["ls-files","-z"],{cwd:root,encoding:"utf8",maxBuffer:64*1024*1024});tracked=new Set(listing.split("\x00").filter(Boolean))}catch{tracked=null;return{has:(path)=>existsSync(resolve(root,path)),[Symbol.iterator]:function*(){}}}return tracked}const listings=new Map;function entriesOf(dir){let entries=listings.get(dir);if(!entries){entries=existsSync(dir)?new Set(readdirSync(dir)):new Set;listings.set(dir,entries)}return entries}export function isFileCaseExact(path,from=root){const relativePath=relative(from,path);if(relativePath.startsWith(".."))return existsSync(path)&&statSync(path).isFile();let dir=from;for(const segment of relativePath.split(sep)){if(!entriesOf(dir).has(segment))return false;dir=join(dir,segment)}return statSync(path).isFile()}export function isTrackedPath(path,files=trackedFiles()){if(files.has(path))return true;const asDirectory=`${path.replace(/\/+$/,"")}/`;for(const tracked of files){if(tracked.startsWith(asDirectory))return true}return false}export function isSkippableLink(target){return target===""||target.startsWith("#")||/^[a-z][\w+.-]*:/i.test(target)||target.startsWith("//")||target.startsWith("{{")||target.includes("<")}export function extractLinks(content){const out=[];const withoutComments=content.replace(/<!--[\s\S]*?-->/g,(match)=>match.replace(/[^\n]/g," "));const lines=withoutComments.split(`
|
|
2
|
+
`);let inFence=false;for(let index=0;index<lines.length;index++){const raw=lines[index];if(/^\s*(```|~~~)/.test(raw)){inFence=!inFence;continue}if(inFence)continue;const line=raw.replace(/`[^`]*`/g,"");for(const match of line.matchAll(INLINE_LINK)){let target=match[1].trim();const space=target.search(/\s/);if(space!==-1)target=target.slice(0,space);out.push({target,line:index+1})}}return out}function candidatesUnder(base,clean,staticRoot){const candidates=[base];if(!/\.\w+$/.test(clean)){candidates.push(...staticRoot?[`${base}.html`,join(base,"index.html")]:[`${base}.md`,join(base,"index.md")])}else if(clean.endsWith(".html")&&!staticRoot){candidates.push(base.replace(/\.html$/,".md"),join(base.replace(/\.html$/,""),"index.md"))}return candidates}export function resolveCandidates(target,fileDir,docsRoot){const clean=target.split("#")[0].split("?")[0];if(!clean)return[];if(!clean.startsWith("/"))return candidatesUnder(resolve(fileDir,clean),clean,false);return[...candidatesUnder(join(docsRoot,clean.slice(1)),clean,false),...candidatesUnder(join(docsRoot,"public",clean.slice(1)),clean,true)]}function walkMarkdown(dir){const files=[];for(const entry of readdirSync(dir,{withFileTypes:true})){const full=join(dir,entry.name);if(entry.isDirectory()){if(entry.name==="node_modules"||entry.name.startsWith("."))continue;files.push(...walkMarkdown(full))}else if(entry.name.endsWith(".md")){files.push(full)}}return files}export function checkDocsLinks(docsRoot=docsDir){const broken=[];for(const file of walkMarkdown(docsRoot)){const content=readFileSync(file,"utf8");for(const{target,line}of extractLinks(content)){const selfPath=selfRepoPath(target);if(selfPath!==null){if(!isTrackedPath(selfPath))broken.push({file:relative(docsRoot,file),line,target});continue}if(isSkippableLink(target))continue;const candidates=resolveCandidates(target,dirname(file),docsRoot);if(candidates.length===0)continue;const resolvedOk=candidates.some((candidate)=>isFileCaseExact(candidate));if(!resolvedOk)broken.push({file:relative(docsRoot,file),line,target})}}return broken}export async function run(){assertFrameworkRepo(root,"docs:links");const broken=checkDocsLinks();if(broken.length===0){console.log("✓ All internal documentation links resolve.")}else{console.error(`✗ ${broken.length} broken internal documentation link(s):`);for(const link of broken)console.error(` ${link.file}:${link.line} -> ${link.target}`);if(process.argv.includes("--check"))process.exit(1)}}if(import.meta.main)await run();
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{existsSync,readFileSync,readdirSync,statSync,writeFileSync}from"node:fs";import{dirname,join,relative}from"node:path";import process from"node:process";import{capabilityRegistry}from"@stacksjs/config/capabilities";import{FEATURE_NAMES}from"@stacksjs/features/names";import{assertFrameworkRepo}from"./framework-repo";const root=new URL("../../../../../../../",import.meta.url).pathname
|
|
1
|
+
import{existsSync,readFileSync,readdirSync,statSync,writeFileSync}from"node:fs";import{dirname,join,relative}from"node:path";import process from"node:process";import{capabilityRegistry}from"@stacksjs/config/capabilities";import{FEATURE_NAMES}from"@stacksjs/features/names";import{assertFrameworkRepo}from"./framework-repo";const root=new URL("../../../../../../../",import.meta.url).pathname;const core="storage/framework/core";const destination="storage/framework/defaults/ai/skills/stacks-native";const PACKAGE_SKILLS={"action-runner":"stacks-actions","calendar-api":"stacks-calendar",defaults:"stacks-build",github:"stacks-git","model-meta":"stacks-models",tinker:"stacks-repl"};function localSource(projectRoot,entry,specifier){const path=join(dirname(entry),specifier);const stem=path.replace(/\.js$/,"");const candidates=[path,`${stem}.ts`,`${stem}.tsx`,join(path,"index.ts")];const resolved=candidates.find((candidate)=>existsSync(join(projectRoot,candidate))&&statSync(join(projectRoot,candidate)).isFile());if(!resolved)throw new Error(`Native catalog cannot resolve ${specifier} from ${entry}`);return resolved}export function nativePackageCatalog(projectRoot=root){const scanner=new Bun.Transpiler({loader:"ts"});return readdirSync(join(projectRoot,core)).filter((slug)=>existsSync(join(projectRoot,core,slug,"package.json"))).sort().map((slug)=>{const directory=join(core,slug);const manifest=JSON.parse(readFileSync(join(projectRoot,directory,"package.json"),"utf8"));const skill=PACKAGE_SKILLS[slug]??`stacks-${slug}`;if(!existsSync(join(projectRoot,"storage/framework/defaults/ai/skills",skill,"SKILL.md")))throw new Error(`Native package ${manifest.name} needs a skill or an explicit package-to-skill mapping`);const source=join(directory,"src/index.ts");const entry=existsSync(join(projectRoot,source))?source:join(directory,"package.json");const scan=entry.endsWith(".ts")?scanner.scan(readFileSync(join(projectRoot,entry),"utf8")):undefined;const tests=existsSync(join(projectRoot,directory,"tests"))?[...new Bun.Glob("**/*.{test,spec}.{ts,tsx,js}").scanSync({cwd:join(projectRoot,directory,"tests"),onlyFiles:true})].sort().map((file)=>join(directory,"tests",file)):[];return{name:manifest.name,directory,skill,entry,exports:scan?.exports.sort()??[],dependencies:[...new Set(scan?.imports.map((item)=>item.path).filter((path)=>path.startsWith("."))??[])].map((path)=>localSource(projectRoot,entry,path)).sort(),tests}})}function sourceLink(path,label=path){return`[${label}](https://github.com/stacksjs/stacks/blob/main/${path})`}export function renderNativeCatalog(projectRoot=root){const packages=nativePackageCatalog(projectRoot);return["# Native Stacks package catalog","","<!-- Generated by buddy docs:native-skills. Edit source packages or the mapping, then regenerate. -->","","This indexes every current core package. It describes source surfaces and","retained tests, not a promise that every export or remote provider is fully","supported. Read the selected skill and implementation before choosing an API.","Wildcard re-exports and type-only exports are not expanded by the source scan.","Browser runtime bindings are documented separately in `stacks-auto-imports`.","","| Package | Task guidance | Source entry | Retained tests |","|---|---|---|---|",...packages.map((entry)=>`| \`${entry.name}\` | [\`${entry.skill}\`](../${entry.skill}/SKILL.md) | ${sourceLink(entry.entry,"entrypoint")} | ${entry.tests.length} |`),"","## Source surfaces","","Use these pointers to discover the current implementation and exact signatures.","An exported name is not evidence that an operation supports every driver.","",...packages.flatMap((entry)=>[`### ${entry.name}`,"",`Guidance: [\`${entry.skill}\`](../${entry.skill}/SKILL.md). Source: ${sourceLink(entry.entry)}.`,"",entry.exports.length?`Declared runtime exports: ${entry.exports.map((name)=>`\`${name}\``).join(", ")}.`:"Read the entrypoint and package export map for re-exported or type-only surfaces.","",...entry.dependencies.length?[`Local source modules: ${entry.dependencies.map((path)=>sourceLink(path,relative(entry.directory,path))).join(", ")}.`,""]:[],...entry.tests.length?[`Evidence directory: ${sourceLink(`${entry.directory}/tests`,`${entry.tests.length} retained tests`)}. These files are evidence pointers, not a claim that all tests were run for this catalog.`,""]:[]])].join(`
|
|
2
2
|
`)}export function renderDriverCapabilities(){return["# Driver evidence and limitations","","<!-- Generated by buddy docs:native-skills from capabilityRegistry. -->","","The registry distinguishes supported, partial, experimental, and unsupported","drivers. Unknown and unsupported selections fail. Partial and experimental","drivers remain subject to the limitations below. Read prerequisites before","deploying; a configuration type does not establish an implemented transport.","",...capabilityRegistry.flatMap((driver)=>[`## ${driver.category}: ${driver.name}`,"",`Status: **${driver.status}**. Topology: ${driver.topology}.`,"",...driver.implementation?[`Implementation: ${sourceLink(driver.implementation)}.`,""]:[],...driver.prerequisites.length?["Prerequisites:","",...driver.prerequisites.map((value)=>`- ${value}`),""]:[],...driver.limitations.length?["Limitations:","",...driver.limitations.map((value)=>`- ${value}`),""]:[],...driver.testEvidence.length?["Retained evidence:","",...driver.testEvidence.map((path)=>`- ${sourceLink(path)}`),""]:[]]),"## Optional application bundles","",`Installable bundle names: ${FEATURE_NAMES.map((name)=>`\`${name}\``).join(", ")}.`,"","Read `stacks-features` for installation, config gates, route bundles, and","migration selection. These are distinct from user-targeted feature flags.",""].join(`
|
|
3
|
-
`).replace(/[\u2014\u2013]/g,"-")}export async function run(){assertFrameworkRepo(root,"docs:native-skills");const
|
|
3
|
+
`).replace(/[\u2014\u2013]/g,"-")}export async function run(){assertFrameworkRepo(root,"docs:native-skills");const outputs=[{path:join(root,destination,"CATALOG.md"),body:renderNativeCatalog()},{path:join(root,destination,"CAPABILITIES.md"),body:renderDriverCapabilities()}];const stale=outputs.filter((file)=>!existsSync(file.path)||readFileSync(file.path,"utf8")!==file.body);if(process.argv.includes("--write")){for(const file of stale)writeFileSync(file.path,file.body,"utf8");console.log(`Native skill references refreshed: ${stale.length} file(s).`)}else if(stale.length){console.error(`Native skill references are stale: ${stale.map((file)=>relative(root,file.path)).join(", ")}. Run ./buddy docs:native-skills.`);process.exitCode=1}else{console.log("Native skill package coverage and driver evidence are current.")}}if(import.meta.main)await run();
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{mkdirSync,readdirSync,readFileSync,rmSync,writeFileSync}from"node:fs";import{createHash}from"node:crypto";import{join}from"node:path";import process from"node:process";import{assertFrameworkRepo}from"./framework-repo";const root=new URL("../../../../../../../",import.meta.url).pathname
|
|
2
|
-
`);let inside
|
|
1
|
+
import{mkdirSync,readdirSync,readFileSync,rmSync,writeFileSync}from"node:fs";import{createHash}from"node:crypto";import{join}from"node:path";import process from"node:process";import{assertFrameworkRepo}from"./framework-repo";const root=new URL("../../../../../../../",import.meta.url).pathname;const docsDir=join(root,"docs");const workDir=join(root,"storage/framework/runtime/docs-imports");const baselinePath=join(root,"docs/.snippet-imports-baseline.json");const FENCE=/^```(?:ts|typescript)\b/;export function extractImports(file,contents){const found=[];const lines=contents.split(`
|
|
2
|
+
`);let inside=false;let pending=null;const specifierOf=(text)=>text.match(/from\s+['"]([^'"]+)['"]/)?.[1]??text.match(/^\s*import\s+['"]([^'"]+)['"]/)?.[1];const finish=(entry)=>{const specifier=specifierOf(entry.text);if(specifier&&!specifier.startsWith("."))found.push({file,line:entry.line,text:entry.text.trim(),specifier})};for(const[index,raw]of lines.entries()){if(raw.startsWith("```")){inside=!inside&&FENCE.test(raw.trim());pending=null;continue}if(!inside)continue;if(pending){pending.text+=`
|
|
3
3
|
${raw.trimEnd()}`;if(specifierOf(pending.text)){finish(pending);pending=null}else if(pending.text.split(`
|
|
4
|
-
`).length>12)pending=null
|
|
4
|
+
`).length>12){pending=null}continue}if(!/^\s*import\s/.test(raw))continue;const entry={line:index+1,text:raw.trimEnd()};if(specifierOf(entry.text))finish(entry);else pending=entry}return found}function markdownFiles(dir){return readdirSync(dir,{withFileTypes:true}).sort((a,b)=>a.name.localeCompare(b.name)).flatMap((entry)=>{const full=join(dir,entry.name);if(entry.isDirectory())return markdownFiles(full);return entry.name.endsWith(".md")?[full]:[]})}export function collectImports(){return markdownFiles(docsDir).flatMap((file)=>extractImports(file.slice(root.length),readFileSync(file,"utf8")))}export function findingKey(finding){return`${finding.file} :: ${finding.specifier} :: ${finding.message}`}export function inScope(specifier,code){if(code!=="TS2307")return true;return specifier.startsWith("@stacksjs/")}export function generatedTsconfig(){return{extends:"../../tsconfig.framework.json",compilerOptions:{noEmit:true,skipLibCheck:true,noUnusedLocals:false,isolatedDeclarations:false,verbatimModuleSyntax:false},include:["./*.js"],exclude:[]}}function compile(imports){rmSync(workDir,{force:true,recursive:true});mkdirSync(workDir,{recursive:true});const byName=new Map;for(const entry of imports){const name=`i${createHash("sha1").update(entry.text).digest("hex").slice(0,16)}`;const existing=byName.get(name);if(existing){existing.push(entry);continue}byName.set(name,[entry]);writeFileSync(join(workDir,`${name}.ts`),`${entry.text}
|
|
5
5
|
export {}
|
|
6
6
|
`)}writeFileSync(join(workDir,"tsconfig.json"),`${JSON.stringify(generatedTsconfig(),null,2)}
|
|
7
|
-
`);const proc=Bun.spawnSync(["bunx","--bun","tsc","--noEmit","-p",workDir],{cwd:root,stdout:"pipe",stderr:"pipe"})
|
|
8
|
-
`)){const match=line.match(/docs-imports\/(i[0-9a-f]+)\.ts.*?error (TS\d+): (.*)$/);if(!match)continue;const occurrences=byName.get(match[1]);if(!occurrences||occurrences.length===0)continue;if(!inScope(occurrences[0].specifier,match[2]))continue;for(const entry of occurrences)findings.push({file:entry.file,line:entry.line,specifier:entry.specifier,code:match[2],message:match[3].trim()})}rmSync(workDir,{force
|
|
9
|
-
`);console.log(
|
|
7
|
+
`);const proc=Bun.spawnSync(["bunx","--bun","tsc","--noEmit","-p",workDir],{cwd:root,stdout:"pipe",stderr:"pipe"});const output=`${proc.stdout.toString()}${proc.stderr.toString()}`;const findings=[];for(const line of output.split(`
|
|
8
|
+
`)){const match=line.match(/docs-imports\/(i[0-9a-f]+)\.ts.*?error (TS\d+): (.*)$/);if(!match)continue;const occurrences=byName.get(match[1]);if(!occurrences||occurrences.length===0)continue;if(!inScope(occurrences[0].specifier,match[2]))continue;for(const entry of occurrences){findings.push({file:entry.file,line:entry.line,specifier:entry.specifier,code:match[2],message:match[3].trim()})}}rmSync(workDir,{force:true,recursive:true});return findings}function readBaseline(){try{return JSON.parse(readFileSync(baselinePath,"utf8")).known??[]}catch{return[]}}export async function run(){assertFrameworkRepo(root,"docs:snippets");const imports=collectImports();const findings=compile(imports);const baseline=new Set(readBaseline());const keys=findings.map(findingKey);if(process.argv.includes("--write")){writeFileSync(baselinePath,`${JSON.stringify({comment:"Known docs-import failures. Empty as of stacksjs/stacks#2581 - every documented import compiles. A new entry here is a regression, not a backlog item: fix the sample instead. See stacksjs/stacks#2580.",known:[...new Set(keys)].sort()},null,2)}
|
|
9
|
+
`);console.log(`✓ recorded ${new Set(keys).size} known docs-import failure(s) across ${imports.length} import(s)`);return}const fresh=findings.filter((finding)=>!baseline.has(findingKey(finding)));const fixed=[...baseline].filter((entry)=>!new Set(keys).has(entry));if(fresh.length===0){const trailer=fixed.length>0?` (${fixed.length} baselined failure(s) now fixed - run \`buddy docs:snippets\` to shorten the baseline)`:"";console.log(`✓ no new docs-import failures across ${imports.length} import(s)${trailer}`);return}console.error(`✗ ${fresh.length} documented import(s) do not compile:`);for(const finding of fresh)console.error(` ${finding.file}:${finding.line} ${finding.specifier}
|
|
10
10
|
${finding.message}`);console.error("\nFix the sample, or run `buddy docs:snippets` to record it if it is expected.");if(process.argv.includes("--check"))process.exit(1)}if(import.meta.main)await run();
|
package/dist/commands/doctor.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{existsSync,lstatSync,readFileSync,readlinkSync}from"node:fs";import{resolve}from"node:path";import process from"node:process";import{bold,dim,green,intro,log,onUnknownSubcommand,red,yellow}from"@stacksjs/cli";import{feature}from"@stacksjs/config";import{inspectDefaultsProvenance,installedDefaultsVersion,path,usesVendoredDefaults}from"@stacksjs/path";import{storage}from"@stacksjs/storage";import{isSupportedBunVersion,isVersionGreaterThanOrEqual,minimumBunVersion}from"@stacksjs/utils";import{FEATURE_NAMES,featurePathsPresent}from"./features";const minimumSqliteVersion="3.47.2";class ProbeWarning extends Error{}async function probe(checks,name,fn,timeoutMs=2000){const start=Date.now()
|
|
2
|
-
`).join("; ")}. Point each route at an action that exists, or delete it. \`buddy upgrade\` removes the ones the scaffold wrote.`)});await probe(checks,"Security overrides",async()=>{const{findShadowedSecurityDefaults,frameworkDefaultsDir,SHADOWED_DEFAULT_REVIEW_MARKER}=await import("@stacksjs/server"),defaultsDir=frameworkDefaultsDir("app");if(!defaultsDir)return"No framework defaults to compare against";const shadowed=findShadowedSecurityDefaults(path.appPath(),defaultsDir);if(shadowed.length===0)return"No app/ file shadows a framework security default";const identical=shadowed.filter((entry)=>entry.kind==="identical").map((entry)=>`app/${entry.path}`),modified=shadowed.filter((entry)=>entry.kind==="modified").map((entry)=>`app/${entry.path} (${SHADOWED_DEFAULT_REVIEW_MARKER} ${entry.fingerprint})`);throw new ProbeWarning([identical.length?`Unchanged copies, delete to receive security fixes: ${identical.join(", ")}.`:"",modified.length?`Differ from the current default, review and mark reviewed: ${modified.join(", ")}.`:""].filter(Boolean).join(" "))});const bunVersion=process.versions.bun;if(bunVersion&&isSupportedBunVersion(bunVersion))checks.push({name:"Bun Runtime",status:"pass",message:`v${bunVersion}`});else if(bunVersion)checks.push({name:"Bun Runtime",status:"fail",message:`v${bunVersion} (requires v${minimumBunVersion} or later, run: bun upgrade)`});else checks.push({name:"Bun Runtime",status:"fail",message:"Not found"});try{const pinnedBun=(await storage.readPackageJson("./package.json")).engines?.bun;if(pinnedBun&&bunVersion&&bunVersion!==pinnedBun)checks.push({name:"Pinned Bun",status:"warn",message:`v${bunVersion} is not the pinned v${pinnedBun} (engines.bun). Installing rewrites bun.lock - use \`./pantry/.bin/bun install\`, the pinned toolchain this checkout already carries, and \`git checkout -- bun.lock\` if it already changed.`});else if(pinnedBun&&bunVersion)checks.push({name:"Pinned Bun",status:"pass",message:`v${bunVersion} matches engines.bun`})}catch{}const nodeVersion=process.versions.node;if(nodeVersion)if(Number.parseInt(nodeVersion.split(".")[0]||"0",10)>=18)checks.push({name:"Node.js",status:"pass",message:`v${nodeVersion}`});else checks.push({name:"Node.js",status:"warn",message:`v${nodeVersion} (v18+ recommended)`});try{const pkg=await storage.readPackageJson("./package.json");if(pkg.name)checks.push({name:"package.json",status:"pass",message:`Found: ${pkg.name}`})}catch{checks.push({name:"package.json",status:"fail",message:"Not found in current directory"})}try{await storage.readTextFile(".env");checks.push({name:".env file",status:"pass",message:"Found"})}catch{checks.push({name:".env file",status:"warn",message:"Not found (optional)"})}const appKey=process.env.APP_KEY;if(appKey&&appKey.length>0)checks.push({name:"APP_KEY",status:appKey.length>=32?"pass":"warn",message:appKey.length>=32?"Set (\u226532 chars)":`Set but short (${appKey.length} chars; \u226532 recommended)`});else checks.push({name:"APP_KEY",status:"fail",message:"Not set - features that depend on it (encrypted columns, signed URLs, env decryption) will refuse to run. Run `buddy key:generate`."});await probe(checks,"SQLite Engine",async()=>{const{Database}=await import("bun:sqlite"),memory=new Database(":memory:");let version;try{const row=memory.query("SELECT sqlite_version() AS version").get();if(typeof row?.version==="string")version=row.version}finally{memory.close()}if(!version)throw new ProbeWarning("could not read sqlite_version() (skipped)");if(!isVersionGreaterThanOrEqual(version,minimumSqliteVersion))throw Error(`v${version} is below the required v${minimumSqliteVersion} (system.sqlite in package.json); upgrade Bun for a newer bundled SQLite`);return`v${version}`});await probe(checks,"Database",async()=>{const{db}=await import("@stacksjs/database"),unsafe=db.unsafe;if(typeof unsafe!=="function")throw new ProbeWarning("driver exposes no raw query method (skipped)");const statement=unsafe("SELECT 1");if(!statement||typeof statement.then!=="function"&&typeof statement.execute!=="function")throw new ProbeWarning("driver returned a non-executable statement (skipped)");const result=typeof statement.execute==="function"?await statement.execute():await statement;if(result===void 0||result===null)throw Error("probe query returned no result");if(Array.isArray(result)&&result.length===0)throw Error("probe query returned no rows");return"Reachable"});await probe(checks,"Database FKs",async()=>{const{auditForeignKeys}=await import("@stacksjs/database"),result=await auditForeignKeys();if(result.declared.length===0)return"No belongsTo declarations";const skipped=result.absentTable.length>0?`, ${result.absentTable.length} on tables not migrated`:"";if(result.missing.length===0)return`${result.declared.length} declared FKs all present${skipped}`;const sample=result.missing.slice(0,5).map((fk)=>`${fk.fromTable}.${fk.fromColumn} \u2192 ${fk.toTable}.${fk.toColumn}`).join(", "),more=result.missing.length>5?` (+${result.missing.length-5} more)`:"";throw Error(`${result.missing.length}/${result.declared.length} declared FKs missing from live schema: ${sample}${more}${skipped}. Run \`buddy migrate:fresh\` (will reset data) or \`buddy migrate\` against a clean DB.`)});await probe(checks,"Unique indexes",async()=>{const{auditUniqueIndexes}=await import("@stacksjs/database"),result=await auditUniqueIndexes();if(!result.supported)return"Dialect not audited (skipped)";const skipped=result.skippedTables.length>0?`, ${result.skippedTables.length} tables skipped (not migrated)`:"";if(result.missing.length===0)return`${result.declared.length} declared unique constraints all indexed${skipped}`;const sample=result.missing.slice(0,5).map((u)=>`${u.table}.${u.columns.join("+")}`).join(", "),more=result.missing.length>5?` (+${result.missing.length-5} more)`:"",first=result.missing[0];if(!first)throw Error("Unique-index audit reported missing entries without details");const example=`CREATE UNIQUE INDEX IF NOT EXISTS "${first.table}_${first.columns.join("_")}_unique" ON "${first.table}" ("${first.columns.join('", "')}")`;throw Error(`${result.missing.length}/${result.declared.length} declared unique constraints have no UNIQUE index: ${sample}${more}. Run \`buddy migrate\` (re-queues missing unique-index migrations, #1952) - dedupe duplicate rows first or migrate hard-fails; if no migration file exists run \`buddy generate:migrations\`, or create manually: ${example}`)},1e4);await probe(checks,"Migration ledger",async()=>{const{auditMigrationLedger}=await import("@stacksjs/database"),result=await auditMigrationLedger();if(!result.supported)return"Dialect not audited (skipped)";if(result.entries.length===0)return"No migration files";const{counts,orphans}=result;if(!result.drift)return`${result.entries.length} migrations, ledger consistent with the schema`;const parts=[];if(counts.stranded>0)parts.push(`${counts.stranded} applied but unrecorded (would re-run)`);if(counts.partial>0)parts.push(`${counts.partial} half-applied`);if(counts.reverted>0)parts.push(`${counts.reverted} recorded but missing from the schema`);if(orphans.length>0)parts.push(`${orphans.length} ledger row(s) with no file on disk`);const needsReapply=counts.reverted+counts.partial,repair=needsReapply>0?`\`buddy migrate:status --reconcile\` cannot repair ${needsReapply} of these - it never runs migration SQL, so it skips anything the schema is missing. Those need re-applying: \`buddy migrate:fresh\` (rebuilds from the corpus, RESETS DATA), or restore the database and re-run the missing files by hand.`:"Repair with `buddy migrate:status --reconcile`.";throw Error(`Migration ledger has drifted: ${parts.join(", ")}. Inspect with \`buddy migrate:status\`. ${repair}`)},1e4);await probe(checks,"FK orphans",async()=>{const{findFkOrphans}=await import("@stacksjs/database"),result=await findFkOrphans();if(!result.supported)return"Dialect not audited (skipped)";if(result.total===0)return"No orphan rows (PRAGMA foreign_key_check clean)";const sample=result.orphans.slice(0,5).map((o)=>`${o.table}.${o.column} \u2192 ${o.parent} (${o.count})`).join(", "),more=result.orphans.length>5?` (+${result.orphans.length-5} more)`:"",first=result.orphans[0];if(!first)throw Error("Foreign-key audit reported orphan rows without details");throw Error(`${result.total} orphan rows violate FKs: ${sample}${more}. Legacy rows written under foreign_keys=OFF (#1951). Review and clean manually, e.g. DELETE FROM ${first.table} WHERE ${first.column} IS NOT NULL AND ${first.column} NOT IN (SELECT id FROM ${first.parent}) - doctor never deletes data.`)},1e4);await probe(checks,"Cache",async()=>{const{cache}=await import("@stacksjs/cache"),k=`__doctor_${Date.now()}`;await cache.set(k,1,5);const v=await cache.get(k);await cache.del(k);if(v!==1)throw Error("round-trip failed");return"Round-trip ok"});await probe(checks,"Queue driver",async()=>{const{config}=await import("@stacksjs/config");return`Driver: ${config.queue?.default??"sync"}`});await probe(checks,"Mail driver",async()=>{const{config}=await import("@stacksjs/config");return`Driver: ${config.email?.default??"log"}`});{const budget=new Promise((resolve)=>setTimeout(()=>resolve([{name:"Mail DNS",status:"warn",message:"DNS lookups timed out (>6s) (skipped)"}]),6000).unref?.());checks.push(...await Promise.race([mailDnsChecks(),budget]).catch((err)=>[{name:"Mail DNS",status:"warn",message:`Could not audit mail DNS: ${err instanceof Error?err.message:String(err)}`}]))}{const{ensureRuntimeDirectories,projectPath}=await import("@stacksjs/path"),leftover=ensureRuntimeDirectories().filter((entry)=>!entry.cleared);checks.push(leftover.length===0?{name:"Runtime directories",status:"pass",message:"All under storage/"}:{name:"Runtime directories",status:"warn",message:`Still in the project root: ${leftover.map((entry)=>entry.legacy.slice(projectPath().length+1)).join(", ")} - remove them so state stays under storage/`})}const hasAwsCreds=Boolean(process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY),hasAwsRole=Boolean(process.env.AWS_PROFILE)||Boolean(process.env.AWS_ROLE_ARN);if(hasAwsCreds||hasAwsRole)checks.push({name:"AWS credentials",status:"pass",message:hasAwsCreds?"Static keys in env":"IAM role configured"});else checks.push({name:"AWS credentials",status:"warn",message:"Not configured (cloud / SES / S3 commands will fail)"});await probe(checks,"Database backups",async()=>{const fs=await import("node:fs"),cloudConfig=resolve(process.cwd(),"config/cloud.ts");if(!fs.existsSync(cloudConfig))return"No config/cloud.ts (skipped)";const{findUnbackedManagedServices,hasOffsiteBackupDestination,unbackedDataMessage}=await import("../unbacked-data");let tsCloud;try{tsCloud=(await import(cloudConfig)).tsCloud}catch{throw new ProbeWarning("could not read config/cloud.ts (skipped)")}const unbacked=findUnbackedManagedServices(tsCloud,await hasOffsiteBackupDestination());if(unbacked.length===0)return"No unbacked managed data services";throw new ProbeWarning(unbackedDataMessage(unbacked))});await probe(checks,".env decryption",async()=>{const fs=await import("node:fs");if(!fs.existsSync(".env"))return"No .env (skipped)";const content=fs.readFileSync(".env","utf8");if(!/(?:^|=)(?:enc|encrypted):/m.test(content))return"No encrypted values";const privateKey=process.env.DOTENV_PRIVATE_KEY;if(!privateKey)throw Error("Encrypted values present but DOTENV_PRIVATE_KEY is unset");const{parse}=await import("@stacksjs/env"),{errors}=parse(content,{privateKey});if(errors.length>0)throw Error(errors.join("; "));return"All encrypted values decrypt cleanly"});try{const{filesystems}=await import("@stacksjs/config"),driver=filesystems.driver??"local";if(driver==="s3"){const bucket=process.env.S3_BUCKET??filesystems.s3?.bucket,accessKeyId=process.env.AWS_ACCESS_KEY_ID,secretAccessKey=process.env.AWS_SECRET_ACCESS_KEY,missing=[];if(!bucket)missing.push("S3_BUCKET");if(!accessKeyId)missing.push("AWS_ACCESS_KEY_ID");if(!secretAccessKey)missing.push("AWS_SECRET_ACCESS_KEY");if(missing.length>0)checks.push({name:"Storage credentials",status:"warn",message:`Default disk is 's3' but missing: ${missing.join(", ")}. Uploads will throw on first use.`});else checks.push({name:"Storage credentials",status:"pass",message:"s3 default disk has bucket + AWS credentials"})}else checks.push({name:"Storage credentials",status:"pass",message:`Default disk is '${driver}' (no remote credentials required)`})}catch(err){checks.push({name:"Storage credentials",status:"warn",message:`Could not audit storage config: ${err instanceof Error?err.message:String(err)}`})}try{if(process.platform!=="darwin")checks.push({name:"Dev domains (rpx)",status:"pass",message:"Not macOS (skipped)"});else{const fs=await import("node:fs"),os=await import("node:os"),path=await import("node:path"),isAlive=(pid)=>{try{process.kill(pid,0);return!0}catch(err){return err.code==="EPERM"}},registryDir=path.join(os.homedir(),".stacks","rpx","registry.d"),registered=new Set,deadRegistryFiles=[];if(fs.existsSync(registryDir))for(const file of fs.readdirSync(registryDir)){if(!file.endsWith(".json"))continue;try{const entry=JSON.parse(fs.readFileSync(path.join(registryDir,file),"utf8"));if(entry.to&&(entry.pid===void 0||isAlive(entry.pid)))registered.add(entry.to.toLowerCase());if(typeof entry.pid==="number"&&!isAlive(entry.pid))deadRegistryFiles.push(file)}catch{}}const staleHosts=new Set,staleResolvers=[],hostsPath="/etc/hosts",hostsLines=fs.existsSync(hostsPath)?fs.readFileSync(hostsPath,"utf8").split(`
|
|
3
|
-
`):[];for(let i=0;i<hostsLines.length;i++){const line=hostsLines[i];if(line.trim()==="# Added by rpx"){for(let j=i+1;j<hostsLines.length;j++){const blockLine=hostsLines[j].trim();if(blockLine===""||blockLine.startsWith("#"))break;const names=blockLine.split("#")[0]?.trim().split(/\s+/).slice(1)??[];for(const name of names)if(!registered.has(name.toLowerCase()))staleHosts.add(name)}continue}const hash=line.indexOf("#");if(hash===-1)continue;const marker=/^rpx(?::pid=(\d+))?$/.exec(line.slice(hash+1).trim());if(!marker)continue;const names=line.slice(0,hash).trim().split(/\s+/).slice(1)
|
|
1
|
+
import{existsSync,lstatSync,readFileSync,readlinkSync}from"node:fs";import{resolve}from"node:path";import process from"node:process";import{bold,dim,green,intro,log,onUnknownSubcommand,red,yellow}from"@stacksjs/cli";import{feature}from"@stacksjs/config";import{inspectDefaultsProvenance,installedDefaultsVersion,path,usesVendoredDefaults}from"@stacksjs/path";import{storage}from"@stacksjs/storage";import{isSupportedBunVersion,isVersionGreaterThanOrEqual,minimumBunVersion}from"@stacksjs/utils";import{FEATURE_NAMES,featurePathsPresent}from"./features";const minimumSqliteVersion="3.47.2";class ProbeWarning extends Error{}async function probe(checks,name,fn,timeoutMs=2000){const start=Date.now();const ac=new AbortController;const timer=setTimeout(()=>ac.abort(),timeoutMs);try{const message=await Promise.race([fn(),new Promise((_,rej)=>ac.signal.addEventListener("abort",()=>rej(new Error(`timed out (>${Math.round(timeoutMs/1000)}s)`))))]);checks.push({name,status:"pass",message:`${message} (${Date.now()-start}ms)`})}catch(err){checks.push({name,status:err instanceof ProbeWarning?"warn":"fail",message:err instanceof Error?err.message:String(err)})}finally{clearTimeout(timer)}}async function mailDnsChecks(){const{hasExplicitEmailConfig,declaredDnsProvider,loadTsCloudConfig}=await import("./deploy");if(!hasExplicitEmailConfig())return[{name:"Mail DNS",status:"pass",message:"No config/email.ts (skipped)"}];const{email}=await import("@stacksjs/config");const cfg=email??{};if(cfg.server?.enabled!==true)return[{name:"Mail DNS",status:"pass",message:"email.server.enabled is off (skipped)"}];const{describeMailDnsProvider,describeMailDnsRecords,describePostmaster,gatherMailDnsFacts,mailDomainFromConfig}=await import("../mail-dns-health");const{envFileForEnvironment,envFileKeys}=await import("../dns-credentials");const domain=mailDomainFromConfig(cfg);if(!domain)return[{name:"Mail DNS",status:"warn",message:"email.server.enabled is on but config/email.ts names no domain (set `domain` or a from-address)"}];const fs=await import("node:fs");const envFile=envFileForEnvironment("production");const envPath=resolve(process.cwd(),envFile);const fileKeys=fs.existsSync(envPath)?envFileKeys(fs.readFileSync(envPath,"utf8")):new Set;const dkimSelector="mail";const[declared,facts]=await Promise.all([loadTsCloudConfig("production").then(declaredDnsProvider).catch(()=>{return}),gatherMailDnsFacts(domain,dkimSelector)]);return[{name:"Mail DNS provider",...describeMailDnsProvider({domain,zone:facts.zone,nameservers:facts.nameservers,declared,fileKeys,envFile})},{name:"Mail DNS records",...describeMailDnsRecords({domain,records:facts.records,dkimSelector,dmarcPolicy:cfg.server?.dmarc?.policy,mxAddresses:facts.mxAddresses})},{name:"Postmaster Tools",...describePostmaster(domain,cfg.server?.postmaster,facts.records.filter((record)=>record.type==="TXT"&&record.name===domain).map((record)=>record.content))}]}export function doctor(buddy){buddy.command("doctor","Run health checks on your Stacks installation").option("--no-fail","Print results but always exit 0 (CI ramp-up)").action(async(options)=>{log.debug("Running `buddy doctor` ...");await intro("buddy doctor");const checks=[];const modulesPath=resolve(process.cwd(),"node_modules");try{if(lstatSync(modulesPath).isSymbolicLink()){const target=resolve(process.cwd(),readlinkSync(modulesPath));const insideProject=target.startsWith(`${resolve(process.cwd())}/`);checks.push({name:"Dependency tree",status:insideProject?"warn":"fail",message:insideProject?`node_modules is a symlink to ${target}`:`node_modules is a symlink to ${target}, which belongs to another project - installs here mutate it, and what runs locally is not what the lockfile resolves. Remove the link and run \`bun install\`.`})}else{checks.push({name:"Dependency tree",status:"pass",message:"node_modules is this project's own"})}}catch{checks.push({name:"Dependency tree",status:"warn",message:"node_modules is missing - run `bun install`"})}const depsPath=resolve(process.cwd(),"config/deps.ts");if(existsSync(depsPath)){const{describeSystemDependencies}=await import("../system-dependencies");checks.push({name:"System dependencies",...describeSystemDependencies(readFileSync(depsPath,"utf8"))})}await probe(checks,"Framework defaults",async()=>{const{measureDefaultsDrift,summarizeStructureChanges}=await import("@stacksjs/actions");const root=resolve(process.cwd());const skew=inspectDefaultsProvenance(root);if(skew.status==="not-applicable"){if(!usesVendoredDefaults(root)&&installedDefaultsVersion(root))return`Runs @stacksjs/defaults ${installedDefaultsVersion(root)} from node_modules (not vendored)`;return"Not a package-managed project (nothing to compare)"}const drift=measureDefaultsDrift(root)??[];const synced=skew.syncedAt?`, synced ${skew.syncedAt.slice(0,10)}`:"";if(drift.length===0)return`Vendored tree matches @stacksjs/defaults ${skew.installed}${synced}. \`buddy unpublish:defaults\` drops the copy from the repository and runs the package instead`;const counts=summarizeStructureChanges(drift);if(skew.status==="stale"){throw new ProbeWarning(`storage/framework/defaults is from ${skew.vendored} while @stacksjs/defaults ${skew.installed} is installed (${counts}). Boot resolves the package, so the tree on disk is not what runs. Run \`buddy upgrade\` to sync it.`)}throw new ProbeWarning(`storage/framework/defaults differs from the installed @stacksjs/defaults ${skew.installed} (${counts}), and carries no record of what it was synced from. The app runs the vendored copy. Run \`buddy upgrade\` to sync it.`)},8000);await probe(checks,"Route actions",async()=>{const{describeDanglingRouteActions,findDanglingRouteActions}=await import("@stacksjs/actions");const dangling=findDanglingRouteActions(resolve(process.cwd()));if(dangling.length===0)return"Every action a route names exists";throw new ProbeWarning(`${describeDanglingRouteActions(dangling).split(`
|
|
2
|
+
`).join("; ")}. Point each route at an action that exists, or delete it. \`buddy upgrade\` removes the ones the scaffold wrote.`)});await probe(checks,"Security overrides",async()=>{const{findShadowedSecurityDefaults,frameworkDefaultsDir,SHADOWED_DEFAULT_REVIEW_MARKER}=await import("@stacksjs/server");const defaultsDir=frameworkDefaultsDir("app");if(!defaultsDir)return"No framework defaults to compare against";const shadowed=findShadowedSecurityDefaults(path.appPath(),defaultsDir);if(shadowed.length===0)return"No app/ file shadows a framework security default";const identical=shadowed.filter((entry)=>entry.kind==="identical").map((entry)=>`app/${entry.path}`);const modified=shadowed.filter((entry)=>entry.kind==="modified").map((entry)=>`app/${entry.path} (${SHADOWED_DEFAULT_REVIEW_MARKER} ${entry.fingerprint})`);throw new ProbeWarning([identical.length?`Unchanged copies, delete to receive security fixes: ${identical.join(", ")}.`:"",modified.length?`Differ from the current default, review and mark reviewed: ${modified.join(", ")}.`:""].filter(Boolean).join(" "))});const bunVersion=process.versions.bun;if(bunVersion&&isSupportedBunVersion(bunVersion)){checks.push({name:"Bun Runtime",status:"pass",message:`v${bunVersion}`})}else if(bunVersion){checks.push({name:"Bun Runtime",status:"fail",message:`v${bunVersion} (requires v${minimumBunVersion} or later, run: bun upgrade)`})}else{checks.push({name:"Bun Runtime",status:"fail",message:"Not found"})}try{const pinnedBun=(await storage.readPackageJson("./package.json")).engines?.bun;if(pinnedBun&&bunVersion&&bunVersion!==pinnedBun){checks.push({name:"Pinned Bun",status:"warn",message:`v${bunVersion} is not the pinned v${pinnedBun} (engines.bun). Installing rewrites bun.lock - use \`./pantry/.bin/bun install\`, the pinned toolchain this checkout already carries, and \`git checkout -- bun.lock\` if it already changed.`})}else if(pinnedBun&&bunVersion){checks.push({name:"Pinned Bun",status:"pass",message:`v${bunVersion} matches engines.bun`})}}catch{}const nodeVersion=process.versions.node;if(nodeVersion){const nodeMajor=Number.parseInt(nodeVersion.split(".")[0]||"0",10);if(nodeMajor>=18){checks.push({name:"Node.js",status:"pass",message:`v${nodeVersion}`})}else{checks.push({name:"Node.js",status:"warn",message:`v${nodeVersion} (v18+ recommended)`})}}try{const pkg=await storage.readPackageJson("./package.json");if(pkg.name){checks.push({name:"package.json",status:"pass",message:`Found: ${pkg.name}`})}}catch{checks.push({name:"package.json",status:"fail",message:"Not found in current directory"})}try{await storage.readTextFile(".env");checks.push({name:".env file",status:"pass",message:"Found"})}catch{checks.push({name:".env file",status:"warn",message:"Not found (optional)"})}const appKey=process.env.APP_KEY;if(appKey&&appKey.length>0){checks.push({name:"APP_KEY",status:appKey.length>=32?"pass":"warn",message:appKey.length>=32?"Set (≥32 chars)":`Set but short (${appKey.length} chars; ≥32 recommended)`})}else{checks.push({name:"APP_KEY",status:"fail",message:"Not set - features that depend on it (encrypted columns, signed URLs, env decryption) will refuse to run. Run `buddy key:generate`."})}await probe(checks,"SQLite Engine",async()=>{const{Database}=await import("bun:sqlite");const memory=new Database(":memory:");let version;try{const row=memory.query("SELECT sqlite_version() AS version").get();if(typeof row?.version==="string")version=row.version}finally{memory.close()}if(!version)throw new ProbeWarning("could not read sqlite_version() (skipped)");if(!isVersionGreaterThanOrEqual(version,minimumSqliteVersion))throw new Error(`v${version} is below the required v${minimumSqliteVersion} (system.sqlite in package.json); upgrade Bun for a newer bundled SQLite`);return`v${version}`});await probe(checks,"Database",async()=>{const{db}=await import("@stacksjs/database");const unsafe=db.unsafe;if(typeof unsafe!=="function")throw new ProbeWarning("driver exposes no raw query method (skipped)");const statement=unsafe("SELECT 1");if(!statement||typeof statement.then!=="function"&&typeof statement.execute!=="function")throw new ProbeWarning("driver returned a non-executable statement (skipped)");const result=typeof statement.execute==="function"?await statement.execute():await statement;if(result===undefined||result===null)throw new Error("probe query returned no result");if(Array.isArray(result)&&result.length===0)throw new Error("probe query returned no rows");return"Reachable"});await probe(checks,"Database FKs",async()=>{const{auditForeignKeys}=await import("@stacksjs/database");const result=await auditForeignKeys();if(result.declared.length===0)return"No belongsTo declarations";const skipped=result.absentTable.length>0?`, ${result.absentTable.length} on tables not migrated`:"";if(result.missing.length===0)return`${result.declared.length} declared FKs all present${skipped}`;const sample=result.missing.slice(0,5).map((fk)=>`${fk.fromTable}.${fk.fromColumn} → ${fk.toTable}.${fk.toColumn}`).join(", ");const more=result.missing.length>5?` (+${result.missing.length-5} more)`:"";throw new Error(`${result.missing.length}/${result.declared.length} declared FKs missing from live schema: ${sample}${more}${skipped}. Run \`buddy migrate:fresh\` (will reset data) or \`buddy migrate\` against a clean DB.`)});await probe(checks,"Unique indexes",async()=>{const{auditUniqueIndexes}=await import("@stacksjs/database");const result=await auditUniqueIndexes();if(!result.supported)return"Dialect not audited (skipped)";const skipped=result.skippedTables.length>0?`, ${result.skippedTables.length} tables skipped (not migrated)`:"";if(result.missing.length===0)return`${result.declared.length} declared unique constraints all indexed${skipped}`;const sample=result.missing.slice(0,5).map((u)=>`${u.table}.${u.columns.join("+")}`).join(", ");const more=result.missing.length>5?` (+${result.missing.length-5} more)`:"";const first=result.missing[0];if(!first)throw new Error("Unique-index audit reported missing entries without details");const example=`CREATE UNIQUE INDEX IF NOT EXISTS "${first.table}_${first.columns.join("_")}_unique" ON "${first.table}" ("${first.columns.join('", "')}")`;throw new Error(`${result.missing.length}/${result.declared.length} declared unique constraints have no UNIQUE index: ${sample}${more}. Run \`buddy migrate\` (re-queues missing unique-index migrations, #1952) - dedupe duplicate rows first or migrate hard-fails; if no migration file exists run \`buddy generate:migrations\`, or create manually: ${example}`)},1e4);await probe(checks,"Migration ledger",async()=>{const{auditMigrationLedger}=await import("@stacksjs/database");const result=await auditMigrationLedger();if(!result.supported)return"Dialect not audited (skipped)";if(result.entries.length===0)return"No migration files";const{counts,orphans}=result;if(!result.drift)return`${result.entries.length} migrations, ledger consistent with the schema`;const parts=[];if(counts.stranded>0)parts.push(`${counts.stranded} applied but unrecorded (would re-run)`);if(counts.partial>0)parts.push(`${counts.partial} half-applied`);if(counts.reverted>0)parts.push(`${counts.reverted} recorded but missing from the schema`);if(orphans.length>0)parts.push(`${orphans.length} ledger row(s) with no file on disk`);const needsReapply=counts.reverted+counts.partial;const repair=needsReapply>0?`\`buddy migrate:status --reconcile\` cannot repair ${needsReapply} of these - it never runs migration SQL, so it skips anything the schema is missing. Those need re-applying: \`buddy migrate:fresh\` (rebuilds from the corpus, RESETS DATA), or restore the database and re-run the missing files by hand.`:`Repair with \`buddy migrate:status --reconcile\`.`;throw new Error(`Migration ledger has drifted: ${parts.join(", ")}. Inspect with \`buddy migrate:status\`. ${repair}`)},1e4);await probe(checks,"FK orphans",async()=>{const{findFkOrphans}=await import("@stacksjs/database");const result=await findFkOrphans();if(!result.supported)return"Dialect not audited (skipped)";if(result.total===0)return"No orphan rows (PRAGMA foreign_key_check clean)";const sample=result.orphans.slice(0,5).map((o)=>`${o.table}.${o.column} → ${o.parent} (${o.count})`).join(", ");const more=result.orphans.length>5?` (+${result.orphans.length-5} more)`:"";const first=result.orphans[0];if(!first)throw new Error("Foreign-key audit reported orphan rows without details");throw new Error(`${result.total} orphan rows violate FKs: ${sample}${more}. Legacy rows written under foreign_keys=OFF (#1951). Review and clean manually, e.g. DELETE FROM ${first.table} WHERE ${first.column} IS NOT NULL AND ${first.column} NOT IN (SELECT id FROM ${first.parent}) - doctor never deletes data.`)},1e4);await probe(checks,"Cache",async()=>{const{cache}=await import("@stacksjs/cache");const k=`__doctor_${Date.now()}`;await cache.set(k,1,5);const v=await cache.get(k);await cache.del(k);if(v!==1)throw new Error("round-trip failed");return"Round-trip ok"});await probe(checks,"Queue driver",async()=>{const{config}=await import("@stacksjs/config");const driver=config.queue?.default??"sync";return`Driver: ${driver}`});await probe(checks,"Mail driver",async()=>{const{config}=await import("@stacksjs/config");const driver=config.email?.default??"log";return`Driver: ${driver}`});{const budget=new Promise((resolve)=>setTimeout(()=>resolve([{name:"Mail DNS",status:"warn",message:"DNS lookups timed out (>6s) (skipped)"}]),6000).unref?.());checks.push(...await Promise.race([mailDnsChecks(),budget]).catch((err)=>[{name:"Mail DNS",status:"warn",message:`Could not audit mail DNS: ${err instanceof Error?err.message:String(err)}`}]))}{const{ensureRuntimeDirectories,projectPath}=await import("@stacksjs/path");const leftover=ensureRuntimeDirectories().filter((entry)=>!entry.cleared);checks.push(leftover.length===0?{name:"Runtime directories",status:"pass",message:"All under storage/"}:{name:"Runtime directories",status:"warn",message:`Still in the project root: ${leftover.map((entry)=>entry.legacy.slice(projectPath().length+1)).join(", ")} - remove them so state stays under storage/`})}const hasAwsCreds=Boolean(process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY);const hasAwsRole=Boolean(process.env.AWS_PROFILE)||Boolean(process.env.AWS_ROLE_ARN);if(hasAwsCreds||hasAwsRole){checks.push({name:"AWS credentials",status:"pass",message:hasAwsCreds?"Static keys in env":"IAM role configured"})}else{checks.push({name:"AWS credentials",status:"warn",message:"Not configured (cloud / SES / S3 commands will fail)"})}await probe(checks,"Database backups",async()=>{const fs=await import("node:fs");const cloudConfig=resolve(process.cwd(),"config/cloud.ts");if(!fs.existsSync(cloudConfig))return"No config/cloud.ts (skipped)";const{findUnbackedManagedServices,hasOffsiteBackupDestination,unbackedDataMessage}=await import("../unbacked-data");let tsCloud;try{tsCloud=(await import(cloudConfig)).tsCloud}catch{throw new ProbeWarning("could not read config/cloud.ts (skipped)")}const unbacked=findUnbackedManagedServices(tsCloud,await hasOffsiteBackupDestination());if(unbacked.length===0)return"No unbacked managed data services";throw new ProbeWarning(unbackedDataMessage(unbacked))});await probe(checks,".env decryption",async()=>{const fs=await import("node:fs");if(!fs.existsSync(".env"))return"No .env (skipped)";const content=fs.readFileSync(".env","utf8");if(!/(?:^|=)(?:enc|encrypted):/m.test(content))return"No encrypted values";const privateKey=process.env.DOTENV_PRIVATE_KEY;if(!privateKey)throw new Error("Encrypted values present but DOTENV_PRIVATE_KEY is unset");const{parse}=await import("@stacksjs/env");const{errors}=parse(content,{privateKey});if(errors.length>0)throw new Error(errors.join("; "));return"All encrypted values decrypt cleanly"});try{const{filesystems}=await import("@stacksjs/config");const driver=filesystems.driver??"local";if(driver==="s3"){const bucket=process.env.S3_BUCKET??filesystems.s3?.bucket;const accessKeyId=process.env.AWS_ACCESS_KEY_ID;const secretAccessKey=process.env.AWS_SECRET_ACCESS_KEY;const missing=[];if(!bucket)missing.push("S3_BUCKET");if(!accessKeyId)missing.push("AWS_ACCESS_KEY_ID");if(!secretAccessKey)missing.push("AWS_SECRET_ACCESS_KEY");if(missing.length>0){checks.push({name:"Storage credentials",status:"warn",message:`Default disk is 's3' but missing: ${missing.join(", ")}. Uploads will throw on first use.`})}else{checks.push({name:"Storage credentials",status:"pass",message:"s3 default disk has bucket + AWS credentials"})}}else{checks.push({name:"Storage credentials",status:"pass",message:`Default disk is '${driver}' (no remote credentials required)`})}}catch(err){checks.push({name:"Storage credentials",status:"warn",message:`Could not audit storage config: ${err instanceof Error?err.message:String(err)}`})}try{if(process.platform!=="darwin"){checks.push({name:"Dev domains (rpx)",status:"pass",message:"Not macOS (skipped)"})}else{const fs=await import("node:fs");const os=await import("node:os");const path=await import("node:path");const isAlive=(pid)=>{try{process.kill(pid,0);return true}catch(err){return err.code==="EPERM"}};const registryDir=path.join(os.homedir(),".stacks","rpx","registry.d");const registered=new Set;const deadRegistryFiles=[];if(fs.existsSync(registryDir)){for(const file of fs.readdirSync(registryDir)){if(!file.endsWith(".json"))continue;try{const entry=JSON.parse(fs.readFileSync(path.join(registryDir,file),"utf8"));if(entry.to&&(entry.pid===undefined||isAlive(entry.pid)))registered.add(entry.to.toLowerCase());if(typeof entry.pid==="number"&&!isAlive(entry.pid))deadRegistryFiles.push(file)}catch{}}}const staleHosts=new Set;const staleResolvers=[];const hostsPath="/etc/hosts";const hostsLines=fs.existsSync(hostsPath)?fs.readFileSync(hostsPath,"utf8").split(`
|
|
3
|
+
`):[];for(let i=0;i<hostsLines.length;i++){const line=hostsLines[i];if(line.trim()==="# Added by rpx"){for(let j=i+1;j<hostsLines.length;j++){const blockLine=hostsLines[j].trim();if(blockLine===""||blockLine.startsWith("#"))break;const names=blockLine.split("#")[0]?.trim().split(/\s+/).slice(1)??[];for(const name of names){if(!registered.has(name.toLowerCase()))staleHosts.add(name)}}continue}const hash=line.indexOf("#");if(hash===-1)continue;const marker=/^rpx(?::pid=(\d+))?$/.exec(line.slice(hash+1).trim());if(!marker)continue;const names=line.slice(0,hash).trim().split(/\s+/).slice(1);const pid=marker[1]?Number.parseInt(marker[1],10):null;const stale=pid!==null?!isAlive(pid):names.every((n)=>!registered.has(n.toLowerCase()));if(stale){for(const name of names)staleHosts.add(name)}}const resolverDir="/etc/resolver";if(fs.existsSync(resolverDir)){for(const file of fs.readdirSync(resolverDir)){try{const content=fs.readFileSync(path.join(resolverDir,file),"utf8");if(!content.includes("127.0.0.1")||!content.includes("15353"))continue;const domain=file.toLowerCase();const claimed=[...registered].some((host)=>host===domain||host.endsWith(`.${domain}`));if(!claimed)staleResolvers.push(file)}catch{}}}if(staleHosts.size>0||staleResolvers.length>0||deadRegistryFiles.length>0){const parts=[];if(staleHosts.size>0)parts.push(`hosts(${[...staleHosts].join(", ")})`);if(staleResolvers.length>0)parts.push(`resolver(${staleResolvers.join(", ")})`);if(deadRegistryFiles.length>0)parts.push(`registry(${deadRegistryFiles.join(", ")})`);checks.push({name:"Dev domains (rpx)",status:"warn",message:`Stale loopback overrides from dead dev sessions: ${parts.join(" ")}. These keep pointing the domain at 127.0.0.1. Remove with: sudo nano /etc/hosts; sudo rm /etc/resolver/<name>; rm ~/.stacks/rpx/registry.d/<file>. Updating @stacksjs/rpx lets the daemon sweep pid-stamped entries automatically.`})}else{checks.push({name:"Dev domains (rpx)",status:"pass",message:"No stale dev-domain overrides"})}}}catch(err){checks.push({name:"Dev domains (rpx)",status:"warn",message:`Could not audit dev-domain overrides: ${err instanceof Error?err.message:String(err)}`})}await probe(checks,"Dev ports",async()=>{const net=await import("node:net");const{config}=await import("@stacksjs/config");const configured=config.ports??{};const targets=[{name:"frontend",key:"frontend",envVar:"PORT",fallback:3000},{name:"api",key:"api",envVar:"PORT_API",fallback:3008},{name:"docs",key:"docs",envVar:"PORT_DOCS",fallback:3006},{name:"dashboard",key:"admin",envVar:"PORT_ADMIN",fallback:3002}].map((t)=>({...t,port:Number(configured[t.key])||t.fallback}));const canConnect=(port,host)=>new Promise((resolve)=>{const socket=net.createConnection({port,host});socket.setTimeout(400);const done=(occupied)=>{socket.destroy();resolve(occupied)};socket.once("connect",()=>done(true));socket.once("timeout",()=>done(false));socket.once("error",()=>done(false))});const occupied=new Set;await Promise.all([...new Set(targets.map((t)=>t.port))].map(async(port)=>{if(await canConnect(port,"127.0.0.1")||await canConnect(port,"::1"))occupied.add(port)}));const busy=targets.filter((t)=>occupied.has(t.port));if(busy.length>0){const list=busy.map((t)=>`${t.name} :${t.port} (${t.envVar})`).join(", ");throw new ProbeWarning(`in use: ${list}. buddy dev will fail to bind; stop the process holding the port or set the override env var`)}return`All free: ${targets.map((t)=>`${t.name} :${t.port}`).join(", ")}`});try{const orphans=[];for(const name of FEATURE_NAMES){if(feature(name))continue;const present=featurePathsPresent(name);if(present.length>0)orphans.push({feature:name,count:present.length})}if(orphans.length>0){const summary=orphans.map((o)=>`${o.feature} (${o.count} path${o.count===1?"":"s"})`).join(", ");checks.push({name:"Feature scaffolding",status:"warn",message:`Stamped files remain for disabled features: ${summary}. Run \`./buddy <feature>:uninstall\` to remove or \`<feature>:install\` to re-enable.`})}else{checks.push({name:"Feature scaffolding",status:"pass",message:"No orphan files for disabled features"})}}catch(err){checks.push({name:"Feature scaffolding",status:"warn",message:`Could not audit feature scaffolding: ${err instanceof Error?err.message:String(err)}`})}log.info("");log.info(bold("Health Check Results:"));log.info(dim("─".repeat(60)));log.info("");let hasFailures=false;let hasWarnings=false;for(const check of checks){let statusIcon="";let statusColor=(text)=>text;if(check.status==="pass"){statusIcon="✓";statusColor=green}else if(check.status==="warn"){statusIcon="⚠";statusColor=yellow;hasWarnings=true}else{statusIcon="✗";statusColor=red;hasFailures=true}log.info(`${statusColor(statusIcon)} ${bold(check.name.padEnd(20))} ${dim(check.message)}`)}log.info("");log.info(dim("─".repeat(60)));log.info("");if(hasFailures){log.error("Some critical checks failed. Please address the issues above.");if(options?.fail!==false){await log.flush();process.exit(1)}}else if(hasWarnings){log.info(yellow("Some checks have warnings. Your system should work but may have issues."))}else{log.success(green("All checks passed! Your Stacks installation looks healthy."))}log.info("")});onUnknownSubcommand(buddy,"doctor")}
|
package/dist/commands/domains.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import process from"node:process";import{runAction}from"@stacksjs/actions";import{bgCyan,bold,intro,italic,log,onUnknownSubcommand,outro,prompts}from"@stacksjs/cli";import{awaitConfig}from"@stacksjs/config";import{addDomain}from"@stacksjs/dns";import{hasTTY,isCI}from"@stacksjs/env";import{Action}from"@stacksjs/enums";import{ExitCode}from"@stacksjs/types";import{resultFailed}from"../result";export function domains(buddy){const descriptions={purchase:"Purchase a domain",add:"Add a domain to your cloud",remove:"Remove a domain from your cloud",skip:"Skip the confirmation prompt",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("domains:purchase <domain>",descriptions.purchase).option("--years <years>","Number of years to purchase the domain for").option("--privacy","Enable privacy protection; --no-privacy disables it (default: contactInfo.privacy, else on)").option("--auto-renew","Enable auto-renew; --no-auto-renew disables it (default: on)").option("--first-name <firstName>","Registrant first name").option("--last-name <lastName>","Registrant last name").option("--organization <organization>","Registrant organization name").option("--address-line1 <address>","Registrant address line 1").option("--address-line2 <address>","Registrant address line 2").option("--city <city>","Registrant city").option("--state <state>","Registrant state").option("--country <country>","Registrant country code").option("--zip <zip>","Registrant zip").option("--phone <phone>","Registrant phone").option("--email <email>","Registrant email").option("--admin-first-name <firstName>","Admin first name").option("--admin-last-name <lastName>","Admin last name").option("--admin-organization <organization>","Admin organization").option("--admin-address-line1 <address>","Admin address line 1").option("--admin-address-line2 <address>","Admin address line 2").option("--admin-city <city>","Admin city").option("--admin-state <state>","Admin state").option("--admin-country <country>","Admin country code").option("--admin-zip <zip>","Admin zip").option("--admin-phone <phone>","Admin phone number").option("--admin-email <email>","Admin email").option("--tech-first-name <firstName>","Tech first name").option("--tech-last-name <lastName>","Tech last name").option("--tech-organization <organization>","Tech organization name").option("--tech-address-line1 <address>","Tech address line 1").option("--tech-address-line2 <address>","Tech address line 2").option("--tech-city <city>","Tech city").option("--tech-state <state>","Tech state").option("--tech-country <country>","Tech country").option("--tech-zip <zip>","Tech zip").option("--tech-phone <phone>","Tech phone").option("--tech-email <email>","Tech email").option("--contact-type <type>","Contact type (default: contactInfo.contactType, else person)").option("-y, --yes","Register (and pay for) the domain without asking first",{default
|
|
1
|
+
import process from"node:process";import{runAction}from"@stacksjs/actions";import{bgCyan,bold,intro,italic,log,onUnknownSubcommand,outro,prompts}from"@stacksjs/cli";import{awaitConfig}from"@stacksjs/config";import{addDomain}from"@stacksjs/dns";import{hasTTY,isCI}from"@stacksjs/env";import{Action}from"@stacksjs/enums";import{ExitCode}from"@stacksjs/types";import{resultFailed}from"../result";export function domains(buddy){const descriptions={purchase:"Purchase a domain",add:"Add a domain to your cloud",remove:"Remove a domain from your cloud",skip:"Skip the confirmation prompt",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("domains:purchase <domain>",descriptions.purchase).option("--years <years>","Number of years to purchase the domain for").option("--privacy","Enable privacy protection; --no-privacy disables it (default: contactInfo.privacy, else on)").option("--auto-renew","Enable auto-renew; --no-auto-renew disables it (default: on)").option("--first-name <firstName>","Registrant first name").option("--last-name <lastName>","Registrant last name").option("--organization <organization>","Registrant organization name").option("--address-line1 <address>","Registrant address line 1").option("--address-line2 <address>","Registrant address line 2").option("--city <city>","Registrant city").option("--state <state>","Registrant state").option("--country <country>","Registrant country code").option("--zip <zip>","Registrant zip").option("--phone <phone>","Registrant phone").option("--email <email>","Registrant email").option("--admin-first-name <firstName>","Admin first name").option("--admin-last-name <lastName>","Admin last name").option("--admin-organization <organization>","Admin organization").option("--admin-address-line1 <address>","Admin address line 1").option("--admin-address-line2 <address>","Admin address line 2").option("--admin-city <city>","Admin city").option("--admin-state <state>","Admin state").option("--admin-country <country>","Admin country code").option("--admin-zip <zip>","Admin zip").option("--admin-phone <phone>","Admin phone number").option("--admin-email <email>","Admin email").option("--tech-first-name <firstName>","Tech first name").option("--tech-last-name <lastName>","Tech last name").option("--tech-organization <organization>","Tech organization name").option("--tech-address-line1 <address>","Tech address line 1").option("--tech-address-line2 <address>","Tech address line 2").option("--tech-city <city>","Tech city").option("--tech-state <state>","Tech state").option("--tech-country <country>","Tech country").option("--tech-zip <zip>","Tech zip").option("--tech-phone <phone>","Tech phone").option("--tech-email <email>","Tech email").option("--contact-type <type>","Contact type (default: contactInfo.contactType, else person)").option("-y, --yes","Register (and pay for) the domain without asking first",{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(domain,options)=>{log.debug("Running `buddy domains:purchase <domain>` ...",options);options.domain=domain;const{yes,y,...rest}=options;const forwarded={...rest};for(const key of["privacy","autoRenew"]){if(forwarded[key]===false)forwarded[key]="false"}const startTime=await intro("buddy domains:purchase");const interactive=!isCI&&hasTTY&&Boolean(process.stdin.isTTY);if(!yes){if(!interactive){log.syncError(`Refusing to register ${domain} from a non-interactive shell without confirmation.`);log.syncError(` ➡️ Re-run with \`--yes\`: \`buddy domains:purchase ${domain} --yes\``);await log.flush();process.exit(ExitCode.FatalError)}const years=Number(options.years)||1;const confirmed=await prompts.confirm(`Register ${domain} for ${years} year${years===1?"":"s"}? Route 53 bills your AWS account and does not refund registrations.`);if(!confirmed){await outro("Cancelled the domains:purchase command",{startTime,useSeconds:true,type:"info"});process.exit(ExitCode.Success)}}const result=await runAction(Action.DomainsPurchase,forwarded);if(resultFailed(result)){await outro("While running the domains:purchase command, there was an issue",{startTime,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}const setAppUrl=!yes&&interactive&&await prompts.confirm(`Would you like to set ${domain} as your APP_URL?`);if(!setAppUrl){await outro(`Alrighty! ${italic(domain)} was added to your account.`,{startTime,useSeconds:true,type:"success"});const{dns}=await awaitConfig();const email=options.email||dns?.contactInfo?.email;log.info(`Please note, you may need to validate your email address. Check your ${italic(email??"registrant")} inbox.`);if(yes||!interactive)log.info(`APP_URL was left as it is. To serve the app from ${domain}, run \`buddy env:set APP_URL ${domain}\`.`);await log.flush();process.exit(ExitCode.Success)}const{writeEnv}=await import("@stacksjs/env");writeEnv("APP_URL",domain);let message=`Great! ${italic(domain)} was added to your account.`;message+=`
|
|
2
2
|
|
|
3
3
|
And your APP_URL has been set to ${italic(domain)}.
|
|
4
4
|
|
|
@@ -6,4 +6,4 @@ Please note, this change has not been deployed yet.
|
|
|
6
6
|
|
|
7
7
|
The next time you run ${bgCyan(italic(bold(" buddy deploy ")))}, your app will deploy to ${italic(domain)}.
|
|
8
8
|
|
|
9
|
-
${italic("You may need to deploy 2-3 times for the changes to take effect. Issue tracked here: https://github.com/stacksjs/stacks/issues/685")}`;await outro(message,{startTime,useSeconds
|
|
9
|
+
${italic("You may need to deploy 2-3 times for the changes to take effect. Issue tracked here: https://github.com/stacksjs/stacks/issues/685")}`;await outro(message,{startTime,useSeconds:true,type:"info"});process.exit(ExitCode.Success)});buddy.command("domains:add <domain>",descriptions.add).option("--verbose",descriptions.verbose,{default:false}).action(async(domain,options)=>{log.debug("Running `buddy domains:add <domain>` ...",options);const startTime=await intro("buddy domains:add");const result=await addDomain({...options,domain,startTime});if(resultFailed(result)){await outro("While running the `buddy deploy`, there was an issue",{startTime,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro("Added your domain.",{startTime,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("domains:remove <domain>",descriptions.remove).option("-y, --yes",descriptions.skip,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(domain,options)=>{log.debug("Running `buddy domains:remove <domain>` ...",options);const opts={...options,domain};const startTime=await intro("buddy domains:remove");if(!opts.yes){if(isCI||!hasTTY||!process.stdin.isTTY){log.syncError(`Refusing to remove ${domain} from a non-interactive shell without confirmation.`);log.syncError(` ➡️ Re-run with \`--yes\`: \`buddy domains:remove ${domain} --yes\``);await log.flush();process.exit(ExitCode.FatalError)}const confirm=await prompts.confirm(`Are you sure you want to remove ${domain}?`);if(!confirm){await outro("Cancelled the domains:remove command",{startTime,useSeconds:true,type:"info"});process.exit(ExitCode.Success)}}const result=await runAction(Action.DomainsRemove,opts);if(resultFailed(result)){await outro("While running the domains:remove command, there was an issue",{startTime,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro("Removed your domain DNS records.",{startTime,useSeconds:true});process.exit(ExitCode.Success)});onUnknownSubcommand(buddy,"domains")}
|
package/dist/commands/email.js
CHANGED
|
@@ -1,46 +1,46 @@
|
|
|
1
|
-
import{readFileSync,existsSync}from"node:fs";import process from"node:process";import{email as emailConfig}from"@stacksjs/config";import{ExitCode}from"@stacksjs/types";import{onUnknownSubcommand}from"@stacksjs/cli";import{getErrorMessage}from"@stacksjs/utils";import{reprocessInboundEmails}from"../email-reprocess";const TIMEOUT_MS=30000;async function withTimeout(promise,ms=TIMEOUT_MS){let timeoutId;const timeoutPromise=new Promise((_,reject)=>{timeoutId=setTimeout(()=>reject(Error(`Operation timed out after ${ms}ms`)),ms)});try{return await Promise.race([promise,timeoutPromise])}finally{clearTimeout(timeoutId)}}let _awsCredsLoaded
|
|
1
|
+
import{readFileSync,existsSync}from"node:fs";import process from"node:process";import{email as emailConfig}from"@stacksjs/config";import{ExitCode}from"@stacksjs/types";import{onUnknownSubcommand}from"@stacksjs/cli";import{getErrorMessage}from"@stacksjs/utils";import{reprocessInboundEmails}from"../email-reprocess";const TIMEOUT_MS=30000;async function withTimeout(promise,ms=TIMEOUT_MS){let timeoutId;const timeoutPromise=new Promise((_,reject)=>{timeoutId=setTimeout(()=>reject(new Error(`Operation timed out after ${ms}ms`)),ms)});try{return await Promise.race([promise,timeoutPromise])}finally{clearTimeout(timeoutId)}}let _awsCredsLoaded=false;async function validateS3Bucket(bucket,region){try{const{S3Client}=await import("@stacksjs/ts-cloud");const s3=new S3Client(region);const list=s3.listObjects;if(typeof list!=="function")return{ok:true};await withTimeout(list.call(s3,{bucket,maxKeys:1}),5000);return{ok:true}}catch(err){const message=err instanceof Error?err.message:String(err);if(/NoSuchBucket/i.test(message)){return{ok:false,reason:`Bucket '${bucket}' does not exist in region '${region}'.`,hint:"Run `buddy deploy` to create email infrastructure, or pass --bucket <name> if you know the correct bucket."}}if(/AccessDenied|Forbidden/i.test(message)){return{ok:false,reason:`Access denied to bucket '${bucket}'.`,hint:"Check that AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY (or your IAM role) have s3:ListBucket permission for this bucket."}}if(/region/i.test(message)||/PermanentRedirect/i.test(message)){return{ok:false,reason:`Bucket '${bucket}' is not in region '${region}'.`,hint:"Set AWS_REGION to the bucket's actual region, or pass the right bucket for this region."}}return{ok:false,reason:message,hint:"Check AWS connectivity and credentials."}}}async function loadAwsCredentials(){if(_awsCredsLoaded)return;_awsCredsLoaded=true;const envPath=".env.production";if(!existsSync(envPath))return;const{parse}=await import("@stacksjs/env");const content=readFileSync(envPath,"utf-8");const{parsed}=parse(content);for(const[key,value]of Object.entries(parsed)){if(process.env[key]===undefined){process.env[key]=value}}}const descriptions={email:"Email server management commands",verify:"Check domain verification status",test:"Send a test email",list:"List configured mailboxes",logs:"View email processing logs",status:"Show email server status",inbox:"View inbox emails from S3",reprocess:"Reprocess raw emails from S3 into mailbox structure"};export function email(buddy){buddy.command("email",descriptions.email).action(async()=>{console.log(`
|
|
2
2
|
\uD83D\uDCE7 Email Server Commands
|
|
3
3
|
`);console.log(" buddy email:verify - Check domain verification status");console.log(" buddy email:test - Send a test email");console.log(" buddy email:list - List configured mailboxes");console.log(" buddy email:inbox - View inbox emails from S3");console.log(" buddy email:reprocess - Reprocess raw emails into mailbox structure");console.log(" buddy email:logs - View email processing logs");console.log(" buddy email:status - Show email server status");console.log("")});buddy.command("email:verify",descriptions.verify).action(async()=>{console.log(`
|
|
4
4
|
\uD83D\uDCE7 Checking Email Domain Verification...
|
|
5
|
-
`);await loadAwsCredentials();try{const{SESClient}=await import("@stacksjs/ts-cloud")
|
|
6
|
-
|
|
5
|
+
`);await loadAwsCredentials();try{const{SESClient}=await import("@stacksjs/ts-cloud");const ses=new SESClient(process.env.AWS_REGION||"us-east-1");const emailDomain=(emailConfig?.from?.address?.includes("@")?emailConfig.from.address.split("@")[1]:undefined)||"stacksjs.com";console.log(`Domain: ${emailDomain}`);const identity=await withTimeout(ses.getEmailIdentity(emailDomain));if(identity){console.log(`
|
|
6
|
+
✅ Domain Status: ${identity.VerificationStatus||"Unknown"}`);if(identity.DkimAttributes){console.log(`
|
|
7
7
|
DKIM Status: ${identity.DkimAttributes.Status||"Unknown"}`);if(identity.DkimAttributes.Tokens){console.log(`
|
|
8
|
-
DKIM Records needed:`);for(const token of identity.DkimAttributes.Tokens){console.log(` CNAME: ${token}._domainkey.${emailDomain}`);console.log(` Value: ${token}.dkim.amazonses.com`)}}}}else
|
|
9
|
-
|
|
8
|
+
DKIM Records needed:`);for(const token of identity.DkimAttributes.Tokens){console.log(` CNAME: ${token}._domainkey.${emailDomain}`);console.log(` Value: ${token}.dkim.amazonses.com`)}}}}else{console.log("\n⚠️ Domain not found in SES. Run `buddy deploy` to set up email.")}}catch(error){console.error(`
|
|
9
|
+
❌ Error checking verification:`,getErrorMessage(error))}process.exit(0)});buddy.command("email:test [recipient]",descriptions.test).action(async(recipient)=>{const to=recipient||emailConfig?.from?.address||"test@example.com";const{config}=await import("@stacksjs/config");const driver=config?.email?.default||"ses";console.log(`
|
|
10
10
|
\uD83D\uDCE7 Sending Test Email to ${to} via the configured mailer ('${driver}')...
|
|
11
|
-
`);try{const{mail}=await import("@stacksjs/email")
|
|
11
|
+
`);try{const{mail}=await import("@stacksjs/email");const from={name:emailConfig?.from?.name||"Stacks",address:emailConfig?.from?.address||`hello@${emailConfig?.domain||"stacksjs.com"}`};const result=await mail.send({to:[to],from,subject:"Test Email from Stacks",text:"This is a test email sent from your Stacks application. If you received this, your mail setup is working.",html:`<!doctype html><html><body style="font-family: sans-serif; padding: 20px;">
|
|
12
12
|
<h1>\uD83D\uDE80 Test Email from Stacks</h1>
|
|
13
13
|
<p>This is a test email sent from your Stacks application.</p>
|
|
14
14
|
<p>If you received this, your mail setup is working correctly!</p>
|
|
15
15
|
<hr><p style="color:#666;font-size:12px;">Sent from ${from.address} via the '${driver}' mailer.</p>
|
|
16
|
-
</body></html>`});if(result?.success
|
|
16
|
+
</body></html>`});if(result?.success===false)throw new Error(result?.message||"send returned success=false");console.log(`✅ Test email sent via '${driver}'!`);if(result?.messageId)console.log(` Message ID: ${result.messageId}`);if(driver==="log"||driver==="capture")console.log(`
|
|
17
17
|
\uD83D\uDCA1 The '${driver}' mailer does not deliver mail - set MAIL_MAILER=smtp (or ses) to send for real.`)}catch(error){console.error(`
|
|
18
|
-
|
|
18
|
+
❌ Error sending test email via '${driver}':`,getErrorMessage(error));if(driver==="smtp")console.log(`
|
|
19
19
|
\uD83D\uDCA1 Check MAIL_HOST/MAIL_PORT/MAIL_USERNAME/MAIL_PASSWORD/MAIL_ENCRYPTION in your .env.`);else if(getErrorMessage(error).includes("not verified"))console.log("\n\uD83D\uDCA1 Tip: make sure your domain is verified in SES (`buddy email:verify`).")}process.exit(0)});buddy.command("email:list",descriptions.list).action(async()=>{console.log(`
|
|
20
20
|
\uD83D\uDCE7 Configured Mailboxes
|
|
21
|
-
`);const emailDomain=(emailConfig?.from?.address?.includes("@")?emailConfig.from.address.split("@")[1]:
|
|
22
|
-
\uD83D\uDCA1 Add mailboxes in config/email.ts:`);console.log(' mailboxes: ["user@domain.com", "another@domain.com"]')}else{console.log("Mailboxes:");for(const mailbox of mailboxes)console.log(` \uD83D\uDCEC ${mailbox}`)}console.log("");process.exit(0)});buddy.command("email:logs",descriptions.logs).option("-n, --lines <count>","Number of log lines to show",{default:"20"}).action(async(options)=>{console.log(`
|
|
21
|
+
`);const emailDomain=(emailConfig?.from?.address?.includes("@")?emailConfig.from.address.split("@")[1]:undefined)||"stacksjs.com";const mailboxes=emailConfig?.mailboxes||[];console.log(`Domain: ${emailDomain}`);console.log(`Default From: ${emailConfig?.from?.name} <${emailConfig?.from?.address}>`);console.log("");if(mailboxes.length===0){console.log("No mailboxes configured.");console.log(`
|
|
22
|
+
\uD83D\uDCA1 Add mailboxes in config/email.ts:`);console.log(' mailboxes: ["user@domain.com", "another@domain.com"]')}else{console.log("Mailboxes:");for(const mailbox of mailboxes){console.log(` \uD83D\uDCEC ${mailbox}`)}}console.log("");process.exit(0)});buddy.command("email:logs",descriptions.logs).option("-n, --lines <count>","Number of log lines to show",{default:"20"}).action(async(options)=>{console.log(`
|
|
23
23
|
\uD83D\uDCE7 Email Processing Logs
|
|
24
|
-
`);await loadAwsCredentials();try{const{CloudWatchLogsClient}=await import("@stacksjs/ts-cloud")
|
|
25
|
-
`);const streams=await withTimeout(logs.describeLogStreams({logGroupName,orderBy:"LastEventTime",descending
|
|
26
|
-
\uD83D\uDCA1 Logs will appear after emails are processed.`);return}const logStreamName=streams.logStreams[0]?.logStreamName;if(!logStreamName){console.log("No log stream name found.");return}const events=await withTimeout(logs.getLogEvents({logGroupName,logStreamName,limit:parseInt(options.lines||"20",10)}));if(events.events&&events.events.length>0)for(const event of events.events){const time=new Date(event.timestamp||0).toISOString();console.log(`[${time}] ${event.message}`)}else{console.log("No log events found.");console.log(`
|
|
27
|
-
\uD83D\uDCA1 Logs will appear after emails are processed.`)}}catch(error){if(getErrorMessage(error).includes("ResourceNotFoundException")||getErrorMessage(error).includes("timed out"))console.log("Log group not found or not accessible. No emails have been processed yet.")
|
|
24
|
+
`);await loadAwsCredentials();try{const{CloudWatchLogsClient}=await import("@stacksjs/ts-cloud");const logs=new CloudWatchLogsClient(process.env.AWS_REGION||"us-east-1");const appName=(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-");const logGroupName=`/aws/lambda/${appName}-inbound-email`;console.log(`Log Group: ${logGroupName}`);console.log(`Showing last ${options.lines} events...
|
|
25
|
+
`);const streams=await withTimeout(logs.describeLogStreams({logGroupName,orderBy:"LastEventTime",descending:true,limit:1}));if(!streams.logStreams||streams.logStreams.length===0){console.log("No log streams found.");console.log(`
|
|
26
|
+
\uD83D\uDCA1 Logs will appear after emails are processed.`);return}const logStreamName=streams.logStreams[0]?.logStreamName;if(!logStreamName){console.log("No log stream name found.");return}const events=await withTimeout(logs.getLogEvents({logGroupName,logStreamName,limit:parseInt(options.lines||"20",10)}));if(events.events&&events.events.length>0){for(const event of events.events){const time=new Date(event.timestamp||0).toISOString();console.log(`[${time}] ${event.message}`)}}else{console.log("No log events found.");console.log(`
|
|
27
|
+
\uD83D\uDCA1 Logs will appear after emails are processed.`)}}catch(error){if(getErrorMessage(error).includes("ResourceNotFoundException")||getErrorMessage(error).includes("timed out")){console.log("Log group not found or not accessible. No emails have been processed yet.")}else{console.error("Error fetching logs:",getErrorMessage(error))}}process.exit(0)});buddy.command("email:status",descriptions.status).action(async()=>{console.log(`
|
|
28
28
|
\uD83D\uDCE7 Email Server Status
|
|
29
|
-
`);await loadAwsCredentials();try{const{AWSCloudFormationClient}=await import("@stacksjs/ts-cloud")
|
|
30
|
-
`);console.log("Resources:");for(const resource of emailResources){const status=resource.ResourceStatus==="CREATE_COMPLETE"||resource.ResourceStatus==="UPDATE_COMPLETE"?"
|
|
31
|
-
Configuration:`);for(const output of emailOutputs)console.log(` ${output.OutputKey}: ${output.OutputValue}`)}}catch(error){console.error("Error checking status:",getErrorMessage(error))}process.exit(0)});buddy.command("email:inbox [mailbox]",descriptions.inbox).option("-n, --limit <count>","Number of emails to show",{default:"20"}).option("--raw <id>","Show raw email content for a specific message ID").option("--bucket <name>","S3 bucket name override").action(async(mailbox,options)=>{await loadAwsCredentials();const region=process.env.AWS_REGION||"us-east-1"
|
|
32
|
-
|
|
29
|
+
`);await loadAwsCredentials();try{const{AWSCloudFormationClient}=await import("@stacksjs/ts-cloud");const{stacksCloudName,stacksCloudRegion}=await import("@stacksjs/cloud");const cf=new AWSCloudFormationClient(await stacksCloudRegion());const stackName=await stacksCloudName();const result=await withTimeout(cf.listStackResources(stackName));const emailResources=result.StackResourceSummaries?.filter((r)=>r.LogicalResourceId.includes("Email")||r.LogicalResourceId.includes("Inbound")||r.LogicalResourceId.includes("Outbound"))||[];if(emailResources.length===0){console.log("❌ Email server not deployed.");console.log("\n\uD83D\uDCA1 Run `buddy deploy` to set up email infrastructure.");return}console.log(`✅ Email Server Deployed
|
|
30
|
+
`);console.log("Resources:");for(const resource of emailResources){const status=resource.ResourceStatus==="CREATE_COMPLETE"||resource.ResourceStatus==="UPDATE_COMPLETE"?"✅":"⏳";console.log(` ${status} ${resource.LogicalResourceId}`)}const stacks=await withTimeout(cf.describeStacks({stackName}));const outputs=stacks.Stacks?.[0]?.Outputs||[];const emailOutputs=outputs.filter((o)=>o.OutputKey?.includes("Email"));if(emailOutputs.length>0){console.log(`
|
|
31
|
+
Configuration:`);for(const output of emailOutputs){console.log(` ${output.OutputKey}: ${output.OutputValue}`)}}}catch(error){console.error("Error checking status:",getErrorMessage(error))}process.exit(0)});buddy.command("email:inbox [mailbox]",descriptions.inbox).option("-n, --limit <count>","Number of emails to show",{default:"20"}).option("--raw <id>","Show raw email content for a specific message ID").option("--bucket <name>","S3 bucket name override").action(async(mailbox,options)=>{await loadAwsCredentials();const region=process.env.AWS_REGION||"us-east-1";const appName=(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-");const emailDomain=(emailConfig?.from?.address?.includes("@")?emailConfig.from.address.split("@")[1]:undefined)||"stacksjs.com";const bucketName=options?.bucket||`${appName}-production-email`;const probe=await validateS3Bucket(bucketName,region);if(!probe.ok){console.error(`
|
|
32
|
+
❌ ${probe.reason}
|
|
33
33
|
\uD83D\uDCA1 ${probe.hint}
|
|
34
34
|
`);process.exit(ExitCode.FatalError)}if(options?.raw){console.log(`
|
|
35
35
|
\uD83D\uDCE7 Fetching raw email: ${options.raw}
|
|
36
|
-
`);try{const{S3Client}=await import("@stacksjs/ts-cloud")
|
|
36
|
+
`);try{const{S3Client}=await import("@stacksjs/ts-cloud");const s3=new S3Client(region);let rawContent=null;try{rawContent=await withTimeout(s3.getObject(bucketName,`inbox/${options.raw}`))}catch(e){if(mailbox){const[localPart,domain]=mailbox.includes("@")?mailbox.split("@"):[mailbox,emailDomain];const listResult=await withTimeout(s3.listObjects({bucket:bucketName,prefix:`mailboxes/${domain}/${localPart}/`,maxKeys:1000}));const matchingKey=listResult.objects?.find((obj)=>obj.Key.includes(options.raw)&&obj.Key.endsWith("/raw.eml"));if(matchingKey){rawContent=await withTimeout(s3.getObject(bucketName,matchingKey.Key))}}}if(rawContent){console.log(rawContent)}else{console.log("Email not found.")}}catch(error){console.error("Error fetching email:",getErrorMessage(error))}process.exit(0);return}const resolvedMailbox=mailbox||`chris@${emailDomain}`;const[localPart,domain]=resolvedMailbox.includes("@")?resolvedMailbox.split("@"):[resolvedMailbox,emailDomain];console.log(`
|
|
37
37
|
\uD83D\uDCE7 Inbox for ${localPart}@${domain}
|
|
38
|
-
`);console.log(` Bucket: ${bucketName}`);console.log("");try{const{S3Client}=await import("@stacksjs/ts-cloud")
|
|
39
|
-
`);source="raw";try{const
|
|
38
|
+
`);console.log(` Bucket: ${bucketName}`);console.log("");try{const{S3Client}=await import("@stacksjs/ts-cloud");const s3=new S3Client(region);const limit=parseInt(options?.limit||"20",10);const inboxKey=`mailboxes/${domain}/${localPart}/inbox.json`;let inboxEmails=[];let source="mailboxes";try{const inboxData=await withTimeout(s3.getObject(bucketName,inboxKey));if(inboxData){try{inboxEmails=JSON.parse(inboxData);source="mailboxes"}catch{inboxEmails=[]}}}catch{}if(inboxEmails.length===0){console.log(` No processed inbox found. Scanning raw emails from inbox/ ...
|
|
39
|
+
`);source="raw";try{const listResult=await withTimeout(s3.listObjects({bucket:bucketName,prefix:"inbox/",maxKeys:limit}));const objects=listResult.objects||[];if(objects.length===0){const listResult2=await withTimeout(s3.listObjects({bucket:bucketName,prefix:"incoming/",maxKeys:limit}));const objects2=listResult2.objects||[];objects.push(...objects2)}for(const obj of objects.slice(0,limit)){try{const rawEmail=await withTimeout(s3.getObject(bucketName,obj.Key));if(!rawEmail)continue;const headers=parseRawEmailHeaders(rawEmail);inboxEmails.push({messageId:obj.Key.split("/").pop()||obj.Key,from:headers.from||"unknown",subject:headers.subject||"No Subject",date:headers.date||obj.LastModified||"unknown",path:obj.Key})}catch(parseErr){inboxEmails.push({messageId:obj.Key.split("/").pop()||obj.Key,from:"unknown",subject:"(could not parse)",date:obj.LastModified||"unknown",path:obj.Key})}}}catch(listErr){console.error("Error listing emails:",listErr.message)}}if(inboxEmails.length===0){console.log(" No emails found.");console.log(`
|
|
40
40
|
Waiting for emails to arrive at inbox/ in the S3 bucket.`);console.log(" Send an email to an @"+domain+" address to test.");process.exit(0);return}console.log(` Source: ${source} (${inboxEmails.length} emails)
|
|
41
|
-
`);console.log(" %-4s %-20s %-30s %s","#","Date","From","Subject");console.log(" "+"-".repeat(90));for(let i=0;i<Math.min(inboxEmails.length,limit);i++){const e=inboxEmails[i]
|
|
42
|
-
View raw email: buddy email:inbox ${resolvedMailbox} --raw <messageId>`)}catch(error){console.error("Error reading inbox:",getErrorMessage(error))}process.exit(0)});buddy.command("email:reprocess",descriptions.reprocess).option("--bucket <name>","S3 bucket name override").option("--prefix <prefix>","S3 prefix to scan",{default:"inbox/"}).option("--domain <domain>","Email domain",{default:"stacksjs.com"}).action(async(options)=>{await loadAwsCredentials();const region=process.env.AWS_REGION||"us-east-1"
|
|
41
|
+
`);console.log(" %-4s %-20s %-30s %s","#","Date","From","Subject");console.log(" "+"-".repeat(90));for(let i=0;i<Math.min(inboxEmails.length,limit);i++){const e=inboxEmails[i];const date=e.date?new Date(e.date).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):"?";const from=(e.from||"").substring(0,20).padEnd(20);const subject=(e.subject||"").substring(0,40);const readMark=e.read===false?"*":" ";console.log(` ${readMark}${String(i+1).padStart(3)} ${date.padEnd(20)} ${from} ${subject}`)}console.log("");console.log(" * = unread");console.log(`
|
|
42
|
+
View raw email: buddy email:inbox ${resolvedMailbox} --raw <messageId>`)}catch(error){console.error("Error reading inbox:",getErrorMessage(error))}process.exit(0)});buddy.command("email:reprocess",descriptions.reprocess).option("--bucket <name>","S3 bucket name override").option("--prefix <prefix>","S3 prefix to scan",{default:"inbox/"}).option("--domain <domain>","Email domain",{default:"stacksjs.com"}).action(async(options)=>{await loadAwsCredentials();const region=process.env.AWS_REGION||"us-east-1";const appName=(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-");const bucketName=options?.bucket||`${appName}-production-email`;const prefix=options?.prefix||"inbox/";const domain=options?.domain||"stacksjs.com";console.log(`
|
|
43
43
|
\uD83D\uDCE7 Reprocessing emails from s3://${bucketName}/${prefix}
|
|
44
|
-
`);try{const{S3Client}=await import("@stacksjs/ts-cloud")
|
|
45
|
-
`);for(const skipped of report.skipped)console.log(` Skipping ${skipped.key}: ${skipped.error}`);for(const mailbox of report.mailboxes)console.log(` Updated inbox for ${mailbox.mailbox}: ${mailbox.newCount} new, ${mailbox.refreshedCount} refreshed (${mailbox.total} total)`)
|
|
46
|
-
Done! Processed ${report.processed} emails.`);process.exit(ExitCode.Success)}catch(error){console.error("Error reprocessing:",getErrorMessage(error));process.exit(ExitCode.FatalError)}});onUnknownSubcommand(buddy,"email")}function parseRawEmailHeaders(rawEmail){const headers={}
|
|
44
|
+
`);try{const{S3Client}=await import("@stacksjs/ts-cloud");const s3=new S3Client(region);const report=await reprocessInboundEmails({storage:s3,bucket:bucketName,prefix,domain,onProgress(processed,discovered){if(processed%5===0)console.log(` Processed ${processed}/${discovered} emails...`)}});console.log(` Found ${report.discovered} raw emails to process
|
|
45
|
+
`);for(const skipped of report.skipped)console.log(` Skipping ${skipped.key}: ${skipped.error}`);for(const mailbox of report.mailboxes){console.log(` Updated inbox for ${mailbox.mailbox}: ${mailbox.newCount} new, ${mailbox.refreshedCount} refreshed (${mailbox.total} total)`)}console.log(`
|
|
46
|
+
Done! Processed ${report.processed} emails.`);process.exit(ExitCode.Success)}catch(error){console.error("Error reprocessing:",getErrorMessage(error));process.exit(ExitCode.FatalError)}});onUnknownSubcommand(buddy,"email")}function parseRawEmailHeaders(rawEmail){const headers={};const lines=rawEmail.split(/\r?\n/);let currentKey="";let currentValue="";for(const line of lines){if(line==="")break;if(/^\s/.test(line)&¤tKey){currentValue+=" "+line.trim();headers[currentKey]=currentValue}else{const match=line.match(/^([^:]+):\s*(.*)$/);if(match){currentKey=match[1].toLowerCase();currentValue=match[2]??"";headers[currentKey]=currentValue}}}return headers}function extractEmailAddress(str){if(!str)return"";const match=str.match(/<([^>]+)>/);return(match?.[1]??str).toLowerCase().trim()}function extractEmailName(str){if(!str)return"";const match=str.match(/^"?([^"<]+)"?\s*</);return match?.[1]?.trim()??""}
|