rapidkit 0.19.0 → 0.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +74 -74
- package/dist/package.json +3 -2
- package/package.json +3 -2
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import v from'path';import {fileURLToPath,pathToFileURL}from'url';import m from'chalk';import {execa}from'execa';import {createRequire}from'module';import
|
|
3
|
-
[${o}/${t}]`),m.white(n));}},y=new ot;});function $t(e){let t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/);if(!t)return null;let n=t[4]?t[4].split(".").map(r=>r.match(/^\d+$/)?Number(r):r):[];return {major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),prerelease:n}}function
|
|
2
|
+
import v from'path';import {fileURLToPath,pathToFileURL}from'url';import m from'chalk';import {execa}from'execa';import {createRequire}from'module';import rn from'crypto';import*as te from'os';import te__default from'os';import*as b from'fs-extra';import b__default from'fs-extra';import W,{promises}from'fs';import Re from'ora';import {Command,Option}from'commander';import gt from'inquirer';import {exec,spawn}from'child_process';import Xo from'validate-npm-package-name';import Mn from'nunjucks';import qn from'openai';import {promisify}from'util';var Go=Object.defineProperty;var se=(e,o)=>()=>(e&&(o=e(e=0)),o);var tt=(e,o)=>{for(var t in o)Go(e,t,{get:o[t],enumerable:true});};var j=se(()=>{});var ot,y,ce=se(()=>{j();ot=class{debugEnabled=false;setDebug(o){this.debugEnabled=o;}debug(o,...t){this.debugEnabled&&console.log(m.gray(`[DEBUG] ${o}`),...t);}info(o,...t){console.log(m.blue(o),...t);}success(o,...t){console.log(m.green(o),...t);}warn(o,...t){console.log(m.yellow(o),...t);}error(o,...t){console.error(m.red(o),...t);}step(o,t,n){console.log(m.cyan(`
|
|
3
|
+
[${o}/${t}]`),m.white(n));}},y=new ot;});function $t(e){let t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/);if(!t)return null;let n=t[4]?t[4].split(".").map(r=>r.match(/^\d+$/)?Number(r):r):[];return {major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),prerelease:n}}function Jo(e,o){let t=$t(e),n=$t(o);if(!t||!n)return 0;if(t.major!==n.major)return t.major>n.major?1:-1;if(t.minor!==n.minor)return t.minor>n.minor?1:-1;if(t.patch!==n.patch)return t.patch>n.patch?1:-1;if(t.prerelease.length===0&&n.prerelease.length===0)return 0;if(t.prerelease.length===0)return 1;if(n.prerelease.length===0)return -1;let r=Math.max(t.prerelease.length,n.prerelease.length);for(let i=0;i<r;i+=1){let s=t.prerelease[i],a=n.prerelease[i];if(s===void 0)return -1;if(a===void 0)return 1;if(s===a)continue;let c=typeof s=="number",l=typeof a=="number";return c&&l?s>a?1:-1:c?-1:l||String(s)>String(a)?1:-1}return 0}async function _t(){try{y.debug("Checking for updates...");let{stdout:e}=await execa("npm",["view",Uo,"version"],{timeout:3e3}),o=e.trim();o&&Jo(o,nt)>0?(console.log(m.yellow(`
|
|
4
4
|
\u26A0\uFE0F Update available: ${nt} \u2192 ${o}`)),console.log(m.cyan(`Run: npm install -g rapidkit@latest
|
|
5
|
-
`))):y.debug("You are using the latest version");}catch{y.debug("Could not check for updates");}}function q(){return nt}var
|
|
5
|
+
`))):y.debug("You are using the latest version");}catch{y.debug("Could not check for updates");}}function q(){return nt}var Uo,Bo,Ho,nt,Pe=se(()=>{j();ce();Uo="rapidkit",Bo=createRequire(import.meta.url),Ho=Bo("../package.json"),nt=Ho?.version??"0.0.0";});var nn,_e,it=se(()=>{j();nn=["version","project","create","init","dev","start","build","test","lint","format","add","list","info","upgrade","diff","doctor","license","commands","reconcile","rollback","uninstall","checkpoint","optimize","snapshot","frameworks","modules","merge"],_e=new Set(nn);});var lt={};tt(lt,{__test__:()=>yn,checkRapidkitCoreAvailable:()=>Ut,getCachedCoreTopLevelCommands:()=>ct,getCoreTopLevelCommands:()=>gn,getModulesCatalog:()=>hn,resolveRapidkitPython:()=>he,runCoreRapidkit:()=>Q,runCoreRapidkitCapture:()=>fe});function Kt(e){if(e instanceof z)switch(e.code){case "PYTHON_NOT_FOUND":return "RapidKit (npm) could not find Python (python3/python) on your PATH.\nInstall Python 3.10+ and ensure `python3` is available, then retry.\nTip: if you are inside a RapidKit project, use the local ./rapidkit launcher.";case "BRIDGE_VENV_CREATE_FAILED":return `RapidKit (npm) failed to create its bridge virtual environment.
|
|
6
6
|
Ensure Python venv support is installed (e.g., python3-venv).
|
|
7
7
|
Details: ${e.message}`;case "BRIDGE_PIP_BOOTSTRAP_FAILED":return `RapidKit (npm) could not bootstrap pip inside the bridge virtual environment.
|
|
8
8
|
Install python3-venv/python3-pip and retry.
|
|
@@ -10,18 +10,18 @@ Details: ${e.message}`;case "BRIDGE_PIP_UPGRADE_FAILED":return `RapidKit (npm) c
|
|
|
10
10
|
Check your network/proxy or disable RAPIDKIT_BRIDGE_UPGRADE_PIP.
|
|
11
11
|
Details: ${e.message}`;case "BRIDGE_PIP_INSTALL_FAILED":return `RapidKit (npm) could not install rapidkit-core in the bridge virtual environment.
|
|
12
12
|
Check your network/proxy, or install manually with: pipx install rapidkit-core.
|
|
13
|
-
Details: ${e.message}`;default:return `RapidKit (npm) bridge error: ${e.message}`}return `RapidKit (npm) failed to run the Python core engine: ${e instanceof Error?e.message:String(e)}`}function rt(){let e=process.env.RAPIDKIT_CORE_PYTHON_PACKAGE;return e&&e.trim()?e.trim():"rapidkit-core"}function
|
|
14
|
-
`);};try{t("probing interpreter-specific rapidkit script");let r=((await execa(e,["-c","import sysconfig, os; print(os.path.join(sysconfig.get_path('scripts'), 'rapidkit'))"],{reject:!1,stdio:"pipe",timeout:2e3})).stdout??"").toString().trim();if(t(`script path: ${r}`),r)try{if(await b.pathExists(r)){t(`found script at ${r}; invoking --version --json`);let i=await execa(r,["--version","--json"],{reject:!1,stdio:"pipe",timeout:4e3});if(t(`script exitCode=${i.exitCode}`),i.exitCode===0){let s=(i.stdout??"").toString().trim();try{let a=JSON.parse(s),c=!!a&&typeof a=="object"&&a!==null&&"version"in a;if(t(`script JSON parse ok=${c}`),c)return !0}catch{t("script output not valid JSON");}}}}catch(i){t(`interpreter-specific script probe failed: ${String(i)}`);}}catch(n){t(`interpreter-specific script probe error: ${String(n)}`);}try{t('probing importlib.find_spec("rapidkit")');let n=await execa(e,["-c","import importlib.util; print(1 if importlib.util.find_spec('rapidkit') else 0)"],{reject:!1,stdio:"pipe",timeout:2e3});if(t(`import probe exitCode=${n.exitCode} stdout=${(n.stdout??"").toString().trim()}`),n.exitCode===0&&(n.stdout??"").toString().trim()==="1")return !0}catch(n){t(`import probe error: ${String(n)}`);}try{t("probing python -m rapidkit");let n=await execa(e,["-m","rapidkit","--version","--json"],{reject:!1,stdio:"pipe",timeout:8e3});if(t(`-m probe exitCode=${n.exitCode}`),n.exitCode===0)return !0}catch(n){t(`-m probe error: ${String(n)}`);}try{t("probing PATH for rapidkit executables");let n=(process.env.PATH??"").split(v.delimiter).filter(Boolean);for(let r of n){let i=v.join(r,process.platform==="win32"?"rapidkit.exe":"rapidkit");try{if(await b.pathExists(i)){t(`found candidate on PATH: ${i}; invoking --version --json`);let s=await execa(i,["--version","--json"],{reject:!1,stdio:"pipe",timeout:4e3});if(t(`candidate exitCode=${s.exitCode}`),s.exitCode===0){let a=(s.stdout??"").toString().trim();try{let c=JSON.parse(a);if(c&&typeof c=="object"&&c!==null&&"version"in c)return !0}catch{t("candidate output not valid JSON, skipping");}}}}catch(s){t(`error probing candidate ${i}: ${String(s)}`);}}return t("no valid rapidkit found on PATH"),!1}catch(n){return t(`PATH probe error: ${String(n)}`),false}}async function st(e){let o=(e??"").toString().trim();if(!o)return false;try{let t=JSON.parse(o);return !!t&&typeof t=="object"&&t!==null&&"version"in t}catch{return false}}async function
|
|
13
|
+
Details: ${e.message}`;default:return `RapidKit (npm) bridge error: ${e.message}`}return `RapidKit (npm) failed to run the Python core engine: ${e instanceof Error?e.message:String(e)}`}function rt(){let e=process.env.RAPIDKIT_CORE_PYTHON_PACKAGE;return e&&e.trim()?e.trim():"rapidkit-core"}function sn(){let e=rt(),o=process.env.RAPIDKIT_CORE_PYTHON_PACKAGE_ID,t=o&&o.trim()?`${e}|${o.trim()}`:e;return rn.createHash("sha256").update(t).digest("hex").slice(0,12)}function Fe(){let e=process.env.XDG_CACHE_HOME;return e&&e.trim()?e:v.join(te__default.homedir(),".cache")}function an(){return v.join(Fe(),"rapidkit","npm-bridge","venv")}function Lt(){let e=sn();return v.join(Fe(),"rapidkit","npm-bridge",`venv-${e}`)}function Dt(e){return process.platform==="win32"?v.join(e,"Scripts","python.exe"):v.join(e,"bin","python")}function Nt(e){return process.platform==="win32"?v.join(e,"Scripts","rapidkit.exe"):v.join(e,"bin","rapidkit")}function cn(e){return /[<>=!~]=|@|\.whl$|\.tar\.gz$|\.zip$|git\+|https?:\/\//.test(e)}function ln(e){return v.dirname(v.dirname(e))}function Gt(){return v.join(Fe(),"rapidkit","npm-bridge","core-commands.json")}async function Wt(e){let o=!!process.env.RAPIDKIT_DEBUG,t=n=>{o&&process.stderr.write(`[DEBUG] tryRapidkit(${e}): ${n}
|
|
14
|
+
`);};try{t("probing interpreter-specific rapidkit script");let r=((await execa(e,["-c","import sysconfig, os; print(os.path.join(sysconfig.get_path('scripts'), 'rapidkit'))"],{reject:!1,stdio:"pipe",timeout:2e3})).stdout??"").toString().trim();if(t(`script path: ${r}`),r)try{if(await b.pathExists(r)){t(`found script at ${r}; invoking --version --json`);let i=await execa(r,["--version","--json"],{reject:!1,stdio:"pipe",timeout:4e3});if(t(`script exitCode=${i.exitCode}`),i.exitCode===0){let s=(i.stdout??"").toString().trim();try{let a=JSON.parse(s),c=!!a&&typeof a=="object"&&a!==null&&"version"in a;if(t(`script JSON parse ok=${c}`),c)return !0}catch{t("script output not valid JSON");}}}}catch(i){t(`interpreter-specific script probe failed: ${String(i)}`);}}catch(n){t(`interpreter-specific script probe error: ${String(n)}`);}try{t('probing importlib.find_spec("rapidkit")');let n=await execa(e,["-c","import importlib.util; print(1 if importlib.util.find_spec('rapidkit') else 0)"],{reject:!1,stdio:"pipe",timeout:2e3});if(t(`import probe exitCode=${n.exitCode} stdout=${(n.stdout??"").toString().trim()}`),n.exitCode===0&&(n.stdout??"").toString().trim()==="1")return !0}catch(n){t(`import probe error: ${String(n)}`);}try{t("probing python -m rapidkit");let n=await execa(e,["-m","rapidkit","--version","--json"],{reject:!1,stdio:"pipe",timeout:8e3});if(t(`-m probe exitCode=${n.exitCode}`),n.exitCode===0)return !0}catch(n){t(`-m probe error: ${String(n)}`);}try{t("probing PATH for rapidkit executables");let n=(process.env.PATH??"").split(v.delimiter).filter(Boolean);for(let r of n){let i=v.join(r,process.platform==="win32"?"rapidkit.exe":"rapidkit");try{if(await b.pathExists(i)){t(`found candidate on PATH: ${i}; invoking --version --json`);let s=await execa(i,["--version","--json"],{reject:!1,stdio:"pipe",timeout:4e3});if(t(`candidate exitCode=${s.exitCode}`),s.exitCode===0){let a=(s.stdout??"").toString().trim();try{let c=JSON.parse(a);if(c&&typeof c=="object"&&c!==null&&"version"in c)return !0}catch{t("candidate output not valid JSON, skipping");}}}}catch(s){t(`error probing candidate ${i}: ${String(s)}`);}}return t("no valid rapidkit found on PATH"),!1}catch(n){return t(`PATH probe error: ${String(n)}`),false}}async function st(e){let o=(e??"").toString().trim();if(!o)return false;try{let t=JSON.parse(o);return !!t&&typeof t=="object"&&t!==null&&"version"in t}catch{return false}}async function dn(e){let o=process.platform==="win32",t=o?v.join(".venv","Scripts","rapidkit.exe"):v.join(".venv","bin","rapidkit"),n=o?v.join(".venv","Scripts","python.exe"):v.join(".venv","bin","python"),r=e;for(let i=0;i<25;i+=1){let s=v.join(r,t);if(await b.pathExists(s)){let l=await execa(s,["--version","--json"],{reject:false,stdio:"pipe",timeout:1500,cwd:r});if(l.exitCode===0&&await st(l.stdout))return {cmd:s,baseArgs:[]}}let a=v.join(r,n);if(await b.pathExists(a)){let l=await execa(a,["-m","rapidkit","--version","--json"],{reject:false,stdio:"pipe",timeout:1500,cwd:r});if(l.exitCode===0&&await st(l.stdout))return {cmd:a,baseArgs:["-m","rapidkit"]}}let c=v.dirname(r);if(c===r)break;r=c;}return null}async function pn(e){try{let o=v.join(e,".python-version");if(await b.pathExists(o)){let n=(await b.readFile(o,"utf-8")).trim();if(n)return n}}catch{}try{let o=v.join(e,".rapidkit-workspace");if(await b.pathExists(o)){let t=await b.readFile(o,"utf-8"),n=JSON.parse(t);if(n.pythonVersion)return n.pythonVersion}}catch{}return null}async function Vt(e){if(e&&e.trim())try{let i=await dn(e);if(i){let s=v.dirname(i.cmd).includes(".venv")?v.dirname(v.dirname(v.dirname(i.cmd))):v.dirname(i.cmd),a=await pn(s);return a&&(process.env.PYENV_VERSION=a),i}}catch{}let o=await he();if(o.kind==="venv"){let i=ln(o.pythonPath),s=Nt(i);return await b.pathExists(s)?{cmd:s,baseArgs:[]}:{cmd:o.pythonPath,baseArgs:["-m","rapidkit"]}}try{if((await execa(o.cmd,["-m","rapidkit","--version","--json"],{reject:!1,stdio:"pipe",timeout:4e3})).exitCode===0)return {cmd:o.cmd,baseArgs:["-m","rapidkit"]}}catch{}try{let s=((await execa(o.cmd,["-c","import sysconfig, os; print(os.path.join(sysconfig.get_path('scripts'), 'rapidkit'))"],{reject:!1,stdio:"pipe",timeout:2e3})).stdout??"").toString().trim();if(s&&await b.pathExists(s))try{let a=await execa(s,["--version","--json"],{reject:!1,stdio:"pipe",timeout:4e3});if(a.exitCode===0&&await st(a.stdout))return {cmd:s,baseArgs:[]}}catch{}}catch{}let t=Lt(),n=await Te(o.cmd),r=Nt(t);return await b.pathExists(r)?{cmd:r,baseArgs:[]}:{cmd:n,baseArgs:["-m","rapidkit"]}}async function at(){for(let e of ["python3","python"])try{return await execa(e,["--version"],{reject:!1,stdio:"pipe",timeout:2e3}),e}catch{}return null}async function Ut(){let e=!!process.env.RAPIDKIT_DEBUG,o=t=>{e&&process.stderr.write(`[DEBUG] checkRapidkitCore: ${t}
|
|
15
15
|
`);};for(let t of ["python3","python","python3.10","python3.11","python3.12"])try{o(`Method 1: trying ${t} import`);let n=await execa(t,["-c","import rapidkit_core; print(1)"],{reject:!1,stdio:"pipe",timeout:3e3});if(n.exitCode===0&&n.stdout?.trim()==="1")return o(`\u2713 Found via ${t} import`),!0}catch{continue}for(let t of ["python3","python"])try{o(`Method 2: trying ${t} -m pip show`);let n=await execa(t,["-m","pip","show","rapidkit-core"],{reject:!1,stdio:"pipe",timeout:3e3});if(n.exitCode===0&&n.stdout?.includes("Name: rapidkit-core"))return o(`\u2713 Found via ${t} -m pip show`),!0}catch{continue}for(let t of ["pip","pip3"])try{o(`Method 3: trying ${t} show`);let n=await execa(t,["show","rapidkit-core"],{reject:!1,stdio:"pipe",timeout:3e3});if(n.exitCode===0&&n.stdout?.includes("Name: rapidkit-core"))return o(`\u2713 Found via ${t} show`),!0}catch{continue}try{o("Method 4: checking pyenv versions");let t=await execa("pyenv",["versions","--bare"],{reject:!1,stdio:"pipe",timeout:3e3});if(t.exitCode===0&&t.stdout){let n=t.stdout.split(`
|
|
16
|
-
`).filter(r=>r.trim());o(`Found pyenv versions: ${n.join(", ")}`);for(let r of n){let i=process.env.PYENV_ROOT||v.join(te__default.homedir(),".pyenv"),s=v.join(i,"versions",r.trim(),"bin","pip");try{let a=await execa(s,["show","rapidkit-core"],{reject:!1,stdio:"pipe",timeout:3e3});if(a.exitCode===0&&a.stdout?.includes("Name: rapidkit-core"))return o(`\u2713 Found in pyenv ${r}`),!0}catch{try{let a=await execa("bash",["-c",`PYENV_VERSION=${r.trim()} pyenv exec pip show rapidkit-core`],{reject:!1,stdio:"pipe",timeout:3e3});if(a.exitCode===0&&a.stdout?.includes("Name: rapidkit-core"))return o(`\u2713 Found in pyenv ${r} via PYENV_VERSION`),!0}catch{continue}}}}}catch{o("pyenv not available");}for(let t of ["python3","python"])try{o(`Method 5: checking ${t} user site`);let n=await execa(t,["-m","site","--user-site"],{reject:!1,stdio:"pipe",timeout:3e3});if(n.exitCode===0&&n.stdout){let r=n.stdout.trim(),i=v.join(r,"rapidkit_core");if(await b.pathExists(i))return o("\u2713 Found in user site-packages"),!0}}catch{continue}try{o("Method 6: checking pipx");let t=await execa("pipx",["list"],{reject:!1,stdio:"pipe",timeout:3e3});if(t.exitCode===0&&t.stdout?.includes("rapidkit-core"))return o("\u2713 Found via pipx"),!0}catch{o("pipx not available");}try{if(o("Method 7: checking poetry"),(await execa("poetry",["show","rapidkit-core"],{reject:!1,stdio:"pipe",timeout:3e3})).exitCode===0)return o("\u2713 Found via poetry"),!0}catch{o("poetry check failed");}try{o("Method 8: checking conda");let t=await execa("conda",["list","rapidkit-core"],{reject:!1,stdio:"pipe",timeout:3e3});if(t.exitCode===0&&t.stdout?.includes("rapidkit-core"))return o("\u2713 Found via conda"),!0}catch{o("conda not available");}return o("\u2717 Not found in any environment"),false}async function
|
|
17
|
-
`),
|
|
18
|
-
${
|
|
16
|
+
`).filter(r=>r.trim());o(`Found pyenv versions: ${n.join(", ")}`);for(let r of n){let i=process.env.PYENV_ROOT||v.join(te__default.homedir(),".pyenv"),s=v.join(i,"versions",r.trim(),"bin","pip");try{let a=await execa(s,["show","rapidkit-core"],{reject:!1,stdio:"pipe",timeout:3e3});if(a.exitCode===0&&a.stdout?.includes("Name: rapidkit-core"))return o(`\u2713 Found in pyenv ${r}`),!0}catch{try{let a=await execa("bash",["-c",`PYENV_VERSION=${r.trim()} pyenv exec pip show rapidkit-core`],{reject:!1,stdio:"pipe",timeout:3e3});if(a.exitCode===0&&a.stdout?.includes("Name: rapidkit-core"))return o(`\u2713 Found in pyenv ${r} via PYENV_VERSION`),!0}catch{continue}}}}}catch{o("pyenv not available");}for(let t of ["python3","python"])try{o(`Method 5: checking ${t} user site`);let n=await execa(t,["-m","site","--user-site"],{reject:!1,stdio:"pipe",timeout:3e3});if(n.exitCode===0&&n.stdout){let r=n.stdout.trim(),i=v.join(r,"rapidkit_core");if(await b.pathExists(i))return o("\u2713 Found in user site-packages"),!0}}catch{continue}try{o("Method 6: checking pipx");let t=await execa("pipx",["list"],{reject:!1,stdio:"pipe",timeout:3e3});if(t.exitCode===0&&t.stdout?.includes("rapidkit-core"))return o("\u2713 Found via pipx"),!0}catch{o("pipx not available");}try{if(o("Method 7: checking poetry"),(await execa("poetry",["show","rapidkit-core"],{reject:!1,stdio:"pipe",timeout:3e3})).exitCode===0)return o("\u2713 Found via poetry"),!0}catch{o("poetry check failed");}try{o("Method 8: checking conda");let t=await execa("conda",["list","rapidkit-core"],{reject:!1,stdio:"pipe",timeout:3e3});if(t.exitCode===0&&t.stdout?.includes("rapidkit-core"))return o("\u2713 Found via conda"),!0}catch{o("conda not available");}return o("\u2717 Not found in any environment"),false}async function Te(e){let o=Lt(),t=an(),n=rt(),r=[o];!cn(n)&&!await b.pathExists(o)&&await b.pathExists(t)&&r.push(t);for(let g of r){let w=Dt(g);if(await b.pathExists(w))try{let h=await execa(w,["-c","import importlib.util; print(1 if importlib.util.find_spec('rapidkit') else 0)"],{reject:!1,stdio:"pipe",timeout:2e3});if(h.exitCode===0&&(h.stdout??"").toString().trim()==="1")return w;await b.remove(g);}catch{await b.remove(g);}}let i=o,s={...process.env,PIP_DISABLE_PIP_VERSION_CHECK:"1",PIP_NO_PYTHON_VERSION_WARNING:"1"},a=Math.max(0,Number(process.env.RAPIDKIT_BRIDGE_PIP_RETRY??"2")),c=Math.max(200,Number(process.env.RAPIDKIT_BRIDGE_PIP_RETRY_DELAY_MS??"800")),l=Math.max(1e4,Number(process.env.RAPIDKIT_BRIDGE_PIP_TIMEOUT_MS??"120000")),d=g=>new Promise(w=>setTimeout(w,g)),p=async(g,w,h)=>{let x=await execa(g,w,{reject:false,stdio:["ignore","pipe","inherit"],env:s,timeout:h});if(x.exitCode===0)return;let T=(x.stdout??"").toString(),F=(x.stderr??"").toString(),V=[T,F].filter(Boolean).join(`
|
|
17
|
+
`),xe=V?`${g} ${w.join(" ")}
|
|
18
|
+
${V}`:`${g} ${w.join(" ")}`;throw new Error(xe)},u=async(g,w,h)=>{let x=0;for(;;)try{await p(g,w,h);return}catch(T){if(x>=a)throw T;let F=Math.floor(Math.random()*200),V=c*Math.pow(2,x)+F;x+=1,await d(V);}};try{await b.ensureDir(v.dirname(i));try{await p(e,["-m","venv",i],6e4);}catch(h){let x=h instanceof Error?h.message:String(h);throw new z("BRIDGE_VENV_CREATE_FAILED",x)}let g=Dt(i);if((await execa(g,["-m","pip","--version"],{reject:!1,stdio:"pipe",timeout:2e3})).exitCode!==0&&(await execa(g,["-m","ensurepip","--default-pip"],{reject:!1,stdio:["ignore","pipe","inherit"],env:s,timeout:6e4})).exitCode!==0)throw new z("BRIDGE_PIP_BOOTSTRAP_FAILED","ensurepip failed; install python3-venv/python3-pip and retry.");if(process.env.RAPIDKIT_BRIDGE_UPGRADE_PIP==="1")try{await u(g,["-m","pip","install","-U","pip"],l);}catch(h){let x=h instanceof Error?h.message:String(h);throw new z("BRIDGE_PIP_UPGRADE_FAILED",x)}try{await u(g,["-m","pip","install","-U",rt()],l);}catch(h){let x=h instanceof Error?h.message:String(h);throw new z("BRIDGE_PIP_INSTALL_FAILED",x)}return g}catch(g){if(g instanceof z)throw g;let w=g instanceof Error?g.message:String(g);throw new z("BRIDGE_VENV_BOOTSTRAP_FAILED",w)}}async function he(){if(process.env.RAPIDKIT_BRIDGE_FORCE_VENV==="1"){let t=await at();if(!t)throw new z("PYTHON_NOT_FOUND","No Python interpreter found (python3/python).");return {kind:"venv",pythonPath:await Te(t)}}for(let t of ["python3","python"])if(await Wt(t))return {kind:"system",cmd:t};let e=await at();if(!e)throw new z("PYTHON_NOT_FOUND","No Python interpreter found (python3/python).");return {kind:"venv",pythonPath:await Te(e)}}async function Q(e,o){try{let t=await Vt(o?.cwd),n=t.cmd,r=[...t.baseArgs,...e],i=await execa(n,r,{cwd:o?.cwd,env:{...process.env,...o?.env},reject:!1,stdio:"inherit"});return typeof i.exitCode=="number"?i.exitCode:1}catch(t){return process.stderr.write(`${Kt(t)}
|
|
19
19
|
`),1}}async function fe(e,o){try{let t=await Vt(o?.cwd),n=t.cmd,r=[...t.baseArgs,...e],i=await execa(n,r,{cwd:o?.cwd,env:{...process.env,...o?.env},reject:!1,stdio:"pipe"});return {exitCode:typeof i.exitCode=="number"?i.exitCode:1,stdout:(i.stdout??"").toString(),stderr:(i.stderr??"").toString()}}catch(t){return {exitCode:1,stdout:"",stderr:`${Kt(t)}
|
|
20
20
|
`}}}function Bt(e){let o=new Set,t=e.split(`
|
|
21
|
-
`),n=false;for(let r of t){let i=r.replace(/\r$/,"");if(!n){/^\s*Commands:\s*$/i.test(i)&&(n=true);let c=i.match(/^\s*rapidkit\s+([a-z0-9_-]+)\b/i);if(c){let l=c[1].trim();l&&!l.startsWith("-")&&o.add(l);}continue}if(!i.trim())break;if(/^\s*(Options|Arguments|Usage|Commands)\s*:/i.test(i))continue;let s=i.match(/^\s*([a-z0-9][a-z0-9_-]*)\b/i);if(!s)continue;let a=s[1].trim();a&&!a.startsWith("-")&&o.add(a);}return o}async function Ht(){let e=Gt();if(!await b.pathExists(e))return null;try{let o=await b.readJson(e);if(o&&o.schema_version===1&&Array.isArray(o.commands))return o}catch{}return null}async function Mt(e){let o=Gt();await b.ensureDir(v.dirname(o)),await b.writeJson(o,e,{spaces:2});}async function
|
|
22
|
-
`,"utf-8");}async function
|
|
21
|
+
`),n=false;for(let r of t){let i=r.replace(/\r$/,"");if(!n){/^\s*Commands:\s*$/i.test(i)&&(n=true);let c=i.match(/^\s*rapidkit\s+([a-z0-9_-]+)\b/i);if(c){let l=c[1].trim();l&&!l.startsWith("-")&&o.add(l);}continue}if(!i.trim())break;if(/^\s*(Options|Arguments|Usage|Commands)\s*:/i.test(i))continue;let s=i.match(/^\s*([a-z0-9][a-z0-9_-]*)\b/i);if(!s)continue;let a=s[1].trim();a&&!a.startsWith("-")&&o.add(a);}return o}async function Ht(){let e=Gt();if(!await b.pathExists(e))return null;try{let o=await b.readJson(e);if(o&&o.schema_version===1&&Array.isArray(o.commands))return o}catch{}return null}async function Mt(e){let o=Gt();await b.ensureDir(v.dirname(o)),await b.writeJson(o,e,{spaces:2});}async function un(){let e=await fe(["version","--json"],{cwd:process.cwd()});if(e.exitCode===0)try{let t=JSON.parse(e.stdout)?.version;return typeof t=="string"?t:void 0}catch{return}}async function mn(){let e=await fe(["commands","--json"],{cwd:process.cwd()});if(e.exitCode!==0)return null;try{let o=JSON.parse(e.stdout);if(o?.schema_version!==1||!Array.isArray(o.commands))return null;let t=o.commands.filter(n=>typeof n=="string");return t.length?t:null}catch{return null}}async function gn(){let o=Date.now(),t=await Ht(),n=await un(),r=!!t?.commands?.length;if(r&&o-t.fetched_at<864e5&&(!n||!t.rapidkit_version||t.rapidkit_version===n))return new Set(t.commands);let i=await mn();if(i?.length){let l=Array.from(new Set(i)).sort();return await Mt({schema_version:1,fetched_at:o,rapidkit_version:n,commands:l}),new Set(l)}let s=await fe(["--help"],{cwd:process.cwd()});if(s.exitCode!==0)return r&&t?.commands?new Set(t.commands):new Set(_e);let a=Bt(s.stdout);if(a.size===0)return new Set(_e);let c=Array.from(a).sort();return await Mt({schema_version:1,fetched_at:o,rapidkit_version:n,commands:c}),a}async function ct(){let o=Date.now(),t=await Ht();return !t||o-t.fetched_at>=864e5||!t.commands?.length?null:new Set(t.commands)}function Jt(){return v.join(Fe(),"rapidkit","npm-bridge","modules-catalog.json")}async function fn(){let e=Jt();if(!await b.pathExists(e))return null;try{let o=await b.readJson(e);if(o&&o.schema_version===1&&Array.isArray(o.modules))return o}catch{}return null}async function Ot(e){let o=Jt();await b.ensureDir(v.dirname(o)),await b.writeJson(o,e,{spaces:2});}function Tt(e){try{return JSON.parse(e)}catch{return null}}async function hn(e={}){let o=typeof e.ttlMs=="number"?e.ttlMs:18e5,t=Date.now(),n=await fn();if(n?.fetched_at&&t-n.fetched_at<o)return n;let r=["modules","list","--json-schema","1"];e.category&&r.push("--category",e.category),e.tag&&r.push("--tag",e.tag),e.detailed&&r.push("--detailed");let i=await fe(r,{cwd:e.cwd,env:e.env});if(i.exitCode===0){let a=Tt(i.stdout);if(a&&a.schema_version===1&&Array.isArray(a.modules)){let c={...a,fetched_at:t};return await Ot(c),c}}let s=await fe(["modules","list","--json"],{cwd:e.cwd,env:e.env});if(s.exitCode===0){let a=Tt(s.stdout);if(Array.isArray(a)){let c={schema_version:1,generated_at:new Date().toISOString(),filters:{category:e.category??null,tag:e.tag??null,detailed:!!e.detailed},stats:{total:a.length,returned:a.length,invalid:0},modules:a,source:"legacy-json",fetched_at:t};return await Ot(c),c}}return n||null}var z,yn,Ke=se(()=>{j();it();z=class extends Error{code;constructor(o,t){super(t),this.code=o;}};yn={pickSystemPython:at,ensureBridgeVenv:Te,parseCoreCommandsFromHelp:Bt,tryRapidkit:Wt,checkRapidkitCoreAvailable:Ut};});var qt={};tt(qt,{createNpmWorkspaceMarker:()=>pt,isValidWorkspaceMarker:()=>kn,readWorkspaceMarker:()=>dt,updateWorkspaceMetadata:()=>wn,writeWorkspaceMarker:()=>Ge});async function dt(e){let o=v.join(e,".rapidkit-workspace");try{if(await b.pathExists(o))return await b.readJson(o)}catch{return null}return null}async function Ge(e,o){let t=v.join(e,".rapidkit-workspace"),n=await dt(e);n?.metadata&&(o.metadata={...n.metadata,...o.metadata}),await b.outputFile(t,JSON.stringify(o,null,2)+`
|
|
22
|
+
`,"utf-8");}async function wn(e,o){let t=await dt(e);return t?(t.metadata={...t.metadata,...o,vscode:o.vscode?{...t.metadata?.vscode,...o.vscode}:t.metadata?.vscode,npm:o.npm?{...t.metadata?.npm,...o.npm}:t.metadata?.npm,python:o.python?{...t.metadata?.python,...o.python}:t.metadata?.python},await Ge(e,t),true):false}function pt(e,o,t){return {signature:"RAPIDKIT_WORKSPACE",createdBy:"rapidkit-npm",version:o,createdAt:new Date().toISOString(),name:e,metadata:{npm:{packageVersion:o,installMethod:t,lastUsedAt:new Date().toISOString()}}}}function kn(e){if(!e||typeof e!="object")return false;let o=e;return o.signature==="RAPIDKIT_WORKSPACE"&&typeof o.createdBy=="string"&&typeof o.version=="string"&&typeof o.createdAt=="string"&&typeof o.name=="string"}var ut=se(()=>{j();});var oe={};tt(oe,{createProject:()=>$n,createWorkspace:()=>xn,listWorkspaces:()=>Rn,registerProjectInWorkspace:()=>bn,registerWorkspace:()=>zt,syncWorkspaceProjects:()=>vn});async function zt(e,o){try{let t=process.env.XDG_CONFIG_HOME||process.env.APPDATA||v.join(te__default.homedir(),".config"),n=process.platform==="win32"?v.join(t,"rapidkit"):v.join(te__default.homedir(),".rapidkit"),r=v.join(n,"workspaces.json");await promises.mkdir(n,{recursive:!0});let i={workspaces:[]};try{let a=await promises.readFile(r,"utf8"),c=JSON.parse(a);c&&Array.isArray(c.workspaces)&&(i=c);}catch{}i.workspaces.some(a=>a.path===e)||(i.workspaces.push({name:o,path:e,mode:"full",projects:[]}),await promises.writeFile(r,JSON.stringify(i,null,2)));}catch{console.warn(m.gray("Note: Could not register workspace in shared registry"));}}async function vn(e,o=false){try{let t=process.env.XDG_CONFIG_HOME||process.env.APPDATA||v.join(te__default.homedir(),".config"),n=process.platform==="win32"?v.join(t,"rapidkit"):v.join(te__default.homedir(),".rapidkit"),r=v.join(n,"workspaces.json"),i={workspaces:[]};try{let d=await promises.readFile(r,"utf8"),p=JSON.parse(d);p&&Array.isArray(p.workspaces)&&(i=p);}catch{o||console.log("\u26A0\uFE0F Workspace registry not found");return}let s=i.workspaces.find(d=>d.path===e);if(!s){o||console.log("\u26A0\uFE0F Workspace not registered in registry");return}Array.isArray(s.projects)||(s.projects=[]);let a=await promises.readdir(e,{withFileTypes:!0}),c=0,l=0;for(let d of a)if(d.isDirectory()&&!d.name.startsWith(".")){let p=v.join(e,d.name),u=v.join(p,".rapidkit","context.json"),g=v.join(p,".rapidkit","project.json");try{let w=!1;try{await promises.access(u),w=!0;}catch{await promises.access(g),w=!0;}w&&(s.projects.some(x=>x.path===p||x.name===d.name)?l++:(s.projects.push({name:d.name,path:p}),c++,o||console.log(`\u2714 Added: ${d.name}`)));}catch{}}c>0?(await promises.writeFile(r,JSON.stringify(i,null,2)),o||console.log(`
|
|
23
23
|
\u2705 Synced ${c} project(s) to registry`)):o||console.log(`
|
|
24
|
-
\u2705 All projects already registered (${l} found)`);}catch(t){o||console.error("\u274C Failed to sync projects:",t.message);}}async function
|
|
24
|
+
\u2705 All projects already registered (${l} found)`);}catch(t){o||console.error("\u274C Failed to sync projects:",t.message);}}async function bn(e,o,t){try{let n=process.env.XDG_CONFIG_HOME||process.env.APPDATA||v.join(te__default.homedir(),".config"),r=process.platform==="win32"?v.join(n,"rapidkit"):v.join(te__default.homedir(),".rapidkit"),i=v.join(r,"workspaces.json");console.log(`[REGISTRY DEBUG] Registry file: ${i}`);let s={workspaces:[]};try{let l=await promises.readFile(i,"utf8"),d=JSON.parse(l);d&&Array.isArray(d.workspaces)&&(s=d),console.log(`[REGISTRY DEBUG] Registry loaded, ${s.workspaces.length} workspaces`);}catch{console.log("[REGISTRY DEBUG] Registry doesn't exist, returning");return}let a=s.workspaces.find(l=>l.path===e);if(!a){console.log("[REGISTRY DEBUG] Workspace not found in registry, returning");return}console.log(`[REGISTRY DEBUG] Workspace found: ${a.name}`),Array.isArray(a.projects)||(a.projects=[]),a.projects.some(l=>l.path===t||l.name===o)?console.log("[REGISTRY DEBUG] Project already exists in registry"):(console.log("[REGISTRY DEBUG] Adding project to registry"),a.projects.push({name:o,path:t}),await promises.writeFile(i,JSON.stringify(s,null,2)),console.log("[REGISTRY DEBUG] Registry updated successfully"));}catch(n){console.log(`[REGISTRY DEBUG] Error: ${n}`);}}async function xn(e,o){let t=Re("Creating RapidKit workspace...").start();try{await promises.mkdir(e,{recursive:!0}),await promises.mkdir(v.join(e,".rapidkit"),{recursive:!0});let n={workspace_name:o.name,author:o.author,rapidkit_version:q(),created_at:new Date().toISOString(),type:"workspace"};await promises.writeFile(v.join(e,".rapidkit","config.json"),JSON.stringify(n,null,2));let r=Pn();await promises.writeFile(v.join(e,"rapidkit"),r),await promises.chmod(v.join(e,"rapidkit"),493);let i=jn(o.name);if(await promises.writeFile(v.join(e,"README.md"),i),await promises.writeFile(v.join(e,".gitignore"),`# RapidKit workspace
|
|
25
25
|
.env
|
|
26
26
|
.env.*
|
|
27
27
|
!.env.example
|
|
@@ -36,7 +36,7 @@ Thumbs.db
|
|
|
36
36
|
|
|
37
37
|
# Logs
|
|
38
38
|
*.log
|
|
39
|
-
`),await promises.writeFile(v.join(e,".rapidkit-workspace"),JSON.stringify({signature:"RAPIDKIT_WORKSPACE",createdBy:"rapidkit-npm",version:q(),createdAt:new Date().toISOString(),name:o.name},null,2)),await
|
|
39
|
+
`),await promises.writeFile(v.join(e,".rapidkit-workspace"),JSON.stringify({signature:"RAPIDKIT_WORKSPACE",createdBy:"rapidkit-npm",version:q(),createdAt:new Date().toISOString(),name:o.name},null,2)),await Cn(e),t.succeed("Workspace created!"),!o.skipGit){let a=Re("Initializing git repository...").start();try{await execa("git",["init"],{cwd:e}),await execa("git",["add","."],{cwd:e}),await execa("git",["commit","-m","Initial commit: RapidKit workspace"],{cwd:e}),a.succeed("Git repository initialized");}catch{a.warn("Could not initialize git repository");}}await zt(e,o.name),console.log(`
|
|
40
40
|
${m.green("\u2728 RapidKit workspace created successfully!")}
|
|
41
41
|
|
|
42
42
|
${m.bold("\u{1F4C2} Workspace structure:")}
|
|
@@ -66,7 +66,7 @@ ${m.bold("\u{1F4DA} Commands:")}
|
|
|
66
66
|
|
|
67
67
|
${m.gray("Alternative: ./rapidkit dev, make dev")}
|
|
68
68
|
${m.gray("\u{1F4A1} Tip: Install globally (npm i -g rapidkit) to use without npx")}
|
|
69
|
-
`);}catch(n){throw t.fail("Failed to create workspace"),n}}function
|
|
69
|
+
`);}catch(n){throw t.fail("Failed to create workspace"),n}}function Pn(){return `#!/usr/bin/env bash
|
|
70
70
|
#
|
|
71
71
|
# RapidKit CLI - Local workspace commands
|
|
72
72
|
# This script provides rapidkit commands within the workspace
|
|
@@ -284,7 +284,7 @@ cmd_project() {
|
|
|
284
284
|
cd "$project_root"
|
|
285
285
|
|
|
286
286
|
case "$kit_name" in
|
|
287
|
-
fastapi.standard|python)
|
|
287
|
+
fastapi.standard|fastapi.ddd|python)
|
|
288
288
|
# Python/FastAPI project
|
|
289
289
|
case "$cmd" in
|
|
290
290
|
init)
|
|
@@ -414,7 +414,7 @@ main() {
|
|
|
414
414
|
}
|
|
415
415
|
|
|
416
416
|
main "$@"
|
|
417
|
-
`}function
|
|
417
|
+
`}function jn(e){return `# ${e}
|
|
418
418
|
|
|
419
419
|
RapidKit workspace for building API projects.
|
|
420
420
|
|
|
@@ -462,7 +462,7 @@ npx rapidkit dev # Start dev server
|
|
|
462
462
|
|
|
463
463
|
- [RapidKit Documentation](https://rapidkit.dev)
|
|
464
464
|
- [GitHub Repository](https://github.com/Baziar/rapidkit)
|
|
465
|
-
`}async function
|
|
465
|
+
`}async function Cn(e){let{fileURLToPath:o}=await import('url'),t=o(import.meta.url),n=v.dirname(t),r=v.resolve(n,".."),i=v.join(r,"templates","kits"),s=v.join(e,".rapidkit","templates"),{default:a}=await import('fs-extra');await a.copy(i,s);let c=v.join(r,"templates","generator.js"),l=v.join(e,".rapidkit","generator.js");await a.copy(c,l);}async function $n(e,o){let t=o.template==="fastapi",n=t?"FastAPI":"NestJS",r=Re(`Creating ${n} project...`).start();try{let{fileURLToPath:i}=await import('url'),s=i(import.meta.url),a=v.dirname(s),c=v.resolve(a,".."),l=t?"fastapi-standard":"nestjs-standard",d=v.join(c,"templates","kits",l);await promises.mkdir(e,{recursive:!0});let p={project_name:t?o.name.replace(/-/g,"_").toLowerCase():o.name.replace(/_/g,"-").toLowerCase(),author:o.author,description:o.description||`${n} application generated with RapidKit`,app_version:"0.1.0",license:"MIT",package_manager:o.package_manager||"npm",created_at:new Date().toISOString(),rapidkit_version:q()};await Qt(d,e,p);let u=t?`# Python
|
|
466
466
|
__pycache__/
|
|
467
467
|
*.py[cod]
|
|
468
468
|
*$py.class
|
|
@@ -530,7 +530,7 @@ Thumbs.db
|
|
|
530
530
|
|
|
531
531
|
# Coverage
|
|
532
532
|
coverage/
|
|
533
|
-
`;if(await promises.writeFile(v.join(e,".gitignore"),u),r.succeed(`${n} project created!`),!o.skipGit){let
|
|
533
|
+
`;if(await promises.writeFile(v.join(e,".gitignore"),u),r.succeed(`${n} project created!`),!o.skipGit){let w=Re("Initializing git repository...").start();try{await execa("git",["init"],{cwd:e}),await execa("git",["add","."],{cwd:e}),await execa("git",["commit","-m",`Initial commit: ${n} project via RapidKit`],{cwd:e}),w.succeed("Git repository initialized");}catch{w.warn("Could not initialize git repository");}}if(!o.skipInstall&&!t){let w=o.package_manager||"npm",h=Re(`Installing dependencies with ${w}...`).start();try{await execa(w,["install"],{cwd:e}),h.succeed("Dependencies installed");}catch{h.warn(`Could not install dependencies. Run '${w} install' manually.`);}}let g=v.basename(e);console.log(t?`
|
|
534
534
|
${m.green("\u2728 FastAPI project created successfully!")}
|
|
535
535
|
|
|
536
536
|
${m.bold("\u{1F4C2} Project structure:")}
|
|
@@ -596,7 +596,7 @@ ${m.bold("\u{1F310} API endpoints:")}
|
|
|
596
596
|
http://localhost:8000/examples/notes # Example API
|
|
597
597
|
|
|
598
598
|
${m.gray("\u{1F4A1} Tip: Install globally (npm i -g rapidkit) to use without npx")}
|
|
599
|
-
`);}catch(i){throw r.fail(`Failed to create ${n} project`),i}}async function Qt(e,o,t){let n=await promises.readdir(e,{withFileTypes:true});for(let r of n){let i=v.join(e,r.name),s=r.name.replace(/\.j2$/,""),a=v.join(o,s);if(r.isDirectory())await promises.mkdir(a,{recursive:true}),await Qt(i,a,t);else {let c=await promises.readFile(i,"utf-8");r.name.endsWith(".j2")&&(c
|
|
599
|
+
`);}catch(i){throw r.fail(`Failed to create ${n} project`),i}}async function Qt(e,o,t){let n=await promises.readdir(e,{withFileTypes:true});for(let r of n){let i=v.join(e,r.name),s=r.name.replace(/\.j2$/,""),a=v.join(o,s);if(r.isDirectory())await promises.mkdir(a,{recursive:true}),await Qt(i,a,t);else {let c=await promises.readFile(i,"utf-8");r.name.endsWith(".j2")&&(c=_n(c,t)),await promises.writeFile(a,c),(s==="rapidkit"||s==="activate"||s.endsWith(".py")&&a.includes(".rapidkit"))&&await promises.chmod(a,493);}}}function _n(e,o){let t=e;for(let[n,r]of Object.entries(o)){let i=new RegExp(`\\{\\{\\s*${n}\\s*\\}\\}`,"g");t=t.replace(i,String(r));let s=new RegExp(`\\{\\{\\s*${n}\\s*\\|\\s*replace\\s*\\(\\s*['"]([^'"]+)['"]\\s*,\\s*['"]([^'"]*)['"]\\s*\\)\\s*\\}\\}`,"g");t=t.replace(s,(l,d,p)=>String(r).replace(new RegExp(d,"g"),p));let a=new RegExp(`\\{\\{\\s*${n}\\s*\\|\\s*lower\\s*\\}\\}`,"g");t=t.replace(a,String(r).toLowerCase());let c=new RegExp(`\\{\\{\\s*${n}\\s*\\|\\s*replace\\s*\\(\\s*['"]([^'"]+)['"]\\s*,\\s*['"]([^'"]*)['"]\\s*\\)\\s*\\|\\s*lower\\s*\\}\\}`,"g");t=t.replace(c,(l,d,p)=>String(r).replace(new RegExp(d,"g"),p).toLowerCase());}return t}async function Rn(){let e=process.env.XDG_CONFIG_HOME||process.env.APPDATA||v.join(te__default.homedir(),".config"),o=process.platform==="win32"?v.join(e,"rapidkit"):v.join(te__default.homedir(),".rapidkit"),t=v.join(o,"workspaces.json");if(!await promises.stat(t).catch(()=>null)){console.log(m.yellow(`
|
|
600
600
|
\u26A0\uFE0F No workspaces registered yet.
|
|
601
601
|
`)),console.log(m.gray(`Create a workspace with: npx rapidkit <workspace-name>
|
|
602
602
|
`));return}try{let n=await promises.readFile(t,"utf8"),r=JSON.parse(n);if(!r.workspaces||r.workspaces.length===0){console.log(m.yellow(`
|
|
@@ -605,7 +605,7 @@ ${m.gray("\u{1F4A1} Tip: Install globally (npm i -g rapidkit) to use without npx
|
|
|
605
605
|
\u{1F4E6} Registered RapidKit Workspaces:
|
|
606
606
|
`));for(let i of r.workspaces)console.log(m.cyan(` ${i.name}`)),console.log(m.gray(` Path: ${i.path}`)),console.log(m.gray(` Projects: ${i.projects?.length||0}`)),await promises.stat(i.path).catch(()=>null)||console.log(m.red(" \u26A0\uFE0F Path not found")),console.log();console.log(m.gray(`Total: ${r.workspaces.length} workspace(s)
|
|
607
607
|
`));}catch(n){console.error(m.red(`
|
|
608
|
-
\u274C Failed to read workspace registry`)),console.error(m.gray(String(n)));}}var ne=se(()=>{
|
|
608
|
+
\u274C Failed to read workspace registry`)),console.error(m.gray(String(n)));}}var ne=se(()=>{j();Pe();});j();ce();Pe();j();ce();var zo=".rapidkitrc.json",Qo=["rapidkit.config.js","rapidkit.config.mjs","rapidkit.config.cjs"];async function je(){let e=v.join(te__default.homedir(),zo);try{let o=await promises.readFile(e,"utf-8"),t=JSON.parse(o);return y.debug(`Loaded config from ${e}`),t}catch{return y.debug("No user config found, using defaults"),{}}}async function Et(e=process.cwd()){let o=e,t=v.parse(o).root;for(;o!==t;){for(let n of Qo){let r=v.join(o,n);try{await promises.access(r),y.debug(`Found config file: ${r}`);let s=await import(pathToFileURL(r).href),a=s.default||s;return y.debug(`Loaded RapidKit config from ${n}`),a}catch{continue}}o=v.dirname(o);}return y.debug("No RapidKit config file found, using defaults"),{}}function It(e,o,t){return {author:t.author||o.workspace?.defaultAuthor||e.author,pythonVersion:o.workspace?.pythonVersion||e.pythonVersion,defaultInstallMethod:t.defaultInstallMethod||o.workspace?.installMethod||e.defaultInstallMethod,defaultKit:t.defaultKit||o.projects?.defaultKit||e.defaultKit,skipGit:t.skipGit??o.projects?.skipGit??e.skipGit,license:t.license||e.license,testRapidKitPath:t.testRapidKitPath||e.testRapidKitPath}}function Me(e){return process.env.RAPIDKIT_DEV_PATH||e.testRapidKitPath||void 0}j();j();var J=class extends Error{constructor(t,n,r){super(t);this.code=n;this.details=r;this.name="RapidKitError",Error.captureStackTrace(this,this.constructor);}},me=class extends J{constructor(o,t){let n=t?`Python ${o}+ required, found ${t}`:`Python ${o}+ not found`;super(n,"PYTHON_NOT_FOUND","Please install Python from https://www.python.org/downloads/");}},Ce=class extends J{constructor(){super("Poetry is not installed","POETRY_NOT_FOUND","Install Poetry from https://python-poetry.org/docs/#installation");}},$e=class extends J{constructor(){super("pipx is not installed","PIPX_NOT_FOUND","Install pipx from https://pypa.github.io/pipx/installation/");}},Oe=class extends J{constructor(o){super(`Directory "${o}" already exists`,"DIRECTORY_EXISTS","Please choose a different name or remove the existing directory");}},ee=class extends J{constructor(o,t){super(`Invalid project name: "${o}"`,"INVALID_PROJECT_NAME",t);}},U=class extends J{constructor(o,t){let n=`Installation failed at: ${o}`,r=`${t.message}
|
|
609
609
|
|
|
610
610
|
Troubleshooting:
|
|
611
611
|
- Check your internet connection
|
|
@@ -615,18 +615,18 @@ Troubleshooting:
|
|
|
615
615
|
2. Use the core workflow: npx rapidkit create workspace <name>
|
|
616
616
|
3. Offline fallback (limited): npx rapidkit create project fastapi.standard <name> --output .
|
|
617
617
|
|
|
618
|
-
Legacy: set RAPIDKIT_SHOW_LEGACY=1 to reveal template-mode flags in help.`);}};function At(e){let o=
|
|
618
|
+
Legacy: set RAPIDKIT_SHOW_LEGACY=1 to reveal template-mode flags in help.`);}};function At(e){let o=Xo(e);if(!o.validForNewPackages){let n=o.errors||[],r=o.warnings||[],i=[...n,...r];throw new ee(e,`NPM validation failed: ${i.join(", ")}`)}if(!/^[a-z][a-z0-9_-]*$/.test(e))throw new ee(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 ee(e,`"${e}" is a reserved name. Please choose a different name.`);if(e.length<2)throw new ee(e,"Name must be at least 2 characters long");if(e.length>214)throw new ee(e,"Name must be less than 214 characters");return true}j();function en(e){return typeof e=="object"&&e!==null}async function tn(e,o,t,n=8e3){try{let r=await execa(e,o,{cwd:t,timeout:n,reject:!1,stdio:"pipe"});return {ok:r.exitCode===0,exitCode:r.exitCode,stdout:r.stdout,stderr:r.stderr}}catch(r){return {ok:false,exitCode:void 0,stdout:"",stderr:r instanceof Error?r.message:String(r)}}}async function on(e,o){let t=["-m","rapidkit",...e],n=["python3","python"];for(let r of n){let i=await tn(r,t,o?.cwd,o?.timeoutMs);if(!i.ok)continue;let s=(i.stdout??"").trim();try{let a=JSON.parse(s);return en(a)?{ok:!0,command:r,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr,data:a}:{ok:!1,command:r,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr}}catch{return {ok:false,command:r,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr}}}return {ok:false}}async function St(e,o){let t=await on(["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}Ke();it();j();ce();Pe();j();function Le(){return process.platform==="win32"?"python":"python3"}ut();async function eo(e,o,t,n){let r=pt(o,q(),t);n&&(r.metadata||(r.metadata={}),r.metadata.python={version:n}),await Ge(e,r);}async function to(e){await b.outputFile(v.join(e,".gitignore"),`.venv/
|
|
619
619
|
__pycache__/
|
|
620
620
|
*.pyc
|
|
621
621
|
.env
|
|
622
622
|
.rapidkit-workspace/
|
|
623
623
|
|
|
624
|
-
`,"utf-8");}async function Xt(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
|
|
625
|
-
`,"utf-8"),y.debug(`Created .python-version with ${o}`);}catch(t){y.warn(`Failed to create .python-version: ${t}`);}}function
|
|
624
|
+
`,"utf-8");}async function Xt(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 En(e,o){try{await promises.writeFile(v.join(e,".python-version"),`${o}
|
|
625
|
+
`,"utf-8"),y.debug(`Created .python-version with ${o}`);}catch(t){y.warn(`Failed to create .python-version: ${t}`);}}function Ee(){let e=v.join(te.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 We(e,o){Ee(),e.start("Checking pipx installation");try{return await execa("pipx",["--version"]),e.succeed("pipx found"),{kind:"binary"}}catch{}let t=Le();try{return await execa(t,["-m","pipx","--version"]),e.succeed("pipx found"),{kind:"python-module",pythonCmd:t}}catch{}if(o)throw new $e;let{installPipx:n}=await gt.prompt([{type:"confirm",name:"installPipx",message:"pipx is not installed. Install it now (user install via python -m pip)?",default:true}]);if(!n)throw new $e;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(r){let i=r,s=String(i?.stderr||i?.shortMessage||i?.message||"");throw new U("Install pipx with python -m pip",r instanceof Error?r:new Error(s))}e.succeed("pipx installed"),Ee();try{return await execa(t,["-m","pipx","--version"]),{kind:"python-module",pythonCmd:t}}catch(r){let i=r,s=String(i?.stderr||i?.shortMessage||i?.message||"pipx not runnable after install");throw new U("Verify pipx after install",new Error(`${s}
|
|
626
626
|
|
|
627
|
-
Try reopening your terminal or run: python3 -m pipx ensurepath`))}}async function we(e,o){return e.kind==="binary"?execa("pipx",o):execa(e.pythonCmd,["-m","pipx",...o])}async function
|
|
627
|
+
Try reopening your terminal or run: python3 -m pipx ensurepath`))}}async function we(e,o){return e.kind==="binary"?execa("pipx",o):execa(e.pythonCmd,["-m","pipx",...o])}async function In(e,o){Ee(),e.start("Checking Poetry installation");try{await execa("poetry",["--version"]),e.succeed("Poetry found");return}catch{}if(o)throw new Ce;let{installPoetry:t}=await gt.prompt([{type:"confirm",name:"installPoetry",message:"Poetry is not installed. Install it now using pipx?",default:true}]);if(!t)throw new Ce;let n=await We(e,o);e.start("Installing Poetry with pipx");try{await we(n,["install","poetry"]);}catch(r){let i=r,s=String(i?.stderr||i?.shortMessage||i?.message||"");if(/already\s+installed|already\s+seems\s+to\s+be\s+installed|exists/i.test(s))try{await we(n,["upgrade","poetry"]);}catch{}else throw new U("Install Poetry with pipx",r instanceof Error?r:new Error(s))}e.succeed("Poetry installed"),Ee();try{await execa("poetry",["--version"]);}catch(r){let i=r,s=String(i?.stderr||i?.shortMessage||i?.message||"Poetry not found on PATH");throw new U("Verify Poetry after pipx install",new Error(`${s}
|
|
628
628
|
|
|
629
|
-
Poetry may be installed but not on PATH yet. Try reopening your terminal or run: pipx ensurepath`))}}function
|
|
629
|
+
Poetry may be installed but not on PATH yet. Try reopening your terminal or run: pipx ensurepath`))}}function An(e){let o=e==="poetry";return `#!/usr/bin/env sh
|
|
630
630
|
set -eu
|
|
631
631
|
|
|
632
632
|
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
|
@@ -645,7 +645,7 @@ echo "- If you used venv: ensure .venv exists (or re-run the installer)." 1>&2
|
|
|
645
645
|
${o?`echo "- If you used Poetry: run 'poetry install' and retry, or activate the env." 1>&2
|
|
646
646
|
`:""}echo "Tip: you can also run: ./.venv/bin/rapidkit --help" 1>&2
|
|
647
647
|
exit 1
|
|
648
|
-
`}function
|
|
648
|
+
`}function Sn(e){return `@echo off
|
|
649
649
|
setlocal
|
|
650
650
|
|
|
651
651
|
set "SCRIPT_DIR=%~dp0"
|
|
@@ -664,14 +664,14 @@ if %ERRORLEVEL%==0 if exist "%SCRIPT_DIR%\\pyproject.toml" (
|
|
|
664
664
|
`:""}echo RapidKit launcher could not find a local Python CLI. 1>&2
|
|
665
665
|
echo Tip: run .venv\\Scripts\\rapidkit.exe --help 1>&2
|
|
666
666
|
exit /b 1
|
|
667
|
-
`}async function oo(e,o){await b.outputFile(v.join(e,"rapidkit"),
|
|
667
|
+
`}async function oo(e,o){await b.outputFile(v.join(e,"rapidkit"),An(o),{encoding:"utf-8",mode:493}),await b.outputFile(v.join(e,"rapidkit.cmd"),Sn(o),"utf-8");}async function no(e,o){let{skipGit:t=false,testMode:n=false,demoMode:r=false,dryRun:i=false,yes:s=false,userConfig:a={},installMethod:c}=o,l=e||"rapidkit",d=v.resolve(process.cwd(),l);if(await b.pathExists(d))throw new Oe(l);if(i){await Nn(d,l,r,a);return}if(r){await Dn(d,l,t);return}let p=s?{pythonVersion:a.pythonVersion||"3.10",installMethod:c||a.defaultInstallMethod||"poetry"}:await gt.prompt([{type:"list",name:"pythonVersion",message:"Select Python version for RapidKit:",choices:["3.10","3.11","3.12"],default:a.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:a.defaultInstallMethod||"poetry"}]);y.step(1,3,"Setting up RapidKit environment");let u=Re("Creating directory").start();try{await b.ensureDir(d),u.succeed("Directory created"),u.start("Detecting Python version");let g=null,w=await io(p.pythonVersion);if(w)g=await Xt(w),g?(y.info(`Detected Python ${g}`),u.succeed(`Python ${g} detected`)):u.warn("Could not detect exact Python version");else {let h=Le();g=await Xt(h),g?u.succeed(`Python ${g} detected`):u.warn("Could not detect Python version, proceeding with defaults");}if(await eo(d,l,p.installMethod,g||void 0),g&&await En(d,g),await to(d),p.installMethod==="poetry")try{await ro(d,p.pythonVersion,u,n,a,s);}catch(h){let x=h?.details||h?.message||String(h);if(x.includes("pyenv")||x.includes("exit status 127")||x.includes("returned non-zero exit status 127")){u.warn("Poetry encountered Python discovery issues, trying venv method"),y.debug(`Poetry error (attempting venv fallback): ${x}`);try{await mt(d,p.pythonVersion,u,n,a),p.installMethod="venv";}catch(F){throw F}}else throw h}else p.installMethod==="venv"?await mt(d,p.pythonVersion,u,n,a):await so(d,u,n,a,s);if(await oo(d,p.installMethod),await ao(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:h}=await Promise.resolve().then(()=>(ne(),oe));await h(d,l);}catch{console.warn(m.gray("Note: Could not register workspace in shared registry"));}if(console.log(m.green(`
|
|
668
668
|
\u2728 RapidKit environment created successfully!
|
|
669
669
|
`)),console.log(m.cyan("\u{1F4C2} Location:"),m.white(d)),console.log(m.cyan(`\u{1F680} Get started:
|
|
670
|
-
`)),console.log(m.white(` cd ${l}`)),p.installMethod==="poetry"){let
|
|
670
|
+
`)),console.log(m.white(` cd ${l}`)),p.installMethod==="poetry"){let h="source $(poetry env info --path)/bin/activate";try{Ee();let{stdout:x}=await execa("poetry",["--version"]),T=x.match(/Poetry.*?(\d+)\.(\d+)/);T&&(parseInt(T[1])>=2?h="source $(poetry env info --path)/bin/activate":h="poetry shell");}catch{}console.log(m.white(` ${h} # Or: poetry run rapidkit`)),console.log(m.white(" rapidkit create # Interactive mode")),console.log(m.white(" cd <project-name> && rapidkit init && rapidkit dev"));}else p.installMethod==="venv"?(console.log(m.white(" source .venv/bin/activate # On Windows: .venv\\Scripts\\activate")),console.log(m.white(" rapidkit create # Interactive mode")),console.log(m.white(" cd <project-name> && rapidkit init && rapidkit dev"))):(console.log(m.white(" rapidkit create # Interactive mode")),console.log(m.white(" cd <project-name> && rapidkit init && rapidkit dev")));console.log(m.white(`
|
|
671
671
|
\u{1F4A1} For more information, check the README.md file.`)),console.log(m.cyan(`
|
|
672
672
|
\u{1F4DA} RapidKit commands:`)),console.log(m.white(" rapidkit create - Create a new project (interactive)")),console.log(m.white(" rapidkit dev - Run development server")),console.log(m.white(" rapidkit add module <name> - Add a module (e.g., settings)")),console.log(m.white(" rapidkit list - List available kits")),console.log(m.white(" rapidkit modules - List available modules")),console.log(m.white(` rapidkit --help - Show all commands
|
|
673
673
|
`));}catch(g){u.fail("Failed to create RapidKit environment"),console.error(m.red(`
|
|
674
|
-
\u274C Error:`),g);try{await b.remove(d);}catch{}throw g}}async function io(e){let o=[];try{let{stdout:t}=await execa("pyenv",["root"]),n=t.trim();o.push(v.join(n,"versions",`${e}.*`,"bin","python"));let[r,i]=e.split(".");o.push(v.join(n,"versions",`${r}.${i}.*`,"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 n=t;if(t.includes("*")){if(n=(await execa("sh",["-c",`ls -d ${t} 2>/dev/null | head -1`])).stdout.trim(),!n)continue;n=v.join(n.split("/").slice(0,-1).join("/"),"../bin/python");}let{stdout:r}=await execa(n,["--version"],{timeout:2e3}),i=r.match(/Python (\d+\.\d+)/)?.[1];if(i&&parseFloat(i)>=parseFloat(e))return await execa(n,["-c","import sys; sys.exit(0)"],{timeout:2e3}),n}catch{continue}return null}async function ro(e,o,t,n,r,i=false){await
|
|
674
|
+
\u274C Error:`),g);try{await b.remove(d);}catch{}throw g}}async function io(e){let o=[];try{let{stdout:t}=await execa("pyenv",["root"]),n=t.trim();o.push(v.join(n,"versions",`${e}.*`,"bin","python"));let[r,i]=e.split(".");o.push(v.join(n,"versions",`${r}.${i}.*`,"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 n=t;if(t.includes("*")){if(n=(await execa("sh",["-c",`ls -d ${t} 2>/dev/null | head -1`])).stdout.trim(),!n)continue;n=v.join(n.split("/").slice(0,-1).join("/"),"../bin/python");}let{stdout:r}=await execa(n,["--version"],{timeout:2e3}),i=r.match(/Python (\d+\.\d+)/)?.[1];if(i&&parseFloat(i)>=parseFloat(e))return await execa(n,["-c","import sys; sys.exit(0)"],{timeout:2e3}),n}catch{continue}return null}async function ro(e,o,t,n,r,i=false){await In(t,i),t.start("Finding Python interpreter");let s=await io(o);s?(y.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 a=v.join(e,"pyproject.toml"),l=await promises.readFile(a,"utf-8");l.includes("[tool.poetry]")?l=l.replace("[tool.poetry]",`[tool.poetry]
|
|
675
675
|
package-mode = false`):l.includes("[project]")&&(l.includes("[build-system]")?l=l.replace("[build-system]",`
|
|
676
676
|
[tool.poetry]
|
|
677
677
|
package-mode = false
|
|
@@ -680,25 +680,25 @@ package-mode = false
|
|
|
680
680
|
|
|
681
681
|
[tool.poetry]
|
|
682
682
|
package-mode = false
|
|
683
|
-
`),await promises.writeFile(a,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}),y.debug(`Poetry configured to use: ${s}`);}catch(d){y.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){y.debug(`Failed to create virtualenv: ${d}`),t.warn("Could not create virtualenv, proceeding with add command");}if(t.start("Installing RapidKit"),n){let d=
|
|
683
|
+
`),await promises.writeFile(a,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}),y.debug(`Poetry configured to use: ${s}`);}catch(d){y.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){y.debug(`Failed to create virtualenv: ${d}`),t.warn("Could not create virtualenv, proceeding with add command");}if(t.start("Installing RapidKit"),n){let d=Me(r||{});if(!d)throw new U("Test mode installation",new Error("No local RapidKit path configured. Set RAPIDKIT_DEV_PATH environment variable."));y.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=!0;break}catch(g){p=g,y.debug(`Poetry add attempt ${u} failed: ${g}`),u<3&&(t.text=`Retrying installation (attempt ${u+1}/3)`,await new Promise(w=>setTimeout(w,2e3)));}if(!d){let u=p?.stderr||p?.message||"Unknown error";throw y.debug(`All Poetry install attempts failed. Last error: ${u}`),u.includes("Could not find")||u.includes("No matching distribution")?new ge:new U("Install rapidkit-core with Poetry",new Error(`Failed to install rapidkit-core after 3 attempts.
|
|
684
684
|
Error: ${u}
|
|
685
685
|
|
|
686
686
|
Possible solutions:
|
|
687
687
|
1. Check your internet connection
|
|
688
688
|
2. Try installing manually: cd ${v.basename(e)} && poetry add rapidkit-core
|
|
689
|
-
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 Promise.resolve().then(()=>(
|
|
689
|
+
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 Promise.resolve().then(()=>(Ke(),lt));if(!await d()&&!n){t.start("Installing RapidKit globally with pipx for CLI access");let u=await We(t,i);try{await we(u,["install","rapidkit-core"]),t.succeed("RapidKit installed globally");}catch(g){t.warn("Could not install globally (non-fatal, project virtualenv has RapidKit)"),y.debug(`pipx install failed: ${g}`);}}}catch(d){y.debug(`Global install check skipped: ${d}`);}}async function mt(e,o,t,n,r,i=false){t.start(`Checking Python ${o}`);let s=Le();try{let{stdout:c}=await execa(s,["--version"]),l=c.match(/Python (\d+\.\d+)/)?.[1];if(l&&parseFloat(l)<parseFloat(o))throw new me(o,l);t.succeed(`Python ${l} found`);}catch(c){throw c instanceof me?c:new me(o)}t.start("Creating virtual environment");try{await execa(s,["-m","venv",".venv"],{cwd:e}),t.succeed("Virtual environment created");}catch(c){if(t.fail("Failed to create virtual environment"),(d=>typeof d=="object"&&d!==null&&"stdout"in d&&typeof d.stdout=="string")(c)&&c.stdout.includes("ensurepip is not")){let d=c.stdout.match(/apt install (python[\d.]+-venv)/),p=d?d[1]:"python3-venv";throw new U("Python venv module not available",new Error(`Virtual environment creation failed.
|
|
690
690
|
|
|
691
691
|
On Debian/Ubuntu systems, install the venv package:
|
|
692
692
|
sudo apt install ${p}
|
|
693
693
|
|
|
694
694
|
Or use Poetry instead (recommended):
|
|
695
|
-
npx rapidkit ${v.basename(e)} --yes`))}throw new
|
|
695
|
+
npx rapidkit ${v.basename(e)} --yes`))}throw new U("Virtual environment creation",c instanceof Error?c:new Error(String(c)))}t.start("Installing RapidKit");let a=v.join(e,".venv",process.platform==="win32"?"Scripts":"bin",process.platform==="win32"?"python.exe":"python");if(await execa(a,["-m","pip","install","--upgrade","pip"],{cwd:e}),n){let c=Me(r||{});if(!c)throw new U("Test mode installation",new Error("No local RapidKit path configured. Set RAPIDKIT_DEV_PATH environment variable."));y.debug(`Installing from local path: ${c}`),t.text="Installing RapidKit from local path (test mode)",await execa(a,["-m","pip","install","-e",c],{cwd:e});}else {t.text="Installing RapidKit from PyPI";let c=false,l=null;for(let d=1;d<=3;d++)try{await execa(a,["-m","pip","install","rapidkit-core"],{cwd:e,timeout:6e4*d}),c=!0;break}catch(p){l=p,y.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(!c){let d=l?.stderr||l?.message||"Unknown error";throw y.debug(`All pip install attempts failed. Last error: ${d}`),d.includes("Could not find")||d.includes("No matching distribution")?new ge:new U("Install rapidkit-core with pip",new Error(`Failed to install rapidkit-core after 3 attempts.
|
|
696
696
|
Error: ${d}
|
|
697
697
|
|
|
698
698
|
Possible solutions:
|
|
699
699
|
1. Check your internet connection
|
|
700
700
|
2. Try installing manually: cd ${v.basename(e)} && .venv/bin/python -m pip install rapidkit-core
|
|
701
|
-
3. Use Poetry instead: npx rapidkit ${v.basename(e)} --install-method=poetry`))}}t.succeed("RapidKit installed in project virtualenv");try{let{checkRapidkitCoreAvailable:c}=await Promise.resolve().then(()=>(
|
|
701
|
+
3. Use Poetry instead: npx rapidkit ${v.basename(e)} --install-method=poetry`))}}t.succeed("RapidKit installed in project virtualenv");try{let{checkRapidkitCoreAvailable:c}=await Promise.resolve().then(()=>(Ke(),lt));if(!await c()&&!n){t.start("Installing RapidKit globally with pipx for CLI access");let d=await We(t,i);try{await we(d,["install","rapidkit-core"]),t.succeed("RapidKit installed globally");}catch(p){t.warn("Could not install globally (non-fatal, project virtualenv has RapidKit)"),y.debug(`pipx install failed: ${p}`);}}}catch(c){y.debug(`Global install check skipped: ${c}`);}}async function so(e,o,t,n,r=false){let i=await We(o,r);if(o.start("Installing RapidKit globally with pipx"),t){let s=Me(n||{});if(!s)throw new U("Test mode installation",new Error("No local RapidKit path configured. Set RAPIDKIT_DEV_PATH environment variable."));y.debug(`Installing from local path: ${s}`),o.text="Installing RapidKit from local path (test mode)",await we(i,["install","-e",s]);}else {o.text="Installing RapidKit from PyPI";try{await we(i,["install","rapidkit-core"]);}catch{throw new ge}}o.succeed("RapidKit installed globally"),await b.outputFile(v.join(e,".rapidkit-global"),`RapidKit installed globally with pipx
|
|
702
702
|
`,"utf-8");}async function pe(e,o){let{skipGit:t=false,testMode:n=false,userConfig:r={},yes:i=false,installMethod:s,pythonVersion:a="3.10"}=o||{},c=s||r.defaultInstallMethod||"poetry";await eo(e,v.basename(e),c),await to(e);let l=Re("Registering workspace").start();try{c==="poetry"?await ro(e,a,l,n,r,i):c==="venv"?await mt(e,a,l,n,r):await so(e,l,n,r,i),await oo(e,c),await ao(e,c),l.succeed("Workspace registered");try{let{registerWorkspace:d}=await Promise.resolve().then(()=>(ne(),oe));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 ao(e,o){let r=`# RapidKit Workspace
|
|
703
703
|
|
|
704
704
|
This directory contains a RapidKit development environment.
|
|
@@ -810,7 +810,7 @@ If you encounter issues:
|
|
|
810
810
|
2. Check RapidKit installation: \`rapidkit --version\`
|
|
811
811
|
3. Run diagnostics: \`rapidkit doctor\`
|
|
812
812
|
4. Visit RapidKit documentation or GitHub issues
|
|
813
|
-
`;await promises.writeFile(v.join(e,"README.md"),r,"utf-8");}async function
|
|
813
|
+
`;await promises.writeFile(v.join(e,"README.md"),r,"utf-8");}async function Dn(e,o,t){let n=Re("Creating demo workspace").start();try{await b.ensureDir(e),n.succeed("Directory created"),n.start("Setting up demo kit generator");let r=JSON.stringify({name:`${o}-workspace`,version:"1.0.0",private:!0,description:"RapidKit demo workspace",scripts:{generate:"node generate-demo.js"}},null,2);await promises.writeFile(v.join(e,"package.json"),r,"utf-8"),await promises.writeFile(v.join(e,"generate-demo.js"),`#!/usr/bin/env node
|
|
814
814
|
/**
|
|
815
815
|
* Demo Kit Generator - Create FastAPI demo projects
|
|
816
816
|
*
|
|
@@ -1014,7 +1014,7 @@ readme = "README.md"
|
|
|
1014
1014
|
package-mode = false
|
|
1015
1015
|
|
|
1016
1016
|
[tool.poetry.dependencies]
|
|
1017
|
-
python = "^3.10
|
|
1017
|
+
python = "^3.10"
|
|
1018
1018
|
fastapi = "^0.128.0"
|
|
1019
1019
|
uvicorn = {extras = ["standard"], version = "^0.40.0"}
|
|
1020
1020
|
pydantic = "^2.12.5"
|
|
@@ -1309,7 +1309,7 @@ __pycache__/
|
|
|
1309
1309
|
`,"utf-8"),await execa("git",["add","."],{cwd:e}),await execa("git",["commit","-m","Initial commit: Demo workspace"],{cwd:e}),n.succeed("Git repository initialized");}catch{n.warn("Could not initialize git repository");}}console.log(m.green(`
|
|
1310
1310
|
\u2728 Demo workspace created successfully!
|
|
1311
1311
|
`)),console.log(m.cyan("\u{1F4C2} Location:"),m.white(e)),console.log(m.cyan(`\u{1F680} Get started:
|
|
1312
|
-
`)),console.log(m.white(` cd ${o}`)),console.log(m.white(" node generate-demo.js my-api")),console.log(m.white(" cd my-api")),console.log(m.white(" rapidkit init")),console.log(m.white(" rapidkit dev")),console.log(),console.log(m.yellow("\u{1F4A1} Note:"),"This is a demo workspace. For full RapidKit features:"),console.log(m.cyan(" pipx install rapidkit")),console.log();}catch(r){throw n.fail("Failed to create demo workspace"),r}}async function
|
|
1312
|
+
`)),console.log(m.white(` cd ${o}`)),console.log(m.white(" node generate-demo.js my-api")),console.log(m.white(" cd my-api")),console.log(m.white(" rapidkit init")),console.log(m.white(" rapidkit dev")),console.log(),console.log(m.yellow("\u{1F4A1} Note:"),"This is a demo workspace. For full RapidKit features:"),console.log(m.cyan(" pipx install rapidkit")),console.log();}catch(r){throw n.fail("Failed to create demo workspace"),r}}async function Nn(e,o,t,n){console.log(m.cyan(`
|
|
1313
1313
|
\u{1F50D} Dry-run mode - showing what would be created:
|
|
1314
1314
|
`)),console.log(m.white("\u{1F4C2} Project path:"),e),console.log(m.white("\u{1F4E6} Project type:"),t?"Demo workspace":"Full RapidKit environment"),t?(console.log(m.white(`
|
|
1315
1315
|
\u{1F4DD} Files to create:`)),console.log(m.gray(" - package.json")),console.log(m.gray(" - generate-demo.js (project generator)")),console.log(m.gray(" - README.md")),console.log(m.gray(" - .gitignore")),console.log(m.white(`
|
|
@@ -1318,7 +1318,7 @@ __pycache__/
|
|
|
1318
1318
|
\u{1F4DD} Files to create:`)),console.log(m.gray(" - pyproject.toml (Poetry) or .venv/ (venv)")),console.log(m.gray(" - README.md")),console.log(m.gray(" - .gitignore")),console.log(m.white(`
|
|
1319
1319
|
\u{1F3AF} Next steps after creation:`)),console.log(m.gray(" 1. Install RapidKit Python package")),console.log(m.gray(" 2. Create projects with rapidkit CLI")),console.log(m.gray(" 3. Add modules and customize"))),console.log(m.white(`
|
|
1320
1320
|
\u{1F4A1} To proceed with actual creation, run without --dry-run flag
|
|
1321
|
-
`));}
|
|
1321
|
+
`));}j();Pe();var Fn=fileURLToPath(import.meta.url),Kn=v.dirname(Fn);function Ln(e=32){let o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=rn.randomBytes(e),n="";for(let r=0;r<e;r++)n+=o[t[r]%o.length];return n}async function co(e,o){let t=o.template||"fastapi",n=t==="fastapi",r=n?"FastAPI":"NestJS",i=Re(`Generating ${r} project...`).start();try{let s=v.resolve(Kn,".."),a=o.kit_name||`${t}.standard`,c;a==="fastapi.ddd"?c="fastapi-ddd":a.startsWith("fastapi")?c="fastapi-standard":c="nestjs-standard";let l=v.join(s,"templates","kits",c),d=Mn.configure(l,{autoescape:!1,trimBlocks:!0,lstripBlocks:!0});d.addFilter("generate_secret",function(h,x=32){return Ln(x)});let p={project_name:o.project_name,author:o.author||"RapidKit User",description:o.description||(n?"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||!1,created_at:new Date().toISOString(),rapidkit_version:q()},u;n?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 h of u){let x=v.join(l,h);try{await promises.access(x);}catch{continue}let T=await promises.readFile(x,"utf-8"),F;try{F=d.renderString(T,p);}catch(Lo){throw console.error(`Failed to render template: ${h}`),Lo}let V=h.replace(/\.j2$/,""),xe=v.join(e,V);await promises.mkdir(v.dirname(xe),{recursive:!0}),await promises.writeFile(xe,F),(V.endsWith(".rapidkit/rapidkit")||V.endsWith(".rapidkit/cli.py")||V.endsWith(".rapidkit/activate")||V==="rapidkit")&&await promises.chmod(xe,493);}if(n){let h=v.join(l,".rapidkit","context.json"),x=v.join(e,".rapidkit","context.json");try{await promises.mkdir(v.join(e,".rapidkit"),{recursive:!0}),await promises.copyFile(h,x);}catch{await promises.mkdir(v.join(e,".rapidkit"),{recursive:!0});let F=o.engine||"pip";await promises.writeFile(x,JSON.stringify({engine:F,created_by:"rapidkit-npm-fallback"},null,2));}}let g=n?`# Python
|
|
1322
1322
|
__pycache__/
|
|
1323
1323
|
*.py[cod]
|
|
1324
1324
|
*$py.class
|
|
@@ -1386,7 +1386,7 @@ Thumbs.db
|
|
|
1386
1386
|
|
|
1387
1387
|
# Coverage
|
|
1388
1388
|
coverage/
|
|
1389
|
-
`;if(await promises.writeFile(v.join(e,".gitignore"),
|
|
1389
|
+
`;if(await promises.writeFile(v.join(e,".gitignore"),g),i.succeed(`${r} project generated!`),!o.skipGit){let h=Re("Initializing git repository...").start();try{await execa("git",["init"],{cwd:e}),await execa("git",["add","."],{cwd:e}),await execa("git",["commit","-m",`Initial commit: ${r} project via RapidKit`],{cwd:e}),h.succeed("Git repository initialized");}catch{h.warn("Could not initialize git repository");}}if(!n&&!o.skipInstall){let h=o.package_manager||"npm",x=Re(`Installing dependencies with ${h}...`).start();try{await execa(h,h==="yarn"?["install"]:h==="pnpm"?["install"]:["install"],{cwd:e}),x.succeed("Dependencies installed");}catch{x.warn(`Could not install dependencies. Run '${h} install' manually.`);}}let w=v.basename(e);console.log(`
|
|
1390
1390
|
${m.yellow("\u26A0\uFE0F Limited offline mode:")} This project was created using basic templates.
|
|
1391
1391
|
${m.gray("For full kit features, install Python 3.10+ and rapidkit-core:")}
|
|
1392
1392
|
${m.cyan(" sudo apt install python3 python3-pip python3-venv")}
|
|
@@ -1407,7 +1407,7 @@ ${e}/
|
|
|
1407
1407
|
\u2514\u2500\u2500 README.md
|
|
1408
1408
|
|
|
1409
1409
|
${m.bold("\u{1F680} Get started:")}
|
|
1410
|
-
${m.cyan(`cd ${
|
|
1410
|
+
${m.cyan(`cd ${w}`)}
|
|
1411
1411
|
${m.cyan("npx rapidkit init")} ${m.gray("# Install dependencies")}
|
|
1412
1412
|
${m.cyan("npx rapidkit dev")} ${m.gray("# Start dev server")}
|
|
1413
1413
|
|
|
@@ -1437,7 +1437,7 @@ ${e}/
|
|
|
1437
1437
|
\u2514\u2500\u2500 README.md
|
|
1438
1438
|
|
|
1439
1439
|
${m.bold("\u{1F680} Get started:")}
|
|
1440
|
-
${m.cyan(`cd ${
|
|
1440
|
+
${m.cyan(`cd ${w}`)}
|
|
1441
1441
|
${m.cyan("npx rapidkit init")} ${m.gray("# Install dependencies")}
|
|
1442
1442
|
${m.cyan("cp .env.example .env")}
|
|
1443
1443
|
${m.cyan("npx rapidkit dev")} ${m.gray("# Start dev server")}
|
|
@@ -1458,7 +1458,7 @@ ${m.bold("\u{1F310} API endpoints:")}
|
|
|
1458
1458
|
|
|
1459
1459
|
${m.gray("Alternative: npm run start:dev, ./rapidkit dev")}
|
|
1460
1460
|
${m.gray("\u{1F4A1} Tip: Install globally (npm i -g rapidkit) to use without npx")}
|
|
1461
|
-
`);}catch(s){throw i.fail(`Failed to generate ${r} project`),s}}P();ce();async function po(){let e=process.platform==="win32"?["python","python3"]:["python3","python"];for(let o of e)try{let{stdout:t}=await execa(o,["--version"],{timeout:3e3}),n=t.match(/Python (\d+\.\d+\.\d+)/);if(n){let r=n[1],[i,s]=r.split(".").map(Number);return i<3||i===3&&s<10?{status:"warn",message:`Python ${r} (requires 3.10+)`,details:`${o} found but version is below minimum requirement`}:{status:"ok",message:`Python ${r}`,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 uo(){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 mo(){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 go(){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"}],n=[{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:i,path:s}of [...t,...n])try{if(await b__default.pathExists(s)){let{stdout:a,exitCode:c}=await execa(s,["--version"],{timeout:3e3,reject:!1});if(c===0&&(a.includes("RapidKit Version")||a.includes("RapidKit"))){let l=a.match(/v?([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);l&&o.push({location:i,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:i,exitCode:s}=await execa("rapidkit",["--version"],{timeout:3e3,reject:!1});if(s===0&&(i.includes("RapidKit Version")||i.includes("RapidKit"))){let a=i.match(/v?([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);if(a)return {status:"ok",message:`RapidKit Core ${a[1]}`,details:"Available via PATH"}}}catch{}try{let{stdout:i,exitCode:s}=await execa("poetry",["run","rapidkit","--version"],{timeout:3e3,reject:!1});if(s===0&&(i.includes("RapidKit Version")||i.includes("RapidKit"))){let a=i.match(/v?([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);if(a)return {status:"ok",message:`RapidKit Core ${a[1]}`,details:"Available via Poetry"}}}catch{}let r=process.platform==="win32"?["python","python3"]:["python3","python"];for(let i of r)try{let{stdout:s,exitCode:a}=await execa(i,["-c","import rapidkit_core; print(rapidkit_core.__version__)"],{timeout:3e3,reject:!1});if(a===0&&s&&!s.includes("Traceback")&&!s.includes("ModuleNotFoundError")){let c=s.trim();if(c)return {status:"ok",message:`RapidKit Core ${c}`,details:`Available in ${i} environment`}}}catch{continue}return {status:"error",message:"RapidKit Core not installed",details:"Install with: pipx install rapidkit-core"}}async function yt(e,o){let t=v.join(e,"Dockerfile");o.hasDocker=await b__default.pathExists(t);let n=v.join(e,"tests"),r=v.join(e,"test");if(o.hasTests=await b__default.pathExists(n)||await b__default.pathExists(r),o.framework==="NestJS"){let i=v.join(e,".eslintrc.js"),s=v.join(e,".eslintrc.json");o.hasCodeQuality=await b__default.pathExists(i)||await b__default.pathExists(s);}else if(o.framework==="FastAPI"){let i=v.join(e,"ruff.toml"),s=v.join(e,"pyproject.toml");if(await b__default.pathExists(s))try{let a=await b__default.readFile(s,"utf8");o.hasCodeQuality=a.includes("[tool.ruff]")||await b__default.pathExists(i);}catch{o.hasCodeQuality=await b__default.pathExists(i);}}try{if(o.framework==="NestJS"){let{stdout:i}=await execa("npm",["audit","--json"],{cwd:e,reject:!1});if(i)try{let a=JSON.parse(i).metadata?.vulnerabilities;a&&(o.vulnerabilities=(a.high||0)+(a.critical||0)+(a.moderate||0));}catch{}}else if(o.framework==="FastAPI"){let i=v.join(e,".venv"),s=process.platform==="win32"?v.join(i,"Scripts","python.exe"):v.join(i,"bin","python");if(await b__default.pathExists(s))try{let{stdout:a}=await execa(s,["-m","pip","list","--format=json"],{timeout:5e3,reject:!1});if(a){let c=JSON.parse(a);o.vulnerabilities=0;}}catch{}}}catch{}}async function Gn(e){let t={name:v.basename(e),path:e,venvActive:false,depsInstalled:false,coreInstalled:false,issues:[],fixCommands:[]},n=v.join(e,".rapidkit");if(!await b__default.pathExists(n))return t.issues.push("Not a valid RapidKit project (missing .rapidkit directory)"),t;try{let c=v.join(e,"registry.json");if(await b__default.pathExists(c)){let l=await b__default.readJson(c);l.installed_modules&&(t.stats={modules:l.installed_modules.length});}}catch{}try{let c=v.join(n,"project.json");if(await b__default.pathExists(c)){let l=await b__default.readJson(c);l.kit&&(t.kit=l.kit);}}catch{}try{let c=v.join(e,".git");if(await b__default.pathExists(c)){let{stdout:l}=await execa("git",["log","-1","--format=%cr"],{cwd:e,reject:!1});l&&(t.lastModified=l.trim());}else {let l=await b__default.stat(e),p=Date.now()-l.mtime.getTime(),u=Math.floor(p/(1e3*60*60*24));t.lastModified=u===0?"today":`${u} day${u>1?"s":""} ago`;}}catch{}let r=v.join(e,"package.json"),i=v.join(e,"pyproject.toml"),s=await b__default.pathExists(r),a=await b__default.pathExists(i);if(s){t.framework="NestJS",t.venvActive=true;let c=v.join(e,"node_modules");if(await b__default.pathExists(c))try{let u=(await b__default.readdir(c)).filter(g=>!g.startsWith(".")&&!g.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 l=v.join(e,".env");if(t.hasEnvFile=await b__default.pathExists(l),!t.hasEnvFile){let p=v.join(e,".env.example");await b__default.pathExists(p)&&(t.issues.push("Environment file missing (found .env.example)"),t.fixCommands?.push(`cd ${e} && cp .env.example .env`));}let d=v.join(e,"src");if(t.modulesHealthy=true,t.missingModules=[],await b__default.pathExists(d))try{let p=await b__default.readdir(d);t.modulesHealthy=p.length>0;}catch{t.modulesHealthy=false;}return await yt(e,t),t}if(a){t.framework="FastAPI";let c=v.join(e,".venv");if(await b__default.pathExists(c)){t.venvActive=true;let u=process.platform==="win32"?v.join(c,"Scripts","python.exe"):v.join(c,"bin","python");if(await b__default.pathExists(u)){try{let{stdout:g}=await execa(u,["-c","import rapidkit_core; print(rapidkit_core.__version__)"],{timeout:2e3});t.coreInstalled=!0,t.coreVersion=g.trim();}catch{t.coreInstalled=false;}try{await execa(u,["-c","import fastapi"],{timeout:2e3}),t.depsInstalled=!0;}catch{try{let g=v.join(c,"lib");if(await b__default.pathExists(g)){let w=(await b__default.readdir(g)).find(C=>C.startsWith("python"));if(w){let C=v.join(g,w,"site-packages");if(await b__default.pathExists(C)){let F=(await b__default.readdir(C)).filter(H=>!H.startsWith("_")&&!H.includes("dist-info")&&!["pip","setuptools","wheel","pkg_resources"].includes(H));t.depsInstalled=F.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 l=v.join(e,".env");if(t.hasEnvFile=await b__default.pathExists(l),!t.hasEnvFile){let u=v.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 d=v.join(e,"src"),p=v.join(e,"modules");if(t.modulesHealthy=true,t.missingModules=[],await b__default.pathExists(d)){let u=v.join(d,"__init__.py");await b__default.pathExists(u)||(t.modulesHealthy=false,t.missingModules.push("src/__init__.py"));}if(await b__default.pathExists(p))try{let u=await fo(p);for(let g of u){let h=v.join(p,g,"__init__.py");await b__default.pathExists(h)||(t.modulesHealthy=!1,t.missingModules.push(`modules/${g}/__init__.py`));}}catch{}return !t.modulesHealthy&&t.missingModules.length>0&&t.issues.push(`Missing module init files: ${t.missingModules.join(", ")}`),await yt(e,t),t}return t.issues.push("Unknown project type (no package.json or pyproject.toml)"),await yt(e,t),t}async function fo(e){try{return (await b__default.readdir(e,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name)}catch{try{let o=await b__default.readdir(e),t=[];for(let n of o)try{(await b__default.stat(v.join(e,n))).isDirectory()&&t.push(n);}catch{continue}return t}catch{return []}}}async function Wn(e,o,t){let n=new Set,r=[{dir:e,depth:0}];for(;r.length>0;){let i=r.shift();if(!i)break;try{let s=await b__default.readdir(i.dir);for(let a of s){if(t.has(a))continue;let c=v.join(i.dir,a),l;try{l=await b__default.stat(c);}catch{continue}if(!l.isDirectory())continue;let d=v.join(c,".rapidkit");if(await b__default.pathExists(d)){n.add(c);continue}i.depth<o&&r.push({dir:c,depth:i.depth+1});}}catch{continue}}return Array.from(n)}async function Vn(e){let o=e,t=v.parse(o).root;for(;o!==t;){let n=[v.join(o,".rapidkit-workspace"),v.join(o,".rapidkit","workspace-marker.json"),v.join(o,".rapidkit","config.json")];for(let r of n)if(await b__default.pathExists(r))return o;o=v.dirname(o);}return null}function Un(e,o){let t=0,n=0,r=0;return e.forEach(s=>{s.status==="ok"?t++:s.status==="warn"?n++:s.status==="error"&&r++;}),o.forEach(s=>{s.issues.length===0&&s.venvActive&&s.depsInstalled?t++:s.issues.length>0&&n++;}),{total:t+n+r,passed:t,warnings:n,errors:r}}async function Bn(e){let o=v.basename(e);try{let r=v.join(e,".rapidkit-workspace");await b__default.pathExists(r)&&(o=(await b__default.readJSON(r)).name||o);}catch{try{let r=v.join(e,".rapidkit","config.json");o=(await b__default.readJSON(r)).workspace_name||o;}catch{}}let t={workspacePath:e,workspaceName:o,python:await po(),poetry:await uo(),pipx:await mo(),rapidkitCore:await go(),projects:[]};try{let r=new Set([".git",".venv","node_modules",".rapidkit","dist","build","coverage","__pycache__"]),i=new Set,s=v.join(e,".rapidkit");await b__default.pathExists(s)&&i.add(e);let a=async(c,l)=>{if(l<0)return;let d=await fo(c);for(let p of d){if(r.has(p))continue;let u=v.join(c,p),g=v.join(u,".rapidkit");if(await b__default.pathExists(g)){i.add(u);continue}l>0&&await a(u,l-1);}};if(await a(e,1),y.debug(`Workspace scan (shallow) found ${i.size} project(s)`),i.size===0){let c=await Wn(e,3,r);c.forEach(l=>i.add(l)),y.debug(`Workspace scan (deep fallback) found ${c.length} project(s)`);}i.size>0&&y.debug(`Workspace projects detected: ${Array.from(i).join(", ")}`);for(let c of i){let l=await Gn(c);t.projects.push(l);}}catch(r){y.debug(`Failed to scan workspace projects: ${r}`);}let n=[t.python,t.poetry,t.pipx,t.rapidkitCore];if(t.healthScore=Un(n,t.projects),t.rapidkitCore.status==="ok"){let r=t.rapidkitCore.message.match(/([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);r&&(t.coreVersion=r[1]);}return t}function ie(e,o){let t=e.status==="ok"?"\u2705":e.status==="warn"?"\u26A0\uFE0F":"\u274C",n=e.status==="ok"?m.green:e.status==="warn"?m.yellow:m.red;console.log(`${t} ${m.bold(o)}: ${n(e.message)}`),e.paths&&e.paths.length>0?e.paths.forEach(r=>{let i=r.version?m.cyan(` -> ${r.version}`):"";console.log(` ${m.cyan("\u2022")} ${m.gray(r.location)}: ${m.dim(r.path)}${i}`);}):e.details&&console.log(` ${m.gray(e.details)}`);}function Hn(e){let o=e.issues.length>0,t=o?"\u26A0\uFE0F":"\u2705",n=o?m.yellow:m.green;if(console.log(`
|
|
1461
|
+
`);}catch(s){throw i.fail(`Failed to generate ${r} project`),s}}j();ce();async function po(){let e=process.platform==="win32"?["python","python3"]:["python3","python"];for(let o of e)try{let{stdout:t}=await execa(o,["--version"],{timeout:3e3}),n=t.match(/Python (\d+\.\d+\.\d+)/);if(n){let r=n[1],[i,s]=r.split(".").map(Number);return i<3||i===3&&s<10?{status:"warn",message:`Python ${r} (requires 3.10+)`,details:`${o} found but version is below minimum requirement`}:{status:"ok",message:`Python ${r}`,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 uo(){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 mo(){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 go(){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"}],n=[{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:i,path:s}of [...t,...n])try{if(await b__default.pathExists(s)){let{stdout:a,exitCode:c}=await execa(s,["--version"],{timeout:3e3,reject:!1});if(c===0&&(a.includes("RapidKit Version")||a.includes("RapidKit"))){let l=a.match(/v?([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);l&&o.push({location:i,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:i,exitCode:s}=await execa("rapidkit",["--version"],{timeout:3e3,reject:!1});if(s===0&&(i.includes("RapidKit Version")||i.includes("RapidKit"))){let a=i.match(/v?([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);if(a)return {status:"ok",message:`RapidKit Core ${a[1]}`,details:"Available via PATH"}}}catch{}try{let{stdout:i,exitCode:s}=await execa("poetry",["run","rapidkit","--version"],{timeout:3e3,reject:!1});if(s===0&&(i.includes("RapidKit Version")||i.includes("RapidKit"))){let a=i.match(/v?([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);if(a)return {status:"ok",message:`RapidKit Core ${a[1]}`,details:"Available via Poetry"}}}catch{}let r=process.platform==="win32"?["python","python3"]:["python3","python"];for(let i of r)try{let{stdout:s,exitCode:a}=await execa(i,["-c","import rapidkit_core; print(rapidkit_core.__version__)"],{timeout:3e3,reject:!1});if(a===0&&s&&!s.includes("Traceback")&&!s.includes("ModuleNotFoundError")){let c=s.trim();if(c)return {status:"ok",message:`RapidKit Core ${c}`,details:`Available in ${i} environment`}}}catch{continue}return {status:"error",message:"RapidKit Core not installed",details:"Install with: pipx install rapidkit-core"}}async function yt(e,o){let t=v.join(e,"Dockerfile");o.hasDocker=await b__default.pathExists(t);let n=v.join(e,"tests"),r=v.join(e,"test");if(o.hasTests=await b__default.pathExists(n)||await b__default.pathExists(r),o.framework==="NestJS"){let i=v.join(e,".eslintrc.js"),s=v.join(e,".eslintrc.json");o.hasCodeQuality=await b__default.pathExists(i)||await b__default.pathExists(s);}else if(o.framework==="FastAPI"){let i=v.join(e,"ruff.toml"),s=v.join(e,"pyproject.toml");if(await b__default.pathExists(s))try{let a=await b__default.readFile(s,"utf8");o.hasCodeQuality=a.includes("[tool.ruff]")||await b__default.pathExists(i);}catch{o.hasCodeQuality=await b__default.pathExists(i);}}try{if(o.framework==="NestJS"){let{stdout:i}=await execa("npm",["audit","--json"],{cwd:e,reject:!1});if(i)try{let a=JSON.parse(i).metadata?.vulnerabilities;a&&(o.vulnerabilities=(a.high||0)+(a.critical||0)+(a.moderate||0));}catch{}}else if(o.framework==="FastAPI"){let i=v.join(e,".venv"),s=process.platform==="win32"?v.join(i,"Scripts","python.exe"):v.join(i,"bin","python");if(await b__default.pathExists(s))try{let{stdout:a}=await execa(s,["-m","pip","list","--format=json"],{timeout:5e3,reject:!1});if(a){let c=JSON.parse(a);o.vulnerabilities=0;}}catch{}}}catch{}}async function Wn(e){let t={name:v.basename(e),path:e,venvActive:false,depsInstalled:false,coreInstalled:false,issues:[],fixCommands:[]},n=v.join(e,".rapidkit");if(!await b__default.pathExists(n))return t.issues.push("Not a valid RapidKit project (missing .rapidkit directory)"),t;try{let c=v.join(e,"registry.json");if(await b__default.pathExists(c)){let l=await b__default.readJson(c);l.installed_modules&&(t.stats={modules:l.installed_modules.length});}}catch{}try{let c=v.join(n,"project.json");if(await b__default.pathExists(c)){let l=await b__default.readJson(c);l.kit&&(t.kit=l.kit);}}catch{}try{let c=v.join(e,".git");if(await b__default.pathExists(c)){let{stdout:l}=await execa("git",["log","-1","--format=%cr"],{cwd:e,reject:!1});l&&(t.lastModified=l.trim());}else {let l=await b__default.stat(e),p=Date.now()-l.mtime.getTime(),u=Math.floor(p/(1e3*60*60*24));t.lastModified=u===0?"today":`${u} day${u>1?"s":""} ago`;}}catch{}let r=v.join(e,"package.json"),i=v.join(e,"pyproject.toml"),s=await b__default.pathExists(r),a=await b__default.pathExists(i);if(s){t.framework="NestJS",t.venvActive=true;let c=v.join(e,"node_modules");if(await b__default.pathExists(c))try{let u=(await b__default.readdir(c)).filter(g=>!g.startsWith(".")&&!g.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 l=v.join(e,".env");if(t.hasEnvFile=await b__default.pathExists(l),!t.hasEnvFile){let p=v.join(e,".env.example");await b__default.pathExists(p)&&(t.issues.push("Environment file missing (found .env.example)"),t.fixCommands?.push(`cd ${e} && cp .env.example .env`));}let d=v.join(e,"src");if(t.modulesHealthy=true,t.missingModules=[],await b__default.pathExists(d))try{let p=await b__default.readdir(d);t.modulesHealthy=p.length>0;}catch{t.modulesHealthy=false;}return await yt(e,t),t}if(a){t.framework="FastAPI";let c=v.join(e,".venv");if(await b__default.pathExists(c)){t.venvActive=true;let u=process.platform==="win32"?v.join(c,"Scripts","python.exe"):v.join(c,"bin","python");if(await b__default.pathExists(u)){try{let{stdout:g}=await execa(u,["-c","import rapidkit_core; print(rapidkit_core.__version__)"],{timeout:2e3});t.coreInstalled=!0,t.coreVersion=g.trim();}catch{t.coreInstalled=false;}try{await execa(u,["-c","import fastapi"],{timeout:2e3}),t.depsInstalled=!0;}catch{try{let g=v.join(c,"lib");if(await b__default.pathExists(g)){let h=(await b__default.readdir(g)).find(x=>x.startsWith("python"));if(h){let x=v.join(g,h,"site-packages");if(await b__default.pathExists(x)){let F=(await b__default.readdir(x)).filter(V=>!V.startsWith("_")&&!V.includes("dist-info")&&!["pip","setuptools","wheel","pkg_resources"].includes(V));t.depsInstalled=F.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 l=v.join(e,".env");if(t.hasEnvFile=await b__default.pathExists(l),!t.hasEnvFile){let u=v.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 d=v.join(e,"src"),p=v.join(e,"modules");if(t.modulesHealthy=true,t.missingModules=[],await b__default.pathExists(d)){let u=v.join(d,"__init__.py");await b__default.pathExists(u)||(t.modulesHealthy=false,t.missingModules.push("src/__init__.py"));}if(await b__default.pathExists(p))try{let u=await fo(p);for(let g of u){let w=v.join(p,g,"__init__.py");await b__default.pathExists(w)||(t.modulesHealthy=!1,t.missingModules.push(`modules/${g}/__init__.py`));}}catch{}return !t.modulesHealthy&&t.missingModules.length>0&&t.issues.push(`Missing module init files: ${t.missingModules.join(", ")}`),await yt(e,t),t}return t.issues.push("Unknown project type (no package.json or pyproject.toml)"),await yt(e,t),t}async function fo(e){try{return (await b__default.readdir(e,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name)}catch{try{let o=await b__default.readdir(e),t=[];for(let n of o)try{(await b__default.stat(v.join(e,n))).isDirectory()&&t.push(n);}catch{continue}return t}catch{return []}}}async function Vn(e,o,t){let n=new Set,r=[{dir:e,depth:0}];for(;r.length>0;){let i=r.shift();if(!i)break;try{let s=await b__default.readdir(i.dir);for(let a of s){if(t.has(a))continue;let c=v.join(i.dir,a),l;try{l=await b__default.stat(c);}catch{continue}if(!l.isDirectory())continue;let d=v.join(c,".rapidkit");if(await b__default.pathExists(d)){n.add(c);continue}i.depth<o&&r.push({dir:c,depth:i.depth+1});}}catch{continue}}return Array.from(n)}async function Un(e){let o=e,t=v.parse(o).root;for(;o!==t;){let n=[v.join(o,".rapidkit-workspace"),v.join(o,".rapidkit","workspace-marker.json"),v.join(o,".rapidkit","config.json")];for(let r of n)if(await b__default.pathExists(r))return o;o=v.dirname(o);}return null}function Bn(e,o){let t=0,n=0,r=0;return e.forEach(s=>{s.status==="ok"?t++:s.status==="warn"?n++:s.status==="error"&&r++;}),o.forEach(s=>{s.issues.length===0&&s.venvActive&&s.depsInstalled?t++:s.issues.length>0&&n++;}),{total:t+n+r,passed:t,warnings:n,errors:r}}async function Hn(e){let o=v.basename(e);try{let r=v.join(e,".rapidkit-workspace");await b__default.pathExists(r)&&(o=(await b__default.readJSON(r)).name||o);}catch{try{let r=v.join(e,".rapidkit","config.json");o=(await b__default.readJSON(r)).workspace_name||o;}catch{}}let t={workspacePath:e,workspaceName:o,python:await po(),poetry:await uo(),pipx:await mo(),rapidkitCore:await go(),projects:[]};try{let r=new Set([".git",".venv","node_modules",".rapidkit","dist","build","coverage","__pycache__"]),i=new Set,s=v.join(e,".rapidkit");await b__default.pathExists(s)&&i.add(e);let a=async(c,l)=>{if(l<0)return;let d=await fo(c);for(let p of d){if(r.has(p))continue;let u=v.join(c,p),g=v.join(u,".rapidkit");if(await b__default.pathExists(g)){i.add(u);continue}l>0&&await a(u,l-1);}};if(await a(e,1),y.debug(`Workspace scan (shallow) found ${i.size} project(s)`),i.size===0){let c=await Vn(e,3,r);c.forEach(l=>i.add(l)),y.debug(`Workspace scan (deep fallback) found ${c.length} project(s)`);}i.size>0&&y.debug(`Workspace projects detected: ${Array.from(i).join(", ")}`);for(let c of i){let l=await Wn(c);t.projects.push(l);}}catch(r){y.debug(`Failed to scan workspace projects: ${r}`);}let n=[t.python,t.poetry,t.pipx,t.rapidkitCore];if(t.healthScore=Bn(n,t.projects),t.rapidkitCore.status==="ok"){let r=t.rapidkitCore.message.match(/([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);r&&(t.coreVersion=r[1]);}return t}function ie(e,o){let t=e.status==="ok"?"\u2705":e.status==="warn"?"\u26A0\uFE0F":"\u274C",n=e.status==="ok"?m.green:e.status==="warn"?m.yellow:m.red;console.log(`${t} ${m.bold(o)}: ${n(e.message)}`),e.paths&&e.paths.length>0?e.paths.forEach(r=>{let i=r.version?m.cyan(` -> ${r.version}`):"";console.log(` ${m.cyan("\u2022")} ${m.gray(r.location)}: ${m.dim(r.path)}${i}`);}):e.details&&console.log(` ${m.gray(e.details)}`);}function Jn(e){let o=e.issues.length>0,t=o?"\u26A0\uFE0F":"\u2705",n=o?m.yellow:m.green;if(console.log(`
|
|
1462
1462
|
${t} ${m.bold("Project")}: ${n(e.name)}`),e.framework){let a=e.framework==="FastAPI"?"\u{1F40D}":e.framework==="NestJS"?"\u{1F985}":"\u{1F4E6}";console.log(` ${a} Framework: ${m.cyan(e.framework)}${e.kit?m.gray(` (${e.kit})`):""}`);}if(console.log(` ${m.gray(`Path: ${e.path}`)}`),!(e.venvActive&&!e.coreInstalled)&&(e.venvActive?console.log(` \u2705 Virtual environment: ${m.green("Active")}`):console.log(` \u274C Virtual environment: ${m.red("Not found")}`),e.coreInstalled?console.log(` ${m.dim("\u2139")} RapidKit Core: ${m.gray(e.coreVersion||"In venv")} ${m.dim("(optional)")}`):console.log(` ${m.dim("\u2139")} RapidKit Core: ${m.gray("Using global installation")} ${m.dim("(recommended)")}`)),e.depsInstalled?console.log(` \u2705 Dependencies: ${m.green("Installed")}`):console.log(` \u26A0\uFE0F Dependencies: ${m.yellow("Not installed")}`),e.hasEnvFile!==void 0&&(e.hasEnvFile?console.log(` \u2705 Environment: ${m.green(".env configured")}`):console.log(` \u26A0\uFE0F Environment: ${m.yellow(".env missing")}`)),e.modulesHealthy!==void 0&&(e.modulesHealthy?console.log(` \u2705 Modules: ${m.green("Healthy")}`):e.missingModules&&e.missingModules.length>0&&console.log(` \u26A0\uFE0F Modules: ${m.yellow(`Missing ${e.missingModules.length} init file(s)`)}`)),e.stats){let a=[];e.stats.modules!==void 0&&a.push(`${e.stats.modules} module${e.stats.modules!==1?"s":""}`),a.length>0&&console.log(` \u{1F4CA} Stats: ${m.cyan(a.join(" \u2022 "))}`);}e.lastModified&&console.log(` \u{1F552} Last Modified: ${m.gray(e.lastModified)}`);let s=[];if(e.hasTests!==void 0&&s.push(e.hasTests?"\u2705 Tests":m.dim("\u2298 No tests")),e.hasDocker!==void 0&&s.push(e.hasDocker?"\u2705 Docker":m.dim("\u2298 No Docker")),e.hasCodeQuality!==void 0){let a=e.framework==="NestJS"?"ESLint":"Ruff";s.push(e.hasCodeQuality?`\u2705 ${a}`:m.dim(`\u2298 No ${a}`));}s.length>0&&console.log(` ${s.join(" \u2022 ")}`),e.vulnerabilities!==void 0&&e.vulnerabilities>0&&console.log(` \u26A0\uFE0F Security: ${m.yellow(`${e.vulnerabilities} vulnerability(ies) found`)}`),e.issues.length>0&&(console.log(` ${m.bold("Issues:")}`),e.issues.forEach(a=>{console.log(` \u2022 ${m.yellow(a)}`);}),e.fixCommands&&e.fixCommands.length>0&&(console.log(`
|
|
1463
1463
|
${m.bold.cyan("\u{1F527} Quick Fix:")}`),e.fixCommands.forEach(a=>{console.log(` ${m.cyan("$")} ${m.white(a)}`);})));}async function lo(e,o=false){let t=e.filter(r=>r.fixCommands&&r.fixCommands.length>0);if(t.length===0){console.log(m.green(`
|
|
1464
1464
|
\u2705 No fixes needed - all projects are healthy!`));return}console.log(m.bold.cyan(`
|
|
@@ -1471,13 +1471,13 @@ ${t} ${m.bold("Project")}: ${n(e.name)}`),e.framework){let a=e.framework==="Fast
|
|
|
1471
1471
|
`));}}console.log(m.bold.green(`
|
|
1472
1472
|
\u2705 Fix process completed!`));}async function ho(e={}){if(e.json||console.log(m.bold.cyan(`
|
|
1473
1473
|
\u{1FA7A} RapidKit Health Check
|
|
1474
|
-
`)),e.workspace){let o=await
|
|
1474
|
+
`)),e.workspace){let o=await Un(process.cwd());o||(y.error("No RapidKit workspace found in current directory or parents"),y.info('Run this command from within a workspace, or use "rapidkit doctor" for system check'),process.exit(1)),e.json||(console.log(m.bold(`Workspace: ${m.cyan(v.basename(o))}`)),console.log(m.gray(`Path: ${o}`)));let t=await Hn(o);if(e.json){let i={workspace:{name:v.basename(o),path:o},healthScore:t.healthScore,system:{python:t.python,poetry:t.poetry,pipx:t.pipx,rapidkitCore:t.rapidkitCore,versions:{core:t.coreVersion,npm:t.npmVersion}},projects:t.projects.map(s=>({name:s.name,path:s.path,venvActive:s.venvActive,depsInstalled:s.depsInstalled,coreInstalled:s.coreInstalled,coreVersion:s.coreVersion,issues:s.issues,fixCommands:s.fixCommands})),summary:{totalProjects:t.projects.length,totalIssues:t.projects.reduce((s,a)=>s+a.issues.length,0),hasSystemErrors:[t.python,t.rapidkitCore].some(s=>s.status==="error")}};console.log(JSON.stringify(i,null,2));return}if(t.healthScore){let i=t.healthScore,s=Math.round(i.passed/i.total*100),a=s>=80?m.green:s>=50?m.yellow:m.red,c="\u2588".repeat(Math.floor(s/5))+"\u2591".repeat(20-Math.floor(s/5));console.log(m.bold(`
|
|
1475
1475
|
\u{1F4CA} Health Score:`)),console.log(` ${a(`${s}%`)} ${m.gray(c)}`),console.log(` ${m.green(`\u2705 ${i.passed} passed`)} ${m.gray("|")} ${m.yellow(`\u26A0\uFE0F ${i.warnings} warnings`)} ${m.gray("|")} ${m.red(`\u274C ${i.errors} errors`)}`);}if(console.log(m.bold(`
|
|
1476
1476
|
|
|
1477
1477
|
System Tools:
|
|
1478
1478
|
`)),ie(t.python,"Python"),ie(t.poetry,"Poetry"),ie(t.pipx,"pipx"),ie(t.rapidkitCore,"RapidKit Core"),t.coreVersion&&t.npmVersion){let i=t.coreVersion.split(".")[1],s=t.npmVersion.split(".")[1];i!==s&&(console.log(m.yellow(`
|
|
1479
1479
|
\u26A0\uFE0F Version mismatch: Core ${t.coreVersion} / CLI ${t.npmVersion}`)),console.log(m.gray(" Consider updating to matching versions for best compatibility")));}t.projects.length>0?(console.log(m.bold(`
|
|
1480
|
-
\u{1F4E6} Projects (${t.projects.length}):`)),t.projects.forEach(i=>
|
|
1480
|
+
\u{1F4E6} Projects (${t.projects.length}):`)),t.projects.forEach(i=>Jn(i))):(console.log(m.bold(`
|
|
1481
1481
|
\u{1F4E6} Projects:`)),console.log(m.gray(" No RapidKit projects found in workspace")));let n=t.projects.reduce((i,s)=>i+s.issues.length,0),r=[t.python,t.rapidkitCore].some(i=>i.status==="error");r||n>0?(console.log(m.bold.yellow(`
|
|
1482
1482
|
\u26A0\uFE0F Found ${n} project issue(s)`)),r&&console.log(m.bold.red("\u274C System requirements not met")),e.fix?await lo(t.projects,true):n>0&&await lo(t.projects,false)):console.log(m.bold.green(`
|
|
1483
1483
|
\u2705 All checks passed! Workspace is healthy.`));}else {console.log(m.bold(`System Tools:
|
|
@@ -1485,9 +1485,9 @@ System Tools:
|
|
|
1485
1485
|
\u274C Some required tools are missing`)),console.log(m.gray(`
|
|
1486
1486
|
Tip: Run "rapidkit doctor --workspace" from within a workspace for detailed project checks`))):(console.log(m.bold.green(`
|
|
1487
1487
|
\u2705 All required tools are installed!`)),console.log(m.gray(`
|
|
1488
|
-
Tip: Run "rapidkit doctor --workspace" from within a workspace for detailed project checks`)));}console.log("");}
|
|
1488
|
+
Tip: Run "rapidkit doctor --workspace" from within a workspace for detailed project checks`)));}console.log("");}j();j();var wt=v.join(te__default.homedir(),".rapidkit"),Ue=v.join(wt,"config.json");function ke(){try{if(!W.existsSync(Ue))return {};let e=W.readFileSync(Ue,"utf-8");return JSON.parse(e)}catch{return {}}}function Be(e){let t={...ke(),...e};W.existsSync(wt)||W.mkdirSync(wt,{recursive:true}),W.writeFileSync(Ue,JSON.stringify(t,null,2),"utf-8");}function Ae(){return process.env.OPENAI_API_KEY||ke().openaiApiKey||null}function kt(){return ke().aiEnabled!==false}function vt(){return Ue}function ko(e){let o=e.command("config").description("Configure RapidKit settings");o.command("set-api-key").description("Set OpenAI API key for AI features").option("--key <key>","API key (or enter interactively)").action(async t=>{let n=t.key;n?n.startsWith("sk-")||(console.log(m.red(`
|
|
1489
1489
|
\u274C Invalid API key format (should start with sk-)
|
|
1490
|
-
`)),process.exit(1)):n=(await gt.prompt([{type:"password",name:"apiKey",message:"Enter your OpenAI API key:",validate:i=>i?i.startsWith("sk-")?i.length<20?"API key seems too short":true:"Invalid API key format (should start with sk-)":"API key is required"}])).apiKey,
|
|
1490
|
+
`)),process.exit(1)):n=(await gt.prompt([{type:"password",name:"apiKey",message:"Enter your OpenAI API key:",validate:i=>i?i.startsWith("sk-")?i.length<20?"API key seems too short":true:"Invalid API key format (should start with sk-)":"API key is required"}])).apiKey,Be({openaiApiKey:n}),console.log(m.green(`
|
|
1491
1491
|
\u2705 OpenAI API key saved successfully!
|
|
1492
1492
|
`)),console.log(m.gray(`Stored in: ${vt()}`)),console.log(m.cyan(`
|
|
1493
1493
|
\u{1F389} You can now use AI features:`)),console.log(m.white(' rapidkit ai recommend "I need user authentication"')),console.log(m.gray(`
|
|
@@ -1498,19 +1498,19 @@ Tip: Run "rapidkit doctor --workspace" from within a workspace for detailed proj
|
|
|
1498
1498
|
\u{1F4C1} Config file: ${vt()}
|
|
1499
1499
|
`));}),o.command("remove-api-key").description("Remove stored OpenAI API key").action(async()=>{if(!ke().openaiApiKey){console.log(m.yellow(`
|
|
1500
1500
|
\u26A0\uFE0F No API key is currently stored
|
|
1501
|
-
`));return}(await gt.prompt([{type:"confirm",name:"confirm",message:"Are you sure you want to remove your OpenAI API key?",default:false}])).confirm?(
|
|
1501
|
+
`));return}(await gt.prompt([{type:"confirm",name:"confirm",message:"Are you sure you want to remove your OpenAI API key?",default:false}])).confirm?(Be({openaiApiKey:void 0}),console.log(m.green(`
|
|
1502
1502
|
\u2705 API key removed successfully
|
|
1503
1503
|
`))):console.log(m.gray(`
|
|
1504
1504
|
Cancelled
|
|
1505
1505
|
`));}),o.command("ai <action>").description("Enable or disable AI features (enable|disable)").action(t=>{t!=="enable"&&t!=="disable"&&(console.log(m.red(`
|
|
1506
1506
|
\u274C Invalid action: ${t}`)),console.log(m.gray(`Use: rapidkit config ai enable|disable
|
|
1507
|
-
`)),process.exit(1));let n=t==="enable";
|
|
1507
|
+
`)),process.exit(1));let n=t==="enable";Be({aiEnabled:n}),console.log(m.green(`
|
|
1508
1508
|
\u2705 AI features ${n?"enabled":"disabled"}
|
|
1509
|
-
`));});}P();P();var Be=null,He=false;function vo(){He=true;}function bo(e){let t=new Array(1536),n=0;for(let i=0;i<e.length;i++)n=(n<<5)-n+e.charCodeAt(i),n=n&n;for(let i=0;i<1536;i++)n=n*1664525+1013904223&4294967295,t[i]=n/4294967295*2-1;let r=Math.sqrt(t.reduce((i,s)=>i+s*s,0));return t.map(i=>i/r)}function Je(e){Be=new Yn({apiKey:e});}function xo(){if(!Be)throw new Error("OpenAI client not initialized. Call initOpenAI() first with your API key.");return Be}async function Po(e){return He?bo(e):(await xo().embeddings.create({model:"text-embedding-3-small",input:e,encoding_format:"float"})).data[0].embedding}async function jo(e){return He?e.map(bo):(await xo().embeddings.create({model:"text-embedding-3-small",input:e,encoding_format:"float"})).data.map(n=>n.embedding)}function Co(){return Be!==null}function $o(){return He}P();P();var Qn=promisify(exec),_o=[{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,Ro=0,Xn=300*1e3;function Zn(e){return {id:e.name||e.id||e.module_id||"",name:e.display_name||e.name||"",category:ei(e.category||"infrastructure"),description:e.description||e.summary||"",longDescription:e.long_description||e.description||"",keywords:e.keywords||e.tags||[],framework:ti(e.framework),dependencies:e.dependencies||[],useCases:e.use_cases||e.useCases||[]}}function ei(e){return {auth:"auth",authentication:"auth",database:"database",payment:"payment",billing:"payment",communication:"communication",infrastructure:"infrastructure",security:"security",analytics:"analytics"}[e.toLowerCase()]||"infrastructure"}function ti(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 oi(){try{let{stdout:e}=await Qn("rapidkit modules list --json-schema 1",{timeout:1e4,maxBuffer:10485760}),o=e.match(/\{[\s\S]*\}/),t=o?o[0]:e,n=JSON.parse(t),r=[];return Array.isArray(n)?r=n:n.modules&&Array.isArray(n.modules)?r=n.modules:n.data&&Array.isArray(n.data)&&(r=n.data),r.map(Zn).filter(i=>i.id&&i.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)"),_o}}async function Ye(){let e=Date.now();return ve&&e-Ro<Xn||(ve=await oi(),Ro=e,ve.length===0&&(console.warn("\u26A0\uFE0F No modules found, using fallback catalog"),ve=_o)),ve}var ii=fileURLToPath(import.meta.url),Io=v.dirname(ii),Ae=null;function ri(){if(Ae)return Ae;let e=[v.join(Io,"../../data/modules-embeddings.json"),v.join(Io,"../data/modules-embeddings.json"),v.join(process.cwd(),"data/modules-embeddings.json")],o=null;for(let r of e)if(W.existsSync(r)){o=r;break}if(!o)throw new Error("embeddings file not found");let t=W.readFileSync(o,"utf-8"),n=JSON.parse(t);return Array.isArray(n)?Ae={model:"mock-or-text-embedding-3-small",dimension:n[0]?.embedding?.length||1536,generated_at:new Date().toISOString(),modules:n}:Ae=n,Ae}function si(e,o){if(e.length!==o.length)throw new Error("Vectors must have the same length");let t=0,n=0,r=0;for(let s=0;s<e.length;s++)t+=e[s]*o[s],n+=e[s]*e[s],r+=o[s]*o[s];let i=Math.sqrt(n)*Math.sqrt(r);return i===0?0:t/i}function ai(e,o){let t=o.toLowerCase(),n=e.keywords.filter(r=>t.includes(r)||r.includes(t));return n.length>0?`Matches: ${n.slice(0,3).join(", ")}`:`Relevant for: ${e.useCases[0]}`}async function Ao(e,o=5){let t=ri(),n=await Ye(),r=await Po(e),i=t.modules.map(s=>{let a=n.find(l=>l.id===s.id);if(!a)return null;let c=si(r,s.embedding);return {module:a,score:c,reason:ai(a,e)}}).filter(s=>s!==null);return i.sort((s,a)=>a.score-s.score),i.slice(0,o)}P();var di=fileURLToPath(import.meta.url),So=v.dirname(di);function pi(){return [v.join(So,"../../data/modules-embeddings.json"),v.join(So,"../data/modules-embeddings.json"),v.join(process.cwd(),"data/modules-embeddings.json")]}function No(){let e=pi();for(let o of e)if(W.existsSync(o))try{let t=JSON.parse(W.readFileSync(o,"utf-8")),n=Array.isArray(t)?t:t.modules||[];return {exists:!0,path:o,moduleCount:n.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(!Co()&&!$o())return console.log(m.red(`
|
|
1509
|
+
`));});}j();j();var He=null,Je=false;function vo(){Je=true;}function bo(e){let t=new Array(1536),n=0;for(let i=0;i<e.length;i++)n=(n<<5)-n+e.charCodeAt(i),n=n&n;for(let i=0;i<1536;i++)n=n*1664525+1013904223&4294967295,t[i]=n/4294967295*2-1;let r=Math.sqrt(t.reduce((i,s)=>i+s*s,0));return t.map(i=>i/r)}function Ye(e){He=new qn({apiKey:e});}function xo(){if(!He)throw new Error("OpenAI client not initialized. Call initOpenAI() first with your API key.");return He}async function Po(e){return Je?bo(e):(await xo().embeddings.create({model:"text-embedding-3-small",input:e,encoding_format:"float"})).data[0].embedding}async function jo(e){return Je?e.map(bo):(await xo().embeddings.create({model:"text-embedding-3-small",input:e,encoding_format:"float"})).data.map(n=>n.embedding)}function Co(){return He!==null}function $o(){return Je}j();j();var Xn=promisify(exec),Ro=[{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,_o=0,Zn=300*1e3;function ei(e){return {id:e.name||e.id||e.module_id||"",name:e.display_name||e.name||"",category:ti(e.category||"infrastructure"),description:e.description||e.summary||"",longDescription:e.long_description||e.description||"",keywords:e.keywords||e.tags||[],framework:oi(e.framework),dependencies:e.dependencies||[],useCases:e.use_cases||e.useCases||[]}}function ti(e){return {auth:"auth",authentication:"auth",database:"database",payment:"payment",billing:"payment",communication:"communication",infrastructure:"infrastructure",security:"security",analytics:"analytics"}[e.toLowerCase()]||"infrastructure"}function oi(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 ni(){try{let{stdout:e}=await Xn("rapidkit modules list --json-schema 1",{timeout:1e4,maxBuffer:10485760}),o=e.match(/\{[\s\S]*\}/),t=o?o[0]:e,n=JSON.parse(t),r=[];return Array.isArray(n)?r=n:n.modules&&Array.isArray(n.modules)?r=n.modules:n.data&&Array.isArray(n.data)&&(r=n.data),r.map(ei).filter(i=>i.id&&i.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)"),Ro}}async function qe(){let e=Date.now();return ve&&e-_o<Zn||(ve=await ni(),_o=e,ve.length===0&&(console.warn("\u26A0\uFE0F No modules found, using fallback catalog"),ve=Ro)),ve}var ri=fileURLToPath(import.meta.url),Io=v.dirname(ri),Se=null;function si(){if(Se)return Se;let e=[v.join(Io,"../../data/modules-embeddings.json"),v.join(Io,"../data/modules-embeddings.json"),v.join(process.cwd(),"data/modules-embeddings.json")],o=null;for(let r of e)if(W.existsSync(r)){o=r;break}if(!o)throw new Error("embeddings file not found");let t=W.readFileSync(o,"utf-8"),n=JSON.parse(t);return Array.isArray(n)?Se={model:"mock-or-text-embedding-3-small",dimension:n[0]?.embedding?.length||1536,generated_at:new Date().toISOString(),modules:n}:Se=n,Se}function ai(e,o){if(e.length!==o.length)throw new Error("Vectors must have the same length");let t=0,n=0,r=0;for(let s=0;s<e.length;s++)t+=e[s]*o[s],n+=e[s]*e[s],r+=o[s]*o[s];let i=Math.sqrt(n)*Math.sqrt(r);return i===0?0:t/i}function ci(e,o){let t=o.toLowerCase(),n=e.keywords.filter(r=>t.includes(r)||r.includes(t));return n.length>0?`Matches: ${n.slice(0,3).join(", ")}`:`Relevant for: ${e.useCases[0]}`}async function Ao(e,o=5){let t=si(),n=await qe(),r=await Po(e),i=t.modules.map(s=>{let a=n.find(l=>l.id===s.id);if(!a)return null;let c=ai(r,s.embedding);return {module:a,score:c,reason:ci(a,e)}}).filter(s=>s!==null);return i.sort((s,a)=>a.score-s.score),i.slice(0,o)}j();var pi=fileURLToPath(import.meta.url),So=v.dirname(pi);function ui(){return [v.join(So,"../../data/modules-embeddings.json"),v.join(So,"../data/modules-embeddings.json"),v.join(process.cwd(),"data/modules-embeddings.json")]}function No(){let e=ui();for(let o of e)if(W.existsSync(o))try{let t=JSON.parse(W.readFileSync(o,"utf-8")),n=Array.isArray(t)?t:t.modules||[];return {exists:!0,path:o,moduleCount:n.length,generatedAt:t.generated_at||null}}catch{continue}return {exists:false,path:null,moduleCount:0,generatedAt:null}}async function Qe(e=true,o){try{if(!Co()&&!$o())return console.log(m.red(`
|
|
1510
1510
|
\u274C OpenAI not initialized`)),console.log(m.yellow("Please set your API key:")),console.log(m.white(" rapidkit config set-api-key")),console.log(m.gray(` OR set: export OPENAI_API_KEY="sk-..."
|
|
1511
1511
|
`)),!1;console.log(m.blue(`
|
|
1512
1512
|
\u{1F916} Generating AI embeddings for RapidKit modules...
|
|
1513
|
-
`)),console.log(m.gray("\u{1F4E1} Fetching modules from RapidKit..."));let t=await
|
|
1513
|
+
`)),console.log(m.gray("\u{1F4E1} Fetching modules from RapidKit..."));let t=await qe();console.log(m.green(`\u2713 Found ${t.length} modules
|
|
1514
1514
|
`));let n=t.length*50/1e6*.02;if(console.log(m.cyan(`\u{1F4B0} Estimated cost: ~$${n.toFixed(3)}`)),console.log(m.gray(` (Based on ${t.length} modules at $0.02/1M tokens)
|
|
1515
1515
|
`)),e){let{confirm:s}=await gt.prompt([{type:"confirm",name:"confirm",message:"Generate embeddings now?",default:!0}]);if(!s)return console.log(m.yellow(`
|
|
1516
1516
|
\u26A0\uFE0F Embeddings generation cancelled
|
|
@@ -1527,18 +1527,18 @@ Cancelled
|
|
|
1527
1527
|
`)),false}}async function Mo(e=true){if(No().exists)return true;if(console.log(m.yellow(`
|
|
1528
1528
|
\u26A0\uFE0F Module embeddings not found`)),console.log(m.gray(`AI recommendations require embeddings to be generated.
|
|
1529
1529
|
`)),!e)return console.log(m.red("\u274C Cannot generate embeddings in non-interactive mode")),console.log(m.white(`Run: rapidkit ai generate-embeddings
|
|
1530
|
-
`)),false;let{action:t}=await gt.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 t==="generate"?await
|
|
1530
|
+
`)),false;let{action:t}=await gt.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 t==="generate"?await Qe(true):(t==="manual"&&(console.log(m.cyan(`
|
|
1531
1531
|
\u{1F4DD} To generate embeddings manually:
|
|
1532
1532
|
`)),console.log(m.white("1. Get OpenAI API key from: https://platform.openai.com/api-keys")),console.log(m.white("2. Set the API key:")),console.log(m.gray(" rapidkit config set-api-key")),console.log(m.gray(` OR: export OPENAI_API_KEY="sk-..."
|
|
1533
1533
|
`)),console.log(m.white("3. Generate embeddings:")),console.log(m.gray(` rapidkit ai generate-embeddings
|
|
1534
1534
|
`)),console.log(m.cyan(`\u{1F4B0} Cost: ~$0.50 one-time
|
|
1535
1535
|
`))),false)}async function Oo(){let e=No();return e.exists?(console.log(m.blue(`
|
|
1536
1536
|
\u{1F504} Updating embeddings...`)),console.log(m.gray(`Current: ${e.moduleCount} modules`)),console.log(m.gray(`Generated: ${e.generatedAt||"unknown"}
|
|
1537
|
-
`)),await
|
|
1537
|
+
`)),await Qe(true,e.path)):(console.log(m.yellow(`
|
|
1538
1538
|
\u26A0\uFE0F No existing embeddings found`)),console.log(m.gray(`Use: rapidkit ai generate-embeddings
|
|
1539
1539
|
`)),false)}ce();function To(e){let o=e.command("ai").description("AI-powered features");o.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,n)=>{try{kt()||(console.log(m.yellow(`
|
|
1540
1540
|
\u26A0\uFE0F AI features are disabled`)),console.log(m.gray(`Enable with: rapidkit config ai enable
|
|
1541
|
-
`)),process.exit(1));let r=
|
|
1541
|
+
`)),process.exit(1));let r=Ae();r?Ye(r):(console.log(m.yellow(`
|
|
1542
1542
|
\u26A0\uFE0F OpenAI API key not configured - using MOCK MODE for testing
|
|
1543
1543
|
`)),console.log(m.gray("\u{1F4DD} Note: Mock embeddings provide approximate results for testing.")),console.log(m.gray(` For production, configure your OpenAI API key:
|
|
1544
1544
|
`)),console.log(m.white(" 1. Get your key from: https://platform.openai.com/api-keys")),console.log(m.white(" 2. Configure it: rapidkit config set-api-key")),console.log(m.gray(` OR set: export OPENAI_API_KEY="sk-proj-..."
|
|
@@ -1554,7 +1554,7 @@ Cancelled
|
|
|
1554
1554
|
`)),console.log(m.white("3. Request feature:")),console.log(m.gray(` https://github.com/getrapidkit/rapidkit/issues
|
|
1555
1555
|
`)),c.length>0)console.log(m.yellow(`\u26A0\uFE0F Low confidence matches found:
|
|
1556
1556
|
`));else return;if(n.json){console.log(JSON.stringify({query:i,recommendations:c},null,2));return}console.log(m.green.bold(`\u{1F4E6} Recommended Modules:
|
|
1557
|
-
`)),c.forEach((p,u)=>{let g=(p.score*100).toFixed(1),
|
|
1557
|
+
`)),c.forEach((p,u)=>{let g=(p.score*100).toFixed(1),w=p.score>.8?" \u2B50":"";console.log(m.bold(`${u+1}. ${p.module.name}${w}`)),console.log(m.gray(` ${p.module.description}`)),console.log(m.cyan(` Match: ${g}%`)+m.gray(` - ${p.reason}`)),console.log(m.yellow(` Category: ${p.module.category}`)),p.module.dependencies.length>0&&console.log(m.magenta(` Requires: ${p.module.dependencies.join(", ")}`)),console.log();});let l=c.slice(0,3).map(p=>p.module.id);console.log(m.cyan("\u{1F4A1} Quick install (top 3):")),console.log(m.white(` rapidkit add module ${l.join(" ")}
|
|
1558
1558
|
`));let{shouldInstall:d}=await gt.prompt([{type:"confirm",name:"shouldInstall",message:"Would you like to install these modules now?",default:!1}]);if(d){let{selectedModules:p}=await gt.prompt([{type:"checkbox",name:"selectedModules",message:"Select modules to install:",choices:c.map(u=>({name:`${u.module.name} - ${u.module.description}`,value:u.module.id,checked:u.score>.7}))}]);p.length>0?(console.log(m.blue(`
|
|
1559
1559
|
\u{1F4E6} Installing ${p.length} modules...
|
|
1560
1560
|
`)),console.log(m.gray(`Command: rapidkit add module ${p.join(" ")}`)),console.log(m.yellow(`
|
|
@@ -1566,7 +1566,7 @@ No modules selected
|
|
|
1566
1566
|
\u{1F4A1} Your API key may be invalid or expired`)),console.log(m.cyan(` Update it: rapidkit config set-api-key
|
|
1567
1567
|
`))):r.message.includes("embeddings file not found")&&(console.log(m.yellow(`
|
|
1568
1568
|
\u{1F4A1} Module embeddings not generated yet`)),console.log(m.cyan(" Generate them (one-time):")),console.log(m.white(" cd rapidkit-npm")),console.log(m.white(' export OPENAI_API_KEY="sk-proj-..."')),console.log(m.white(` npx tsx src/ai/generate-embeddings.ts
|
|
1569
|
-
`))),process.exit(1);}}),o.command("info").description("Show AI features information").action(()=>{let t=
|
|
1569
|
+
`))),process.exit(1);}}),o.command("info").description("Show AI features information").action(()=>{let t=Ae(),n=kt();console.log(m.bold(`
|
|
1570
1570
|
\u{1F916} RapidKit AI Features
|
|
1571
1571
|
`)),console.log(m.cyan("Status:"),n?m.green("Enabled"):m.red("Disabled")),console.log(m.cyan("API Key:"),t?m.green("Configured \u2713"):m.red("Not configured \u2717")),console.log(m.bold(`
|
|
1572
1572
|
\u{1F4E6} Available Features:
|
|
@@ -1574,32 +1574,32 @@ No modules selected
|
|
|
1574
1574
|
\u{1F4B0} Pricing:
|
|
1575
1575
|
`)),console.log(m.white("\u2022 Per query: ~$0.0002")+m.gray(" (practically free)")),console.log(m.white("\u2022 100 queries: ~$0.02")+m.gray(" (2 cents)")),console.log(m.white("\u2022 1000 queries: ~$0.20")+m.gray(" (20 cents)")),console.log(m.bold(`
|
|
1576
1576
|
\u{1F680} Getting Started:
|
|
1577
|
-
`)),t?(console.log(m.green("\u2713 You're all set!")),console.log(m.white(' Try: rapidkit ai recommend "user authentication"'))):(console.log(m.white("1. Get OpenAI API key: https://platform.openai.com/api-keys")),console.log(m.white("2. Configure: rapidkit config set-api-key")),console.log(m.white('3. Try: rapidkit ai recommend "user authentication"'))),console.log();}),o.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=
|
|
1577
|
+
`)),t?(console.log(m.green("\u2713 You're all set!")),console.log(m.white(' Try: rapidkit ai recommend "user authentication"'))):(console.log(m.white("1. Get OpenAI API key: https://platform.openai.com/api-keys")),console.log(m.white("2. Configure: rapidkit config set-api-key")),console.log(m.white('3. Try: rapidkit ai recommend "user authentication"'))),console.log();}),o.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=Ae();t||(console.log(m.red(`
|
|
1578
1578
|
\u274C OpenAI API key not configured
|
|
1579
1579
|
`)),console.log(m.cyan(`To generate embeddings, you need an OpenAI API key:
|
|
1580
1580
|
`)),console.log(m.white("1. Get your key from: https://platform.openai.com/api-keys")),console.log(m.white("2. Configure it: rapidkit config set-api-key")),console.log(m.gray(`
|
|
1581
1581
|
OR set environment variable:`)),console.log(m.white(` export OPENAI_API_KEY="sk-proj-..."
|
|
1582
|
-
`)),process.exit(1)),
|
|
1583
|
-
`))),process.exit(n?0:1);}catch(t){y.error("Failed to generate embeddings:",t.message),process.exit(1);}}),o.command("update-embeddings").description("Update existing embeddings with latest modules").action(async()=>{try{let t=
|
|
1582
|
+
`)),process.exit(1)),Ye(t);let n=await Qe(!0);n&&(console.log(m.green("\u2705 Ready to use AI recommendations!")),console.log(m.cyan(`Try: rapidkit ai recommend "authentication"
|
|
1583
|
+
`))),process.exit(n?0:1);}catch(t){y.error("Failed to generate embeddings:",t.message),process.exit(1);}}),o.command("update-embeddings").description("Update existing embeddings with latest modules").action(async()=>{try{let t=Ae();t||(console.log(m.red(`
|
|
1584
1584
|
\u274C OpenAI API key not configured
|
|
1585
1585
|
`)),console.log(m.white(`Set your API key: rapidkit config set-api-key
|
|
1586
|
-
`)),process.exit(1)),
|
|
1586
|
+
`)),process.exit(1)),Ye(t);let n=await Oo();process.exit(n?0:1);}catch(t){y.error("Failed to update embeddings:",t.message),process.exit(1);}});}function xt(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 gi(e){let o=e.trim().toLowerCase();return o?o.startsWith("fastapi")?"fastapi":o.startsWith("nestjs")?"nestjs":null:null}function fi(e,o){let t=e.indexOf(o);if(t>=0&&t+1<e.length)return e[t+1];let n=e.find(r=>r.startsWith(`${o}=`));if(n)return n.slice(o.length+1)}async function Pt(e,o){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\`.
|
|
1587
1587
|
Reason: ${o}.
|
|
1588
1588
|
Install Python 3.10+ to use the interactive wizard and full kit catalog.
|
|
1589
1589
|
`),1;let r=e[2],i=e[3];if(!r||!i)return process.stderr.write(`Usage: rapidkit create project <kit> <name> [--output <dir>]
|
|
1590
1590
|
Tip: offline fallback supports only fastapi* and nestjs* kits.
|
|
1591
|
-
`),1;let s=
|
|
1591
|
+
`),1;let s=gi(r);if(!s)return process.stderr.write(`RapidKit (npm) could not run the Python core engine to create this kit.
|
|
1592
1592
|
Reason: ${o}.
|
|
1593
1593
|
Requested kit: ${r}
|
|
1594
1594
|
Offline fallback only supports: fastapi.standard, nestjs.standard (and their shorthands).
|
|
1595
1595
|
Install Python 3.10+ to access all kits.
|
|
1596
|
-
`),1;let a=
|
|
1597
|
-
`),1;let p="pip",u=
|
|
1598
|
-
`),1}}async function
|
|
1596
|
+
`),1;let a=fi(e,"--output")||process.cwd(),c=v.resolve(a,i),l=e.includes("--skip-git")||e.includes("--no-git"),d=e.includes("--skip-install");try{if(await b.ensureDir(v.dirname(c)),await b.pathExists(c))return process.stderr.write(`\u274C Directory "${c}" already exists
|
|
1597
|
+
`),1;let p="pip",u=Ze(process.cwd());if(u)try{let{readWorkspaceMarker:g}=await Promise.resolve().then(()=>(ut(),qt)),w=await g(u);w?.metadata?.npm?.installMethod&&(p=w.metadata.npm.installMethod,console.log(`[DEBUG] Detected workspace engine: ${p}`));}catch(g){console.log("[DEBUG] Failed to read workspace marker:",g);}else console.log("[DEBUG] No workspace found, using default engine: pip");if(await b.ensureDir(c),await co(c,{project_name:i,template:s,kit_name:r,skipGit:l,skipInstall:d,engine:p}),u){let{syncWorkspaceProjects:g}=await Promise.resolve().then(()=>(ne(),oe));await g(u,!0);}return 0}catch(p){return process.stderr.write(`RapidKit (npm) offline fallback failed: ${p?.message??p}
|
|
1598
|
+
`),1}}async function hi(e){let o=new Set(["--yes","-y","--skip-git","--skip-install","--debug","--dry-run","--no-update-check","--create-workspace","--no-workspace"]);try{if(e[0]==="create"&&e[1]==="project"){let t=e.includes("--create-workspace"),n=e.includes("--no-workspace"),r=e.includes("--yes")||e.includes("-y"),i=e.includes("--skip-git")||e.includes("--no-git");if(!!!Xe(process.cwd())){if(t)await pe(process.cwd(),{skipGit:i,yes:r,userConfig:await je()});else if(!n)if(r)await pe(process.cwd(),{skipGit:i,yes:!0,userConfig:await je()});else {let{createWs:c}=await gt.prompt([{type:"confirm",name:"createWs",message:"This project will be created outside a RapidKit workspace. Create and register a workspace here?",default:!0}]);c&&await pe(process.cwd(),{skipGit:i,yes:!1,userConfig:await je()});}}let a=e.filter(c=>{let l=c.split("=")[0];return !o.has(c)&&!o.has(l)});try{await he();let c=await Q(a,{cwd:process.cwd()});if(c===0){let l=Ze(process.cwd());if(l){try{let p=e[3];if(p){let u=e.indexOf("--output"),g=u>=0?e[u+1]:".",w=v.resolve(process.cwd(),g,p),h=v.join(l,".python-version"),x=v.join(w,".python-version");if(W.existsSync(h)&&W.existsSync(w)){let T=W.readFileSync(h,"utf-8");W.writeFileSync(x,T.trim()+`
|
|
1599
1599
|
`),y.debug(`Synced Python version ${T.trim()} from workspace to ${p}`);}}}catch(p){y.debug("Could not sync Python version from workspace:",p);}let{syncWorkspaceProjects:d}=await Promise.resolve().then(()=>(ne(),oe));await d(l,!0);}}return c}catch(c){let l=xt(c);return l?await Pt(a,l):(process.stderr.write(`RapidKit (npm) failed to run the Python core engine: ${c?.message??c}
|
|
1600
|
-
`),1)}}if(e[0]==="create"&&e[1]!=="project")try{await he();let t=await Q(e,{cwd:process.cwd()});if(t===0){let n=
|
|
1600
|
+
`),1)}}if(e[0]==="create"&&e[1]!=="project")try{await he();let t=await Q(e,{cwd:process.cwd()});if(t===0){let n=Ze(process.cwd());if(n){let{syncWorkspaceProjects:r}=await Promise.resolve().then(()=>(ne(),oe));await r(n,!0);}}return t}catch(t){let n=xt(t);return n?await Pt(e,n):(process.stderr.write(`RapidKit (npm) failed to run the Python core engine: ${t?.message??t}
|
|
1601
1601
|
`),1)}return await he(),await Q(e,{cwd:process.cwd()})}catch(t){let n=xt(t);return n?await Pt(e,n):(process.stderr.write(`RapidKit (npm) failed to run the Python core engine: ${t?.message??t}
|
|
1602
|
-
`),1)}}var Ko=["init","dev","start","build","test","lint","format","create","help","--help","-h"];function
|
|
1602
|
+
`),1)}}var Ko=["init","dev","start","build","test","lint","format","create","help","--help","-h"];function yi(e){let o=e;for(;;){let t=v.join(o,".rapidkit","context.json");if(W.existsSync(t))return t;let n=v.dirname(o);if(n===o)break;o=n;}return null}function Xe(e){let o=e;for(;;){let t=v.join(o,".rapidkit-workspace");if(W.existsSync(t))return t;let n=v.dirname(o);if(n===o)break;o=n;}return null}function Ze(e){let o=e;for(;;){let t=v.join(o,".rapidkit-workspace");if(W.existsSync(t))return o;let n=v.dirname(o);if(n===o)break;o=n;}return null}async function wi(){let e=process.cwd(),o=process.argv.slice(2);if(o[0]==="create")return false;try{let c=o[0],l=!c||c==="--help"||c==="-h"||c==="help";if(Xe(e)&&l){let p=await Q(c?["--help"]:[],{cwd:e});process.exit(p);}}catch{}try{let c=o[0],l=c==="shell"&&o[1]==="activate",d=c==="create",p=await St(e,{cwd:e,timeoutMs:1200});if(p.ok&&p.data?.isRapidkitProject&&p.data.engine==="python"&&!l&&!d){let u=await Q(process.argv.slice(2),{cwd:e});process.exit(u);}}catch{}let t=yi(e),n=process.platform==="win32",r=n?[v.join(e,"rapidkit.cmd"),v.join(e,"rapidkit"),v.join(e,".rapidkit","rapidkit.cmd"),v.join(e,".rapidkit","rapidkit")]:[v.join(e,"rapidkit"),v.join(e,".rapidkit","rapidkit")],i=null;for(let c of r)if(await b.pathExists(c)){i=c;break}let s=o[0],a=s==="create";if(i&&s&&Ko.includes(s)&&!a){y.debug(`Delegating to local CLI: ${i} ${o.join(" ")}`);let c=spawn(i,o,{stdio:"inherit",cwd:e,shell:n});return c.on("close",l=>{process.exit(l??0);}),c.on("error",l=>{y.error(`Failed to run local rapidkit: ${l.message}`),process.exit(1);}),true}if(t&&await b.pathExists(t))try{if((await b.readJson(t)).engine==="pip"){let l=o[0],p=process.platform==="win32"?[v.join(e,"rapidkit.cmd"),v.join(e,"rapidkit"),v.join(e,".rapidkit","rapidkit.cmd"),v.join(e,".rapidkit","rapidkit")]:[v.join(e,"rapidkit"),v.join(e,".rapidkit","rapidkit")],u=null;for(let w of p)if(await b.pathExists(w)){u=w;break}if(u&&l&&Ko.includes(l)){y.debug(`Delegating to local CLI (early detection): ${u} ${o.join(" ")}`);let w=spawn(u,o,{stdio:"inherit",cwd:e});return w.on("close",h=>process.exit(h??0)),w.on("error",h=>{y.error(`Failed to run local rapidkit: ${h.message}`),process.exit(1);}),!0}if(l==="shell"&&o[1]==="activate"){let w=`# RapidKit: activation snippet - eval "$(rapidkit shell activate)"
|
|
1603
1603
|
VENV='.venv'
|
|
1604
1604
|
if [ -f "$VENV/bin/activate" ]; then
|
|
1605
1605
|
. "$VENV/bin/activate"
|
|
@@ -1610,9 +1610,9 @@ export RAPIDKIT_PROJECT_ROOT="$(pwd)"
|
|
|
1610
1610
|
export PATH="$(pwd)/.rapidkit:$(pwd):$PATH"
|
|
1611
1611
|
`;console.log(m.green.bold(`
|
|
1612
1612
|
\u2705 Activation snippet \u2014 run the following to activate this project in your current shell:
|
|
1613
|
-
`)),console.log(
|
|
1613
|
+
`)),console.log(w),console.log(m.gray(`
|
|
1614
1614
|
\u{1F4A1} After activation you can run: rapidkit dev
|
|
1615
|
-
`)),process.exit(0);}let g=await Q(o,{cwd:e});process.exit(g);}}catch{}return false}var re=null,
|
|
1615
|
+
`)),process.exit(0);}let g=await Q(o,{cwd:e});process.exit(g);}}catch{}return false}var re=null,et=false,Z=new Command;async function vi(e){if(e.length===0)return false;let o=e[0],t=e[1];if(o==="shell"&&t==="activate"||o==="workspace"||o==="doctor"||o==="ai"||o==="config")return false;if(e.includes("--tui"))return true;if(o==="--help"||o==="-h"||o==="help"||o==="--version"||o==="-V"||e.includes("--template")||e.includes("-t"))return false;let n=new Set(["--yes","-y","--skip-git","--skip-install","--debug","--dry-run","--no-update-check","--create-workspace","--no-workspace"]);if(e.some(i=>n.has(i)))return false;let r=await ct();return r?r.has(o):!!(_e.has(o)||e.length>1)}Z.name("rapidkit").description("Create RapidKit workspaces and projects").version(q());Z.addHelpText("beforeAll",`RapidKit
|
|
1616
1616
|
|
|
1617
1617
|
Global CLI
|
|
1618
1618
|
Create RapidKit workspaces and projects
|
|
@@ -1626,9 +1626,9 @@ Project Commands
|
|
|
1626
1626
|
rapidkit dev
|
|
1627
1627
|
|
|
1628
1628
|
Use "rapidkit help <command>" for more information.
|
|
1629
|
-
`);Z.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("--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,o)=>{try{o.debug&&(y.setDebug(!0),y.debug("Debug mode enabled"));let t=await
|
|
1629
|
+
`);Z.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("--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,o)=>{try{o.debug&&(y.setDebug(!0),y.debug("Debug mode enabled"));let t=await je();y.debug("User config loaded",t);let n=await Et();y.debug("RapidKit config loaded",n);let r=It(t,n,{author:o.author,pythonVersion:void 0,skipGit:o.skipGit});y.debug("Merged config",r),o.updateCheck!==!1&&await _t(),console.log(m.blue.bold(`
|
|
1630
1630
|
\u{1F680} Welcome to RapidKit!
|
|
1631
|
-
`)),e||(
|
|
1631
|
+
`)),e||(bi(),process.exit(0));try{At(e);}catch(a){throw a instanceof J&&(y.error(`
|
|
1632
1632
|
\u274C ${a.message}`),a.details&&y.warn(`\u{1F4A1} ${a.details}
|
|
1633
1633
|
`),process.exit(1)),a}let i=v.resolve(process.cwd(),e);re=i,await b.pathExists(i)&&(y.error(`
|
|
1634
1634
|
\u274C Directory "${e}" already exists`),console.log(m.cyan(`
|
|
@@ -1636,17 +1636,17 @@ Use "rapidkit help <command>" for more information.
|
|
|
1636
1636
|
`)),process.exit(1));let s=!!o.template;if(o.dryRun){console.log(m.cyan(`
|
|
1637
1637
|
\u{1F50D} Dry-run mode - showing what would be created:
|
|
1638
1638
|
`)),console.log(m.white("\u{1F4C2} Path:"),i),console.log(m.white("\u{1F4E6} Type:"),s?`Project (${o.template})`:"Workspace"),console.log();return}if(!o.yes&&!s?await gt.prompt([{type:"input",name:"author",message:"Author name:",default:process.env.USER||"RapidKit User"}]):o.yes&&console.log(m.gray(`Using default values (--yes flag)
|
|
1639
|
-
`)),s){let a=String(o.template||"").trim(),c=a.toLowerCase(),l=c==="fastapi"?"fastapi.standard":c==="nestjs"?"nestjs.standard":a;if(!!!
|
|
1640
|
-
`),y.debug(`Synced Python version ${T.trim()} from workspace to project`);}}catch(T){y.debug("Could not sync Python version from workspace:",T);}}if(!o.skipInstall){let
|
|
1639
|
+
`)),s){let a=String(o.template||"").trim(),c=a.toLowerCase(),l=c==="fastapi"?"fastapi.standard":c==="nestjs"?"nestjs.standard":a;if(!!!Xe(process.cwd())){if(o.createWorkspace)await pe(process.cwd(),{skipGit:o.skipGit,yes:o.yes,userConfig:t});else if(!o.noWorkspace)if(o.yes)await pe(process.cwd(),{skipGit:o.skipGit,yes:!0,userConfig:t});else {let{createWs:w}=await gt.prompt([{type:"confirm",name:"createWs",message:"This project will be created outside a RapidKit workspace. Create and register a workspace here?",default:!0}]);w&&await pe(process.cwd(),{skipGit:o.skipGit,yes:!1,userConfig:t});}}let p=["create","project",l,e,"--output",process.cwd(),"--install-essentials"],u=await Q(p,{cwd:process.cwd()});u!==0&&process.exit(u);let g=Xe(process.cwd());if(g){let w=v.dirname(g),h=v.join(w,".python-version"),x=v.join(i,".python-version");try{if(await b.pathExists(h)){let T=W.readFileSync(h,"utf-8");W.writeFileSync(x,T.trim()+`
|
|
1640
|
+
`),y.debug(`Synced Python version ${T.trim()} from workspace to project`);}}catch(T){y.debug("Could not sync Python version from workspace:",T);}}if(!o.skipInstall){let w=await Q(["init",i],{cwd:process.cwd()});if(w!==0&&process.exit(w),g){let h=v.dirname(g),x=v.join(h,".python-version"),T=v.join(i,".python-version");try{if(await b.pathExists(x)){let F=W.readFileSync(x,"utf-8");W.writeFileSync(T,F.trim()+`
|
|
1641
1641
|
`),y.debug(`Re-synced Python version ${F.trim()} after init`);}}catch(F){y.debug("Could not re-sync Python version after init:",F);}}}}else await no(e,{skipGit:o.skipGit,dryRun:o.dryRun,yes:o.yes,userConfig:r,installMethod:o.installMethod});}catch(t){t instanceof J?(y.error(`
|
|
1642
1642
|
\u274C ${t.message}`),t.details&&y.warn(`\u{1F4A1} ${t.details}`),y.debug("Error code:",t.code)):(y.error(`
|
|
1643
|
-
\u274C An unexpected error occurred:`),console.error(t)),process.exit(1);}finally{re=null;}});To(Z);ko(Z);Z.command("shell <action>").description("Shell helpers (activate virtualenv in current shell)").action(async e=>{e!=="activate"&&(console.log(m.red(`Unknown shell command: ${e}`)),process.exit(1));let o=process.cwd();function t(c){let l=c;for(;;){let d=v.join(l,".rapidkit","context.json");if(W.existsSync(d))return d;let p=v.dirname(l);if(p===l)break;l=p;}return null}let n=t(o);function r(c){let l=c;for(;;){let d=v.join(l,".venv"),p=v.join(l,".rapidkit","activate");if(W.existsSync(p)||W.existsSync(d))return {venv:d,activateFile:p};let u=v.dirname(l);if(u===l)break;l=u;}return null}let i=r(o);!n&&!i&&(console.log(m.yellow("No RapidKit project found in this directory")),process.exit(1));let s;i&&W.existsSync(i.activateFile)?s=i.activateFile:i&&W.existsSync(i.venv)?s=process.platform==="win32"?v.join(i.venv,"Scripts","activate"):v.join(i.venv,"bin","activate"):(console.log(m.yellow("No virtual environment found")),process.exit(1));let a=process.platform==="win32";console.log(a?`call "${s}"`:`. "${s}"`);});Z.command("doctor").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=>{await ho(e);});Z.command("workspace <action>").description("Manage RapidKit workspaces (list, sync)").action(async e=>{if(e==="list"){let{listWorkspaces:o}=await Promise.resolve().then(()=>(ne(),oe));await o();}else if(e==="sync"){let o=
|
|
1643
|
+
\u274C An unexpected error occurred:`),console.error(t)),process.exit(1);}finally{re=null;}});To(Z);ko(Z);Z.command("shell <action>").description("Shell helpers (activate virtualenv in current shell)").action(async e=>{e!=="activate"&&(console.log(m.red(`Unknown shell command: ${e}`)),process.exit(1));let o=process.cwd();function t(c){let l=c;for(;;){let d=v.join(l,".rapidkit","context.json");if(W.existsSync(d))return d;let p=v.dirname(l);if(p===l)break;l=p;}return null}let n=t(o);function r(c){let l=c;for(;;){let d=v.join(l,".venv"),p=v.join(l,".rapidkit","activate");if(W.existsSync(p)||W.existsSync(d))return {venv:d,activateFile:p};let u=v.dirname(l);if(u===l)break;l=u;}return null}let i=r(o);!n&&!i&&(console.log(m.yellow("No RapidKit project found in this directory")),process.exit(1));let s;i&&W.existsSync(i.activateFile)?s=i.activateFile:i&&W.existsSync(i.venv)?s=process.platform==="win32"?v.join(i.venv,"Scripts","activate"):v.join(i.venv,"bin","activate"):(console.log(m.yellow("No virtual environment found")),process.exit(1));let a=process.platform==="win32";console.log(a?`call "${s}"`:`. "${s}"`);});Z.command("doctor").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=>{await ho(e);});Z.command("workspace <action>").description("Manage RapidKit workspaces (list, sync)").action(async e=>{if(e==="list"){let{listWorkspaces:o}=await Promise.resolve().then(()=>(ne(),oe));await o();}else if(e==="sync"){let o=Ze(process.cwd());o||(console.log(m.red("\u274C Not inside a RapidKit workspace")),console.log(m.gray("\u{1F4A1} Run this command from within a workspace directory")),process.exit(1));let{syncWorkspaceProjects:t}=await Promise.resolve().then(()=>(ne(),oe));console.log(m.cyan(`\u{1F4C2} Scanning workspace: ${v.basename(o)}`)),await t(o);}else console.log(m.red(`Unknown workspace action: ${e}`)),console.log(m.gray("Available: list, sync")),process.exit(1);});function bi(){console.log(m.white(`Usage:
|
|
1644
1644
|
`)),console.log(m.cyan(" npx rapidkit <workspace-name> [options]")),console.log(m.cyan(` npx rapidkit create <...>
|
|
1645
1645
|
`)),console.log(m.bold("Recommended workflow:")),console.log(m.cyan(" npx rapidkit my-workspace")),console.log(m.cyan(" cd my-workspace")),console.log(m.cyan(" npx rapidkit create project fastapi.standard my-api --output .")),console.log(m.cyan(" cd my-api")),console.log(m.cyan(` npx rapidkit init && npx rapidkit dev
|
|
1646
1646
|
`)),console.log(m.bold("Options (workspace creation):")),console.log(m.gray(" -y, --yes Skip prompts and use defaults")),console.log(m.gray(" --skip-git Skip git initialization")),console.log(m.gray(" --debug Enable debug logging")),console.log(m.gray(" --dry-run Show what would be created")),console.log(m.gray(" --create-workspace When creating a project outside a workspace: create and register a workspace in the current directory")),console.log(m.gray(" --no-workspace When creating a project outside a workspace: do not create a workspace")),console.log(m.gray(` --no-update-check Skip checking for updates
|
|
1647
1647
|
`)),console.log(m.gray(`Tip: set RAPIDKIT_SHOW_LEGACY=1 to show legacy template flags in help.
|
|
1648
|
-
`));}process.on("SIGINT",async()=>{if(!
|
|
1648
|
+
`));}process.on("SIGINT",async()=>{if(!et){if(et=true,console.log(m.yellow(`
|
|
1649
1649
|
|
|
1650
|
-
\u26A0\uFE0F Interrupted by user`)),re&&await b.pathExists(re)){console.log(m.gray("Cleaning up partial installation..."));try{await b.remove(re),console.log(m.green("\u2713 Cleanup complete"));}catch(e){y.debug("Cleanup failed:",e);}}process.exit(130);}});process.on("SIGTERM",async()=>{if(!
|
|
1651
|
-
`),o[0]==="create"){let n=await
|
|
1652
|
-
`),t){let n=await Q(o,{cwd:process.cwd()});process.exit(n);}Z.parse();}});export{
|
|
1650
|
+
\u26A0\uFE0F Interrupted by user`)),re&&await b.pathExists(re)){console.log(m.gray("Cleaning up partial installation..."));try{await b.remove(re),console.log(m.green("\u2713 Cleanup complete"));}catch(e){y.debug("Cleanup failed:",e);}}process.exit(130);}});process.on("SIGTERM",async()=>{if(!et){if(et=true,y.debug("Received SIGTERM"),re&&await b.pathExists(re))try{await b.remove(re);}catch(e){y.debug("Cleanup failed:",e);}process.exit(143);}});wi().then(async e=>{if(!e){let o=process.argv.slice(2);if(process.env.RAPIDKIT_NPM_DEBUG_ARGS==="1"&&process.stderr.write(`[rapidkit-npm] argv=${JSON.stringify(o)}
|
|
1651
|
+
`),o[0]==="create"){let n=await hi(o);process.exit(n);}let t=await vi(o);if(process.env.RAPIDKIT_NPM_DEBUG_ARGS==="1"&&process.stderr.write(`[rapidkit-npm] shouldForwardToCore=${t}
|
|
1652
|
+
`),t){let n=await Q(o,{cwd:process.cwd()});process.exit(n);}Z.parse();}});export{hi as handleCreateOrFallback};
|
package/dist/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "rapidkit",
|
|
3
|
-
"version": "0.19.
|
|
3
|
+
"version": "0.19.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Create RapidKit projects with a single command - The official CLI for RapidKit framework",
|
|
6
6
|
"keywords": [
|
|
@@ -41,6 +41,7 @@
|
|
|
41
41
|
"test:drift": "RAPIDKIT_DRIFT_GUARD=1 vitest run src/__tests__/drift-guard.test.ts",
|
|
42
42
|
"test:watch": "vitest",
|
|
43
43
|
"test:coverage": "vitest run --coverage",
|
|
44
|
+
"test:prepare-embeddings": "npx tsx scripts/generate-mock-embeddings.ts",
|
|
44
45
|
"test:e2e": "vitest run src/__tests__/e2e.test.ts",
|
|
45
46
|
"test:scenarios": "bash scripts/scenario-matrix-local.sh",
|
|
46
47
|
"test:scenarios:full": "RAPIDKIT_SCENARIO_FULL_BOOTSTRAP=1 bash scripts/scenario-matrix-local.sh",
|
|
@@ -66,7 +67,7 @@
|
|
|
66
67
|
"commander": "^12.1.0",
|
|
67
68
|
"execa": "^9.3.1",
|
|
68
69
|
"fs-extra": "^11.2.0",
|
|
69
|
-
"inquirer": "^
|
|
70
|
+
"inquirer": "^13.2.2",
|
|
70
71
|
"nunjucks": "^3.2.4",
|
|
71
72
|
"openai": "^4.80.0",
|
|
72
73
|
"ora": "^8.0.1",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "rapidkit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.20.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Create RapidKit projects with a single command - The official CLI for RapidKit framework",
|
|
6
6
|
"keywords": [
|
|
@@ -41,6 +41,7 @@
|
|
|
41
41
|
"test:drift": "RAPIDKIT_DRIFT_GUARD=1 vitest run src/__tests__/drift-guard.test.ts",
|
|
42
42
|
"test:watch": "vitest",
|
|
43
43
|
"test:coverage": "vitest run --coverage",
|
|
44
|
+
"test:prepare-embeddings": "npx tsx scripts/generate-mock-embeddings.ts",
|
|
44
45
|
"test:e2e": "vitest run src/__tests__/e2e.test.ts",
|
|
45
46
|
"test:scenarios": "bash scripts/scenario-matrix-local.sh",
|
|
46
47
|
"test:scenarios:full": "RAPIDKIT_SCENARIO_FULL_BOOTSTRAP=1 bash scripts/scenario-matrix-local.sh",
|
|
@@ -66,7 +67,7 @@
|
|
|
66
67
|
"commander": "^12.1.0",
|
|
67
68
|
"execa": "^9.3.1",
|
|
68
69
|
"fs-extra": "^11.2.0",
|
|
69
|
-
"inquirer": "^
|
|
70
|
+
"inquirer": "^13.2.2",
|
|
70
71
|
"nunjucks": "^3.2.4",
|
|
71
72
|
"openai": "^4.80.0",
|
|
72
73
|
"ora": "^8.0.1",
|