rapidkit 0.23.1 → 0.24.2
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/LICENSE +1 -1
- package/README.md +103 -727
- package/dist/chunk-5JB4MOC5.js +33 -0
- package/dist/{chunk-7LU4Z66R.js → chunk-N64Z3XVF.js} +2 -2
- package/dist/chunk-XP4GTL4L.js +776 -0
- package/dist/create-3OT5GA5W.js +1 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +290 -975
- package/dist/package.json +10 -3
- package/dist/{pythonRapidkitExec-YIFUZLND.js → pythonRapidkitExec-EXCX5QGH.js} +1 -1
- package/dist/{workspace-LZZGJRGV.js → workspace-6SADFTND.js} +1 -1
- package/package.json +6 -1
- package/dist/chunk-74G6C57B.js +0 -24
package/dist/index.js
CHANGED
|
@@ -1,730 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {e,d,c as c$
|
|
3
|
-
|
|
4
|
-
Troubleshooting:
|
|
5
|
-
- Check your internet connection
|
|
6
|
-
- Verify Python/Poetry installation
|
|
7
|
-
- Try running with --debug flag for more details`;super(r,"INSTALLATION_ERROR",i);}},le=class extends H{constructor(){super("RapidKit Python package is not yet available on PyPI","RAPIDKIT_NOT_AVAILABLE",`Available options:
|
|
8
|
-
1. Install Python 3.10+ and retry the same command
|
|
9
|
-
2. Use the core workflow: npx rapidkit create workspace <name>
|
|
10
|
-
3. Offline fallback (limited): npx rapidkit create project fastapi.standard <name> --output .
|
|
11
|
-
|
|
12
|
-
Legacy: set RAPIDKIT_SHOW_LEGACY=1 to reveal template-mode flags in help.`);}};function ct(e){let o=Ko(e);if(!o.validForNewPackages){let r=o.errors||[],i=o.warnings||[],n=[...r,...i];throw new Y(e,`NPM validation failed: ${n.join(", ")}`)}if(!/^[a-z][a-z0-9_-]*$/.test(e))throw new Y(e,"Must start with a lowercase letter and contain only lowercase letters, numbers, hyphens, and underscores");if(["test","tests","src","dist","build","lib","python","pip","poetry","node","npm","rapidkit","rapidkit"].includes(e.toLowerCase()))throw new Y(e,`"${e}" is a reserved name. Please choose a different name.`);if(e.length<2)throw new Y(e,"Name must be at least 2 characters long");if(e.length>214)throw new Y(e,"Name must be less than 214 characters");return true}function Vo(e){return typeof e=="object"&&e!==null}async function Wo(e,o,t,r=8e3){try{let i=await execa(e,o,{cwd:t,timeout:r,reject:false,stdio:"pipe"});return {ok:i.exitCode===0,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr}}catch(i){return {ok:false,exitCode:void 0,stdout:"",stderr:i instanceof Error?i.message:String(i)}}}async function Bo(e,o){let t=["-m","rapidkit",...e],r=["python3","python"];for(let i of r){let n=await Wo(i,t,o?.cwd,o?.timeoutMs);if(!n.ok)continue;let s=(n.stdout??"").trim();try{let c=JSON.parse(s);return Vo(c)?{ok:true,command:i,exitCode:n.exitCode,stdout:n.stdout,stderr:n.stderr,data:c}:{ok:false,command:i,exitCode:n.exitCode,stdout:n.stdout,stderr:n.stderr}}catch{return {ok:false,command:i,exitCode:n.exitCode,stdout:n.stdout,stderr:n.stderr}}}return {ok:false}}async function Gt(e,o){let t=await Bo(["project","detect","--path",e,"--json"],o);return !t.ok||!t.data||t.data.schema_version!==1?{ok:false,command:t.command,exitCode:t.exitCode,stdout:t.stdout,stderr:t.stderr}:t}function Ne(){return process.platform==="win32"?"python":"python3"}async function Mt(e,o,t,r){let i=d$1(o,c(),t);r&&(i.metadata||(i.metadata={}),i.metadata.python={version:r}),await b$1(e,i);}async function qt(e){await R.outputFile(v.join(e,".gitignore"),`.venv/
|
|
13
|
-
__pycache__/
|
|
14
|
-
*.pyc
|
|
15
|
-
.env
|
|
16
|
-
.rapidkit-workspace/
|
|
17
|
-
|
|
18
|
-
`,"utf-8");}function Jo(e,o,t){return JSON.stringify({schema_version:"1.0",workspace_name:e,rapidkit_version:c(),created_at:new Date().toISOString(),created_by:"rapidkit-npm",profile:"minimal",engine:{install_method:o,python_version:t||null}},null,2)}function zo(e,o){return JSON.stringify({schema_version:"1.0",generated_by:"rapidkit-npm",generated_at:new Date().toISOString(),runtime:{python:{version:o||null,install_method:e},node:{version:process.version},go:{version:null}}},null,2)}function Yo(){return `version: "1.0"
|
|
19
|
-
mode: warn
|
|
20
|
-
rules:
|
|
21
|
-
enforce_workspace_marker: true
|
|
22
|
-
enforce_toolchain_lock: false
|
|
23
|
-
disallow_untrusted_tool_sources: false
|
|
24
|
-
`}function Qo(){return `version: "1.0"
|
|
25
|
-
cache:
|
|
26
|
-
strategy: shared
|
|
27
|
-
prune_on_bootstrap: false
|
|
28
|
-
self_heal: true
|
|
29
|
-
verify_integrity: false
|
|
30
|
-
`}async function Lt(e,o,t,r){await R.outputFile(v.join(e,".rapidkit","workspace.json"),Jo(o,t,r),"utf-8"),await R.outputFile(v.join(e,".rapidkit","toolchain.lock"),zo(t,r),"utf-8"),await R.outputFile(v.join(e,".rapidkit","policies.yml"),Yo(),"utf-8"),await R.outputFile(v.join(e,".rapidkit","cache-config.yml"),Qo(),"utf-8");}async function $t(e){try{let{stdout:o}=await execa(e,["--version"],{timeout:3e3}),t=o.match(/Python (\d+\.\d+\.\d+)/);if(t)return t[1]}catch{}return null}async function Xo(e,o){try{await promises.writeFile(v.join(e,".python-version"),`${o}
|
|
31
|
-
`,"utf-8"),a.debug(`Created .python-version with ${o}`);}catch(t){a.warn(`Failed to create .python-version: ${t}`);}}function ve(){let e=v.join(qo.homedir(),".local","bin"),t=(process.env.PATH||"").split(v.delimiter).filter(Boolean);t.includes(e)||(process.env.PATH=[e,...t].join(v.delimiter));}async function je(e,o){ve(),e.start("Checking pipx installation");try{return await execa("pipx",["--version"]),e.succeed("pipx found"),{kind:"binary"}}catch{}let t=Ne();try{return await execa(t,["-m","pipx","--version"]),e.succeed("pipx found"),{kind:"python-module",pythonCmd:t}}catch{}if(o)throw new ye;let{installPipx:r}=await ae.prompt([{type:"confirm",name:"installPipx",message:"pipx is not installed. Install it now (user install via python -m pip)?",default:true}]);if(!r)throw new ye;e.start("Installing pipx (user install)");try{try{await execa(t,["-m","pip","install","--user","--upgrade","pip"]);}catch{}await execa(t,["-m","pip","install","--user","--upgrade","pipx"]);}catch(i){let n=i,s=String(n?.stderr||n?.shortMessage||n?.message||"");throw new F("Install pipx with python -m pip",i instanceof Error?i:new Error(s))}e.succeed("pipx installed"),ve();try{return await execa(t,["-m","pipx","--version"]),{kind:"python-module",pythonCmd:t}}catch(i){let n=i,s=String(n?.stderr||n?.shortMessage||n?.message||"pipx not runnable after install");throw new F("Verify pipx after install",new Error(`${s}
|
|
32
|
-
|
|
33
|
-
Try reopening your terminal or run: python3 -m pipx ensurepath`))}}async function pe(e,o){return e.kind==="binary"?execa("pipx",o):execa(e.pythonCmd,["-m","pipx",...o])}async function Zo(e,o){ve(),e.start("Checking Poetry installation");try{await execa("poetry",["--version"]),e.succeed("Poetry found");return}catch{}if(o)throw new we;let{installPoetry:t}=await ae.prompt([{type:"confirm",name:"installPoetry",message:"Poetry is not installed. Install it now using pipx?",default:true}]);if(!t)throw new we;let r=await je(e,o);e.start("Installing Poetry with pipx");try{await pe(r,["install","poetry"]);}catch(i){let n=i,s=String(n?.stderr||n?.shortMessage||n?.message||"");if(/already\s+installed|already\s+seems\s+to\s+be\s+installed|exists/i.test(s))try{await pe(r,["upgrade","poetry"]);}catch{}else throw new F("Install Poetry with pipx",i instanceof Error?i:new Error(s))}e.succeed("Poetry installed"),ve();try{await execa("poetry",["--version"]);}catch(i){let n=i,s=String(n?.stderr||n?.shortMessage||n?.message||"Poetry not found on PATH");throw new F("Verify Poetry after pipx install",new Error(`${s}
|
|
34
|
-
|
|
35
|
-
Poetry may be installed but not on PATH yet. Try reopening your terminal or run: pipx ensurepath`))}}function er(e){let o=e==="poetry";return `#!/usr/bin/env sh
|
|
36
|
-
set -eu
|
|
37
|
-
|
|
38
|
-
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
|
39
|
-
|
|
40
|
-
VENV_RAPIDKIT="$SCRIPT_DIR/.venv/bin/rapidkit"
|
|
41
|
-
if [ -x "$VENV_RAPIDKIT" ]; then
|
|
42
|
-
exec "$VENV_RAPIDKIT" "$@"
|
|
43
|
-
fi
|
|
44
|
-
|
|
45
|
-
${o?`if command -v poetry >/dev/null 2>&1 && [ -f "$SCRIPT_DIR/pyproject.toml" ]; then
|
|
46
|
-
exec poetry run rapidkit "$@"
|
|
47
|
-
fi
|
|
48
|
-
|
|
49
|
-
`:""}echo "RapidKit launcher could not find a local Python CLI." 1>&2
|
|
50
|
-
echo "- If you used venv: ensure .venv exists (or re-run the installer)." 1>&2
|
|
51
|
-
${o?`echo "- If you used Poetry: run 'poetry install' and retry, or activate the env." 1>&2
|
|
52
|
-
`:""}echo "Tip: you can also run: ./.venv/bin/rapidkit --help" 1>&2
|
|
53
|
-
exit 1
|
|
54
|
-
`}function tr(e){return `@echo off
|
|
55
|
-
setlocal
|
|
56
|
-
|
|
57
|
-
set "SCRIPT_DIR=%~dp0"
|
|
58
|
-
|
|
59
|
-
if exist "%SCRIPT_DIR%\\.venv\\Scripts\\rapidkit.exe" (
|
|
60
|
-
"%SCRIPT_DIR%\\.venv\\Scripts\\rapidkit.exe" %*
|
|
61
|
-
exit /b %ERRORLEVEL%
|
|
62
|
-
)
|
|
63
|
-
|
|
64
|
-
${e==="poetry"?`where poetry >nul 2>nul
|
|
65
|
-
if %ERRORLEVEL%==0 if exist "%SCRIPT_DIR%\\pyproject.toml" (
|
|
66
|
-
poetry run rapidkit %*
|
|
67
|
-
exit /b %ERRORLEVEL%
|
|
68
|
-
)
|
|
69
|
-
|
|
70
|
-
`:""}echo RapidKit launcher could not find a local Python CLI. 1>&2
|
|
71
|
-
echo Tip: run .venv\\Scripts\\rapidkit.exe --help 1>&2
|
|
72
|
-
exit /b 1
|
|
73
|
-
`}async function Ft(e,o){await R.outputFile(v.join(e,"rapidkit"),er(o),{encoding:"utf-8",mode:493}),await R.outputFile(v.join(e,"rapidkit.cmd"),tr(o),"utf-8");}async function Ge(e,o){let{skipGit:t=false,testMode:r=false,demoMode:i=false,dryRun:n=false,yes:s=false,userConfig:c={},installMethod:a$1}=o,l=e||"rapidkit",d=v.resolve(process.cwd(),l);if(await R.pathExists(d))throw new Oe(l);if(n){await rr(d,l,i,c);return}if(i){await or(d,l,t);return}let p=s?{pythonVersion:c.pythonVersion||"3.10",installMethod:a$1||c.defaultInstallMethod||"poetry"}:await ae.prompt([{type:"list",name:"pythonVersion",message:"Select Python version for RapidKit:",choices:["3.10","3.11","3.12"],default:c.pythonVersion||"3.10"},{type:"list",name:"installMethod",message:"How would you like to install RapidKit?",choices:[{name:"\u{1F3AF} Poetry (Recommended - includes virtual env)",value:"poetry"},{name:"\u{1F4E6} pip with venv (Standard)",value:"venv"},{name:"\u{1F527} pipx (Global isolated install)",value:"pipx"}],default:c.defaultInstallMethod||"poetry"}]);a.step(1,3,"Setting up RapidKit environment");let u=pt("Creating directory").start();try{await R.ensureDir(d),u.succeed("Directory created"),u.start("Detecting Python version");let h=null,x=await Ht(p.pythonVersion);if(x)h=await $t(x),h?(a.info(` Detected Python ${h}`),u.succeed(`Python ${h} detected`)):u.warn("Could not detect exact Python version");else {let y=Ne();h=await $t(y),h?u.succeed(`Python ${h} detected`):u.warn("Could not detect Python version, proceeding with defaults");}if(await Mt(d,l,p.installMethod,h||void 0),h&&await Xo(d,h),await Lt(d,l,p.installMethod,h||p.pythonVersion),await qt(d),p.installMethod==="poetry")try{await Kt(d,p.pythonVersion,u,r,c,s);}catch(y){let C=y?.details||y?.message||String(y);if(C.includes("pyenv")||C.includes("exit status 127")||C.includes("returned non-zero exit status 127")){u.warn("Poetry encountered Python discovery issues, trying venv method"),a.debug(`Poetry error (attempting venv fallback): ${C}`);try{await dt(d,p.pythonVersion,u,r,c),p.installMethod="venv";}catch(q){throw q}}else throw y}else p.installMethod==="venv"?await dt(d,p.pythonVersion,u,r,c):await Ut(d,u,r,c,s);if(await Ft(d,p.installMethod),await Vt(d,p.installMethod),u.succeed("RapidKit environment ready!"),!o.skipGit){u.start("Initializing git repository");try{await execa("git",["init"],{cwd:d}),await execa("git",["add","."],{cwd:d}),await execa("git",["commit","-m","Initial commit: RapidKit environment"],{cwd:d}),u.succeed("Git repository initialized");}catch{u.warn("Could not initialize git repository");}}try{let{registerWorkspace:y}=await import('./workspace-LZZGJRGV.js');await y(d,l);}catch{console.warn(g.gray("Note: Could not register workspace in shared registry"));}if(console.log(g.green(`
|
|
74
|
-
\u2728 RapidKit environment created successfully!
|
|
75
|
-
`)),console.log(g.cyan("\u{1F4C2} Location:"),g.white(d)),console.log(g.cyan(`\u{1F680} Get started:
|
|
76
|
-
`)),console.log(g.white(` cd ${l}`)),p.installMethod==="poetry"){let y="source $(poetry env info --path)/bin/activate";try{ve();let{stdout:C}=await execa("poetry",["--version"]),E=C.match(/Poetry.*?(\d+)\.(\d+)/);E&&(parseInt(E[1])>=2?y="source $(poetry env info --path)/bin/activate":y="poetry shell");}catch{}console.log(g.white(` ${y} # Or: poetry run rapidkit`)),console.log(g.white(" rapidkit create # Interactive mode")),console.log(g.white(" cd <project-name> && rapidkit init && rapidkit dev"));}else p.installMethod==="venv"?(console.log(g.white(" source .venv/bin/activate # On Windows: .venv\\Scripts\\activate")),console.log(g.white(" rapidkit create # Interactive mode")),console.log(g.white(" cd <project-name> && rapidkit init && rapidkit dev"))):(console.log(g.white(" rapidkit create # Interactive mode")),console.log(g.white(" cd <project-name> && rapidkit init && rapidkit dev")));console.log(g.white(`
|
|
77
|
-
\u{1F4A1} For more information, check the README.md file.`)),console.log(g.cyan(`
|
|
78
|
-
\u{1F4DA} RapidKit commands:`)),console.log(g.white(" rapidkit create - Create a new project (interactive)")),console.log(g.white(" rapidkit dev - Run development server")),console.log(g.white(" rapidkit add module <name> - Add a module (e.g., settings)")),console.log(g.white(" rapidkit list - List available kits")),console.log(g.white(" rapidkit modules - List available modules")),console.log(g.white(` rapidkit --help - Show all commands
|
|
79
|
-
`));try{let{stdout:y}=await execa("go",["version"],{timeout:3e3}),C=y.match(/go version go(\d+\.\d+(?:\.\d+)?)/),E=C?C[1]:"unknown";console.log(g.gray(`\u{1F439} Go toolchain: Go ${E} detected \u2014 ready for gofiber.standard projects`));}catch{console.log(g.yellow("\u26A0\uFE0F Go toolchain not installed \u2014 needed for gofiber.standard projects")),console.log(g.gray(" Install: https://go.dev/dl/"));}console.log("");}catch(h){u.fail("Failed to create RapidKit environment"),console.error(g.red(`
|
|
80
|
-
\u274C Error:`),h);try{await R.remove(d);}catch{}throw h}}async function Ht(e){let o=[];try{let{stdout:t}=await execa("pyenv",["root"]),r=t.trim();o.push(v.join(r,"versions",`${e}.*`,"bin","python"));let[i,n]=e.split(".");o.push(v.join(r,"versions",`${i}.${n}.*`,"bin","python"));}catch{}o.push(`python${e}`,`python3.${e.split(".")[1]}`,"python3","python"),o.push(`/usr/bin/python${e}`,"/usr/bin/python3",`/usr/local/bin/python${e}`,"/usr/local/bin/python3");for(let t of o)try{let r=t;if(t.includes("*")){if(r=(await execa("sh",["-c",`ls -d ${t} 2>/dev/null | head -1`])).stdout.trim(),!r)continue;r=v.join(r.split("/").slice(0,-1).join("/"),"../bin/python");}let{stdout:i}=await execa(r,["--version"],{timeout:2e3}),n=i.match(/Python (\d+\.\d+)/)?.[1];if(n&&parseFloat(n)>=parseFloat(e))return await execa(r,["-c","import sys; sys.exit(0)"],{timeout:2e3}),r}catch{continue}return null}async function Kt(e,o,t,r,i,n=false){await Zo(t,n),t.start("Finding Python interpreter");let s=await Ht(o);s?(a.debug(`Found working Python: ${s}`),t.succeed("Python found")):t.warn("Could not verify Python path, proceeding with default"),t.start("Initializing Poetry project"),await execa("poetry",["init","--no-interaction","--python",`^${o}`],{cwd:e}),t.succeed("Poetry project initialized");let c=v.join(e,"pyproject.toml"),l=await promises.readFile(c,"utf-8");l.includes("[tool.poetry]")?l=l.replace("[tool.poetry]",`[tool.poetry]
|
|
81
|
-
package-mode = false`):l.includes("[project]")&&(l.includes("[build-system]")?l=l.replace("[build-system]",`
|
|
82
|
-
[tool.poetry]
|
|
83
|
-
package-mode = false
|
|
84
|
-
|
|
85
|
-
[build-system]`):l+=`
|
|
86
|
-
|
|
87
|
-
[tool.poetry]
|
|
88
|
-
package-mode = false
|
|
89
|
-
`),await promises.writeFile(c,l,"utf-8"),t.start("Configuring Poetry");try{if(await execa("poetry",["config","virtualenvs.in-project","true","--local"],{cwd:e}),s)try{await execa("poetry",["env","use",s],{cwd:e}),a.debug(`Poetry configured to use: ${s}`);}catch(d){a.debug(`Could not set Poetry env to ${s}: ${d}`);}t.succeed("Poetry configured");}catch{t.warn("Could not configure Poetry virtualenvs.in-project");}t.start("Creating virtualenv");try{await execa("poetry",["install","--no-root"],{cwd:e,timeout:3e4}),t.succeed("Virtualenv created");}catch(d){a.debug(`Failed to create virtualenv: ${d}`),t.warn("Could not create virtualenv, proceeding with add command");}if(t.start("Installing RapidKit"),r){let d=Ae(i||{});if(!d)throw new F("Test mode installation",new Error("No local RapidKit path configured. Set RAPIDKIT_DEV_PATH environment variable."));a.debug(`Installing from local path: ${d}`),t.text="Installing RapidKit from local path (test mode)",await execa("poetry",["add",d],{cwd:e});}else {t.text="Installing RapidKit from PyPI";let d=false,p=null;for(let u=1;u<=3;u++)try{await execa("poetry",["add","rapidkit-core"],{cwd:e,timeout:6e4*u}),d=true;break}catch(h){p=h,a.debug(`Poetry add attempt ${u} failed: ${h}`),u<3&&(t.text=`Retrying installation (attempt ${u+1}/3)`,await new Promise(x=>setTimeout(x,2e3)));}if(!d){let u=p?.stderr||p?.message||"Unknown error";throw a.debug(`All Poetry install attempts failed. Last error: ${u}`),u.includes("Could not find")||u.includes("No matching distribution")?new le:new F("Install rapidkit-core with Poetry",new Error(`Failed to install rapidkit-core after 3 attempts.
|
|
90
|
-
Error: ${u}
|
|
91
|
-
|
|
92
|
-
Possible solutions:
|
|
93
|
-
1. Check your internet connection
|
|
94
|
-
2. Try installing manually: cd ${v.basename(e)} && poetry add rapidkit-core
|
|
95
|
-
3. Use venv method instead: npx rapidkit ${v.basename(e)} --install-method=venv`))}}t.succeed("RapidKit installed in project virtualenv");try{let{checkRapidkitCoreAvailable:d}=await import('./pythonRapidkitExec-YIFUZLND.js');if(!await d()&&!r){t.start("Installing RapidKit globally with pipx for CLI access");let u=await je(t,n);try{await pe(u,["install","rapidkit-core"]),t.succeed("RapidKit installed globally");}catch(h){t.warn("Could not install globally (non-fatal, project virtualenv has RapidKit)"),a.debug(`pipx install failed: ${h}`);}}}catch(d){a.debug(`Global install check skipped: ${d}`);}}async function dt(e,o,t,r,i,n=false){t.start(`Checking Python ${o}`);let s=Ne();try{let{stdout:a}=await execa(s,["--version"]),l=a.match(/Python (\d+\.\d+)/)?.[1];if(l&&parseFloat(l)<parseFloat(o))throw new de(o,l);t.succeed(`Python ${l} found`);}catch(a){throw a instanceof de?a:new de(o)}t.start("Creating virtual environment");try{await execa(s,["-m","venv",".venv"],{cwd:e}),t.succeed("Virtual environment created");}catch(a){if(t.fail("Failed to create virtual environment"),(d=>typeof d=="object"&&d!==null&&"stdout"in d&&typeof d.stdout=="string")(a)&&a.stdout.includes("ensurepip is not")){let d=a.stdout.match(/apt install (python[\d.]+-venv)/),p=d?d[1]:"python3-venv";throw new F("Python venv module not available",new Error(`Virtual environment creation failed.
|
|
96
|
-
|
|
97
|
-
On Debian/Ubuntu systems, install the venv package:
|
|
98
|
-
sudo apt install ${p}
|
|
99
|
-
|
|
100
|
-
Or use Poetry instead (recommended):
|
|
101
|
-
npx rapidkit ${v.basename(e)} --yes`))}throw new F("Virtual environment creation",a instanceof Error?a:new Error(String(a)))}t.start("Installing RapidKit");let c=v.join(e,".venv",process.platform==="win32"?"Scripts":"bin",process.platform==="win32"?"python.exe":"python");if(await execa(c,["-m","pip","install","--upgrade","pip"],{cwd:e}),r){let a$1=Ae(i||{});if(!a$1)throw new F("Test mode installation",new Error("No local RapidKit path configured. Set RAPIDKIT_DEV_PATH environment variable."));a.debug(`Installing from local path: ${a$1}`),t.text="Installing RapidKit from local path (test mode)",await execa(c,["-m","pip","install","-e",a$1],{cwd:e});}else {t.text="Installing RapidKit from PyPI";let a$1=false,l=null;for(let d=1;d<=3;d++)try{await execa(c,["-m","pip","install","rapidkit-core"],{cwd:e,timeout:6e4*d}),a$1=true;break}catch(p){l=p,a.debug(`pip install attempt ${d} failed: ${p}`),d<3&&(t.text=`Retrying installation (attempt ${d+1}/3)`,await new Promise(u=>setTimeout(u,2e3)));}if(!a$1){let d=l?.stderr||l?.message||"Unknown error";throw a.debug(`All pip install attempts failed. Last error: ${d}`),d.includes("Could not find")||d.includes("No matching distribution")?new le:new F("Install rapidkit-core with pip",new Error(`Failed to install rapidkit-core after 3 attempts.
|
|
102
|
-
Error: ${d}
|
|
103
|
-
|
|
104
|
-
Possible solutions:
|
|
105
|
-
1. Check your internet connection
|
|
106
|
-
2. Try installing manually: cd ${v.basename(e)} && .venv/bin/python -m pip install rapidkit-core
|
|
107
|
-
3. Use Poetry instead: npx rapidkit ${v.basename(e)} --install-method=poetry`))}}t.succeed("RapidKit installed in project virtualenv");try{let{checkRapidkitCoreAvailable:a$1}=await import('./pythonRapidkitExec-YIFUZLND.js');if(!await a$1()&&!r){t.start("Installing RapidKit globally with pipx for CLI access");let d=await je(t,n);try{await pe(d,["install","rapidkit-core"]),t.succeed("RapidKit installed globally");}catch(p){t.warn("Could not install globally (non-fatal, project virtualenv has RapidKit)"),a.debug(`pipx install failed: ${p}`);}}}catch(a$1){a.debug(`Global install check skipped: ${a$1}`);}}async function Ut(e,o,t,r,i=false){let n=await je(o,i);if(o.start("Installing RapidKit globally with pipx"),t){let s=Ae(r||{});if(!s)throw new F("Test mode installation",new Error("No local RapidKit path configured. Set RAPIDKIT_DEV_PATH environment variable."));a.debug(`Installing from local path: ${s}`),o.text="Installing RapidKit from local path (test mode)",await pe(n,["install","-e",s]);}else {o.text="Installing RapidKit from PyPI";try{await pe(n,["install","rapidkit-core"]);}catch{throw new le}}o.succeed("RapidKit installed globally"),await R.outputFile(v.join(e,".rapidkit-global"),`RapidKit installed globally with pipx
|
|
108
|
-
`,"utf-8");}async function te(e,o){let{skipGit:t=false,testMode:r=false,userConfig:i={},yes:n=false,installMethod:s,pythonVersion:c="3.10"}=o||{},a=s||i.defaultInstallMethod||"poetry";await Mt(e,v.basename(e),a),await qt(e),await Lt(e,v.basename(e),a,c);let l=pt("Registering workspace").start();try{a==="poetry"?await Kt(e,c,l,r,i,n):a==="venv"?await dt(e,c,l,r,i):await Ut(e,l,r,i,n),await Ft(e,a),await Vt(e,a),l.succeed("Workspace registered");try{let{registerWorkspace:d}=await import('./workspace-LZZGJRGV.js');await d(e,v.basename(e));}catch{}if(!t){l.start("Initializing git repository");try{await execa("git",["init"],{cwd:e}),await execa("git",["add","."],{cwd:e}),await execa("git",["commit","-m","Initial commit: RapidKit workspace"],{cwd:e}),l.succeed("Git repository initialized");}catch{l.warn("Could not initialize git repository");}}}catch(d){throw l.fail("Failed to register workspace"),d}}async function Vt(e,o){let i=`# RapidKit Workspace
|
|
109
|
-
|
|
110
|
-
This directory contains a RapidKit development environment.
|
|
111
|
-
|
|
112
|
-
## Installation Method
|
|
113
|
-
|
|
114
|
-
**${o==="poetry"?"Poetry":o==="venv"?"Python venv + pip":"pipx (global)"}**
|
|
115
|
-
|
|
116
|
-
## Getting Started
|
|
117
|
-
|
|
118
|
-
### 0. Run Without Activation (Recommended)
|
|
119
|
-
|
|
120
|
-
This workspace includes a local launcher script so you can run the Python Core CLI without activating the environment:
|
|
121
|
-
|
|
122
|
-
\`\`\`bash
|
|
123
|
-
${o==="poetry"?`# No activation needed (recommended):
|
|
124
|
-
./rapidkit --help
|
|
125
|
-
# or:
|
|
126
|
-
poetry run rapidkit --help`:o==="venv"?`# No activation needed (recommended):
|
|
127
|
-
./rapidkit --help
|
|
128
|
-
# or direct:
|
|
129
|
-
./.venv/bin/rapidkit --help`:`# Optional: use the local launcher
|
|
130
|
-
./rapidkit --help
|
|
131
|
-
# (pipx installs may require Poetry/venv to be present in this folder)`}
|
|
132
|
-
\`\`\`
|
|
133
|
-
|
|
134
|
-
### 1. Activate Environment
|
|
135
|
-
|
|
136
|
-
\`\`\`bash
|
|
137
|
-
${o==="poetry"?`source $(poetry env info --path)/bin/activate
|
|
138
|
-
# Or simply use: poetry run rapidkit <command>`:o==="venv"?"source .venv/bin/activate # On Windows: .venv\\Scripts\\activate":"N/A (globally installed)"}
|
|
139
|
-
\`\`\`
|
|
140
|
-
|
|
141
|
-
### 2. Create Your First Project
|
|
142
|
-
|
|
143
|
-
\`\`\`bash
|
|
144
|
-
# Interactive mode (recommended):
|
|
145
|
-
rapidkit create
|
|
146
|
-
# Follow the prompts to choose kit and project name
|
|
147
|
-
|
|
148
|
-
# Or specify directly:
|
|
149
|
-
rapidkit create project fastapi.standard my-project
|
|
150
|
-
|
|
151
|
-
# With poetry run (no activation needed):
|
|
152
|
-
poetry run rapidkit create
|
|
153
|
-
\`\`\`
|
|
154
|
-
|
|
155
|
-
Interactive mode will guide you through selecting a kit and configuring your project.
|
|
156
|
-
|
|
157
|
-
### 3. Navigate and Run
|
|
158
|
-
|
|
159
|
-
\`\`\`bash
|
|
160
|
-
cd my-project
|
|
161
|
-
# Install dependencies (preferred):
|
|
162
|
-
rapidkit init
|
|
163
|
-
|
|
164
|
-
# Run the server (project-aware):
|
|
165
|
-
rapidkit dev
|
|
166
|
-
|
|
167
|
-
# Or with poetry run (manual / advanced):
|
|
168
|
-
poetry run rapidkit dev
|
|
169
|
-
|
|
170
|
-
# Or manually:
|
|
171
|
-
uvicorn src.main:app --reload
|
|
172
|
-
\`\`\`
|
|
173
|
-
|
|
174
|
-
### 4. Add Modules (Optional)
|
|
175
|
-
|
|
176
|
-
\`\`\`bash
|
|
177
|
-
# Add common modules to your project:
|
|
178
|
-
rapidkit add module settings
|
|
179
|
-
rapidkit add module logging
|
|
180
|
-
rapidkit add module database
|
|
181
|
-
|
|
182
|
-
# List available modules:
|
|
183
|
-
rapidkit modules list
|
|
184
|
-
\`\`\`
|
|
185
|
-
|
|
186
|
-
## Available Commands
|
|
187
|
-
|
|
188
|
-
- \`rapidkit create\` - Create a new project (interactive)
|
|
189
|
-
- \`rapidkit create project <kit> <name>\` - Create project with specific kit
|
|
190
|
-
- \`rapidkit dev\` - Run development server
|
|
191
|
-
- \`rapidkit add module <name>\` - Add a module (e.g., \`rapidkit add module settings\`)
|
|
192
|
-
- \`rapidkit list\` - List available kits
|
|
193
|
-
- \`rapidkit modules\` - List available modules
|
|
194
|
-
- \`rapidkit upgrade\` - Upgrade RapidKit
|
|
195
|
-
- \`rapidkit doctor\` - Check system requirements
|
|
196
|
-
- \`rapidkit --help\` - Show all commands
|
|
197
|
-
|
|
198
|
-
## RapidKit Documentation
|
|
199
|
-
|
|
200
|
-
For full documentation, visit: [RapidKit Docs](https://getrapidkit.com) *(or appropriate URL)*
|
|
201
|
-
|
|
202
|
-
## Workspace Structure
|
|
203
|
-
|
|
204
|
-
\`\`\`
|
|
205
|
-
${o==="venv"?".venv/ # Python virtual environment":""}
|
|
206
|
-
${o==="poetry"?"pyproject.toml # Poetry configuration":""}
|
|
207
|
-
my-project/ # Your RapidKit projects go here
|
|
208
|
-
README.md # This file
|
|
209
|
-
\`\`\`
|
|
210
|
-
|
|
211
|
-
## Troubleshooting
|
|
212
|
-
|
|
213
|
-
If you encounter issues:
|
|
214
|
-
|
|
215
|
-
1. Ensure Python 3.10+ is installed: \`python3 --version\`
|
|
216
|
-
2. Check RapidKit installation: \`rapidkit --version\`
|
|
217
|
-
3. Run diagnostics: \`rapidkit doctor\`
|
|
218
|
-
4. Visit RapidKit documentation or GitHub issues
|
|
219
|
-
`;await promises.writeFile(v.join(e,"README.md"),i,"utf-8");}async function or(e,o,t){let r=pt("Creating demo workspace").start();try{await R.ensureDir(e),r.succeed("Directory created"),r.start("Setting up demo kit generator");let i=JSON.stringify({name:`${o}-workspace`,version:"1.0.0",private:true,description:"RapidKit demo workspace",scripts:{generate:"node generate-demo.js"}},null,2);await promises.writeFile(v.join(e,"package.json"),i,"utf-8"),await promises.writeFile(v.join(e,"generate-demo.js"),`#!/usr/bin/env node
|
|
220
|
-
/**
|
|
221
|
-
* Demo Kit Generator - Create FastAPI demo projects
|
|
222
|
-
*
|
|
223
|
-
* This workspace contains bundled RapidKit templates that you can use
|
|
224
|
-
* to generate demo projects without installing Python RapidKit.
|
|
225
|
-
*
|
|
226
|
-
* Usage:
|
|
227
|
-
* npm run generate <project-name>
|
|
228
|
-
* node generate-demo.js <project-name>
|
|
229
|
-
*
|
|
230
|
-
* Example:
|
|
231
|
-
* npm run generate my-api
|
|
232
|
-
*/
|
|
233
|
-
|
|
234
|
-
const fs = require('fs');
|
|
235
|
-
const path = require('path');
|
|
236
|
-
const readline = require('readline');
|
|
237
|
-
|
|
238
|
-
const projectName = process.argv[2];
|
|
239
|
-
|
|
240
|
-
if (!projectName) {
|
|
241
|
-
console.error('\\n\u274C Please provide a project name');
|
|
242
|
-
console.log('\\nUsage: npm run generate <project-name>\\n');
|
|
243
|
-
console.log('Example: npm run generate my-api\\n');
|
|
244
|
-
process.exit(1);
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
const rl = readline.createInterface({
|
|
248
|
-
input: process.stdin,
|
|
249
|
-
output: process.stdout
|
|
250
|
-
});
|
|
251
|
-
|
|
252
|
-
function ask(question, defaultValue) {
|
|
253
|
-
return new Promise((resolve) => {
|
|
254
|
-
rl.question(\`\${question} (\${defaultValue}): \`, (answer) => {
|
|
255
|
-
resolve(answer || defaultValue);
|
|
256
|
-
});
|
|
257
|
-
});
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
async function main() {
|
|
261
|
-
const targetPath = path.join(process.cwd(), projectName);
|
|
262
|
-
|
|
263
|
-
if (fs.existsSync(targetPath)) {
|
|
264
|
-
console.error(\`\\n\u274C Directory "\${projectName}" already exists\\n\`);
|
|
265
|
-
process.exit(1);
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
console.log(\`\\n\u{1F680} Creating FastAPI project: \${projectName}\\n\`);
|
|
269
|
-
|
|
270
|
-
const snakeName = projectName.replace(/-/g, '_').toLowerCase();
|
|
271
|
-
const project_name = await ask('Project name (snake_case)', snakeName);
|
|
272
|
-
const author = await ask('Author name', process.env.USER || 'RapidKit User');
|
|
273
|
-
const description = await ask('Description', 'FastAPI service generated with RapidKit');
|
|
274
|
-
|
|
275
|
-
rl.close();
|
|
276
|
-
|
|
277
|
-
// Create project structure
|
|
278
|
-
const dirs = [
|
|
279
|
-
'',
|
|
280
|
-
'src',
|
|
281
|
-
'src/routing',
|
|
282
|
-
'src/modules',
|
|
283
|
-
'tests',
|
|
284
|
-
'.rapidkit'
|
|
285
|
-
];
|
|
286
|
-
|
|
287
|
-
for (const dir of dirs) {
|
|
288
|
-
fs.mkdirSync(path.join(targetPath, dir), { recursive: true });
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
// Template files with content
|
|
292
|
-
const files = {
|
|
293
|
-
'src/__init__.py': '"""' + project_name + ' package."""\\n',
|
|
294
|
-
'src/modules/__init__.py': '"""Modules package."""\\n',
|
|
295
|
-
'tests/__init__.py': '"""Tests package."""\\n',
|
|
296
|
-
'src/main.py': \`"""\${project_name} application entrypoint."""
|
|
297
|
-
|
|
298
|
-
from __future__ import annotations
|
|
299
|
-
|
|
300
|
-
from contextlib import asynccontextmanager
|
|
301
|
-
from typing import AsyncIterator
|
|
302
|
-
|
|
303
|
-
from fastapi import FastAPI
|
|
304
|
-
from fastapi.middleware.cors import CORSMiddleware
|
|
305
|
-
|
|
306
|
-
from .routing import api_router
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
@asynccontextmanager
|
|
310
|
-
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
|
|
311
|
-
"""Application lifespan context manager for startup/shutdown events."""
|
|
312
|
-
yield
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
app = FastAPI(
|
|
316
|
-
title="\${project_name}",
|
|
317
|
-
description="\${description}",
|
|
318
|
-
version="0.1.0",
|
|
319
|
-
docs_url="/docs",
|
|
320
|
-
redoc_url="/redoc",
|
|
321
|
-
lifespan=lifespan,
|
|
322
|
-
)
|
|
323
|
-
|
|
324
|
-
app.add_middleware(
|
|
325
|
-
CORSMiddleware,
|
|
326
|
-
allow_origins=["*"],
|
|
327
|
-
allow_credentials=True,
|
|
328
|
-
allow_methods=["*"],
|
|
329
|
-
allow_headers=["*"],
|
|
330
|
-
)
|
|
331
|
-
|
|
332
|
-
app.include_router(api_router, prefix="/api")
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
if __name__ == "__main__":
|
|
336
|
-
import uvicorn
|
|
337
|
-
uvicorn.run("src.main:app", host="0.0.0.0", port=8001, reload=True)
|
|
338
|
-
\`,
|
|
339
|
-
'src/routing/__init__.py': \`"""API routing configuration."""
|
|
340
|
-
|
|
341
|
-
from fastapi import APIRouter
|
|
342
|
-
|
|
343
|
-
from .health import router as health_router
|
|
344
|
-
|
|
345
|
-
api_router = APIRouter()
|
|
346
|
-
|
|
347
|
-
api_router.include_router(health_router)
|
|
348
|
-
\`,
|
|
349
|
-
'src/routing/health.py': \`"""Health check endpoints."""
|
|
350
|
-
|
|
351
|
-
from __future__ import annotations
|
|
352
|
-
|
|
353
|
-
from fastapi import APIRouter
|
|
354
|
-
|
|
355
|
-
router = APIRouter(prefix="/health", tags=["health"])
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
@router.get("/", summary="Health check")
|
|
359
|
-
async def heartbeat() -> dict[str, str]:
|
|
360
|
-
"""Return basic service heartbeat."""
|
|
361
|
-
return {"status": "ok"}
|
|
362
|
-
\`,
|
|
363
|
-
'src/cli.py': \`"""CLI commands for \${project_name}."""
|
|
364
|
-
|
|
365
|
-
import subprocess
|
|
366
|
-
import sys
|
|
367
|
-
from pathlib import Path
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
def dev():
|
|
371
|
-
"""Start development server with hot reload."""
|
|
372
|
-
print("\u{1F680} Starting development server...")
|
|
373
|
-
subprocess.run([
|
|
374
|
-
sys.executable, "-m", "uvicorn",
|
|
375
|
-
"src.main:app", "--reload",
|
|
376
|
-
"--host", "0.0.0.0", "--port", "8000"
|
|
377
|
-
])
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
def start():
|
|
381
|
-
"""Start production server."""
|
|
382
|
-
print("\u26A1 Starting production server...")
|
|
383
|
-
subprocess.run([
|
|
384
|
-
sys.executable, "-m", "uvicorn",
|
|
385
|
-
"src.main:app",
|
|
386
|
-
"--host", "0.0.0.0", "--port", "8000"
|
|
387
|
-
])
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
def test():
|
|
391
|
-
"""Run tests."""
|
|
392
|
-
print("\u{1F9EA} Running tests...")
|
|
393
|
-
subprocess.run([sys.executable, "-m", "pytest", "-q"])
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
if __name__ == "__main__":
|
|
397
|
-
if len(sys.argv) < 2:
|
|
398
|
-
print("Usage: python -m src.cli <command>")
|
|
399
|
-
print("Commands: dev, start, test")
|
|
400
|
-
sys.exit(1)
|
|
401
|
-
|
|
402
|
-
cmd = sys.argv[1]
|
|
403
|
-
if cmd == "dev":
|
|
404
|
-
dev()
|
|
405
|
-
elif cmd == "start":
|
|
406
|
-
start()
|
|
407
|
-
elif cmd == "test":
|
|
408
|
-
test()
|
|
409
|
-
else:
|
|
410
|
-
print(f"Unknown command: {cmd}")
|
|
411
|
-
sys.exit(1)
|
|
412
|
-
\`,
|
|
413
|
-
'pyproject.toml': \`[tool.poetry]
|
|
414
|
-
name = "\${project_name}"
|
|
415
|
-
version = "0.1.0"
|
|
416
|
-
description = "\${description}"
|
|
417
|
-
authors = ["\${author}"]
|
|
418
|
-
license = "MIT"
|
|
419
|
-
readme = "README.md"
|
|
420
|
-
package-mode = false
|
|
421
|
-
|
|
422
|
-
[tool.poetry.dependencies]
|
|
423
|
-
python = "^3.10"
|
|
424
|
-
fastapi = "^0.128.0"
|
|
425
|
-
uvicorn = {extras = ["standard"], version = "^0.40.0"}
|
|
426
|
-
pydantic = "^2.12.5"
|
|
427
|
-
pydantic-settings = "^2.12.0"
|
|
428
|
-
|
|
429
|
-
[tool.poetry.group.dev.dependencies]
|
|
430
|
-
pytest = "^9.0.2"
|
|
431
|
-
pytest-asyncio = "^1.3.0"
|
|
432
|
-
pytest-cov = "^7.0.0"
|
|
433
|
-
httpx = "^0.28.1"
|
|
434
|
-
black = "^25.12.0"
|
|
435
|
-
ruff = "^0.14.10"
|
|
436
|
-
mypy = "^1.19.1"
|
|
437
|
-
|
|
438
|
-
[tool.poetry.scripts]
|
|
439
|
-
dev = "src.cli:dev"
|
|
440
|
-
start = "src.cli:start"
|
|
441
|
-
test = "src.cli:test"
|
|
442
|
-
|
|
443
|
-
[build-system]
|
|
444
|
-
requires = ["poetry-core"]
|
|
445
|
-
build-backend = "poetry.core.masonry.api"
|
|
446
|
-
|
|
447
|
-
[tool.pytest.ini_options]
|
|
448
|
-
asyncio_mode = "auto"
|
|
449
|
-
testpaths = ["tests"]
|
|
450
|
-
|
|
451
|
-
[tool.ruff]
|
|
452
|
-
line-length = 100
|
|
453
|
-
target-version = "py311"
|
|
454
|
-
|
|
455
|
-
[tool.black]
|
|
456
|
-
line-length = 100
|
|
457
|
-
target-version = ["py311"]
|
|
458
|
-
\`,
|
|
459
|
-
'README.md': \`# \${project_name}
|
|
460
|
-
|
|
461
|
-
\${description}
|
|
462
|
-
|
|
463
|
-
## Quick start
|
|
464
|
-
|
|
465
|
-
\\\`\\\`\\\`bash
|
|
466
|
-
npx rapidkit init # Install dependencies
|
|
467
|
-
npx rapidkit dev # Start dev server
|
|
468
|
-
\\\`\\\`\\\`
|
|
469
|
-
|
|
470
|
-
## Available commands
|
|
471
|
-
|
|
472
|
-
\\\`\\\`\\\`bash
|
|
473
|
-
npx rapidkit init # \u{1F527} Install dependencies
|
|
474
|
-
npx rapidkit dev # \u{1F680} Start development server with hot reload
|
|
475
|
-
npx rapidkit start # \u26A1 Start production server
|
|
476
|
-
npx rapidkit test # \u{1F9EA} Run tests
|
|
477
|
-
npx rapidkit help # \u{1F4DA} Show available commands
|
|
478
|
-
\\\`\\\`\\\`
|
|
479
|
-
|
|
480
|
-
## Project layout
|
|
481
|
-
|
|
482
|
-
\\\`\\\`\\\`
|
|
483
|
-
\${project_name}/
|
|
484
|
-
\u251C\u2500\u2500 src/
|
|
485
|
-
\u2502 \u251C\u2500\u2500 main.py # FastAPI application
|
|
486
|
-
\u2502 \u251C\u2500\u2500 cli.py # CLI commands
|
|
487
|
-
\u2502 \u251C\u2500\u2500 routing/ # API routes
|
|
488
|
-
\u2502 \u2514\u2500\u2500 modules/ # Module system
|
|
489
|
-
\u251C\u2500\u2500 tests/ # Test suite
|
|
490
|
-
\u251C\u2500\u2500 pyproject.toml # Poetry configuration
|
|
491
|
-
\u2514\u2500\u2500 README.md
|
|
492
|
-
\\\`\\\`\\\`
|
|
493
|
-
\`,
|
|
494
|
-
'.rapidkit/project.json': JSON.stringify({
|
|
495
|
-
kit_name: "fastapi.standard",
|
|
496
|
-
profile: "fastapi/standard",
|
|
497
|
-
created_at: new Date().toISOString(),
|
|
498
|
-
rapidkit_version: "npm-demo"
|
|
499
|
-
}, null, 2),
|
|
500
|
-
'.rapidkit/cli.py': \`#!/usr/bin/env python3
|
|
501
|
-
"""RapidKit CLI wrapper for demo projects."""
|
|
502
|
-
|
|
503
|
-
import subprocess
|
|
504
|
-
import sys
|
|
505
|
-
from pathlib import Path
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
def dev(port=8000, host="0.0.0.0"):
|
|
509
|
-
"""Start development server."""
|
|
510
|
-
print("\u{1F680} Starting development server with hot reload...")
|
|
511
|
-
subprocess.run([
|
|
512
|
-
sys.executable, "-m", "uvicorn",
|
|
513
|
-
"src.main:app", "--reload",
|
|
514
|
-
"--host", host, "--port", str(port)
|
|
515
|
-
])
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
def start(port=8000, host="0.0.0.0"):
|
|
519
|
-
"""Start production server."""
|
|
520
|
-
print("\u26A1 Starting production server...")
|
|
521
|
-
subprocess.run([
|
|
522
|
-
sys.executable, "-m", "uvicorn",
|
|
523
|
-
"src.main:app",
|
|
524
|
-
"--host", host, "--port", str(port)
|
|
525
|
-
])
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
def init():
|
|
529
|
-
"""Install dependencies."""
|
|
530
|
-
print("\u{1F4E6} Installing dependencies...")
|
|
531
|
-
subprocess.run(["poetry", "install"])
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
def test():
|
|
535
|
-
"""Run tests."""
|
|
536
|
-
print("\u{1F9EA} Running tests...")
|
|
537
|
-
subprocess.run([sys.executable, "-m", "pytest", "-q"])
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
def help_cmd():
|
|
541
|
-
"""Show help."""
|
|
542
|
-
print("\u{1F4DA} Available commands:")
|
|
543
|
-
print(" init - Install dependencies")
|
|
544
|
-
print(" dev - Start dev server")
|
|
545
|
-
print(" start - Start production server")
|
|
546
|
-
print(" test - Run tests")
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
if __name__ == "__main__":
|
|
550
|
-
cmd = sys.argv[1] if len(sys.argv) > 1 else "help"
|
|
551
|
-
cmds = {"dev": dev, "start": start, "init": init, "test": test, "help": help_cmd}
|
|
552
|
-
cmds.get(cmd, help_cmd)()
|
|
553
|
-
\`,
|
|
554
|
-
'.rapidkit/rapidkit': '#!/usr/bin/env bash\\n# Local RapidKit launcher for demo projects\\nset -euo pipefail\\nSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"\\nROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"\\ncd "$ROOT_DIR"\\n\\nif [ -f "pyproject.toml" ]; then\\n if command -v poetry >/dev/null 2>&1; then\\n exec poetry run python "$SCRIPT_DIR/cli.py" "$@"\\n fi\\nfi\\n\\necho "Poetry not found. Install with: pip install poetry"\\nexit 1\\n',
|
|
555
|
-
'.gitignore': \`# Python
|
|
556
|
-
__pycache__/
|
|
557
|
-
*.py[cod]
|
|
558
|
-
*.so
|
|
559
|
-
.Python
|
|
560
|
-
build/
|
|
561
|
-
dist/
|
|
562
|
-
*.egg-info/
|
|
563
|
-
|
|
564
|
-
# Virtual environments
|
|
565
|
-
.venv/
|
|
566
|
-
venv/
|
|
567
|
-
|
|
568
|
-
# IDEs
|
|
569
|
-
.vscode/
|
|
570
|
-
.idea/
|
|
571
|
-
|
|
572
|
-
# OS
|
|
573
|
-
.DS_Store
|
|
574
|
-
|
|
575
|
-
# Project
|
|
576
|
-
.env
|
|
577
|
-
.env.local
|
|
578
|
-
\`
|
|
579
|
-
};
|
|
580
|
-
|
|
581
|
-
for (const [filePath, content] of Object.entries(files)) {
|
|
582
|
-
fs.writeFileSync(path.join(targetPath, filePath), content);
|
|
583
|
-
}
|
|
584
|
-
|
|
585
|
-
// Make scripts executable
|
|
586
|
-
try {
|
|
587
|
-
fs.chmodSync(path.join(targetPath, '.rapidkit/cli.py'), 0o755);
|
|
588
|
-
fs.chmodSync(path.join(targetPath, '.rapidkit/rapidkit'), 0o755);
|
|
589
|
-
} catch (e) {
|
|
590
|
-
// Ignore on Windows
|
|
591
|
-
}
|
|
592
|
-
|
|
593
|
-
console.log(\`
|
|
594
|
-
\u2728 Demo project created successfully!
|
|
595
|
-
|
|
596
|
-
\u{1F4C2} Project: \${targetPath}
|
|
597
|
-
|
|
598
|
-
\u{1F680} Get started:
|
|
599
|
-
cd \${projectName}
|
|
600
|
-
npx rapidkit init # Install dependencies
|
|
601
|
-
npx rapidkit dev # Start dev server
|
|
602
|
-
|
|
603
|
-
\u{1F4DA} Available commands:
|
|
604
|
-
npx rapidkit init # \u{1F527} Install dependencies
|
|
605
|
-
npx rapidkit dev # \u{1F680} Start dev server with hot reload
|
|
606
|
-
npx rapidkit start # \u26A1 Start production server
|
|
607
|
-
npx rapidkit test # \u{1F9EA} Run tests
|
|
608
|
-
npx rapidkit help # \u{1F4DA} Show help
|
|
609
|
-
|
|
610
|
-
\u{1F4A1} For full RapidKit features: pipx install rapidkit
|
|
611
|
-
\`);
|
|
612
|
-
}
|
|
613
|
-
|
|
614
|
-
main().catch(console.error);
|
|
615
|
-
`,"utf-8");try{await execa("chmod",["+x",v.join(e,"generate-demo.js")]);}catch{}let s=`# RapidKit Demo Workspace
|
|
616
|
-
|
|
617
|
-
Welcome to your RapidKit demo workspace! This environment lets you generate FastAPI demo projects using bundled RapidKit templates, without needing to install Python RapidKit.
|
|
618
|
-
|
|
619
|
-
## \u{1F680} Quick Start
|
|
620
|
-
|
|
621
|
-
### Generate Your First Demo Project
|
|
622
|
-
|
|
623
|
-
\`\`\`bash
|
|
624
|
-
# Generate a demo project:
|
|
625
|
-
node generate-demo.js my-api
|
|
626
|
-
|
|
627
|
-
# Navigate to the project:
|
|
628
|
-
cd my-api
|
|
629
|
-
|
|
630
|
-
# Install dependencies:
|
|
631
|
-
rapidkit init
|
|
632
|
-
|
|
633
|
-
# Run the development server:
|
|
634
|
-
rapidkit dev
|
|
635
|
-
\`\`\`
|
|
636
|
-
|
|
637
|
-
Your API will be available at \`http://localhost:8000\`
|
|
638
|
-
|
|
639
|
-
## \u{1F4E6} Generate Multiple Projects
|
|
640
|
-
|
|
641
|
-
You can create multiple demo projects in this workspace:
|
|
642
|
-
|
|
643
|
-
\`\`\`bash
|
|
644
|
-
node generate-demo.js api-service
|
|
645
|
-
node generate-demo.js auth-service
|
|
646
|
-
node generate-demo.js data-service
|
|
647
|
-
\`\`\`
|
|
648
|
-
|
|
649
|
-
Each project is independent and has its own dependencies.
|
|
650
|
-
|
|
651
|
-
## \u{1F3AF} What's Included
|
|
652
|
-
|
|
653
|
-
Each generated demo project contains:
|
|
654
|
-
|
|
655
|
-
- **FastAPI Application** - Modern async web framework
|
|
656
|
-
- **Routing System** - Organized API routes
|
|
657
|
-
- **Module System** - Extensible module architecture
|
|
658
|
-
- **CLI Commands** - Built-in command system
|
|
659
|
-
- **Testing Setup** - pytest configuration
|
|
660
|
-
- **Poetry Configuration** - Dependency management
|
|
661
|
-
|
|
662
|
-
## \u{1F4DA} Next Steps
|
|
663
|
-
|
|
664
|
-
1. **Explore the Generated Code** - Check out \`src/main.py\` and \`src/routing/\`
|
|
665
|
-
2. **Add Routes** - Create new endpoints in \`src/routing/\`
|
|
666
|
-
3. **Install Full RapidKit** - For advanced features: \`pipx install rapidkit\`
|
|
667
|
-
4. **Read the Documentation** - Visit [RapidKit Docs](https://getrapidkit.com)
|
|
668
|
-
|
|
669
|
-
## \u26A0\uFE0F Demo Mode Limitations
|
|
670
|
-
|
|
671
|
-
This is a demo workspace with:
|
|
672
|
-
- \u2705 Pre-built FastAPI templates
|
|
673
|
-
- \u2705 Project generation without Python RapidKit
|
|
674
|
-
- \u274C No RapidKit CLI commands (\`rapidkit create\`, \`rapidkit add module\`)
|
|
675
|
-
- \u274C No interactive module system
|
|
676
|
-
|
|
677
|
-
For full RapidKit features, install the Python package:
|
|
678
|
-
|
|
679
|
-
\`\`\`bash
|
|
680
|
-
pipx install rapidkit
|
|
681
|
-
\`\`\`
|
|
682
|
-
|
|
683
|
-
## \u{1F6E0}\uFE0F Workspace Structure
|
|
684
|
-
|
|
685
|
-
\`\`\`
|
|
686
|
-
${o}/
|
|
687
|
-
\u251C\u2500\u2500 generate-demo.js # Demo project generator
|
|
688
|
-
\u251C\u2500\u2500 README.md # This file
|
|
689
|
-
\u2514\u2500\u2500 my-api/ # Your generated projects go here
|
|
690
|
-
\`\`\`
|
|
691
|
-
|
|
692
|
-
## \u{1F4A1} Tips
|
|
693
|
-
|
|
694
|
-
- Run \`node generate-demo.js --help\` for more options (coming soon)
|
|
695
|
-
- Each project can have different configurations
|
|
696
|
-
- Demo projects are production-ready FastAPI applications
|
|
697
|
-
- You can copy and modify templates as needed
|
|
698
|
-
|
|
699
|
-
---
|
|
700
|
-
|
|
701
|
-
**Generated with RapidKit** | [GitHub](https://github.com/getrapidkit/rapidkit-npm)
|
|
702
|
-
`;if(await promises.writeFile(v.join(e,"README.md"),s,"utf-8"),r.succeed("Demo workspace setup complete"),!t){r.start("Initializing git repository");try{await execa("git",["init"],{cwd:e}),await R.outputFile(v.join(e,".gitignore"),`# Dependencies
|
|
703
|
-
node_modules/
|
|
704
|
-
|
|
705
|
-
# Generated projects
|
|
706
|
-
*/
|
|
707
|
-
!generate-demo.js
|
|
708
|
-
!README.md
|
|
709
|
-
|
|
710
|
-
# Python
|
|
711
|
-
__pycache__/
|
|
712
|
-
*.pyc
|
|
713
|
-
.venv/
|
|
714
|
-
.env
|
|
715
|
-
`,"utf-8"),await execa("git",["add","."],{cwd:e}),await execa("git",["commit","-m","Initial commit: Demo workspace"],{cwd:e}),r.succeed("Git repository initialized");}catch{r.warn("Could not initialize git repository");}}console.log(g.green(`
|
|
716
|
-
\u2728 Demo workspace created successfully!
|
|
717
|
-
`)),console.log(g.cyan("\u{1F4C2} Location:"),g.white(e)),console.log(g.cyan(`\u{1F680} Get started:
|
|
718
|
-
`)),console.log(g.white(` cd ${o}`)),console.log(g.white(" node generate-demo.js my-api")),console.log(g.white(" cd my-api")),console.log(g.white(" rapidkit init")),console.log(g.white(" rapidkit dev")),console.log(),console.log(g.yellow("\u{1F4A1} Note:"),"This is a demo workspace. For full RapidKit features:"),console.log(g.cyan(" pipx install rapidkit")),console.log();}catch(i){throw r.fail("Failed to create demo workspace"),i}}async function rr(e,o,t,r){console.log(g.cyan(`
|
|
719
|
-
\u{1F50D} Dry-run mode - showing what would be created:
|
|
720
|
-
`)),console.log(g.white("\u{1F4C2} Project path:"),e),console.log(g.white("\u{1F4E6} Project type:"),t?"Demo workspace":"Full RapidKit environment"),t?(console.log(g.white(`
|
|
721
|
-
\u{1F4DD} Files to create:`)),console.log(g.gray(" - package.json")),console.log(g.gray(" - generate-demo.js (project generator)")),console.log(g.gray(" - README.md")),console.log(g.gray(" - .gitignore")),console.log(g.white(`
|
|
722
|
-
\u{1F3AF} Capabilities:`)),console.log(g.gray(" - Generate multiple FastAPI demo projects")),console.log(g.gray(" - No Python RapidKit installation required")),console.log(g.gray(" - Bundled templates included"))):(console.log(g.white(`
|
|
723
|
-
\u2699\uFE0F Configuration:`)),console.log(g.gray(` - Python version: ${r.pythonVersion||"3.10"}`)),console.log(g.gray(` - Install method: ${r.defaultInstallMethod||"poetry"}`)),console.log(g.gray(` - Git initialization: ${r.skipGit?"No":"Yes"}`)),console.log(g.white(`
|
|
724
|
-
\u{1F4DD} Files to create:`)),console.log(g.gray(" - pyproject.toml (Poetry) or .venv/ (venv)")),console.log(g.gray(" - README.md")),console.log(g.gray(" - .gitignore")),console.log(g.white(`
|
|
725
|
-
\u{1F3AF} Next steps after creation:`)),console.log(g.gray(" 1. Install RapidKit Python package")),console.log(g.gray(" 2. Create projects with rapidkit CLI")),console.log(g.gray(" 3. Add modules and customize"))),console.log(g.white(`
|
|
726
|
-
\u{1F4A1} To proceed with actual creation, run without --dry-run flag
|
|
727
|
-
`));}var ar=fileURLToPath(import.meta.url),cr=v.dirname(ar);function dr(e=32){let o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=sr.randomBytes(e),r="";for(let i=0;i<e;i++)r+=o[t[i]%o.length];return r}async function Wt(e,o){let t=o.template||"fastapi",r=t==="fastapi",i=r?"FastAPI":"NestJS",n=pt(`Generating ${i} project...`).start();try{let s=v.resolve(cr,".."),c$1=o.kit_name||`${t}.standard`,a;c$1==="fastapi.ddd"?a="fastapi-ddd":c$1.startsWith("fastapi")?a="fastapi-standard":a="nestjs-standard";let l=v.join(s,"templates","kits",a),d=nr.configure(l,{autoescape:false,trimBlocks:true,lstripBlocks:true});d.addFilter("generate_secret",function(y,C=32){return dr(C)});let p={project_name:o.project_name,author:o.author||"RapidKit User",description:o.description||(r?"FastAPI service generated with RapidKit":"NestJS application generated with RapidKit"),app_version:o.app_version||"0.1.0",license:o.license||"MIT",package_manager:o.package_manager||"npm",node_version:o.node_version||"20.0.0",database_type:o.database_type||"postgresql",include_caching:o.include_caching||false,created_at:new Date().toISOString(),rapidkit_version:c()},u;r?u=["src/main.py.j2","src/__init__.py.j2","src/cli.py.j2","src/routing/__init__.py.j2","src/routing/health.py.j2","src/modules/__init__.py.j2","tests/__init__.py.j2","README.md.j2","pyproject.toml.j2","Makefile.j2",".rapidkit/__init__.py.j2",".rapidkit/project.json.j2",".rapidkit/cli.py.j2",".rapidkit/rapidkit.j2",".rapidkit/activate.j2","rapidkit.j2","rapidkit.cmd.j2"]:u=["src/main.ts.j2","src/app.module.ts.j2","src/app.controller.ts.j2","src/app.service.ts.j2","src/config/configuration.ts.j2","src/config/validation.ts.j2","src/config/index.ts.j2","src/modules/index.ts.j2","src/examples/examples.module.ts.j2","src/examples/examples.controller.ts.j2","src/examples/examples.service.ts.j2","src/examples/dto/create-note.dto.ts.j2","test/app.controller.spec.ts.j2","test/examples.controller.spec.ts.j2","test/app.e2e-spec.ts.j2","test/jest-e2e.json.j2","package.json.j2","tsconfig.json.j2","tsconfig.build.json.j2","nest-cli.json.j2","jest.config.ts.j2","eslint.config.cjs.j2",".env.example.j2","docker-compose.yml.j2","Dockerfile.j2","README.md.j2",".rapidkit/project.json.j2",".rapidkit/rapidkit.j2",".rapidkit/rapidkit.cmd.j2",".rapidkit/activate.j2","rapidkit.j2","rapidkit.cmd.j2"];for(let y of u){let C=v.join(l,y);try{await promises.access(C);}catch{continue}let E=await promises.readFile(C,"utf-8"),q;try{q=d.renderString(E,p);}catch(st){throw console.error(`Failed to render template: ${y}`),st}let V=y.replace(/\.j2$/,""),Ie=v.join(e,V);await promises.mkdir(v.dirname(Ie),{recursive:true}),await promises.writeFile(Ie,q),(V.endsWith(".rapidkit/rapidkit")||V.endsWith(".rapidkit/cli.py")||V.endsWith(".rapidkit/activate")||V==="rapidkit")&&await promises.chmod(Ie,493);}if(r){let y=v.join(l,".rapidkit","context.json"),C=v.join(e,".rapidkit","context.json");try{await promises.mkdir(v.join(e,".rapidkit"),{recursive:true}),await promises.copyFile(y,C);}catch{await promises.mkdir(v.join(e,".rapidkit"),{recursive:true});let q=o.engine||"pip";await promises.writeFile(C,JSON.stringify({engine:q,created_by:"rapidkit-npm-fallback"},null,2));}}let h=r?`# Python
|
|
2
|
+
import {e,d as d$1,c as c$2,h as h$1,a as a$2}from'./chunk-5JB4MOC5.js';import {a as a$1,b as b$1,c as c$1,d,i,h,e as e$1,f as f$1}from'./chunk-XP4GTL4L.js';import {c,a,b as b$2}from'./chunk-N64Z3XVF.js';import {Command,Option}from'commander';import l from'chalk';import xe from'inquirer';import f from'path';import {fileURLToPath}from'url';import {exec,spawn}from'child_process';import so from'validate-npm-package-name';import*as b from'fs-extra';import b__default from'fs-extra';import S,{promises,createWriteStream}from'fs';import {execa}from'execa';import mo from'nunjucks';import At from'ora';import ho,{createHash,createVerify,createHmac}from'crypto';import qi from'os';import {promisify}from'util';import Kr from'http';import Ur from'https';function Ot(e){let r=so(e);if(!r.validForNewPackages){let o=r.errors||[],i=r.warnings||[],n=[...o,...i];throw new e$1(e,`NPM validation failed: ${n.join(", ")}`)}if(!/^[a-z][a-z0-9_-]*$/.test(e))throw new e$1(e,"Must start with a lowercase letter and contain only lowercase letters, numbers, hyphens, and underscores");if(["test","tests","src","dist","build","lib","python","pip","poetry","node","npm","rapidkit","rapidkit"].includes(e.toLowerCase()))throw new e$1(e,`"${e}" is a reserved name. Please choose a different name.`);if(e.length<2)throw new e$1(e,"Name must be at least 2 characters long");if(e.length>214)throw new e$1(e,"Name must be less than 214 characters");return true}function co(){return process.platform==="win32"?["python","py","python3"]:["python3","python"]}function lo(e,r){return e==="py"?["-3",...r]:r}function po(e){return typeof e=="object"&&e!==null}async function uo(e,r,t,o=8e3){try{let i=await execa(e,r,{cwd:t,timeout:o,reject:false,stdio:"pipe"});return {ok:i.exitCode===0,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr}}catch(i){return {ok:false,exitCode:void 0,stdout:"",stderr:i instanceof Error?i.message:String(i)}}}async function go(e,r){let t=["-m","rapidkit",...e],o=co();for(let i of o){let n=await uo(i,lo(i,t),r?.cwd,r?.timeoutMs);if(!n.ok)continue;let a=(n.stdout??"").trim();try{let s=JSON.parse(a);return po(s)?{ok:true,command:i,exitCode:n.exitCode,stdout:n.stdout,stderr:n.stderr,data:s}:{ok:false,command:i,exitCode:n.exitCode,stdout:n.stdout,stderr:n.stderr}}catch{return {ok:false,command:i,exitCode:n.exitCode,stdout:n.stdout,stderr:n.stderr}}}return {ok:false}}async function tr(e,r){let t=await go(["project","detect","--path",e,"--json"],r);return !t.ok||!t.data||t.data.schema_version!==1?{ok:false,command:t.command,exitCode:t.exitCode,stdout:t.stdout,stderr:t.stderr}:t}var yo=fileURLToPath(import.meta.url),wo=f.dirname(yo);function vo(e=32){let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=ho.randomBytes(e),o="";for(let i=0;i<e;i++)o+=r[t[i]%r.length];return o}async function rr(e,r){let t=r.template||"fastapi",o=t==="fastapi",i=o?"FastAPI":"NestJS",n=At(`Generating ${i} project...`).start();try{let a=f.resolve(wo,".."),s=r.kit_name||`${t}.standard`,c$1;s==="fastapi.ddd"?c$1="fastapi-ddd":s.startsWith("fastapi")?c$1="fastapi-standard":c$1="nestjs-standard";let p=f.join(a,"templates","kits",c$1),d=mo.configure(p,{autoescape:false,trimBlocks:true,lstripBlocks:true});d.addFilter("generate_secret",function(u,C=32){return vo(C)});let m={project_name:r.project_name,author:r.author||"RapidKit User",description:r.description||(o?"FastAPI service generated with RapidKit":"NestJS application generated with RapidKit"),app_version:r.app_version||"0.1.0",license:r.license||"MIT",package_manager:r.package_manager||"npm",node_version:r.node_version||"20.0.0",database_type:r.database_type||"postgresql",include_caching:r.include_caching||false,created_at:new Date().toISOString(),rapidkit_version:c()},h;o?h=["src/main.py.j2","src/__init__.py.j2","src/cli.py.j2","src/routing/__init__.py.j2","src/routing/health.py.j2","src/modules/__init__.py.j2","tests/__init__.py.j2","README.md.j2","pyproject.toml.j2","Makefile.j2",".rapidkit/__init__.py.j2",".rapidkit/project.json.j2",".rapidkit/cli.py.j2",".rapidkit/rapidkit.j2",".rapidkit/activate.j2","rapidkit.j2","rapidkit.cmd.j2"]:h=["src/main.ts.j2","src/app.module.ts.j2","src/app.controller.ts.j2","src/app.service.ts.j2","src/config/configuration.ts.j2","src/config/validation.ts.j2","src/config/index.ts.j2","src/modules/index.ts.j2","src/examples/examples.module.ts.j2","src/examples/examples.controller.ts.j2","src/examples/examples.service.ts.j2","src/examples/dto/create-note.dto.ts.j2","test/app.controller.spec.ts.j2","test/examples.controller.spec.ts.j2","test/app.e2e-spec.ts.j2","test/jest-e2e.json.j2","package.json.j2","tsconfig.json.j2","tsconfig.build.json.j2","nest-cli.json.j2","jest.config.ts.j2","eslint.config.cjs.j2",".env.example.j2","docker-compose.yml.j2","Dockerfile.j2","README.md.j2",".rapidkit/project.json.j2",".rapidkit/rapidkit.j2",".rapidkit/rapidkit.cmd.j2",".rapidkit/activate.j2","rapidkit.j2","rapidkit.cmd.j2"];for(let u of h){let C=f.join(p,u);try{await promises.access(C);}catch{continue}let I=await promises.readFile(C,"utf-8"),A;try{A=d.renderString(I,m);}catch(K){throw console.error(`Failed to render template: ${u}`),K}let _=u.replace(/\.j2$/,""),N=f.join(e,_);await promises.mkdir(f.dirname(N),{recursive:true}),await promises.writeFile(N,A),(_.endsWith(".rapidkit/rapidkit")||_.endsWith(".rapidkit/cli.py")||_.endsWith(".rapidkit/activate")||_==="rapidkit")&&await promises.chmod(N,493);}if(o){let u=f.join(p,".rapidkit","context.json"),C=f.join(e,".rapidkit","context.json");try{await promises.mkdir(f.join(e,".rapidkit"),{recursive:true}),await promises.copyFile(u,C);}catch{await promises.mkdir(f.join(e,".rapidkit"),{recursive:true});let A=r.engine||"pip";await promises.writeFile(C,JSON.stringify({engine:A,created_by:"rapidkit-npm-fallback"},null,2));}}let w=o?`# Python
|
|
728
3
|
__pycache__/
|
|
729
4
|
*.py[cod]
|
|
730
5
|
*$py.class
|
|
@@ -792,15 +67,15 @@ Thumbs.db
|
|
|
792
67
|
|
|
793
68
|
# Coverage
|
|
794
69
|
coverage/
|
|
795
|
-
`;if(await promises.writeFile(
|
|
796
|
-
${
|
|
797
|
-
${
|
|
798
|
-
${
|
|
799
|
-
${
|
|
800
|
-
`),console.log(
|
|
801
|
-
${
|
|
802
|
-
|
|
803
|
-
${
|
|
70
|
+
`;if(await promises.writeFile(f.join(e,".gitignore"),w),n.succeed(`${i} project generated!`),!r.skipGit){let u=At("Initializing git repository...").start();try{await execa("git",["init"],{cwd:e}),await execa("git",["add","."],{cwd:e}),await execa("git",["commit","-m",`Initial commit: ${i} project via RapidKit`],{cwd:e}),u.succeed("Git repository initialized");}catch{u.warn("Could not initialize git repository");}}if(!o&&!r.skipInstall){let u=r.package_manager||"npm",C=At(`Installing dependencies with ${u}...`).start();try{await execa(u,u==="yarn"?["install"]:u==="pnpm"?["install"]:["install"],{cwd:e}),C.succeed("Dependencies installed");}catch{C.warn(`Could not install dependencies. Run '${u} install' manually.`);}}let g=f.basename(e);console.log(`
|
|
71
|
+
${l.yellow("\u26A0\uFE0F Limited offline mode:")} This project was created using basic templates.
|
|
72
|
+
${l.gray("For full kit features, install Python 3.10+ and rapidkit-core:")}
|
|
73
|
+
${l.cyan(" sudo apt install python3 python3-pip python3-venv")}
|
|
74
|
+
${l.cyan(" pip install rapidkit-core")}
|
|
75
|
+
`),console.log(o?`
|
|
76
|
+
${l.green("\u2728 FastAPI project created successfully!")}
|
|
77
|
+
|
|
78
|
+
${l.bold("\u{1F4C2} Project structure:")}
|
|
804
79
|
${e}/
|
|
805
80
|
\u251C\u2500\u2500 .rapidkit/ # RapidKit CLI module
|
|
806
81
|
\u251C\u2500\u2500 src/
|
|
@@ -812,12 +87,12 @@ ${e}/
|
|
|
812
87
|
\u251C\u2500\u2500 pyproject.toml # Poetry configuration
|
|
813
88
|
\u2514\u2500\u2500 README.md
|
|
814
89
|
|
|
815
|
-
${
|
|
816
|
-
${
|
|
817
|
-
${
|
|
818
|
-
${
|
|
90
|
+
${l.bold("\u{1F680} Get started:")}
|
|
91
|
+
${l.cyan(`cd ${g}`)}
|
|
92
|
+
${l.cyan("npx rapidkit init")} ${l.gray("# Install dependencies")}
|
|
93
|
+
${l.cyan("npx rapidkit dev")} ${l.gray("# Start dev server")}
|
|
819
94
|
|
|
820
|
-
${
|
|
95
|
+
${l.bold("\u{1F4DA} Available commands:")}
|
|
821
96
|
npx rapidkit init # Install dependencies (poetry install)
|
|
822
97
|
npx rapidkit dev # Start dev server with hot reload
|
|
823
98
|
npx rapidkit start # Start production server
|
|
@@ -825,12 +100,12 @@ ${g.bold("\u{1F4DA} Available commands:")}
|
|
|
825
100
|
npx rapidkit lint # Lint code
|
|
826
101
|
npx rapidkit format # Format code
|
|
827
102
|
|
|
828
|
-
${
|
|
829
|
-
${
|
|
103
|
+
${l.gray("Alternative: make dev, ./rapidkit dev, poetry run dev")}
|
|
104
|
+
${l.gray("\u{1F4A1} Tip: Install globally (npm i -g rapidkit) to use without npx")}
|
|
830
105
|
`:`
|
|
831
|
-
${
|
|
106
|
+
${l.green("\u2728 NestJS project created successfully!")}
|
|
832
107
|
|
|
833
|
-
${
|
|
108
|
+
${l.bold("\u{1F4C2} Project structure:")}
|
|
834
109
|
${e}/
|
|
835
110
|
\u251C\u2500\u2500 .rapidkit/ # RapidKit CLI module
|
|
836
111
|
\u251C\u2500\u2500 src/
|
|
@@ -842,13 +117,13 @@ ${e}/
|
|
|
842
117
|
\u251C\u2500\u2500 package.json # Dependencies
|
|
843
118
|
\u2514\u2500\u2500 README.md
|
|
844
119
|
|
|
845
|
-
${
|
|
846
|
-
${
|
|
847
|
-
${
|
|
848
|
-
${
|
|
849
|
-
${
|
|
120
|
+
${l.bold("\u{1F680} Get started:")}
|
|
121
|
+
${l.cyan(`cd ${g}`)}
|
|
122
|
+
${l.cyan("npx rapidkit init")} ${l.gray("# Install dependencies")}
|
|
123
|
+
${l.cyan("cp .env.example .env")}
|
|
124
|
+
${l.cyan("npx rapidkit dev")} ${l.gray("# Start dev server")}
|
|
850
125
|
|
|
851
|
-
${
|
|
126
|
+
${l.bold("\u{1F4DA} Available commands:")}
|
|
852
127
|
npx rapidkit init # Install dependencies
|
|
853
128
|
npx rapidkit dev # Start dev server with hot reload
|
|
854
129
|
npx rapidkit start # Start production server
|
|
@@ -857,14 +132,14 @@ ${g.bold("\u{1F4DA} Available commands:")}
|
|
|
857
132
|
npx rapidkit lint # Lint code
|
|
858
133
|
npx rapidkit format # Format code
|
|
859
134
|
|
|
860
|
-
${
|
|
135
|
+
${l.bold("\u{1F310} API endpoints:")}
|
|
861
136
|
http://localhost:8000/health # Health check
|
|
862
137
|
http://localhost:8000/docs # Swagger docs
|
|
863
138
|
http://localhost:8000/examples/notes # Example API
|
|
864
139
|
|
|
865
|
-
${
|
|
866
|
-
${
|
|
867
|
-
`);}catch(
|
|
140
|
+
${l.gray("Alternative: npm run start:dev, ./rapidkit dev")}
|
|
141
|
+
${l.gray("\u{1F4A1} Tip: Install globally (npm i -g rapidkit) to use without npx")}
|
|
142
|
+
`);}catch(a){throw n.fail(`Failed to generate ${i} project`),a}}function or(e){return e.split(/[-_\s]+/).map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join("")}async function bo(e,r){await promises.mkdir(f.dirname(e),{recursive:true}),await promises.writeFile(e,r,"utf8");}function Ro(e){return `package main
|
|
868
143
|
|
|
869
144
|
import (
|
|
870
145
|
"fmt"
|
|
@@ -918,7 +193,7 @@ func main() {
|
|
|
918
193
|
}
|
|
919
194
|
slog.Info("server stopped")
|
|
920
195
|
}
|
|
921
|
-
`}function
|
|
196
|
+
`}function Co(e){return `module ${e.module_path}
|
|
922
197
|
|
|
923
198
|
go ${e.go_version}
|
|
924
199
|
|
|
@@ -952,7 +227,7 @@ require (
|
|
|
952
227
|
golang.org/x/tools v0.21.0 // indirect
|
|
953
228
|
gopkg.in/yaml.v2 v2.4.0 // indirect
|
|
954
229
|
)
|
|
955
|
-
`}function
|
|
230
|
+
`}function So(e){return `package config
|
|
956
231
|
|
|
957
232
|
import (
|
|
958
233
|
"log/slog"
|
|
@@ -1005,7 +280,7 @@ func getEnv(key, fallback string) string {
|
|
|
1005
280
|
}
|
|
1006
281
|
return fallback
|
|
1007
282
|
}
|
|
1008
|
-
`}function
|
|
283
|
+
`}function _o(e){return `package server
|
|
1009
284
|
|
|
1010
285
|
import (
|
|
1011
286
|
"net/http"
|
|
@@ -1071,7 +346,7 @@ func NewApp(cfg *config.Config) *fiber.App {
|
|
|
1071
346
|
|
|
1072
347
|
return app
|
|
1073
348
|
}
|
|
1074
|
-
`}function
|
|
349
|
+
`}function xo(){return `package handlers
|
|
1075
350
|
|
|
1076
351
|
import (
|
|
1077
352
|
"time"
|
|
@@ -1109,7 +384,7 @@ func Readiness(c *fiber.Ctx) error {
|
|
|
1109
384
|
"time": time.Now().UTC().Format(time.RFC3339),
|
|
1110
385
|
})
|
|
1111
386
|
}
|
|
1112
|
-
`}function
|
|
387
|
+
`}function Po(e){return `package handlers_test
|
|
1113
388
|
|
|
1114
389
|
import (
|
|
1115
390
|
"encoding/json"
|
|
@@ -1158,7 +433,7 @@ func TestReadiness(t *testing.T) {
|
|
|
1158
433
|
t.Fatalf("expected 200, got %d: %s", resp.StatusCode, resp.Status)
|
|
1159
434
|
}
|
|
1160
435
|
}
|
|
1161
|
-
`}function
|
|
436
|
+
`}function Eo(){return `# \u2500\u2500 Build stage \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
1162
437
|
FROM golang:1.24-alpine AS builder
|
|
1163
438
|
|
|
1164
439
|
# Build-time version injection
|
|
@@ -1187,7 +462,7 @@ EXPOSE 3000
|
|
|
1187
462
|
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \\
|
|
1188
463
|
CMD wget -qO- http://localhost:3000/api/v1/health/live || exit 1
|
|
1189
464
|
ENTRYPOINT ["/server"]
|
|
1190
|
-
`}function
|
|
465
|
+
`}function Io(e){return `version: "3.9"
|
|
1191
466
|
|
|
1192
467
|
services:
|
|
1193
468
|
api:
|
|
@@ -1202,7 +477,7 @@ services:
|
|
|
1202
477
|
CORS_ALLOW_ORIGINS: "*"
|
|
1203
478
|
RATE_LIMIT_RPS: "100"
|
|
1204
479
|
restart: unless-stopped
|
|
1205
|
-
`}function
|
|
480
|
+
`}function To(e){return `.PHONY: dev run build test cover lint fmt tidy docs docker-up docker-down
|
|
1206
481
|
|
|
1207
482
|
# Build-time metadata
|
|
1208
483
|
VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo "dev")
|
|
@@ -1248,7 +523,7 @@ docker-up:
|
|
|
1248
523
|
|
|
1249
524
|
docker-down:
|
|
1250
525
|
docker compose down
|
|
1251
|
-
`}function
|
|
526
|
+
`}function Oo(e){return `# Application
|
|
1252
527
|
PORT=${e.port}
|
|
1253
528
|
APP_ENV=development
|
|
1254
529
|
LOG_LEVEL=debug
|
|
@@ -1258,7 +533,7 @@ CORS_ALLOW_ORIGINS=*
|
|
|
1258
533
|
|
|
1259
534
|
# Rate limiting \u2014 max requests per IP per second
|
|
1260
535
|
RATE_LIMIT_RPS=100
|
|
1261
|
-
`}function
|
|
536
|
+
`}function Ao(){return `# Binaries
|
|
1262
537
|
bin/
|
|
1263
538
|
*.exe
|
|
1264
539
|
*.exe~
|
|
@@ -1298,7 +573,7 @@ docs/docs.go
|
|
|
1298
573
|
# OS
|
|
1299
574
|
.DS_Store
|
|
1300
575
|
Thumbs.db
|
|
1301
|
-
`}function
|
|
576
|
+
`}function No(e){return `name: CI
|
|
1302
577
|
|
|
1303
578
|
on:
|
|
1304
579
|
push:
|
|
@@ -1352,7 +627,7 @@ jobs:
|
|
|
1352
627
|
uses: golangci/golangci-lint-action@v6
|
|
1353
628
|
with:
|
|
1354
629
|
version: latest
|
|
1355
|
-
`}function
|
|
630
|
+
`}function jo(e){return `# ${or(e.project_name)}
|
|
1356
631
|
|
|
1357
632
|
> ${e.description}
|
|
1358
633
|
|
|
@@ -1467,7 +742,7 @@ ${e.project_name}/
|
|
|
1467
742
|
## License
|
|
1468
743
|
|
|
1469
744
|
${e.app_version} \xB7 ${e.author}
|
|
1470
|
-
`}function
|
|
745
|
+
`}function $o(){return `package middleware
|
|
1471
746
|
|
|
1472
747
|
import (
|
|
1473
748
|
"crypto/rand"
|
|
@@ -1520,7 +795,7 @@ func newID() string {
|
|
|
1520
795
|
}
|
|
1521
796
|
return hex.EncodeToString(b)
|
|
1522
797
|
}
|
|
1523
|
-
`}function
|
|
798
|
+
`}function Do(e){return `package middleware_test
|
|
1524
799
|
|
|
1525
800
|
import (
|
|
1526
801
|
"net/http"
|
|
@@ -1573,7 +848,7 @@ func TestRequestID_IsReused(t *testing.T) {
|
|
|
1573
848
|
t.Fatalf("expected X-Request-ID to be reused, got %q", id)
|
|
1574
849
|
}
|
|
1575
850
|
}
|
|
1576
|
-
`}function
|
|
851
|
+
`}function Go(){return `// Package apierr provides a consistent JSON error envelope for all API responses.
|
|
1577
852
|
//
|
|
1578
853
|
// Every error response looks like:
|
|
1579
854
|
//
|
|
@@ -1637,7 +912,7 @@ func InternalError(c *fiber.Ctx, _ error) error {
|
|
|
1637
912
|
func TooManyRequests(c *fiber.Ctx, msg string) error {
|
|
1638
913
|
return reply(c, http.StatusTooManyRequests, msg, "TOO_MANY_REQUESTS")
|
|
1639
914
|
}
|
|
1640
|
-
`}function
|
|
915
|
+
`}function Mo(e){return `package apierr_test
|
|
1641
916
|
|
|
1642
917
|
import (
|
|
1643
918
|
"encoding/json"
|
|
@@ -1769,11 +1044,11 @@ func TestTooManyRequests(t *testing.T) {
|
|
|
1769
1044
|
t.Fatalf("expected TOO_MANY_REQUESTS, got %q", body.Code)
|
|
1770
1045
|
}
|
|
1771
1046
|
}
|
|
1772
|
-
`}function
|
|
1047
|
+
`}function Lo(e){return `// Package docs provides the swaggo-generated OpenAPI specification.
|
|
1773
1048
|
//
|
|
1774
1049
|
// Run \`make docs\` to regenerate after changing handler annotations.
|
|
1775
1050
|
//
|
|
1776
|
-
// @title ${
|
|
1051
|
+
// @title ${or(e.project_name)} API
|
|
1777
1052
|
// @version ${e.app_version}
|
|
1778
1053
|
// @description ${e.description}
|
|
1779
1054
|
// @host localhost:${e.port}
|
|
@@ -1783,7 +1058,7 @@ func TestTooManyRequests(t *testing.T) {
|
|
|
1783
1058
|
// @contact.name ${e.author}
|
|
1784
1059
|
// @license.name MIT
|
|
1785
1060
|
package docs
|
|
1786
|
-
`}function
|
|
1061
|
+
`}function qo(e){return `package handlers
|
|
1787
1062
|
|
|
1788
1063
|
import (
|
|
1789
1064
|
"net/http"
|
|
@@ -1825,7 +1100,7 @@ func EchoParams(c *fiber.Ctx) error {
|
|
|
1825
1100
|
RequestID: rid,
|
|
1826
1101
|
})
|
|
1827
1102
|
}
|
|
1828
|
-
`}function
|
|
1103
|
+
`}function Fo(e){return `package handlers_test
|
|
1829
1104
|
|
|
1830
1105
|
import (
|
|
1831
1106
|
"encoding/json"
|
|
@@ -1893,7 +1168,7 @@ func TestEchoParams_EmptyName(t *testing.T) {
|
|
|
1893
1168
|
t.Fatalf("expected code=BAD_REQUEST, got %v", body["code"])
|
|
1894
1169
|
}
|
|
1895
1170
|
}
|
|
1896
|
-
`}function
|
|
1171
|
+
`}function Ho(e){return `package config_test
|
|
1897
1172
|
|
|
1898
1173
|
import (
|
|
1899
1174
|
"log/slog"
|
|
@@ -1961,7 +1236,7 @@ func TestLoad_Defaults(t *testing.T) {
|
|
|
1961
1236
|
t.Errorf("expected default LogLevel=debug (development env), got %q", cfg.LogLevel)
|
|
1962
1237
|
}
|
|
1963
1238
|
}
|
|
1964
|
-
`}function
|
|
1239
|
+
`}function Ko(){return `package middleware
|
|
1965
1240
|
|
|
1966
1241
|
import (
|
|
1967
1242
|
"os"
|
|
@@ -1989,7 +1264,7 @@ func CORS() fiber.Handler {
|
|
|
1989
1264
|
MaxAge: 600,
|
|
1990
1265
|
})
|
|
1991
1266
|
}
|
|
1992
|
-
`}function
|
|
1267
|
+
`}function Uo(e){return `package middleware_test
|
|
1993
1268
|
|
|
1994
1269
|
import (
|
|
1995
1270
|
"net/http"
|
|
@@ -2061,7 +1336,7 @@ func TestCORS_Default_Origin(t *testing.T) {
|
|
|
2061
1336
|
t.Fatal("expected CORS header when origins defaulting to *")
|
|
2062
1337
|
}
|
|
2063
1338
|
}
|
|
2064
|
-
`}function
|
|
1339
|
+
`}function Wo(e){return `package server_test
|
|
2065
1340
|
|
|
2066
1341
|
import (
|
|
2067
1342
|
"encoding/json"
|
|
@@ -2150,7 +1425,7 @@ func TestServer_Docs_Redirect(t *testing.T) {
|
|
|
2150
1425
|
t.Fatalf("expected Location=/docs/index.html, got %q", loc)
|
|
2151
1426
|
}
|
|
2152
1427
|
}
|
|
2153
|
-
`}function
|
|
1428
|
+
`}function Vo(e){return `package middleware
|
|
2154
1429
|
|
|
2155
1430
|
import (
|
|
2156
1431
|
"os"
|
|
@@ -2183,7 +1458,7 @@ func RateLimit() fiber.Handler {
|
|
|
2183
1458
|
},
|
|
2184
1459
|
})
|
|
2185
1460
|
}
|
|
2186
|
-
`}function
|
|
1461
|
+
`}function Bo(e){return `package middleware_test
|
|
2187
1462
|
|
|
2188
1463
|
import (
|
|
2189
1464
|
"net/http"
|
|
@@ -2259,7 +1534,7 @@ func TestRateLimit_InvalidRPS(t *testing.T) {
|
|
|
2259
1534
|
t.Fatalf("expected 200 with invalid RPS env, got %d", resp.StatusCode)
|
|
2260
1535
|
}
|
|
2261
1536
|
}
|
|
2262
|
-
`}function
|
|
1537
|
+
`}function Jo(e){return `# Air \u2014 live reload for Go projects
|
|
2263
1538
|
# https://github.com/air-verse/air
|
|
2264
1539
|
root = "."
|
|
2265
1540
|
tmp_dir = "tmp"
|
|
@@ -2283,7 +1558,7 @@ tmp_dir = "tmp"
|
|
|
2283
1558
|
|
|
2284
1559
|
[log]
|
|
2285
1560
|
time = false
|
|
2286
|
-
`}function
|
|
1561
|
+
`}function Yo(e){return `run:
|
|
2287
1562
|
timeout: 5m
|
|
2288
1563
|
|
|
2289
1564
|
linters:
|
|
@@ -2329,7 +1604,7 @@ issues:
|
|
|
2329
1604
|
linters:
|
|
2330
1605
|
- errcheck
|
|
2331
1606
|
- wrapcheck
|
|
2332
|
-
`}function
|
|
1607
|
+
`}function zo(){return JSON.stringify({engine:"npm",runtime:"go"},null,2)}function Qo(e){return `#!/usr/bin/env sh
|
|
2333
1608
|
# RapidKit Go/Fiber project launcher \u2014 generated by RapidKit CLI
|
|
2334
1609
|
# https://getrapidkit.com
|
|
2335
1610
|
|
|
@@ -2408,7 +1683,7 @@ case "$CMD" in
|
|
|
2408
1683
|
exit 1
|
|
2409
1684
|
;;
|
|
2410
1685
|
esac
|
|
2411
|
-
`}function
|
|
1686
|
+
`}function Xo(e){return `@echo off
|
|
2412
1687
|
rem RapidKit Go/Fiber project launcher \u2014 Windows
|
|
2413
1688
|
set CMD=%1
|
|
2414
1689
|
if "%CMD%"=="" goto usage
|
|
@@ -2433,8 +1708,8 @@ if "%CMD%"=="start" ( bin\\${e.project_name}.exe %* & exit /b %ERRORLEVEL% )
|
|
|
2433
1708
|
:usage
|
|
2434
1709
|
echo Available: init, dev, start, build, docs, test, lint, format
|
|
2435
1710
|
exit /b 1
|
|
2436
|
-
`}function
|
|
2437
|
-
`));}let i=
|
|
1711
|
+
`}function Zo(e,r){return JSON.stringify({kit_name:"gofiber.standard",runtime:"go",module_support:false,project_name:e.project_name,module_path:e.module_path,app_version:e.app_version,created_by:"rapidkit-npm",rapidkit_version:r,created_at:new Date().toISOString()},null,2)}async function Nt(e,r){let t={project_name:r.project_name,module_path:r.module_path||r.project_name,author:r.author||"RapidKit User",description:r.description||`Go/Fiber REST API \u2014 ${r.project_name}`,go_version:r.go_version||"1.24",app_version:r.app_version||"0.1.0",port:r.port||"3000",skipGit:r.skipGit??false},o=c();try{await execa("go",["version"],{timeout:3e3});}catch{console.log(l.yellow("\n\u26A0 Go not found in PATH \u2014 project will be scaffolded, but `go mod tidy` requires Go 1.21+")),console.log(l.gray(` Install: https://go.dev/dl/
|
|
1712
|
+
`));}let i=At(`Generating Go/Fiber project: ${t.project_name}\u2026`).start();try{let n=(c,p)=>bo(f.join(e,c),p),a=f.join(e,"rapidkit"),s=f.join(e,"rapidkit.cmd");await Promise.all([n("cmd/server/main.go",Ro(t)),n("go.mod",Co(t)),n("internal/config/config.go",So(t)),n("internal/server/server.go",_o(t)),n("internal/middleware/requestid.go",$o()),n("internal/middleware/requestid_test.go",Do(t)),n("internal/apierr/apierr.go",Go()),n("internal/apierr/apierr_test.go",Mo(t)),n("internal/handlers/health.go",xo()),n("internal/handlers/health_test.go",Po(t)),n("internal/handlers/example.go",qo(t)),n("internal/handlers/example_test.go",Fo(t)),n("internal/config/config_test.go",Ho(t)),n("internal/middleware/cors.go",Ko()),n("internal/middleware/cors_test.go",Uo(t)),n("internal/middleware/ratelimit.go",Vo(t)),n("internal/middleware/ratelimit_test.go",Bo(t)),n("internal/server/server_test.go",Wo(t)),n("docs/doc.go",Lo(t)),n(".air.toml",Jo(t)),n("Dockerfile",Eo()),n("docker-compose.yml",Io(t)),n("Makefile",To(t)),n(".golangci.yml",Yo(t.module_path)),n(".env.example",Oo(t)),n(".gitignore",Ao()),n(".github/workflows/ci.yml",No(t)),n("README.md",jo(t)),n(".rapidkit/project.json",Zo(t,o)),n(".rapidkit/context.json",zo()),n("rapidkit",Qo(t)),n("rapidkit.cmd",Xo(t))]),await promises.chmod(a,493),await promises.chmod(s,493),i.succeed(l.green(`Project created at ${e}`));try{i.start("Fetching Go dependencies\u2026"),await execa("go",["mod","tidy"],{cwd:e,timeout:12e4}),i.succeed(l.gray("\u2713 go mod tidy completed"));}catch{i.warn(l.yellow("\u26A0 go mod tidy failed \u2014 run manually: go mod tidy"));}if(!t.skipGit)try{await execa("git",["init"],{cwd:e}),await execa("git",["add","-A"],{cwd:e}),await execa("git",["commit","-m","chore: initial scaffold (rapidkit gofiber.standard)"],{cwd:e}),console.log(l.gray("\u2713 git repository initialized"));}catch{console.log(l.gray("\u26A0 git init skipped (git not found or error)"));}console.log(""),console.log(l.bold("\u2705 Go/Fiber project ready!")),console.log(""),console.log(l.cyan("Next steps:")),console.log(l.white(` cd ${t.project_name}`)),console.log(l.white(" make run # start dev server")),console.log(l.white(" make test # run tests")),console.log(""),console.log(l.gray("Server will listen on port "+t.port)),console.log(l.gray(" http://localhost:"+t.port+"/api/v1/health/live")),console.log(l.gray(" http://localhost:"+t.port+"/api/v1/health/ready")),console.log(""),console.log(l.yellow("\u2139 RapidKit modules are not available for Go projects (module system uses Python/pip).")),console.log("");}catch(n){throw i.fail(l.red("Failed to generate Go/Fiber project")),n}}function ir(e){return e.split(/[-_\s]+/).map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join("")}async function ti(e,r){await promises.mkdir(f.dirname(e),{recursive:true}),await promises.writeFile(e,r,"utf8");}function ri(e){return `package main
|
|
2438
1713
|
|
|
2439
1714
|
import (
|
|
2440
1715
|
"context"
|
|
@@ -2501,7 +1776,7 @@ func main() {
|
|
|
2501
1776
|
}
|
|
2502
1777
|
slog.Info("server stopped")
|
|
2503
1778
|
}
|
|
2504
|
-
`}function
|
|
1779
|
+
`}function oi(e){return `module ${e.module_path}
|
|
2505
1780
|
|
|
2506
1781
|
go ${e.go_version}
|
|
2507
1782
|
|
|
@@ -2550,7 +1825,7 @@ require (
|
|
|
2550
1825
|
gopkg.in/yaml.v2 v2.4.0 // indirect
|
|
2551
1826
|
gopkg.in/yaml.v3 v3.0.1 // indirect
|
|
2552
1827
|
)
|
|
2553
|
-
`}function
|
|
1828
|
+
`}function ii(e){return `package config
|
|
2554
1829
|
|
|
2555
1830
|
import (
|
|
2556
1831
|
"log/slog"
|
|
@@ -2605,7 +1880,7 @@ func getEnv(key, fallback string) string {
|
|
|
2605
1880
|
}
|
|
2606
1881
|
return fallback
|
|
2607
1882
|
}
|
|
2608
|
-
`}function
|
|
1883
|
+
`}function ni(e){return `package server
|
|
2609
1884
|
|
|
2610
1885
|
import (
|
|
2611
1886
|
"net/http"
|
|
@@ -2657,7 +1932,7 @@ func NewRouter(cfg *config.Config) *gin.Engine {
|
|
|
2657
1932
|
|
|
2658
1933
|
return r
|
|
2659
1934
|
}
|
|
2660
|
-
`}function
|
|
1935
|
+
`}function si(){return `package handlers
|
|
2661
1936
|
|
|
2662
1937
|
import (
|
|
2663
1938
|
"net/http"
|
|
@@ -2696,7 +1971,7 @@ func Readiness(c *gin.Context) {
|
|
|
2696
1971
|
"time": time.Now().UTC().Format(time.RFC3339),
|
|
2697
1972
|
})
|
|
2698
1973
|
}
|
|
2699
|
-
`}function
|
|
1974
|
+
`}function ai(e){return `package handlers_test
|
|
2700
1975
|
|
|
2701
1976
|
import (
|
|
2702
1977
|
"encoding/json"
|
|
@@ -2741,7 +2016,7 @@ func TestReadiness(t *testing.T) {
|
|
|
2741
2016
|
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
|
|
2742
2017
|
}
|
|
2743
2018
|
}
|
|
2744
|
-
`}function
|
|
2019
|
+
`}function ci(){return `# \u2500\u2500 Build stage \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
2745
2020
|
FROM golang:1.24-alpine AS builder
|
|
2746
2021
|
|
|
2747
2022
|
# Build-time version injection
|
|
@@ -2770,7 +2045,7 @@ EXPOSE 8080
|
|
|
2770
2045
|
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \\
|
|
2771
2046
|
CMD wget -qO- http://localhost:8080/api/v1/health/live || exit 1
|
|
2772
2047
|
ENTRYPOINT ["/server"]
|
|
2773
|
-
`}function
|
|
2048
|
+
`}function li(e){return `version: "3.9"
|
|
2774
2049
|
|
|
2775
2050
|
services:
|
|
2776
2051
|
api:
|
|
@@ -2786,7 +2061,7 @@ services:
|
|
|
2786
2061
|
CORS_ALLOW_ORIGINS: "*"
|
|
2787
2062
|
RATE_LIMIT_RPS: "100"
|
|
2788
2063
|
restart: unless-stopped
|
|
2789
|
-
`}function
|
|
2064
|
+
`}function di(e){return `.PHONY: dev run build test cover lint fmt tidy docs docker-up docker-down
|
|
2790
2065
|
|
|
2791
2066
|
# Build-time metadata
|
|
2792
2067
|
VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo "dev")
|
|
@@ -2840,7 +2115,7 @@ docker-up:
|
|
|
2840
2115
|
|
|
2841
2116
|
docker-down:
|
|
2842
2117
|
docker compose down
|
|
2843
|
-
`}function
|
|
2118
|
+
`}function pi(e){return `# Application
|
|
2844
2119
|
PORT=${e.port}
|
|
2845
2120
|
APP_ENV=development
|
|
2846
2121
|
GIN_MODE=debug
|
|
@@ -2851,7 +2126,7 @@ CORS_ALLOW_ORIGINS=*
|
|
|
2851
2126
|
|
|
2852
2127
|
# Rate limiting \u2014 max requests per IP per second
|
|
2853
2128
|
RATE_LIMIT_RPS=100
|
|
2854
|
-
`}function
|
|
2129
|
+
`}function ui(){return `# Binaries
|
|
2855
2130
|
bin/
|
|
2856
2131
|
*.exe
|
|
2857
2132
|
*.exe~
|
|
@@ -2891,7 +2166,7 @@ docs/docs.go
|
|
|
2891
2166
|
# OS
|
|
2892
2167
|
.DS_Store
|
|
2893
2168
|
Thumbs.db
|
|
2894
|
-
`}function
|
|
2169
|
+
`}function gi(e){return `name: CI
|
|
2895
2170
|
|
|
2896
2171
|
on:
|
|
2897
2172
|
push:
|
|
@@ -2945,7 +2220,7 @@ jobs:
|
|
|
2945
2220
|
uses: golangci/golangci-lint-action@v6
|
|
2946
2221
|
with:
|
|
2947
2222
|
version: latest
|
|
2948
|
-
`}function
|
|
2223
|
+
`}function mi(e){return `# ${ir(e.project_name)}
|
|
2949
2224
|
|
|
2950
2225
|
> ${e.description}
|
|
2951
2226
|
|
|
@@ -3061,7 +2336,7 @@ ${e.project_name}/
|
|
|
3061
2336
|
## License
|
|
3062
2337
|
|
|
3063
2338
|
${e.app_version} \xB7 ${e.author}
|
|
3064
|
-
`}function
|
|
2339
|
+
`}function fi(){return `package middleware
|
|
3065
2340
|
|
|
3066
2341
|
import (
|
|
3067
2342
|
"crypto/rand"
|
|
@@ -3113,7 +2388,7 @@ func newID() string {
|
|
|
3113
2388
|
}
|
|
3114
2389
|
return hex.EncodeToString(b)
|
|
3115
2390
|
}
|
|
3116
|
-
`}function
|
|
2391
|
+
`}function hi(e){return `package middleware_test
|
|
3117
2392
|
|
|
3118
2393
|
import (
|
|
3119
2394
|
"net/http"
|
|
@@ -3162,7 +2437,7 @@ func TestRequestID_IsReused(t *testing.T) {
|
|
|
3162
2437
|
t.Fatalf("expected X-Request-ID to be reused, got %q", id)
|
|
3163
2438
|
}
|
|
3164
2439
|
}
|
|
3165
|
-
`}function
|
|
2440
|
+
`}function yi(){return `// Package apierr provides a consistent JSON error envelope for all API responses.
|
|
3166
2441
|
//
|
|
3167
2442
|
// Every error response looks like:
|
|
3168
2443
|
//
|
|
@@ -3225,7 +2500,7 @@ func InternalError(c *gin.Context, _ error) {
|
|
|
3225
2500
|
func TooManyRequests(c *gin.Context) {
|
|
3226
2501
|
reply(c, http.StatusTooManyRequests, "rate limit exceeded", "TOO_MANY_REQUESTS")
|
|
3227
2502
|
}
|
|
3228
|
-
`}function
|
|
2503
|
+
`}function wi(e){return `package apierr_test
|
|
3229
2504
|
|
|
3230
2505
|
import (
|
|
3231
2506
|
"encoding/json"
|
|
@@ -3351,11 +2626,11 @@ func TestTooManyRequests(t *testing.T) {
|
|
|
3351
2626
|
t.Fatalf("expected TOO_MANY_REQUESTS, got %q", body.Code)
|
|
3352
2627
|
}
|
|
3353
2628
|
}
|
|
3354
|
-
`}function
|
|
2629
|
+
`}function vi(e){return `// Package docs provides the swaggo-generated OpenAPI specification.
|
|
3355
2630
|
//
|
|
3356
2631
|
// Run \`make docs\` to regenerate after changing handler annotations.
|
|
3357
2632
|
//
|
|
3358
|
-
// @title ${
|
|
2633
|
+
// @title ${ir(e.project_name)} API
|
|
3359
2634
|
// @version ${e.app_version}
|
|
3360
2635
|
// @description ${e.description}
|
|
3361
2636
|
// @host localhost:${e.port}
|
|
@@ -3365,7 +2640,7 @@ func TestTooManyRequests(t *testing.T) {
|
|
|
3365
2640
|
// @contact.name ${e.author}
|
|
3366
2641
|
// @license.name MIT
|
|
3367
2642
|
package docs
|
|
3368
|
-
`}function
|
|
2643
|
+
`}function ki(e){return `package handlers
|
|
3369
2644
|
|
|
3370
2645
|
import (
|
|
3371
2646
|
"net/http"
|
|
@@ -3407,7 +2682,7 @@ func EchoParams(c *gin.Context) {
|
|
|
3407
2682
|
RequestID: c.GetString("X-Request-ID"),
|
|
3408
2683
|
})
|
|
3409
2684
|
}
|
|
3410
|
-
`}function
|
|
2685
|
+
`}function bi(e){return `package handlers_test
|
|
3411
2686
|
|
|
3412
2687
|
import (
|
|
3413
2688
|
"encoding/json"
|
|
@@ -3472,7 +2747,7 @@ func TestEchoParams_EmptyName(t *testing.T) {
|
|
|
3472
2747
|
t.Fatalf("expected code=BAD_REQUEST, got %v", body["code"])
|
|
3473
2748
|
}
|
|
3474
2749
|
}
|
|
3475
|
-
`}function
|
|
2750
|
+
`}function Ri(e){return `package config_test
|
|
3476
2751
|
|
|
3477
2752
|
import (
|
|
3478
2753
|
"log/slog"
|
|
@@ -3548,7 +2823,7 @@ func TestLoad_Defaults(t *testing.T) {
|
|
|
3548
2823
|
t.Errorf("expected default GinMode=debug, got %q", cfg.GinMode)
|
|
3549
2824
|
}
|
|
3550
2825
|
}
|
|
3551
|
-
`}function
|
|
2826
|
+
`}function Ci(){return `package middleware
|
|
3552
2827
|
|
|
3553
2828
|
import (
|
|
3554
2829
|
"net/http"
|
|
@@ -3596,7 +2871,7 @@ func CORS() gin.HandlerFunc {
|
|
|
3596
2871
|
c.Next()
|
|
3597
2872
|
}
|
|
3598
2873
|
}
|
|
3599
|
-
`}function
|
|
2874
|
+
`}function Si(e){return `package middleware_test
|
|
3600
2875
|
|
|
3601
2876
|
import (
|
|
3602
2877
|
"net/http"
|
|
@@ -3682,7 +2957,7 @@ func TestCORS_Default_Origin(t *testing.T) {
|
|
|
3682
2957
|
t.Fatal("expected CORS header when CORS_ALLOW_ORIGINS defaults to *")
|
|
3683
2958
|
}
|
|
3684
2959
|
}
|
|
3685
|
-
`}function
|
|
2960
|
+
`}function _i(e){return `package server_test
|
|
3686
2961
|
|
|
3687
2962
|
import (
|
|
3688
2963
|
"encoding/json"
|
|
@@ -3792,7 +3067,7 @@ func TestServer_ReleaseMode(t *testing.T) {
|
|
|
3792
3067
|
t.Fatalf("expected 200 in release mode, got %d", w.Code)
|
|
3793
3068
|
}
|
|
3794
3069
|
}
|
|
3795
|
-
`}function
|
|
3070
|
+
`}function xi(e){return `package middleware
|
|
3796
3071
|
|
|
3797
3072
|
import (
|
|
3798
3073
|
"os"
|
|
@@ -3843,7 +3118,7 @@ func RateLimit() gin.HandlerFunc {
|
|
|
3843
3118
|
c.Next()
|
|
3844
3119
|
}
|
|
3845
3120
|
}
|
|
3846
|
-
`}function
|
|
3121
|
+
`}function Pi(e){return `package middleware_test
|
|
3847
3122
|
|
|
3848
3123
|
import (
|
|
3849
3124
|
"net/http"
|
|
@@ -3912,7 +3187,7 @@ func TestRateLimit_InvalidRPS(t *testing.T) {
|
|
|
3912
3187
|
t.Fatalf("expected 200 with invalid RPS env, got %d", w.Code)
|
|
3913
3188
|
}
|
|
3914
3189
|
}
|
|
3915
|
-
`}function
|
|
3190
|
+
`}function Ei(e){return `# Air \u2014 live reload for Go projects
|
|
3916
3191
|
# https://github.com/air-verse/air
|
|
3917
3192
|
root = "."
|
|
3918
3193
|
tmp_dir = "tmp"
|
|
@@ -3937,7 +3212,7 @@ tmp_dir = "tmp"
|
|
|
3937
3212
|
|
|
3938
3213
|
[log]
|
|
3939
3214
|
time = false
|
|
3940
|
-
`}function
|
|
3215
|
+
`}function Ii(e){return `run:
|
|
3941
3216
|
timeout: 5m
|
|
3942
3217
|
|
|
3943
3218
|
linters:
|
|
@@ -3983,7 +3258,7 @@ issues:
|
|
|
3983
3258
|
linters:
|
|
3984
3259
|
- errcheck
|
|
3985
3260
|
- wrapcheck
|
|
3986
|
-
`}function
|
|
3261
|
+
`}function Ti(){return JSON.stringify({engine:"npm",runtime:"go"},null,2)}function Oi(e,r){return JSON.stringify({kit_name:"gogin.standard",runtime:"go",module_support:false,project_name:e.project_name,module_path:e.module_path,app_version:e.app_version,created_by:"rapidkit-npm",rapidkit_version:r,created_at:new Date().toISOString()},null,2)}function Ai(e){return `#!/usr/bin/env sh
|
|
3987
3262
|
# RapidKit Go/Gin project launcher \u2014 generated by RapidKit CLI
|
|
3988
3263
|
# https://getrapidkit.com
|
|
3989
3264
|
|
|
@@ -4062,7 +3337,7 @@ case "$CMD" in
|
|
|
4062
3337
|
exit 1
|
|
4063
3338
|
;;
|
|
4064
3339
|
esac
|
|
4065
|
-
`}function
|
|
3340
|
+
`}function Ni(e){return `@echo off
|
|
4066
3341
|
rem RapidKit Go/Gin project launcher \u2014 Windows
|
|
4067
3342
|
set CMD=%1
|
|
4068
3343
|
if "%CMD%"=="" goto usage
|
|
@@ -4087,169 +3362,190 @@ if "%CMD%"=="start" ( bin\\${e.project_name}.exe %* & exit /b %ERRORLEVEL% )
|
|
|
4087
3362
|
:usage
|
|
4088
3363
|
echo Available: init, dev, start, build, docs, test, lint, format
|
|
4089
3364
|
exit /b 1
|
|
4090
|
-
`}async function
|
|
4091
|
-
`));}let i=pt(`Generating Go/Gin project: ${t.project_name}\u2026`).start();try{let n=(a,l)=>Vr(v.join(e,a),l),s=v.join(e,"rapidkit"),c=v.join(e,"rapidkit.cmd");await Promise.all([n("cmd/server/main.go",Wr(t)),n("go.mod",Br(t)),n("internal/config/config.go",Jr(t)),n("internal/server/server.go",zr(t)),n("internal/middleware/requestid.go",sn()),n("internal/middleware/requestid_test.go",an(t)),n("internal/apierr/apierr.go",cn()),n("internal/apierr/apierr_test.go",dn(t)),n("internal/handlers/health.go",Yr()),n("internal/handlers/health_test.go",Qr(t)),n("internal/handlers/example.go",pn(t)),n("internal/handlers/example_test.go",un(t)),n("internal/config/config_test.go",gn(t)),n("internal/middleware/cors.go",mn()),n("internal/middleware/cors_test.go",fn(t)),n("internal/middleware/ratelimit.go",wn(t)),n("internal/middleware/ratelimit_test.go",yn(t)),n("internal/server/server_test.go",hn(t)),n("docs/doc.go",ln(t)),n(".air.toml",vn(t)),n("Dockerfile",Xr()),n("docker-compose.yml",Zr(t)),n("Makefile",en(t)),n(".golangci.yml",bn(t.module_path)),n(".env.example",tn(t)),n(".gitignore",on()),n(".github/workflows/ci.yml",rn(t)),n("README.md",nn(t)),n(".rapidkit/project.json",Rn(t,r)),n(".rapidkit/context.json",kn()),n("rapidkit",xn(t)),n("rapidkit.cmd",Cn(t))]),await promises.chmod(s,493),await promises.chmod(c,493),i.succeed(g.green(`Project created at ${e}`));try{i.start("Fetching Go dependencies\u2026"),await execa("go",["mod","tidy"],{cwd:e,timeout:12e4}),i.succeed(g.gray("\u2713 go mod tidy completed"));}catch{i.warn(g.yellow("\u26A0 go mod tidy failed \u2014 run manually: go mod tidy"));}if(!t.skipGit)try{await execa("git",["init"],{cwd:e}),await execa("git",["add","-A"],{cwd:e}),await execa("git",["commit","-m","chore: initial scaffold (rapidkit gogin.standard)"],{cwd:e}),console.log(g.gray("\u2713 git repository initialized"));}catch{console.log(g.gray("\u26A0 git init skipped (git not found or error)"));}console.log(""),console.log(g.bold("\u2705 Go/Gin project ready!")),console.log(""),console.log(g.cyan("Next steps:")),console.log(g.white(` cd ${t.project_name}`)),console.log(g.white(" make run # start dev server")),console.log(g.white(" make test # run tests")),console.log(""),console.log(g.gray("Server will listen on port "+t.port)),console.log(g.gray(" http://localhost:"+t.port+"/api/v1/health/live")),console.log(g.gray(" http://localhost:"+t.port+"/api/v1/health/ready")),console.log(""),console.log(g.yellow("\u2139 RapidKit modules are not available for Go projects (module system uses Python/pip).")),console.log("");}catch(n){throw i.fail(g.red("Failed to generate Go/Gin project")),n}}async function Yt(){let e=process.platform==="win32"?["python","python3"]:["python3","python"];for(let o of e)try{let{stdout:t}=await execa(o,["--version"],{timeout:3e3}),r=t.match(/Python (\d+\.\d+\.\d+)/);if(r){let i=r[1],[n,s]=i.split(".").map(Number);return n<3||n===3&&s<10?{status:"warn",message:`Python ${i} (requires 3.10+)`,details:`${o} found but version is below minimum requirement`}:{status:"ok",message:`Python ${i}`,details:`Using ${o}`}}}catch{continue}return {status:"error",message:"Python not found",details:"Install Python 3.10+ and ensure it's in PATH"}}async function Qt(){try{let{stdout:e}=await execa("poetry",["--version"],{timeout:3e3}),o=e.match(/Poetry .*version ([\d.]+)/);return o?{status:"ok",message:`Poetry ${o[1]}`,details:"Available for dependency management"}:{status:"warn",message:"Poetry version unknown"}}catch{return {status:"warn",message:"Poetry not installed",details:"Optional: Install for better dependency management"}}}async function Xt(){try{let{stdout:e}=await execa("pipx",["--version"],{timeout:3e3});return {status:"ok",message:`pipx ${e.trim()}`,details:"Available for global tool installation"}}catch{return {status:"warn",message:"pipx not installed",details:"Optional: Install for isolated Python tools"}}}async function Zt(){try{let{stdout:e}=await execa("go",["version"],{timeout:3e3}),o=e.match(/go version go(\d+\.\d+(?:\.\d+)?)/);return o?{status:"ok",message:`Go ${o[1]}`,details:"Available for Go/Fiber and Go/Gin projects"}:{status:"ok",message:"Go (version unknown)",details:"go found in PATH"}}catch{return {status:"warn",message:"Go not installed",details:"Optional: Required only for gofiber.standard / gogin.standard projects \u2014 https://go.dev/dl/"}}}async function eo(){let e=process.env.HOME||process.env.USERPROFILE||"",o=[],t=[{location:"Global (pipx)",path:v.join(e,".local","bin","rapidkit")},{location:"Global (pipx)",path:v.join(e,"AppData","Roaming","Python","Scripts","rapidkit.exe")},{location:"Global (pyenv)",path:v.join(e,".pyenv","shims","rapidkit")},{location:"Global (system)",path:"/usr/local/bin/rapidkit"},{location:"Global (system)",path:"/usr/bin/rapidkit"}],r=[{location:"Workspace (.venv)",path:v.join(process.cwd(),".venv","bin","rapidkit")},{location:"Workspace (.venv)",path:v.join(process.cwd(),".venv","Scripts","rapidkit.exe")}];for(let{location:n,path:s}of [...t,...r])try{if(await R__default.pathExists(s)){let{stdout:c,exitCode:a}=await execa(s,["--version"],{timeout:3e3,reject:false});if(a===0&&(c.includes("RapidKit Version")||c.includes("RapidKit"))){let l=c.match(/v?([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);l&&o.push({location:n,path:s,version:l[1]});}}}catch{continue}if(o.length>0)return {status:"ok",message:`RapidKit Core ${o[0].version}`,paths:o.map(s=>({location:s.location,path:s.path,version:s.version}))};try{let{stdout:n,exitCode:s}=await execa("rapidkit",["--version"],{timeout:3e3,reject:false});if(s===0&&(n.includes("RapidKit Version")||n.includes("RapidKit"))){let c=n.match(/v?([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);if(c)return {status:"ok",message:`RapidKit Core ${c[1]}`,details:"Available via PATH"}}}catch{}try{let{stdout:n,exitCode:s}=await execa("poetry",["run","rapidkit","--version"],{timeout:3e3,reject:false});if(s===0&&(n.includes("RapidKit Version")||n.includes("RapidKit"))){let c=n.match(/v?([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);if(c)return {status:"ok",message:`RapidKit Core ${c[1]}`,details:"Available via Poetry"}}}catch{}let i=process.platform==="win32"?["python","python3"]:["python3","python"];for(let n of i)try{let{stdout:s,exitCode:c}=await execa(n,["-c","import rapidkit_core; print(rapidkit_core.__version__)"],{timeout:3e3,reject:false});if(c===0&&s&&!s.includes("Traceback")&&!s.includes("ModuleNotFoundError")){let a=s.trim();if(a)return {status:"ok",message:`RapidKit Core ${a}`,details:`Available in ${n} environment`}}}catch{continue}return {status:"error",message:"RapidKit Core not installed",details:"Install with: pipx install rapidkit-core"}}async function Fe(e,o){let t=v.join(e,"Dockerfile");o.hasDocker=await R__default.pathExists(t);let r=v.join(e,"tests"),i=v.join(e,"test"),n=await R__default.pathExists(r)||await R__default.pathExists(i),s=false;if(o.framework==="Go/Fiber"||o.framework==="Go/Gin")try{let c=[{dir:e,depth:0}],a=4,l=new Set([".git",".venv","node_modules","dist","build","vendor"]);for(;c.length>0&&!s;){let d=c.shift();if(!d)break;let p=[];try{p=await R__default.readdir(d.dir);}catch{continue}for(let u of p){let h=v.join(d.dir,u),x;try{x=await R__default.stat(h);}catch{continue}if(x.isFile()&&u.endsWith("_test.go")){s=true;break}x.isDirectory()&&d.depth<a&&!l.has(u)&&!u.startsWith(".")&&c.push({dir:h,depth:d.depth+1});}}}catch{}if(o.hasTests=n||s,o.framework==="NestJS"){let c=v.join(e,".eslintrc.js"),a=v.join(e,".eslintrc.json");o.hasCodeQuality=await R__default.pathExists(c)||await R__default.pathExists(a);}else if(o.framework==="Go/Fiber"||o.framework==="Go/Gin"){let c=v.join(e,".golangci.yml"),a=v.join(e,".golangci.yaml"),l=v.join(e,"Makefile"),d=await R__default.pathExists(l)&&(await R__default.readFile(l,"utf8")).includes("golangci-lint");o.hasCodeQuality=await R__default.pathExists(c)||await R__default.pathExists(a)||d;}else if(o.framework==="FastAPI"){let c=v.join(e,"ruff.toml"),a=v.join(e,"pyproject.toml");if(await R__default.pathExists(a))try{let l=await R__default.readFile(a,"utf8");o.hasCodeQuality=l.includes("[tool.ruff]")||await R__default.pathExists(c);}catch{o.hasCodeQuality=await R__default.pathExists(c);}}try{if(o.framework==="NestJS"){let{stdout:c}=await execa("npm",["audit","--json"],{cwd:e,reject:false});if(c)try{let l=JSON.parse(c).metadata?.vulnerabilities;l&&(o.vulnerabilities=(l.high||0)+(l.critical||0)+(l.moderate||0));}catch{}}else if(o.framework==="FastAPI"){let c=v.join(e,".venv"),a=process.platform==="win32"?v.join(c,"Scripts","python.exe"):v.join(c,"bin","python");if(await R__default.pathExists(a))try{let{stdout:l}=await execa(a,["-m","pip","list","--format=json"],{timeout:5e3,reject:false});if(l){JSON.parse(l);o.vulnerabilities=0;}}catch{}}}catch{}}async function _n(e){let t={name:v.basename(e),path:e,venvActive:false,depsInstalled:false,coreInstalled:false,issues:[],fixCommands:[]},r=v.join(e,".rapidkit");if(!await R__default.pathExists(r))return t.issues.push("Not a valid RapidKit project (missing .rapidkit directory)"),t;try{let p=v.join(e,"registry.json");if(await R__default.pathExists(p)){let u=await R__default.readJson(p);u.installed_modules&&(t.stats={modules:u.installed_modules.length});}}catch{}let i=null;try{let p=v.join(r,"project.json");if(await R__default.pathExists(p)){i=await R__default.readJson(p);let u=i?.kit_name||i?.kit;u&&(t.kit=u);}}catch{}try{let p=v.join(e,".git");if(await R__default.pathExists(p)){let{stdout:u}=await execa("git",["log","-1","--format=%cr"],{cwd:e,reject:false});u&&(t.lastModified=u.trim());}else {let u=await R__default.stat(e),x=Date.now()-u.mtime.getTime(),y=Math.floor(x/(1e3*60*60*24));t.lastModified=y===0?"today":`${y} day${y>1?"s":""} ago`;}}catch{}let n=v.join(e,"package.json"),s=v.join(e,"pyproject.toml"),c=v.join(e,"go.mod");if(await R__default.pathExists(c)||i?.runtime==="go"||typeof i?.kit_name=="string"&&(i.kit_name.startsWith("gofiber")||i.kit_name.startsWith("gogin"))){let p=i?.kit_name??"";t.framework=p.startsWith("gogin")?"Go/Gin":"Go/Fiber",t.isGoProject=true,t.venvActive=true,t.coreInstalled=false;try{await execa("go",["version"],{timeout:3e3});}catch{t.issues.push("Go toolchain not found \u2014 install from https://go.dev/dl/"),t.fixCommands?.push("https://go.dev/dl/");}let u=v.join(e,"go.sum");return await R__default.pathExists(u)?t.depsInstalled=true:(t.depsInstalled=false,t.issues.push("Go dependencies not downloaded (go.sum missing)"),t.fixCommands?.push(`cd ${e} && go mod tidy`)),await Fe(e,t),t}let l=await R__default.pathExists(n),d=await R__default.pathExists(s);if(l){t.framework="NestJS",t.venvActive=true;let p=v.join(e,"node_modules");if(await R__default.pathExists(p))try{let y=(await R__default.readdir(p)).filter(C=>!C.startsWith(".")&&!C.startsWith("_"));t.depsInstalled=y.length>0;}catch{t.depsInstalled=false;}t.depsInstalled||(t.issues.push("Dependencies not installed (node_modules empty or missing)"),t.fixCommands?.push(`cd ${e} && rapidkit init`)),t.coreInstalled=false;let u=v.join(e,".env");if(t.hasEnvFile=await R__default.pathExists(u),!t.hasEnvFile){let x=v.join(e,".env.example");await R__default.pathExists(x)&&(t.issues.push("Environment file missing (found .env.example)"),t.fixCommands?.push(`cd ${e} && cp .env.example .env`));}let h=v.join(e,"src");if(t.modulesHealthy=true,t.missingModules=[],await R__default.pathExists(h))try{let x=await R__default.readdir(h);t.modulesHealthy=x.length>0;}catch{t.modulesHealthy=false;}return await Fe(e,t),t}if(d){t.framework="FastAPI";let p=v.join(e,".venv");if(await R__default.pathExists(p)){t.venvActive=true;let y=process.platform==="win32"?v.join(p,"Scripts","python.exe"):v.join(p,"bin","python");if(await R__default.pathExists(y)){try{let{stdout:C}=await execa(y,["-c","import rapidkit_core; print(rapidkit_core.__version__)"],{timeout:2e3});t.coreInstalled=true,t.coreVersion=C.trim();}catch{t.coreInstalled=false;}try{await execa(y,["-c","import fastapi"],{timeout:2e3}),t.depsInstalled=true;}catch{try{let C=v.join(p,"lib");if(await R__default.pathExists(C)){let q=(await R__default.readdir(C)).find(V=>V.startsWith("python"));if(q){let V=v.join(C,q,"site-packages");if(await R__default.pathExists(V)){let st=(await R__default.readdir(V)).filter(at=>!at.startsWith("_")&&!at.includes("dist-info")&&!["pip","setuptools","wheel","pkg_resources"].includes(at));t.depsInstalled=st.length>0;}}}t.depsInstalled||(t.issues.push("Dependencies not installed"),t.fixCommands?.push(`cd ${e} && rapidkit init`));}catch{t.issues.push("Could not verify dependency installation");}}}else t.issues.push("Virtual environment exists but Python executable not found");}else t.issues.push("Virtual environment not created"),t.fixCommands?.push(`cd ${e} && rapidkit init`);let u=v.join(e,".env");if(t.hasEnvFile=await R__default.pathExists(u),!t.hasEnvFile){let y=v.join(e,".env.example");await R__default.pathExists(y)&&(t.issues.push("Environment file missing (found .env.example)"),t.fixCommands?.push(`cd ${e} && cp .env.example .env`));}let h=v.join(e,"src"),x=v.join(e,"modules");if(t.modulesHealthy=true,t.missingModules=[],await R__default.pathExists(h)){let y=v.join(h,"__init__.py");await R__default.pathExists(y)||(t.modulesHealthy=false,t.missingModules.push("src/__init__.py"));}if(await R__default.pathExists(x))try{let y=await to(x);for(let C of y){let E=v.join(x,C,"__init__.py");await R__default.pathExists(E)||(t.modulesHealthy=false,t.missingModules.push(`modules/${C}/__init__.py`));}}catch{}return !t.modulesHealthy&&t.missingModules.length>0&&t.issues.push(`Missing module init files: ${t.missingModules.join(", ")}`),await Fe(e,t),t}return t.issues.push("Unknown project type (no package.json or pyproject.toml)"),await Fe(e,t),t}async function to(e){try{return (await R__default.readdir(e,{withFileTypes:true})).filter(t=>t.isDirectory()).map(t=>t.name)}catch{try{let o=await R__default.readdir(e),t=[];for(let r of o)try{(await R__default.stat(v.join(e,r))).isDirectory()&&t.push(r);}catch{continue}return t}catch{return []}}}async function ft(e){let o=v.join(e,".rapidkit");if(!await R__default.pathExists(o))return false;let t=["project.json","context.json","file-hashes.json"];for(let r of t)if(await R__default.pathExists(v.join(o,r)))return true;return false}function oo(e,o){if(o.has(e))return true;let t=e.toLowerCase();return !!(t==="dist"||t.startsWith("dist-")||t.startsWith("dist_")||t==="build"||t.startsWith("build-")||t.startsWith("build_"))}async function Pn(e,o,t){let r=new Set,i=[{dir:e,depth:0}];for(;i.length>0;){let n=i.shift();if(!n)break;try{let s=await R__default.readdir(n.dir);for(let c of s){if(oo(c,t))continue;let a=v.join(n.dir,c),l;try{l=await R__default.stat(a);}catch{continue}if(l.isDirectory()){if(await ft(a)){r.add(a);continue}n.depth<o&&i.push({dir:a,depth:n.depth+1});}}}catch{continue}}return Array.from(r)}async function In(e){let o=e,t=v.parse(o).root;for(;o!==t;){let r=[v.join(o,".rapidkit-workspace"),v.join(o,".rapidkit","workspace-marker.json"),v.join(o,".rapidkit","config.json")];for(let i of r)if(await R__default.pathExists(i))return o;o=v.dirname(o);}return null}function En(e,o){let t=0,r=0,i=0;return e.forEach(s=>{s.status==="ok"?t++:s.status==="warn"?r++:s.status==="error"&&i++;}),o.forEach(s=>{(s.isGoProject?s.issues.length===0&&s.depsInstalled:s.issues.length===0&&s.venvActive&&s.depsInstalled)?t++:s.issues.length>0&&r++;}),{total:t+r+i,passed:t,warnings:r,errors:i}}async function Tn(e){let o=v.basename(e);try{let i=v.join(e,".rapidkit-workspace");await R__default.pathExists(i)&&(o=(await R__default.readJSON(i)).name||o);}catch{try{let i=v.join(e,".rapidkit","config.json");o=(await R__default.readJSON(i)).workspace_name||o;}catch{}}let t={workspacePath:e,workspaceName:o,python:await Yt(),poetry:await Qt(),pipx:await Xt(),go:await Zt(),rapidkitCore:await eo(),projects:[]};try{let i=new Set([".git",".venv","node_modules",".rapidkit","dist","build","coverage","__pycache__"]),n=new Set;await ft(e)&&n.add(e);let s=async(c,a)=>{if(a<0)return;let l=await to(c);for(let d of l){if(oo(d,i))continue;let p=v.join(c,d);if(await ft(p)){n.add(p);continue}a>0&&await s(p,a-1);}};if(await s(e,1),a.debug(`Workspace scan (shallow) found ${n.size} project(s)`),n.size===0){let c=await Pn(e,3,i);c.forEach(a=>n.add(a)),a.debug(`Workspace scan (deep fallback) found ${c.length} project(s)`);}n.size>0&&a.debug(`Workspace projects detected: ${Array.from(n).join(", ")}`);for(let c of n){let a=await _n(c);t.projects.push(a);}}catch(i){a.debug(`Failed to scan workspace projects: ${i}`);}let r=[t.python,t.poetry,t.pipx,t.go,t.rapidkitCore];if(t.healthScore=En(r,t.projects),t.rapidkitCore.status==="ok"){let i=t.rapidkitCore.message.match(/([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);i&&(t.coreVersion=i[1]);}return t}function B(e,o){let t=e.status==="ok"?"\u2705":e.status==="warn"?"\u26A0\uFE0F":"\u274C",r=e.status==="ok"?g.green:e.status==="warn"?g.yellow:g.red;console.log(`${t} ${g.bold(o)}: ${r(e.message)}`),e.paths&&e.paths.length>0?e.paths.forEach(i=>{let n=i.version?g.cyan(` -> ${i.version}`):"";console.log(` ${g.cyan("\u2022")} ${g.gray(i.location)}: ${g.dim(i.path)}${n}`);}):e.details&&console.log(` ${g.gray(e.details)}`);}function An(e){let o=e.issues.length>0,t=o?"\u26A0\uFE0F":"\u2705",r=o?g.yellow:g.green;if(console.log(`
|
|
4092
|
-
${t} ${
|
|
4093
|
-
${
|
|
4094
|
-
\u2705 No fixes needed - all projects are healthy!`));return}console.log(
|
|
3365
|
+
`}async function jt(e,r){let t={project_name:r.project_name,module_path:r.module_path||r.project_name,author:r.author||"RapidKit User",description:r.description||`Go/Gin REST API \u2014 ${r.project_name}`,go_version:r.go_version||"1.24",app_version:r.app_version||"0.1.0",port:r.port||"8080",skipGit:r.skipGit??false},o=c();try{await execa("go",["version"],{timeout:3e3});}catch{console.log(l.yellow("\n\u26A0 Go not found in PATH \u2014 project will be scaffolded, but `go mod tidy` requires Go 1.21+")),console.log(l.gray(` Install: https://go.dev/dl/
|
|
3366
|
+
`));}let i=At(`Generating Go/Gin project: ${t.project_name}\u2026`).start();try{let n=(c,p)=>ti(f.join(e,c),p),a=f.join(e,"rapidkit"),s=f.join(e,"rapidkit.cmd");await Promise.all([n("cmd/server/main.go",ri(t)),n("go.mod",oi(t)),n("internal/config/config.go",ii(t)),n("internal/server/server.go",ni(t)),n("internal/middleware/requestid.go",fi()),n("internal/middleware/requestid_test.go",hi(t)),n("internal/apierr/apierr.go",yi()),n("internal/apierr/apierr_test.go",wi(t)),n("internal/handlers/health.go",si()),n("internal/handlers/health_test.go",ai(t)),n("internal/handlers/example.go",ki(t)),n("internal/handlers/example_test.go",bi(t)),n("internal/config/config_test.go",Ri(t)),n("internal/middleware/cors.go",Ci()),n("internal/middleware/cors_test.go",Si(t)),n("internal/middleware/ratelimit.go",xi(t)),n("internal/middleware/ratelimit_test.go",Pi(t)),n("internal/server/server_test.go",_i(t)),n("docs/doc.go",vi(t)),n(".air.toml",Ei(t)),n("Dockerfile",ci()),n("docker-compose.yml",li(t)),n("Makefile",di(t)),n(".golangci.yml",Ii(t.module_path)),n(".env.example",pi(t)),n(".gitignore",ui()),n(".github/workflows/ci.yml",gi(t)),n("README.md",mi(t)),n(".rapidkit/project.json",Oi(t,o)),n(".rapidkit/context.json",Ti()),n("rapidkit",Ai(t)),n("rapidkit.cmd",Ni(t))]),await promises.chmod(a,493),await promises.chmod(s,493),i.succeed(l.green(`Project created at ${e}`));try{i.start("Fetching Go dependencies\u2026"),await execa("go",["mod","tidy"],{cwd:e,timeout:12e4}),i.succeed(l.gray("\u2713 go mod tidy completed"));}catch{i.warn(l.yellow("\u26A0 go mod tidy failed \u2014 run manually: go mod tidy"));}if(!t.skipGit)try{await execa("git",["init"],{cwd:e}),await execa("git",["add","-A"],{cwd:e}),await execa("git",["commit","-m","chore: initial scaffold (rapidkit gogin.standard)"],{cwd:e}),console.log(l.gray("\u2713 git repository initialized"));}catch{console.log(l.gray("\u26A0 git init skipped (git not found or error)"));}console.log(""),console.log(l.bold("\u2705 Go/Gin project ready!")),console.log(""),console.log(l.cyan("Next steps:")),console.log(l.white(` cd ${t.project_name}`)),console.log(l.white(" make run # start dev server")),console.log(l.white(" make test # run tests")),console.log(""),console.log(l.gray("Server will listen on port "+t.port)),console.log(l.gray(" http://localhost:"+t.port+"/api/v1/health/live")),console.log(l.gray(" http://localhost:"+t.port+"/api/v1/health/ready")),console.log(""),console.log(l.yellow("\u2139 RapidKit modules are not available for Go projects (module system uses Python/pip).")),console.log("");}catch(n){throw i.fail(l.red("Failed to generate Go/Gin project")),n}}async function ar(){let e=process.platform==="win32"?["python","python3"]:["python3","python"];for(let r of e)try{let{stdout:t}=await execa(r,["--version"],{timeout:3e3}),o=t.match(/Python (\d+\.\d+\.\d+)/);if(o){let i=o[1],[n,a]=i.split(".").map(Number);return n<3||n===3&&a<10?{status:"warn",message:`Python ${i} (requires 3.10+)`,details:`${r} found but version is below minimum requirement`}:{status:"ok",message:`Python ${i}`,details:`Using ${r}`}}}catch{continue}return {status:"error",message:"Python not found",details:"Install Python 3.10+ and ensure it's in PATH"}}async function cr(){try{let{stdout:e}=await execa("poetry",["--version"],{timeout:3e3}),r=e.match(/Poetry .*version ([\d.]+)/);return r?{status:"ok",message:`Poetry ${r[1]}`,details:"Available for dependency management"}:{status:"warn",message:"Poetry version unknown"}}catch{return {status:"warn",message:"Poetry not installed",details:"Optional: Install for better dependency management"}}}async function lr(){try{let{stdout:e}=await execa("pipx",["--version"],{timeout:3e3});return {status:"ok",message:`pipx ${e.trim()}`,details:"Available for global tool installation"}}catch{return {status:"warn",message:"pipx not installed",details:"Optional: Install for isolated Python tools"}}}async function dr(){try{let{stdout:e}=await execa("go",["version"],{timeout:3e3}),r=e.match(/go version go(\d+\.\d+(?:\.\d+)?)/);return r?{status:"ok",message:`Go ${r[1]}`,details:"Available for Go/Fiber and Go/Gin projects"}:{status:"ok",message:"Go (version unknown)",details:"go found in PATH"}}catch{return {status:"warn",message:"Go not installed",details:"Optional: Required only for gofiber.standard / gogin.standard projects \u2014 https://go.dev/dl/"}}}async function pr(){let e=process.env.HOME||process.env.USERPROFILE||"",r=[],t=[{location:"Global (pipx)",path:f.join(e,".local","bin","rapidkit")},{location:"Global (pipx)",path:f.join(e,"AppData","Roaming","Python","Scripts","rapidkit.exe")},{location:"Global (pyenv)",path:f.join(e,".pyenv","shims","rapidkit")},{location:"Global (system)",path:"/usr/local/bin/rapidkit"},{location:"Global (system)",path:"/usr/bin/rapidkit"}],o=[{location:"Workspace (.venv)",path:f.join(process.cwd(),".venv","bin","rapidkit")},{location:"Workspace (.venv)",path:f.join(process.cwd(),".venv","Scripts","rapidkit.exe")}];for(let{location:n,path:a}of [...t,...o])try{if(await b__default.pathExists(a)){let{stdout:s,exitCode:c}=await execa(a,["--version"],{timeout:3e3,reject:false});if(c===0&&(s.includes("RapidKit Version")||s.includes("RapidKit"))){let p=s.match(/v?([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);p&&r.push({location:n,path:a,version:p[1]});}}}catch{continue}if(r.length>0)return {status:"ok",message:`RapidKit Core ${r[0].version}`,paths:r.map(a=>({location:a.location,path:a.path,version:a.version}))};try{let{stdout:n,exitCode:a}=await execa("rapidkit",["--version"],{timeout:3e3,reject:false});if(a===0&&(n.includes("RapidKit Version")||n.includes("RapidKit"))){let s=n.match(/v?([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);if(s)return {status:"ok",message:`RapidKit Core ${s[1]}`,details:"Available via PATH"}}}catch{}try{let{stdout:n,exitCode:a}=await execa("poetry",["run","rapidkit","--version"],{timeout:3e3,reject:false});if(a===0&&(n.includes("RapidKit Version")||n.includes("RapidKit"))){let s=n.match(/v?([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);if(s)return {status:"ok",message:`RapidKit Core ${s[1]}`,details:"Available via Poetry"}}}catch{}let i=process.platform==="win32"?["python","python3"]:["python3","python"];for(let n of i)try{let{stdout:a,exitCode:s}=await execa(n,["-c","import rapidkit_core; print(rapidkit_core.__version__)"],{timeout:3e3,reject:false});if(s===0&&a&&!a.includes("Traceback")&&!a.includes("ModuleNotFoundError")){let c=a.trim();if(c)return {status:"ok",message:`RapidKit Core ${c}`,details:`Available in ${n} environment`}}}catch{continue}return {status:"error",message:"RapidKit Core not installed",details:"Install with: pipx install rapidkit-core"}}async function mt(e,r){let t=f.join(e,"Dockerfile");r.hasDocker=await b__default.pathExists(t);let o=f.join(e,"tests"),i=f.join(e,"test"),n=await b__default.pathExists(o)||await b__default.pathExists(i),a=false;if(r.framework==="Go/Fiber"||r.framework==="Go/Gin")try{let s=[{dir:e,depth:0}],c=4,p=new Set([".git",".venv","node_modules","dist","build","vendor"]);for(;s.length>0&&!a;){let d=s.shift();if(!d)break;let m=[];try{m=await b__default.readdir(d.dir);}catch{continue}for(let h of m){let w=f.join(d.dir,h),g;try{g=await b__default.stat(w);}catch{continue}if(g.isFile()&&h.endsWith("_test.go")){a=true;break}g.isDirectory()&&d.depth<c&&!p.has(h)&&!h.startsWith(".")&&s.push({dir:w,depth:d.depth+1});}}}catch{}if(r.hasTests=n||a,r.framework==="NestJS"){let s=f.join(e,".eslintrc.js"),c=f.join(e,".eslintrc.json");r.hasCodeQuality=await b__default.pathExists(s)||await b__default.pathExists(c);}else if(r.framework==="Go/Fiber"||r.framework==="Go/Gin"){let s=f.join(e,".golangci.yml"),c=f.join(e,".golangci.yaml"),p=f.join(e,"Makefile"),d=await b__default.pathExists(p)&&(await b__default.readFile(p,"utf8")).includes("golangci-lint");r.hasCodeQuality=await b__default.pathExists(s)||await b__default.pathExists(c)||d;}else if(r.framework==="FastAPI"){let s=f.join(e,"ruff.toml"),c=f.join(e,"pyproject.toml");if(await b__default.pathExists(c))try{let p=await b__default.readFile(c,"utf8");r.hasCodeQuality=p.includes("[tool.ruff]")||await b__default.pathExists(s);}catch{r.hasCodeQuality=await b__default.pathExists(s);}}try{if(r.framework==="NestJS"){let{stdout:s}=await execa("npm",["audit","--json"],{cwd:e,reject:false});if(s)try{let p=JSON.parse(s).metadata?.vulnerabilities;p&&(r.vulnerabilities=(p.high||0)+(p.critical||0)+(p.moderate||0));}catch{}}else if(r.framework==="FastAPI"){let s=f.join(e,".venv"),c=process.platform==="win32"?f.join(s,"Scripts","python.exe"):f.join(s,"bin","python");if(await b__default.pathExists(c))try{let{stdout:p}=await execa(c,["-m","pip","list","--format=json"],{timeout:5e3,reject:false});if(p){JSON.parse(p);r.vulnerabilities=0;}}catch{}}}catch{}}async function $i(e){let t={name:f.basename(e),path:e,venvActive:false,depsInstalled:false,coreInstalled:false,issues:[],fixCommands:[]},o=f.join(e,".rapidkit");if(!await b__default.pathExists(o))return t.issues.push("Not a valid RapidKit project (missing .rapidkit directory)"),t;try{let m=f.join(e,"registry.json");if(await b__default.pathExists(m)){let h=await b__default.readJson(m);h.installed_modules&&(t.stats={modules:h.installed_modules.length});}}catch{}let i=null;try{let m=f.join(o,"project.json");if(await b__default.pathExists(m)){i=await b__default.readJson(m);let h=i?.kit_name||i?.kit;h&&(t.kit=h);}}catch{}try{let m=f.join(e,".git");if(await b__default.pathExists(m)){let{stdout:h}=await execa("git",["log","-1","--format=%cr"],{cwd:e,reject:false});h&&(t.lastModified=h.trim());}else {let h=await b__default.stat(e),g=Date.now()-h.mtime.getTime(),u=Math.floor(g/(1e3*60*60*24));t.lastModified=u===0?"today":`${u} day${u>1?"s":""} ago`;}}catch{}let n=f.join(e,"package.json"),a=f.join(e,"pyproject.toml"),s=f.join(e,"go.mod");if(await b__default.pathExists(s)||i?.runtime==="go"||typeof i?.kit_name=="string"&&(i.kit_name.startsWith("gofiber")||i.kit_name.startsWith("gogin"))){let m=i?.kit_name??"";t.framework=m.startsWith("gogin")?"Go/Gin":"Go/Fiber",t.isGoProject=true,t.venvActive=true,t.coreInstalled=false;try{await execa("go",["version"],{timeout:3e3});}catch{t.issues.push("Go toolchain not found \u2014 install from https://go.dev/dl/"),t.fixCommands?.push("https://go.dev/dl/");}let h=f.join(e,"go.sum");return await b__default.pathExists(h)?t.depsInstalled=true:(t.depsInstalled=false,t.issues.push("Go dependencies not downloaded (go.sum missing)"),t.fixCommands?.push(`cd ${e} && go mod tidy`)),await mt(e,t),t}let p=await b__default.pathExists(n),d=await b__default.pathExists(a);if(p){t.framework="NestJS",t.venvActive=true;let m=f.join(e,"node_modules");if(await b__default.pathExists(m))try{let u=(await b__default.readdir(m)).filter(C=>!C.startsWith(".")&&!C.startsWith("_"));t.depsInstalled=u.length>0;}catch{t.depsInstalled=false;}t.depsInstalled||(t.issues.push("Dependencies not installed (node_modules empty or missing)"),t.fixCommands?.push(`cd ${e} && rapidkit init`)),t.coreInstalled=false;let h=f.join(e,".env");if(t.hasEnvFile=await b__default.pathExists(h),!t.hasEnvFile){let g=f.join(e,".env.example");await b__default.pathExists(g)&&(t.issues.push("Environment file missing (found .env.example)"),t.fixCommands?.push(`cd ${e} && cp .env.example .env`));}let w=f.join(e,"src");if(t.modulesHealthy=true,t.missingModules=[],await b__default.pathExists(w))try{let g=await b__default.readdir(w);t.modulesHealthy=g.length>0;}catch{t.modulesHealthy=false;}return await mt(e,t),t}if(d){t.framework="FastAPI";let m=f.join(e,".venv");if(await b__default.pathExists(m)){t.venvActive=true;let u=process.platform==="win32"?f.join(m,"Scripts","python.exe"):f.join(m,"bin","python");if(await b__default.pathExists(u)){try{let{stdout:C}=await execa(u,["-c","import rapidkit_core; print(rapidkit_core.__version__)"],{timeout:2e3});t.coreInstalled=true,t.coreVersion=C.trim();}catch{t.coreInstalled=false;}try{await execa(u,["-c","import fastapi"],{timeout:2e3}),t.depsInstalled=true;}catch{try{let C=f.join(m,"lib");if(await b__default.pathExists(C)){let A=(await b__default.readdir(C)).find(_=>_.startsWith("python"));if(A){let _=f.join(C,A,"site-packages");if(await b__default.pathExists(_)){let K=(await b__default.readdir(_)).filter(D=>!D.startsWith("_")&&!D.includes("dist-info")&&!["pip","setuptools","wheel","pkg_resources"].includes(D));t.depsInstalled=K.length>0;}}}t.depsInstalled||(t.issues.push("Dependencies not installed"),t.fixCommands?.push(`cd ${e} && rapidkit init`));}catch{t.issues.push("Could not verify dependency installation");}}}else t.issues.push("Virtual environment exists but Python executable not found");}else t.issues.push("Virtual environment not created"),t.fixCommands?.push(`cd ${e} && rapidkit init`);let h=f.join(e,".env");if(t.hasEnvFile=await b__default.pathExists(h),!t.hasEnvFile){let u=f.join(e,".env.example");await b__default.pathExists(u)&&(t.issues.push("Environment file missing (found .env.example)"),t.fixCommands?.push(`cd ${e} && cp .env.example .env`));}let w=f.join(e,"src"),g=f.join(e,"modules");if(t.modulesHealthy=true,t.missingModules=[],await b__default.pathExists(w)){let u=f.join(w,"__init__.py");await b__default.pathExists(u)||(t.modulesHealthy=false,t.missingModules.push("src/__init__.py"));}if(await b__default.pathExists(g))try{let u=await ur(g);for(let C of u){let I=f.join(g,C,"__init__.py");await b__default.pathExists(I)||(t.modulesHealthy=false,t.missingModules.push(`modules/${C}/__init__.py`));}}catch{}return !t.modulesHealthy&&t.missingModules.length>0&&t.issues.push(`Missing module init files: ${t.missingModules.join(", ")}`),await mt(e,t),t}return t.issues.push("Unknown project type (no package.json or pyproject.toml)"),await mt(e,t),t}async function ur(e){try{return (await b__default.readdir(e,{withFileTypes:true})).filter(t=>t.isDirectory()).map(t=>t.name)}catch{try{let r=await b__default.readdir(e),t=[];for(let o of r)try{(await b__default.stat(f.join(e,o))).isDirectory()&&t.push(o);}catch{continue}return t}catch{return []}}}async function $t(e){let r=f.join(e,".rapidkit");if(!await b__default.pathExists(r))return false;let t=["project.json","context.json","file-hashes.json"];for(let o of t)if(await b__default.pathExists(f.join(r,o)))return true;return false}function gr(e,r){if(r.has(e))return true;let t=e.toLowerCase();return !!(t==="dist"||t.startsWith("dist-")||t.startsWith("dist_")||t==="build"||t.startsWith("build-")||t.startsWith("build_"))}async function Di(e,r,t){let o=new Set,i=[{dir:e,depth:0}];for(;i.length>0;){let n=i.shift();if(!n)break;try{let a=await b__default.readdir(n.dir);for(let s of a){if(gr(s,t))continue;let c=f.join(n.dir,s),p;try{p=await b__default.stat(c);}catch{continue}if(p.isDirectory()){if(await $t(c)){o.add(c);continue}n.depth<r&&i.push({dir:c,depth:n.depth+1});}}}catch{continue}}return Array.from(o)}async function nr(e){let r=e,t=f.parse(r).root;for(;r!==t;){let o=[f.join(r,".rapidkit-workspace"),f.join(r,".rapidkit","workspace-marker.json"),f.join(r,".rapidkit","config.json")];for(let i of o)if(await b__default.pathExists(i))return r;r=f.dirname(r);}return null}function Gi(e,r){let t=0,o=0,i=0;return e.forEach(a=>{a.status==="ok"?t++:a.status==="warn"?o++:a.status==="error"&&i++;}),r.forEach(a=>{(a.isGoProject?a.issues.length===0&&a.depsInstalled:a.issues.length===0&&a.venvActive&&a.depsInstalled)?t++:a.issues.length>0&&o++;}),{total:t+o+i,passed:t,warnings:o,errors:i}}async function Mi(e){let r=f.basename(e);try{let i=f.join(e,".rapidkit-workspace");await b__default.pathExists(i)&&(r=(await b__default.readJSON(i)).name||r);}catch{try{let i=f.join(e,".rapidkit","config.json");r=(await b__default.readJSON(i)).workspace_name||r;}catch{}}let t={workspacePath:e,workspaceName:r,python:await ar(),poetry:await cr(),pipx:await lr(),go:await dr(),rapidkitCore:await pr(),projects:[]};try{let i=new Set([".git",".venv","node_modules",".rapidkit","dist","build","coverage","__pycache__"]),n=new Set;await $t(e)&&n.add(e);let a$1=async(s,c)=>{if(c<0)return;let p=await ur(s);for(let d of p){if(gr(d,i))continue;let m=f.join(s,d);if(await $t(m)){n.add(m);continue}c>0&&await a$1(m,c-1);}};if(await a$1(e,1),a.debug(`Workspace scan (shallow) found ${n.size} project(s)`),n.size===0){let s=await Di(e,3,i);s.forEach(c=>n.add(c)),a.debug(`Workspace scan (deep fallback) found ${s.length} project(s)`);}n.size>0&&a.debug(`Workspace projects detected: ${Array.from(n).join(", ")}`);for(let s of n){let c=await $i(s);t.projects.push(c);}}catch(i){a.debug(`Failed to scan workspace projects: ${i}`);}let o=[t.python,t.poetry,t.pipx,t.go,t.rapidkitCore];if(t.healthScore=Gi(o,t.projects),t.rapidkitCore.status==="ok"){let i=t.rapidkitCore.message.match(/([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);i&&(t.coreVersion=i[1]);}return t}function Re(e,r){let t=e.status==="ok"?"\u2705":e.status==="warn"?"\u26A0\uFE0F":"\u274C",o=e.status==="ok"?l.green:e.status==="warn"?l.yellow:l.red;console.log(`${t} ${l.bold(r)}: ${o(e.message)}`),e.paths&&e.paths.length>0?e.paths.forEach(i=>{let n=i.version?l.cyan(` -> ${i.version}`):"";console.log(` ${l.cyan("\u2022")} ${l.gray(i.location)}: ${l.dim(i.path)}${n}`);}):e.details&&console.log(` ${l.gray(e.details)}`);}function Li(e){let r=e.issues.length>0,t=r?"\u26A0\uFE0F":"\u2705",o=r?l.yellow:l.green;if(console.log(`
|
|
3367
|
+
${t} ${l.bold("Project")}: ${o(e.name)}`),e.framework){let c=e.framework==="FastAPI"?"\u{1F40D}":e.framework==="NestJS"?"\u{1F985}":e.framework==="Go/Fiber"||e.framework==="Go/Gin"?"\u{1F439}":"\u{1F4E6}";console.log(` ${c} Framework: ${l.cyan(e.framework)}${e.kit?l.gray(` (${e.kit})`):""}`);}console.log(` ${l.gray(`Path: ${e.path}`)}`);let i=e.isGoProject===true,n=!i&&e.venvActive&&!e.coreInstalled;if(!i&&!n&&(e.venvActive?console.log(` \u2705 Virtual environment: ${l.green("Active")}`):console.log(` \u274C Virtual environment: ${l.red("Not found")}`),e.coreInstalled?console.log(` ${l.dim("\u2139")} RapidKit Core: ${l.gray(e.coreVersion||"In venv")} ${l.dim("(optional)")}`):console.log(` ${l.dim("\u2139")} RapidKit Core: ${l.gray("Using global installation")} ${l.dim("(recommended)")}`)),e.depsInstalled?console.log(` \u2705 Dependencies: ${l.green("Installed")}`):console.log(` \u26A0\uFE0F Dependencies: ${l.yellow("Not installed")}`),e.hasEnvFile!==void 0&&(e.hasEnvFile?console.log(` \u2705 Environment: ${l.green(".env configured")}`):console.log(` \u26A0\uFE0F Environment: ${l.yellow(".env missing")}`)),e.modulesHealthy!==void 0&&(e.modulesHealthy?console.log(` \u2705 Modules: ${l.green("Healthy")}`):e.missingModules&&e.missingModules.length>0&&console.log(` \u26A0\uFE0F Modules: ${l.yellow(`Missing ${e.missingModules.length} init file(s)`)}`)),e.stats){let c=[];e.stats.modules!==void 0&&c.push(`${e.stats.modules} module${e.stats.modules!==1?"s":""}`),c.length>0&&console.log(` \u{1F4CA} Stats: ${l.cyan(c.join(" \u2022 "))}`);}e.lastModified&&console.log(` \u{1F552} Last Modified: ${l.gray(e.lastModified)}`);let s=[];if(e.hasTests!==void 0&&s.push(e.hasTests?"\u2705 Tests":l.dim("\u2298 No tests")),e.hasDocker!==void 0&&s.push(e.hasDocker?"\u2705 Docker":l.dim("\u2298 No Docker")),e.hasCodeQuality!==void 0){let c=e.framework==="NestJS"?"ESLint":e.framework==="Go/Fiber"||e.framework==="Go/Gin"?"golangci-lint":"Ruff";s.push(e.hasCodeQuality?`\u2705 ${c}`:l.dim(`\u2298 No ${c}`));}s.length>0&&console.log(` ${s.join(" \u2022 ")}`),e.vulnerabilities!==void 0&&e.vulnerabilities>0&&console.log(` \u26A0\uFE0F Security: ${l.yellow(`${e.vulnerabilities} vulnerability(ies) found`)}`),e.issues.length>0&&(console.log(` ${l.bold("Issues:")}`),e.issues.forEach(c=>{console.log(` \u2022 ${l.yellow(c)}`);}),e.fixCommands&&e.fixCommands.length>0&&(console.log(`
|
|
3368
|
+
${l.bold.cyan("\u{1F527} Quick Fix:")}`),e.fixCommands.forEach(c=>{console.log(` ${l.cyan("$")} ${l.white(c)}`);})));}async function sr(e,r=false){let t=e.filter(a=>a.fixCommands&&a.fixCommands.length>0);if(t.length===0){console.log(l.green(`
|
|
3369
|
+
\u2705 No fixes needed - all projects are healthy!`));return}console.log(l.bold.cyan(`
|
|
4095
3370
|
\u{1F527} Available Fixes:
|
|
4096
|
-
`));for(let
|
|
4097
|
-
\u26A0\uFE0F Fixes cancelled by user`));return}console.log(
|
|
3371
|
+
`));for(let a of t)console.log(l.bold(`Project: ${l.yellow(a.name)}`)),a.fixCommands.forEach((s,c)=>{console.log(` ${c+1}. ${l.cyan(s)}`);}),console.log();if(!r){console.log(l.gray('\u{1F4A1} Run "npx rapidkit doctor workspace --fix" to apply fixes automatically'));return}let{confirm:o}=await xe.prompt([{type:"confirm",name:"confirm",message:`Apply ${t.reduce((a,s)=>a+s.fixCommands.length,0)} fix(es)?`,default:false}]);if(!o){console.log(l.yellow(`
|
|
3372
|
+
\u26A0\uFE0F Fixes cancelled by user`));return}console.log(l.bold.cyan(`
|
|
4098
3373
|
\u{1F680} Applying fixes...
|
|
4099
|
-
`));for(let
|
|
4100
|
-
`));}
|
|
4101
|
-
`));}}console.log(
|
|
4102
|
-
|
|
3374
|
+
`));let i=a=>/^https?:\/\//i.test(a.trim()),n=a=>{let s=a.match(/^cd\s+(.+?)\s*&&\s*cp\s+\.env\.example\s+\.env\s*$/);return s?{projectPath:s[1].trim()}:null};for(let a of t){console.log(l.bold(`Fixing ${l.cyan(a.name)}...`));for(let s of a.fixCommands)try{if(console.log(l.gray(` $ ${s}`)),i(s)){console.log(l.yellow(` \u2139 Manual action required: open ${s}`)),console.log(l.green(` \u2705 Recorded as guidance
|
|
3375
|
+
`));continue}let c=n(s);if(c){let p=f.join(c.projectPath,".env.example"),d=f.join(c.projectPath,".env");if(!await b__default.pathExists(p))throw new Error(`.env.example not found at ${p}`);if(await b__default.pathExists(d)){console.log(l.green(` \u2705 .env already exists
|
|
3376
|
+
`));continue}await b__default.copy(p,d,{overwrite:false,errorOnExist:false}),console.log(l.green(` \u2705 Success
|
|
3377
|
+
`));continue}await execa(s,{shell:true,stdio:"inherit"}),console.log(l.green(` \u2705 Success
|
|
3378
|
+
`));}catch(c){console.log(l.red(` \u274C Failed: ${c instanceof Error?c.message:String(c)}
|
|
3379
|
+
`));}}console.log(l.bold.green(`
|
|
3380
|
+
\u2705 Fix process completed!`));}async function mr(e={}){let r=!e.workspace&&e.fix?await nr(process.cwd()):null,t=e.workspace||!!r;if(e.json||console.log(l.bold.cyan(`
|
|
4103
3381
|
\u{1FA7A} RapidKit Health Check
|
|
4104
|
-
`)),
|
|
4105
|
-
\u{1F4CA} Health Score:`)),console.log(` ${
|
|
3382
|
+
`)),t){let o=r??await nr(process.cwd());o||(a.error("No RapidKit workspace found in current directory or parents"),a.info('Run this command from within a workspace, or use "rapidkit doctor" for system check'),process.exit(1)),e.json||(r&&console.log(l.gray("\u2139\uFE0F Detected workspace context; enabling workspace checks for --fix")),console.log(l.bold(`Workspace: ${l.cyan(f.basename(o))}`)),console.log(l.gray(`Path: ${o}`)));let i=await Mi(o);if(e.json){let s={workspace:{name:f.basename(o),path:o},healthScore:i.healthScore,system:{python:i.python,poetry:i.poetry,pipx:i.pipx,rapidkitCore:i.rapidkitCore,versions:{core:i.coreVersion,npm:i.npmVersion}},projects:i.projects.map(c=>({name:c.name,path:c.path,venvActive:c.venvActive,depsInstalled:c.depsInstalled,coreInstalled:c.coreInstalled,coreVersion:c.coreVersion,issues:c.issues,fixCommands:c.fixCommands})),summary:{totalProjects:i.projects.length,totalIssues:i.projects.reduce((c,p)=>c+p.issues.length,0),hasSystemErrors:[i.python,i.rapidkitCore].some(c=>c.status==="error")}};console.log(JSON.stringify(s,null,2));return}if(i.healthScore){let s=i.healthScore,c=Math.round(s.passed/s.total*100),p=c>=80?l.green:c>=50?l.yellow:l.red,d="\u2588".repeat(Math.floor(c/5))+"\u2591".repeat(20-Math.floor(c/5));console.log(l.bold(`
|
|
3383
|
+
\u{1F4CA} Health Score:`)),console.log(` ${p(`${c}%`)} ${l.gray(d)}`),console.log(` ${l.green(`\u2705 ${s.passed} passed`)} ${l.gray("|")} ${l.yellow(`\u26A0\uFE0F ${s.warnings} warnings`)} ${l.gray("|")} ${l.red(`\u274C ${s.errors} errors`)}`);}if(console.log(l.bold(`
|
|
4106
3384
|
|
|
4107
3385
|
System Tools:
|
|
4108
|
-
`)),
|
|
4109
|
-
\u26A0\uFE0F Version mismatch: Core ${
|
|
4110
|
-
\u{1F4E6} Projects (${
|
|
4111
|
-
\u{1F4E6} Projects:`)),console.log(
|
|
4112
|
-
\u26A0\uFE0F Found ${
|
|
4113
|
-
\u2705 All checks passed! Workspace is healthy.`));}else {console.log(
|
|
4114
|
-
`));let o=await
|
|
4115
|
-
\u274C Some required tools are missing`)),console.log(
|
|
4116
|
-
Tip:
|
|
4117
|
-
|
|
4118
|
-
|
|
3386
|
+
`)),Re(i.python,"Python"),Re(i.poetry,"Poetry"),Re(i.pipx,"pipx"),Re(i.go,"Go"),Re(i.rapidkitCore,"RapidKit Core"),i.coreVersion&&i.npmVersion){let s=i.coreVersion.split(".")[1],c=i.npmVersion.split(".")[1];s!==c&&(console.log(l.yellow(`
|
|
3387
|
+
\u26A0\uFE0F Version mismatch: Core ${i.coreVersion} / CLI ${i.npmVersion}`)),console.log(l.gray(" Consider updating to matching versions for best compatibility")));}i.projects.length>0?(console.log(l.bold(`
|
|
3388
|
+
\u{1F4E6} Projects (${i.projects.length}):`)),i.projects.forEach(s=>Li(s))):(console.log(l.bold(`
|
|
3389
|
+
\u{1F4E6} Projects:`)),console.log(l.gray(" No RapidKit projects found in workspace")));let n=i.projects.reduce((s,c)=>s+c.issues.length,0),a$1=[i.python,i.rapidkitCore].some(s=>s.status==="error");a$1||n>0?(console.log(l.bold.yellow(`
|
|
3390
|
+
\u26A0\uFE0F Found ${n} project issue(s)`)),a$1&&console.log(l.bold.red("\u274C System requirements not met")),e.fix?await sr(i.projects,true):n>0&&await sr(i.projects,false)):console.log(l.bold.green(`
|
|
3391
|
+
\u2705 All checks passed! Workspace is healthy.`));}else {console.log(l.bold(`System Tools:
|
|
3392
|
+
`));let o=await ar(),i=await cr(),n=await lr(),a=await dr(),s=await pr();Re(o,"Python"),Re(i,"Poetry"),Re(n,"pipx"),Re(a,"Go"),Re(s,"RapidKit Core"),[o,s].some(p=>p.status==="error")?(console.log(l.bold.red(`
|
|
3393
|
+
\u274C Some required tools are missing`)),e.fix&&console.log(l.gray(`
|
|
3394
|
+
Tip: Project auto-fix runs in workspace mode. Run from a workspace and use "npx rapidkit doctor workspace --fix"`)),console.log(l.gray(`
|
|
3395
|
+
Tip: Run "npx rapidkit doctor workspace" for detailed project checks`))):(console.log(l.bold.green(`
|
|
3396
|
+
\u2705 All required tools are installed!`)),e.fix&&console.log(l.gray(`
|
|
3397
|
+
Tip: Project auto-fix runs in workspace mode. Run from a workspace and use "npx rapidkit doctor workspace --fix"`)),console.log(l.gray(`
|
|
3398
|
+
Tip: Run "npx rapidkit doctor workspace" for detailed project checks`)));}console.log("");}var Dt=f.join(qi.homedir(),".rapidkit"),ft=f.join(Dt,"config.json");function We(){try{if(!S.existsSync(ft))return {};let e=S.readFileSync(ft,"utf-8");return JSON.parse(e)}catch{return {}}}function ht(e){let t={...We(),...e};S.existsSync(Dt)||S.mkdirSync(Dt,{recursive:true}),S.writeFileSync(ft,JSON.stringify(t,null,2),"utf-8");}function et(){return process.env.OPENAI_API_KEY||We().openaiApiKey||null}function Gt(){return We().aiEnabled!==false}function Mt(){return ft}async function hr(){return (await import('inquirer')).default}function yr(e){let r=e.command("config").description("Configure RapidKit settings");r.command("set-api-key").description("Set OpenAI API key for AI features").option("--key <key>","API key (or enter interactively)").action(async t=>{let o=t.key;o?o.startsWith("sk-")||(console.log(l.red(`
|
|
4119
3399
|
\u274C Invalid API key format (should start with sk-)
|
|
4120
|
-
`)),process.exit(1)):
|
|
3400
|
+
`)),process.exit(1)):o=(await(await hr()).prompt([{type:"password",name:"apiKey",message:"Enter your OpenAI API key:",validate:a=>a?a.startsWith("sk-")?a.length<20?"API key seems too short":true:"Invalid API key format (should start with sk-)":"API key is required"}])).apiKey,ht({openaiApiKey:o}),console.log(l.green(`
|
|
4121
3401
|
\u2705 OpenAI API key saved successfully!
|
|
4122
|
-
`)),console.log(
|
|
4123
|
-
\u{1F389} You can now use AI features:`)),console.log(
|
|
4124
|
-
\u{1F4A1} To generate module embeddings (one-time):`)),console.log(
|
|
4125
|
-
`));}),
|
|
3402
|
+
`)),console.log(l.gray(`Stored in: ${Mt()}`)),console.log(l.cyan(`
|
|
3403
|
+
\u{1F389} You can now use AI features:`)),console.log(l.white(' rapidkit ai recommend "I need user authentication"')),console.log(l.gray(`
|
|
3404
|
+
\u{1F4A1} To generate module embeddings (one-time):`)),console.log(l.white(" cd rapidkit-npm")),console.log(l.white(` npx tsx src/ai/generate-embeddings.ts
|
|
3405
|
+
`));}),r.command("show").description("Show current configuration").action(()=>{let t=We();if(console.log(l.bold(`
|
|
4126
3406
|
\u2699\uFE0F RapidKit Configuration
|
|
4127
|
-
`)),t.openaiApiKey){let
|
|
4128
|
-
\u{1F4C1} Config file: ${
|
|
4129
|
-
`));}),
|
|
3407
|
+
`)),t.openaiApiKey){let o=t.openaiApiKey.substring(0,8)+"..."+t.openaiApiKey.slice(-4);console.log(l.cyan("OpenAI API Key:"),l.white(o));}else console.log(l.cyan("OpenAI API Key:"),l.red("Not set")),console.log(l.gray(" Set with: rapidkit config set-api-key"));console.log(l.cyan("AI Features:"),t.aiEnabled!==false?l.green("Enabled"):l.red("Disabled")),console.log(l.gray(`
|
|
3408
|
+
\u{1F4C1} Config file: ${Mt()}
|
|
3409
|
+
`));}),r.command("remove-api-key").description("Remove stored OpenAI API key").action(async()=>{if(!We().openaiApiKey){console.log(l.yellow(`
|
|
4130
3410
|
\u26A0\uFE0F No API key is currently stored
|
|
4131
|
-
`));return}(await(await
|
|
3411
|
+
`));return}(await(await hr()).prompt([{type:"confirm",name:"confirm",message:"Are you sure you want to remove your OpenAI API key?",default:false}])).confirm?(ht({openaiApiKey:void 0}),console.log(l.green(`
|
|
4132
3412
|
\u2705 API key removed successfully
|
|
4133
|
-
`))):console.log(
|
|
3413
|
+
`))):console.log(l.gray(`
|
|
4134
3414
|
Cancelled
|
|
4135
|
-
`));}),
|
|
4136
|
-
\u274C Invalid action: ${t}`)),console.log(
|
|
4137
|
-
`)),process.exit(1));let
|
|
4138
|
-
\u2705 AI features ${
|
|
4139
|
-
`));});}var Ue=null,Ve=false,vt=null;async function Nn(){return vt||(vt=(await import('openai')).default),vt}function ao(){Ve=true;}function co(e){let t=new Array(1536),r=0;for(let n=0;n<e.length;n++)r=(r<<5)-r+e.charCodeAt(n),r=r&r;for(let n=0;n<1536;n++)r=r*1664525+1013904223&4294967295,t[n]=r/4294967295*2-1;let i=Math.sqrt(t.reduce((n,s)=>n+s*s,0));return t.map(n=>n/i)}async function We(e){let o=await Nn();Ue=new o({apiKey:e});}function lo(){if(!Ue)throw new Error("OpenAI client not initialized. Call initOpenAI() first with your API key.");return Ue}async function po(e){return Ve?co(e):(await lo().embeddings.create({model:"text-embedding-3-small",input:e,encoding_format:"float"})).data[0].embedding}async function uo(e){return Ve?e.map(co):(await lo().embeddings.create({model:"text-embedding-3-small",input:e,encoding_format:"float"})).data.map(r=>r.embedding)}function go(){return Ue!==null}function mo(){return Ve}var $n=promisify(exec),ho=[{id:"authentication-core",name:"Authentication Core",category:"auth",description:"Complete authentication system with password hashing, JWT tokens, OAuth 2.0, and secure session management",longDescription:"Production-ready authentication with bcrypt password hashing, JWT access/refresh tokens, OAuth 2.0 providers (Google, GitHub, etc), rate limiting, and security best practices.",keywords:["auth","login","password","jwt","oauth","token","authentication","security","signin","signup"],framework:"both",dependencies:[],useCases:["User login and logout","Password reset flow","OAuth social login (Google, GitHub)","JWT authentication","Secure session management","Token refresh","Rate limiting"]},{id:"users-core",name:"Users Core",category:"auth",description:"User management system with profiles, roles, permissions, and user CRUD operations",longDescription:"Complete user management with user profiles, role-based access control (RBAC), permissions, user search, soft delete, and audit trails.",keywords:["user","profile","role","permission","rbac","management","admin","accounts"],framework:"both",dependencies:["authentication-core"],useCases:["User registration","User profile management","Role management (admin, user, etc)","Permission system","User administration dashboard","Soft delete users"]},{id:"session-management",name:"Session Management",category:"auth",description:"Secure session handling with Redis storage, session rotation, and device tracking",longDescription:"Advanced session management with Redis-backed storage, automatic session rotation, device fingerprinting, IP tracking, and session revocation.",keywords:["session","redis","cookie","storage","device","tracking"],framework:"both",dependencies:["authentication-core","redis-cache"],useCases:["User session management","Remember me functionality","Device tracking","Session security","Logout from all devices","Session expiration"]},{id:"db-postgres",name:"PostgreSQL",category:"database",description:"PostgreSQL integration with async SQLAlchemy, migrations, connection pooling, and query optimization",longDescription:"Production-ready PostgreSQL with async SQLAlchemy 2.0, Alembic migrations, connection pooling, query optimization, JSON support, and full-text search.",keywords:["postgres","postgresql","database","sql","sqlalchemy","migration","orm","relational"],framework:"both",dependencies:[],useCases:["Relational database","Complex SQL queries","Database transactions","Data integrity","Production-grade database","ACID compliance"]},{id:"db-mongodb",name:"MongoDB",category:"database",description:"MongoDB integration with Motor async driver, schema validation, and aggregation pipelines",longDescription:"Async MongoDB with Motor driver, Pydantic schema validation, aggregation pipelines, indexes, and Atlas integration.",keywords:["mongodb","mongo","nosql","document","database","motor"],framework:"both",dependencies:[],useCases:["Document storage","Flexible schema","Real-time data","JSON documents","Unstructured data","Analytics"]},{id:"stripe-payment",name:"Stripe Payment",category:"payment",description:"Stripe integration with payment intents, subscriptions, webhooks, and customer portal",longDescription:"Complete Stripe integration with Payment Intents API, subscription management, automatic webhooks, customer portal, refunds, and SCA compliance.",keywords:["stripe","payment","subscription","billing","checkout","webhook","credit card"],framework:"both",dependencies:[],useCases:["Accept credit card payments","Subscription billing","One-time payments","Checkout flow","Payment webhooks","Refunds and disputes"]},{id:"email",name:"Email",category:"communication",description:"Email sending with templates, SMTP/SendGrid/AWS SES support, and queue management",longDescription:"Production email system with Jinja2 templates, multiple providers (SMTP, SendGrid, AWS SES), queue management, retry logic, and bounce handling.",keywords:["email","mail","smtp","sendgrid","ses","template","notification"],framework:"both",dependencies:[],useCases:["Welcome emails","Password reset emails","Notifications","Marketing emails","Transactional emails","Email templates"]},{id:"sms",name:"SMS",category:"communication",description:"SMS sending with Twilio, verification codes, and delivery tracking",longDescription:"SMS integration with Twilio, verification codes, two-factor authentication, delivery tracking, and international support.",keywords:["sms","twilio","text","message","2fa","verification","otp"],framework:"both",dependencies:[],useCases:["2FA verification codes","SMS notifications","Phone verification","OTP generation","SMS alerts"]},{id:"redis-cache",name:"Redis Cache",category:"infrastructure",description:"Redis caching with decorators, TTL management, and cache invalidation patterns",longDescription:"Redis integration with async client, caching decorators, TTL management, cache invalidation, pub/sub, and rate limiting.",keywords:["redis","cache","memory","performance","speed","pubsub"],framework:"both",dependencies:[],useCases:["API response caching","Session storage","Rate limiting","Real-time features","Performance optimization","Pub/sub messaging"]},{id:"celery",name:"Celery",category:"infrastructure",description:"Background task processing with Celery, periodic tasks, and monitoring",longDescription:"Celery task queue with Redis/RabbitMQ backend, periodic tasks (cron), task monitoring, retry logic, and failure handling.",keywords:["celery","task","background","queue","async","worker","job","cron"],framework:"fastapi",dependencies:["redis-cache"],useCases:["Background email sending","Data processing","Report generation","Scheduled tasks","Long-running jobs"]},{id:"storage",name:"Storage",category:"infrastructure",description:"File storage with S3, local filesystem, and image processing",longDescription:"Unified storage interface for AWS S3, local files, image resizing, format conversion, CDN integration, and presigned URLs.",keywords:["storage","s3","file","upload","image","cdn","aws"],framework:"both",dependencies:[],useCases:["File uploads","Image storage","Document management","Profile pictures","Media files","CDN integration"]}],ge=null,fo=0,Dn=300*1e3;function Mn(e){return {id:e.name||e.id||e.module_id||"",name:e.display_name||e.name||"",category:qn(e.category||"infrastructure"),description:e.description||e.summary||"",longDescription:e.long_description||e.description||"",keywords:e.keywords||e.tags||[],framework:Ln(e.framework),dependencies:e.dependencies||[],useCases:e.use_cases||e.useCases||[]}}function qn(e){return {auth:"auth",authentication:"auth",database:"database",payment:"payment",billing:"payment",communication:"communication",infrastructure:"infrastructure",security:"security",analytics:"analytics"}[e.toLowerCase()]||"infrastructure"}function Ln(e){if(!e)return "both";if(typeof e=="string"){if(e.toLowerCase().includes("fastapi"))return "fastapi";if(e.toLowerCase().includes("nest"))return "nestjs"}return "both"}async function Fn(){try{let{stdout:e}=await $n("rapidkit modules list --json-schema 1",{timeout:1e4,maxBuffer:10485760}),o=e.match(/\{[\s\S]*\}/),t=o?o[0]:e,r=JSON.parse(t),i=[];return Array.isArray(r)?i=r:r.modules&&Array.isArray(r.modules)?i=r.modules:r.data&&Array.isArray(r.data)&&(i=r.data),i.map(Mn).filter(n=>n.id&&n.name)}catch(e){return e.code==="ENOENT"?console.warn("\u26A0\uFE0F RapidKit Python Core not found in PATH"):e.killed?console.warn("\u26A0\uFE0F Python Core command timed out"):console.warn("\u26A0\uFE0F Failed to fetch modules from Python Core:",e.message),console.warn(" Using fallback module catalog (11 modules)"),ho}}async function Be(){let e=Date.now();return ge&&e-fo<Dn||(ge=await Fn(),fo=e,ge.length===0&&(console.warn("\u26A0\uFE0F No modules found, using fallback catalog"),ge=ho)),ge}var Kn=fileURLToPath(import.meta.url),yo=v.dirname(Kn),Ce=null;function Un(){if(Ce)return Ce;let e=[v.join(yo,"../../data/modules-embeddings.json"),v.join(yo,"../data/modules-embeddings.json"),v.join(process.cwd(),"data/modules-embeddings.json")],o=null;for(let i of e)if(A.existsSync(i)){o=i;break}if(!o)throw new Error("embeddings file not found");let t=A.readFileSync(o,"utf-8"),r=JSON.parse(t);return Array.isArray(r)?Ce={model:"mock-or-text-embedding-3-small",dimension:r[0]?.embedding?.length||1536,generated_at:new Date().toISOString(),modules:r}:Ce=r,Ce}function Vn(e,o){if(e.length!==o.length)throw new Error("Vectors must have the same length");let t=0,r=0,i=0;for(let s=0;s<e.length;s++)t+=e[s]*o[s],r+=e[s]*e[s],i+=o[s]*o[s];let n=Math.sqrt(r)*Math.sqrt(i);return n===0?0:t/n}function Wn(e,o){let t=o.toLowerCase(),r=e.keywords.filter(i=>t.includes(i)||i.includes(t));return r.length>0?`Matches: ${r.slice(0,3).join(", ")}`:`Relevant for: ${e.useCases[0]}`}async function vo(e,o=5){let t=Un(),r=await Be(),i=await po(e),n=t.modules.map(s=>{let c=r.find(l=>l.id===s.id);if(!c)return null;let a=Vn(i,s.embedding);return {module:c,score:a,reason:Wn(c,e)}}).filter(s=>s!==null);return n.sort((s,c)=>c.score-s.score),n.slice(0,o)}var zn=fileURLToPath(import.meta.url),bo=v.dirname(zn);async function ko(){return (await import('inquirer')).default}function Yn(){return [v.join(bo,"../../data/modules-embeddings.json"),v.join(bo,"../data/modules-embeddings.json"),v.join(process.cwd(),"data/modules-embeddings.json")]}function Ro(){let e=Yn();for(let o of e)if(A.existsSync(o))try{let t=JSON.parse(A.readFileSync(o,"utf-8")),r=Array.isArray(t)?t:t.modules||[];return {exists:true,path:o,moduleCount:r.length,generatedAt:t.generated_at||null}}catch{continue}return {exists:false,path:null,moduleCount:0,generatedAt:null}}async function ze(e=true,o){try{if(!go()&&!mo())return console.log(g.red(`
|
|
4140
|
-
\u274C OpenAI not initialized`)),console.log(
|
|
4141
|
-
`)),false;console.log(
|
|
3415
|
+
`));}),r.command("ai <action>").description("Enable or disable AI features (enable|disable)").action(t=>{t!=="enable"&&t!=="disable"&&(console.log(l.red(`
|
|
3416
|
+
\u274C Invalid action: ${t}`)),console.log(l.gray(`Use: rapidkit config ai enable|disable
|
|
3417
|
+
`)),process.exit(1));let o=t==="enable";ht({aiEnabled:o}),console.log(l.green(`
|
|
3418
|
+
\u2705 AI features ${o?"enabled":"disabled"}
|
|
3419
|
+
`));});}var yt=null,wt=false,Lt=null;async function Fi(){return Lt||(Lt=(await import('openai')).default),Lt}function wr(){wt=true;}function vr(e){let t=new Array(1536),o=0;for(let n=0;n<e.length;n++)o=(o<<5)-o+e.charCodeAt(n),o=o&o;for(let n=0;n<1536;n++)o=o*1664525+1013904223&4294967295,t[n]=o/4294967295*2-1;let i=Math.sqrt(t.reduce((n,a)=>n+a*a,0));return t.map(n=>n/i)}async function vt(e){let r=await Fi();yt=new r({apiKey:e});}function kr(){if(!yt)throw new Error("OpenAI client not initialized. Call initOpenAI() first with your API key.");return yt}async function br(e){return wt?vr(e):(await kr().embeddings.create({model:"text-embedding-3-small",input:e,encoding_format:"float"})).data[0].embedding}async function Rr(e){return wt?e.map(vr):(await kr().embeddings.create({model:"text-embedding-3-small",input:e,encoding_format:"float"})).data.map(o=>o.embedding)}function Cr(){return yt!==null}function Sr(){return wt}var Ui=promisify(exec),xr=[{id:"authentication-core",name:"Authentication Core",category:"auth",description:"Complete authentication system with password hashing, JWT tokens, OAuth 2.0, and secure session management",longDescription:"Production-ready authentication with bcrypt password hashing, JWT access/refresh tokens, OAuth 2.0 providers (Google, GitHub, etc), rate limiting, and security best practices.",keywords:["auth","login","password","jwt","oauth","token","authentication","security","signin","signup"],framework:"both",dependencies:[],useCases:["User login and logout","Password reset flow","OAuth social login (Google, GitHub)","JWT authentication","Secure session management","Token refresh","Rate limiting"]},{id:"users-core",name:"Users Core",category:"auth",description:"User management system with profiles, roles, permissions, and user CRUD operations",longDescription:"Complete user management with user profiles, role-based access control (RBAC), permissions, user search, soft delete, and audit trails.",keywords:["user","profile","role","permission","rbac","management","admin","accounts"],framework:"both",dependencies:["authentication-core"],useCases:["User registration","User profile management","Role management (admin, user, etc)","Permission system","User administration dashboard","Soft delete users"]},{id:"session-management",name:"Session Management",category:"auth",description:"Secure session handling with Redis storage, session rotation, and device tracking",longDescription:"Advanced session management with Redis-backed storage, automatic session rotation, device fingerprinting, IP tracking, and session revocation.",keywords:["session","redis","cookie","storage","device","tracking"],framework:"both",dependencies:["authentication-core","redis-cache"],useCases:["User session management","Remember me functionality","Device tracking","Session security","Logout from all devices","Session expiration"]},{id:"db-postgres",name:"PostgreSQL",category:"database",description:"PostgreSQL integration with async SQLAlchemy, migrations, connection pooling, and query optimization",longDescription:"Production-ready PostgreSQL with async SQLAlchemy 2.0, Alembic migrations, connection pooling, query optimization, JSON support, and full-text search.",keywords:["postgres","postgresql","database","sql","sqlalchemy","migration","orm","relational"],framework:"both",dependencies:[],useCases:["Relational database","Complex SQL queries","Database transactions","Data integrity","Production-grade database","ACID compliance"]},{id:"db-mongodb",name:"MongoDB",category:"database",description:"MongoDB integration with Motor async driver, schema validation, and aggregation pipelines",longDescription:"Async MongoDB with Motor driver, Pydantic schema validation, aggregation pipelines, indexes, and Atlas integration.",keywords:["mongodb","mongo","nosql","document","database","motor"],framework:"both",dependencies:[],useCases:["Document storage","Flexible schema","Real-time data","JSON documents","Unstructured data","Analytics"]},{id:"stripe-payment",name:"Stripe Payment",category:"payment",description:"Stripe integration with payment intents, subscriptions, webhooks, and customer portal",longDescription:"Complete Stripe integration with Payment Intents API, subscription management, automatic webhooks, customer portal, refunds, and SCA compliance.",keywords:["stripe","payment","subscription","billing","checkout","webhook","credit card"],framework:"both",dependencies:[],useCases:["Accept credit card payments","Subscription billing","One-time payments","Checkout flow","Payment webhooks","Refunds and disputes"]},{id:"email",name:"Email",category:"communication",description:"Email sending with templates, SMTP/SendGrid/AWS SES support, and queue management",longDescription:"Production email system with Jinja2 templates, multiple providers (SMTP, SendGrid, AWS SES), queue management, retry logic, and bounce handling.",keywords:["email","mail","smtp","sendgrid","ses","template","notification"],framework:"both",dependencies:[],useCases:["Welcome emails","Password reset emails","Notifications","Marketing emails","Transactional emails","Email templates"]},{id:"sms",name:"SMS",category:"communication",description:"SMS sending with Twilio, verification codes, and delivery tracking",longDescription:"SMS integration with Twilio, verification codes, two-factor authentication, delivery tracking, and international support.",keywords:["sms","twilio","text","message","2fa","verification","otp"],framework:"both",dependencies:[],useCases:["2FA verification codes","SMS notifications","Phone verification","OTP generation","SMS alerts"]},{id:"redis-cache",name:"Redis Cache",category:"infrastructure",description:"Redis caching with decorators, TTL management, and cache invalidation patterns",longDescription:"Redis integration with async client, caching decorators, TTL management, cache invalidation, pub/sub, and rate limiting.",keywords:["redis","cache","memory","performance","speed","pubsub"],framework:"both",dependencies:[],useCases:["API response caching","Session storage","Rate limiting","Real-time features","Performance optimization","Pub/sub messaging"]},{id:"celery",name:"Celery",category:"infrastructure",description:"Background task processing with Celery, periodic tasks, and monitoring",longDescription:"Celery task queue with Redis/RabbitMQ backend, periodic tasks (cron), task monitoring, retry logic, and failure handling.",keywords:["celery","task","background","queue","async","worker","job","cron"],framework:"fastapi",dependencies:["redis-cache"],useCases:["Background email sending","Data processing","Report generation","Scheduled tasks","Long-running jobs"]},{id:"storage",name:"Storage",category:"infrastructure",description:"File storage with S3, local filesystem, and image processing",longDescription:"Unified storage interface for AWS S3, local files, image resizing, format conversion, CDN integration, and presigned URLs.",keywords:["storage","s3","file","upload","image","cdn","aws"],framework:"both",dependencies:[],useCases:["File uploads","Image storage","Document management","Profile pictures","Media files","CDN integration"]}],Ve=null,_r=0,Wi=300*1e3;function Vi(e){return {id:e.name||e.id||e.module_id||"",name:e.display_name||e.name||"",category:Bi(e.category||"infrastructure"),description:e.description||e.summary||"",longDescription:e.long_description||e.description||"",keywords:e.keywords||e.tags||[],framework:Ji(e.framework),dependencies:e.dependencies||[],useCases:e.use_cases||e.useCases||[]}}function Bi(e){return {auth:"auth",authentication:"auth",database:"database",payment:"payment",billing:"payment",communication:"communication",infrastructure:"infrastructure",security:"security",analytics:"analytics"}[e.toLowerCase()]||"infrastructure"}function Ji(e){if(!e)return "both";if(typeof e=="string"){if(e.toLowerCase().includes("fastapi"))return "fastapi";if(e.toLowerCase().includes("nest"))return "nestjs"}return "both"}async function Yi(){try{let{stdout:e}=await Ui("rapidkit modules list --json-schema 1",{timeout:1e4,maxBuffer:10485760}),r=e.match(/\{[\s\S]*\}/),t=r?r[0]:e,o=JSON.parse(t),i=[];return Array.isArray(o)?i=o:o.modules&&Array.isArray(o.modules)?i=o.modules:o.data&&Array.isArray(o.data)&&(i=o.data),i.map(Vi).filter(n=>n.id&&n.name)}catch(e){return e.code==="ENOENT"?console.warn("\u26A0\uFE0F RapidKit Python Core not found in PATH"):e.killed?console.warn("\u26A0\uFE0F Python Core command timed out"):console.warn("\u26A0\uFE0F Failed to fetch modules from Python Core:",e.message),console.warn(" Using fallback module catalog (11 modules)"),xr}}async function kt(){let e=Date.now();return Ve&&e-_r<Wi||(Ve=await Yi(),_r=e,Ve.length===0&&(console.warn("\u26A0\uFE0F No modules found, using fallback catalog"),Ve=xr)),Ve}var Qi=fileURLToPath(import.meta.url),Er=f.dirname(Qi),tt=null;function Xi(){if(tt)return tt;let e=[f.join(Er,"../../data/modules-embeddings.json"),f.join(Er,"../data/modules-embeddings.json"),f.join(process.cwd(),"data/modules-embeddings.json")],r=null;for(let i of e)if(S.existsSync(i)){r=i;break}if(!r)throw new Error("embeddings file not found");let t=S.readFileSync(r,"utf-8"),o=JSON.parse(t);return Array.isArray(o)?tt={model:"mock-or-text-embedding-3-small",dimension:o[0]?.embedding?.length||1536,generated_at:new Date().toISOString(),modules:o}:tt=o,tt}function Zi(e,r){if(e.length!==r.length)throw new Error("Vectors must have the same length");let t=0,o=0,i=0;for(let a=0;a<e.length;a++)t+=e[a]*r[a],o+=e[a]*e[a],i+=r[a]*r[a];let n=Math.sqrt(o)*Math.sqrt(i);return n===0?0:t/n}function en(e,r){let t=r.toLowerCase(),o=e.keywords.filter(i=>t.includes(i)||i.includes(t));return o.length>0?`Matches: ${o.slice(0,3).join(", ")}`:`Relevant for: ${e.useCases[0]}`}async function Ir(e,r=5){let t=Xi(),o=await kt(),i=await br(e),n=t.modules.map(a=>{let s=o.find(p=>p.id===a.id);if(!s)return null;let c=Zi(i,a.embedding);return {module:s,score:c,reason:en(s,e)}}).filter(a=>a!==null);return n.sort((a,s)=>s.score-a.score),n.slice(0,r)}var on=fileURLToPath(import.meta.url),Tr=f.dirname(on);async function Or(){return (await import('inquirer')).default}function nn(){return [f.join(Tr,"../../data/modules-embeddings.json"),f.join(Tr,"../data/modules-embeddings.json"),f.join(process.cwd(),"data/modules-embeddings.json")]}function Ar(){let e=nn();for(let r of e)if(S.existsSync(r))try{let t=JSON.parse(S.readFileSync(r,"utf-8")),o=Array.isArray(t)?t:t.modules||[];return {exists:true,path:r,moduleCount:o.length,generatedAt:t.generated_at||null}}catch{continue}return {exists:false,path:null,moduleCount:0,generatedAt:null}}async function Rt(e=true,r){try{if(!Cr()&&!Sr())return console.log(l.red(`
|
|
3420
|
+
\u274C OpenAI not initialized`)),console.log(l.yellow("Please set your API key:")),console.log(l.white(" rapidkit config set-api-key")),console.log(l.gray(` OR set: export OPENAI_API_KEY="sk-..."
|
|
3421
|
+
`)),false;console.log(l.blue(`
|
|
4142
3422
|
\u{1F916} Generating AI embeddings for RapidKit modules...
|
|
4143
|
-
`)),console.log(
|
|
4144
|
-
`));let
|
|
4145
|
-
`)),e){let
|
|
3423
|
+
`)),console.log(l.gray("\u{1F4E1} Fetching modules from RapidKit..."));let t=await kt();console.log(l.green(`\u2713 Found ${t.length} modules
|
|
3424
|
+
`));let o=t.length*50/1e6*.02;if(console.log(l.cyan(`\u{1F4B0} Estimated cost: ~$${o.toFixed(3)}`)),console.log(l.gray(` (Based on ${t.length} modules at $0.02/1M tokens)
|
|
3425
|
+
`)),e){let a=await Or(),{confirm:s}=await a.prompt([{type:"confirm",name:"confirm",message:"Generate embeddings now?",default:true}]);if(!s)return console.log(l.yellow(`
|
|
4146
3426
|
\u26A0\uFE0F Embeddings generation cancelled
|
|
4147
|
-
`)),false}let i=t.map(
|
|
4148
|
-
\u2705 Embeddings generated successfully!`)),console.log(
|
|
4149
|
-
`)),true}catch(
|
|
4150
|
-
\u274C OpenAI API quota exceeded`)),console.log(
|
|
4151
|
-
`))):
|
|
4152
|
-
\u274C Invalid API key`)),console.log(
|
|
4153
|
-
`))):console.log(
|
|
4154
|
-
\u274C Error: ${
|
|
4155
|
-
`)),false}}catch(t){return console.log(
|
|
3427
|
+
`)),false}let i=t.map(a=>`${a.name}. ${a.description}. ${a.longDescription}. Keywords: ${a.keywords.join(", ")}. Use cases: ${a.useCases.join(", ")}.`),n=At(`Generating embeddings for ${t.length} modules...`).start();try{let a=await Rr(i);n.succeed(`Generated embeddings for ${t.length} modules`);let s={model:"text-embedding-3-small",dimension:a[0].length,generated_at:new Date().toISOString(),modules:t.map((d,m)=>({id:d.id,name:d.name,embedding:a[m]}))},c=r||f.join(process.cwd(),"data","modules-embeddings.json"),p=f.dirname(c);return S.existsSync(p)||S.mkdirSync(p,{recursive:true}),S.writeFileSync(c,JSON.stringify(s,null,2)),console.log(l.green(`
|
|
3428
|
+
\u2705 Embeddings generated successfully!`)),console.log(l.gray(`\u{1F4C1} Saved to: ${c}`)),console.log(l.gray(`\u{1F4CA} Size: ${t.length} modules, ${a[0].length} dimensions
|
|
3429
|
+
`)),true}catch(a){return n.fail("Failed to generate embeddings"),a.message?.includes("429")?(console.log(l.red(`
|
|
3430
|
+
\u274C OpenAI API quota exceeded`)),console.log(l.yellow(`Please check your billing: https://platform.openai.com/account/billing
|
|
3431
|
+
`))):a.message?.includes("401")?(console.log(l.red(`
|
|
3432
|
+
\u274C Invalid API key`)),console.log(l.yellow("Please set a valid API key:")),console.log(l.white(` rapidkit config set-api-key
|
|
3433
|
+
`))):console.log(l.red(`
|
|
3434
|
+
\u274C Error: ${a.message}
|
|
3435
|
+
`)),false}}catch(t){return console.log(l.red(`
|
|
4156
3436
|
\u274C Failed to generate embeddings: ${t.message}
|
|
4157
|
-
`)),false}}async function
|
|
4158
|
-
\u26A0\uFE0F Module embeddings not found`)),console.log(
|
|
4159
|
-
`)),!e)return console.log(
|
|
4160
|
-
`)),false;let t=await
|
|
3437
|
+
`)),false}}async function Nr(e=true){if(Ar().exists)return true;if(console.log(l.yellow(`
|
|
3438
|
+
\u26A0\uFE0F Module embeddings not found`)),console.log(l.gray(`AI recommendations require embeddings to be generated.
|
|
3439
|
+
`)),!e)return console.log(l.red("\u274C Cannot generate embeddings in non-interactive mode")),console.log(l.white(`Run: rapidkit ai generate-embeddings
|
|
3440
|
+
`)),false;let t=await Or(),{action:o}=await t.prompt([{type:"list",name:"action",message:"What would you like to do?",choices:[{name:"\u{1F680} Generate embeddings now (requires OpenAI API key)",value:"generate"},{name:"\u{1F4DD} Show me how to generate them manually",value:"manual"},{name:"\u274C Cancel",value:"cancel"}]}]);return o==="generate"?await Rt(true):(o==="manual"&&(console.log(l.cyan(`
|
|
4161
3441
|
\u{1F4DD} To generate embeddings manually:
|
|
4162
|
-
`)),console.log(
|
|
4163
|
-
`)),console.log(
|
|
4164
|
-
`)),console.log(
|
|
4165
|
-
`))),false)}async function
|
|
4166
|
-
\u{1F504} Updating embeddings...`)),console.log(
|
|
4167
|
-
`)),await
|
|
4168
|
-
\u26A0\uFE0F No existing embeddings found`)),console.log(
|
|
4169
|
-
`)),false)}async function
|
|
4170
|
-
\u26A0\uFE0F AI features are disabled`)),console.log(
|
|
4171
|
-
`)),process.exit(1));let i=
|
|
3442
|
+
`)),console.log(l.white("1. Get OpenAI API key from: https://platform.openai.com/api-keys")),console.log(l.white("2. Set the API key:")),console.log(l.gray(" rapidkit config set-api-key")),console.log(l.gray(` OR: export OPENAI_API_KEY="sk-..."
|
|
3443
|
+
`)),console.log(l.white("3. Generate embeddings:")),console.log(l.gray(` rapidkit ai generate-embeddings
|
|
3444
|
+
`)),console.log(l.cyan(`\u{1F4B0} Cost: ~$0.50 one-time
|
|
3445
|
+
`))),false)}async function jr(){let e=Ar();return e.exists?(console.log(l.blue(`
|
|
3446
|
+
\u{1F504} Updating embeddings...`)),console.log(l.gray(`Current: ${e.moduleCount} modules`)),console.log(l.gray(`Generated: ${e.generatedAt||"unknown"}
|
|
3447
|
+
`)),await Rt(true,e.path)):(console.log(l.yellow(`
|
|
3448
|
+
\u26A0\uFE0F No existing embeddings found`)),console.log(l.gray(`Use: rapidkit ai generate-embeddings
|
|
3449
|
+
`)),false)}async function $r(){return (await import('inquirer')).default}function Dr(e){let r=e.command("ai").description("AI-powered features");r.command("recommend").description("Get AI-powered module recommendations").argument("[query]",'What do you want to build? (e.g., "user authentication with email")').option("-n, --number <count>","Number of recommendations","5").option("--json","Output as JSON").action(async(t,o)=>{try{Gt()||(console.log(l.yellow(`
|
|
3450
|
+
\u26A0\uFE0F AI features are disabled`)),console.log(l.gray(`Enable with: rapidkit config ai enable
|
|
3451
|
+
`)),process.exit(1));let i=et();i?await vt(i):(console.log(l.yellow(`
|
|
4172
3452
|
\u26A0\uFE0F OpenAI API key not configured - using MOCK MODE for testing
|
|
4173
|
-
`)),console.log(
|
|
4174
|
-
`)),console.log(
|
|
4175
|
-
`)),
|
|
3453
|
+
`)),console.log(l.gray("\u{1F4DD} Note: Mock embeddings provide approximate results for testing.")),console.log(l.gray(` For production, configure your OpenAI API key:
|
|
3454
|
+
`)),console.log(l.white(" 1. Get your key from: https://platform.openai.com/api-keys")),console.log(l.white(" 2. Configure it: rapidkit config set-api-key")),console.log(l.gray(` OR set: export OPENAI_API_KEY="sk-proj-..."
|
|
3455
|
+
`)),wr());let n=t;n||(n=(await(await $r()).prompt([{type:"input",name:"query",message:"\u{1F916} What do you want to build?",validate:g=>g.length===0?"Please enter a description":g.length<3?"Please be more specific (at least 3 characters)":true}])).query),o.json||console.log(l.blue(`
|
|
4176
3456
|
\u{1F916} Analyzing your request...
|
|
4177
|
-
`)),await
|
|
3457
|
+
`)),await Nr(!o.json)||(console.log(l.yellow(`
|
|
4178
3458
|
\u26A0\uFE0F Cannot proceed without embeddings
|
|
4179
|
-
`)),process.exit(1));let
|
|
3459
|
+
`)),process.exit(1));let s=parseInt(o.number,10),c=await Ir(n,s);if(c.length===0||c[0].score<.3)if(console.log(l.yellow(`
|
|
4180
3460
|
\u26A0\uFE0F No matching modules found in RapidKit registry.
|
|
4181
|
-
`)),console.log(
|
|
4182
|
-
`)),console.log(
|
|
4183
|
-
`)),console.log(
|
|
4184
|
-
`)),console.log(
|
|
4185
|
-
`)),
|
|
4186
|
-
`));else return;if(
|
|
4187
|
-
`)),
|
|
4188
|
-
`));let d=await
|
|
4189
|
-
\u{1F4E6} Installing ${
|
|
4190
|
-
`)),console.log(
|
|
4191
|
-
\u26A0\uFE0F Note: Module installation not yet implemented`)),console.log(
|
|
4192
|
-
`))):console.log(
|
|
3461
|
+
`)),console.log(l.cyan(`\u{1F4A1} Options:
|
|
3462
|
+
`)),console.log(l.white("1. Create custom module:")),console.log(l.gray(" rapidkit modules scaffold <name> --category <category>")),console.log(l.gray(` Example: rapidkit modules scaffold blockchain-integration --category integrations
|
|
3463
|
+
`)),console.log(l.white("2. Search with different keywords")),console.log(l.gray(` Try more general terms (e.g., "storage" instead of "blockchain")
|
|
3464
|
+
`)),console.log(l.white("3. Request feature:")),console.log(l.gray(` https://github.com/getrapidkit/rapidkit/issues
|
|
3465
|
+
`)),c.length>0)console.log(l.yellow(`\u26A0\uFE0F Low confidence matches found:
|
|
3466
|
+
`));else return;if(o.json){console.log(JSON.stringify({query:n,recommendations:c},null,2));return}console.log(l.green.bold(`\u{1F4E6} Recommended Modules:
|
|
3467
|
+
`)),c.forEach((h,w)=>{let g=(h.score*100).toFixed(1),u=h.score>.8?" \u2B50":"";console.log(l.bold(`${w+1}. ${h.module.name}${u}`)),console.log(l.gray(` ${h.module.description}`)),console.log(l.cyan(` Match: ${g}%`)+l.gray(` - ${h.reason}`)),console.log(l.yellow(` Category: ${h.module.category}`)),h.module.dependencies.length>0&&console.log(l.magenta(` Requires: ${h.module.dependencies.join(", ")}`)),console.log();});let p=c.slice(0,3).map(h=>h.module.id);console.log(l.cyan("\u{1F4A1} Quick install (top 3):")),console.log(l.white(` rapidkit add module ${p.join(" ")}
|
|
3468
|
+
`));let d=await $r(),{shouldInstall:m}=await d.prompt([{type:"confirm",name:"shouldInstall",message:"Would you like to install these modules now?",default:false}]);if(m){let{selectedModules:h}=await d.prompt([{type:"checkbox",name:"selectedModules",message:"Select modules to install:",choices:c.map(w=>({name:`${w.module.name} - ${w.module.description}`,value:w.module.id,checked:w.score>.7}))}]);h.length>0?(console.log(l.blue(`
|
|
3469
|
+
\u{1F4E6} Installing ${h.length} modules...
|
|
3470
|
+
`)),console.log(l.gray(`Command: rapidkit add module ${h.join(" ")}`)),console.log(l.yellow(`
|
|
3471
|
+
\u26A0\uFE0F Note: Module installation not yet implemented`)),console.log(l.gray(`Coming soon in next version!
|
|
3472
|
+
`))):console.log(l.gray(`
|
|
4193
3473
|
No modules selected
|
|
4194
3474
|
`));}}catch(i){a.error(`
|
|
4195
|
-
\u274C Error:`,i.message),i.code==="invalid_api_key"?(console.log(
|
|
4196
|
-
\u{1F4A1} Your API key may be invalid or expired`)),console.log(
|
|
4197
|
-
`))):i.message.includes("embeddings file not found")&&(console.log(
|
|
4198
|
-
\u{1F4A1} Module embeddings not generated yet`)),console.log(
|
|
4199
|
-
`))),process.exit(1);}}),
|
|
3475
|
+
\u274C Error:`,i.message),i.code==="invalid_api_key"?(console.log(l.yellow(`
|
|
3476
|
+
\u{1F4A1} Your API key may be invalid or expired`)),console.log(l.cyan(` Update it: rapidkit config set-api-key
|
|
3477
|
+
`))):i.message.includes("embeddings file not found")&&(console.log(l.yellow(`
|
|
3478
|
+
\u{1F4A1} Module embeddings not generated yet`)),console.log(l.cyan(" Generate them (one-time):")),console.log(l.white(" cd rapidkit-npm")),console.log(l.white(' export OPENAI_API_KEY="sk-proj-..."')),console.log(l.white(` npx tsx src/ai/generate-embeddings.ts
|
|
3479
|
+
`))),process.exit(1);}}),r.command("info").description("Show AI features information").action(()=>{let t=et(),o=Gt();console.log(l.bold(`
|
|
4200
3480
|
\u{1F916} RapidKit AI Features
|
|
4201
|
-
`)),console.log(
|
|
3481
|
+
`)),console.log(l.cyan("Status:"),o?l.green("Enabled"):l.red("Disabled")),console.log(l.cyan("API Key:"),t?l.green("Configured \u2713"):l.red("Not configured \u2717")),console.log(l.bold(`
|
|
4202
3482
|
\u{1F4E6} Available Features:
|
|
4203
|
-
`)),console.log(
|
|
3483
|
+
`)),console.log(l.white("\u2022 Module Recommender")+l.gray(" - AI-powered module suggestions")),console.log(l.gray(' Usage: rapidkit ai recommend "I need authentication"')),console.log(l.bold(`
|
|
4204
3484
|
\u{1F4B0} Pricing:
|
|
4205
|
-
`)),console.log(
|
|
3485
|
+
`)),console.log(l.white("\u2022 Per query: ~$0.0002")+l.gray(" (practically free)")),console.log(l.white("\u2022 100 queries: ~$0.02")+l.gray(" (2 cents)")),console.log(l.white("\u2022 1000 queries: ~$0.20")+l.gray(" (20 cents)")),console.log(l.bold(`
|
|
4206
3486
|
\u{1F680} Getting Started:
|
|
4207
|
-
`)),t?(console.log(
|
|
3487
|
+
`)),t?(console.log(l.green("\u2713 You're all set!")),console.log(l.white(' Try: rapidkit ai recommend "user authentication"'))):(console.log(l.white("1. Get OpenAI API key: https://platform.openai.com/api-keys")),console.log(l.white("2. Configure: rapidkit config set-api-key")),console.log(l.white('3. Try: rapidkit ai recommend "user authentication"'))),console.log();}),r.command("generate-embeddings").description("Generate AI embeddings for all modules (one-time setup)").option("--force","Force regeneration even if embeddings exist").action(async()=>{try{let t=et();t||(console.log(l.red(`
|
|
4208
3488
|
\u274C OpenAI API key not configured
|
|
4209
|
-
`)),console.log(
|
|
4210
|
-
`)),console.log(
|
|
4211
|
-
OR set environment variable:`)),console.log(
|
|
4212
|
-
`)),process.exit(1)),
|
|
4213
|
-
`))),process.exit(
|
|
3489
|
+
`)),console.log(l.cyan(`To generate embeddings, you need an OpenAI API key:
|
|
3490
|
+
`)),console.log(l.white("1. Get your key from: https://platform.openai.com/api-keys")),console.log(l.white("2. Configure it: rapidkit config set-api-key")),console.log(l.gray(`
|
|
3491
|
+
OR set environment variable:`)),console.log(l.white(` export OPENAI_API_KEY="sk-proj-..."
|
|
3492
|
+
`)),process.exit(1)),vt(t);let o=await Rt(true);o&&(console.log(l.green("\u2705 Ready to use AI recommendations!")),console.log(l.cyan(`Try: rapidkit ai recommend "authentication"
|
|
3493
|
+
`))),process.exit(o?0:1);}catch(t){a.error("Failed to generate embeddings:",t.message),process.exit(1);}}),r.command("update-embeddings").description("Update existing embeddings with latest modules").action(async()=>{try{let t=et();t||(console.log(l.red(`
|
|
4214
3494
|
\u274C OpenAI API key not configured
|
|
4215
|
-
`)),console.log(
|
|
4216
|
-
`)),process.exit(1)),We(t);let r=await Co();process.exit(r?0:1);}catch(t){a.error("Failed to update embeddings:",t.message),process.exit(1);}});}var Ye=class{constructor(o){this.runCommand=o;}runtime="go";async run(o,t,r){return {exitCode:await this.runCommand(o,t,r)}}async checkPrereqs(){return this.run("go",["version"],process.cwd())}async initProject(o){return this.run("go",["mod","tidy"],o)}async runDev(o){let t=v.join(o,"Makefile");return A.existsSync(t)?this.run("make",["run"],o):this.run("go",["run","./main.go"],o)}async runTest(o){return this.run("go",["test","./..."],o)}async runBuild(o){return this.run("go",["build","./..."],o)}async runStart(o){let t=v.join(o,"server");return A.existsSync(t)?this.run(t,[],o):this.run("go",["run","./main.go"],o)}async doctorHints(o){return ["Install Go from https://go.dev/dl/ if missing.","Run go mod tidy when dependencies are out of sync.","Use make run for hot-reload if Makefile exists."]}};var Qe=class{constructor(o){this.runCommand=o;}runtime="node";async run(o,t,r){return {exitCode:await this.runCommand(o,t,r)}}detectPackageManager(o){return A.existsSync(v.join(o,"pnpm-lock.yaml"))?"pnpm":A.existsSync(v.join(o,"yarn.lock"))?"yarn":"npm"}scriptArgs(o,t){return o==="npm"?["run",t]:["run",t]}async checkPrereqs(){return this.run("node",["--version"],process.cwd())}async initProject(o){let t=this.detectPackageManager(o);return this.run(t,["install"],o)}async runDev(o){let t=this.detectPackageManager(o);return this.run(t,this.scriptArgs(t,"dev"),o)}async runTest(o){let t=this.detectPackageManager(o);return this.run(t,this.scriptArgs(t,"test"),o)}async runBuild(o){let t=this.detectPackageManager(o);return this.run(t,this.scriptArgs(t,"build"),o)}async runStart(o){let t=this.detectPackageManager(o);return this.run(t,this.scriptArgs(t,"start"),o)}async doctorHints(o){return ["Install Node.js LTS and ensure node/npm are on PATH.","Use lockfiles (package-lock.json, pnpm-lock.yaml, yarn.lock) for deterministic installs.","Run install before dev/test/build if dependencies changed."]}};var Xe=class{constructor(o){this.runCore=o;}runtime="python";async run(o,t){return {exitCode:await this.runCore(o,t)}}async checkPrereqs(){return this.run(["doctor","--json"],process.cwd())}async initProject(o){return this.run(["init"],o)}async runDev(o){return this.run(["dev"],o)}async runTest(o){return this.run(["test"],o)}async runBuild(o){return this.run(["build"],o)}async runStart(o){return this.run(["start"],o)}async doctorHints(o){return ["Run rapidkit doctor --workspace for a full workspace scan.","Use rapidkit init after adding or changing modules.","Use workspace launcher ./rapidkit to avoid environment drift."]}};function Q(){return process.env.RAPIDKIT_ENABLE_RUNTIME_ADAPTERS==="1"}function fe(e,o){return e==="go"?new Ye((t,r,i)=>o.runCommandInCwd(t,r,i)):e==="node"?new Qe((t,r,i)=>o.runCommandInCwd(t,r,i)):new Xe((t,r)=>o.runCoreRapidkit(t,{cwd:r}))}var Ze=v.join(qo__default.homedir(),".rapidkit","cache"),Ao=1440*60*1e3,et=class e{static instance;memoryCache=new Map;constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}getCacheKey(o){return createHash("md5").update(o).digest("hex")}getCachePath(o){return v.join(Ze,`${this.getCacheKey(o)}.json`)}async get(o,t="1.0"){let r=this.memoryCache.get(o);if(r&&r.version===t&&Date.now()-r.timestamp<Ao)return a.debug(`Cache hit (memory): ${o}`),r.data;try{let i=this.getCachePath(o),n=await promises.readFile(i,"utf-8"),s=JSON.parse(n);if(s.version===t&&Date.now()-s.timestamp<Ao)return a.debug(`Cache hit (disk): ${o}`),this.memoryCache.set(o,s),s.data;await promises.unlink(i).catch(()=>{});}catch{a.debug(`Cache miss: ${o}`);}return null}async set(o,t,r="1.0"){let i={data:t,timestamp:Date.now(),version:r};this.memoryCache.set(o,i);try{await promises.mkdir(Ze,{recursive:true});let n=this.getCachePath(o);await promises.writeFile(n,JSON.stringify(i),"utf-8"),a.debug(`Cache set: ${o}`);}catch(n){a.debug(`Cache write failed: ${o}`,n);}}async invalidate(o){this.memoryCache.delete(o);try{let t=this.getCachePath(o);await promises.unlink(t),a.debug(`Cache invalidated: ${o}`);}catch{}}async clear(){this.memoryCache.clear();try{let o=await promises.readdir(Ze);await Promise.all(o.map(t=>promises.unlink(v.join(Ze,t)))),a.debug("Cache cleared");}catch{}}};function ie(e){let o=e;for(;;){let t=v.join(o,".rapidkit","project.json");if(A.existsSync(t))try{return JSON.parse(A.readFileSync(t,"utf8"))}catch{return null}let r=v.dirname(o);if(r===o)break;o=r;}return null}function _e(e,o){let t=e?.runtime?.toLowerCase(),r=e?.kit_name?.toLowerCase(),i=A.existsSync(v.join(o,"go.mod"));return t==="go"||(r?.startsWith("gofiber")??false)||(r?.startsWith("gogin")??false)||i}function he(e,o){let t=e?.runtime?.toLowerCase(),r=e?.kit_name?.toLowerCase(),i=A.existsSync(v.join(o,"package.json"));return t==="node"||t==="typescript"||(r?.startsWith("nestjs")??false)||i}function tt(e,o){let t=e?.runtime?.toLowerCase(),r=e?.kit_name?.toLowerCase(),i=A.existsSync(v.join(o,"pyproject.toml")),n=A.existsSync(v.join(o,"requirements.txt"))||A.existsSync(v.join(o,"requirements.in"));return t==="python"||(r?.startsWith("fastapi")??false)||i||n}function kt(e){if(!e||typeof e!="object")return null;let o=e.code;return o==="PYTHON_NOT_FOUND"||o==="BRIDGE_VENV_BOOTSTRAP_FAILED"?o:null}function ei(e){let o=e.trim().toLowerCase();return o?o.startsWith("fastapi")?"fastapi":o.startsWith("nestjs")?"nestjs":null:null}function St(e){let o=e.trim().toLowerCase();return o.startsWith("gofiber")||o==="go"||o==="go.standard"||o==="fiber"}function ot(e){let o=e.trim().toLowerCase();return o.startsWith("gogin")||o==="gin"}function it(e,o){let t=e.indexOf(o);if(t>=0&&t+1<e.length)return e[t+1];let r=e.find(i=>i.startsWith(`${o}=`));if(r)return r.slice(o.length+1)}async function No(e){if(e[0]!=="create"||e[1]!=="project")return 1;let o=e[2],t=e[3];if(!o||!t)return process.stderr.write(`Usage: rapidkit create project gofiber.standard <name> [--output <dir>]
|
|
4217
|
-
|
|
4218
|
-
`),1;await s.ensureDir(i),await gt(i,{project_name:t,module_path:t,skipGit:n});let c=ce(process.cwd());if(c){let{syncWorkspaceProjects:a}=await import('./workspace-LZZGJRGV.js');await a(c,true);}return 0}catch(s){return process.stderr.write(`RapidKit Go/Fiber generator failed: ${s?.message??s}
|
|
4219
|
-
|
|
4220
|
-
`),
|
|
4221
|
-
`),1;
|
|
4222
|
-
`),1
|
|
4223
|
-
|
|
3495
|
+
`)),console.log(l.white(`Set your API key: rapidkit config set-api-key
|
|
3496
|
+
`)),process.exit(1)),vt(t);let o=await jr();process.exit(o?0:1);}catch(t){a.error("Failed to update embeddings:",t.message),process.exit(1);}});}var Ct=class{constructor(r){this.runCommand=r;}runtime="go";async run(r,t,o){return {exitCode:await this.runCommand(r,t,o)}}findWorkspaceRoot(r){let t=r;for(;;){if(S.existsSync(f.join(t,".rapidkit-workspace")))return t;let o=f.dirname(t);if(o===t)break;t=o;}return null}resolveDependencyMode(r){let t=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(t==="shared-runtime-caches"||t==="shared-node-deps"||t==="isolated")return t;let o=this.findWorkspaceRoot(r);if(!o)return "isolated";let i=f.join(o,".rapidkit","policies.yml");if(!S.existsSync(i))return "isolated";try{let s=S.readFileSync(i,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*$/m)?.[1]?.toLowerCase();if(s==="shared-runtime-caches"||s==="shared-node-deps"||s==="isolated")return s}catch{}return "isolated"}withGoCacheEnv(r,t){let o=this.resolveDependencyMode(r),i=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(r),n=o==="shared-runtime-caches"?f.join(i||r,".rapidkit","cache","go"):f.join(r,".rapidkit","cache","go"),a=process.env.GOMODCACHE,s=process.env.GOCACHE;return process.env.GOMODCACHE=f.join(n,"mod"),process.env.GOCACHE=f.join(n,"build"),t().finally(()=>{typeof a>"u"?delete process.env.GOMODCACHE:process.env.GOMODCACHE=a,typeof s>"u"?delete process.env.GOCACHE:process.env.GOCACHE=s;})}async checkPrereqs(){return this.run("go",["version"],process.cwd())}async warmSetupCache(r){return this.withGoCacheEnv(r,async()=>{try{return process.env.GOMODCACHE&&S.mkdirSync(process.env.GOMODCACHE,{recursive:true}),process.env.GOCACHE&&S.mkdirSync(process.env.GOCACHE,{recursive:true}),{exitCode:0}}catch{return {exitCode:1,message:"Failed to prepare Go cache directories"}}})}async initProject(r){return this.withGoCacheEnv(r,()=>this.run("go",["mod","tidy"],r))}async runDev(r){return this.withGoCacheEnv(r,()=>{let t=f.join(r,"Makefile");return S.existsSync(t)?this.run("make",["run"],r):this.run("go",["run","./main.go"],r)})}async runTest(r){return this.withGoCacheEnv(r,()=>this.run("go",["test","./..."],r))}async runBuild(r){return this.withGoCacheEnv(r,()=>this.run("go",["build","./..."],r))}async runStart(r){return this.withGoCacheEnv(r,()=>{let o=(process.platform==="win32"?[f.join(r,"server.exe"),f.join(r,"server")]:[f.join(r,"server")]).find(i=>S.existsSync(i));return o?this.run(o,[],r):this.run("go",["run","./main.go"],r)})}async doctorHints(r){return ["Install Go from https://go.dev/dl/ if missing.","Run go mod tidy when dependencies are out of sync.","Use make run for hot-reload if Makefile exists."]}};var St=class{constructor(r){this.runCommand=r;}runtime="node";async run(r,t,o){return {exitCode:await this.runCommand(r,t,o)}}findWorkspaceRoot(r){let t=r;for(;;){if(S.existsSync(f.join(t,".rapidkit-workspace")))return t;let o=f.dirname(t);if(o===t)break;t=o;}return null}resolveDependencyMode(r){let t=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(t==="shared-runtime-caches"||t==="shared-node-deps"||t==="isolated")return t;let o=this.findWorkspaceRoot(r);if(!o)return "isolated";let i=f.join(o,".rapidkit","policies.yml");if(!S.existsSync(i))return "isolated";try{let s=S.readFileSync(i,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*$/m)?.[1]?.toLowerCase();if(s==="shared-runtime-caches"||s==="shared-node-deps"||s==="isolated")return s}catch{}return "isolated"}withDependencyEnv(r,t,o){let i=this.resolveDependencyMode(r),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(r),a=i==="isolated"?f.join(r,".rapidkit","cache","node"):f.join(n||r,".rapidkit","cache","node"),s=process.env.npm_config_cache,c=process.env.npm_config_store_dir;return t==="pnpm"?(process.env.npm_config_store_dir=f.join(a,"pnpm-store"),process.env.npm_config_cache=f.join(a,"pnpm-cache")):t==="yarn"?process.env.npm_config_cache=f.join(a,"yarn-cache"):process.env.npm_config_cache=f.join(a,"npm-cache"),o().finally(()=>{typeof s>"u"?delete process.env.npm_config_cache:process.env.npm_config_cache=s,typeof c>"u"?delete process.env.npm_config_store_dir:process.env.npm_config_store_dir=c;})}detectPackageManager(r){return S.existsSync(f.join(r,"pnpm-lock.yaml"))?"pnpm":S.existsSync(f.join(r,"yarn.lock"))?"yarn":"npm"}scriptArgs(r,t){return r==="npm"?["run",t]:["run",t]}async checkPrereqs(){return this.run("node",["--version"],process.cwd())}async warmSetupCache(r){let t=this.detectPackageManager(r);return this.withDependencyEnv(r,t,async()=>{try{return process.env.npm_config_cache&&S.mkdirSync(process.env.npm_config_cache,{recursive:true}),t==="pnpm"&&process.env.npm_config_store_dir&&S.mkdirSync(process.env.npm_config_store_dir,{recursive:true}),{exitCode:0}}catch{return {exitCode:1,message:"Failed to prepare Node cache directories"}}})}async initProject(r){let t=this.detectPackageManager(r),o=this.resolveDependencyMode(r),i=o==="shared-runtime-caches"||o==="shared-node-deps"?["install","--prefer-offline"]:["install"];return this.withDependencyEnv(r,t,()=>this.run(t,i,r))}async runDev(r){let t=this.detectPackageManager(r);return this.withDependencyEnv(r,t,()=>this.run(t,this.scriptArgs(t,"dev"),r))}async runTest(r){let t=this.detectPackageManager(r);return this.withDependencyEnv(r,t,()=>this.run(t,this.scriptArgs(t,"test"),r))}async runBuild(r){let t=this.detectPackageManager(r);return this.withDependencyEnv(r,t,()=>this.run(t,this.scriptArgs(t,"build"),r))}async runStart(r){let t=this.detectPackageManager(r);return this.withDependencyEnv(r,t,()=>this.run(t,this.scriptArgs(t,"start"),r))}async doctorHints(r){return ["Install Node.js LTS and ensure node/npm are on PATH.","Use lockfiles (package-lock.json, pnpm-lock.yaml, yarn.lock) for deterministic installs.","Run install before dev/test/build if dependencies changed."]}};var _t=class{constructor(r){this.runCore=r;}runtime="python";async run(r,t){return {exitCode:await this.withPythonCacheEnv(t,()=>this.runCore(r,t))}}findWorkspaceRoot(r){let t=r;for(;;){if(S.existsSync(f.join(t,".rapidkit-workspace")))return t;let o=f.dirname(t);if(o===t)break;t=o;}return null}resolveDependencyMode(r){let t=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(t==="shared-runtime-caches"||t==="shared-node-deps"||t==="isolated")return t;let o=this.findWorkspaceRoot(r);if(!o)return "isolated";let i=f.join(o,".rapidkit","policies.yml");if(!S.existsSync(i))return "isolated";try{let s=S.readFileSync(i,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*$/m)?.[1]?.toLowerCase();if(s==="shared-runtime-caches"||s==="shared-node-deps"||s==="isolated")return s}catch{}return "isolated"}withPythonCacheEnv(r,t){let o=this.resolveDependencyMode(r),i=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(r),n=o==="shared-runtime-caches"?f.join(i||r,".rapidkit","cache","python"):f.join(r,".rapidkit","cache","python"),a=process.env.PIP_CACHE_DIR,s=process.env.POETRY_CACHE_DIR;return process.env.PIP_CACHE_DIR=f.join(n,"pip"),process.env.POETRY_CACHE_DIR=f.join(n,"poetry"),t().finally(()=>{typeof a>"u"?delete process.env.PIP_CACHE_DIR:process.env.PIP_CACHE_DIR=a,typeof s>"u"?delete process.env.POETRY_CACHE_DIR:process.env.POETRY_CACHE_DIR=s;})}async checkPrereqs(){let r=process.cwd(),t=await this.run(["doctor","check"],r);return t.exitCode===0?t:this.run(["doctor"],r)}async initProject(r){return this.run(["init"],r)}async runDev(r){return this.run(["dev"],r)}async runTest(r){return this.run(["test"],r)}async runBuild(r){return this.run(["build"],r)}async runStart(r){return this.run(["start"],r)}async doctorHints(r){return ['Run "npx rapidkit doctor workspace" for a full workspace scan.','Use "npx rapidkit init" after adding or changing modules.','Use workspace launcher "./rapidkit" to avoid environment drift.']}};function sn(){let e={...process.env},r=e.PATH||"";if(r){let t=r.split(f.delimiter).filter(o=>!o.replace(/\\/g,"/").includes("/.pyenv/shims")).join(f.delimiter);e.PATH=t;}return e.PYENV_VERSION="system",e.POETRY_PYTHON=e.POETRY_PYTHON||(process.platform==="win32"?"python":"python3"),typeof e.RAPIDKIT_SKIP_LOCK_SYNC>"u"&&(e.RAPIDKIT_SKIP_LOCK_SYNC="1"),e}function Me(e,r){return e==="go"?new Ct((t,o,i)=>r.runCommandInCwd(t,o,i)):e==="node"?new St((t,o,i)=>r.runCommandInCwd(t,o,i)):new _t((t,o)=>r.runCoreRapidkit(t,{cwd:o,env:sn()}))}var xt=f.join(qi.homedir(),".rapidkit","cache"),Mr=1440*60*1e3,Pt=class e{static instance;memoryCache=new Map;constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}getCacheKey(r){return createHash("md5").update(r).digest("hex")}getCachePath(r){return f.join(xt,`${this.getCacheKey(r)}.json`)}async get(r,t="1.0"){let o=this.memoryCache.get(r);if(o&&o.version===t&&Date.now()-o.timestamp<Mr)return a.debug(`Cache hit (memory): ${r}`),o.data;try{let i=this.getCachePath(r),n=await promises.readFile(i,"utf-8"),a$1=JSON.parse(n);if(a$1.version===t&&Date.now()-a$1.timestamp<Mr)return a.debug(`Cache hit (disk): ${r}`),this.memoryCache.set(r,a$1),a$1.data;await promises.unlink(i).catch(()=>{});}catch{a.debug(`Cache miss: ${r}`);}return null}async set(r,t,o="1.0"){let i={data:t,timestamp:Date.now(),version:o};this.memoryCache.set(r,i);try{await promises.mkdir(xt,{recursive:true});let n=this.getCachePath(r);await promises.writeFile(n,JSON.stringify(i),"utf-8"),a.debug(`Cache set: ${r}`);}catch(n){a.debug(`Cache write failed: ${r}`,n);}}async invalidate(r){this.memoryCache.delete(r);try{let t=this.getCachePath(r);await promises.unlink(t),a.debug(`Cache invalidated: ${r}`);}catch{}}async clear(){this.memoryCache.clear();try{let r=await promises.readdir(xt);await Promise.all(r.map(t=>promises.unlink(f.join(xt,t)))),a.debug("Cache cleared");}catch{}}};function Te(e){let r=e;for(;;){let t=f.join(r,".rapidkit","project.json");if(S.existsSync(t))try{return JSON.parse(S.readFileSync(t,"utf8"))}catch{return null}let o=f.dirname(r);if(o===r)break;r=o;}return null}function ge(e,r){let t=e?.runtime?.toLowerCase(),o=e?.kit_name?.toLowerCase(),i=S.existsSync(f.join(r,"go.mod"));return t==="go"||(o?.startsWith("gofiber")??false)||(o?.startsWith("gogin")??false)||i}function me(e,r){let t=e?.runtime?.toLowerCase(),o=e?.kit_name?.toLowerCase(),i=S.existsSync(f.join(r,"package.json"));return t==="node"||t==="typescript"||(o?.startsWith("nestjs")??false)||i}function fe(e,r){let t=e?.runtime?.toLowerCase(),o=e?.kit_name?.toLowerCase(),i=S.existsSync(f.join(r,"pyproject.toml")),n=S.existsSync(f.join(r,"requirements.txt"))||S.existsSync(f.join(r,"requirements.in"));return t==="python"||(o?.startsWith("fastapi")??false)||i||n}async function un(e){let r=await promises.readFile(e);return createHash("sha256").update(r).digest("hex")}async function Lr(e,r){await b.outputFile(e,`${JSON.stringify(r,null,2)}
|
|
3497
|
+
`,"utf-8");}function ve(e,r){return f.isAbsolute(r)?r:f.join(e,r)}function gn(e,r){if(e.target)return e.target;if(e.source)return f.basename(e.source);if(e.url)try{let t=new URL(e.url).pathname,o=f.basename(t);if(o&&o!=="/")return o}catch{}return `${r}.artifact`}async function mn(e){let r=f.join(e,".rapidkit","trusted-sources.lock"),t=new Set(["localhost","127.0.0.1"]);if(!await b.pathExists(r))return t;try{let i=(await promises.readFile(r,"utf-8")).split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#"));for(let n of i)t.add(n.toLowerCase());}catch{}return t}async function fn(e,r,t){await b.ensureDir(f.dirname(r)),await new Promise((o,i)=>{let a=(e.startsWith("https://")?Ur:Kr).get(e,s=>{if(!s.statusCode||s.statusCode<200||s.statusCode>=300){i(new Error(`HTTP ${s.statusCode||"unknown"}`)),s.resume();return}let c=createWriteStream(r);s.pipe(c),c.on("finish",()=>{c.close(),o();}),c.on("error",p=>{i(p);});});a.setTimeout(t,()=>{a.destroy(new Error(`Request timeout after ${t}ms`));}),a.on("error",s=>{i(s);});});}async function hn(e,r,t,o,i){let n=new URL(e),a=JSON.stringify(r),s=n.protocol==="https:"?Ur:Kr;await new Promise((c,p)=>{let d=s.request({method:"POST",hostname:n.hostname,port:n.port||(n.protocol==="https:"?443:80),path:`${n.pathname}${n.search}`,headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(a),...o?{Authorization:`Bearer ${o}`}:{},...i||{}}},m=>{if(!m.statusCode||m.statusCode<200||m.statusCode>=300){p(new Error(`HTTP ${m.statusCode||"unknown"}`)),m.resume();return}m.resume(),c();});d.setTimeout(t,()=>{d.destroy(new Error(`Request timeout after ${t}ms`));}),d.on("error",m=>{p(m);}),d.write(a),d.end();});}function qr(e){return new Promise(r=>setTimeout(r,e))}async function yn(e,r,t,o){let i=ve(e,r||".rapidkit/reports/evidence-export-dead-letter.ndjson");return await b.ensureDir(f.dirname(i)),await promises.appendFile(i,`${JSON.stringify({timestamp:new Date().toISOString(),reason:o,payload:t})}
|
|
3498
|
+
`,"utf-8"),i}function wn(e,r){if(!r?.enabled)return {headers:{}};let t=process.env[r.hmacKeyEnv];if(!t)return {headers:{},error:`Evidence signing key env is missing: ${r.hmacKeyEnv}`};let o=(r.algorithm||"sha256").toLowerCase(),i=r.headerName||"x-rapidkit-evidence-signature",n=createHmac(o,t).update(JSON.stringify(e)).digest("hex");return {headers:{[i]:n,"x-rapidkit-evidence-signature-alg":o}}}async function vn(e,r,t){let o=(t.algorithm||"sha256").toLowerCase(),i=ve(e,t.publicKeyPath);if(!await b.pathExists(i))return {verified:false,algorithm:o,publicKeyPath:i,publicKeyFingerprint:"",signature:t.signature,message:`Public key not found: ${i}`};try{let n=await promises.readFile(i,"utf-8"),a=await promises.readFile(r),s=createVerify(o);s.update(a),s.end();let c=Buffer.from(t.signature,"base64"),p=s.verify(n,c),d=createHash("sha256").update(n).digest("hex");return {verified:p,algorithm:o,publicKeyPath:i,publicKeyFingerprint:d,signature:t.signature,message:p?"Attestation verified.":"Attestation signature verification failed."}}catch(n){return {verified:false,algorithm:o,publicKeyPath:i,publicKeyFingerprint:"",signature:t.signature,message:`Attestation verification error: ${n.message}`}}}async function kn(e,r,t,o){let i=process.env.RAPIDKIT_SIGSTORE_MOCK;if(i==="success")return {verified:true,tlogVerified:o.requireTransparencyLog,message:"Sigstore verification passed (mock).",identity:t.identity||null,issuer:t.issuer||null,rekorUrl:t.rekorUrl||null,bundlePath:t.bundlePath||null,certificatePath:t.certificatePath||null,signaturePath:t.signaturePath||null};if(i==="fail")return {verified:false,tlogVerified:false,message:"Sigstore verification failed (mock).",identity:t.identity||null,issuer:t.issuer||null,rekorUrl:t.rekorUrl||null,bundlePath:t.bundlePath||null,certificatePath:t.certificatePath||null,signaturePath:t.signaturePath||null};let n=t.signaturePath?ve(e,t.signaturePath):null;if(!n||!await b.pathExists(n))return {verified:false,tlogVerified:false,message:"Sigstore signaturePath is missing or not found.",identity:t.identity||null,issuer:t.issuer||null,rekorUrl:t.rekorUrl||null,bundlePath:t.bundlePath||null,certificatePath:t.certificatePath||null,signaturePath:n};let a=["verify-blob",r,"--signature",n],s=t.certificatePath?ve(e,t.certificatePath):null;s&&a.push("--certificate",s);let c=t.bundlePath?ve(e,t.bundlePath):null;c&&a.push("--bundle",c);let p=t.keyPath?ve(e,t.keyPath):null;p&&a.push("--key",p),t.identity&&a.push("--certificate-identity",t.identity),t.issuer&&a.push("--certificate-oidc-issuer",t.issuer),t.rekorUrl&&a.push("--rekor-url",t.rekorUrl),o.requireTransparencyLog||a.push("--insecure-ignore-tlog");try{let d=await execa("cosign",a,{reject:false});return d.exitCode===0?{verified:true,tlogVerified:o.requireTransparencyLog,message:"Sigstore verification passed.",identity:t.identity||null,issuer:t.issuer||null,rekorUrl:t.rekorUrl||null,bundlePath:c,certificatePath:s,signaturePath:n}:{verified:false,tlogVerified:false,message:`Sigstore verification failed: ${d.stderr||d.stdout||"unknown error"}`,identity:t.identity||null,issuer:t.issuer||null,rekorUrl:t.rekorUrl||null,bundlePath:c,certificatePath:s,signaturePath:n}}catch(d){return {verified:false,tlogVerified:false,message:`Sigstore verification error: ${d.message}`,identity:t.identity||null,issuer:t.issuer||null,rekorUrl:t.rekorUrl||null,bundlePath:c,certificatePath:s,signaturePath:n}}}async function bn(e,r){let t=r.algorithm||"sha256",o=ve(e,r.policyPath),i=ve(e,r.signaturePath),n=ve(e,r.publicKeyPath);if(!await b.pathExists(o))return {verified:false,message:`Governance policy bundle not found: ${o}`,policies:null};if(!await b.pathExists(i))return {verified:false,message:`Governance policy signature not found: ${i}`,policies:null};if(!await b.pathExists(n))return {verified:false,message:`Governance policy public key not found: ${n}`,policies:null};try{let a=await promises.readFile(o,"utf-8"),s=(await promises.readFile(i,"utf-8")).trim(),c=await promises.readFile(n,"utf-8"),p=createVerify(t);return p.update(a),p.end(),p.verify(c,Buffer.from(s,"base64"))?{verified:true,message:"Governance policy bundle verified.",policies:JSON.parse(a).policies||{}}:{verified:false,message:"Governance policy bundle signature verification failed.",policies:null}}catch(a){return {verified:false,message:`Governance policy bundle verification error: ${a.message}`,policies:null}}}async function Ht(e,r){let t=[],o={syncedArtifacts:0,verifiedArtifacts:0,rotatedFiles:0,lockWritten:false,governanceBundleVerified:false,transparencyEvidenceWritten:false,transparencyEvidenceRecords:0,evidenceExported:false,evidenceExportTarget:null},i=f.join(e,".rapidkit"),n=f.join(i,"mirror-config.json"),a=f.join(i,"mirror.lock"),s=f.join(i,"mirror","artifacts"),c=f.join(i,"reports"),p=await mn(e);if(!await b.pathExists(n))return t.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror lifecycle skipped: .rapidkit/mirror-config.json not found."}),{checks:t,details:o};let d={};try{d=JSON.parse(await promises.readFile(n,"utf-8"));}catch{return t.push({id:"mirror.lifecycle.config",status:"failed",message:"Mirror lifecycle failed: invalid JSON in mirror-config.json."}),{checks:t,details:o}}if(!(r.forceRun===true||r.ciMode||r.offlineMode||d.mode==="offline-only"))return t.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror lifecycle skipped: not in ci/offline mode."}),{checks:t,details:o};await b.ensureDir(s);let h=Math.max(0,d.prefetch?.retries??2),w=Math.max(0,d.prefetch?.backoffMs??250),g=Math.max(1e3,d.prefetch?.timeoutMs??15e3),u=d.security?.requireAttestation===true,C=d.security?.requireSigstore===true,I=d.security?.requireTransparencyLog===true,A=d.security?.requireSignedGovernance===true,_=d.security?.evidenceExport,N=(process.env.RAPIDKIT_ENV||d.security?.governance?.environment||"dev").toLowerCase(),K=d.security?.governance?.policies||{};if(d.security?.governanceBundle){let B=await bn(e,d.security.governanceBundle);if(t.push({id:"governance.bundle.verify",status:B.verified?"passed":"failed",message:B.message}),B.verified&&B.policies)K=B.policies,o.governanceBundleVerified=true;else if(A)return {checks:t,details:o}}let D=K[N],q=I||D?.requireTransparencyLog===true,ke=[],Ye=Array.isArray(d.artifacts)?d.artifacts:[],he=[];for(let B=0;B<Ye.length;B+=1){let G=Ye[B],k=G.id||`artifact-${B+1}`,oe=G.source?ve(e,G.source):null,ie=gn(G,k),F=f.join(s,ie),te=false,ae={sourceType:"path",source:oe||G.url||"unknown",host:null,fetchedAt:new Date().toISOString(),attempts:1,trusted:true};if(oe&&await b.pathExists(oe))await b.ensureDir(f.dirname(F)),await b.copyFile(oe,F),o.syncedArtifacts+=1,te=true,ae={sourceType:"path",source:oe,host:null,fetchedAt:new Date().toISOString(),attempts:1,trusted:true},t.push({id:`mirror.sync.${k}`,status:"passed",message:`Mirrored artifact ${k} from source path.`});else if(G.url){let U="";try{U=new URL(G.url).hostname.toLowerCase();}catch{t.push({id:`mirror.prefetch.${k}`,status:"failed",message:`Invalid URL for ${k}: ${G.url}`});continue}if(!(process.env.RAPIDKIT_TRUSTED_SOURCES==="1"||p.has(U))){t.push({id:`mirror.prefetch.trust.${k}`,status:"failed",message:`Untrusted mirror host for ${k}: ${U}. Add host to .rapidkit/trusted-sources.lock or set RAPIDKIT_TRUSTED_SOURCES=1.`});continue}if(r.offlineMode&&(await b.pathExists(F)?(te=true,ae={sourceType:"url",source:G.url,host:U,fetchedAt:new Date().toISOString(),attempts:0,trusted:true},t.push({id:`mirror.prefetch.${k}`,status:"passed",message:`Offline mode reused existing mirrored artifact ${k}.`})):t.push({id:`mirror.prefetch.${k}`,status:"failed",message:`Offline mode cannot prefetch remote artifact ${k} without an existing mirrored copy.`}),!te))continue;if(!te){let re=null,Ee=0;for(let _e=1;_e<=h+1;_e+=1){Ee=_e;try{await fn(G.url,F,g),o.syncedArtifacts+=1,te=true,ae={sourceType:"url",source:G.url,host:U,fetchedAt:new Date().toISOString(),attempts:Ee,trusted:true},t.push({id:`mirror.prefetch.${k}`,status:"passed",message:Ee>1?`Prefetched artifact ${k} from ${U} after ${Ee} attempts.`:`Prefetched artifact ${k} from ${U}.`});break}catch(nt){if(re=nt,_e<=h){await qr(w*_e);continue}}}if(!te){t.push({id:`mirror.prefetch.${k}`,status:"failed",message:`Failed to prefetch ${k} after ${h+1} attempt(s): ${re?.message||"unknown error"}`});continue}}if(!te){t.push({id:`mirror.prefetch.${k}`,status:"failed",message:`Failed to prefetch ${k}.`});continue}}if(!te){G.required||r.offlineMode?t.push({id:`mirror.sync.${k}`,status:"failed",message:`Mirror source missing for ${k}${oe?`: ${oe}`:""}`}):t.push({id:`mirror.sync.${k}`,status:"skipped",message:`Mirror source not found for optional artifact ${k}.`});continue}let x=await un(F);if(G.sha256&&G.sha256.toLowerCase()!==x.toLowerCase()){t.push({id:`mirror.verify.${k}`,status:"failed",message:`Checksum mismatch for ${k}.`});continue}o.verifiedArtifacts+=1,t.push({id:`mirror.verify.${k}`,status:"passed",message:`Checksum verified for ${k}.`});let P=G.attestation?await vn(e,F,G.attestation):null;if(G.attestation){if(t.push({id:`mirror.attest.${k}`,status:P?.verified?"passed":"failed",message:P?.message||"Attestation verification failed."}),!P?.verified)continue}else if(u){t.push({id:`mirror.attest.${k}`,status:"failed",message:`Attestation is required but missing for ${k}.`});continue}else t.push({id:`mirror.attest.${k}`,status:"skipped",message:`No attestation provided for ${k}.`});let $=G.attestation?.sigstore,T=$?await kn(e,F,$,{requireTransparencyLog:q}):null;if($){if(t.push({id:`mirror.sigstore.${k}`,status:T?.verified?"passed":"failed",message:T?.message||"Sigstore verification failed."}),ke.push({artifactId:k,verified:!!T?.verified,tlogVerified:!!T?.tlogVerified,identity:T?.identity||null,issuer:T?.issuer||null,rekorUrl:T?.rekorUrl||null,timestamp:new Date().toISOString(),environment:N}),!T?.verified)continue}else if(C){t.push({id:`mirror.sigstore.${k}`,status:"failed",message:`Sigstore attestation is required but missing for ${k}.`});continue}else t.push({id:`mirror.sigstore.${k}`,status:"skipped",message:`No Sigstore attestation provided for ${k}.`});if($&&T?.verified&&D){let U=D.allowedIdentities||[];if(U.length>0){let re=!!T.identity&&U.includes(T.identity);if(t.push({id:`mirror.sigstore.policy.identity.${k}`,status:re?"passed":"failed",message:re?`Sigstore identity policy passed for ${k} in ${N}.`:`Sigstore identity policy failed for ${k} in ${N}.`}),!re)continue}let Pe=D.allowedIssuers||[];if(Pe.length>0){let re=!!T.issuer&&Pe.includes(T.issuer);if(t.push({id:`mirror.sigstore.policy.issuer.${k}`,status:re?"passed":"failed",message:re?`Sigstore issuer policy passed for ${k} in ${N}.`:`Sigstore issuer policy failed for ${k} in ${N}.`}),!re)continue}let Se=D.allowedRekorUrls||[];if(Se.length>0){let re=!!T.rekorUrl&&Se.includes(T.rekorUrl);if(t.push({id:`mirror.sigstore.policy.rekor.${k}`,status:re?"passed":"failed",message:re?`Sigstore Rekor policy passed for ${k} in ${N}.`:`Sigstore Rekor policy failed for ${k} in ${N}.`}),!re)continue}}else D&&t.push({id:`mirror.sigstore.policy.${k}`,status:"skipped",message:`Sigstore governance policy configured for ${N} but no verified Sigstore attestation for ${k}.`});let de=await promises.stat(F);he.push({id:k,path:f.relative(e,F),sha256:x,size:de.size,provenance:ae,attestation:{detached:{provided:!!G.attestation,verified:P?.verified||false,algorithm:P?.algorithm||null,publicKeyPath:P?.publicKeyPath||null,publicKeyFingerprint:P?.publicKeyFingerprint||null,signature:P?.signature||null,verifiedAt:P?.verified?new Date().toISOString():null},sigstore:{provided:!!$,verified:T?.verified||false,tlogVerified:T?.tlogVerified||false,identity:T?.identity||null,issuer:T?.issuer||null,rekorUrl:T?.rekorUrl||null,bundlePath:T?.bundlePath||null,certificatePath:T?.certificatePath||null,signaturePath:T?.signaturePath||null,verifiedAt:T?.verified?new Date().toISOString():null}}});}let pe=d.retention?.keepLast;if(typeof pe=="number"&&pe>0){let G=(await promises.readdir(s,{withFileTypes:true})).filter(k=>k.isFile()).map(k=>f.join(s,k.name));if(G.length>pe){let k=await Promise.all(G.map(async ie=>({filePath:ie,stat:await promises.stat(ie)})));k.sort((ie,F)=>F.stat.mtimeMs-ie.stat.mtimeMs);let oe=k.slice(pe);for(let ie of oe)await promises.unlink(ie.filePath),o.rotatedFiles+=1;}}t.push({id:"mirror.rotate",status:"passed",message:o.rotatedFiles>0?`Mirror retention rotation removed ${o.rotatedFiles} file(s).`:"Mirror retention rotation completed with no removals."});let Ke={schemaVersion:"1.0",generatedAt:new Date().toISOString(),mode:d.mode||null,environment:N,artifacts:he};if(await promises.writeFile(a,`${JSON.stringify(Ke,null,2)}
|
|
3499
|
+
`,"utf-8"),o.lockWritten=true,t.push({id:"mirror.lock.write",status:"passed",message:`Mirror lock updated at ${f.relative(e,a)}.`}),o.transparencyEvidenceRecords=ke.length,ke.length>0){let B={schemaVersion:"1.0",generatedAt:new Date().toISOString(),environment:N,records:ke},G=new Date().toISOString().replace(/[:.]/g,"-"),k=f.join(c,`transparency-evidence-${G}.json`),oe=f.join(c,"transparency-evidence.latest.json");if(await b.ensureDir(c),await Lr(k,B),await Lr(oe,B),o.transparencyEvidenceWritten=true,t.push({id:"sigstore.evidence.write",status:"passed",message:`Transparency evidence written to ${f.relative(e,oe)}.`}),_?.enabled){let ie=Math.max(1e3,_.timeoutMs??1e4);if(_.target==="file")if(!_.filePath)t.push({id:"sigstore.evidence.export.file",status:"failed",message:"Evidence export target=file requires security.evidenceExport.filePath."});else try{let F=ve(e,_.filePath);await b.ensureDir(f.dirname(F)),await promises.appendFile(F,`${JSON.stringify(B)}
|
|
3500
|
+
`,"utf-8"),o.evidenceExported=true,o.evidenceExportTarget=F,t.push({id:"sigstore.evidence.export.file",status:"passed",message:`Transparency evidence exported to file sink ${F}.`});}catch(F){t.push({id:"sigstore.evidence.export.file",status:"failed",message:`Evidence file export failed: ${F.message}`});}else if(_.target==="http")if(!_.endpoint)t.push({id:"sigstore.evidence.export.http",status:"failed",message:"Evidence export target=http requires security.evidenceExport.endpoint."});else {let F=Math.max(0,_.retries??0),te=Math.max(0,_.backoffMs??500),ae=wn(B,_.signing);ae.error&&t.push({id:"sigstore.evidence.export.http",status:"failed",message:ae.error});try{let x=_.authTokenEnv?process.env[_.authTokenEnv]:void 0,P=false,$=null;for(let T=1;T<=F+1;T+=1)try{if(ae.error)throw new Error(ae.error);await hn(_.endpoint,B,ie,x,ae.headers),o.evidenceExported=true,o.evidenceExportTarget=_.endpoint,t.push({id:"sigstore.evidence.export.http",status:"passed",message:T>1?`Transparency evidence exported to HTTP endpoint ${_.endpoint} after ${T} attempts.`:`Transparency evidence exported to HTTP endpoint ${_.endpoint}.`}),P=true;break}catch(de){$=de,T<=F&&await qr(te*T);}if(!P)throw $||new Error("unknown evidence export error")}catch(x){let P=`Evidence HTTP export failed: ${x.message}`;t.push({id:"sigstore.evidence.export.http",status:"failed",message:P});try{let $=await yn(e,_.deadLetterPath,B,P);t.push({id:"sigstore.evidence.export.deadletter",status:"passed",message:`Evidence export failure persisted to dead-letter sink ${$}.`});}catch($){t.push({id:"sigstore.evidence.export.deadletter",status:"failed",message:`Evidence dead-letter write failed: ${$.message}`});}}}if(_.failOnError&&t.some(te=>te.status==="failed"&&(te.id==="sigstore.evidence.export.file"||te.id==="sigstore.evidence.export.http")))return {checks:t,details:o}}else t.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export not configured (security.evidenceExport.enabled=false)."});}else t.push({id:"sigstore.evidence.write",status:"skipped",message:"No Sigstore records available for transparency evidence output."}),t.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export skipped because no transparency evidence records exist."});return {checks:t,details:o}}function Kt(e){if(!e||typeof e!="object")return null;let r=e.code;return r==="PYTHON_NOT_FOUND"||r==="BRIDGE_VENV_BOOTSTRAP_FAILED"?r:null}function Cn(e){let r=e.trim().toLowerCase();return r?r.startsWith("fastapi")?"fastapi":r.startsWith("nestjs")?"nestjs":null:null}function It(e){let r=e.trim().toLowerCase();return r.startsWith("gofiber")||r==="go"||r==="go.standard"||r==="fiber"}function ot(e){let r=e.trim().toLowerCase();return r.startsWith("gogin")||r==="gin"}function it(e,r){let t=e.indexOf(r);if(t>=0&&t+1<e.length)return e[t+1];let o=e.find(i=>i.startsWith(`${r}=`));if(o)return o.slice(r.length+1)}function Zr(){return process.platform==="win32"?["python","py"]:["python3","python"]}function Vr(){let e={...process.env},r=e.PATH||"";return r&&(e.PATH=r.split(f.delimiter).filter(t=>!t.replace(/\\/g,"/").includes("/.pyenv/shims")).join(f.delimiter)),e.PYENV_VERSION="system",e.POETRY_PYTHON||(e.POETRY_PYTHON=process.platform==="win32"?"python":"python3"),e.RAPIDKIT_SKIP_LOCK_SYNC||(e.RAPIDKIT_SKIP_LOCK_SYNC="1"),e.POETRY_KEYRING_ENABLED||(e.POETRY_KEYRING_ENABLED="false"),e.PYTHON_KEYRING_BACKEND||(e.PYTHON_KEYRING_BACKEND="keyring.backends.null.Keyring"),e.POETRY_NO_INTERACTION||(e.POETRY_NO_INTERACTION="1"),e}function Sn(e){return process.platform==="win32"?f.join(e,".venv","Scripts","python.exe"):f.join(e,".venv","bin","python")}async function _n(e){for(let r of Zr())if(await le(r,r==="py"?["-3","-m","venv",".venv"]:["-m","venv",".venv"],e)===0)return 0;return 1}async function Br(e){if(e[0]!=="create"||e[1]!=="project")return 1;let r=e[2],t=e[3];if(!r||!t)return process.stderr.write(`Usage: rapidkit create project gofiber.standard <name> [--output <dir>]
|
|
3501
|
+
`),1;let o=it(e,"--output")||process.cwd(),i=f.resolve(o,t),n=e.includes("--skip-git")||e.includes("--no-git");try{let{default:a}=await import('fs-extra');if(await a.ensureDir(f.dirname(i)),await a.pathExists(i))return process.stderr.write(`\u274C Directory "${i}" already exists
|
|
3502
|
+
`),1;await a.ensureDir(i),await Nt(i,{project_name:t,module_path:t,skipGit:n});let s=J(process.cwd());if(s){let{syncWorkspaceProjects:c}=await import('./workspace-6SADFTND.js');await c(s,true);}return 0}catch(a){return process.stderr.write(`RapidKit Go/Fiber generator failed: ${a?.message??a}
|
|
3503
|
+
`),1}}async function Jr(e){if(e[0]!=="create"||e[1]!=="project")return 1;let r=e[2],t=e[3];if(!r||!t)return process.stderr.write(`Usage: rapidkit create project gogin.standard <name> [--output <dir>]
|
|
3504
|
+
`),1;let o=it(e,"--output")||process.cwd(),i=f.resolve(o,t),n=e.includes("--skip-git")||e.includes("--no-git");try{let{default:a}=await import('fs-extra');if(await a.ensureDir(f.dirname(i)),await a.pathExists(i))return process.stderr.write(`\u274C Directory "${i}" already exists
|
|
3505
|
+
`),1;await a.ensureDir(i),await jt(i,{project_name:t,module_path:t,skipGit:n});let s=J(process.cwd());if(s){let{syncWorkspaceProjects:c}=await import('./workspace-6SADFTND.js');await c(s,true);}return 0}catch(a){return process.stderr.write(`RapidKit Go/Gin generator failed: ${a?.message??a}
|
|
3506
|
+
`),1}}async function Ut(e,r){if(e.includes("--json"))return process.stderr.write("RapidKit (npm) offline fallback does not support --json for `create` commands.\nInstall Python 3.10+ and retry the same command.\n"),1;if(e[0]!=="create")return 1;if(e[1]!=="project")return process.stderr.write(`RapidKit (npm) could not run the Python core engine for \`create\`.
|
|
3507
|
+
Reason: ${r}.
|
|
4224
3508
|
Install Python 3.10+ to use the interactive wizard and full kit catalog.
|
|
4225
3509
|
`),1;let i=e[2],n=e[3];if(!i||!n)return process.stderr.write(`Usage: rapidkit create project <kit> <name> [--output <dir>]
|
|
4226
3510
|
Tip: offline fallback supports only fastapi* and nestjs* kits.
|
|
4227
|
-
`),1;let
|
|
4228
|
-
Reason: ${
|
|
3511
|
+
`),1;let a=Cn(i);if(!a)return process.stderr.write(`RapidKit (npm) could not run the Python core engine to create this kit.
|
|
3512
|
+
Reason: ${r}.
|
|
4229
3513
|
Requested kit: ${i}
|
|
4230
3514
|
Offline fallback only supports: fastapi.standard, nestjs.standard (and their shorthands).
|
|
4231
3515
|
Install Python 3.10+ to access all kits.
|
|
4232
|
-
`),1;let
|
|
4233
|
-
`),1;let
|
|
4234
|
-
`),1}}async function
|
|
4235
|
-
`),1;try{
|
|
4236
|
-
`),1;throw
|
|
4237
|
-
`),1;let
|
|
4238
|
-
`),1}try{if(e[0]==="create"&&e[1]==="project"){if(
|
|
3516
|
+
`),1;let s=it(e,"--output")||process.cwd(),c=f.resolve(s,n),p=e.includes("--skip-git")||e.includes("--no-git"),d=e.includes("--skip-install");try{if(await b.ensureDir(f.dirname(c)),await b.pathExists(c))return process.stderr.write(`\u274C Directory "${c}" already exists
|
|
3517
|
+
`),1;let m="pip",h=J(process.cwd());if(h)try{let{readWorkspaceMarker:w}=await import('./workspace-marker-IOPQ42A7.js'),g=await w(h);g?.metadata?.npm?.installMethod&&(m=g.metadata.npm.installMethod,console.log(`[DEBUG] Detected workspace engine: ${m}`));}catch(w){console.log("[DEBUG] Failed to read workspace marker:",w);}else console.log("[DEBUG] No workspace found, using default engine: pip");if(await b.ensureDir(c),await rr(c,{project_name:n,template:a,kit_name:i,skipGit:p,skipInstall:d,engine:m}),h){let{syncWorkspaceProjects:w}=await import('./workspace-6SADFTND.js');await w(h,true);}return 0}catch(m){return process.stderr.write(`RapidKit (npm) offline fallback failed: ${m?.message??m}
|
|
3518
|
+
`),1}}async function xn(e){let r=new Set(["--yes","-y","--skip-git","--skip-install","--debug","--dry-run","--no-update-check","--create-workspace","--no-workspace"]);if(e[0]==="create"&&e[1]==="workspace")try{let t=e.includes("--yes")||e.includes("-y"),o=e.includes("--skip-git")||e.includes("--no-git"),i=e[2]&&!e[2].startsWith("-")?e[2]:void 0,n=it(e,"--install-method"),a=n==="poetry"||n==="venv"||n==="pipx"?n:void 0,s=it(e,"--profile"),c=s==="minimal"||s==="go-only"||s==="python-only"||s==="node-only"||s==="polyglot"||s==="enterprise"?s:void 0,p=i||(t?"my-workspace":(await xe.prompt([{type:"input",name:"workspaceName",message:"Workspace name:",default:"my-workspace"}])).workspaceName);if(!p||!p.trim())return process.stderr.write(`Workspace name is required.
|
|
3519
|
+
`),1;try{Ot(p);}catch(w){if(w instanceof d)return process.stderr.write(`${w.message}
|
|
3520
|
+
`),1;throw w}let d$1=f.resolve(process.cwd(),p);if(await b.pathExists(d$1))return process.stderr.write(`\u274C Directory "${p}" already exists
|
|
3521
|
+
`),1;let m=await a$1(),h$1=m.author||process.env.USER||"RapidKit User";if(!t){let w=await xe.prompt([{type:"input",name:"author",message:"Author name:",default:h$1}]);w.author?.trim()&&(h$1=w.author.trim());}return await h(p,{skipGit:o,yes:t,userConfig:{...m,author:h$1},installMethod:a,profile:c}),0}catch(t){return process.stderr.write(`RapidKit (npm) failed to create workspace: ${t?.message??t}
|
|
3522
|
+
`),1}try{if(e[0]==="create"&&e[1]==="project"){if(e.includes("--help")||e.includes("-h"))try{return await c$2(),await d$1(["create","project","--help"],{cwd:process.cwd()})}catch(g){return process.stderr.write(`RapidKit (npm) failed to run the Python core engine: ${g?.message??g}
|
|
3523
|
+
`),1}if(!e[2]||e[2].startsWith("-")){console.log(l.bold(`
|
|
4239
3524
|
\u{1F680} RapidKit
|
|
4240
|
-
`));let{kitChoice:
|
|
4241
|
-
`),a.debug(`Synced Python version ${
|
|
4242
|
-
`),1)}}if(e[0]==="create"&&e[1]!=="project")try{await c$
|
|
4243
|
-
`),1)}return await c$
|
|
4244
|
-
`),1)}}var
|
|
4245
|
-
|
|
4246
|
-
|
|
4247
|
-
`)
|
|
4248
|
-
\u{
|
|
4249
|
-
|
|
4250
|
-
|
|
4251
|
-
`))
|
|
4252
|
-
|
|
3525
|
+
`));let{kitChoice:g}=await xe.prompt([{type:"rawlist",name:"kitChoice",message:"Select a kit to scaffold:",choices:[{name:"fastapi \u2014 FastAPI Standard Kit",value:"fastapi.standard"},{name:"fastapi \u2014 FastAPI DDD Kit",value:"fastapi.ddd"},{name:"nestjs \u2014 NestJS Standard Kit",value:"nestjs.standard"},{name:"go/fiber \u2014 Go Fiber Standard Kit",value:"gofiber.standard"},{name:"go/gin \u2014 Go Gin Standard Kit",value:"gogin.standard"}]}]);if(It(g)||ot(g)){let{projectName:C}=await xe.prompt([{type:"input",name:"projectName",message:"Project name:",validate:A=>A.trim().length>0||"Project name is required"}]),I=e.slice(2).filter(A=>A.startsWith("-"));return ot(g)?await Jr(["create","project",g,C.trim(),...I]):await Br(["create","project",g,C.trim(),...I])}let{projectName:u}=await xe.prompt([{type:"input",name:"projectName",message:"Project name:",validate:C=>C.trim().length>0||"Project name is required"}]);e.splice(2,0,g,u.trim());}{let g=J(process.cwd()),u=(e[2]||"").toLowerCase();if(g&&u){let C=f.join(g,".rapidkit","workspace.json"),I=f.join(g,".rapidkit","policies.yml");try{let[A,_]=await Promise.all([b.pathExists(C).then(pe=>pe?S.promises.readFile(C,"utf-8"):"{}"),b.pathExists(I).then(pe=>pe?S.promises.readFile(I,"utf-8"):"")]),N=JSON.parse(A).profile,D=_.match(/^\s*mode:\s*(warn|strict)\s*$/m)?.[1]??"warn",q=It(u)||ot(u)||u.startsWith("go"),ke=["nestjs","react","vue","nextjs","next","vite","angular","svelte","express","koa","fastify"].some(pe=>u.includes(pe)),Ye=!q&&!ke,he=null;if(N==="python-only"&&!Ye?he=`Kit "${u}" is not a Python kit, but workspace profile is "python-only".`:N==="node-only"&&!ke?he=`Kit "${u}" is not a Node kit, but workspace profile is "node-only".`:N==="go-only"&&!q&&(he=`Kit "${u}" is not a Go kit, but workspace profile is "go-only".`),he){if(D==="strict")return console.log(l.red(`\u274C Profile violation (strict mode): ${he}`)),console.log(l.gray("\u{1F4A1} Change workspace profile or use --no-workspace to skip enforcement.")),1;console.log(l.yellow(`\u26A0\uFE0F Profile warning: ${he}`)),console.log(l.gray('\u{1F4A1} Consider using a "polyglot" workspace profile for multi-language projects.'));}}catch{}}}if(It(e[2]||""))return await Br(e);if(ot(e[2]||""))return await Jr(e);let o=e.includes("--create-workspace"),i$1=e.includes("--no-workspace"),n=e.includes("--yes")||e.includes("-y"),a$2=e.includes("--skip-git")||e.includes("--no-git");if(!!!Bt(process.cwd())){if(o)await i(process.cwd(),{skipGit:a$2,yes:n,userConfig:await a$1()});else if(!i$1)if(n)await i(process.cwd(),{skipGit:a$2,yes:true,userConfig:await a$1()});else {let{createWs:g}=await xe.prompt([{type:"confirm",name:"createWs",message:"This project will be created outside a RapidKit workspace. Create and register a workspace here?",default:true}]);g&&await i(process.cwd(),{skipGit:a$2,yes:false,userConfig:await a$1()});}}let p=[...e.filter(g=>{let u=g.split("=")[0];return !r.has(g)&&!r.has(u)})],d=J(process.cwd()),w=e.includes("--skip-install")||!!d?{...process.env,RAPIDKIT_SKIP_LOCKS:"1",RAPIDKIT_GENERATE_LOCKS:"0"}:void 0;try{await c$2();let g=await d$1(p,{cwd:process.cwd(),env:w});if(g===0&&d&&!e.includes("--skip-install")&&(console.log(l.gray("\u2139\uFE0F Fast create mode (workspace): dependencies were deferred.")),console.log(l.white(" Next: cd <project-name> && npx rapidkit init"))),g===0){let u=d||J(process.cwd());if(u){try{let I=e[3];if(I){let A=e.indexOf("--output"),_=A>=0?e[A+1]:".",N=f.resolve(process.cwd(),_,I),K=f.join(u,".python-version"),D=f.join(N,".python-version");if(S.existsSync(K)&&S.existsSync(N)){let q=S.readFileSync(K,"utf-8");S.writeFileSync(D,q.trim()+`
|
|
3526
|
+
`),a.debug(`Synced Python version ${q.trim()} from workspace to ${I}`);}}}catch(I){a.debug("Could not sync Python version from workspace:",I);}let{syncWorkspaceProjects:C}=await import('./workspace-6SADFTND.js');await C(u,true);}}return g}catch(g){let u=Kt(g);return u?await Ut(p,u):(process.stderr.write(`RapidKit (npm) failed to run the Python core engine: ${g?.message??g}
|
|
3527
|
+
`),1)}}if(e[0]==="create"&&e[1]!=="project")try{await c$2();let t=await d$1(e,{cwd:process.cwd()});if(t===0){let o=J(process.cwd());if(o){let{syncWorkspaceProjects:i}=await import('./workspace-6SADFTND.js');await i(o,true);}}return t}catch(t){let o=Kt(t);return o?await Ut(e,o):(process.stderr.write(`RapidKit (npm) failed to run the Python core engine: ${t?.message??t}
|
|
3528
|
+
`),1)}return await c$2(),await d$1(e,{cwd:process.cwd()})}catch(t){let o=Kt(t);return o?await Ut(e,o):(process.stderr.write(`RapidKit (npm) failed to run the Python core engine: ${t?.message??t}
|
|
3529
|
+
`),1)}}var Yr=["init","dev","start","build","test","docs","lint","format","create","help","--help","-h"];function eo(e){let r=e;for(;;){let t=f.join(r,".rapidkit","context.json");if(S.existsSync(t))return t;let o=f.dirname(r);if(o===r)break;r=o;}return null}function Bt(e){let r=e;for(;;){let t=f.join(r,".rapidkit-workspace");if(S.existsSync(t))return t;let o=f.dirname(r);if(o===r)break;r=o;}return null}function J(e){let r=e;for(;;){let t=f.join(r,".rapidkit-workspace");if(S.existsSync(t))return r;let o=f.dirname(r);if(o===r)break;r=o;}return null}function Pn(e){let r=e;for(;;){let t=f.join(r,".rapidkit-workspace"),o=f.join(r,".rapidkit","workspace.json");if(!S.existsSync(t)&&S.existsSync(o))return r;let i=f.dirname(r);if(i===r)break;r=i;}return null}function En(e){if(!e)return "isolated";let t=e.match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*$/m)?.[1]?.toLowerCase();return t==="shared-runtime-caches"||t==="shared-node-deps"||t==="isolated"?t:"isolated"}function to(e){if(!e)return {mode:"isolated",status:"skipped",message:"No policies.yml found; dependency_sharing_mode defaults to isolated."};let r=e.match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*$/m);if(!r)return {mode:"isolated",status:"skipped",message:"dependency_sharing_mode is not set; defaulting to isolated."};let t=r[1].toLowerCase();return t==="isolated"||t==="shared-runtime-caches"||t==="shared-node-deps"?{mode:t,status:"passed",message:`dependency_sharing_mode is valid: ${t}.`}:{mode:"isolated",status:"failed",message:`Invalid dependency_sharing_mode: ${t}. Use one of: isolated, shared-runtime-caches, shared-node-deps.`}}async function ro(e,r){let t=J(e),o=t?f.join(t,".rapidkit","policies.yml"):null,i="isolated";if(o&&await b.pathExists(o))try{let s=await S.promises.readFile(o,"utf-8"),c=to(s);if(c.status==="failed")return console.log(l.red(`\u274C ${c.message}`)),{ok:false,code:1};i=c.mode;}catch{return console.log(l.red("\u274C Failed to read workspace policy file (.rapidkit/policies.yml).")),{ok:false,code:1}}let n=process.env.RAPIDKIT_DEP_SHARING_MODE,a=process.env.RAPIDKIT_WORKSPACE_PATH;process.env.RAPIDKIT_DEP_SHARING_MODE=i,t&&(process.env.RAPIDKIT_WORKSPACE_PATH=t);try{return {ok:true,value:await r()}}finally{typeof n>"u"?delete process.env.RAPIDKIT_DEP_SHARING_MODE:process.env.RAPIDKIT_DEP_SHARING_MODE=n,typeof a>"u"?delete process.env.RAPIDKIT_WORKSPACE_PATH:process.env.RAPIDKIT_WORKSPACE_PATH=a;}}async function le(e,r,t){return await new Promise(o=>{let i=spawn(e,r,{stdio:"inherit",cwd:t,shell:process.platform==="win32"});i.on("close",n=>o(n??1)),i.on("error",()=>o(1));})}async function Je(e,r){await b.outputFile(e,`${JSON.stringify(r,null,2)}
|
|
3530
|
+
`,"utf-8");}async function In(e){let r=new Set(["go-only"]);try{let o=f.join(e,".rapidkit","workspace.json"),i=JSON.parse(await S.promises.readFile(o,"utf-8"));if(r.has(i.profile??""))return 0}catch{}let t="poetry";try{let{readWorkspaceMarker:o}=await import('./workspace-marker-IOPQ42A7.js'),n=(await o(e))?.metadata?.npm?.installMethod;(n==="poetry"||n==="venv"||n==="pipx"||n==="pip")&&(t=n);}catch{}if(t==="poetry"||t==="venv"){let o=f.join(e,"pyproject.toml"),i=false;try{i=(await S.promises.readFile(o,"utf-8")).includes("rapidkit-core");}catch{i=false;}let n=process.env.RAPIDKIT_DEV_PATH,a=n?await b.pathExists(n):false;if(i){let s=Sn(e);if(!await b.pathExists(s)){let d=await _n(e);if(d!==0)return d}let p=await le(s,a&&n?["-m","pip","install",n,"--quiet","--disable-pip-version-check"]:["-m","pip","install","rapidkit-core","--quiet","--disable-pip-version-check"],e);if(p!==0)return p}else {let s=await le("poetry",["install","--no-root"],e);if(s!==0)return s;let c=await le("poetry",["add","rapidkit-core"],e);if(c!==0)return c}try{let{writeWorkspaceLauncher:s}=await import('./create-3OT5GA5W.js');await s(e,"poetry");}catch{}return 0}return 0}async function oo(e){let r=await S.promises.readdir(e,{withFileTypes:true}),t=[];for(let o of r){if(!o.isDirectory()||o.name.startsWith("."))continue;let i=f.join(e,o.name),n=f.join(i,".rapidkit","context.json"),a=f.join(i,".rapidkit","project.json");(await b.pathExists(n)||await b.pathExists(a))&&t.push(i);}return t}function Tn(e){let r="my-workspace",t=1;for(;;){let o=t===1?r:`${r}-${t}`,i=f.join(e,o);if(!S.existsSync(i))return {name:o,targetPath:i};t+=1;}}async function Wt(e){return (await Me("go",{runCommandInCwd:le,runCoreRapidkit:d$1}).initProject(e)).exitCode}async function He(e,r){let t=Me("node",{runCommandInCwd:le,runCoreRapidkit:d$1});return e==="init"?(await t.initProject(r)).exitCode:e==="dev"?(await t.runDev(r)).exitCode:e==="test"?(await t.runTest(r)).exitCode:e==="build"?(await t.runBuild(r)).exitCode:(await t.runStart(r)).exitCode}async function On(e,r=io){let t=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof t>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let n=function(x){if(!x)return null;let P=x.trim().toLowerCase();return P==="minimal"||P==="go-only"||P==="python-only"||P==="node-only"||P==="polyglot"||P==="enterprise"?P:null},a=function(x){let T=x.match(/^\s*mode:\s*([a-zA-Z]+)\s*$/m)?.[1]?.toLowerCase()==="strict"?"strict":"warn",de=(U,Pe)=>{let Se=x.match(new RegExp(`^\\s*${U}:\\s*(true|false)\\s*$`,"m"));return Se?Se[1].toLowerCase()==="true":Pe};return {mode:T,dependency_sharing_mode:En(x),rules:{enforce_workspace_marker:de("enforce_workspace_marker",true),enforce_toolchain_lock:de("enforce_toolchain_lock",false),disallow_untrusted_tool_sources:de("disallow_untrusted_tool_sources",false),enforce_compatibility_matrix:de("enforce_compatibility_matrix",false),require_mirror_lock_for_offline:de("require_mirror_lock_for_offline",true)}}};let s=["init"],c,p=false,d=false,m=false;for(let x=1;x<e.length;x+=1){let P=e[x];if(P==="--ci"){p=true;continue}if(P==="--offline"){d=true;continue}if(P==="--json"){m=true;continue}if(P==="--profile"){let $=e[x+1];if(!$||$.startsWith("-"))return console.log(l.yellow("Usage: rapidkit bootstrap [path] [--profile <minimal|go-only|python-only|node-only|polyglot|enterprise>] [--ci] [--offline] [--json]")),1;c=$,x+=1;continue}if(P.startsWith("--profile=")){c=P.slice(10);continue}s.push(P);}let h=n(c);if(c&&!h)return console.log(l.red(`Invalid profile: ${c}. Use one of: minimal, go-only, python-only, node-only, polyglot, enterprise.`)),1;let w=process.cwd(),g=J(w);g||(g=Pn(w));let u=[],C=null,I=null;if(g)try{let x=f.join(g,".rapidkit","workspace.json"),P=await S.promises.readFile(x,"utf-8"),$=JSON.parse(P);I=n($.profile);}catch{I=null;}let A=["minimal","python-only","node-only","go-only","polyglot","enterprise"],_={minimal:"minimal \u2014 Foundation files only (fastest bootstrap, mixed projects)","python-only":"python-only \u2014 Python + Poetry (FastAPI, Django, ML pipelines)","node-only":"node-only \u2014 Node.js runtime (NestJS, Express, Next.js)","go-only":"go-only \u2014 Go runtime (Fiber, Gin, gRPC, microservices)",polyglot:"polyglot \u2014 Python + Node.js + Go multi-runtime workspace",enterprise:"enterprise \u2014 Polyglot + governance + Sigstore verification"},N=h;if(!!g&&!h&&!p&&!m&&!!process.stdin.isTTY&&!!process.stdout.isTTY){let x=I||"minimal",{chosenProfile:P}=await xe.prompt([{type:"rawlist",name:"chosenProfile",message:`Select workspace profile for bootstrap (current: ${x})`,choices:A.map($=>({name:$===x?`${_[$]} \u2190 current`:_[$],value:$})),default:A.indexOf(x)}]);N=P;}let D=N||I||"minimal";if(g)try{let P=D==="python-only"||D==="polyglot"||D==="enterprise"?"poetry":"venv",$;try{let U=(await S.promises.readFile(f.join(g,".python-version"),"utf-8")).trim();U&&($=U);}catch{}let T=await f$1(g,{workspaceName:f.basename(g),installMethod:P,pythonVersion:$,profile:D,writeMarker:true,writeGitignore:true,onlyIfMissing:true});u.push({id:"workspace.legacy.sync",status:T.length>0?"passed":"skipped",message:T.length>0?`Legacy workspace foundation synchronized: ${T.join(", ")}`:"Workspace foundation files are already up to date."});}catch(x){u.push({id:"workspace.legacy.sync",status:"failed",message:`Failed to synchronize legacy workspace foundation files: ${x.message}`});}if(g&&N&&N!==I)try{let x=f.join(g,".rapidkit","workspace.json"),P=await S.promises.readFile(x,"utf-8"),$=JSON.parse(P);$.profile=N,await S.promises.writeFile(x,JSON.stringify($,null,2)+`
|
|
3531
|
+
`,"utf-8");}catch{}let q={mode:"warn",dependency_sharing_mode:"isolated",rules:{enforce_workspace_marker:true,enforce_toolchain_lock:false,disallow_untrusted_tool_sources:false,enforce_compatibility_matrix:false,require_mirror_lock_for_offline:true}},ke=null;if(g)try{let x=await S.promises.readFile(f.join(g,".rapidkit","policies.yml"),"utf-8");ke=x,q=a(x);}catch{u.push({id:"policy.file",status:"skipped",message:"No workspace policy file found; using default bootstrap policy."});}else u.push({id:"workspace.detect",status:"skipped",message:"No workspace marker found; bootstrap runs in project/single-path mode."});if(g){let x=to(ke);q.dependency_sharing_mode=x.mode,u.push({id:"policy.schema.dependency_sharing_mode",status:x.status,message:x.message}),u.push({id:"policy.dependency_sharing_mode.effective",status:"passed",message:q.dependency_sharing_mode==="isolated"?"Effective dependency mode: isolated (default secure mode).":q.dependency_sharing_mode==="shared-node-deps"?"Effective dependency mode: shared-node-deps (Node projects share workspace-level caches).":"Effective dependency mode: shared-runtime-caches (Node/Python/Go share workspace-level caches)."});let P=S.existsSync(f.join(g,".rapidkit-workspace"));u.push({id:"policy.enforce_workspace_marker",status:!q.rules.enforce_workspace_marker||P?"passed":"failed",message:!q.rules.enforce_workspace_marker||P?"Workspace marker policy satisfied.":"Workspace marker policy failed: .rapidkit-workspace is missing."});let $=S.existsSync(f.join(g,".rapidkit","toolchain.lock"));u.push({id:"policy.enforce_toolchain_lock",status:!q.rules.enforce_toolchain_lock||$?"passed":"failed",message:!q.rules.enforce_toolchain_lock||$?"Toolchain lock policy satisfied.":"Toolchain lock policy failed: .rapidkit/toolchain.lock is missing."});let T=process.env.RAPIDKIT_TRUSTED_SOURCES==="1"||S.existsSync(f.join(g,".rapidkit","trusted-sources.lock"));u.push({id:"policy.disallow_untrusted_tool_sources",status:!q.rules.disallow_untrusted_tool_sources||T?"passed":"failed",message:!q.rules.disallow_untrusted_tool_sources||T?"Trusted tool sources policy satisfied.":"Trusted tool sources policy failed: set RAPIDKIT_TRUSTED_SOURCES=1 or provide .rapidkit/trusted-sources.lock."});let de=f.join(g,".rapidkit","compatibility-matrix.json"),U=S.existsSync(de),Pe=q.rules.enforce_compatibility_matrix;if(u.push({id:"policy.enforce_compatibility_matrix",status:!Pe||U?"passed":"failed",message:!Pe||U?"Compatibility matrix policy satisfied.":"Compatibility matrix policy failed: .rapidkit/compatibility-matrix.json is missing."}),U)try{let L=await S.promises.readFile(de,"utf-8"),Y=JSON.parse(L),st=!!Y&&typeof Y=="object";u.push({id:"compatibility.matrix.parse",status:st?"passed":"failed",message:st?"Compatibility matrix parsed successfully.":"Compatibility matrix parse failed: invalid JSON object."});}catch{u.push({id:"compatibility.matrix.parse",status:"failed",message:"Compatibility matrix parse failed: invalid JSON."});}let Se=f.join(g,".rapidkit","mirror-config.json"),re=f.join(g,".rapidkit","mirror.lock"),Ee=S.existsSync(Se),_e=S.existsSync(re),nt={};if(Ee)try{nt=JSON.parse(await S.promises.readFile(Se,"utf-8")),u.push({id:"mirror.config.parse",status:"passed",message:"Mirror configuration parsed successfully."});}catch{u.push({id:"mirror.config.parse",status:"failed",message:"Mirror configuration parse failed: invalid JSON in .rapidkit/mirror-config.json."});}let Tt=await Ht(g,{ciMode:p,offlineMode:d});if(u.push(...Tt.checks.map(L=>({id:L.id,status:L.status,message:L.message}))),C=Tt.details,Tt.details.lockWritten&&(_e=true),d){let L=process.env.RAPIDKIT_MIRROR_ENABLED==="1"||nt.enabled===true;u.push({id:"offline.mirror.enabled",status:L?"passed":"failed",message:L?"Offline mode mirror is enabled.":'Offline mode requires mirror enablement (set RAPIDKIT_MIRROR_ENABLED=1 or .rapidkit/mirror-config.json {"enabled": true}).'});let Y=q.rules.require_mirror_lock_for_offline;u.push({id:"offline.mirror.lock",status:!Y||_e?"passed":"failed",message:!Y||_e?"Offline mode mirror lock policy satisfied.":"Offline mode mirror lock policy failed: .rapidkit/mirror.lock is missing."});}else u.push({id:"offline.mirror.enabled",status:"skipped",message:"Offline mirror checks skipped (offline mode is disabled)."});let no=await oo(g),ce=new Set;for(let L of no){let Y=Te(L);if(ge(Y,L)){ce.add("go");continue}if(me(Y,L)){ce.add("node");continue}if(fe(Y,L)){ce.add("python");continue}ce.add("unknown");}if(D==="go-only"){let L=ce.size===0||[...ce].every(Y=>Y==="go");u.push({id:"profile.go-only",status:L?"passed":"failed",message:L?"go-only profile validated for discovered projects.":`go-only profile mismatch: detected runtimes [${[...ce].join(", ")}].`});}else if(D==="python-only"){let L=ce.size===0||[...ce].every(Y=>Y==="python");u.push({id:"profile.python-only",status:L?"passed":"failed",message:L?"python-only profile validated for discovered projects.":`python-only profile mismatch: detected runtimes [${[...ce].join(", ")}].`});}else if(D==="node-only"){let L=ce.size===0||[...ce].every(Y=>Y==="node");u.push({id:"profile.node-only",status:L?"passed":"failed",message:L?"node-only profile validated for discovered projects.":`node-only profile mismatch: detected runtimes [${[...ce].join(", ")}].`});}else if(D==="minimal"){let L=[...ce].filter(st=>st!=="unknown"),Y=L.length<=1;u.push({id:"profile.minimal",status:Y?"passed":"failed",message:Y?"minimal profile is compatible with detected runtime mix.":`minimal profile mismatch: multiple runtimes detected [${L.join(", ")}].`});}else D==="enterprise"&&(u.push({id:"profile.enterprise.ci",status:p?"passed":"failed",message:p?"enterprise profile running with --ci.":"enterprise profile expects --ci for deterministic non-interactive mode."}),u.push({id:"profile.enterprise.compatibility-matrix",status:U?"passed":"failed",message:U?"enterprise profile has compatibility matrix.":"enterprise profile requires .rapidkit/compatibility-matrix.json."}),u.push({id:"profile.enterprise.mirror-config",status:Ee?"passed":"failed",message:Ee?"enterprise profile has mirror configuration.":"enterprise profile requires .rapidkit/mirror-config.json."}));}p&&(process.env.RAPIDKIT_BOOTSTRAP_CI="1"),d&&(process.env.RAPIDKIT_OFFLINE_MODE="1");let he=u.some(x=>x.id.startsWith("policy.schema.")&&x.status==="failed")||q.mode==="strict"&&u.some(x=>x.status==="failed"),pe=g||w,Ke=f.join(pe,".rapidkit","reports"),B=new Date().toISOString().replace(/[:.]/g,"-"),G=f.join(Ke,`bootstrap-compliance-${B}.json`),k=f.join(Ke,"bootstrap-compliance.latest.json"),oe={command:"bootstrap",timestamp:new Date().toISOString(),workspacePath:g,profile:D,options:{ci:p,offline:d,strict:q.mode==="strict"},policyMode:q.mode,policyRules:q.rules,mirrorLifecycle:C,checks:u};if(he){let x={...oe,result:"blocked",initExitCode:null};return await b.ensureDir(Ke),await Je(G,x),await Je(k,x),m?process.stdout.write(`${JSON.stringify(x,null,2)}
|
|
3532
|
+
`):(console.log(l.red("\u274C Bootstrap blocked by strict policy checks.")),console.log(l.gray(`Compliance report: ${G}`))),1}let ie=0;m||(ie=await r(s));let F=u.filter(x=>x.status==="failed").length,te=ie!==0?"failed":F>0?"ok_with_warnings":"ok",ae={...oe,result:te,initExitCode:ie};if(await b.ensureDir(Ke),await Je(G,ae),await Je(k,ae),m)process.stdout.write(`${JSON.stringify(ae,null,2)}
|
|
3533
|
+
`);else {let x=u.filter(P=>P.status==="failed").length;x>0&&console.log(l.yellow(`\u26A0\uFE0F Bootstrap completed with ${x} policy/profile warnings.`)),console.log(l.gray(`Compliance report: ${G}`));}return ie}finally{typeof t>"u"?delete process.env.RAPIDKIT_SKIP_LOCK_SYNC:process.env.RAPIDKIT_SKIP_LOCK_SYNC=t;}}async function An(e){let r=(e[1]||"").toLowerCase(),t=e.includes("--warm-deps")||e.includes("--warm-dependencies");if(!r||!["python","node","go"].includes(r))return console.log(l.yellow("Usage: rapidkit setup <python|node|go> [--warm-deps]")),1;let o=async(p,d)=>{if(p==="node"){if(!S.existsSync(f.join(d,"package.json")))return {exitCode:0,message:"Node warm-up skipped: package.json not found in current directory."};let h=S.existsSync(f.join(d,"pnpm-lock.yaml")),w=S.existsSync(f.join(d,"yarn.lock"));return h?{exitCode:await le("pnpm",["install","--lockfile-only","--ignore-scripts"],d)}:w?{exitCode:await le("yarn",["install","--ignore-scripts"],d)}:{exitCode:await le("npm",["install","--package-lock-only","--ignore-scripts"],d)}}return p==="go"?S.existsSync(f.join(d,"go.mod"))?{exitCode:await le("go",["mod","download"],d)}:{exitCode:0,message:"Go warm-up skipped: go.mod not found in current directory."}:{exitCode:0,message:"Dependency warm-up currently applies to node/go runtimes."}},i=Me(r,{runCommandInCwd:le,runCoreRapidkit:(p,d)=>d$1(p,{...d,cwd:void 0})}),n=await i.checkPrereqs(),a=await i.doctorHints(process.cwd()),s=J(process.cwd()),c=s||process.cwd();if(n.exitCode===0){console.log(l.green(`\u2705 ${r} prerequisites look good.`));let p=["python","node","go"].filter(d=>d!==r).join("/");if(console.log(l.gray(` Scope: validated ${r} runtime only. ${p} checks are optional unless your workspace profile uses them.`)),r==="python"&&console.log(l.gray(" Note: Poetry is recommended, but venv/pipx-based flows are supported in workspace creation.")),i.warmSetupCache&&((await i.warmSetupCache(c)).exitCode===0?console.log(l.gray(` ${r} cache warm-up completed.`)):console.log(l.yellow(` ${r} cache warm-up skipped (non-fatal).`))),t){let d=await o(r,c),m=/skipped/i.test(d.message||"");d.message&&console.log(l.gray(` ${d.message}`)),d.exitCode===0&&!m?console.log(l.gray(` ${r} dependency warm-up completed (--warm-deps).`)):d.exitCode!==0&&console.log(l.yellow(` ${r} dependency warm-up failed (non-fatal).`));}if(s)try{let d=f.join(s,".rapidkit","toolchain.lock"),m={};try{m=JSON.parse(await S.promises.readFile(d,"utf-8"));}catch{}(!m.runtime||typeof m.runtime!="object")&&(m.runtime={});let h=m.runtime;if(r==="python"){let w=null;try{let{execa:g}=await import('execa');for(let u of Zr()){let I=await g(u,u==="py"?["-3","--version"]:["--version"],{cwd:s,stdio:"pipe",reject:false,timeout:3e3});if(I.exitCode===0){let _=(I.stdout||I.stderr||"").match(/Python\s+(\S+)/);if(w=_?_[1]:null,w)break}}}catch{}h.python={...h.python||{},version:w,last_setup:new Date().toISOString()};}else if(r==="node")h.node={...h.node||{},version:process.version,last_setup:new Date().toISOString()};else if(r==="go"){let w=null;try{let{execa:g}=await import('execa'),C=((await g("go",["version"],{cwd:s,stdio:"pipe"})).stdout||"").match(/go(\d+\.\d+(?:\.\d+)?)/i);w=C?C[1]:null;}catch{}h.go={...h.go||{},version:w,last_setup:new Date().toISOString()};}m.updated_at=new Date().toISOString(),await S.promises.writeFile(d,JSON.stringify(m,null,2)+`
|
|
3534
|
+
`,"utf-8"),console.log(l.gray(" toolchain.lock updated (.rapidkit/toolchain.lock)"));}catch{}}else console.log(l.red(`\u274C ${r} prerequisites check failed.`));if(a.length>0){console.log(l.gray(`
|
|
3535
|
+
Hints:`));for(let p of a)console.log(l.gray(`- ${p}`));}return n.exitCode}function Nn(e){let r={strategy:"shared",prune_on_bootstrap:false,self_heal:true,verify_integrity:false};for(let t of e.split(`
|
|
3536
|
+
`)){let o=t.trim(),i=o.match(/^strategy:\s*(\S+)/);i&&(r.strategy=i[1].replace(/['"]]/g,""));let n=o.match(/^prune_on_bootstrap:\s*(true|false)/);n&&(r.prune_on_bootstrap=n[1]==="true");let a=o.match(/^self_heal:\s*(true|false)/);a&&(r.self_heal=a[1]==="true");let s=o.match(/^verify_integrity:\s*(true|false)/);s&&(r.verify_integrity=s[1]==="true");}return r}async function jn(e){let r=(e[1]||"status").toLowerCase(),t=Pt.getInstance(),o=J(process.cwd()),i={strategy:"shared",prune_on_bootstrap:false,self_heal:true,verify_integrity:false};if(o)try{let n=await S.promises.readFile(f.join(o,".rapidkit","cache-config.yml"),"utf-8");i=Nn(n);}catch{}return r==="status"?(console.log(l.cyan("RapidKit cache is enabled")),console.log(l.cyan("RapidKit cache status")),o?(console.log(l.gray(` Workspace: ${o}`)),console.log(l.gray(` Strategy: ${i.strategy}`)),console.log(l.gray(` Self-heal: ${i.self_heal}`)),console.log(l.gray(` Prune on bootstrap:${i.prune_on_bootstrap}`)),console.log(l.gray(` Verify integrity: ${i.verify_integrity}`))):console.log(l.gray(" (not inside a workspace \u2014 showing in-memory cache only)")),console.log(l.gray(" In-memory cache: enabled")),console.log(l.gray(" Use: rapidkit cache clear|prune|repair")),0):r==="clear"?(await t.clear(),console.log(l.green("Cache clear completed")),console.log(l.green("\u2705 Cache cleared (all entries removed).")),0):r==="prune"?(await t.clear(),console.log(l.green("\u2705 Cache pruned (stale entries removed).")),i.prune_on_bootstrap||console.log(l.gray(" Tip: set prune_on_bootstrap: true in .rapidkit/cache-config.yml to auto-prune on every bootstrap.")),0):r==="repair"?i.self_heal?(await t.clear(),console.log(l.green("\u2705 Cache repaired (self-heal applied, stale entries evicted).")),i.verify_integrity&&console.log(l.gray(" Integrity verification is enabled in cache-config.yml.")),0):(console.log(l.yellow("\u26A0\uFE0F self_heal is disabled in .rapidkit/cache-config.yml \u2014 skipping repair.")),0):(console.log(l.yellow("Usage: rapidkit cache <status|clear|prune|repair>")),1)}async function $n(e){let r=(e[1]||"status").toLowerCase(),t=e.includes("--json"),o=J(process.cwd());if(!o)return console.log(l.red("\u274C Not inside a RapidKit workspace")),console.log(l.gray("\u{1F4A1} Run this command from within a workspace directory")),1;let i=f.join(o,".rapidkit"),n=f.join(i,"mirror-config.json"),a=f.join(i,"mirror.lock"),s=f.join(i,"mirror","artifacts"),c=f.join(i,"reports");async function p(d){let m=new Date().toISOString().replace(/[:.]/g,"-"),h=f.join(c,`mirror-ops-${m}.json`),w=f.join(c,"mirror-ops.latest.json");await b.ensureDir(c),await Je(h,d),await Je(w,d);}if(r==="status"){if(!await b.pathExists(n))try{let C={schema_version:"1.0",enabled:false,strategy:"on-demand",artifacts:[],created_at:new Date().toISOString(),note:"Auto-generated by rapidkit mirror status. Set enabled: true and add artifact entries to activate mirroring."};await b.ensureDir(i),await S.promises.writeFile(n,JSON.stringify(C,null,2)+`
|
|
3537
|
+
`,"utf-8"),console.log(l.gray(" mirror-config.json created with defaults (.rapidkit/mirror-config.json)"));}catch{}let m=await b.pathExists(n),h=await b.pathExists(s),w=await b.pathExists(a),g=h?(await S.promises.readdir(s,{withFileTypes:true})).filter(C=>C.isFile()).length:0,u={command:"mirror",action:r,result:"ok",timestamp:new Date().toISOString(),workspacePath:o,mirror:{configExists:m,lockExists:w,artifactsCount:g}};return await p(u),t?(process.stdout.write(`${JSON.stringify(u,null,2)}
|
|
3538
|
+
`),0):(console.log(l.cyan("RapidKit mirror status")),console.log(l.gray(`Workspace: ${o}`)),console.log(l.gray(`Config: ${m?"present":"missing"} (${n})`)),console.log(l.gray(`Lock: ${w?"present":"missing"} (${a})`)),console.log(l.gray(`Artifacts: ${g}`)),0)}if(r==="sync"||r==="verify"||r==="rotate"){let d=await Ht(o,{ciMode:true,offlineMode:r==="verify",forceRun:true}),m=d.checks.filter(g=>g.status==="failed"),h=d.checks.some(g=>g.id.startsWith("mirror.verify.")&&g.status==="failed");if(r==="verify"&&h){let g={command:"mirror",action:r,result:"failed",timestamp:new Date().toISOString(),workspacePath:o,details:d.details,checks:d.checks};if(await p(g),t)return process.stdout.write(`${JSON.stringify(g,null,2)}
|
|
3539
|
+
`),1;console.log(l.red("\u274C Mirror verify failed."));for(let u of d.checks.filter(C=>C.id.startsWith("mirror.verify.")))console.log(l.gray(`- ${u.id}: ${u.message}`));return 1}if(m.length>0){let g={command:"mirror",action:r,result:"failed",timestamp:new Date().toISOString(),workspacePath:o,details:d.details,checks:d.checks};if(await p(g),t)return process.stdout.write(`${JSON.stringify(g,null,2)}
|
|
3540
|
+
`),1;console.log(l.yellow(`\u26A0\uFE0F Mirror ${r} completed with ${m.length} issue(s).`));for(let u of m)console.log(l.gray(`- ${u.id}: ${u.message}`));return 1}let w={command:"mirror",action:r,result:"ok",timestamp:new Date().toISOString(),workspacePath:o,details:d.details,checks:d.checks};return await p(w),t?(process.stdout.write(`${JSON.stringify(w,null,2)}
|
|
3541
|
+
`),0):r==="rotate"?(console.log(l.green(`\u2705 Mirror rotate completed. Rotated files: ${d.details.rotatedFiles}.`)),0):r==="verify"?(console.log(l.green(`\u2705 Mirror verify completed. Verified artifacts: ${d.details.verifiedArtifacts}.`)),0):(console.log(l.green(`\u2705 Mirror sync completed. Synced artifacts: ${d.details.syncedArtifacts}.`)),0)}return console.log(l.yellow("Usage: rapidkit mirror <status|sync|verify|rotate> [--json]")),1}async function io(e){let r=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof r>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let t=process.cwd(),o=await ro(t,async()=>{let i=J(t),n=Me("python",{runCommandInCwd:le,runCoreRapidkit:d$1});if(e.length>1){let m=f.resolve(t,e[1]),h=Te(m);return ge(h,m)?await Wt(m):me(h,m)?await He("init",m):fe(h,m)?(await n.initProject(m)).exitCode:await d$1(e,{cwd:t})}let a=Te(t),s=!!J(t)&&t===J(t);if(!s&&ge(a,t))return await Wt(t);if(!s&&me(a,t))return await He("init",t);if(!s&&fe(a,t))return (await n.initProject(t)).exitCode;let c=i||J(t),p=eo(t),d=p?f.dirname(f.dirname(p)):null;if(d&&d!==c)return (await n.initProject(d)).exitCode;if(c&&t===c){let m=await In(c);if(m!==0)return m;let h=await oo(c);if(h.length===0){let w="minimal";try{w=JSON.parse(await S.promises.readFile(f.join(c,".rapidkit","workspace.json"),"utf-8")).profile??"minimal";}catch{}return w==="go-only"?(console.log(l.green("\u2714 Go workspace ready")),console.log(l.gray(`
|
|
3542
|
+
No projects yet \u2014 create one and then run init inside it:`)),console.log(l.white(" npx rapidkit create project gofiber.standard my-api")),console.log(l.white(" cd my-api && npx rapidkit init")),console.log(l.gray(`
|
|
3543
|
+
\u{1F4A1} Go dependencies are managed per-project (go.mod / go mod tidy).`))):(console.log(l.green("\u2714 Workspace ready")),console.log(l.gray(`
|
|
3544
|
+
No projects yet \u2014 create one to get started:`)),console.log(l.white(" npx rapidkit create project"))),0}for(let w of h){let g=Te(w);if(ge(g,w)){let u=await Wt(w);if(u!==0)return u}else {if(me(g,w)){let C=await He("init",w);if(C!==0)return C;continue}if(fe(g,w)){let C=await n.initProject(w);if(C.exitCode!==0)return C.exitCode;continue}let u=await d$1(["init"],{cwd:w});if(u!==0)return u}}return 0}if(!c){let m=await a$1(),{name:h$1}=Tn(t);return await h(h$1,{yes:true,userConfig:m}),0}return await d$1(e,{cwd:t})});return o.ok?o.value:o.code}finally{typeof r>"u"?delete process.env.RAPIDKIT_SKIP_LOCK_SYNC:process.env.RAPIDKIT_SKIP_LOCK_SYNC=r;}}async function zr(e){let r=J(e);if(!r)return [];let t="warn";try{(await S.promises.readFile(f.join(r,".rapidkit","policies.yml"),"utf-8")).match(/^\s*mode:\s*(warn|strict)\s*$/m)?.[1]==="strict"&&(t="strict");}catch{return []}if(t!=="strict")return [];let o=[],i=f.join(r,".rapidkit","toolchain.lock");if(!S.existsSync(i))return o.push("toolchain.lock is missing \u2014 run `rapidkit bootstrap` first (strict mode requires a reproducible toolchain)."),o;let n={};try{n=JSON.parse(await S.promises.readFile(i,"utf-8"));}catch{return []}let a=n.runtime??{},s=Te(e);ge(s,e)&&!a.go?.version?o.push("go.version is not pinned in toolchain.lock \u2014 run `rapidkit setup go` first."):me(s,e)&&!a.node?.version?o.push("node.version is not pinned in toolchain.lock \u2014 run `rapidkit setup node` first."):fe(s,e)&&!a.python?.version&&o.push("python.version is not pinned in toolchain.lock \u2014 run `rapidkit setup python` first.");try{let p=JSON.parse(await S.promises.readFile(f.join(r,".rapidkit","workspace.json"),"utf-8")).profile??"";p==="python-only"&&(ge(s,e)||me(s,e))?o.push('Workspace profile is "python-only" but this project is not Python.'):p==="node-only"&&(ge(s,e)||fe(s,e))?o.push('Workspace profile is "node-only" but this project is not Node.'):p==="go-only"&&(me(s,e)||fe(s,e))&&o.push('Workspace profile is "go-only" but this project is not Go.');}catch{}return o}async function Dn(){let e=process.cwd(),r=process.argv.slice(2),t=r[0],o=!t||t==="--help"||t==="-h"||t==="help",i=S.existsSync(f.join(e,".rapidkit-workspace")),n=S.existsSync(f.join(e,".rapidkit","project.json")),a$1=["bootstrap","cache","mirror","setup","workspace","doctor","ai","config"];if(r[0]&&a$1.includes(r[0])||r[0]==="create"||r[0]==="init"&&i&&!n)return false;try{let w=t==="shell"&&r[1]==="activate",g=t==="create",u=await tr(e,{cwd:e,timeoutMs:1200});if(u.ok&&u.data?.isRapidkitProject&&u.data.engine==="python"&&!o&&!w&&!(g||t==="bootstrap"||t==="cache"||t==="mirror"||t==="setup"||t==="workspace")){if(t&&["build","dev","start","test"].includes(t)){let A=await zr(e).catch(()=>[]);if(A.length>0){process.stderr.write(l.red("\u274C Strict policy violations prevent running this command:")+`
|
|
3545
|
+
`);for(let _ of A)process.stderr.write(l.red(` \u2022 ${_}`)+`
|
|
3546
|
+
`);process.exit(1);}}let I=await d$1(process.argv.slice(2),{cwd:e});process.exit(I);}}catch{}let s=eo(e),c=process.platform==="win32",p=c?[f.join(e,"rapidkit.cmd"),f.join(e,"rapidkit"),f.join(e,".rapidkit","rapidkit.cmd"),f.join(e,".rapidkit","rapidkit")]:[f.join(e,"rapidkit"),f.join(e,".rapidkit","rapidkit")],d=null;for(let w of p)if(await b.pathExists(w)){d=w;break}let m=t==="create";if(t==="init"&&i&&!n)return false;if(t&&["build","dev","start","test"].includes(t)){let w=await zr(e);if(w.length>0){process.stderr.write(l.red("\u274C Strict policy violations prevent running this command:")+`
|
|
3547
|
+
`);for(let g of w)process.stderr.write(l.red(` \u2022 ${g}`)+`
|
|
3548
|
+
`);process.exit(1);}}if(d&&t&&Yr.includes(t)&&!m){a.debug(`Delegating to local CLI: ${d} ${r.join(" ")}`);let w=t==="init"?Vr():process.env,g=spawn(d,r,{stdio:"inherit",cwd:e,shell:c,env:w});return g.on("close",u=>{process.exit(u??0);}),g.on("error",u=>{a.error(`Failed to run local rapidkit: ${u.message}`),process.exit(1);}),true}if(s&&await b.pathExists(s))try{if((await b.readJson(s)).engine==="pip"){let g=r[0],C=process.platform==="win32"?[f.join(e,"rapidkit.cmd"),f.join(e,"rapidkit"),f.join(e,".rapidkit","rapidkit.cmd"),f.join(e,".rapidkit","rapidkit")]:[f.join(e,"rapidkit"),f.join(e,".rapidkit","rapidkit")],I=null;for(let _ of C)if(await b.pathExists(_)){I=_;break}if(I&&g&&Yr.includes(g)){a.debug(`Delegating to local CLI (early detection): ${I} ${r.join(" ")}`);let _=g==="init"?Vr():process.env,N=spawn(I,r,{stdio:"inherit",cwd:e,env:_});return N.on("close",K=>process.exit(K??0)),N.on("error",K=>{a.error(`Failed to run local rapidkit: ${K.message}`),process.exit(1);}),true}if(g==="shell"&&r[1]==="activate"){let _=`# RapidKit: activation snippet - eval "$(rapidkit shell activate)"
|
|
4253
3549
|
VENV='.venv'
|
|
4254
3550
|
if [ -f "$VENV/bin/activate" ]; then
|
|
4255
3551
|
. "$VENV/bin/activate"
|
|
@@ -4258,45 +3554,64 @@ elif [ -f "$VENV/bin/activate.fish" ]; then
|
|
|
4258
3554
|
fi
|
|
4259
3555
|
export RAPIDKIT_PROJECT_ROOT="$(pwd)"
|
|
4260
3556
|
export PATH="$(pwd)/.rapidkit:$(pwd):$PATH"
|
|
4261
|
-
`;console.log(
|
|
3557
|
+
`;console.log(l.green.bold(`
|
|
4262
3558
|
\u2705 Activation snippet \u2014 run the following to activate this project in your current shell:
|
|
4263
|
-
`)),console.log(
|
|
3559
|
+
`)),console.log(_),console.log(l.gray(`
|
|
4264
3560
|
\u{1F4A1} After activation you can run: rapidkit dev
|
|
4265
|
-
`)),process.exit(0);}let
|
|
3561
|
+
`)),process.exit(0);}if(!o&&!["bootstrap","cache","mirror","setup","workspace","doctor","ai","config"].includes(g)){let _=await d$1(r,{cwd:e});process.exit(_);}}}catch{}return false}var Ae=null,Et=false,Ce=new Command;async function Mn(e){if(e.length===0)return false;let r=e[0],t=e[1];if(r==="shell"&&t==="activate"||r==="workspace"||r==="doctor"||r==="bootstrap"||r==="setup"||r==="cache"||r==="mirror"||r==="ai"||r==="config")return false;if(e.includes("--tui"))return true;if(r==="--help"||r==="-h"||r==="help"||r==="--version"||r==="-V"||e.includes("--template")||e.includes("-t"))return false;let o=new Set(["--yes","-y","--skip-git","--skip-install","--debug","--dry-run","--no-update-check","--create-workspace","--no-workspace"]);if(e.some(n=>o.has(n)))return false;let i=await h$1();return i?i.has(r):!!(a$2.has(r)||e.length>1)}Ce.name("rapidkit").description("Create RapidKit workspaces and projects").version(c());Ce.addHelpText("beforeAll",`RapidKit
|
|
4266
3562
|
|
|
4267
3563
|
Global CLI
|
|
4268
|
-
Create
|
|
3564
|
+
Create workspaces, scaffold projects, and manage your development toolchain.
|
|
3565
|
+
`);Ce.addHelpText("afterAll",`
|
|
3566
|
+
Workspace Setup Commands
|
|
3567
|
+
rapidkit bootstrap Bootstrap projects in workspace (--profile python-only|node-only|go-only|polyglot|enterprise)
|
|
3568
|
+
rapidkit setup <runtime> Set up runtime toolchain (runtime: python | node | go)
|
|
3569
|
+
rapidkit mirror Manage registry mirrors (mirror status --json | sync | verify | rotate)
|
|
3570
|
+
rapidkit cache Manage package cache (cache status | clear | prune | repair)
|
|
4269
3571
|
|
|
4270
|
-
Global Engine Commands
|
|
4271
|
-
Access engine-level commands when inside a RapidKit workspace or via the core bridge
|
|
4272
|
-
`);z.addHelpText("afterAll",`
|
|
4273
3572
|
Project Commands
|
|
4274
|
-
rapidkit create
|
|
4275
|
-
rapidkit init
|
|
4276
|
-
rapidkit dev
|
|
3573
|
+
rapidkit create Scaffold a new project (rapidkit create project)
|
|
3574
|
+
rapidkit init Install project dependencies
|
|
3575
|
+
rapidkit dev Start dev server
|
|
3576
|
+
rapidkit build Build for production
|
|
3577
|
+
rapidkit test Run tests
|
|
3578
|
+
|
|
3579
|
+
Quick start:
|
|
3580
|
+
npx rapidkit my-workspace # Create + bootstrap workspace
|
|
3581
|
+
cd my-workspace
|
|
3582
|
+
npx rapidkit create project # Interactive kit picker
|
|
3583
|
+
npx rapidkit init && npx rapidkit dev # Install deps + run
|
|
3584
|
+
|
|
3585
|
+
Notes:
|
|
3586
|
+
--skip-install (npm wrapper) enables fast-path for lock/dependency steps.
|
|
3587
|
+
It is different from core --skip-essentials (essential module installation).
|
|
4277
3588
|
|
|
4278
3589
|
Use "rapidkit help <command>" for more information.
|
|
4279
|
-
`);
|
|
3590
|
+
`);Ce.argument("[name]","Name of the workspace or project directory").addOption(new Option("-t, --template <template>","Legacy: create a project with template (fastapi, nestjs) instead of a workspace").hideHelp()).option("-y, --yes","Skip prompts and use defaults").addOption(new Option("--skip-git","Skip git initialization").hideHelp()).addOption(new Option("--skip-install","Legacy: skip installing dependencies (template mode)").hideHelp()).option("--debug","Enable debug logging").addOption(new Option("--dry-run","Show what would be created without creating it").hideHelp()).addOption(new Option("--install-method <method>","Installation method: poetry, venv, or pipx").choices(["poetry","venv","pipx"]).hideHelp()).addOption(new Option("--profile <profile>","Workspace bootstrap profile: minimal, python-only, node-only, go-only, polyglot, enterprise").choices(["minimal","python-only","node-only","go-only","polyglot","enterprise"]).hideHelp()).addOption(new Option("--create-workspace","When creating a project outside a workspace: create and register a workspace in the current directory").hideHelp()).addOption(new Option("--no-workspace","When creating a project outside a workspace: do not create a workspace").hideHelp()).option("--no-update-check","Skip checking for updates").action(async(e$1,r)=>{try{r.debug&&(a.setDebug(true),a.debug("Debug mode enabled"));let t=await a$1();a.debug("User config loaded",t);let o=await b$1();a.debug("RapidKit config loaded",o);let i$1=c$1(t,o,{author:r.author,pythonVersion:void 0,skipGit:r.skipGit});a.debug("Merged config",i$1),r.updateCheck!==false&&await b$2(),console.log(l.blue.bold(`
|
|
4280
3591
|
\u{1F680} Welcome to RapidKit!
|
|
4281
|
-
`)),e$1||(
|
|
4282
|
-
\u274C ${
|
|
4283
|
-
`),process.exit(1)),
|
|
4284
|
-
\u274C Directory "${e$1}" already exists`),console.log(
|
|
3592
|
+
`)),e$1||(Ln(),process.exit(0));try{Ot(e$1);}catch(s){throw s instanceof d&&(a.error(`
|
|
3593
|
+
\u274C ${s.message}`),s.details&&a.warn(`\u{1F4A1} ${s.details}
|
|
3594
|
+
`),process.exit(1)),s}let n=f.resolve(process.cwd(),e$1);Ae=n,await b.pathExists(n)&&(a.error(`
|
|
3595
|
+
\u274C Directory "${e$1}" already exists`),console.log(l.cyan(`
|
|
4285
3596
|
\u{1F4A1} Choose a different name or delete the existing directory.
|
|
4286
|
-
`)),process.exit(1));let
|
|
3597
|
+
`)),process.exit(1));let a$2=!!r.template;if(r.dryRun){console.log(l.cyan(`
|
|
4287
3598
|
\u{1F50D} Dry-run mode - showing what would be created:
|
|
4288
|
-
`)),console.log(
|
|
4289
|
-
`)),
|
|
4290
|
-
`),a.debug(`Synced Python version ${
|
|
4291
|
-
`),a.debug(`Re-synced Python version ${
|
|
3599
|
+
`)),console.log(l.white("\u{1F4C2} Path:"),n),console.log(l.white("\u{1F4E6} Type:"),a$2?`Project (${r.template})`:"Workspace"),console.log();return}if(!r.yes&&!a$2?await xe.prompt([{type:"input",name:"author",message:"Author name:",default:process.env.USER||"RapidKit User"}]):r.yes&&console.log(l.gray(`Using default values (--yes flag)
|
|
3600
|
+
`)),a$2){let s=String(r.template||"").trim(),c=s.toLowerCase(),p=c==="fastapi"?"fastapi.standard":c==="nestjs"?"nestjs.standard":c==="go"||c==="fiber"?"gofiber.standard":c==="gin"?"gogin.standard":s;if(It(p)){let A=f.resolve(process.cwd(),e$1);await Nt(A,{project_name:e$1,module_path:e$1,skipGit:r.skipGit});return}if(ot(p)){let A=f.resolve(process.cwd(),e$1);await jt(A,{project_name:e$1,module_path:e$1,skipGit:r.skipGit});return}if(!!!Bt(process.cwd())){if(r.createWorkspace)await i(process.cwd(),{skipGit:r.skipGit,yes:r.yes,userConfig:t});else if(!r.noWorkspace)if(r.yes)await i(process.cwd(),{skipGit:r.skipGit,yes:true,userConfig:t});else {let{createWs:A}=await xe.prompt([{type:"confirm",name:"createWs",message:"This project will be created outside a RapidKit workspace. Create and register a workspace here?",default:true}]);A&&await i(process.cwd(),{skipGit:r.skipGit,yes:false,userConfig:t});}}let m=["create","project",p,e$1,"--output",process.cwd()];r.yes&&m.push("--yes");let h=J(process.cwd()),w=!!r.skipInstall,g=w||!!h;w&&m.push("--skip-essentials");let u=g?{...process.env,RAPIDKIT_SKIP_LOCKS:"1",RAPIDKIT_GENERATE_LOCKS:"0"}:void 0,C=await e(m,{cwd:process.cwd(),env:u});C!==0&&process.exit(C),h&&!r.skipInstall&&(console.log(l.gray("\u2139\uFE0F Fast create mode (workspace): dependencies were deferred.")),console.log(l.white(" Next: cd <project-name> && npx rapidkit init")));let I=Bt(process.cwd());if(I){let A=f.dirname(I),_=f.join(A,".python-version"),N=f.join(n,".python-version");try{if(await b.pathExists(_)){let K=S.readFileSync(_,"utf-8");S.writeFileSync(N,K.trim()+`
|
|
3601
|
+
`),a.debug(`Synced Python version ${K.trim()} from workspace to project`);}}catch(K){a.debug("Could not sync Python version from workspace:",K);}}if(!r.skipInstall){let A=await d$1(["init",n],{cwd:process.cwd()});if(A!==0&&process.exit(A),I){let _=f.dirname(I),N=f.join(_,".python-version"),K=f.join(n,".python-version");try{if(await b.pathExists(N)){let D=S.readFileSync(N,"utf-8");S.writeFileSync(K,D.trim()+`
|
|
3602
|
+
`),a.debug(`Re-synced Python version ${D.trim()} after init`);}}catch(D){a.debug("Could not re-sync Python version after init:",D);}}}}else await h(e$1,{skipGit:r.skipGit,dryRun:r.dryRun,yes:r.yes,userConfig:i$1,installMethod:r.installMethod,profile:r.profile});}catch(t){t instanceof d?(a.error(`
|
|
4292
3603
|
\u274C ${t.message}`),t.details&&a.warn(`\u{1F4A1} ${t.details}`),a.debug("Error code:",t.code)):(a.error(`
|
|
4293
|
-
\u274C An unexpected error occurred:`),console.error(t)),process.exit(1);}finally{
|
|
4294
|
-
`)),console.log(
|
|
4295
|
-
`)),console.log(
|
|
4296
|
-
`)),console.log(
|
|
4297
|
-
`)),console.log(
|
|
4298
|
-
`))
|
|
4299
|
-
|
|
4300
|
-
|
|
4301
|
-
`)
|
|
4302
|
-
`)
|
|
3604
|
+
\u274C An unexpected error occurred:`),console.error(t)),process.exit(1);}finally{Ae=null;}});Dr(Ce);yr(Ce);Ce.command("shell <action>").description("Shell helpers (activate virtualenv in current shell)").action(async e=>{e!=="activate"&&(console.log(l.red(`Unknown shell command: ${e}`)),process.exit(1));let r=process.cwd();function t(c){let p=c;for(;;){let d=f.join(p,".rapidkit","context.json");if(S.existsSync(d))return d;let m=f.dirname(p);if(m===p)break;p=m;}return null}let o=t(r);function i(c){let p=c;for(;;){let d=f.join(p,".venv"),m=f.join(p,".rapidkit","activate");if(S.existsSync(m)||S.existsSync(d))return {venv:d,activateFile:m};let h=f.dirname(p);if(h===p)break;p=h;}return null}let n=i(r);!o&&!n&&(console.log(l.yellow("No RapidKit project found in this directory")),process.exit(1));let a;n&&S.existsSync(n.activateFile)?a=n.activateFile:n&&S.existsSync(n.venv)?a=process.platform==="win32"?f.join(n.venv,"Scripts","activate"):f.join(n.venv,"bin","activate"):(console.log(l.yellow("No virtual environment found")),process.exit(1));let s=process.platform==="win32";console.log(s?`call "${a}"`:`. "${a}"`);});Ce.command("doctor [scope]").description("\u{1FA7A} Check RapidKit environment health").option("--workspace","Check entire workspace (including all projects)").option("--json","Output results in JSON format (for CI/CD pipelines)").option("--fix","Automatically fix common issues (with confirmation)").action(async(e,r)=>{e&&e!=="workspace"&&(console.log(l.red(`Unknown doctor scope: ${e}`)),console.log(l.gray("Available: workspace")),process.exit(1)),await mr({...r,workspace:r.workspace||e==="workspace"});});Ce.command("workspace <action>").description("Manage RapidKit workspaces (list, sync)").action(async e=>{if(e==="list"){let{listWorkspaces:r}=await import('./workspace-6SADFTND.js');await r();}else if(e==="sync"){let r=J(process.cwd());r||(console.log(l.red("\u274C Not inside a RapidKit workspace")),console.log(l.gray("\u{1F4A1} Run this command from within a workspace directory")),process.exit(1));let{syncWorkspaceProjects:t}=await import('./workspace-6SADFTND.js');console.log(l.cyan(`\u{1F4C2} Scanning workspace: ${f.basename(r)}`)),await t(r);}else console.log(l.red(`Unknown workspace action: ${e}`)),console.log(l.gray("Available: list, sync")),process.exit(1);});function Ln(){console.log(l.white(`Usage:
|
|
3605
|
+
`)),console.log(l.cyan(` npx rapidkit <workspace-name> [options]
|
|
3606
|
+
`)),console.log(l.bold("Quick start \u2014 workspace workflow:")),console.log(l.cyan(" npx rapidkit my-workspace ")+l.gray("# Create workspace (interactive profile picker)")),console.log(l.cyan(" cd my-workspace")),console.log(l.cyan(" rapidkit bootstrap ")+l.gray("# Bootstrap all runtime toolchains")),console.log(l.cyan(" rapidkit create project ")+l.gray("# Interactive kit picker")),console.log(l.cyan(" cd my-api")),console.log(l.cyan(` rapidkit init && rapidkit dev
|
|
3607
|
+
`)),console.log(l.bold("Workspace profiles (asked during creation):")),console.log(l.gray(" minimal Foundation files only \u2014 fastest bootstrap (default)")),console.log(l.gray(" python-only Python + Poetry (FastAPI, Django, ML)")),console.log(l.gray(" node-only Node.js runtime (NestJS, Express, Next.js)")),console.log(l.gray(" go-only Go runtime (Fiber, Gin, gRPC)")),console.log(l.gray(" polyglot Python + Node.js + Go multi-runtime")),console.log(l.gray(` enterprise Polyglot + governance + Sigstore
|
|
3608
|
+
`)),console.log(l.bold("Workspace commands (inside a workspace):")),console.log(l.gray(" rapidkit bootstrap [--profile <p>] Re-bootstrap toolchains")),console.log(l.gray(" rapidkit setup python|node|go [--warm-deps] Set up runtime (+ optional deps warm-up)")),console.log(l.gray(" rapidkit mirror [status|sync|verify|rotate] Registry mirror management")),console.log(l.gray(` rapidkit cache [status|clear|prune|repair] Package cache management
|
|
3609
|
+
`)),console.log(l.bold("Options (workspace creation):")),console.log(l.gray(" -y, --yes Skip prompts and use defaults")),console.log(l.gray(" --skip-git Skip git initialization")),console.log(l.gray(" --debug Enable debug logging")),console.log(l.gray(" --dry-run Show what would be created")),console.log(l.gray(" --create-workspace When creating a project outside a workspace: create and register a workspace in the current directory")),console.log(l.gray(" --no-workspace When creating a project outside a workspace: do not create a workspace")),console.log(l.gray(` --no-update-check Skip checking for updates
|
|
3610
|
+
`)),console.log(l.bold("Project commands (inside a project):")),console.log(l.gray(" rapidkit create project Scaffold a new project")),console.log(l.gray(" cd my-api Change directory to the new project")),console.log(l.gray(" rapidkit init Install project dependencies")),console.log(l.gray(" rapidkit dev Start dev server")),console.log(l.gray(" rapidkit build Build for production")),console.log(l.gray(` rapidkit test Run tests
|
|
3611
|
+
`)),console.log(l.bold("Flags clarification:")),console.log(l.gray(" --skip-install npm fast-path for lock/dependency steps")),console.log(l.gray(` --skip-essentials core flag for skipping essential module installation
|
|
3612
|
+
`)),console.log(l.gray(`Tip: set RAPIDKIT_SHOW_LEGACY=1 to show legacy template flags in help.
|
|
3613
|
+
`));}var Qr="__rapidkit_signal_handlers_registered__",Xr=globalThis;Xr[Qr]||(Xr[Qr]=true,process.on("SIGINT",async()=>{if(!Et){if(Et=true,console.log(l.yellow(`
|
|
3614
|
+
|
|
3615
|
+
\u26A0\uFE0F Interrupted by user`)),Ae&&await b.pathExists(Ae)){console.log(l.gray("Cleaning up partial installation..."));try{await b.remove(Ae),console.log(l.green("\u2713 Cleanup complete"));}catch(e){a.debug("Cleanup failed:",e);}}process.exit(130);}}),process.on("SIGTERM",async()=>{if(!Et){if(Et=true,a.debug("Received SIGTERM"),Ae&&await b.pathExists(Ae))try{await b.remove(Ae);}catch(e){a.debug("Cleanup failed:",e);}process.exit(143);}}));var qn=process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test",Fn=(()=>{let e=process.argv[1];if(!e)return false;try{return S.realpathSync(e)===S.realpathSync(fileURLToPath(import.meta.url))}catch{return f.resolve(e)===f.resolve(fileURLToPath(import.meta.url))}})(),Hn=!qn||Fn;Hn&&Dn().then(async e=>{if(!e){let r=process.argv.slice(2);if(process.env.RAPIDKIT_NPM_DEBUG_ARGS==="1"&&process.stderr.write(`[rapidkit-npm] argv=${JSON.stringify(r)}
|
|
3616
|
+
`),r[0]==="create"){let o=await xn(r);process.exit(o);}if(r[0]==="init"){let o=await io(r);process.exit(o);}if(r[0]==="bootstrap"){let o=await On(r);process.exit(o);}if(r[0]==="setup"){let o=await An(r);process.exit(o);}if(r[0]==="cache"){let o=await jn(r);process.exit(o);}if(r[0]==="mirror"){let o=await $n(r);process.exit(o);}if(r[0]==="dev"||r[0]==="test"||r[0]==="build"||r[0]==="start"){let o=r[0],i=Te(process.cwd()),n=J(process.cwd());if(n){let s=f.join(n,".rapidkit","policies.yml");if(await b.pathExists(s))try{let c=await S.promises.readFile(s,"utf-8");if(((c.match(/^\s*enforcement_mode:\s*(warn|strict)\s*$/m)??c.match(/^\s*mode:\s*(warn|strict)\s*$/m))?.[1]??"warn")==="strict"){let m=f.join(n,".rapidkit","toolchain.lock"),h=[];if(!await b.pathExists(m))h.push("toolchain.lock is missing \u2014 run `rapidkit bootstrap` first (strict mode requires a reproducible toolchain).");else try{let u=JSON.parse(await S.promises.readFile(m,"utf-8")).runtime??{};ge(i,process.cwd())&&!u.go?.version&&h.push("Go runtime version is not pinned in toolchain.lock \u2014 run `rapidkit setup go` first."),me(i,process.cwd())&&!u.node?.version&&h.push("Node runtime version is not pinned in toolchain.lock \u2014 run `rapidkit setup node` first."),fe(i,process.cwd())&&!u.python?.version&&h.push("Python runtime version is not pinned in toolchain.lock \u2014 run `rapidkit setup python` first.");}catch{}let w=f.join(n,".rapidkit","workspace.json");if(await b.pathExists(w))try{let u=JSON.parse(await S.promises.readFile(w,"utf-8")).profile??"";u==="python-only"&&(ge(i,process.cwd())||me(i,process.cwd()))&&h.push('Workspace profile is "python-only" but this project is not Python. Update the workspace profile or use a polyglot workspace.'),u==="node-only"&&(ge(i,process.cwd())||fe(i,process.cwd()))&&h.push('Workspace profile is "node-only" but this project is not Node. Update the workspace profile or use a polyglot workspace.'),u==="go-only"&&(fe(i,process.cwd())||me(i,process.cwd()))&&h.push('Workspace profile is "go-only" but this project is not Go. Update the workspace profile or use a polyglot workspace.');}catch{}if(h.length>0){console.log(l.red(`\u274C Strict policy violations block \`${o}\`:`));for(let g of h)console.log(l.red(` \u2022 ${g}`));console.log(l.gray("\u{1F4A1} Fix violations or switch to warn mode: set enforcement_mode: warn in .rapidkit/policies.yml")),process.exit(1);}}}catch{}}let a=await ro(process.cwd(),async()=>{if(ge(i,process.cwd())){let s=Me("go",{runCommandInCwd:le,runCoreRapidkit:d$1});return o==="dev"?(await s.runDev(process.cwd())).exitCode:o==="test"?(await s.runTest(process.cwd())).exitCode:o==="build"?(await s.runBuild(process.cwd())).exitCode:(await s.runStart(process.cwd())).exitCode}if(me(i,process.cwd()))return o==="dev"?await He("dev",process.cwd()):o==="test"?await He("test",process.cwd()):o==="build"?await He("build",process.cwd()):await He("start",process.cwd());if(fe(i,process.cwd())){let s=Me("python",{runCommandInCwd:le,runCoreRapidkit:d$1});return o==="dev"?(await s.runDev(process.cwd())).exitCode:o==="test"?(await s.runTest(process.cwd())).exitCode:o==="build"?(await s.runBuild(process.cwd())).exitCode:(await s.runStart(process.cwd())).exitCode}return -1});a.ok||process.exit(a.code),a.value>=0&&process.exit(a.value);}if(r[0]==="add"||r[0]==="module"&&r[1]==="add"){let o=Te(process.cwd());(o?.runtime==="go"||o?.module_support===false)&&(console.error(l.red("\u274C RapidKit modules are not available for Go projects.")),console.error(l.gray(" The module system requires Python and is only supported for FastAPI and NestJS projects.")),process.exit(1));}let t=await Mn(r);if(process.env.RAPIDKIT_NPM_DEBUG_ARGS==="1"&&process.stderr.write(`[rapidkit-npm] shouldForwardToCore=${t}
|
|
3617
|
+
`),t){let o=await d$1(r,{cwd:process.cwd()});process.exit(o);}Ce.parse();}});export{On as handleBootstrapCommand,jn as handleCacheCommand,xn as handleCreateOrFallback,io as handleInitCommand,$n as handleMirrorCommand,An as handleSetupCommand,Mn as shouldForwardToCore};
|