rapidkit 0.18.1 → 0.19.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/README.md +133 -0
- package/dist/index.js +228 -130
- package/dist/package.json +2 -1
- package/package.json +2 -1
package/dist/index.js
CHANGED
|
@@ -1,27 +1,27 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
[${
|
|
4
|
-
\u26A0\uFE0F Update available: ${
|
|
5
|
-
`))):y.debug("You are using the latest version");}catch{y.debug("Could not check for updates");}}function
|
|
2
|
+
import v from'path';import {fileURLToPath,pathToFileURL}from'url';import m from'chalk';import {execa}from'execa';import {createRequire}from'module';import nn 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 Qo from'validate-npm-package-name';import Nn from'nunjucks';import Yn from'openai';import {promisify}from'util';var Lo=Object.defineProperty;var se=(e,o)=>()=>(e&&(o=e(e=0)),o);var tt=(e,o)=>{for(var t in o)Lo(e,t,{get:o[t],enumerable:true});};var P=se(()=>{});var ot,y,ce=se(()=>{P();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 Ho(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 Rt(){try{y.debug("Checking for updates...");let{stdout:e}=await execa("npm",["view",Vo,"version"],{timeout:3e3}),o=e.trim();o&&Ho(o,nt)>0?(console.log(m.yellow(`
|
|
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 Vo,Uo,Bo,nt,xe=se(()=>{P();ce();Vo="rapidkit",Uo=createRequire(import.meta.url),Bo=Uo("../package.json"),nt=Bo?.version??"0.0.0";});var on,$e,it=se(()=>{P();on=["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(on);});var lt={};tt(lt,{__test__:()=>hn,checkRapidkitCoreAvailable:()=>Ut,getCachedCoreTopLevelCommands:()=>ct,getCoreTopLevelCommands:()=>mn,getModulesCatalog:()=>fn,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
|
-
Details: ${
|
|
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.
|
|
9
|
-
Details: ${
|
|
9
|
+
Details: ${e.message}`;case "BRIDGE_PIP_UPGRADE_FAILED":return `RapidKit (npm) could not upgrade pip in the bridge virtual environment.
|
|
10
10
|
Check your network/proxy or disable RAPIDKIT_BRIDGE_UPGRADE_PIP.
|
|
11
|
-
Details: ${
|
|
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: ${
|
|
14
|
-
`);};try{
|
|
15
|
-
`);};for(let
|
|
16
|
-
`).filter(r=>r.trim());
|
|
17
|
-
`),
|
|
18
|
-
${
|
|
19
|
-
`),1}}async function
|
|
20
|
-
`}}}function
|
|
21
|
-
`),
|
|
22
|
-
`,"utf-8");}async function
|
|
23
|
-
\u2705 Synced ${c} project(s) to registry`)):
|
|
24
|
-
\u2705 All projects already registered (${l} found)`);}catch(
|
|
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 rn(){let e=rt(),o=process.env.RAPIDKIT_CORE_PYTHON_PACKAGE_ID,t=o&&o.trim()?`${e}|${o.trim()}`:e;return nn.createHash("sha256").update(t).digest("hex").slice(0,12)}function Te(){let e=process.env.XDG_CACHE_HOME;return e&&e.trim()?e:v.join(te__default.homedir(),".cache")}function sn(){return v.join(Te(),"rapidkit","npm-bridge","venv")}function Lt(){let e=rn();return v.join(Te(),"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 an(e){return /[<>=!~]=|@|\.whl$|\.tar\.gz$|\.zip$|git\+|https?:\/\//.test(e)}function cn(e){return v.dirname(v.dirname(e))}function Gt(){return v.join(Te(),"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 ln(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 dn(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 ln(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 dn(s);return a&&(process.env.PYENV_VERSION=a),i}}catch{}let o=await he();if(o.kind==="venv"){let i=cn(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 Oe(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
|
+
`);};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 Oe(e){let o=Lt(),t=sn(),n=rt(),r=[o];!an(n)&&!await b.pathExists(o)&&await b.pathExists(t)&&r.push(t);for(let g of r){let h=Dt(g);if(await b.pathExists(h))try{let w=await execa(h,["-c","import importlib.util; print(1 if importlib.util.find_spec('rapidkit') else 0)"],{reject:!1,stdio:"pipe",timeout:2e3});if(w.exitCode===0&&(w.stdout??"").toString().trim()==="1")return h;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(h=>setTimeout(h,g)),p=async(g,h,w)=>{let C=await execa(g,h,{reject:false,stdio:["ignore","pipe","inherit"],env:s,timeout:w});if(C.exitCode===0)return;let T=(C.stdout??"").toString(),F=(C.stderr??"").toString(),H=[T,F].filter(Boolean).join(`
|
|
17
|
+
`),et=H?`${g} ${h.join(" ")}
|
|
18
|
+
${H}`:`${g} ${h.join(" ")}`;throw new Error(et)},u=async(g,h,w)=>{let C=0;for(;;)try{await p(g,h,w);return}catch(T){if(C>=a)throw T;let F=Math.floor(Math.random()*200),H=c*Math.pow(2,C)+F;C+=1,await d(H);}};try{await b.ensureDir(v.dirname(i));try{await p(e,["-m","venv",i],6e4);}catch(w){let C=w instanceof Error?w.message:String(w);throw new z("BRIDGE_VENV_CREATE_FAILED",C)}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(w){let C=w instanceof Error?w.message:String(w);throw new z("BRIDGE_PIP_UPGRADE_FAILED",C)}try{await u(g,["-m","pip","install","-U",rt()],l);}catch(w){let C=w instanceof Error?w.message:String(w);throw new z("BRIDGE_PIP_INSTALL_FAILED",C)}return g}catch(g){if(g instanceof z)throw g;let h=g instanceof Error?g.message:String(g);throw new z("BRIDGE_VENV_BOOTSTRAP_FAILED",h)}}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 Oe(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 Oe(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
|
+
`),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
|
+
`}}}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 pn(){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 un(){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 mn(){let o=Date.now(),t=await Ht(),n=await pn(),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 un();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(Te(),"rapidkit","npm-bridge","modules-catalog.json")}async function gn(){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 fn(e={}){let o=typeof e.ttlMs=="number"?e.ttlMs:18e5,t=Date.now(),n=await gn();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,hn,Fe=se(()=>{P();it();z=class extends Error{code;constructor(o,t){super(t),this.code=o;}};hn={pickSystemPython:at,ensureBridgeVenv:Oe,parseCoreCommandsFromHelp:Bt,tryRapidkit:Wt,checkRapidkitCoreAvailable:Ut};});var qt={};tt(qt,{createNpmWorkspaceMarker:()=>pt,isValidWorkspaceMarker:()=>wn,readWorkspaceMarker:()=>dt,updateWorkspaceMetadata:()=>yn,writeWorkspaceMarker:()=>Le});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 Le(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 yn(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 Le(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 wn(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(()=>{P();});var oe={};tt(oe,{createProject:()=>Cn,createWorkspace:()=>bn,listWorkspaces:()=>Rn,registerProjectInWorkspace:()=>vn,registerWorkspace:()=>zt,syncWorkspaceProjects:()=>kn});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 kn(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 h=!1;try{await promises.access(u),h=!0;}catch{await promises.access(g),h=!0;}h&&(s.projects.some(C=>C.path===p||C.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
|
+
\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 vn(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 bn(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=xn();await promises.writeFile(v.join(e,"rapidkit"),r),await promises.chmod(v.join(e,"rapidkit"),493);let i=Pn(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,11 +36,11 @@ Thumbs.db
|
|
|
36
36
|
|
|
37
37
|
# Logs
|
|
38
38
|
*.log
|
|
39
|
-
`),await promises.writeFile(
|
|
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 jn(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:")}
|
|
43
|
-
${
|
|
43
|
+
${e}/
|
|
44
44
|
\u251C\u2500\u2500 rapidkit # Local CLI wrapper
|
|
45
45
|
\u251C\u2500\u2500 .rapidkit/ # Workspace configuration
|
|
46
46
|
\u2502 \u251C\u2500\u2500 config.json # Workspace settings
|
|
@@ -48,7 +48,7 @@ ${t}/
|
|
|
48
48
|
\u2514\u2500\u2500 README.md
|
|
49
49
|
|
|
50
50
|
${m.bold("\u{1F680} Get started:")}
|
|
51
|
-
${m.cyan(`cd ${
|
|
51
|
+
${m.cyan(`cd ${o.name}`)}
|
|
52
52
|
${m.cyan("npx rapidkit my-api --template fastapi")}
|
|
53
53
|
${m.cyan("cd my-api")}
|
|
54
54
|
${m.cyan("npx rapidkit init")}
|
|
@@ -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(
|
|
69
|
+
`);}catch(n){throw t.fail("Failed to create workspace"),n}}function xn(){return `#!/usr/bin/env bash
|
|
70
70
|
#
|
|
71
71
|
# RapidKit CLI - Local workspace commands
|
|
72
72
|
# This script provides rapidkit commands within the workspace
|
|
@@ -402,7 +402,7 @@ main() {
|
|
|
402
402
|
print_help
|
|
403
403
|
;;
|
|
404
404
|
version|-v|--version)
|
|
405
|
-
echo "RapidKit CLI (npm workspace) v${
|
|
405
|
+
echo "RapidKit CLI (npm workspace) v${q()}"
|
|
406
406
|
;;
|
|
407
407
|
*)
|
|
408
408
|
echo -e "\${RED}\u274C Unknown command: $cmd\${NC}"
|
|
@@ -414,7 +414,7 @@ main() {
|
|
|
414
414
|
}
|
|
415
415
|
|
|
416
416
|
main "$@"
|
|
417
|
-
`}function
|
|
417
|
+
`}function Pn(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 jn(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 Cn(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,11 +530,11 @@ Thumbs.db
|
|
|
530
530
|
|
|
531
531
|
# Coverage
|
|
532
532
|
coverage/
|
|
533
|
-
`;if(await promises.writeFile(
|
|
533
|
+
`;if(await promises.writeFile(v.join(e,".gitignore"),u),r.succeed(`${n} project created!`),!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: ${n} project via RapidKit`],{cwd:e}),h.succeed("Git repository initialized");}catch{h.warn("Could not initialize git repository");}}if(!o.skipInstall&&!t){let h=o.package_manager||"npm",w=Re(`Installing dependencies with ${h}...`).start();try{await execa(h,["install"],{cwd:e}),w.succeed("Dependencies installed");}catch{w.warn(`Could not install dependencies. Run '${h} 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:")}
|
|
537
|
-
${
|
|
537
|
+
${e}/
|
|
538
538
|
\u251C\u2500\u2500 .rapidkit/ # RapidKit CLI module
|
|
539
539
|
\u251C\u2500\u2500 src/
|
|
540
540
|
\u2502 \u251C\u2500\u2500 main.py # FastAPI application
|
|
@@ -546,7 +546,7 @@ ${t}/
|
|
|
546
546
|
\u2514\u2500\u2500 README.md
|
|
547
547
|
|
|
548
548
|
${m.bold("\u{1F680} Get started:")}
|
|
549
|
-
${m.cyan(`cd ${
|
|
549
|
+
${m.cyan(`cd ${g}`)}
|
|
550
550
|
${m.cyan("npx rapidkit init")} ${m.gray("# Install dependencies")}
|
|
551
551
|
${m.cyan("npx rapidkit dev")} ${m.gray("# Start dev server")}
|
|
552
552
|
|
|
@@ -564,7 +564,7 @@ ${m.gray("\u{1F4A1} Tip: Install globally (npm i -g rapidkit) to use without npx
|
|
|
564
564
|
${m.green("\u2728 NestJS project created successfully!")}
|
|
565
565
|
|
|
566
566
|
${m.bold("\u{1F4C2} Project structure:")}
|
|
567
|
-
${
|
|
567
|
+
${e}/
|
|
568
568
|
\u251C\u2500\u2500 .rapidkit/ # RapidKit CLI module
|
|
569
569
|
\u251C\u2500\u2500 src/
|
|
570
570
|
\u2502 \u251C\u2500\u2500 main.ts # Application entry point
|
|
@@ -576,8 +576,8 @@ ${t}/
|
|
|
576
576
|
\u2514\u2500\u2500 README.md
|
|
577
577
|
|
|
578
578
|
${m.bold("\u{1F680} Get started:")}
|
|
579
|
-
${m.cyan(`cd ${
|
|
580
|
-
${
|
|
579
|
+
${m.cyan(`cd ${g}`)}
|
|
580
|
+
${o.skipInstall?m.cyan("npx rapidkit init")+m.gray(" # npm install")+`
|
|
581
581
|
`:""}${m.cyan("cp .env.example .env")}
|
|
582
582
|
${m.cyan("npx rapidkit dev")} ${m.gray("# Start dev server")}
|
|
583
583
|
|
|
@@ -596,37 +596,37 @@ ${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(
|
|
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
|
-
`));return}try{let
|
|
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(`
|
|
603
603
|
\u26A0\uFE0F No workspaces registered yet.
|
|
604
604
|
`));return}console.log(m.bold(`
|
|
605
605
|
\u{1F4E6} Registered RapidKit Workspaces:
|
|
606
|
-
`));for(let
|
|
607
|
-
`));}catch(
|
|
608
|
-
\u274C Failed to read workspace registry`)),console.error(m.gray(String(
|
|
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
|
+
`));}catch(n){console.error(m.red(`
|
|
608
|
+
\u274C Failed to read workspace registry`)),console.error(m.gray(String(n)));}}var ne=se(()=>{P();xe();});P();ce();xe();P();ce();var qo=".rapidkitrc.json",zo=["rapidkit.config.js","rapidkit.config.mjs","rapidkit.config.cjs"];async function Pe(){let e=v.join(te__default.homedir(),qo);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 zo){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 Ne(e){return process.env.RAPIDKIT_DEV_PATH||e.testRapidKitPath||void 0}P();P();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/");}},je=class extends J{constructor(){super("Poetry is not installed","POETRY_NOT_FOUND","Install Poetry from https://python-poetry.org/docs/#installation");}},Ce=class extends J{constructor(){super("pipx is not installed","PIPX_NOT_FOUND","Install pipx from https://pypa.github.io/pipx/installation/");}},Me=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);}},V=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
|
|
612
612
|
- Verify Python/Poetry installation
|
|
613
|
-
- Try running with --debug flag for more details`;super(
|
|
613
|
+
- Try running with --debug flag for more details`;super(n,"INSTALLATION_ERROR",r);}},ge=class extends J{constructor(){super("RapidKit Python package is not yet available on PyPI","RAPIDKIT_NOT_AVAILABLE",`Available options:
|
|
614
614
|
1. Install Python 3.10+ and retry the same command
|
|
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
|
|
618
|
+
Legacy: set RAPIDKIT_SHOW_LEGACY=1 to reveal template-mode flags in help.`);}};function At(e){let o=Qo(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}P();function Zo(e){return typeof e=="object"&&e!==null}async function en(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 tn(e,o){let t=["-m","rapidkit",...e],n=["python3","python"];for(let r of n){let i=await en(r,t,o?.cwd,o?.timeoutMs);if(!i.ok)continue;let s=(i.stdout??"").trim();try{let a=JSON.parse(s);return Zo(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 tn(["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}Fe();it();P();ce();xe();P();function Ke(){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 Le(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
|
|
625
|
-
`,"utf-8"),y.debug(`Created .python-version with ${
|
|
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 _n(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 _e(){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 Ge(e,o){_e(),e.start("Checking pipx installation");try{return await execa("pipx",["--version"]),e.succeed("pipx found"),{kind:"binary"}}catch{}let t=Ke();try{return await execa(t,["-m","pipx","--version"]),e.succeed("pipx found"),{kind:"python-module",pythonCmd:t}}catch{}if(o)throw new Ce;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 Ce;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 V("Install pipx with python -m pip",r instanceof Error?r:new Error(s))}e.succeed("pipx installed"),_e();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 V("Verify pipx after install",new Error(`${s}
|
|
626
626
|
|
|
627
|
-
Try reopening your terminal or run: python3 -m pipx ensurepath`))}}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 En(e,o){_e(),e.start("Checking Poetry installation");try{await execa("poetry",["--version"]),e.succeed("Poetry found");return}catch{}if(o)throw new je;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 je;let n=await Ge(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 V("Install Poetry with pipx",r instanceof Error?r:new Error(s))}e.succeed("Poetry installed"),_e();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 V("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 In(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)
|
|
@@ -636,16 +636,16 @@ if [ -x "$VENV_RAPIDKIT" ]; then
|
|
|
636
636
|
exec "$VENV_RAPIDKIT" "$@"
|
|
637
637
|
fi
|
|
638
638
|
|
|
639
|
-
${
|
|
639
|
+
${o?`if command -v poetry >/dev/null 2>&1 && [ -f "$SCRIPT_DIR/pyproject.toml" ]; then
|
|
640
640
|
exec poetry run rapidkit "$@"
|
|
641
641
|
fi
|
|
642
642
|
|
|
643
643
|
`:""}echo "RapidKit launcher could not find a local Python CLI." 1>&2
|
|
644
644
|
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 An(e){return `@echo off
|
|
649
649
|
setlocal
|
|
650
650
|
|
|
651
651
|
set "SCRIPT_DIR=%~dp0"
|
|
@@ -655,7 +655,7 @@ if exist "%SCRIPT_DIR%\\.venv\\Scripts\\rapidkit.exe" (
|
|
|
655
655
|
exit /b %ERRORLEVEL%
|
|
656
656
|
)
|
|
657
657
|
|
|
658
|
-
${
|
|
658
|
+
${e==="poetry"?`where poetry >nul 2>nul
|
|
659
659
|
if %ERRORLEVEL%==0 if exist "%SCRIPT_DIR%\\pyproject.toml" (
|
|
660
660
|
poetry run rapidkit %*
|
|
661
661
|
exit /b %ERRORLEVEL%
|
|
@@ -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
|
|
667
|
+
`}async function oo(e,o){await b.outputFile(v.join(e,"rapidkit"),In(o),{encoding:"utf-8",mode:493}),await b.outputFile(v.join(e,"rapidkit.cmd"),An(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 Me(l);if(i){await Dn(d,l,r,a);return}if(r){await Sn(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,h=await io(p.pythonVersion);if(h)g=await Xt(h),g?(y.info(`Detected Python ${g}`),u.succeed(`Python ${g} detected`)):u.warn("Could not detect exact Python version");else {let w=Ke();g=await Xt(w),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 _n(d,g),await to(d),p.installMethod==="poetry")try{await ro(d,p.pythonVersion,u,n,a,s);}catch(w){let C=w?.details||w?.message||String(w);if(C.includes("pyenv")||C.includes("exit status 127")||C.includes("returned non-zero exit status 127")){u.warn("Poetry encountered Python discovery issues, trying venv method"),y.debug(`Poetry error (attempting venv fallback): ${C}`);try{await mt(d,p.pythonVersion,u,n,a),p.installMethod="venv";}catch(F){throw F}}else throw w}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:w}=await Promise.resolve().then(()=>(ne(),oe));await w(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
|
-
`)),console.log(m.cyan("\u{1F4C2} Location:"),m.white(
|
|
670
|
-
`)),console.log(m.white(` cd ${l}`)),
|
|
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 w="source $(poetry env info --path)/bin/activate";try{_e();let{stdout:C}=await execa("poetry",["--version"]),T=C.match(/Poetry.*?(\d+)\.(\d+)/);T&&(parseInt(T[1])>=2?w="source $(poetry env info --path)/bin/activate":w="poetry shell");}catch{}console.log(m.white(` ${w} # 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
|
-
`));}catch(
|
|
674
|
-
\u274C Error:`),
|
|
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 En(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,32 +680,32 @@ package-mode = false
|
|
|
680
680
|
|
|
681
681
|
[tool.poetry]
|
|
682
682
|
package-mode = false
|
|
683
|
-
`),await promises.writeFile(
|
|
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=Ne(r||{});if(!d)throw new V("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(h=>setTimeout(h,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 V("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
|
-
2. Try installing manually: cd ${
|
|
689
|
-
3. Use venv method instead: npx rapidkit ${
|
|
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(()=>(Fe(),lt));if(!await d()&&!n){t.start("Installing RapidKit globally with pipx for CLI access");let u=await Ge(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=Ke();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 V("Python venv module not available",new Error(`Virtual environment creation failed.
|
|
690
690
|
|
|
691
691
|
On Debian/Ubuntu systems, install the venv package:
|
|
692
|
-
sudo apt install ${
|
|
692
|
+
sudo apt install ${p}
|
|
693
693
|
|
|
694
694
|
Or use Poetry instead (recommended):
|
|
695
|
-
npx rapidkit ${
|
|
696
|
-
Error: ${
|
|
695
|
+
npx rapidkit ${v.basename(e)} --yes`))}throw new V("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=Ne(r||{});if(!c)throw new V("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 V("Install rapidkit-core with pip",new Error(`Failed to install rapidkit-core after 3 attempts.
|
|
696
|
+
Error: ${d}
|
|
697
697
|
|
|
698
698
|
Possible solutions:
|
|
699
699
|
1. Check your internet connection
|
|
700
|
-
2. Try installing manually: cd ${
|
|
701
|
-
3. Use Poetry instead: npx rapidkit ${
|
|
702
|
-
`,"utf-8");}async function
|
|
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(()=>(Fe(),lt));if(!await c()&&!n){t.start("Installing RapidKit globally with pipx for CLI access");let d=await Ge(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 Ge(o,r);if(o.start("Installing RapidKit globally with pipx"),t){let s=Ne(n||{});if(!s)throw new V("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
|
+
`,"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.
|
|
705
705
|
|
|
706
706
|
## Installation Method
|
|
707
707
|
|
|
708
|
-
**${
|
|
708
|
+
**${o==="poetry"?"Poetry":o==="venv"?"Python venv + pip":"pipx (global)"}**
|
|
709
709
|
|
|
710
710
|
## Getting Started
|
|
711
711
|
|
|
@@ -714,10 +714,10 @@ This directory contains a RapidKit development environment.
|
|
|
714
714
|
This workspace includes a local launcher script so you can run the Python Core CLI without activating the environment:
|
|
715
715
|
|
|
716
716
|
\`\`\`bash
|
|
717
|
-
${
|
|
717
|
+
${o==="poetry"?`# No activation needed (recommended):
|
|
718
718
|
./rapidkit --help
|
|
719
719
|
# or:
|
|
720
|
-
poetry run rapidkit --help`:
|
|
720
|
+
poetry run rapidkit --help`:o==="venv"?`# No activation needed (recommended):
|
|
721
721
|
./rapidkit --help
|
|
722
722
|
# or direct:
|
|
723
723
|
./.venv/bin/rapidkit --help`:`# Optional: use the local launcher
|
|
@@ -728,8 +728,8 @@ poetry run rapidkit --help`:i==="venv"?`# No activation needed (recommended):
|
|
|
728
728
|
### 1. Activate Environment
|
|
729
729
|
|
|
730
730
|
\`\`\`bash
|
|
731
|
-
${
|
|
732
|
-
# Or simply use: poetry run rapidkit <command>`:
|
|
731
|
+
${o==="poetry"?`source $(poetry env info --path)/bin/activate
|
|
732
|
+
# Or simply use: poetry run rapidkit <command>`:o==="venv"?"source .venv/bin/activate # On Windows: .venv\\Scripts\\activate":"N/A (globally installed)"}
|
|
733
733
|
\`\`\`
|
|
734
734
|
|
|
735
735
|
### 2. Create Your First Project
|
|
@@ -796,8 +796,8 @@ For full documentation, visit: [RapidKit Docs](https://getrapidkit.com) *(or app
|
|
|
796
796
|
## Workspace Structure
|
|
797
797
|
|
|
798
798
|
\`\`\`
|
|
799
|
-
${
|
|
800
|
-
${
|
|
799
|
+
${o==="venv"?".venv/ # Python virtual environment":""}
|
|
800
|
+
${o==="poetry"?"pyproject.toml # Poetry configuration":""}
|
|
801
801
|
my-project/ # Your RapidKit projects go here
|
|
802
802
|
README.md # This file
|
|
803
803
|
\`\`\`
|
|
@@ -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(
|
|
813
|
+
`;await promises.writeFile(v.join(e,"README.md"),r,"utf-8");}async function Sn(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
|
*
|
|
@@ -1206,7 +1206,7 @@ venv/
|
|
|
1206
1206
|
}
|
|
1207
1207
|
|
|
1208
1208
|
main().catch(console.error);
|
|
1209
|
-
`,"utf-8");try{await execa("chmod",["+x",
|
|
1209
|
+
`,"utf-8");try{await execa("chmod",["+x",v.join(e,"generate-demo.js")]);}catch{}let s=`# RapidKit Demo Workspace
|
|
1210
1210
|
|
|
1211
1211
|
Welcome to your RapidKit demo workspace! This environment lets you generate FastAPI demo projects using bundled RapidKit templates, without needing to install Python RapidKit.
|
|
1212
1212
|
|
|
@@ -1277,7 +1277,7 @@ pipx install rapidkit
|
|
|
1277
1277
|
## \u{1F6E0}\uFE0F Workspace Structure
|
|
1278
1278
|
|
|
1279
1279
|
\`\`\`
|
|
1280
|
-
${
|
|
1280
|
+
${o}/
|
|
1281
1281
|
\u251C\u2500\u2500 generate-demo.js # Demo project generator
|
|
1282
1282
|
\u251C\u2500\u2500 README.md # This file
|
|
1283
1283
|
\u2514\u2500\u2500 my-api/ # Your generated projects go here
|
|
@@ -1293,7 +1293,7 @@ ${i}/
|
|
|
1293
1293
|
---
|
|
1294
1294
|
|
|
1295
1295
|
**Generated with RapidKit** | [GitHub](https://github.com/getrapidkit/rapidkit-npm)
|
|
1296
|
-
`;if(await promises.writeFile(
|
|
1296
|
+
`;if(await promises.writeFile(v.join(e,"README.md"),s,"utf-8"),n.succeed("Demo workspace setup complete"),!t){n.start("Initializing git repository");try{await execa("git",["init"],{cwd:e}),await b.outputFile(v.join(e,".gitignore"),`# Dependencies
|
|
1297
1297
|
node_modules/
|
|
1298
1298
|
|
|
1299
1299
|
# Generated projects
|
|
@@ -1306,19 +1306,19 @@ __pycache__/
|
|
|
1306
1306
|
*.pyc
|
|
1307
1307
|
.venv/
|
|
1308
1308
|
.env
|
|
1309
|
-
`,"utf-8"),await execa("git",["add","."],{cwd:
|
|
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
|
-
`)),console.log(m.cyan("\u{1F4C2} Location:"),m.white(
|
|
1312
|
-
`)),console.log(m.white(` cd ${
|
|
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 Dn(e,o,t,n){console.log(m.cyan(`
|
|
1313
1313
|
\u{1F50D} Dry-run mode - showing what would be created:
|
|
1314
|
-
`)),console.log(m.white("\u{1F4C2} Project path:"),
|
|
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(`
|
|
1316
1316
|
\u{1F3AF} Capabilities:`)),console.log(m.gray(" - Generate multiple FastAPI demo projects")),console.log(m.gray(" - No Python RapidKit installation required")),console.log(m.gray(" - Bundled templates included"))):(console.log(m.white(`
|
|
1317
|
-
\u2699\uFE0F Configuration:`)),console.log(m.gray(` - Python version: ${
|
|
1317
|
+
\u2699\uFE0F Configuration:`)),console.log(m.gray(` - Python version: ${n.pythonVersion||"3.10"}`)),console.log(m.gray(` - Install method: ${n.defaultInstallMethod||"poetry"}`)),console.log(m.gray(` - Git initialization: ${n.skipGit?"No":"Yes"}`)),console.log(m.white(`
|
|
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
|
+
`));}P();xe();var Tn=fileURLToPath(import.meta.url),Fn=v.dirname(Tn);function Kn(e=32){let o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=nn.randomBytes(e),n="";for(let r=0;r<e;r++)n+=o[t[r]%o.length];return n}async function co(e,o){let n=(o.template||"fastapi")==="fastapi",r=n?"FastAPI":"NestJS",i=Re(`Generating ${r} project...`).start();try{let s=v.resolve(Fn,".."),a=n?"fastapi-standard":"nestjs-standard",c=v.join(s,"templates","kits",a),l=Nn.configure(c,{autoescape:!1,trimBlocks:!0,lstripBlocks:!0});l.addFilter("generate_secret",function(h,w=32){return Kn(w)});let d={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()},p;n?p=["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"]:p=["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 p){let w=v.join(c,h);try{await promises.access(w);}catch{continue}let C=await promises.readFile(w,"utf-8"),T;try{T=l.renderString(C,d);}catch(et){throw console.error(`Failed to render template: ${h}`),et}let F=h.replace(/\.j2$/,""),H=v.join(e,F);await promises.mkdir(v.dirname(H),{recursive:!0}),await promises.writeFile(H,T),(F.endsWith(".rapidkit/rapidkit")||F.endsWith(".rapidkit/cli.py")||F.endsWith(".rapidkit/activate")||F==="rapidkit")&&await promises.chmod(H,493);}if(n){let h=v.join(c,".rapidkit","context.json"),w=v.join(e,".rapidkit","context.json");try{await promises.mkdir(v.join(e,".rapidkit"),{recursive:!0}),await promises.copyFile(h,w);}catch{await promises.mkdir(v.join(e,".rapidkit"),{recursive:!0});let T=o.engine||"pip";await promises.writeFile(w,JSON.stringify({engine:T,created_by:"rapidkit-npm-fallback"},null,2));}}let u=n?`# Python
|
|
1322
1322
|
__pycache__/
|
|
1323
1323
|
*.py[cod]
|
|
1324
1324
|
*$py.class
|
|
@@ -1386,16 +1386,16 @@ Thumbs.db
|
|
|
1386
1386
|
|
|
1387
1387
|
# Coverage
|
|
1388
1388
|
coverage/
|
|
1389
|
-
`;if(await promises.writeFile(
|
|
1389
|
+
`;if(await promises.writeFile(v.join(e,".gitignore"),u),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",w=Re(`Installing dependencies with ${h}...`).start();try{await execa(h,h==="yarn"?["install"]:h==="pnpm"?["install"]:["install"],{cwd:e}),w.succeed("Dependencies installed");}catch{w.warn(`Could not install dependencies. Run '${h} install' manually.`);}}let g=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")}
|
|
1393
1393
|
${m.cyan(" pip install rapidkit-core")}
|
|
1394
|
-
`),console.log(
|
|
1394
|
+
`),console.log(n?`
|
|
1395
1395
|
${m.green("\u2728 FastAPI project created successfully!")}
|
|
1396
1396
|
|
|
1397
1397
|
${m.bold("\u{1F4C2} Project structure:")}
|
|
1398
|
-
${
|
|
1398
|
+
${e}/
|
|
1399
1399
|
\u251C\u2500\u2500 .rapidkit/ # RapidKit CLI module
|
|
1400
1400
|
\u251C\u2500\u2500 src/
|
|
1401
1401
|
\u2502 \u251C\u2500\u2500 main.py # FastAPI application
|
|
@@ -1407,7 +1407,7 @@ ${t}/
|
|
|
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 ${g}`)}
|
|
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
|
|
|
@@ -1425,7 +1425,7 @@ ${m.gray("\u{1F4A1} Tip: Install globally (npm i -g rapidkit) to use without npx
|
|
|
1425
1425
|
${m.green("\u2728 NestJS project created successfully!")}
|
|
1426
1426
|
|
|
1427
1427
|
${m.bold("\u{1F4C2} Project structure:")}
|
|
1428
|
-
${
|
|
1428
|
+
${e}/
|
|
1429
1429
|
\u251C\u2500\u2500 .rapidkit/ # RapidKit CLI module
|
|
1430
1430
|
\u251C\u2500\u2500 src/
|
|
1431
1431
|
\u2502 \u251C\u2500\u2500 main.ts # Application entry point
|
|
@@ -1437,7 +1437,7 @@ ${t}/
|
|
|
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 ${g}`)}
|
|
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,50 +1458,148 @@ ${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(a){throw n.fail(`Failed to generate ${r} project`),a}}E();lt();async function We(){let t=process.platform==="win32"?["python","python3"]:["python3","python"];for(let i of t)try{let{stdout:e}=await execa(i,["--version"],{timeout:3e3}),o=e.match(/Python (\d+\.\d+\.\d+)/);if(o){let r=o[1],[n,a]=r.split(".").map(Number);return n<3||n===3&&a<10?{status:"warn",message:`Python ${r} (requires 3.10+)`,details:`${i} found but version is below minimum requirement`}:{status:"ok",message:`Python ${r}`,details:`Using ${i}`}}}catch{continue}return {status:"error",message:"Python not found",details:"Install Python 3.10+ and ensure it's in PATH"}}async function Ve(){try{let{stdout:t}=await execa("poetry",["--version"],{timeout:3e3}),i=t.match(/Poetry .*version ([\d.]+)/);return i?{status:"ok",message:`Poetry ${i[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 Ue(){try{let{stdout:t}=await execa("pipx",["--version"],{timeout:3e3});return {status:"ok",message:`pipx ${t.trim()}`,details:"Available for global tool installation"}}catch{return {status:"warn",message:"pipx not installed",details:"Optional: Install for isolated Python tools"}}}async function Be(){let t=process.env.HOME||process.env.USERPROFILE||"",i=[],e=[{location:"Global (pipx)",path:k.join(t,".local","bin","rapidkit")},{location:"Global (pipx)",path:k.join(t,"AppData","Roaming","Python","Scripts","rapidkit.exe")},{location:"Global (pyenv)",path:k.join(t,".pyenv","shims","rapidkit")},{location:"Global (system)",path:"/usr/local/bin/rapidkit"},{location:"Global (system)",path:"/usr/bin/rapidkit"}],o=[{location:"Workspace (.venv)",path:k.join(process.cwd(),".venv","bin","rapidkit")},{location:"Workspace (.venv)",path:k.join(process.cwd(),".venv","Scripts","rapidkit.exe")}];for(let{location:n,path:a}of [...e,...o])try{if(await v__default.pathExists(a)){let{stdout:s,exitCode:c}=await execa(a,["--version"],{timeout:3e3,reject:!1});if(c===0&&(s.includes("RapidKit Version")||s.includes("RapidKit"))){let l=s.match(/v?([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);l&&i.push({location:n,path:a,version:l[1]});}}}catch{continue}if(i.length>0)return {status:"ok",message:`RapidKit Core ${i[0].version}`,paths:i.map(a=>({location:a.location,path:a.path,version:a.version}))};try{let{stdout:n,exitCode:a}=await execa("rapidkit",["--version"],{timeout:3e3,reject:!1});if(a===0&&(n.includes("RapidKit Version")||n.includes("RapidKit"))){let s=n.match(/v?([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);if(s)return {status:"ok",message:`RapidKit Core ${s[1]}`,details:"Available via PATH"}}}catch{}try{let{stdout:n,exitCode:a}=await execa("poetry",["run","rapidkit","--version"],{timeout:3e3,reject:!1});if(a===0&&(n.includes("RapidKit Version")||n.includes("RapidKit"))){let s=n.match(/v?([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);if(s)return {status:"ok",message:`RapidKit Core ${s[1]}`,details:"Available via Poetry"}}}catch{}let r=process.platform==="win32"?["python","python3"]:["python3","python"];for(let n of r)try{let{stdout:a,exitCode:s}=await execa(n,["-c","import rapidkit_core; print(rapidkit_core.__version__)"],{timeout:3e3,reject:!1});if(s===0&&a&&!a.includes("Traceback")&&!a.includes("ModuleNotFoundError")){let c=a.trim();if(c)return {status:"ok",message:`RapidKit Core ${c}`,details:`Available in ${n} environment`}}}catch{continue}return {status:"error",message:"RapidKit Core not installed",details:"Install with: pipx install rapidkit-core"}}async function Zt(t,i){let e=k.join(t,"Dockerfile");i.hasDocker=await v__default.pathExists(e);let o=k.join(t,"tests"),r=k.join(t,"test");if(i.hasTests=await v__default.pathExists(o)||await v__default.pathExists(r),i.framework==="NestJS"){let n=k.join(t,".eslintrc.js"),a=k.join(t,".eslintrc.json");i.hasCodeQuality=await v__default.pathExists(n)||await v__default.pathExists(a);}else if(i.framework==="FastAPI"){let n=k.join(t,"ruff.toml"),a=k.join(t,"pyproject.toml");if(await v__default.pathExists(a))try{let s=await v__default.readFile(a,"utf8");i.hasCodeQuality=s.includes("[tool.ruff]")||await v__default.pathExists(n);}catch{i.hasCodeQuality=await v__default.pathExists(n);}}try{if(i.framework==="NestJS"){let{stdout:n}=await execa("npm",["audit","--json"],{cwd:t,reject:!1});if(n)try{let s=JSON.parse(n).metadata?.vulnerabilities;s&&(i.vulnerabilities=(s.high||0)+(s.critical||0)+(s.moderate||0));}catch{}}else if(i.framework==="FastAPI"){let n=k.join(t,".venv"),a=process.platform==="win32"?k.join(n,"Scripts","python.exe"):k.join(n,"bin","python");if(await v__default.pathExists(a))try{let{stdout:s}=await execa(a,["-m","pip","list","--format=json"],{timeout:5e3,reject:!1});if(s){let c=JSON.parse(s);i.vulnerabilities=0;}}catch{}}}catch{}}async function qi(t){let e={name:k.basename(t),path:t,venvActive:false,depsInstalled:false,coreInstalled:false,issues:[],fixCommands:[]},o=k.join(t,".rapidkit");if(!await v__default.pathExists(o))return e.issues.push("Not a valid RapidKit project (missing .rapidkit directory)"),e;try{let c=k.join(t,"registry.json");if(await v__default.pathExists(c)){let l=await v__default.readJson(c);l.installed_modules&&(e.stats={modules:l.installed_modules.length});}}catch{}try{let c=k.join(o,"project.json");if(await v__default.pathExists(c)){let l=await v__default.readJson(c);l.kit&&(e.kit=l.kit);}}catch{}try{let c=k.join(t,".git");if(await v__default.pathExists(c)){let{stdout:l}=await execa("git",["log","-1","--format=%cr"],{cwd:t,reject:!1});l&&(e.lastModified=l.trim());}else {let l=await v__default.stat(t),d=Date.now()-l.mtime.getTime(),u=Math.floor(d/(1e3*60*60*24));e.lastModified=u===0?"today":`${u} day${u>1?"s":""} ago`;}}catch{}let r=k.join(t,"package.json"),n=k.join(t,"pyproject.toml"),a=await v__default.pathExists(r),s=await v__default.pathExists(n);if(a){e.framework="NestJS",e.venvActive=true;let c=k.join(t,"node_modules");if(await v__default.pathExists(c))try{let u=(await v__default.readdir(c)).filter(f=>!f.startsWith(".")&&!f.startsWith("_"));e.depsInstalled=u.length>0;}catch{e.depsInstalled=false;}e.depsInstalled||(e.issues.push("Dependencies not installed (node_modules empty or missing)"),e.fixCommands?.push(`cd ${t} && rapidkit init`)),e.coreInstalled=false;let l=k.join(t,".env");if(e.hasEnvFile=await v__default.pathExists(l),!e.hasEnvFile){let d=k.join(t,".env.example");await v__default.pathExists(d)&&(e.issues.push("Environment file missing (found .env.example)"),e.fixCommands?.push(`cd ${t} && cp .env.example .env`));}let p=k.join(t,"src");if(e.modulesHealthy=true,e.missingModules=[],await v__default.pathExists(p))try{let d=await v__default.readdir(p);e.modulesHealthy=d.length>0;}catch{e.modulesHealthy=false;}return await Zt(t,e),e}if(s){e.framework="FastAPI";let c=k.join(t,".venv");if(await v__default.pathExists(c)){e.venvActive=true;let u=process.platform==="win32"?k.join(c,"Scripts","python.exe"):k.join(c,"bin","python");if(await v__default.pathExists(u)){try{let{stdout:f}=await execa(u,["-c","import rapidkit_core; print(rapidkit_core.__version__)"],{timeout:2e3});e.coreInstalled=!0,e.coreVersion=f.trim();}catch{e.coreInstalled=false;}try{await execa(u,["-c","import fastapi"],{timeout:2e3}),e.depsInstalled=!0;}catch{try{let f=k.join(c,"lib");if(await v__default.pathExists(f)){let h=(await v__default.readdir(f)).find(j=>j.startsWith("python"));if(h){let j=k.join(f,h,"site-packages");if(await v__default.pathExists(j)){let T=(await v__default.readdir(j)).filter(V=>!V.startsWith("_")&&!V.includes("dist-info")&&!["pip","setuptools","wheel","pkg_resources"].includes(V));e.depsInstalled=T.length>0;}}}e.depsInstalled||(e.issues.push("Dependencies not installed"),e.fixCommands?.push(`cd ${t} && rapidkit init`));}catch{e.issues.push("Could not verify dependency installation");}}}else e.issues.push("Virtual environment exists but Python executable not found");}else e.issues.push("Virtual environment not created"),e.fixCommands?.push(`cd ${t} && rapidkit init`);let l=k.join(t,".env");if(e.hasEnvFile=await v__default.pathExists(l),!e.hasEnvFile){let u=k.join(t,".env.example");await v__default.pathExists(u)&&(e.issues.push("Environment file missing (found .env.example)"),e.fixCommands?.push(`cd ${t} && cp .env.example .env`));}let p=k.join(t,"src"),d=k.join(t,"modules");if(e.modulesHealthy=true,e.missingModules=[],await v__default.pathExists(p)){let u=k.join(p,"__init__.py");await v__default.pathExists(u)||(e.modulesHealthy=false,e.missingModules.push("src/__init__.py"));}if(await v__default.pathExists(d))try{let u=await He(d);for(let f of u){let g=k.join(d,f,"__init__.py");await v__default.pathExists(g)||(e.modulesHealthy=!1,e.missingModules.push(`modules/${f}/__init__.py`));}}catch{}return !e.modulesHealthy&&e.missingModules.length>0&&e.issues.push(`Missing module init files: ${e.missingModules.join(", ")}`),await Zt(t,e),e}return e.issues.push("Unknown project type (no package.json or pyproject.toml)"),await Zt(t,e),e}async function He(t){try{return (await v__default.readdir(t,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>e.name)}catch{try{let i=await v__default.readdir(t),e=[];for(let o of i)try{(await v__default.stat(k.join(t,o))).isDirectory()&&e.push(o);}catch{continue}return e}catch{return []}}}async function Qi(t,i,e){let o=new Set,r=[{dir:t,depth:0}];for(;r.length>0;){let n=r.shift();if(!n)break;try{let a=await v__default.readdir(n.dir);for(let s of a){if(e.has(s))continue;let c=k.join(n.dir,s),l;try{l=await v__default.stat(c);}catch{continue}if(!l.isDirectory())continue;let p=k.join(c,".rapidkit");if(await v__default.pathExists(p)){o.add(c);continue}n.depth<i&&r.push({dir:c,depth:n.depth+1});}}catch{continue}}return Array.from(o)}async function Xi(t){let i=t,e=k.parse(i).root;for(;i!==e;){let o=[k.join(i,".rapidkit-workspace"),k.join(i,".rapidkit","workspace-marker.json"),k.join(i,".rapidkit","config.json")];for(let r of o)if(await v__default.pathExists(r))return i;i=k.dirname(i);}return null}function Zi(t,i){let e=0,o=0,r=0;return t.forEach(a=>{a.status==="ok"?e++:a.status==="warn"?o++:a.status==="error"&&r++;}),i.forEach(a=>{a.issues.length===0&&a.venvActive&&a.depsInstalled?e++:a.issues.length>0&&o++;}),{total:e+o+r,passed:e,warnings:o,errors:r}}async function to(t){let i=k.basename(t);try{let r=k.join(t,".rapidkit-workspace");await v__default.pathExists(r)&&(i=(await v__default.readJSON(r)).name||i);}catch{try{let r=k.join(t,".rapidkit","config.json");i=(await v__default.readJSON(r)).workspace_name||i;}catch{}}let e={workspacePath:t,workspaceName:i,python:await We(),poetry:await Ve(),pipx:await Ue(),rapidkitCore:await Be(),projects:[]};try{let r=new Set([".git",".venv","node_modules",".rapidkit","dist","build","coverage","__pycache__"]),n=new Set,a=k.join(t,".rapidkit");await v__default.pathExists(a)&&n.add(t);let s=async(c,l)=>{if(l<0)return;let p=await He(c);for(let d of p){if(r.has(d))continue;let u=k.join(c,d),f=k.join(u,".rapidkit");if(await v__default.pathExists(f)){n.add(u);continue}l>0&&await s(u,l-1);}};if(await s(t,1),y.debug(`Workspace scan (shallow) found ${n.size} project(s)`),n.size===0){let c=await Qi(t,3,r);c.forEach(l=>n.add(l)),y.debug(`Workspace scan (deep fallback) found ${c.length} project(s)`);}n.size>0&&y.debug(`Workspace projects detected: ${Array.from(n).join(", ")}`);for(let c of n){let l=await qi(c);e.projects.push(l);}}catch(r){y.debug(`Failed to scan workspace projects: ${r}`);}let o=[e.python,e.poetry,e.pipx,e.rapidkitCore];if(e.healthScore=Zi(o,e.projects),e.rapidkitCore.status==="ok"){let r=e.rapidkitCore.message.match(/([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);r&&(e.coreVersion=r[1]);}return e}function tt(t,i){let e=t.status==="ok"?"\u2705":t.status==="warn"?"\u26A0\uFE0F":"\u274C",o=t.status==="ok"?m.green:t.status==="warn"?m.yellow:m.red;console.log(`${e} ${m.bold(i)}: ${o(t.message)}`),t.paths&&t.paths.length>0?t.paths.forEach(r=>{let n=r.version?m.cyan(` -> ${r.version}`):"";console.log(` ${m.cyan("\u2022")} ${m.gray(r.location)}: ${m.dim(r.path)}${n}`);}):t.details&&console.log(` ${m.gray(t.details)}`);}function eo(t){let i=t.issues.length>0,e=i?"\u26A0\uFE0F":"\u2705",o=i?m.yellow:m.green;if(console.log(`
|
|
1462
|
-
${
|
|
1463
|
-
${m.bold.cyan("\u{1F527} Quick Fix:")}`),
|
|
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(`
|
|
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
|
+
${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(`
|
|
1465
1465
|
\u{1F527} Available Fixes:
|
|
1466
|
-
`));for(let r of
|
|
1466
|
+
`));for(let r of t)console.log(m.bold(`Project: ${m.yellow(r.name)}`)),r.fixCommands.forEach((i,s)=>{console.log(` ${s+1}. ${m.cyan(i)}`);}),console.log();if(!o){console.log(m.gray("\u{1F4A1} Run with --fix flag to apply fixes automatically"));return}let{confirm:n}=await gt.prompt([{type:"confirm",name:"confirm",message:`Apply ${t.reduce((r,i)=>r+i.fixCommands.length,0)} fix(es)?`,default:false}]);if(!n){console.log(m.yellow(`
|
|
1467
1467
|
\u26A0\uFE0F Fixes cancelled by user`));return}console.log(m.bold.cyan(`
|
|
1468
1468
|
\u{1F680} Applying fixes...
|
|
1469
|
-
`));for(let r of
|
|
1470
|
-
`));}catch(
|
|
1469
|
+
`));for(let r of t){console.log(m.bold(`Fixing ${m.cyan(r.name)}...`));for(let i of r.fixCommands)try{console.log(m.gray(` $ ${i}`)),await execa(i,{shell:!0,stdio:"inherit"}),console.log(m.green(` \u2705 Success
|
|
1470
|
+
`));}catch(s){console.log(m.red(` \u274C Failed: ${s instanceof Error?s.message:String(s)}
|
|
1471
1471
|
`));}}console.log(m.bold.green(`
|
|
1472
|
-
\u2705 Fix process completed!`));}async function
|
|
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
|
-
`)),
|
|
1475
|
-
\u{1F4CA} Health Score:`)),console.log(` ${
|
|
1474
|
+
`)),e.workspace){let o=await Vn(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 Bn(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
|
+
\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
|
-
`)),
|
|
1479
|
-
\u26A0\uFE0F Version mismatch: Core ${
|
|
1480
|
-
\u{1F4E6} Projects (${
|
|
1481
|
-
\u{1F4E6} Projects:`)),console.log(m.gray(" No RapidKit projects found in workspace")));let
|
|
1482
|
-
\u26A0\uFE0F Found ${
|
|
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
|
+
\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=>Hn(i))):(console.log(m.bold(`
|
|
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
|
+
\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:
|
|
1484
|
-
`));let
|
|
1484
|
+
`));let o=await po(),t=await uo(),n=await mo(),r=await go();ie(o,"Python"),ie(t,"Poetry"),ie(n,"pipx"),ie(r,"RapidKit Core"),[o,r].some(s=>s.status==="error")?(console.log(m.bold.red(`
|
|
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("");}function
|
|
1489
|
-
|
|
1488
|
+
Tip: Run "rapidkit doctor --workspace" from within a workspace for detailed project checks`)));}console.log("");}P();P();var wt=v.join(te__default.homedir(),".rapidkit"),Ve=v.join(wt,"config.json");function ke(){try{if(!W.existsSync(Ve))return {};let e=W.readFileSync(Ve,"utf-8");return JSON.parse(e)}catch{return {}}}function Ue(e){let t={...ke(),...e};W.existsSync(wt)||W.mkdirSync(wt,{recursive:true}),W.writeFileSync(Ve,JSON.stringify(t,null,2),"utf-8");}function Ie(){return process.env.OPENAI_API_KEY||ke().openaiApiKey||null}function kt(){return ke().aiEnabled!==false}function vt(){return Ve}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
|
+
\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,Ue({openaiApiKey:n}),console.log(m.green(`
|
|
1491
|
+
\u2705 OpenAI API key saved successfully!
|
|
1492
|
+
`)),console.log(m.gray(`Stored in: ${vt()}`)),console.log(m.cyan(`
|
|
1493
|
+
\u{1F389} You can now use AI features:`)),console.log(m.white(' rapidkit ai recommend "I need user authentication"')),console.log(m.gray(`
|
|
1494
|
+
\u{1F4A1} To generate module embeddings (one-time):`)),console.log(m.white(" cd rapidkit-npm")),console.log(m.white(` npx tsx src/ai/generate-embeddings.ts
|
|
1495
|
+
`));}),o.command("show").description("Show current configuration").action(()=>{let t=ke();if(console.log(m.bold(`
|
|
1496
|
+
\u2699\uFE0F RapidKit Configuration
|
|
1497
|
+
`)),t.openaiApiKey){let n=t.openaiApiKey.substring(0,8)+"..."+t.openaiApiKey.slice(-4);console.log(m.cyan("OpenAI API Key:"),m.white(n));}else console.log(m.cyan("OpenAI API Key:"),m.red("Not set")),console.log(m.gray(" Set with: rapidkit config set-api-key"));console.log(m.cyan("AI Features:"),t.aiEnabled!==false?m.green("Enabled"):m.red("Disabled")),console.log(m.gray(`
|
|
1498
|
+
\u{1F4C1} Config file: ${vt()}
|
|
1499
|
+
`));}),o.command("remove-api-key").description("Remove stored OpenAI API key").action(async()=>{if(!ke().openaiApiKey){console.log(m.yellow(`
|
|
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?(Ue({openaiApiKey:void 0}),console.log(m.green(`
|
|
1502
|
+
\u2705 API key removed successfully
|
|
1503
|
+
`))):console.log(m.gray(`
|
|
1504
|
+
Cancelled
|
|
1505
|
+
`));}),o.command("ai <action>").description("Enable or disable AI features (enable|disable)").action(t=>{t!=="enable"&&t!=="disable"&&(console.log(m.red(`
|
|
1506
|
+
\u274C Invalid action: ${t}`)),console.log(m.gray(`Use: rapidkit config ai enable|disable
|
|
1507
|
+
`)),process.exit(1));let n=t==="enable";Ue({aiEnabled:n}),console.log(m.green(`
|
|
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(`
|
|
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
|
+
`)),!1;console.log(m.blue(`
|
|
1512
|
+
\u{1F916} Generating AI embeddings for RapidKit modules...
|
|
1513
|
+
`)),console.log(m.gray("\u{1F4E1} Fetching modules from RapidKit..."));let t=await Ye();console.log(m.green(`\u2713 Found ${t.length} modules
|
|
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
|
+
`)),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
|
+
\u26A0\uFE0F Embeddings generation cancelled
|
|
1517
|
+
`)),!1}let r=t.map(s=>`${s.name}. ${s.description}. ${s.longDescription}. Keywords: ${s.keywords.join(", ")}. Use cases: ${s.useCases.join(", ")}.`),i=Re(`Generating embeddings for ${t.length} modules...`).start();try{let s=await jo(r);i.succeed(`Generated embeddings for ${t.length} modules`);let a={model:"text-embedding-3-small",dimension:s[0].length,generated_at:new Date().toISOString(),modules:t.map((d,p)=>({id:d.id,name:d.name,embedding:s[p]}))},c=o||v.join(process.cwd(),"data","modules-embeddings.json"),l=v.dirname(c);return W.existsSync(l)||W.mkdirSync(l,{recursive:!0}),W.writeFileSync(c,JSON.stringify(a,null,2)),console.log(m.green(`
|
|
1518
|
+
\u2705 Embeddings generated successfully!`)),console.log(m.gray(`\u{1F4C1} Saved to: ${c}`)),console.log(m.gray(`\u{1F4CA} Size: ${t.length} modules, ${s[0].length} dimensions
|
|
1519
|
+
`)),!0}catch(s){return i.fail("Failed to generate embeddings"),s.message?.includes("429")?(console.log(m.red(`
|
|
1520
|
+
\u274C OpenAI API quota exceeded`)),console.log(m.yellow(`Please check your billing: https://platform.openai.com/account/billing
|
|
1521
|
+
`))):s.message?.includes("401")?(console.log(m.red(`
|
|
1522
|
+
\u274C Invalid API key`)),console.log(m.yellow("Please set a valid API key:")),console.log(m.white(` rapidkit config set-api-key
|
|
1523
|
+
`))):console.log(m.red(`
|
|
1524
|
+
\u274C Error: ${s.message}
|
|
1525
|
+
`)),!1}}catch(t){return console.log(m.red(`
|
|
1526
|
+
\u274C Failed to generate embeddings: ${t.message}
|
|
1527
|
+
`)),false}}async function Mo(e=true){if(No().exists)return true;if(console.log(m.yellow(`
|
|
1528
|
+
\u26A0\uFE0F Module embeddings not found`)),console.log(m.gray(`AI recommendations require embeddings to be generated.
|
|
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 ze(true):(t==="manual"&&(console.log(m.cyan(`
|
|
1531
|
+
\u{1F4DD} To generate embeddings manually:
|
|
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
|
+
`)),console.log(m.white("3. Generate embeddings:")),console.log(m.gray(` rapidkit ai generate-embeddings
|
|
1534
|
+
`)),console.log(m.cyan(`\u{1F4B0} Cost: ~$0.50 one-time
|
|
1535
|
+
`))),false)}async function Oo(){let e=No();return e.exists?(console.log(m.blue(`
|
|
1536
|
+
\u{1F504} Updating embeddings...`)),console.log(m.gray(`Current: ${e.moduleCount} modules`)),console.log(m.gray(`Generated: ${e.generatedAt||"unknown"}
|
|
1537
|
+
`)),await ze(true,e.path)):(console.log(m.yellow(`
|
|
1538
|
+
\u26A0\uFE0F No existing embeddings found`)),console.log(m.gray(`Use: rapidkit ai generate-embeddings
|
|
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
|
+
\u26A0\uFE0F AI features are disabled`)),console.log(m.gray(`Enable with: rapidkit config ai enable
|
|
1541
|
+
`)),process.exit(1));let r=Ie();r?Je(r):(console.log(m.yellow(`
|
|
1542
|
+
\u26A0\uFE0F OpenAI API key not configured - using MOCK MODE for testing
|
|
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
|
+
`)),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-..."
|
|
1545
|
+
`)),vo());let i=t;i||(i=(await gt.prompt([{type:"input",name:"query",message:"\u{1F916} What do you want to build?",validate:u=>u.length===0?"Please enter a description":u.length<3?"Please be more specific (at least 3 characters)":!0}])).query),n.json||console.log(m.blue(`
|
|
1546
|
+
\u{1F916} Analyzing your request...
|
|
1547
|
+
`)),await Mo(!n.json)||(console.log(m.yellow(`
|
|
1548
|
+
\u26A0\uFE0F Cannot proceed without embeddings
|
|
1549
|
+
`)),process.exit(1));let a=parseInt(n.number,10),c=await Ao(i,a);if(c.length===0||c[0].score<.3)if(console.log(m.yellow(`
|
|
1550
|
+
\u26A0\uFE0F No matching modules found in RapidKit registry.
|
|
1551
|
+
`)),console.log(m.cyan(`\u{1F4A1} Options:
|
|
1552
|
+
`)),console.log(m.white("1. Create custom module:")),console.log(m.gray(" rapidkit modules scaffold <name> --category <category>")),console.log(m.gray(` Example: rapidkit modules scaffold blockchain-integration --category integrations
|
|
1553
|
+
`)),console.log(m.white("2. Search with different keywords")),console.log(m.gray(` Try more general terms (e.g., "storage" instead of "blockchain")
|
|
1554
|
+
`)),console.log(m.white("3. Request feature:")),console.log(m.gray(` https://github.com/getrapidkit/rapidkit/issues
|
|
1555
|
+
`)),c.length>0)console.log(m.yellow(`\u26A0\uFE0F Low confidence matches found:
|
|
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),h=p.score>.8?" \u2B50":"";console.log(m.bold(`${u+1}. ${p.module.name}${h}`)),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
|
+
`));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
|
+
\u{1F4E6} Installing ${p.length} modules...
|
|
1560
|
+
`)),console.log(m.gray(`Command: rapidkit add module ${p.join(" ")}`)),console.log(m.yellow(`
|
|
1561
|
+
\u26A0\uFE0F Note: Module installation not yet implemented`)),console.log(m.gray(`Coming soon in next version!
|
|
1562
|
+
`))):console.log(m.gray(`
|
|
1563
|
+
No modules selected
|
|
1564
|
+
`));}}catch(r){y.error(`
|
|
1565
|
+
\u274C Error:`,r.message),r.code==="invalid_api_key"?(console.log(m.yellow(`
|
|
1566
|
+
\u{1F4A1} Your API key may be invalid or expired`)),console.log(m.cyan(` Update it: rapidkit config set-api-key
|
|
1567
|
+
`))):r.message.includes("embeddings file not found")&&(console.log(m.yellow(`
|
|
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=Ie(),n=kt();console.log(m.bold(`
|
|
1570
|
+
\u{1F916} RapidKit AI Features
|
|
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
|
+
\u{1F4E6} Available Features:
|
|
1573
|
+
`)),console.log(m.white("\u2022 Module Recommender")+m.gray(" - AI-powered module suggestions")),console.log(m.gray(' Usage: rapidkit ai recommend "I need authentication"')),console.log(m.bold(`
|
|
1574
|
+
\u{1F4B0} Pricing:
|
|
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
|
+
\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=Ie();t||(console.log(m.red(`
|
|
1578
|
+
\u274C OpenAI API key not configured
|
|
1579
|
+
`)),console.log(m.cyan(`To generate embeddings, you need an OpenAI API key:
|
|
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
|
+
OR set environment variable:`)),console.log(m.white(` export OPENAI_API_KEY="sk-proj-..."
|
|
1582
|
+
`)),process.exit(1)),Je(t);let n=await ze(!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=Ie();t||(console.log(m.red(`
|
|
1584
|
+
\u274C OpenAI API key not configured
|
|
1585
|
+
`)),console.log(m.white(`Set your API key: rapidkit config set-api-key
|
|
1586
|
+
`)),process.exit(1)),Je(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 mi(e){let o=e.trim().toLowerCase();return o?o.startsWith("fastapi")?"fastapi":o.startsWith("nestjs")?"nestjs":null:null}function gi(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
|
+
Reason: ${o}.
|
|
1490
1588
|
Install Python 3.10+ to use the interactive wizard and full kit catalog.
|
|
1491
|
-
`),1;let r=
|
|
1589
|
+
`),1;let r=e[2],i=e[3];if(!r||!i)return process.stderr.write(`Usage: rapidkit create project <kit> <name> [--output <dir>]
|
|
1492
1590
|
Tip: offline fallback supports only fastapi* and nestjs* kits.
|
|
1493
|
-
`),1;let
|
|
1494
|
-
Reason: ${
|
|
1591
|
+
`),1;let s=mi(r);if(!s)return process.stderr.write(`RapidKit (npm) could not run the Python core engine to create this kit.
|
|
1592
|
+
Reason: ${o}.
|
|
1495
1593
|
Requested kit: ${r}
|
|
1496
1594
|
Offline fallback only supports: fastapi.standard, nestjs.standard (and their shorthands).
|
|
1497
1595
|
Install Python 3.10+ to access all kits.
|
|
1498
|
-
`),1;let
|
|
1499
|
-
`),1;let
|
|
1500
|
-
`),1}}async function
|
|
1501
|
-
`),y.debug(`Synced Python version ${
|
|
1502
|
-
`),1)}}if(
|
|
1503
|
-
`),1)}return await
|
|
1504
|
-
`),1)}}var
|
|
1596
|
+
`),1;let a=gi(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=Xe(process.cwd());if(u)try{let{readWorkspaceMarker:g}=await Promise.resolve().then(()=>(ut(),qt)),h=await g(u);h?.metadata?.npm?.installMethod&&(p=h.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,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 fi(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(!!!Qe(process.cwd())){if(t)await pe(process.cwd(),{skipGit:i,yes:r,userConfig:await Pe()});else if(!n)if(r)await pe(process.cwd(),{skipGit:i,yes:!0,userConfig:await Pe()});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 Pe()});}}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=Xe(process.cwd());if(l){try{let p=e[3];if(p){let u=e.indexOf("--output"),g=u>=0?e[u+1]:".",h=v.resolve(process.cwd(),g,p),w=v.join(l,".python-version"),C=v.join(h,".python-version");if(W.existsSync(w)&&W.existsSync(h)){let T=W.readFileSync(w,"utf-8");W.writeFileSync(C,T.trim()+`
|
|
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=Xe(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
|
+
`),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 hi(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 Qe(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 Xe(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 yi(){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(Qe(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=hi(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 h of p)if(await b.pathExists(h)){u=h;break}if(u&&l&&Ko.includes(l)){y.debug(`Delegating to local CLI (early detection): ${u} ${o.join(" ")}`);let h=spawn(u,o,{stdio:"inherit",cwd:e});return h.on("close",w=>process.exit(w??0)),h.on("error",w=>{y.error(`Failed to run local rapidkit: ${w.message}`),process.exit(1);}),!0}if(l==="shell"&&o[1]==="activate"){let h=`# RapidKit: activation snippet - eval "$(rapidkit shell activate)"
|
|
1505
1603
|
VENV='.venv'
|
|
1506
1604
|
if [ -f "$VENV/bin/activate" ]; then
|
|
1507
1605
|
. "$VENV/bin/activate"
|
|
@@ -1512,43 +1610,43 @@ export RAPIDKIT_PROJECT_ROOT="$(pwd)"
|
|
|
1512
1610
|
export PATH="$(pwd)/.rapidkit:$(pwd):$PATH"
|
|
1513
1611
|
`;console.log(m.green.bold(`
|
|
1514
1612
|
\u2705 Activation snippet \u2014 run the following to activate this project in your current shell:
|
|
1515
|
-
`)),console.log(
|
|
1613
|
+
`)),console.log(h),console.log(m.gray(`
|
|
1516
1614
|
\u{1F4A1} After activation you can run: rapidkit dev
|
|
1517
|
-
`)),process.exit(0);}let
|
|
1615
|
+
`)),process.exit(0);}let g=await Q(o,{cwd:e});process.exit(g);}}catch{}return false}var re=null,Ze=false,Z=new Command;async function ki(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
|
|
1518
1616
|
|
|
1519
1617
|
Global CLI
|
|
1520
1618
|
Create RapidKit workspaces and projects
|
|
1521
1619
|
|
|
1522
1620
|
Global Engine Commands
|
|
1523
1621
|
Access engine-level commands when inside a RapidKit workspace or via the core bridge
|
|
1524
|
-
`);
|
|
1622
|
+
`);Z.addHelpText("afterAll",`
|
|
1525
1623
|
Project Commands
|
|
1526
1624
|
rapidkit create
|
|
1527
1625
|
rapidkit init
|
|
1528
1626
|
rapidkit dev
|
|
1529
1627
|
|
|
1530
1628
|
Use "rapidkit help <command>" for more information.
|
|
1531
|
-
`);
|
|
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 Pe();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 Rt(),console.log(m.blue.bold(`
|
|
1532
1630
|
\u{1F680} Welcome to RapidKit!
|
|
1533
|
-
`)),
|
|
1534
|
-
\u274C ${
|
|
1535
|
-
`),process.exit(1)),
|
|
1536
|
-
\u274C Directory "${
|
|
1631
|
+
`)),e||(vi(),process.exit(0));try{At(e);}catch(a){throw a instanceof J&&(y.error(`
|
|
1632
|
+
\u274C ${a.message}`),a.details&&y.warn(`\u{1F4A1} ${a.details}
|
|
1633
|
+
`),process.exit(1)),a}let i=v.resolve(process.cwd(),e);re=i,await b.pathExists(i)&&(y.error(`
|
|
1634
|
+
\u274C Directory "${e}" already exists`),console.log(m.cyan(`
|
|
1537
1635
|
\u{1F4A1} Choose a different name or delete the existing directory.
|
|
1538
|
-
`)),process.exit(1));let
|
|
1636
|
+
`)),process.exit(1));let s=!!o.template;if(o.dryRun){console.log(m.cyan(`
|
|
1539
1637
|
\u{1F50D} Dry-run mode - showing what would be created:
|
|
1540
|
-
`)),console.log(m.white("\u{1F4C2} Path:"),
|
|
1541
|
-
`)),
|
|
1542
|
-
`),y.debug(`Synced Python version ${
|
|
1543
|
-
`),y.debug(`Re-synced Python version ${
|
|
1544
|
-
\u274C ${
|
|
1545
|
-
\u274C An unexpected error occurred:`),console.error(
|
|
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(!!!Qe(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:h}=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}]);h&&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=Qe(process.cwd());if(g){let h=v.dirname(g),w=v.join(h,".python-version"),C=v.join(i,".python-version");try{if(await b.pathExists(w)){let T=W.readFileSync(w,"utf-8");W.writeFileSync(C,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 h=await Q(["init",i],{cwd:process.cwd()});if(h!==0&&process.exit(h),g){let w=v.dirname(g),C=v.join(w,".python-version"),T=v.join(i,".python-version");try{if(await b.pathExists(C)){let F=W.readFileSync(C,"utf-8");W.writeFileSync(T,F.trim()+`
|
|
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
|
+
\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=Xe(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 vi(){console.log(m.white(`Usage:
|
|
1546
1644
|
`)),console.log(m.cyan(" npx rapidkit <workspace-name> [options]")),console.log(m.cyan(` npx rapidkit create <...>
|
|
1547
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
|
|
1548
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
|
|
1549
1647
|
`)),console.log(m.gray(`Tip: set RAPIDKIT_SHOW_LEGACY=1 to show legacy template flags in help.
|
|
1550
|
-
`));}process.on("SIGINT",async()=>{if(!
|
|
1648
|
+
`));}process.on("SIGINT",async()=>{if(!Ze){if(Ze=true,console.log(m.yellow(`
|
|
1551
1649
|
|
|
1552
|
-
\u26A0\uFE0F Interrupted by user`)),
|
|
1553
|
-
`),
|
|
1554
|
-
`),
|
|
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(!Ze){if(Ze=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);}});yi().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 fi(o);process.exit(n);}let t=await ki(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{fi as handleCreateOrFallback};
|