rapidkit 0.25.4 → 0.25.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -2,6 +2,15 @@
2
2
  declare function handleCreateOrFallback(args: string[]): Promise<number>;
3
3
  declare const NPM_ONLY_TOP_LEVEL_COMMANDS: readonly ["doctor", "workspace", "bootstrap", "setup", "cache", "mirror", "ai", "config", "shell"];
4
4
  declare const WRAPPER_ORCHESTRATED_PROJECT_COMMANDS: readonly ["init"];
5
+ interface DoctorWorkspaceShadowDiagnostic {
6
+ detected: boolean;
7
+ candidatePath?: string;
8
+ reason?: string;
9
+ }
10
+ declare function detectWindowsDoctorWorkspaceShadow(params: {
11
+ scope?: string;
12
+ workspaceFlag?: boolean;
13
+ }, cwd?: string, platform?: NodeJS.Platform): Promise<DoctorWorkspaceShadowDiagnostic>;
5
14
  declare function handleBootstrapCommand(args: string[], initRunner?: (nextArgs: string[]) => Promise<number>): Promise<number>;
6
15
  declare function handleSetupCommand(args: string[]): Promise<number>;
7
16
  declare function handleCacheCommand(args: string[]): Promise<number>;
@@ -9,4 +18,4 @@ declare function handleMirrorCommand(args: string[]): Promise<number>;
9
18
  declare function handleInitCommand(args: string[]): Promise<number>;
10
19
  declare function shouldForwardToCore(args: string[]): Promise<boolean>;
11
20
 
12
- export { NPM_ONLY_TOP_LEVEL_COMMANDS, WRAPPER_ORCHESTRATED_PROJECT_COMMANDS, handleBootstrapCommand, handleCacheCommand, handleCreateOrFallback, handleInitCommand, handleMirrorCommand, handleSetupCommand, shouldForwardToCore };
21
+ export { type DoctorWorkspaceShadowDiagnostic, NPM_ONLY_TOP_LEVEL_COMMANDS, WRAPPER_ORCHESTRATED_PROJECT_COMMANDS, detectWindowsDoctorWorkspaceShadow, handleBootstrapCommand, handleCacheCommand, handleCreateOrFallback, handleInitCommand, handleMirrorCommand, handleSetupCommand, shouldForwardToCore };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {e,d as d$1,c as c$2,h as h$3,a as a$3}from'./chunk-UOGFCKQ5.js';import {a as a$2,b as b$1,c as c$1,d,i,h as h$1,e as e$1,f}from'./chunk-KAV65WZO.js';import {c,a as a$1,b as b$2}from'./chunk-EDH5S5JF.js';import {a,h as h$2,i as i$1,b as b$3,c as c$3,d as d$2,f as f$1,k,g}from'./chunk-Z5LKRG57.js';import {Command,Option}from'commander';import l from'chalk';import xe from'inquirer';import h from'path';import {fileURLToPath}from'url';import {exec,spawn}from'child_process';import Gr from'validate-npm-package-name';import*as b from'fs-extra';import b__default from'fs-extra';import _,{promises,createWriteStream}from'fs';import {execa}from'execa';import Wr from'nunjucks';import Ut from'ora';import Vr,{createHash,createVerify,createHmac}from'crypto';import Tn from'os';import {promisify}from'util';import cr from'http';import lr from'https';function Wt(e){let o=Gr(e);if(!o.validForNewPackages){let r=o.errors||[],i=o.warnings||[],n=[...r,...i];throw new e$1(e,`NPM validation failed: ${n.join(", ")}`)}if(!/^[a-z][a-z0-9_-]*$/.test(e))throw new e$1(e,"Must start with a lowercase letter and contain only lowercase letters, numbers, hyphens, and underscores");if(["test","tests","src","dist","build","lib","python","pip","poetry","node","npm","rapidkit","rapidkit"].includes(e.toLowerCase()))throw new e$1(e,`"${e}" is a reserved name. Please choose a different name.`);if(e.length<2)throw new e$1(e,"Name must be at least 2 characters long");if(e.length>214)throw new e$1(e,"Name must be less than 214 characters");return true}function Lr(){return d$2()}function qr(e,o){return e==="py"?["-3",...o]:o}function Fr(e){return typeof e=="object"&&e!==null}async function Hr(e,o,t,r=8e3){try{let i=await execa(e,o,{cwd:t,timeout:r,reject:false,stdio:"pipe"});return {ok:i.exitCode===0,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr}}catch(i){return {ok:false,exitCode:void 0,stdout:"",stderr:i instanceof Error?i.message:String(i)}}}async function Kr(e,o){let t=["-m","rapidkit",...e],r=Lr();for(let i of r){let n=await Hr(i,qr(i,t),o?.cwd,o?.timeoutMs);if(!n.ok)continue;let a=(n.stdout??"").trim();try{let s=JSON.parse(a);return Fr(s)?{ok:true,command:i,exitCode:n.exitCode,stdout:n.stdout,stderr:n.stderr,data:s}:{ok:false,command:i,exitCode:n.exitCode,stdout:n.stdout,stderr:n.stderr}}catch{return {ok:false,command:i,exitCode:n.exitCode,stdout:n.stdout,stderr:n.stderr}}}return {ok:false}}async function vo(e,o){let t=await Kr(["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}var Br=fileURLToPath(import.meta.url),Jr=h.dirname(Br);function Yr(e=32){let o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=Vr.randomBytes(e),r="";for(let i=0;i<e;i++)r+=o[t[i]%o.length];return r}async function ko(e,o){let t=o.template||"fastapi",r=t==="fastapi",i=r?"FastAPI":"NestJS",n=Ut(`Generating ${i} project...`).start();try{let a=h.resolve(Jr,".."),s=o.kit_name||`${t}.standard`,c$1;s==="fastapi.ddd"?c$1="fastapi-ddd":s.startsWith("fastapi")?c$1="fastapi-standard":c$1="nestjs-standard";let p=h.join(a,"templates","kits",c$1),d=Wr.configure(p,{autoescape:false,trimBlocks:true,lstripBlocks:true});d.addFilter("generate_secret",function(g,R=32){return Yr(R)});let u={project_name:o.project_name,author:o.author||"RapidKit User",description:o.description||(r?"FastAPI service generated with RapidKit":"NestJS application generated with RapidKit"),app_version:o.app_version||"0.1.0",license:o.license||"MIT",package_manager:o.package_manager||"npm",node_version:o.node_version||"20.0.0",database_type:o.database_type||"postgresql",include_caching:o.include_caching||false,created_at:new Date().toISOString(),rapidkit_version:c()},m;r?m=["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"]:m=["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 g of m){let R=h.join(p,g);try{await promises.access(R);}catch{continue}let x=await promises.readFile(R,"utf-8"),T;try{T=d.renderString(x,u);}catch(G){throw console.error(`Failed to render template: ${g}`),G}let C=g.replace(/\.j2$/,""),P=h.join(e,C);await promises.mkdir(h.dirname(P),{recursive:true}),await promises.writeFile(P,T),(C.endsWith(".rapidkit/rapidkit")||C.endsWith(".rapidkit/cli.py")||C.endsWith(".rapidkit/activate")||C==="rapidkit")&&await promises.chmod(P,493);}if(r){let g=h.join(p,".rapidkit","context.json"),R=h.join(e,".rapidkit","context.json");try{await promises.mkdir(h.join(e,".rapidkit"),{recursive:true}),await promises.copyFile(g,R);}catch{await promises.mkdir(h.join(e,".rapidkit"),{recursive:true});let T=o.engine||"pip";await promises.writeFile(R,JSON.stringify({engine:T,created_by:"rapidkit-npm-fallback"},null,2));}}let w=r?`# Python
2
+ import {e,d as d$1,c as c$2,h as h$3,a as a$3}from'./chunk-UOGFCKQ5.js';import {a as a$2,b as b$1,c as c$1,d,i,h as h$1,e as e$1,f}from'./chunk-KAV65WZO.js';import {c,a as a$1,b as b$2}from'./chunk-EDH5S5JF.js';import {a,h as h$2,i as i$1,b as b$3,c as c$3,d as d$2,f as f$1,k,g}from'./chunk-Z5LKRG57.js';import {Command,Option}from'commander';import l from'chalk';import xe from'inquirer';import h from'path';import {fileURLToPath}from'url';import {exec,spawn}from'child_process';import Gr from'validate-npm-package-name';import*as b from'fs-extra';import b__default from'fs-extra';import _,{promises,createWriteStream}from'fs';import {execa}from'execa';import Wr from'nunjucks';import Ut from'ora';import Vr,{createHash,createVerify,createHmac}from'crypto';import Tn from'os';import {promisify}from'util';import cr from'http';import lr from'https';function Wt(e){let o=Gr(e);if(!o.validForNewPackages){let r=o.errors||[],i=o.warnings||[],n=[...r,...i];throw new e$1(e,`NPM validation failed: ${n.join(", ")}`)}if(!/^[a-z][a-z0-9_-]*$/.test(e))throw new e$1(e,"Must start with a lowercase letter and contain only lowercase letters, numbers, hyphens, and underscores");if(["test","tests","src","dist","build","lib","python","pip","poetry","node","npm","rapidkit","rapidkit"].includes(e.toLowerCase()))throw new e$1(e,`"${e}" is a reserved name. Please choose a different name.`);if(e.length<2)throw new e$1(e,"Name must be at least 2 characters long");if(e.length>214)throw new e$1(e,"Name must be less than 214 characters");return true}function Lr(){return d$2()}function qr(e,o){return e==="py"?["-3",...o]:o}function Fr(e){return typeof e=="object"&&e!==null}async function Hr(e,o,t,r=8e3){try{let i=await execa(e,o,{cwd:t,timeout:r,reject:false,stdio:"pipe"});return {ok:i.exitCode===0,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr}}catch(i){return {ok:false,exitCode:void 0,stdout:"",stderr:i instanceof Error?i.message:String(i)}}}async function Kr(e,o){let t=["-m","rapidkit",...e],r=Lr();for(let i of r){let n=await Hr(i,qr(i,t),o?.cwd,o?.timeoutMs);if(!n.ok)continue;let a=(n.stdout??"").trim();try{let s=JSON.parse(a);return Fr(s)?{ok:true,command:i,exitCode:n.exitCode,stdout:n.stdout,stderr:n.stderr,data:s}:{ok:false,command:i,exitCode:n.exitCode,stdout:n.stdout,stderr:n.stderr}}catch{return {ok:false,command:i,exitCode:n.exitCode,stdout:n.stdout,stderr:n.stderr}}}return {ok:false}}async function vo(e,o){let t=await Kr(["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}var Br=fileURLToPath(import.meta.url),Jr=h.dirname(Br);function Yr(e=32){let o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=Vr.randomBytes(e),r="";for(let i=0;i<e;i++)r+=o[t[i]%o.length];return r}async function ko(e,o){let t=o.template||"fastapi",r=t==="fastapi",i=r?"FastAPI":"NestJS",n=Ut(`Generating ${i} project...`).start();try{let a=h.resolve(Jr,".."),s=o.kit_name||`${t}.standard`,c$1;s==="fastapi.ddd"?c$1="fastapi-ddd":s.startsWith("fastapi")?c$1="fastapi-standard":c$1="nestjs-standard";let p=h.join(a,"templates","kits",c$1),d=Wr.configure(p,{autoescape:false,trimBlocks:true,lstripBlocks:true});d.addFilter("generate_secret",function(g,R=32){return Yr(R)});let u={project_name:o.project_name,author:o.author||"RapidKit User",description:o.description||(r?"FastAPI service generated with RapidKit":"NestJS application generated with RapidKit"),app_version:o.app_version||"0.1.0",license:o.license||"MIT",package_manager:o.package_manager||"npm",node_version:o.node_version||"20.0.0",database_type:o.database_type||"postgresql",include_caching:o.include_caching||false,created_at:new Date().toISOString(),rapidkit_version:c()},m;r?m=["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"]:m=["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 g of m){let R=h.join(p,g);try{await promises.access(R);}catch{continue}let x=await promises.readFile(R,"utf-8"),T;try{T=d.renderString(x,u);}catch(G){throw console.error(`Failed to render template: ${g}`),G}let C=g.replace(/\.j2$/,""),E=h.join(e,C);await promises.mkdir(h.dirname(E),{recursive:true}),await promises.writeFile(E,T),(C.endsWith(".rapidkit/rapidkit")||C.endsWith(".rapidkit/cli.py")||C.endsWith(".rapidkit/activate")||C==="rapidkit")&&await promises.chmod(E,493);}if(r){let g=h.join(p,".rapidkit","context.json"),R=h.join(e,".rapidkit","context.json");try{await promises.mkdir(h.join(e,".rapidkit"),{recursive:true}),await promises.copyFile(g,R);}catch{await promises.mkdir(h.join(e,".rapidkit"),{recursive:true});let T=o.engine||"pip";await promises.writeFile(R,JSON.stringify({engine:T,created_by:"rapidkit-npm-fallback"},null,2));}}let w=r?`# Python
3
3
  __pycache__/
4
4
  *.py[cod]
5
5
  *$py.class
@@ -3363,7 +3363,7 @@ if "%CMD%"=="start" ( bin\\${e.project_name}.exe %* & exit /b %ERRORLEVEL% )
3363
3363
  echo Available: init, dev, start, build, docs, test, lint, format
3364
3364
  exit /b 1
3365
3365
  `}async function Bt(e,o){let t={project_name:o.project_name,module_path:o.module_path||o.project_name,author:o.author||"RapidKit User",description:o.description||`Go/Gin REST API \u2014 ${o.project_name}`,go_version:o.go_version||"1.24",app_version:o.app_version||"0.1.0",port:o.port||"8080",skipGit:o.skipGit??false},r=c();try{await execa("go",["version"],{timeout:3e3});}catch{console.log(l.yellow("\n\u26A0 Go not found in PATH \u2014 project will be scaffolded, but `go mod tidy` requires Go 1.21+")),console.log(l.gray(` Install: https://go.dev/dl/
3366
- `));}let i=Ut(`Generating Go/Gin project: ${t.project_name}\u2026`).start();try{let n=(c,p)=>Ai(h.join(e,c),p),a=h.join(e,"rapidkit"),s=h.join(e,"rapidkit.cmd");await Promise.all([n("cmd/server/main.go",Oi(t)),n("go.mod",Ni(t)),n("internal/config/config.go",ji(t)),n("internal/server/server.go",$i(t)),n("internal/middleware/requestid.go",Ui()),n("internal/middleware/requestid_test.go",Vi(t)),n("internal/apierr/apierr.go",Bi()),n("internal/apierr/apierr_test.go",Ji(t)),n("internal/handlers/health.go",Di()),n("internal/handlers/health_test.go",Gi(t)),n("internal/handlers/example.go",zi(t)),n("internal/handlers/example_test.go",Qi(t)),n("internal/config/config_test.go",Xi(t)),n("internal/middleware/cors.go",Zi()),n("internal/middleware/cors_test.go",en(t)),n("internal/middleware/ratelimit.go",on(t)),n("internal/middleware/ratelimit_test.go",rn(t)),n("internal/server/server_test.go",tn(t)),n("docs/doc.go",Yi(t)),n(".air.toml",nn(t)),n("Dockerfile",Mi()),n("docker-compose.yml",Li(t)),n("Makefile",qi(t)),n(".golangci.yml",sn(t.module_path)),n(".env.example",Fi(t)),n(".gitignore",Hi()),n(".github/workflows/ci.yml",Ki(t)),n("README.md",Wi(t)),n(".rapidkit/project.json",cn(t,r)),n(".rapidkit/context.json",an()),n("rapidkit",ln(t)),n("rapidkit.cmd",dn(t))]),await promises.chmod(a,493),await promises.chmod(s,493),i.succeed(l.green(`Project created at ${e}`));try{i.start("Fetching Go dependencies\u2026"),await execa("go",["mod","tidy"],{cwd:e,timeout:12e4}),i.succeed(l.gray("\u2713 go mod tidy completed"));}catch{i.warn(l.yellow("\u26A0 go mod tidy failed \u2014 run manually: go mod tidy"));}if(!t.skipGit)try{await execa("git",["init"],{cwd:e}),await execa("git",["add","-A"],{cwd:e}),await execa("git",["commit","-m","chore: initial scaffold (rapidkit gogin.standard)"],{cwd:e}),console.log(l.gray("\u2713 git repository initialized"));}catch{console.log(l.gray("\u26A0 git init skipped (git not found or error)"));}console.log(""),console.log(l.bold("\u2705 Go/Gin project ready!")),console.log(""),console.log(l.cyan("Next steps:")),console.log(l.white(` cd ${t.project_name}`)),console.log(l.white(" make run # start dev server")),console.log(l.white(" make test # run tests")),console.log(""),console.log(l.gray("Server will listen on port "+t.port)),console.log(l.gray(" http://localhost:"+t.port+"/api/v1/health/live")),console.log(l.gray(" http://localhost:"+t.port+"/api/v1/health/ready")),console.log(""),console.log(l.yellow("\u2139 RapidKit modules are not available for Go projects (module system uses Python/pip).")),console.log("");}catch(n){throw i.fail(l.red("Failed to generate Go/Gin project")),n}}function un(e){return [...new Set(e.filter(o=>o&&o.trim().length>0))]}function gn(){let e=k().map(r=>h.join(r,a()?"poetry.exe":"poetry")),o=a()?[h.join(process.env.APPDATA||"","Python","Scripts","poetry.exe"),h.join(process.env.USERPROFILE||"","AppData","Roaming","Python","Scripts","poetry.exe")]:[],t=a()?[]:["/usr/local/bin/poetry","/usr/bin/poetry"];return un([...e,...o,...t])}function mn(e){let o=k().map(c=>({location:"Global (user-local)",path:h.join(c,a()?"rapidkit.exe":"rapidkit")})),t=[{location:"Global (pipx)",path:h.join(e,".local","bin","rapidkit")},{location:"Global (pipx)",path:h.join(e,"AppData","Roaming","Python","Scripts","rapidkit.exe")},{location:"Global (pyenv)",path:h.join(e,".pyenv","shims","rapidkit")},{location:"Global (system)",path:"/usr/local/bin/rapidkit"},{location:"Global (system)",path:"/usr/bin/rapidkit"}],r=g(h.join(process.cwd(),".venv")),i=i$1(process.cwd()),n=[{location:"Workspace (.venv)",path:r},...i.map(c=>({location:"Workspace (launcher)",path:c}))],a$1=[...o,...t,...n],s=new Set;return a$1.filter(c=>s.has(c.path)?false:(s.add(c.path),true))}function fn(e){let o=new Map([["Workspace (.venv)",0],["Global (user-local)",1],["Global (pipx)",2],["Global (pyenv)",3],["Global (system)",4]]);return [...e].sort((t,r)=>{let i=o.get(t.location)??Number.MAX_SAFE_INTEGER,n=o.get(r.location)??Number.MAX_SAFE_INTEGER;return i!==n?i-n:t.path.localeCompare(r.path)})}function Je(e,o){return a()?`cd "${e}"; ${o}`:`cd ${e} && ${o}`}function _o(e){return a()?Je(e,"Copy-Item .env.example .env"):Je(e,"cp .env.example .env")}async function Co(e){try{let o=await b__default.stat(e);return `${h.basename(e)}:${o.isDirectory()?"d":"f"}:${o.size}:${o.mtimeMs}`}catch{return `${h.basename(e)}:missing`}}async function hn(e){try{let o=new Set([".git",".venv","node_modules",".rapidkit","dist","build","coverage","__pycache__"]),t=new Set;await Jt(e)&&t.add(e);let r=async(i,n)=>{if(n<0)return;let a=await To(i);for(let s of a){if(Ao(s,o))continue;let c=h.join(i,s);if(await Jt(c)){t.add(c);continue}n>0&&await r(c,n-1);}};return await r(e,1),t.size===0&&(await Pn(e,3,o)).forEach(n=>t.add(n)),Array.from(t).sort((i,n)=>i.localeCompare(n))}catch{return []}}async function yn(e,o){let t=[h.join(e,".rapidkit-workspace"),h.join(e,".rapidkit","workspace.json"),h.join(e,".rapidkit","policies.yml"),h.join(e,".rapidkit","toolchain.lock"),h.join(e,".rapidkit","cache-config.yml")],r=[".rapidkit/project.json",".rapidkit/context.json",".rapidkit/file-hashes.json","package.json","pyproject.toml","go.mod","go.sum","requirements.txt","Dockerfile","Makefile",".env",".env.example","src","modules","tests","test",".venv","node_modules"],i=await Promise.all(t.map(Co)),n=await Promise.all(o.map(async a=>{let s=await Promise.all(r.map(c=>Co(h.join(a,c))));return `${a}::${s.join("|")}`}));return [...i,...n].join("||")}async function wn(e,o){try{if(!await b__default.pathExists(e))return null;let t=await b__default.readJSON(e);return !t||t.signature!==o||!Array.isArray(t.projects)?null:t}catch{return null}}async function vn(e,o){try{await b__default.ensureDir(h.dirname(e)),await b__default.writeJSON(e,o,{spaces:2});}catch{}}async function kn(e,o,t){let r=h.join(e,".rapidkit","reports","doctor-last-run.json");try{return await b__default.ensureDir(h.dirname(r)),await b__default.writeJSON(r,{generatedAt:new Date().toISOString(),workspacePath:e,workspaceName:o.workspaceName,projectScanCached:o.projectScanCached??false,projectScanSignature:o.projectScanSignature,cachePath:t,healthScore:o.healthScore,system:{python:o.python,poetry:o.poetry,pipx:o.pipx,go:o.go,rapidkitCore:o.rapidkitCore,versions:{core:o.coreVersion,npm:o.npmVersion}},projects:o.projects,summary:{totalProjects:o.projects.length,totalIssues:o.projects.reduce((i,n)=>i+n.issues.length,0),hasSystemErrors:[o.python,o.rapidkitCore].some(i=>i.status==="error")}},{spaces:2}),r}catch{return}}async function Io(){let[e,o,t,r,i]=await Promise.all([bn(),Rn(),_n(),Cn(),Sn()]);return {python:e,poetry:o,pipx:t,go:r,rapidkitCore:i}}async function bn(){let e=d$2();for(let o of e)try{let{stdout:t}=await execa(o,["--version"],{timeout:3e3}),r=t.match(/Python (\d+\.\d+\.\d+)/);if(r){let i=r[1],[n,a]=i.split(".").map(Number);return n<3||n===3&&a<10?{status:"warn",message:`Python ${i} (requires 3.10+)`,details:`${o} found but version is below minimum requirement`}:{status:"ok",message:`Python ${i}`,details:`Using ${o}`}}}catch{continue}return {status:"error",message:"Python not found",details:"Install Python 3.10+ and ensure it's in PATH"}}async function Rn(){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{let e=d$2().map(o=>({cmd:o,args:o==="py"?["-3","-m","poetry","--version"]:["-m","poetry","--version"]}));for(let o of e)try{let{stdout:t}=await execa(o.cmd,o.args,{timeout:3e3,shell:b$3()}),r=t.match(/Poetry .*version ([\d.]+)/)||t.match(/([\d.]+)/);return {status:"ok",message:r?.[1]?`Poetry ${r[1]}`:"Poetry detected",details:`Available via ${o.cmd} ${o.args.join(" ")}`}}catch{continue}for(let o of gn())try{if(!await b__default.pathExists(o))continue;let{stdout:t}=await execa(o,["--version"],{timeout:3e3,shell:b$3()}),r=t.match(/Poetry .*version ([\d.]+)/)||t.match(/([\d.]+)/);return {status:"ok",message:r?.[1]?`Poetry ${r[1]}`:"Poetry detected",details:`Available at ${o}`}}catch{continue}return {status:"warn",message:"Poetry not installed",details:"Optional: Install for better dependency management"}}}async function _n(){try{let{stdout:e}=await execa("pipx",["--version"],{timeout:3e3});return {status:"ok",message:`pipx ${e.trim()}`,details:"Available for global tool installation"}}catch{let e=d$2();for(let o of e)try{let t=o==="py"?["-3","-m","pipx","--version"]:["-m","pipx","--version"],{stdout:r}=await execa(o,t,{timeout:3e3,shell:b$3()});return {status:"ok",message:`pipx ${r.trim()}`,details:`Available via ${o} ${t.join(" ")}`}}catch{continue}return {status:"warn",message:"pipx not installed",details:"Optional: Install for isolated Python tools"}}}async function Cn(){try{let{stdout:e}=await execa("go",["version"],{timeout:3e3}),o=e.match(/go version go(\d+\.\d+(?:\.\d+)?)/);return o?{status:"ok",message:`Go ${o[1]}`,details:"Available for Go/Fiber and Go/Gin projects"}:{status:"ok",message:"Go (version unknown)",details:"go found in PATH"}}catch{return {status:"warn",message:"Go not installed",details:"Optional: Required only for gofiber.standard / gogin.standard projects \u2014 https://go.dev/dl/"}}}async function Sn(){let e=process.env.HOME||process.env.USERPROFILE||"",o=[],t=mn(e);for(let{location:i,path:n}of t)try{if(await b__default.pathExists(n)){let{stdout:a,exitCode:s}=await execa(n,["--version"],{timeout:3e3,reject:false});if(s===0&&(a.includes("RapidKit Version")||a.includes("RapidKit"))){let c=a.match(/v?([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);c&&o.push({location:i,path:n,version:c[1]});}}}catch{continue}if(o.length>0){let i=o.filter(a=>a.location!=="Workspace (launcher)");if(i.length>0){let a=fn(i);return {status:"ok",message:`RapidKit Core ${a[0].version}`,paths:a.map(c=>({location:c.location,path:c.path,version:c.version}))}}return {status:"ok",message:`RapidKit Core ${o[0].version}`,details:"Detected via workspace launcher"}}try{let{stdout:i,exitCode:n}=await execa("rapidkit",["--version"],{timeout:3e3,reject:false});if(n===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:n}=await execa("poetry",["run","rapidkit","--version"],{timeout:3e3,reject:false});if(n===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=d$2();for(let i of r)try{let{stdout:n,exitCode:a}=await execa(i,["-c","import rapidkit_core; print(rapidkit_core.__version__)"],{timeout:3e3,reject:false});if(a===0&&n&&!n.includes("Traceback")&&!n.includes("ModuleNotFoundError")){let s=n.trim();if(s)return {status:"ok",message:`RapidKit Core ${s}`,details:`Available in ${i} environment`}}}catch{continue}return {status:"error",message:"RapidKit Core not installed",details:"Install with: pipx install rapidkit-core"}}async function Rt(e,o){let t=h.join(e,"Dockerfile");o.hasDocker=await b__default.pathExists(t);let r=h.join(e,"tests"),i=h.join(e,"test"),n=await b__default.pathExists(r)||await b__default.pathExists(i),a=false;if(o.framework==="Go/Fiber"||o.framework==="Go/Gin")try{let s=[{dir:e,depth:0}],c=4,p=new Set([".git",".venv","node_modules","dist","build","vendor"]);for(;s.length>0&&!a;){let d=s.shift();if(!d)break;let u=[];try{u=await b__default.readdir(d.dir);}catch{continue}for(let m of u){let w=h.join(d.dir,m),f;try{f=await b__default.stat(w);}catch{continue}if(f.isFile()&&m.endsWith("_test.go")){a=true;break}f.isDirectory()&&d.depth<c&&!p.has(m)&&!m.startsWith(".")&&s.push({dir:w,depth:d.depth+1});}}}catch{}if(o.hasTests=n||a,o.framework==="NestJS"){let s=h.join(e,".eslintrc.js"),c=h.join(e,".eslintrc.json");o.hasCodeQuality=await b__default.pathExists(s)||await b__default.pathExists(c);}else if(o.framework==="Go/Fiber"||o.framework==="Go/Gin"){let s=h.join(e,".golangci.yml"),c=h.join(e,".golangci.yaml"),p=h.join(e,"Makefile"),d=await b__default.pathExists(p)&&(await b__default.readFile(p,"utf8")).includes("golangci-lint");o.hasCodeQuality=await b__default.pathExists(s)||await b__default.pathExists(c)||d;}else if(o.framework==="FastAPI"){let s=h.join(e,"ruff.toml"),c=h.join(e,"pyproject.toml");if(await b__default.pathExists(c))try{let p=await b__default.readFile(c,"utf8");o.hasCodeQuality=p.includes("[tool.ruff]")||await b__default.pathExists(s);}catch{o.hasCodeQuality=await b__default.pathExists(s);}}try{if(o.framework==="NestJS"){let{stdout:s}=await execa("npm",["audit","--json"],{cwd:e,reject:false});if(s)try{let p=JSON.parse(s).metadata?.vulnerabilities;p&&(o.vulnerabilities=(p.high||0)+(p.critical||0)+(p.moderate||0));}catch{}}else if(o.framework==="FastAPI"){let s=h.join(e,".venv"),c=f$1(s);if(await b__default.pathExists(c))try{let{stdout:p}=await execa(c,["-m","pip","list","--format=json"],{timeout:5e3,reject:false});if(p){JSON.parse(p);o.vulnerabilities=0;}}catch{}}}catch{}}async function xn(e){let t={name:h.basename(e),path:e,venvActive:false,depsInstalled:false,coreInstalled:false,issues:[],fixCommands:[]},r=h.join(e,".rapidkit");if(!await b__default.pathExists(r))return t.issues.push("Not a valid RapidKit project (missing .rapidkit directory)"),t;try{let u=h.join(e,"registry.json");if(await b__default.pathExists(u)){let m=await b__default.readJson(u);m.installed_modules&&(t.stats={modules:m.installed_modules.length});}}catch{}let i=null;try{let u=h.join(r,"project.json");if(await b__default.pathExists(u)){i=await b__default.readJson(u);let m=i?.kit_name||i?.kit;m&&(t.kit=m);}}catch{}try{let u=h.join(e,".git");if(await b__default.pathExists(u)){let{stdout:m}=await execa("git",["log","-1","--format=%cr"],{cwd:e,reject:false});m&&(t.lastModified=m.trim());}else {let m=await b__default.stat(e),f=Date.now()-m.mtime.getTime(),g=Math.floor(f/(1e3*60*60*24));t.lastModified=g===0?"today":`${g} day${g>1?"s":""} ago`;}}catch{}let n=h.join(e,"package.json"),a=h.join(e,"pyproject.toml"),s=h.join(e,"go.mod");if(await b__default.pathExists(s)||i?.runtime==="go"||typeof i?.kit_name=="string"&&(i.kit_name.startsWith("gofiber")||i.kit_name.startsWith("gogin"))){let u=i?.kit_name??"";t.framework=u.startsWith("gogin")?"Go/Gin":"Go/Fiber",t.isGoProject=true,t.venvActive=true,t.coreInstalled=false;try{await execa("go",["version"],{timeout:3e3});}catch{t.issues.push("Go toolchain not found \u2014 install from https://go.dev/dl/"),t.fixCommands?.push("https://go.dev/dl/");}let m=h.join(e,"go.sum");return await b__default.pathExists(m)?t.depsInstalled=true:(t.depsInstalled=false,t.issues.push("Go dependencies not downloaded (go.sum missing)"),t.fixCommands?.push(Je(e,"go mod tidy"))),await Rt(e,t),t}let p=await b__default.pathExists(n),d=await b__default.pathExists(a);if(p){t.framework="NestJS",t.venvActive=true;let u=h.join(e,"node_modules");if(await b__default.pathExists(u))try{let g=(await b__default.readdir(u)).filter(R=>!R.startsWith(".")&&!R.startsWith("_"));t.depsInstalled=g.length>0;}catch{t.depsInstalled=false;}t.depsInstalled||(t.issues.push("Dependencies not installed (node_modules empty or missing)"),t.fixCommands?.push(Je(e,"rapidkit init"))),t.coreInstalled=false;let m=h.join(e,".env");if(t.hasEnvFile=await b__default.pathExists(m),!t.hasEnvFile){let f=h.join(e,".env.example");await b__default.pathExists(f)&&(t.issues.push("Environment file missing (found .env.example)"),t.fixCommands?.push(_o(e)));}let w=h.join(e,"src");if(t.modulesHealthy=true,t.missingModules=[],await b__default.pathExists(w))try{let f=await b__default.readdir(w);t.modulesHealthy=f.length>0;}catch{t.modulesHealthy=false;}return await Rt(e,t),t}if(d){t.framework="FastAPI";let u=h.join(e,".venv");if(await b__default.pathExists(u)){t.venvActive=true;let g=f$1(u);if(await b__default.pathExists(g)){try{let{stdout:R}=await execa(g,["-c","import rapidkit_core; print(rapidkit_core.__version__)"],{timeout:2e3});t.coreInstalled=true,t.coreVersion=R.trim();}catch{t.coreInstalled=false;}try{await execa(g,["-c","import fastapi"],{timeout:2e3}),t.depsInstalled=true;}catch{try{let R=h.join(u,"lib");if(await b__default.pathExists(R)){let T=(await b__default.readdir(R)).find(C=>C.startsWith("python"));if(T){let C=h.join(R,T,"site-packages");if(await b__default.pathExists(C)){let G=(await b__default.readdir(C)).filter(N=>!N.startsWith("_")&&!N.includes("dist-info")&&!["pip","setuptools","wheel","pkg_resources"].includes(N));t.depsInstalled=G.length>0;}}}t.depsInstalled||(t.issues.push("Dependencies not installed"),t.fixCommands?.push(Je(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(Je(e,"rapidkit init"));let m=h.join(e,".env");if(t.hasEnvFile=await b__default.pathExists(m),!t.hasEnvFile){let g=h.join(e,".env.example");await b__default.pathExists(g)&&(t.issues.push("Environment file missing (found .env.example)"),t.fixCommands?.push(_o(e)));}let w=h.join(e,"src"),f=h.join(e,"modules");if(t.modulesHealthy=true,t.missingModules=[],await b__default.pathExists(w)){let g=h.join(w,"__init__.py");await b__default.pathExists(g)||(t.modulesHealthy=false,t.missingModules.push("src/__init__.py"));}if(await b__default.pathExists(f))try{let g=await To(f);for(let R of g){let x=h.join(f,R,"__init__.py");await b__default.pathExists(x)||(t.modulesHealthy=false,t.missingModules.push(`modules/${R}/__init__.py`));}}catch{}return !t.modulesHealthy&&t.missingModules.length>0&&t.issues.push(`Missing module init files: ${t.missingModules.join(", ")}`),await Rt(e,t),t}return t.issues.push("Unknown project type (no package.json or pyproject.toml)"),await Rt(e,t),t}async function To(e){try{return (await b__default.readdir(e,{withFileTypes:true})).filter(t=>t.isDirectory()).map(t=>t.name)}catch{try{let o=await b__default.readdir(e),t=[];for(let r of o)try{(await b__default.stat(h.join(e,r))).isDirectory()&&t.push(r);}catch{continue}return t}catch{return []}}}async function Jt(e){let o=h.join(e,".rapidkit");if(!await b__default.pathExists(o))return false;let t=["project.json","context.json","file-hashes.json"];for(let r of t)if(await b__default.pathExists(h.join(o,r)))return true;return false}function Ao(e,o){if(o.has(e))return true;let t=e.toLowerCase();return !!(t==="dist"||t.startsWith("dist-")||t.startsWith("dist_")||t==="build"||t.startsWith("build-")||t.startsWith("build_"))}async function Pn(e,o,t){let r=new Set,i=[{dir:e,depth:0}];for(;i.length>0;){let n=i.shift();if(!n)break;try{let a=await b__default.readdir(n.dir);for(let s of a){if(Ao(s,t))continue;let c=h.join(n.dir,s),p;try{p=await b__default.stat(c);}catch{continue}if(p.isDirectory()){if(await Jt(c)){r.add(c);continue}n.depth<o&&i.push({dir:c,depth:n.depth+1});}}}catch{continue}}return Array.from(r)}async function So(e){let o=e,t=h.parse(o).root;for(;o!==t;){let r=[h.join(o,".rapidkit-workspace"),h.join(o,".rapidkit","workspace-marker.json"),h.join(o,".rapidkit","config.json")];for(let i of r)if(await b__default.pathExists(i))return o;o=h.dirname(o);}return null}function En(e,o){let t=0,r=0,i=0;return e.forEach(a=>{a.status==="ok"?t++:a.status==="warn"?r++:a.status==="error"&&i++;}),o.forEach(a=>{(a.isGoProject?a.issues.length===0&&a.depsInstalled:a.issues.length===0&&a.venvActive&&a.depsInstalled)?t++:a.issues.length>0&&r++;}),{total:t+r+i,passed:t,warnings:r,errors:i}}async function xo(e,o=true){let t=h.basename(e);try{let d=h.join(e,".rapidkit-workspace");await b__default.pathExists(d)&&(t=(await b__default.readJSON(d)).name||t);}catch{try{let d=h.join(e,".rapidkit","config.json");t=(await b__default.readJSON(d)).workspace_name||t;}catch{}}let[r,i]=await Promise.all([Io(),hn(e)]),n={workspacePath:e,workspaceName:t,python:r.python,poetry:r.poetry,pipx:r.pipx,go:r.go,rapidkitCore:r.rapidkitCore,projects:[]};a$1.debug(`Workspace scan found ${i.length} project(s)`);let a=await yn(e,i),s=h.join(e,".rapidkit","reports","doctor-workspace-cache.json"),c=o?await wn(s,a):null;if(c)n.projects=c.projects,n.projectScanCached=true,a$1.debug(`Workspace project health cache hit: ${s}`);else try{let d=await Promise.all(i.map(u=>xn(u)));n.projects=d,n.projectScanCached=false,await vn(s,{signature:a,generatedAt:new Date().toISOString(),projects:d}),a$1.debug(`Workspace project health cache refreshed: ${s}`);}catch(d){a$1.debug(`Failed to scan workspace projects: ${d}`);}n.projectScanSignature=a,n.projectScanCachePath=s;let p=[n.python,n.poetry,n.pipx,n.go,n.rapidkitCore];if(n.healthScore=En(p,n.projects),n.rapidkitCore.status==="ok"){let d=n.rapidkitCore.message.match(/([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);d&&(n.coreVersion=d[1]);}return n.evidencePath=await kn(e,n,c?s:null),n}function Ce(e,o){let t=e.status==="ok"?"\u2705":e.status==="warn"?"\u26A0\uFE0F":"\u274C",r=e.status==="ok"?l.green:e.status==="warn"?l.yellow:l.red;console.log(`${t} ${l.bold(o)}: ${r(e.message)}`),e.paths&&e.paths.length>0?e.paths.forEach(i=>{let n=i.version?l.cyan(` -> ${i.version}`):"";console.log(` ${l.cyan("\u2022")} ${l.gray(i.location)}: ${l.dim(i.path)}${n}`);}):e.details&&console.log(` ${l.gray(e.details)}`);}function In(e){let o=e.issues.length>0,t=o?"\u26A0\uFE0F":"\u2705",r=o?l.yellow:l.green;if(console.log(`
3366
+ `));}let i=Ut(`Generating Go/Gin project: ${t.project_name}\u2026`).start();try{let n=(c,p)=>Ai(h.join(e,c),p),a=h.join(e,"rapidkit"),s=h.join(e,"rapidkit.cmd");await Promise.all([n("cmd/server/main.go",Oi(t)),n("go.mod",Ni(t)),n("internal/config/config.go",ji(t)),n("internal/server/server.go",$i(t)),n("internal/middleware/requestid.go",Ui()),n("internal/middleware/requestid_test.go",Vi(t)),n("internal/apierr/apierr.go",Bi()),n("internal/apierr/apierr_test.go",Ji(t)),n("internal/handlers/health.go",Di()),n("internal/handlers/health_test.go",Gi(t)),n("internal/handlers/example.go",zi(t)),n("internal/handlers/example_test.go",Qi(t)),n("internal/config/config_test.go",Xi(t)),n("internal/middleware/cors.go",Zi()),n("internal/middleware/cors_test.go",en(t)),n("internal/middleware/ratelimit.go",on(t)),n("internal/middleware/ratelimit_test.go",rn(t)),n("internal/server/server_test.go",tn(t)),n("docs/doc.go",Yi(t)),n(".air.toml",nn(t)),n("Dockerfile",Mi()),n("docker-compose.yml",Li(t)),n("Makefile",qi(t)),n(".golangci.yml",sn(t.module_path)),n(".env.example",Fi(t)),n(".gitignore",Hi()),n(".github/workflows/ci.yml",Ki(t)),n("README.md",Wi(t)),n(".rapidkit/project.json",cn(t,r)),n(".rapidkit/context.json",an()),n("rapidkit",ln(t)),n("rapidkit.cmd",dn(t))]),await promises.chmod(a,493),await promises.chmod(s,493),i.succeed(l.green(`Project created at ${e}`));try{i.start("Fetching Go dependencies\u2026"),await execa("go",["mod","tidy"],{cwd:e,timeout:12e4}),i.succeed(l.gray("\u2713 go mod tidy completed"));}catch{i.warn(l.yellow("\u26A0 go mod tidy failed \u2014 run manually: go mod tidy"));}if(!t.skipGit)try{await execa("git",["init"],{cwd:e}),await execa("git",["add","-A"],{cwd:e}),await execa("git",["commit","-m","chore: initial scaffold (rapidkit gogin.standard)"],{cwd:e}),console.log(l.gray("\u2713 git repository initialized"));}catch{console.log(l.gray("\u26A0 git init skipped (git not found or error)"));}console.log(""),console.log(l.bold("\u2705 Go/Gin project ready!")),console.log(""),console.log(l.cyan("Next steps:")),console.log(l.white(` cd ${t.project_name}`)),console.log(l.white(" make run # start dev server")),console.log(l.white(" make test # run tests")),console.log(""),console.log(l.gray("Server will listen on port "+t.port)),console.log(l.gray(" http://localhost:"+t.port+"/api/v1/health/live")),console.log(l.gray(" http://localhost:"+t.port+"/api/v1/health/ready")),console.log(""),console.log(l.yellow("\u2139 RapidKit modules are not available for Go projects (module system uses Python/pip).")),console.log("");}catch(n){throw i.fail(l.red("Failed to generate Go/Gin project")),n}}function un(e){return [...new Set(e.filter(o=>o&&o.trim().length>0))]}function gn(){let e=k().map(r=>h.join(r,a()?"poetry.exe":"poetry")),o=a()?[h.join(process.env.APPDATA||"","Python","Scripts","poetry.exe"),h.join(process.env.USERPROFILE||"","AppData","Roaming","Python","Scripts","poetry.exe")]:[],t=a()?[]:["/usr/local/bin/poetry","/usr/bin/poetry"];return un([...e,...o,...t])}function mn(e){let o=k().map(c=>({location:"Global (user-local)",path:h.join(c,a()?"rapidkit.exe":"rapidkit")})),t=[{location:"Global (pipx)",path:h.join(e,".local","bin","rapidkit")},{location:"Global (pipx)",path:h.join(e,"AppData","Roaming","Python","Scripts","rapidkit.exe")},{location:"Global (pyenv)",path:h.join(e,".pyenv","shims","rapidkit")},{location:"Global (system)",path:"/usr/local/bin/rapidkit"},{location:"Global (system)",path:"/usr/bin/rapidkit"}],r=g(h.join(process.cwd(),".venv")),i=i$1(process.cwd()),n=[{location:"Workspace (.venv)",path:r},...i.map(c=>({location:"Workspace (launcher)",path:c}))],a$1=[...o,...t,...n],s=new Set;return a$1.filter(c=>s.has(c.path)?false:(s.add(c.path),true))}function fn(e){let o=new Map([["Workspace (.venv)",0],["Global (user-local)",1],["Global (pipx)",2],["Global (pyenv)",3],["Global (system)",4]]);return [...e].sort((t,r)=>{let i=o.get(t.location)??Number.MAX_SAFE_INTEGER,n=o.get(r.location)??Number.MAX_SAFE_INTEGER;return i!==n?i-n:t.path.localeCompare(r.path)})}function Ye(e,o){return a()?`cd "${e}"; ${o}`:`cd ${e} && ${o}`}function _o(e){return a()?Ye(e,"Copy-Item .env.example .env"):Ye(e,"cp .env.example .env")}async function Co(e){try{let o=await b__default.stat(e);return `${h.basename(e)}:${o.isDirectory()?"d":"f"}:${o.size}:${o.mtimeMs}`}catch{return `${h.basename(e)}:missing`}}async function hn(e){try{let o=new Set([".git",".venv","node_modules",".rapidkit","dist","build","coverage","__pycache__"]),t=new Set;await Jt(e)&&t.add(e);let r=async(i,n)=>{if(n<0)return;let a=await To(i);for(let s of a){if(Ao(s,o))continue;let c=h.join(i,s);if(await Jt(c)){t.add(c);continue}n>0&&await r(c,n-1);}};return await r(e,1),t.size===0&&(await Pn(e,3,o)).forEach(n=>t.add(n)),Array.from(t).sort((i,n)=>i.localeCompare(n))}catch{return []}}async function yn(e,o){let t=[h.join(e,".rapidkit-workspace"),h.join(e,".rapidkit","workspace.json"),h.join(e,".rapidkit","policies.yml"),h.join(e,".rapidkit","toolchain.lock"),h.join(e,".rapidkit","cache-config.yml")],r=[".rapidkit/project.json",".rapidkit/context.json",".rapidkit/file-hashes.json","package.json","pyproject.toml","go.mod","go.sum","requirements.txt","Dockerfile","Makefile",".env",".env.example","src","modules","tests","test",".venv","node_modules"],i=await Promise.all(t.map(Co)),n=await Promise.all(o.map(async a=>{let s=await Promise.all(r.map(c=>Co(h.join(a,c))));return `${a}::${s.join("|")}`}));return [...i,...n].join("||")}async function wn(e,o){try{if(!await b__default.pathExists(e))return null;let t=await b__default.readJSON(e);return !t||t.signature!==o||!Array.isArray(t.projects)?null:t}catch{return null}}async function vn(e,o){try{await b__default.ensureDir(h.dirname(e)),await b__default.writeJSON(e,o,{spaces:2});}catch{}}async function kn(e,o,t){let r=h.join(e,".rapidkit","reports","doctor-last-run.json");try{return await b__default.ensureDir(h.dirname(r)),await b__default.writeJSON(r,{generatedAt:new Date().toISOString(),workspacePath:e,workspaceName:o.workspaceName,projectScanCached:o.projectScanCached??false,projectScanSignature:o.projectScanSignature,cachePath:t,healthScore:o.healthScore,system:{python:o.python,poetry:o.poetry,pipx:o.pipx,go:o.go,rapidkitCore:o.rapidkitCore,versions:{core:o.coreVersion,npm:o.npmVersion}},projects:o.projects,summary:{totalProjects:o.projects.length,totalIssues:o.projects.reduce((i,n)=>i+n.issues.length,0),hasSystemErrors:[o.python,o.rapidkitCore].some(i=>i.status==="error")}},{spaces:2}),r}catch{return}}async function Io(){let[e,o,t,r,i]=await Promise.all([bn(),Rn(),_n(),Cn(),Sn()]);return {python:e,poetry:o,pipx:t,go:r,rapidkitCore:i}}async function bn(){let e=d$2();for(let o of e)try{let{stdout:t}=await execa(o,["--version"],{timeout:3e3}),r=t.match(/Python (\d+\.\d+\.\d+)/);if(r){let i=r[1],[n,a]=i.split(".").map(Number);return n<3||n===3&&a<10?{status:"warn",message:`Python ${i} (requires 3.10+)`,details:`${o} found but version is below minimum requirement`}:{status:"ok",message:`Python ${i}`,details:`Using ${o}`}}}catch{continue}return {status:"error",message:"Python not found",details:"Install Python 3.10+ and ensure it's in PATH"}}async function Rn(){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{let e=d$2().map(o=>({cmd:o,args:o==="py"?["-3","-m","poetry","--version"]:["-m","poetry","--version"]}));for(let o of e)try{let{stdout:t}=await execa(o.cmd,o.args,{timeout:3e3,shell:b$3()}),r=t.match(/Poetry .*version ([\d.]+)/)||t.match(/([\d.]+)/);return {status:"ok",message:r?.[1]?`Poetry ${r[1]}`:"Poetry detected",details:`Available via ${o.cmd} ${o.args.join(" ")}`}}catch{continue}for(let o of gn())try{if(!await b__default.pathExists(o))continue;let{stdout:t}=await execa(o,["--version"],{timeout:3e3,shell:b$3()}),r=t.match(/Poetry .*version ([\d.]+)/)||t.match(/([\d.]+)/);return {status:"ok",message:r?.[1]?`Poetry ${r[1]}`:"Poetry detected",details:`Available at ${o}`}}catch{continue}return {status:"warn",message:"Poetry not installed",details:"Optional: Install for better dependency management"}}}async function _n(){try{let{stdout:e}=await execa("pipx",["--version"],{timeout:3e3});return {status:"ok",message:`pipx ${e.trim()}`,details:"Available for global tool installation"}}catch{let e=d$2();for(let o of e)try{let t=o==="py"?["-3","-m","pipx","--version"]:["-m","pipx","--version"],{stdout:r}=await execa(o,t,{timeout:3e3,shell:b$3()});return {status:"ok",message:`pipx ${r.trim()}`,details:`Available via ${o} ${t.join(" ")}`}}catch{continue}return {status:"warn",message:"pipx not installed",details:"Optional: Install for isolated Python tools"}}}async function Cn(){try{let{stdout:e}=await execa("go",["version"],{timeout:3e3}),o=e.match(/go version go(\d+\.\d+(?:\.\d+)?)/);return o?{status:"ok",message:`Go ${o[1]}`,details:"Available for Go/Fiber and Go/Gin projects"}:{status:"ok",message:"Go (version unknown)",details:"go found in PATH"}}catch{return {status:"warn",message:"Go not installed",details:"Optional: Required only for gofiber.standard / gogin.standard projects \u2014 https://go.dev/dl/"}}}async function Sn(){let e=process.env.HOME||process.env.USERPROFILE||"",o=[],t=mn(e);for(let{location:i,path:n}of t)try{if(await b__default.pathExists(n)){let{stdout:a,exitCode:s}=await execa(n,["--version"],{timeout:3e3,reject:false});if(s===0&&(a.includes("RapidKit Version")||a.includes("RapidKit"))){let c=a.match(/v?([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);c&&o.push({location:i,path:n,version:c[1]});}}}catch{continue}if(o.length>0){let i=o.filter(a=>a.location!=="Workspace (launcher)");if(i.length>0){let a=fn(i);return {status:"ok",message:`RapidKit Core ${a[0].version}`,paths:a.map(c=>({location:c.location,path:c.path,version:c.version}))}}return {status:"ok",message:`RapidKit Core ${o[0].version}`,details:"Detected via workspace launcher"}}try{let{stdout:i,exitCode:n}=await execa("rapidkit",["--version"],{timeout:3e3,reject:false});if(n===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:n}=await execa("poetry",["run","rapidkit","--version"],{timeout:3e3,reject:false});if(n===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=d$2();for(let i of r)try{let{stdout:n,exitCode:a}=await execa(i,["-c","import rapidkit_core; print(rapidkit_core.__version__)"],{timeout:3e3,reject:false});if(a===0&&n&&!n.includes("Traceback")&&!n.includes("ModuleNotFoundError")){let s=n.trim();if(s)return {status:"ok",message:`RapidKit Core ${s}`,details:`Available in ${i} environment`}}}catch{continue}return {status:"error",message:"RapidKit Core not installed",details:"Install with: pipx install rapidkit-core"}}async function Rt(e,o){let t=h.join(e,"Dockerfile");o.hasDocker=await b__default.pathExists(t);let r=h.join(e,"tests"),i=h.join(e,"test"),n=await b__default.pathExists(r)||await b__default.pathExists(i),a=false;if(o.framework==="Go/Fiber"||o.framework==="Go/Gin")try{let s=[{dir:e,depth:0}],c=4,p=new Set([".git",".venv","node_modules","dist","build","vendor"]);for(;s.length>0&&!a;){let d=s.shift();if(!d)break;let u=[];try{u=await b__default.readdir(d.dir);}catch{continue}for(let m of u){let w=h.join(d.dir,m),f;try{f=await b__default.stat(w);}catch{continue}if(f.isFile()&&m.endsWith("_test.go")){a=true;break}f.isDirectory()&&d.depth<c&&!p.has(m)&&!m.startsWith(".")&&s.push({dir:w,depth:d.depth+1});}}}catch{}if(o.hasTests=n||a,o.framework==="NestJS"){let s=h.join(e,".eslintrc.js"),c=h.join(e,".eslintrc.json");o.hasCodeQuality=await b__default.pathExists(s)||await b__default.pathExists(c);}else if(o.framework==="Go/Fiber"||o.framework==="Go/Gin"){let s=h.join(e,".golangci.yml"),c=h.join(e,".golangci.yaml"),p=h.join(e,"Makefile"),d=await b__default.pathExists(p)&&(await b__default.readFile(p,"utf8")).includes("golangci-lint");o.hasCodeQuality=await b__default.pathExists(s)||await b__default.pathExists(c)||d;}else if(o.framework==="FastAPI"){let s=h.join(e,"ruff.toml"),c=h.join(e,"pyproject.toml");if(await b__default.pathExists(c))try{let p=await b__default.readFile(c,"utf8");o.hasCodeQuality=p.includes("[tool.ruff]")||await b__default.pathExists(s);}catch{o.hasCodeQuality=await b__default.pathExists(s);}}try{if(o.framework==="NestJS"){let{stdout:s}=await execa("npm",["audit","--json"],{cwd:e,reject:false});if(s)try{let p=JSON.parse(s).metadata?.vulnerabilities;p&&(o.vulnerabilities=(p.high||0)+(p.critical||0)+(p.moderate||0));}catch{}}else if(o.framework==="FastAPI"){let s=h.join(e,".venv"),c=f$1(s);if(await b__default.pathExists(c))try{let{stdout:p}=await execa(c,["-m","pip","list","--format=json"],{timeout:5e3,reject:false});if(p){JSON.parse(p);o.vulnerabilities=0;}}catch{}}}catch{}}async function xn(e){let t={name:h.basename(e),path:e,venvActive:false,depsInstalled:false,coreInstalled:false,issues:[],fixCommands:[]},r=h.join(e,".rapidkit");if(!await b__default.pathExists(r))return t.issues.push("Not a valid RapidKit project (missing .rapidkit directory)"),t;try{let u=h.join(e,"registry.json");if(await b__default.pathExists(u)){let m=await b__default.readJson(u);m.installed_modules&&(t.stats={modules:m.installed_modules.length});}}catch{}let i=null;try{let u=h.join(r,"project.json");if(await b__default.pathExists(u)){i=await b__default.readJson(u);let m=i?.kit_name||i?.kit;m&&(t.kit=m);}}catch{}try{let u=h.join(e,".git");if(await b__default.pathExists(u)){let{stdout:m}=await execa("git",["log","-1","--format=%cr"],{cwd:e,reject:false});m&&(t.lastModified=m.trim());}else {let m=await b__default.stat(e),f=Date.now()-m.mtime.getTime(),g=Math.floor(f/(1e3*60*60*24));t.lastModified=g===0?"today":`${g} day${g>1?"s":""} ago`;}}catch{}let n=h.join(e,"package.json"),a=h.join(e,"pyproject.toml"),s=h.join(e,"go.mod");if(await b__default.pathExists(s)||i?.runtime==="go"||typeof i?.kit_name=="string"&&(i.kit_name.startsWith("gofiber")||i.kit_name.startsWith("gogin"))){let u=i?.kit_name??"";t.framework=u.startsWith("gogin")?"Go/Gin":"Go/Fiber",t.isGoProject=true,t.venvActive=true,t.coreInstalled=false;try{await execa("go",["version"],{timeout:3e3});}catch{t.issues.push("Go toolchain not found \u2014 install from https://go.dev/dl/"),t.fixCommands?.push("https://go.dev/dl/");}let m=h.join(e,"go.sum");return await b__default.pathExists(m)?t.depsInstalled=true:(t.depsInstalled=false,t.issues.push("Go dependencies not downloaded (go.sum missing)"),t.fixCommands?.push(Ye(e,"go mod tidy"))),await Rt(e,t),t}let p=await b__default.pathExists(n),d=await b__default.pathExists(a);if(p){t.framework="NestJS",t.venvActive=true;let u=h.join(e,"node_modules");if(await b__default.pathExists(u))try{let g=(await b__default.readdir(u)).filter(R=>!R.startsWith(".")&&!R.startsWith("_"));t.depsInstalled=g.length>0;}catch{t.depsInstalled=false;}t.depsInstalled||(t.issues.push("Dependencies not installed (node_modules empty or missing)"),t.fixCommands?.push(Ye(e,"rapidkit init"))),t.coreInstalled=false;let m=h.join(e,".env");if(t.hasEnvFile=await b__default.pathExists(m),!t.hasEnvFile){let f=h.join(e,".env.example");await b__default.pathExists(f)&&(t.issues.push("Environment file missing (found .env.example)"),t.fixCommands?.push(_o(e)));}let w=h.join(e,"src");if(t.modulesHealthy=true,t.missingModules=[],await b__default.pathExists(w))try{let f=await b__default.readdir(w);t.modulesHealthy=f.length>0;}catch{t.modulesHealthy=false;}return await Rt(e,t),t}if(d){t.framework="FastAPI";let u=h.join(e,".venv");if(await b__default.pathExists(u)){t.venvActive=true;let g=f$1(u);if(await b__default.pathExists(g)){try{let{stdout:R}=await execa(g,["-c","import rapidkit_core; print(rapidkit_core.__version__)"],{timeout:2e3});t.coreInstalled=true,t.coreVersion=R.trim();}catch{t.coreInstalled=false;}try{await execa(g,["-c","import fastapi"],{timeout:2e3}),t.depsInstalled=true;}catch{try{let R=h.join(u,"lib");if(await b__default.pathExists(R)){let T=(await b__default.readdir(R)).find(C=>C.startsWith("python"));if(T){let C=h.join(R,T,"site-packages");if(await b__default.pathExists(C)){let G=(await b__default.readdir(C)).filter(N=>!N.startsWith("_")&&!N.includes("dist-info")&&!["pip","setuptools","wheel","pkg_resources"].includes(N));t.depsInstalled=G.length>0;}}}t.depsInstalled||(t.issues.push("Dependencies not installed"),t.fixCommands?.push(Ye(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(Ye(e,"rapidkit init"));let m=h.join(e,".env");if(t.hasEnvFile=await b__default.pathExists(m),!t.hasEnvFile){let g=h.join(e,".env.example");await b__default.pathExists(g)&&(t.issues.push("Environment file missing (found .env.example)"),t.fixCommands?.push(_o(e)));}let w=h.join(e,"src"),f=h.join(e,"modules");if(t.modulesHealthy=true,t.missingModules=[],await b__default.pathExists(w)){let g=h.join(w,"__init__.py");await b__default.pathExists(g)||(t.modulesHealthy=false,t.missingModules.push("src/__init__.py"));}if(await b__default.pathExists(f))try{let g=await To(f);for(let R of g){let x=h.join(f,R,"__init__.py");await b__default.pathExists(x)||(t.modulesHealthy=false,t.missingModules.push(`modules/${R}/__init__.py`));}}catch{}return !t.modulesHealthy&&t.missingModules.length>0&&t.issues.push(`Missing module init files: ${t.missingModules.join(", ")}`),await Rt(e,t),t}return t.issues.push("Unknown project type (no package.json or pyproject.toml)"),await Rt(e,t),t}async function To(e){try{return (await b__default.readdir(e,{withFileTypes:true})).filter(t=>t.isDirectory()).map(t=>t.name)}catch{try{let o=await b__default.readdir(e),t=[];for(let r of o)try{(await b__default.stat(h.join(e,r))).isDirectory()&&t.push(r);}catch{continue}return t}catch{return []}}}async function Jt(e){let o=h.join(e,".rapidkit");if(!await b__default.pathExists(o))return false;let t=["project.json","context.json","file-hashes.json"];for(let r of t)if(await b__default.pathExists(h.join(o,r)))return true;return false}function Ao(e,o){if(o.has(e))return true;let t=e.toLowerCase();return !!(t==="dist"||t.startsWith("dist-")||t.startsWith("dist_")||t==="build"||t.startsWith("build-")||t.startsWith("build_"))}async function Pn(e,o,t){let r=new Set,i=[{dir:e,depth:0}];for(;i.length>0;){let n=i.shift();if(!n)break;try{let a=await b__default.readdir(n.dir);for(let s of a){if(Ao(s,t))continue;let c=h.join(n.dir,s),p;try{p=await b__default.stat(c);}catch{continue}if(p.isDirectory()){if(await Jt(c)){r.add(c);continue}n.depth<o&&i.push({dir:c,depth:n.depth+1});}}}catch{continue}}return Array.from(r)}async function So(e){let o=e,t=h.parse(o).root;for(;o!==t;){let r=[h.join(o,".rapidkit-workspace"),h.join(o,".rapidkit","workspace-marker.json"),h.join(o,".rapidkit","config.json")];for(let i of r)if(await b__default.pathExists(i))return o;o=h.dirname(o);}return null}function En(e,o){let t=0,r=0,i=0;return e.forEach(a=>{a.status==="ok"?t++:a.status==="warn"?r++:a.status==="error"&&i++;}),o.forEach(a=>{(a.isGoProject?a.issues.length===0&&a.depsInstalled:a.issues.length===0&&a.venvActive&&a.depsInstalled)?t++:a.issues.length>0&&r++;}),{total:t+r+i,passed:t,warnings:r,errors:i}}async function xo(e,o=true){let t=h.basename(e);try{let d=h.join(e,".rapidkit-workspace");await b__default.pathExists(d)&&(t=(await b__default.readJSON(d)).name||t);}catch{try{let d=h.join(e,".rapidkit","config.json");t=(await b__default.readJSON(d)).workspace_name||t;}catch{}}let[r,i]=await Promise.all([Io(),hn(e)]),n={workspacePath:e,workspaceName:t,python:r.python,poetry:r.poetry,pipx:r.pipx,go:r.go,rapidkitCore:r.rapidkitCore,projects:[]};a$1.debug(`Workspace scan found ${i.length} project(s)`);let a=await yn(e,i),s=h.join(e,".rapidkit","reports","doctor-workspace-cache.json"),c=o?await wn(s,a):null;if(c)n.projects=c.projects,n.projectScanCached=true,a$1.debug(`Workspace project health cache hit: ${s}`);else try{let d=await Promise.all(i.map(u=>xn(u)));n.projects=d,n.projectScanCached=false,await vn(s,{signature:a,generatedAt:new Date().toISOString(),projects:d}),a$1.debug(`Workspace project health cache refreshed: ${s}`);}catch(d){a$1.debug(`Failed to scan workspace projects: ${d}`);}n.projectScanSignature=a,n.projectScanCachePath=s;let p=[n.python,n.poetry,n.pipx,n.go,n.rapidkitCore];if(n.healthScore=En(p,n.projects),n.rapidkitCore.status==="ok"){let d=n.rapidkitCore.message.match(/([\d.]+(?:rc\d+)?(?:a\d+)?(?:b\d+)?)/);d&&(n.coreVersion=d[1]);}return n.evidencePath=await kn(e,n,c?s:null),n}function Ce(e,o){let t=e.status==="ok"?"\u2705":e.status==="warn"?"\u26A0\uFE0F":"\u274C",r=e.status==="ok"?l.green:e.status==="warn"?l.yellow:l.red;console.log(`${t} ${l.bold(o)}: ${r(e.message)}`),e.paths&&e.paths.length>0?e.paths.forEach(i=>{let n=i.version?l.cyan(` -> ${i.version}`):"";console.log(` ${l.cyan("\u2022")} ${l.gray(i.location)}: ${l.dim(i.path)}${n}`);}):e.details&&console.log(` ${l.gray(e.details)}`);}function In(e){let o=e.issues.length>0,t=o?"\u26A0\uFE0F":"\u2705",r=o?l.yellow:l.green;if(console.log(`
3367
3367
  ${t} ${l.bold("Project")}: ${r(e.name)}`),e.framework){let c=e.framework==="FastAPI"?"\u{1F40D}":e.framework==="NestJS"?"\u{1F985}":e.framework==="Go/Fiber"||e.framework==="Go/Gin"?"\u{1F439}":"\u{1F4E6}";console.log(` ${c} Framework: ${l.cyan(e.framework)}${e.kit?l.gray(` (${e.kit})`):""}`);}console.log(` ${l.gray(`Path: ${e.path}`)}`);let i=e.isGoProject===true,n=!i&&e.venvActive&&!e.coreInstalled;if(!i&&!n&&(e.venvActive?console.log(` \u2705 Virtual environment: ${l.green("Active")}`):console.log(` \u274C Virtual environment: ${l.red("Not found")}`),e.coreInstalled?console.log(` ${l.dim("\u2139")} RapidKit Core: ${l.gray(e.coreVersion||"In venv")} ${l.dim("(optional)")}`):console.log(` ${l.dim("\u2139")} RapidKit Core: ${l.gray("Using global installation")} ${l.dim("(recommended)")}`)),e.depsInstalled?console.log(` \u2705 Dependencies: ${l.green("Installed")}`):console.log(` \u26A0\uFE0F Dependencies: ${l.yellow("Not installed")}`),e.hasEnvFile!==void 0&&(e.hasEnvFile?console.log(` \u2705 Environment: ${l.green(".env configured")}`):console.log(` \u26A0\uFE0F Environment: ${l.yellow(".env missing")}`)),e.modulesHealthy!==void 0&&(e.modulesHealthy?console.log(` \u2705 Modules: ${l.green("Healthy")}`):e.missingModules&&e.missingModules.length>0&&console.log(` \u26A0\uFE0F Modules: ${l.yellow(`Missing ${e.missingModules.length} init file(s)`)}`)),e.stats){let c=[];e.stats.modules!==void 0&&c.push(`${e.stats.modules} module${e.stats.modules!==1?"s":""}`),c.length>0&&console.log(` \u{1F4CA} Stats: ${l.cyan(c.join(" \u2022 "))}`);}e.lastModified&&console.log(` \u{1F552} Last Modified: ${l.gray(e.lastModified)}`);let s=[];if(e.hasTests!==void 0&&s.push(e.hasTests?"\u2705 Tests":l.dim("\u2298 No tests")),e.hasDocker!==void 0&&s.push(e.hasDocker?"\u2705 Docker":l.dim("\u2298 No Docker")),e.hasCodeQuality!==void 0){let c=e.framework==="NestJS"?"ESLint":e.framework==="Go/Fiber"||e.framework==="Go/Gin"?"golangci-lint":"Ruff";s.push(e.hasCodeQuality?`\u2705 ${c}`:l.dim(`\u2298 No ${c}`));}s.length>0&&console.log(` ${s.join(" \u2022 ")}`),e.vulnerabilities!==void 0&&e.vulnerabilities>0&&console.log(` \u26A0\uFE0F Security: ${l.yellow(`${e.vulnerabilities} vulnerability(ies) found`)}`),e.issues.length>0&&(console.log(` ${l.bold("Issues:")}`),e.issues.forEach(c=>{console.log(` \u2022 ${l.yellow(c)}`);}),e.fixCommands&&e.fixCommands.length>0&&(console.log(`
3368
3368
  ${l.bold.cyan("\u{1F527} Quick Fix:")}`),e.fixCommands.forEach(c=>{console.log(` ${l.cyan("$")} ${l.white(c)}`);})));}async function Po(){try{return (await execa("go",["version"],{timeout:3e3,reject:false})).exitCode===0}catch{return false}}async function Eo(e,o=false){let t=e.filter(p=>p.fixCommands&&p.fixCommands.length>0),r=null;if(t.length===0){console.log(l.green(`
3369
3369
  \u2705 No fixes needed - all projects are healthy!`));return}console.log(l.bold.cyan(`
@@ -3400,18 +3400,18 @@ Tip: Project auto-fix runs in workspace mode. Run from a workspace and use "rapi
3400
3400
  Tip: Run "rapidkit doctor workspace" for detailed project checks`))):(console.log(l.bold.green(`
3401
3401
  \u2705 All required tools are installed!`)),e.fix&&console.log(l.gray(`
3402
3402
  Tip: Project auto-fix runs in workspace mode. Run from a workspace and use "rapidkit doctor workspace --fix"`)),console.log(l.gray(`
3403
- Tip: Run "rapidkit doctor workspace" for detailed project checks`)));}console.log("");}var Yt=h.join(Tn.homedir(),".rapidkit"),_t=h.join(Yt,"config.json");function Ye(){try{if(!_.existsSync(_t))return {};let e=_.readFileSync(_t,"utf-8");return JSON.parse(e)}catch{return {}}}function Ct(e){let t={...Ye(),...e};_.existsSync(Yt)||_.mkdirSync(Yt,{recursive:true}),_.writeFileSync(_t,JSON.stringify(t,null,2),"utf-8");}function nt(){return process.env.OPENAI_API_KEY||Ye().openaiApiKey||null}function zt(){return Ye().aiEnabled!==false}function Qt(){return _t}async function jo(){return (await import('inquirer')).default}function $o(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 r=t.key;r?r.startsWith("sk-")||(console.log(l.red(`
3403
+ Tip: Run "rapidkit doctor workspace" for detailed project checks`)));}console.log("");}var Yt=h.join(Tn.homedir(),".rapidkit"),_t=h.join(Yt,"config.json");function ze(){try{if(!_.existsSync(_t))return {};let e=_.readFileSync(_t,"utf-8");return JSON.parse(e)}catch{return {}}}function Ct(e){let t={...ze(),...e};_.existsSync(Yt)||_.mkdirSync(Yt,{recursive:true}),_.writeFileSync(_t,JSON.stringify(t,null,2),"utf-8");}function nt(){return process.env.OPENAI_API_KEY||ze().openaiApiKey||null}function zt(){return ze().aiEnabled!==false}function Qt(){return _t}async function jo(){return (await import('inquirer')).default}function $o(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 r=t.key;r?r.startsWith("sk-")||(console.log(l.red(`
3404
3404
  \u274C Invalid API key format (should start with sk-)
3405
3405
  `)),process.exit(1)):r=(await(await jo()).prompt([{type:"password",name:"apiKey",message:"Enter your OpenAI API key:",validate:a=>a?a.startsWith("sk-")?a.length<20?"API key seems too short":true:"Invalid API key format (should start with sk-)":"API key is required"}])).apiKey,Ct({openaiApiKey:r}),console.log(l.green(`
3406
3406
  \u2705 OpenAI API key saved successfully!
3407
3407
  `)),console.log(l.gray(`Stored in: ${Qt()}`)),console.log(l.cyan(`
3408
3408
  \u{1F389} You can now use AI features:`)),console.log(l.white(' rapidkit ai recommend "I need user authentication"')),console.log(l.gray(`
3409
3409
  \u{1F4A1} To generate module embeddings (one-time):`)),console.log(l.white(" cd rapidkit-npm")),console.log(l.white(` npx tsx src/ai/generate-embeddings.ts
3410
- `));}),o.command("show").description("Show current configuration").action(()=>{let t=Ye();if(console.log(l.bold(`
3410
+ `));}),o.command("show").description("Show current configuration").action(()=>{let t=ze();if(console.log(l.bold(`
3411
3411
  \u2699\uFE0F RapidKit Configuration
3412
3412
  `)),t.openaiApiKey){let r=t.openaiApiKey.substring(0,8)+"..."+t.openaiApiKey.slice(-4);console.log(l.cyan("OpenAI API Key:"),l.white(r));}else console.log(l.cyan("OpenAI API Key:"),l.red("Not set")),console.log(l.gray(" Set with: rapidkit config set-api-key"));console.log(l.cyan("AI Features:"),t.aiEnabled!==false?l.green("Enabled"):l.red("Disabled")),console.log(l.gray(`
3413
3413
  \u{1F4C1} Config file: ${Qt()}
3414
- `));}),o.command("remove-api-key").description("Remove stored OpenAI API key").action(async()=>{if(!Ye().openaiApiKey){console.log(l.yellow(`
3414
+ `));}),o.command("remove-api-key").description("Remove stored OpenAI API key").action(async()=>{if(!ze().openaiApiKey){console.log(l.yellow(`
3415
3415
  \u26A0\uFE0F No API key is currently stored
3416
3416
  `));return}(await(await jo()).prompt([{type:"confirm",name:"confirm",message:"Are you sure you want to remove your OpenAI API key?",default:false}])).confirm?(Ct({openaiApiKey:void 0}),console.log(l.green(`
3417
3417
  \u2705 API key removed successfully
@@ -3421,7 +3421,7 @@ Cancelled
3421
3421
  \u274C Invalid action: ${t}`)),console.log(l.gray(`Use: rapidkit config ai enable|disable
3422
3422
  `)),process.exit(1));let r=t==="enable";Ct({aiEnabled:r}),console.log(l.green(`
3423
3423
  \u2705 AI features ${r?"enabled":"disabled"}
3424
- `));});}var St=null,xt=false,Xt=null;async function An(){return Xt||(Xt=(await import('openai')).default),Xt}function Do(){xt=true;}function Go(e){let t=new Array(1536),r=0;for(let n=0;n<e.length;n++)r=(r<<5)-r+e.charCodeAt(n),r=r&r;for(let n=0;n<1536;n++)r=r*1664525+1013904223&4294967295,t[n]=r/4294967295*2-1;let i=Math.sqrt(t.reduce((n,a)=>n+a*a,0));return t.map(n=>n/i)}async function Pt(e){let o=await An();St=new o({apiKey:e});}function Mo(){if(!St)throw new Error("OpenAI client not initialized. Call initOpenAI() first with your API key.");return St}async function Lo(e){return xt?Go(e):(await Mo().embeddings.create({model:"text-embedding-3-small",input:e,encoding_format:"float"})).data[0].embedding}async function qo(e){return xt?e.map(Go):(await Mo().embeddings.create({model:"text-embedding-3-small",input:e,encoding_format:"float"})).data.map(r=>r.embedding)}function Fo(){return St!==null}function Ho(){return xt}var jn=promisify(exec),Wo=[{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"]}],ze=null,Ko=0,$n=300*1e3;function Dn(e){return {id:e.name||e.id||e.module_id||"",name:e.display_name||e.name||"",category:Gn(e.category||"infrastructure"),description:e.description||e.summary||"",longDescription:e.long_description||e.description||"",keywords:e.keywords||e.tags||[],framework:Mn(e.framework),dependencies:e.dependencies||[],useCases:e.use_cases||e.useCases||[]}}function Gn(e){return {auth:"auth",authentication:"auth",database:"database",payment:"payment",billing:"payment",communication:"communication",infrastructure:"infrastructure",security:"security",analytics:"analytics"}[e.toLowerCase()]||"infrastructure"}function Mn(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 Ln(){try{let{stdout:e}=await jn("rapidkit modules list --json-schema 1",{timeout:1e4,maxBuffer:10485760}),o=e.match(/\{[\s\S]*\}/),t=o?o[0]:e,r=JSON.parse(t),i=[];return Array.isArray(r)?i=r:r.modules&&Array.isArray(r.modules)?i=r.modules:r.data&&Array.isArray(r.data)&&(i=r.data),i.map(Dn).filter(n=>n.id&&n.name)}catch(e){return e.code==="ENOENT"?console.warn("\u26A0\uFE0F RapidKit Python Core not found in PATH"):e.killed?console.warn("\u26A0\uFE0F Python Core command timed out"):console.warn("\u26A0\uFE0F Failed to fetch modules from Python Core:",e.message),console.warn(" Using fallback module catalog (11 modules)"),Wo}}async function Et(){let e=Date.now();return ze&&e-Ko<$n||(ze=await Ln(),Ko=e,ze.length===0&&(console.warn("\u26A0\uFE0F No modules found, using fallback catalog"),ze=Wo)),ze}var Fn=fileURLToPath(import.meta.url),Vo=h.dirname(Fn),st=null;function Hn(){if(st)return st;let e=[h.join(Vo,"../../data/modules-embeddings.json"),h.join(Vo,"../data/modules-embeddings.json"),h.join(process.cwd(),"data/modules-embeddings.json")],o=null;for(let i of e)if(_.existsSync(i)){o=i;break}if(!o)throw new Error("embeddings file not found");let t=_.readFileSync(o,"utf-8"),r=JSON.parse(t);return Array.isArray(r)?st={model:"mock-or-text-embedding-3-small",dimension:r[0]?.embedding?.length||1536,generated_at:new Date().toISOString(),modules:r}:st=r,st}function Kn(e,o){if(e.length!==o.length)throw new Error("Vectors must have the same length");let t=0,r=0,i=0;for(let a=0;a<e.length;a++)t+=e[a]*o[a],r+=e[a]*e[a],i+=o[a]*o[a];let n=Math.sqrt(r)*Math.sqrt(i);return n===0?0:t/n}function Wn(e,o){let t=o.toLowerCase(),r=e.keywords.filter(i=>t.includes(i)||i.includes(t));return r.length>0?`Matches: ${r.slice(0,3).join(", ")}`:`Relevant for: ${e.useCases[0]}`}async function Bo(e,o=5){let t=Hn(),r=await Et(),i=await Lo(e),n=t.modules.map(a=>{let s=r.find(p=>p.id===a.id);if(!s)return null;let c=Kn(i,a.embedding);return {module:s,score:c,reason:Wn(s,e)}}).filter(a=>a!==null);return n.sort((a,s)=>s.score-a.score),n.slice(0,o)}var Bn=fileURLToPath(import.meta.url),Jo=h.dirname(Bn);async function Yo(){return (await import('inquirer')).default}function Jn(){return [h.join(Jo,"../../data/modules-embeddings.json"),h.join(Jo,"../data/modules-embeddings.json"),h.join(process.cwd(),"data/modules-embeddings.json")]}function zo(){let e=Jn();for(let o of e)if(_.existsSync(o))try{let t=JSON.parse(_.readFileSync(o,"utf-8")),r=Array.isArray(t)?t:t.modules||[];return {exists:true,path:o,moduleCount:r.length,generatedAt:t.generated_at||null}}catch{continue}return {exists:false,path:null,moduleCount:0,generatedAt:null}}async function Tt(e=true,o){try{if(!Fo()&&!Ho())return console.log(l.red(`
3424
+ `));});}var St=null,xt=false,Xt=null;async function An(){return Xt||(Xt=(await import('openai')).default),Xt}function Do(){xt=true;}function Go(e){let t=new Array(1536),r=0;for(let n=0;n<e.length;n++)r=(r<<5)-r+e.charCodeAt(n),r=r&r;for(let n=0;n<1536;n++)r=r*1664525+1013904223&4294967295,t[n]=r/4294967295*2-1;let i=Math.sqrt(t.reduce((n,a)=>n+a*a,0));return t.map(n=>n/i)}async function Pt(e){let o=await An();St=new o({apiKey:e});}function Mo(){if(!St)throw new Error("OpenAI client not initialized. Call initOpenAI() first with your API key.");return St}async function Lo(e){return xt?Go(e):(await Mo().embeddings.create({model:"text-embedding-3-small",input:e,encoding_format:"float"})).data[0].embedding}async function qo(e){return xt?e.map(Go):(await Mo().embeddings.create({model:"text-embedding-3-small",input:e,encoding_format:"float"})).data.map(r=>r.embedding)}function Fo(){return St!==null}function Ho(){return xt}var jn=promisify(exec),Wo=[{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"]}],Qe=null,Ko=0,$n=300*1e3;function Dn(e){return {id:e.name||e.id||e.module_id||"",name:e.display_name||e.name||"",category:Gn(e.category||"infrastructure"),description:e.description||e.summary||"",longDescription:e.long_description||e.description||"",keywords:e.keywords||e.tags||[],framework:Mn(e.framework),dependencies:e.dependencies||[],useCases:e.use_cases||e.useCases||[]}}function Gn(e){return {auth:"auth",authentication:"auth",database:"database",payment:"payment",billing:"payment",communication:"communication",infrastructure:"infrastructure",security:"security",analytics:"analytics"}[e.toLowerCase()]||"infrastructure"}function Mn(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 Ln(){try{let{stdout:e}=await jn("rapidkit modules list --json-schema 1",{timeout:1e4,maxBuffer:10485760}),o=e.match(/\{[\s\S]*\}/),t=o?o[0]:e,r=JSON.parse(t),i=[];return Array.isArray(r)?i=r:r.modules&&Array.isArray(r.modules)?i=r.modules:r.data&&Array.isArray(r.data)&&(i=r.data),i.map(Dn).filter(n=>n.id&&n.name)}catch(e){return e.code==="ENOENT"?console.warn("\u26A0\uFE0F RapidKit Python Core not found in PATH"):e.killed?console.warn("\u26A0\uFE0F Python Core command timed out"):console.warn("\u26A0\uFE0F Failed to fetch modules from Python Core:",e.message),console.warn(" Using fallback module catalog (11 modules)"),Wo}}async function Et(){let e=Date.now();return Qe&&e-Ko<$n||(Qe=await Ln(),Ko=e,Qe.length===0&&(console.warn("\u26A0\uFE0F No modules found, using fallback catalog"),Qe=Wo)),Qe}var Fn=fileURLToPath(import.meta.url),Vo=h.dirname(Fn),st=null;function Hn(){if(st)return st;let e=[h.join(Vo,"../../data/modules-embeddings.json"),h.join(Vo,"../data/modules-embeddings.json"),h.join(process.cwd(),"data/modules-embeddings.json")],o=null;for(let i of e)if(_.existsSync(i)){o=i;break}if(!o)throw new Error("embeddings file not found");let t=_.readFileSync(o,"utf-8"),r=JSON.parse(t);return Array.isArray(r)?st={model:"mock-or-text-embedding-3-small",dimension:r[0]?.embedding?.length||1536,generated_at:new Date().toISOString(),modules:r}:st=r,st}function Kn(e,o){if(e.length!==o.length)throw new Error("Vectors must have the same length");let t=0,r=0,i=0;for(let a=0;a<e.length;a++)t+=e[a]*o[a],r+=e[a]*e[a],i+=o[a]*o[a];let n=Math.sqrt(r)*Math.sqrt(i);return n===0?0:t/n}function Wn(e,o){let t=o.toLowerCase(),r=e.keywords.filter(i=>t.includes(i)||i.includes(t));return r.length>0?`Matches: ${r.slice(0,3).join(", ")}`:`Relevant for: ${e.useCases[0]}`}async function Bo(e,o=5){let t=Hn(),r=await Et(),i=await Lo(e),n=t.modules.map(a=>{let s=r.find(p=>p.id===a.id);if(!s)return null;let c=Kn(i,a.embedding);return {module:s,score:c,reason:Wn(s,e)}}).filter(a=>a!==null);return n.sort((a,s)=>s.score-a.score),n.slice(0,o)}var Bn=fileURLToPath(import.meta.url),Jo=h.dirname(Bn);async function Yo(){return (await import('inquirer')).default}function Jn(){return [h.join(Jo,"../../data/modules-embeddings.json"),h.join(Jo,"../data/modules-embeddings.json"),h.join(process.cwd(),"data/modules-embeddings.json")]}function zo(){let e=Jn();for(let o of e)if(_.existsSync(o))try{let t=JSON.parse(_.readFileSync(o,"utf-8")),r=Array.isArray(t)?t:t.modules||[];return {exists:true,path:o,moduleCount:r.length,generatedAt:t.generated_at||null}}catch{continue}return {exists:false,path:null,moduleCount:0,generatedAt:null}}async function Tt(e=true,o){try{if(!Fo()&&!Ho())return console.log(l.red(`
3425
3425
  \u274C OpenAI not initialized`)),console.log(l.yellow("Please set your API key:")),console.log(l.white(" rapidkit config set-api-key")),console.log(l.gray(` OR set: export OPENAI_API_KEY="sk-..."
3426
3426
  `)),false;console.log(l.blue(`
3427
3427
  \u{1F916} Generating AI embeddings for RapidKit modules...
@@ -3500,9 +3500,9 @@ No modules selected
3500
3500
  `)),console.log(l.white(`Set your API key: rapidkit config set-api-key
3501
3501
  `)),process.exit(1)),Pt(t);let r=await Xo();process.exit(r?0:1);}catch(t){a$1.error("Failed to update embeddings:",t.message),process.exit(1);}});}var At=class{constructor(o){this.runCommand=o;}runtime="go";async run(o,t,r){return {exitCode:await this.runCommand(o,t,r)}}async ensureGoInstalled(o){return (await this.run("go",["version"],o)).exitCode===0?null:{exitCode:1,message:"Go toolchain is not installed or not available on PATH. Install Go from https://go.dev/dl/ and retry."}}findWorkspaceRoot(o){let t=o;for(;;){if(_.existsSync(h.join(t,".rapidkit-workspace")))return t;let r=h.dirname(t);if(r===t)break;t=r;}return null}resolveDependencyMode(o){let t=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(t==="shared-runtime-caches"||t==="shared-node-deps"||t==="isolated")return t;let r=this.findWorkspaceRoot(o);if(!r)return "isolated";let i=h.join(r,".rapidkit","policies.yml");if(!_.existsSync(i))return "isolated";try{let s=_.readFileSync(i,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(s==="shared-runtime-caches"||s==="shared-node-deps"||s==="isolated")return s}catch{}return "isolated"}withGoCacheEnv(o,t){let r=this.resolveDependencyMode(o),i=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(o),n=r==="shared-runtime-caches"?h.join(i||o,".rapidkit","cache","go"):h.join(o,".rapidkit","cache","go"),a=process.env.GOMODCACHE,s=process.env.GOCACHE;return process.env.GOMODCACHE=h.join(n,"mod"),process.env.GOCACHE=h.join(n,"build"),t().finally(()=>{typeof a>"u"?delete process.env.GOMODCACHE:process.env.GOMODCACHE=a,typeof s>"u"?delete process.env.GOCACHE:process.env.GOCACHE=s;})}async checkPrereqs(){return this.run("go",["version"],process.cwd())}async warmSetupCache(o){return this.withGoCacheEnv(o,async()=>{try{return process.env.GOMODCACHE&&_.mkdirSync(process.env.GOMODCACHE,{recursive:true}),process.env.GOCACHE&&_.mkdirSync(process.env.GOCACHE,{recursive:true}),{exitCode:0}}catch{return {exitCode:1,message:"Failed to prepare Go cache directories"}}})}async initProject(o){return this.withGoCacheEnv(o,async()=>{let t=await this.ensureGoInstalled(o);return t||this.run("go",["mod","tidy"],o)})}async runDev(o){return this.withGoCacheEnv(o,()=>(async()=>{let t=await this.ensureGoInstalled(o);if(t)return t;let r=h.join(o,"Makefile");return _.existsSync(r)?this.run("make",["run"],o):this.run("go",["run","./main.go"],o)})())}async runTest(o){return this.withGoCacheEnv(o,async()=>{let t=await this.ensureGoInstalled(o);return t||this.run("go",["test","./..."],o)})}async runBuild(o){return this.withGoCacheEnv(o,async()=>{let t=await this.ensureGoInstalled(o);return t||this.run("go",["build","./..."],o)})}async runStart(o){return this.withGoCacheEnv(o,async()=>{let r=(a()?[h.join(o,"server.exe"),h.join(o,"server")]:[h.join(o,"server")]).find(n=>_.existsSync(n));if(r)return this.run(r,[],o);let i=await this.ensureGoInstalled(o);return i||this.run("go",["run","./main.go"],o)})}async doctorHints(o){return ["Install Go from https://go.dev/dl/ if missing.","Run go mod tidy when dependencies are out of sync.","Use make run for hot-reload if Makefile exists."]}};var Ot=class{constructor(o){this.runCommand=o;}runtime="node";async run(o,t,r){return {exitCode:await this.runCommand(o,t,r)}}findWorkspaceRoot(o){let t=o;for(;;){if(_.existsSync(h.join(t,".rapidkit-workspace")))return t;let r=h.dirname(t);if(r===t)break;t=r;}return null}resolveDependencyMode(o){let t=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(t==="shared-runtime-caches"||t==="shared-node-deps"||t==="isolated")return t;let r=this.findWorkspaceRoot(o);if(!r)return "isolated";let i=h.join(r,".rapidkit","policies.yml");if(!_.existsSync(i))return "isolated";try{let s=_.readFileSync(i,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(s==="shared-runtime-caches"||s==="shared-node-deps"||s==="isolated")return s}catch{}return "isolated"}withDependencyEnv(o,t,r){let i=this.resolveDependencyMode(o),n=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(o),a=i==="isolated"?h.join(o,".rapidkit","cache","node"):h.join(n||o,".rapidkit","cache","node"),s=process.env.npm_config_cache,c=process.env.npm_config_store_dir;return t==="pnpm"?(process.env.npm_config_store_dir=h.join(a,"pnpm-store"),process.env.npm_config_cache=h.join(a,"pnpm-cache")):t==="yarn"?process.env.npm_config_cache=h.join(a,"yarn-cache"):process.env.npm_config_cache=h.join(a,"npm-cache"),r().finally(()=>{typeof s>"u"?delete process.env.npm_config_cache:process.env.npm_config_cache=s,typeof c>"u"?delete process.env.npm_config_store_dir:process.env.npm_config_store_dir=c;})}detectPackageManager(o){return _.existsSync(h.join(o,"pnpm-lock.yaml"))?"pnpm":_.existsSync(h.join(o,"yarn.lock"))?"yarn":"npm"}scriptArgs(o,t){return o==="npm"?["run",t]:["run",t]}async checkPrereqs(){return this.run("node",["--version"],process.cwd())}async warmSetupCache(o){let t=this.detectPackageManager(o);return this.withDependencyEnv(o,t,async()=>{try{return process.env.npm_config_cache&&_.mkdirSync(process.env.npm_config_cache,{recursive:true}),t==="pnpm"&&process.env.npm_config_store_dir&&_.mkdirSync(process.env.npm_config_store_dir,{recursive:true}),{exitCode:0}}catch{return {exitCode:1,message:"Failed to prepare Node cache directories"}}})}async initProject(o){let t=this.detectPackageManager(o),r=this.resolveDependencyMode(o),i=r==="shared-runtime-caches"||r==="shared-node-deps"?["install","--prefer-offline"]:["install"];return this.withDependencyEnv(o,t,()=>this.run(t,i,o))}async runDev(o){let t=this.detectPackageManager(o);return this.withDependencyEnv(o,t,()=>this.run(t,this.scriptArgs(t,"dev"),o))}async runTest(o){let t=this.detectPackageManager(o);return this.withDependencyEnv(o,t,()=>this.run(t,this.scriptArgs(t,"test"),o))}async runBuild(o){let t=this.detectPackageManager(o);return this.withDependencyEnv(o,t,()=>this.run(t,this.scriptArgs(t,"build"),o))}async runStart(o){let t=this.detectPackageManager(o);return this.withDependencyEnv(o,t,()=>this.run(t,this.scriptArgs(t,"start"),o))}async doctorHints(o){return ["Install Node.js LTS and ensure node/npm are on PATH.","Use lockfiles (package-lock.json, pnpm-lock.yaml, yarn.lock) for deterministic installs.","Run install before dev/test/build if dependencies changed."]}};var Nt=class{constructor(o){this.runCore=o;}runtime="python";async run(o,t){return {exitCode:await this.withPythonCacheEnv(t,()=>this.runCore(o,t))}}findWorkspaceRoot(o){let t=o;for(;;){if(_.existsSync(h.join(t,".rapidkit-workspace")))return t;let r=h.dirname(t);if(r===t)break;t=r;}return null}resolveDependencyMode(o){let t=process.env.RAPIDKIT_DEP_SHARING_MODE?.toLowerCase();if(t==="shared-runtime-caches"||t==="shared-node-deps"||t==="isolated")return t;let r=this.findWorkspaceRoot(o);if(!r)return "isolated";let i=h.join(r,".rapidkit","policies.yml");if(!_.existsSync(i))return "isolated";try{let s=_.readFileSync(i,"utf-8").match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();if(s==="shared-runtime-caches"||s==="shared-node-deps"||s==="isolated")return s}catch{}return "isolated"}withPythonCacheEnv(o,t){let r=this.resolveDependencyMode(o),i=process.env.RAPIDKIT_WORKSPACE_PATH||this.findWorkspaceRoot(o),n=r==="shared-runtime-caches"?h.join(i||o,".rapidkit","cache","python"):h.join(o,".rapidkit","cache","python"),a=process.env.PIP_CACHE_DIR,s=process.env.POETRY_CACHE_DIR;return process.env.PIP_CACHE_DIR=h.join(n,"pip"),process.env.POETRY_CACHE_DIR=h.join(n,"poetry"),t().finally(()=>{typeof a>"u"?delete process.env.PIP_CACHE_DIR:process.env.PIP_CACHE_DIR=a,typeof s>"u"?delete process.env.POETRY_CACHE_DIR:process.env.POETRY_CACHE_DIR=s;})}async checkPrereqs(){let o=process.cwd(),t=await this.run(["doctor","check"],o);return t.exitCode===0?t:this.run(["doctor"],o)}async initProject(o){return this.run(["init"],o)}async runDev(o){return this.run(["dev"],o)}async runTest(o){return this.run(["test"],o)}async runBuild(o){return this.run(["build"],o)}async runStart(o){return this.run(["start"],o)}async doctorHints(o){return ['Run "npx rapidkit doctor workspace" for a full workspace scan.','Use "npx rapidkit init" after adding or changing modules.','Use workspace launcher "./rapidkit" to avoid environment drift.']}};function Yn(){let e={...process.env},o=e.PATH||"";if(o){let t=o.split(h.delimiter).filter(r=>!r.replace(/\\/g,"/").includes("/.pyenv/shims")).join(h.delimiter);e.PATH=t;}return e.PYENV_VERSION="system",e.POETRY_PYTHON=e.POETRY_PYTHON||c$3(),typeof e.RAPIDKIT_SKIP_LOCK_SYNC>"u"&&(e.RAPIDKIT_SKIP_LOCK_SYNC="1"),e}function He(e,o){return e==="go"?new At((t,r,i)=>o.runCommandInCwd(t,r,i)):e==="node"?new Ot((t,r,i)=>o.runCommandInCwd(t,r,i)):new Nt((t,r)=>o.runCoreRapidkit(t,{cwd:r,env:Yn()}))}var or=h.join(Tn.homedir(),".rapidkit","cache"),rr=1440*60*1e3;function eo(){let e=process.env.RAPIDKIT_CACHE_DIR?.trim();if(e)return e;let o=process.env.VITEST_WORKER_ID?.trim();return o?h.join(or,`vitest-${o}`):or}var $t=class e{static instance;memoryCache=new Map;constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}getCacheKey(o){return createHash("md5").update(o).digest("hex")}getCachePath(o){return h.join(eo(),`${this.getCacheKey(o)}.json`)}async get(o,t="1.0"){let r=this.memoryCache.get(o);if(r&&r.version===t&&Date.now()-r.timestamp<rr)return a$1.debug(`Cache hit (memory): ${o}`),r.data;try{let i=this.getCachePath(o),n=await promises.readFile(i,"utf-8"),a=JSON.parse(n);if(a.version===t&&Date.now()-a.timestamp<rr)return a$1.debug(`Cache hit (disk): ${o}`),this.memoryCache.set(o,a),a.data;await promises.unlink(i).catch(()=>{});}catch{a$1.debug(`Cache miss: ${o}`);}return null}async set(o,t,r="1.0"){let i={data:t,timestamp:Date.now(),version:r};this.memoryCache.set(o,i);try{await promises.mkdir(eo(),{recursive:true});let n=this.getCachePath(o);await promises.writeFile(n,JSON.stringify(i),"utf-8"),a$1.debug(`Cache set: ${o}`);}catch(n){a$1.debug(`Cache write failed: ${o}`,n);}}async invalidate(o){this.memoryCache.delete(o);try{let t=this.getCachePath(o);await promises.unlink(t),a$1.debug(`Cache invalidated: ${o}`);}catch{}}async clear(){this.memoryCache.clear();try{let o=eo(),t=await promises.readdir(o);await Promise.all(t.map(r=>promises.unlink(h.join(o,r)))),a$1.debug("Cache cleared");}catch{}}};function Se(e){let o=e;for(;;){let t=h.join(o,".rapidkit","project.json");if(_.existsSync(t))try{return JSON.parse(_.readFileSync(t,"utf8"))}catch{return null}let r=h.dirname(o);if(r===o)break;o=r;}return null}function pe(e,o){let t=e?.runtime?.toLowerCase(),r=e?.kit_name?.toLowerCase(),i=_.existsSync(h.join(o,"go.mod"));return t==="go"||(r?.startsWith("gofiber")??false)||(r?.startsWith("gogin")??false)||i}function ue(e,o){let t=e?.runtime?.toLowerCase(),r=e?.kit_name?.toLowerCase(),i=_.existsSync(h.join(o,"package.json"));return t==="node"||t==="typescript"||(r?.startsWith("nestjs")??false)||i}function me(e,o){let t=e?.runtime?.toLowerCase(),r=e?.kit_name?.toLowerCase(),i=_.existsSync(h.join(o,"pyproject.toml")),n=_.existsSync(h.join(o,"requirements.txt"))||_.existsSync(h.join(o,"requirements.in"));return t==="python"||(r?.startsWith("fastapi")??false)||i||n}async function ts(e){let o=await promises.readFile(e);return createHash("sha256").update(o).digest("hex")}async function ir(e,o){await b.outputFile(e,`${JSON.stringify(o,null,2)}
3502
3502
  `,"utf-8");}function be(e,o){return h.isAbsolute(o)?o:h.join(e,o)}function os(e,o){if(e.target)return e.target;if(e.source)return h.basename(e.source);if(e.url)try{let t=new URL(e.url).pathname,r=h.basename(t);if(r&&r!=="/")return r}catch{}return `${o}.artifact`}async function rs(e){let o=h.join(e,".rapidkit","trusted-sources.lock"),t=new Set(["localhost","127.0.0.1"]);if(!await b.pathExists(o))return t;try{let i=(await promises.readFile(o,"utf-8")).split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#"));for(let n of i)t.add(n.toLowerCase());}catch{}return t}async function is(e,o,t){await b.ensureDir(h.dirname(o)),await new Promise((r,i)=>{let a=(e.startsWith("https://")?lr:cr).get(e,s=>{if(!s.statusCode||s.statusCode<200||s.statusCode>=300){i(new Error(`HTTP ${s.statusCode||"unknown"}`)),s.resume();return}let c=createWriteStream(o);s.pipe(c),c.on("finish",()=>{c.close(),r();}),c.on("error",p=>{i(p);});});a.setTimeout(t,()=>{a.destroy(new Error(`Request timeout after ${t}ms`));}),a.on("error",s=>{i(s);});});}async function ns(e,o,t,r,i){let n=new URL(e),a=JSON.stringify(o),s=n.protocol==="https:"?lr:cr;await new Promise((c,p)=>{let d=s.request({method:"POST",hostname:n.hostname,port:n.port||(n.protocol==="https:"?443:80),path:`${n.pathname}${n.search}`,headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(a),...r?{Authorization:`Bearer ${r}`}:{},...i||{}}},u=>{if(!u.statusCode||u.statusCode<200||u.statusCode>=300){p(new Error(`HTTP ${u.statusCode||"unknown"}`)),u.resume();return}u.resume(),c();});d.setTimeout(t,()=>{d.destroy(new Error(`Request timeout after ${t}ms`));}),d.on("error",u=>{p(u);}),d.write(a),d.end();});}function nr(e){return new Promise(o=>setTimeout(o,e))}async function ss(e,o,t,r){let i=be(e,o||".rapidkit/reports/evidence-export-dead-letter.ndjson");return await b.ensureDir(h.dirname(i)),await promises.appendFile(i,`${JSON.stringify({timestamp:new Date().toISOString(),reason:r,payload:t})}
3503
- `,"utf-8"),i}function as(e,o){if(!o?.enabled)return {headers:{}};let t=process.env[o.hmacKeyEnv];if(!t)return {headers:{},error:`Evidence signing key env is missing: ${o.hmacKeyEnv}`};let r=(o.algorithm||"sha256").toLowerCase(),i=o.headerName||"x-rapidkit-evidence-signature",n=createHmac(r,t).update(JSON.stringify(e)).digest("hex");return {headers:{[i]:n,"x-rapidkit-evidence-signature-alg":r}}}async function cs(e,o,t){let r=(t.algorithm||"sha256").toLowerCase(),i=be(e,t.publicKeyPath);if(!await b.pathExists(i))return {verified:false,algorithm:r,publicKeyPath:i,publicKeyFingerprint:"",signature:t.signature,message:`Public key not found: ${i}`};try{let n=await promises.readFile(i,"utf-8"),a=await promises.readFile(o),s=createVerify(r);s.update(a),s.end();let c=Buffer.from(t.signature,"base64"),p=s.verify(n,c),d=createHash("sha256").update(n).digest("hex");return {verified:p,algorithm:r,publicKeyPath:i,publicKeyFingerprint:d,signature:t.signature,message:p?"Attestation verified.":"Attestation signature verification failed."}}catch(n){return {verified:false,algorithm:r,publicKeyPath:i,publicKeyFingerprint:"",signature:t.signature,message:`Attestation verification error: ${n.message}`}}}async function ls(e,o,t,r){let i=process.env.RAPIDKIT_SIGSTORE_MOCK;if(i==="success")return {verified:true,tlogVerified:r.requireTransparencyLog,message:"Sigstore verification passed (mock).",identity:t.identity||null,issuer:t.issuer||null,rekorUrl:t.rekorUrl||null,bundlePath:t.bundlePath||null,certificatePath:t.certificatePath||null,signaturePath:t.signaturePath||null};if(i==="fail")return {verified:false,tlogVerified:false,message:"Sigstore verification failed (mock).",identity:t.identity||null,issuer:t.issuer||null,rekorUrl:t.rekorUrl||null,bundlePath:t.bundlePath||null,certificatePath:t.certificatePath||null,signaturePath:t.signaturePath||null};let n=t.signaturePath?be(e,t.signaturePath):null;if(!n||!await b.pathExists(n))return {verified:false,tlogVerified:false,message:"Sigstore signaturePath is missing or not found.",identity:t.identity||null,issuer:t.issuer||null,rekorUrl:t.rekorUrl||null,bundlePath:t.bundlePath||null,certificatePath:t.certificatePath||null,signaturePath:n};let a=["verify-blob",o,"--signature",n],s=t.certificatePath?be(e,t.certificatePath):null;s&&a.push("--certificate",s);let c=t.bundlePath?be(e,t.bundlePath):null;c&&a.push("--bundle",c);let p=t.keyPath?be(e,t.keyPath):null;p&&a.push("--key",p),t.identity&&a.push("--certificate-identity",t.identity),t.issuer&&a.push("--certificate-oidc-issuer",t.issuer),t.rekorUrl&&a.push("--rekor-url",t.rekorUrl),r.requireTransparencyLog||a.push("--insecure-ignore-tlog");try{let d=await execa("cosign",a,{reject:false});return d.exitCode===0?{verified:true,tlogVerified:r.requireTransparencyLog,message:"Sigstore verification passed.",identity:t.identity||null,issuer:t.issuer||null,rekorUrl:t.rekorUrl||null,bundlePath:c,certificatePath:s,signaturePath:n}:{verified:false,tlogVerified:false,message:`Sigstore verification failed: ${d.stderr||d.stdout||"unknown error"}`,identity:t.identity||null,issuer:t.issuer||null,rekorUrl:t.rekorUrl||null,bundlePath:c,certificatePath:s,signaturePath:n}}catch(d){return {verified:false,tlogVerified:false,message:`Sigstore verification error: ${d.message}`,identity:t.identity||null,issuer:t.issuer||null,rekorUrl:t.rekorUrl||null,bundlePath:c,certificatePath:s,signaturePath:n}}}async function ds(e,o){let t=o.algorithm||"sha256",r=be(e,o.policyPath),i=be(e,o.signaturePath),n=be(e,o.publicKeyPath);if(!await b.pathExists(r))return {verified:false,message:`Governance policy bundle not found: ${r}`,policies:null};if(!await b.pathExists(i))return {verified:false,message:`Governance policy signature not found: ${i}`,policies:null};if(!await b.pathExists(n))return {verified:false,message:`Governance policy public key not found: ${n}`,policies:null};try{let a=await promises.readFile(r,"utf-8"),s=(await promises.readFile(i,"utf-8")).trim(),c=await promises.readFile(n,"utf-8"),p=createVerify(t);return p.update(a),p.end(),p.verify(c,Buffer.from(s,"base64"))?{verified:true,message:"Governance policy bundle verified.",policies:JSON.parse(a).policies||{}}:{verified:false,message:"Governance policy bundle signature verification failed.",policies:null}}catch(a){return {verified:false,message:`Governance policy bundle verification error: ${a.message}`,policies:null}}}async function to(e,o){let t=[],r={syncedArtifacts:0,verifiedArtifacts:0,rotatedFiles:0,lockWritten:false,governanceBundleVerified:false,transparencyEvidenceWritten:false,transparencyEvidenceRecords:0,evidenceExported:false,evidenceExportTarget:null},i=h.join(e,".rapidkit"),n=h.join(i,"mirror-config.json"),a=h.join(i,"mirror.lock"),s=h.join(i,"mirror","artifacts"),c=h.join(i,"reports"),p=await rs(e);if(!await b.pathExists(n))return t.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror lifecycle skipped: .rapidkit/mirror-config.json not found."}),{checks:t,details:r};let d={};try{d=JSON.parse(await promises.readFile(n,"utf-8"));}catch{return t.push({id:"mirror.lifecycle.config",status:"failed",message:"Mirror lifecycle failed: invalid JSON in mirror-config.json."}),{checks:t,details:r}}if(!(o.forceRun===true||o.ciMode||o.offlineMode||d.mode==="offline-only"))return t.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror lifecycle skipped: not in ci/offline mode."}),{checks:t,details:r};await b.ensureDir(s);let m=Math.max(0,d.prefetch?.retries??2),w=Math.max(0,d.prefetch?.backoffMs??250),f=Math.max(1e3,d.prefetch?.timeoutMs??15e3),g=d.security?.requireAttestation===true,R=d.security?.requireSigstore===true,x=d.security?.requireTransparencyLog===true,T=d.security?.requireSignedGovernance===true,C=d.security?.evidenceExport,P=(process.env.RAPIDKIT_ENV||d.security?.governance?.environment||"dev").toLowerCase(),G=d.security?.governance?.policies||{};if(d.security?.governanceBundle){let z=await ds(e,d.security.governanceBundle);if(t.push({id:"governance.bundle.verify",status:z.verified?"passed":"failed",message:z.message}),z.verified&&z.policies)G=z.policies,r.governanceBundleVerified=true;else if(T)return {checks:t,details:r}}let N=G[P],$=x||N?.requireTransparencyLog===true,Re=[],Ze=Array.isArray(d.artifacts)?d.artifacts:[],we=[];for(let z=0;z<Ze.length;z+=1){let L=Ze[z],S=L.id||`artifact-${z+1}`,se=L.source?be(e,L.source):null,ae=os(L,S),H=h.join(s,ae),re=false,le={sourceType:"path",source:se||L.url||"unknown",host:null,fetchedAt:new Date().toISOString(),attempts:1,trusted:true};if(se&&await b.pathExists(se))await b.ensureDir(h.dirname(H)),await b.copyFile(se,H),r.syncedArtifacts+=1,re=true,le={sourceType:"path",source:se,host:null,fetchedAt:new Date().toISOString(),attempts:1,trusted:true},t.push({id:`mirror.sync.${S}`,status:"passed",message:`Mirrored artifact ${S} from source path.`});else if(L.url){let U="";try{U=new URL(L.url).hostname.toLowerCase();}catch{t.push({id:`mirror.prefetch.${S}`,status:"failed",message:`Invalid URL for ${S}: ${L.url}`});continue}if(!(process.env.RAPIDKIT_TRUSTED_SOURCES==="1"||p.has(U))){t.push({id:`mirror.prefetch.trust.${S}`,status:"failed",message:`Untrusted mirror host for ${S}: ${U}. Add host to .rapidkit/trusted-sources.lock or set RAPIDKIT_TRUSTED_SOURCES=1.`});continue}if(o.offlineMode&&(await b.pathExists(H)?(re=true,le={sourceType:"url",source:L.url,host:U,fetchedAt:new Date().toISOString(),attempts:0,trusted:true},t.push({id:`mirror.prefetch.${S}`,status:"passed",message:`Offline mode reused existing mirrored artifact ${S}.`})):t.push({id:`mirror.prefetch.${S}`,status:"failed",message:`Offline mode cannot prefetch remote artifact ${S} without an existing mirrored copy.`}),!re))continue;if(!re){let ie=null,Ae=0;for(let Ee=1;Ee<=m+1;Ee+=1){Ae=Ee;try{await is(L.url,H,f),r.syncedArtifacts+=1,re=true,le={sourceType:"url",source:L.url,host:U,fetchedAt:new Date().toISOString(),attempts:Ae,trusted:true},t.push({id:`mirror.prefetch.${S}`,status:"passed",message:Ae>1?`Prefetched artifact ${S} from ${U} after ${Ae} attempts.`:`Prefetched artifact ${S} from ${U}.`});break}catch(ut){if(ie=ut,Ee<=m){await nr(w*Ee);continue}}}if(!re){t.push({id:`mirror.prefetch.${S}`,status:"failed",message:`Failed to prefetch ${S} after ${m+1} attempt(s): ${ie?.message||"unknown error"}`});continue}}if(!re){t.push({id:`mirror.prefetch.${S}`,status:"failed",message:`Failed to prefetch ${S}.`});continue}}if(!re){L.required||o.offlineMode?t.push({id:`mirror.sync.${S}`,status:"failed",message:`Mirror source missing for ${S}${se?`: ${se}`:""}`}):t.push({id:`mirror.sync.${S}`,status:"skipped",message:`Mirror source not found for optional artifact ${S}.`});continue}let I=await ts(H);if(L.sha256&&L.sha256.toLowerCase()!==I.toLowerCase()){t.push({id:`mirror.verify.${S}`,status:"failed",message:`Checksum mismatch for ${S}.`});continue}r.verifiedArtifacts+=1,t.push({id:`mirror.verify.${S}`,status:"passed",message:`Checksum verified for ${S}.`});let O=L.attestation?await cs(e,H,L.attestation):null;if(L.attestation){if(t.push({id:`mirror.attest.${S}`,status:O?.verified?"passed":"failed",message:O?.message||"Attestation verification failed."}),!O?.verified)continue}else if(g){t.push({id:`mirror.attest.${S}`,status:"failed",message:`Attestation is required but missing for ${S}.`});continue}else t.push({id:`mirror.attest.${S}`,status:"skipped",message:`No attestation provided for ${S}.`});let M=L.attestation?.sigstore,j=M?await ls(e,H,M,{requireTransparencyLog:$}):null;if(M){if(t.push({id:`mirror.sigstore.${S}`,status:j?.verified?"passed":"failed",message:j?.message||"Sigstore verification failed."}),Re.push({artifactId:S,verified:!!j?.verified,tlogVerified:!!j?.tlogVerified,identity:j?.identity||null,issuer:j?.issuer||null,rekorUrl:j?.rekorUrl||null,timestamp:new Date().toISOString(),environment:P}),!j?.verified)continue}else if(R){t.push({id:`mirror.sigstore.${S}`,status:"failed",message:`Sigstore attestation is required but missing for ${S}.`});continue}else t.push({id:`mirror.sigstore.${S}`,status:"skipped",message:`No Sigstore attestation provided for ${S}.`});if(M&&j?.verified&&N){let U=N.allowedIdentities||[];if(U.length>0){let ie=!!j.identity&&U.includes(j.identity);if(t.push({id:`mirror.sigstore.policy.identity.${S}`,status:ie?"passed":"failed",message:ie?`Sigstore identity policy passed for ${S} in ${P}.`:`Sigstore identity policy failed for ${S} in ${P}.`}),!ie)continue}let Te=N.allowedIssuers||[];if(Te.length>0){let ie=!!j.issuer&&Te.includes(j.issuer);if(t.push({id:`mirror.sigstore.policy.issuer.${S}`,status:ie?"passed":"failed",message:ie?`Sigstore issuer policy passed for ${S} in ${P}.`:`Sigstore issuer policy failed for ${S} in ${P}.`}),!ie)continue}let Pe=N.allowedRekorUrls||[];if(Pe.length>0){let ie=!!j.rekorUrl&&Pe.includes(j.rekorUrl);if(t.push({id:`mirror.sigstore.policy.rekor.${S}`,status:ie?"passed":"failed",message:ie?`Sigstore Rekor policy passed for ${S} in ${P}.`:`Sigstore Rekor policy failed for ${S} in ${P}.`}),!ie)continue}}else N&&t.push({id:`mirror.sigstore.policy.${S}`,status:"skipped",message:`Sigstore governance policy configured for ${P} but no verified Sigstore attestation for ${S}.`});let ge=await promises.stat(H);we.push({id:S,path:h.relative(e,H),sha256:I,size:ge.size,provenance:le,attestation:{detached:{provided:!!L.attestation,verified:O?.verified||false,algorithm:O?.algorithm||null,publicKeyPath:O?.publicKeyPath||null,publicKeyFingerprint:O?.publicKeyFingerprint||null,signature:O?.signature||null,verifiedAt:O?.verified?new Date().toISOString():null},sigstore:{provided:!!M,verified:j?.verified||false,tlogVerified:j?.tlogVerified||false,identity:j?.identity||null,issuer:j?.issuer||null,rekorUrl:j?.rekorUrl||null,bundlePath:j?.bundlePath||null,certificatePath:j?.certificatePath||null,signaturePath:j?.signaturePath||null,verifiedAt:j?.verified?new Date().toISOString():null}}});}let fe=d.retention?.keepLast;if(typeof fe=="number"&&fe>0){let L=(await promises.readdir(s,{withFileTypes:true})).filter(S=>S.isFile()).map(S=>h.join(s,S.name));if(L.length>fe){let S=await Promise.all(L.map(async ae=>({filePath:ae,stat:await promises.stat(ae)})));S.sort((ae,H)=>H.stat.mtimeMs-ae.stat.mtimeMs);let se=S.slice(fe);for(let ae of se)await promises.unlink(ae.filePath),r.rotatedFiles+=1;}}t.push({id:"mirror.rotate",status:"passed",message:r.rotatedFiles>0?`Mirror retention rotation removed ${r.rotatedFiles} file(s).`:"Mirror retention rotation completed with no removals."});let Ve={schemaVersion:"1.0",generatedAt:new Date().toISOString(),mode:d.mode||null,environment:P,artifacts:we};if(await promises.writeFile(a,`${JSON.stringify(Ve,null,2)}
3504
- `,"utf-8"),r.lockWritten=true,t.push({id:"mirror.lock.write",status:"passed",message:`Mirror lock updated at ${h.relative(e,a)}.`}),r.transparencyEvidenceRecords=Re.length,Re.length>0){let z={schemaVersion:"1.0",generatedAt:new Date().toISOString(),environment:P,records:Re},L=new Date().toISOString().replace(/[:.]/g,"-"),S=h.join(c,`transparency-evidence-${L}.json`),se=h.join(c,"transparency-evidence.latest.json");if(await b.ensureDir(c),await ir(S,z),await ir(se,z),r.transparencyEvidenceWritten=true,t.push({id:"sigstore.evidence.write",status:"passed",message:`Transparency evidence written to ${h.relative(e,se)}.`}),C?.enabled){let ae=Math.max(1e3,C.timeoutMs??1e4);if(C.target==="file")if(!C.filePath)t.push({id:"sigstore.evidence.export.file",status:"failed",message:"Evidence export target=file requires security.evidenceExport.filePath."});else try{let H=be(e,C.filePath);await b.ensureDir(h.dirname(H)),await promises.appendFile(H,`${JSON.stringify(z)}
3505
- `,"utf-8"),r.evidenceExported=true,r.evidenceExportTarget=H,t.push({id:"sigstore.evidence.export.file",status:"passed",message:`Transparency evidence exported to file sink ${H}.`});}catch(H){t.push({id:"sigstore.evidence.export.file",status:"failed",message:`Evidence file export failed: ${H.message}`});}else if(C.target==="http")if(!C.endpoint)t.push({id:"sigstore.evidence.export.http",status:"failed",message:"Evidence export target=http requires security.evidenceExport.endpoint."});else {let H=Math.max(0,C.retries??0),re=Math.max(0,C.backoffMs??500),le=as(z,C.signing);le.error&&t.push({id:"sigstore.evidence.export.http",status:"failed",message:le.error});try{let I=C.authTokenEnv?process.env[C.authTokenEnv]:void 0,O=false,M=null;for(let j=1;j<=H+1;j+=1)try{if(le.error)throw new Error(le.error);await ns(C.endpoint,z,ae,I,le.headers),r.evidenceExported=true,r.evidenceExportTarget=C.endpoint,t.push({id:"sigstore.evidence.export.http",status:"passed",message:j>1?`Transparency evidence exported to HTTP endpoint ${C.endpoint} after ${j} attempts.`:`Transparency evidence exported to HTTP endpoint ${C.endpoint}.`}),O=true;break}catch(ge){M=ge,j<=H&&await nr(re*j);}if(!O)throw M||new Error("unknown evidence export error")}catch(I){let O=`Evidence HTTP export failed: ${I.message}`;t.push({id:"sigstore.evidence.export.http",status:"failed",message:O});try{let M=await ss(e,C.deadLetterPath,z,O);t.push({id:"sigstore.evidence.export.deadletter",status:"passed",message:`Evidence export failure persisted to dead-letter sink ${M}.`});}catch(M){t.push({id:"sigstore.evidence.export.deadletter",status:"failed",message:`Evidence dead-letter write failed: ${M.message}`});}}}if(C.failOnError&&t.some(re=>re.status==="failed"&&(re.id==="sigstore.evidence.export.file"||re.id==="sigstore.evidence.export.http")))return {checks:t,details:r}}else t.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export not configured (security.evidenceExport.enabled=false)."});}else t.push({id:"sigstore.evidence.write",status:"skipped",message:"No Sigstore records available for transparency evidence output."}),t.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export skipped because no transparency evidence records exist."});return {checks:t,details:r}}function oo(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 us(e){let o=e.trim().toLowerCase();return o?o.startsWith("fastapi")?"fastapi":o.startsWith("nestjs")?"nestjs":null:null}function qt(e){let o=e.trim().toLowerCase();return o.startsWith("gofiber")||o==="go"||o==="go.standard"||o==="fiber"}function lt(e){let o=e.trim().toLowerCase();return o.startsWith("gogin")||o==="gin"}function pt(e,o){let t=e.indexOf(o);if(t>=0&&t+1<e.length)return e[t+1];let r=e.find(i=>i.startsWith(`${o}=`));if(r)return r.slice(o.length+1)}function co(){return d$2()}function pr(){let e={...process.env},o=e.PATH||"";return o&&(e.PATH=o.split(h.delimiter).filter(t=>!t.replace(/\\/g,"/").includes("/.pyenv/shims")).join(h.delimiter)),e.PYENV_VERSION="system",e.POETRY_PYTHON||(e.POETRY_PYTHON=c$3()),e.RAPIDKIT_SKIP_LOCK_SYNC||(e.RAPIDKIT_SKIP_LOCK_SYNC="1"),e.POETRY_KEYRING_ENABLED||(e.POETRY_KEYRING_ENABLED="false"),e.PYTHON_KEYRING_BACKEND||(e.PYTHON_KEYRING_BACKEND="keyring.backends.null.Keyring"),e.POETRY_NO_INTERACTION||(e.POETRY_NO_INTERACTION="1"),e}function gs(e){return f$1(h.join(e,".venv"))}async function _r(e,o){return await W(e,["--version"],o)===0}async function ro(e){let o=h.join(e,"go.mod");if(await b.pathExists(o))return "go";let t=h.join(e,"package.json");if(await b.pathExists(t))return "node";let r=h.join(e,"pyproject.toml"),i=h.join(e,"requirements.txt"),n=h.join(e,"poetry.lock");return await b.pathExists(r)||await b.pathExists(i)||await b.pathExists(n)?"python":null}async function ms(e){for(let o of co())if(await W(o,o==="py"?["-3","-m","venv",".venv"]:["-m","venv",".venv"],e)===0)return 0;return 1}async function Cr(e){for(let o of co())if(await W(o,o==="py"?["-3","-m","venv",".venv"]:["-m","venv",".venv"],e)===0)return 0;return 1}async function fs(e){let o=f$1(h.join(e,".venv"));if(!await b.pathExists(o)){let n=await Cr(e);if(n!==0)return n}if(!await _r("poetry",e))return 0;let r=await W("poetry",["config","virtualenvs.in-project","true","--local"],e);if(r!==0)return r;let i=await W("poetry",["env","use",o],e);return i!==0?i:0}async function hs(e){let o=f$1(h.join(e,".venv"));if(!await b.pathExists(o)){let i=await Cr(e);if(i!==0)return i}await W(o,["-m","pip","install","--upgrade","pip","setuptools","wheel"],e);let t=h.join(e,"requirements.txt");if(await b.pathExists(t)&&await W(o,["-m","pip","install","-r","requirements.txt"],e)===0)return 0;let r=h.join(e,"pyproject.toml");return await b.pathExists(r)&&(await W(o,["-m","pip","install","-e","."],e)===0||await W(o,["-m","pip","install","."],e)===0)?0:1}async function Dt(e,o){return await fs(e)!==0&&console.log(l.yellow("\u26A0\uFE0F Could not fully configure Poetry local venv. Trying fallback installer...")),(await o.initProject(e)).exitCode===0&&await b.pathExists(h.join(e,".venv"))?0:(console.log(l.yellow("\u26A0\uFE0F Python init fallback: installing dependencies directly into project .venv")),await hs(e))}async function Gt(e){let o=await dt("init",e);if(o===0)return 0;let t=["npm","pnpm","yarn"];for(let r of t){if(!await _r(r,e))continue;if(await W(r,["install"],e)===0)return console.log(l.green(`\u2705 Node init fallback succeeded with ${r} install`)),0}return o}async function ur(e){if(e[0]!=="create"||e[1]!=="project")return 1;let o=e[2],t=e[3];if(!o||!t)return process.stderr.write(`Usage: rapidkit create project gofiber.standard <name> [--output <dir>]
3503
+ `,"utf-8"),i}function as(e,o){if(!o?.enabled)return {headers:{}};let t=process.env[o.hmacKeyEnv];if(!t)return {headers:{},error:`Evidence signing key env is missing: ${o.hmacKeyEnv}`};let r=(o.algorithm||"sha256").toLowerCase(),i=o.headerName||"x-rapidkit-evidence-signature",n=createHmac(r,t).update(JSON.stringify(e)).digest("hex");return {headers:{[i]:n,"x-rapidkit-evidence-signature-alg":r}}}async function cs(e,o,t){let r=(t.algorithm||"sha256").toLowerCase(),i=be(e,t.publicKeyPath);if(!await b.pathExists(i))return {verified:false,algorithm:r,publicKeyPath:i,publicKeyFingerprint:"",signature:t.signature,message:`Public key not found: ${i}`};try{let n=await promises.readFile(i,"utf-8"),a=await promises.readFile(o),s=createVerify(r);s.update(a),s.end();let c=Buffer.from(t.signature,"base64"),p=s.verify(n,c),d=createHash("sha256").update(n).digest("hex");return {verified:p,algorithm:r,publicKeyPath:i,publicKeyFingerprint:d,signature:t.signature,message:p?"Attestation verified.":"Attestation signature verification failed."}}catch(n){return {verified:false,algorithm:r,publicKeyPath:i,publicKeyFingerprint:"",signature:t.signature,message:`Attestation verification error: ${n.message}`}}}async function ls(e,o,t,r){let i=process.env.RAPIDKIT_SIGSTORE_MOCK;if(i==="success")return {verified:true,tlogVerified:r.requireTransparencyLog,message:"Sigstore verification passed (mock).",identity:t.identity||null,issuer:t.issuer||null,rekorUrl:t.rekorUrl||null,bundlePath:t.bundlePath||null,certificatePath:t.certificatePath||null,signaturePath:t.signaturePath||null};if(i==="fail")return {verified:false,tlogVerified:false,message:"Sigstore verification failed (mock).",identity:t.identity||null,issuer:t.issuer||null,rekorUrl:t.rekorUrl||null,bundlePath:t.bundlePath||null,certificatePath:t.certificatePath||null,signaturePath:t.signaturePath||null};let n=t.signaturePath?be(e,t.signaturePath):null;if(!n||!await b.pathExists(n))return {verified:false,tlogVerified:false,message:"Sigstore signaturePath is missing or not found.",identity:t.identity||null,issuer:t.issuer||null,rekorUrl:t.rekorUrl||null,bundlePath:t.bundlePath||null,certificatePath:t.certificatePath||null,signaturePath:n};let a=["verify-blob",o,"--signature",n],s=t.certificatePath?be(e,t.certificatePath):null;s&&a.push("--certificate",s);let c=t.bundlePath?be(e,t.bundlePath):null;c&&a.push("--bundle",c);let p=t.keyPath?be(e,t.keyPath):null;p&&a.push("--key",p),t.identity&&a.push("--certificate-identity",t.identity),t.issuer&&a.push("--certificate-oidc-issuer",t.issuer),t.rekorUrl&&a.push("--rekor-url",t.rekorUrl),r.requireTransparencyLog||a.push("--insecure-ignore-tlog");try{let d=await execa("cosign",a,{reject:false});return d.exitCode===0?{verified:true,tlogVerified:r.requireTransparencyLog,message:"Sigstore verification passed.",identity:t.identity||null,issuer:t.issuer||null,rekorUrl:t.rekorUrl||null,bundlePath:c,certificatePath:s,signaturePath:n}:{verified:false,tlogVerified:false,message:`Sigstore verification failed: ${d.stderr||d.stdout||"unknown error"}`,identity:t.identity||null,issuer:t.issuer||null,rekorUrl:t.rekorUrl||null,bundlePath:c,certificatePath:s,signaturePath:n}}catch(d){return {verified:false,tlogVerified:false,message:`Sigstore verification error: ${d.message}`,identity:t.identity||null,issuer:t.issuer||null,rekorUrl:t.rekorUrl||null,bundlePath:c,certificatePath:s,signaturePath:n}}}async function ds(e,o){let t=o.algorithm||"sha256",r=be(e,o.policyPath),i=be(e,o.signaturePath),n=be(e,o.publicKeyPath);if(!await b.pathExists(r))return {verified:false,message:`Governance policy bundle not found: ${r}`,policies:null};if(!await b.pathExists(i))return {verified:false,message:`Governance policy signature not found: ${i}`,policies:null};if(!await b.pathExists(n))return {verified:false,message:`Governance policy public key not found: ${n}`,policies:null};try{let a=await promises.readFile(r,"utf-8"),s=(await promises.readFile(i,"utf-8")).trim(),c=await promises.readFile(n,"utf-8"),p=createVerify(t);return p.update(a),p.end(),p.verify(c,Buffer.from(s,"base64"))?{verified:true,message:"Governance policy bundle verified.",policies:JSON.parse(a).policies||{}}:{verified:false,message:"Governance policy bundle signature verification failed.",policies:null}}catch(a){return {verified:false,message:`Governance policy bundle verification error: ${a.message}`,policies:null}}}async function to(e,o){let t=[],r={syncedArtifacts:0,verifiedArtifacts:0,rotatedFiles:0,lockWritten:false,governanceBundleVerified:false,transparencyEvidenceWritten:false,transparencyEvidenceRecords:0,evidenceExported:false,evidenceExportTarget:null},i=h.join(e,".rapidkit"),n=h.join(i,"mirror-config.json"),a=h.join(i,"mirror.lock"),s=h.join(i,"mirror","artifacts"),c=h.join(i,"reports"),p=await rs(e);if(!await b.pathExists(n))return t.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror lifecycle skipped: .rapidkit/mirror-config.json not found."}),{checks:t,details:r};let d={};try{d=JSON.parse(await promises.readFile(n,"utf-8"));}catch{return t.push({id:"mirror.lifecycle.config",status:"failed",message:"Mirror lifecycle failed: invalid JSON in mirror-config.json."}),{checks:t,details:r}}if(!(o.forceRun===true||o.ciMode||o.offlineMode||d.mode==="offline-only"))return t.push({id:"mirror.lifecycle",status:"skipped",message:"Mirror lifecycle skipped: not in ci/offline mode."}),{checks:t,details:r};await b.ensureDir(s);let m=Math.max(0,d.prefetch?.retries??2),w=Math.max(0,d.prefetch?.backoffMs??250),f=Math.max(1e3,d.prefetch?.timeoutMs??15e3),g=d.security?.requireAttestation===true,R=d.security?.requireSigstore===true,x=d.security?.requireTransparencyLog===true,T=d.security?.requireSignedGovernance===true,C=d.security?.evidenceExport,E=(process.env.RAPIDKIT_ENV||d.security?.governance?.environment||"dev").toLowerCase(),G=d.security?.governance?.policies||{};if(d.security?.governanceBundle){let z=await ds(e,d.security.governanceBundle);if(t.push({id:"governance.bundle.verify",status:z.verified?"passed":"failed",message:z.message}),z.verified&&z.policies)G=z.policies,r.governanceBundleVerified=true;else if(T)return {checks:t,details:r}}let N=G[E],$=x||N?.requireTransparencyLog===true,Re=[],et=Array.isArray(d.artifacts)?d.artifacts:[],we=[];for(let z=0;z<et.length;z+=1){let L=et[z],S=L.id||`artifact-${z+1}`,se=L.source?be(e,L.source):null,ae=os(L,S),H=h.join(s,ae),ie=false,le={sourceType:"path",source:se||L.url||"unknown",host:null,fetchedAt:new Date().toISOString(),attempts:1,trusted:true};if(se&&await b.pathExists(se))await b.ensureDir(h.dirname(H)),await b.copyFile(se,H),r.syncedArtifacts+=1,ie=true,le={sourceType:"path",source:se,host:null,fetchedAt:new Date().toISOString(),attempts:1,trusted:true},t.push({id:`mirror.sync.${S}`,status:"passed",message:`Mirrored artifact ${S} from source path.`});else if(L.url){let U="";try{U=new URL(L.url).hostname.toLowerCase();}catch{t.push({id:`mirror.prefetch.${S}`,status:"failed",message:`Invalid URL for ${S}: ${L.url}`});continue}if(!(process.env.RAPIDKIT_TRUSTED_SOURCES==="1"||p.has(U))){t.push({id:`mirror.prefetch.trust.${S}`,status:"failed",message:`Untrusted mirror host for ${S}: ${U}. Add host to .rapidkit/trusted-sources.lock or set RAPIDKIT_TRUSTED_SOURCES=1.`});continue}if(o.offlineMode&&(await b.pathExists(H)?(ie=true,le={sourceType:"url",source:L.url,host:U,fetchedAt:new Date().toISOString(),attempts:0,trusted:true},t.push({id:`mirror.prefetch.${S}`,status:"passed",message:`Offline mode reused existing mirrored artifact ${S}.`})):t.push({id:`mirror.prefetch.${S}`,status:"failed",message:`Offline mode cannot prefetch remote artifact ${S} without an existing mirrored copy.`}),!ie))continue;if(!ie){let ne=null,Ae=0;for(let Ee=1;Ee<=m+1;Ee+=1){Ae=Ee;try{await is(L.url,H,f),r.syncedArtifacts+=1,ie=true,le={sourceType:"url",source:L.url,host:U,fetchedAt:new Date().toISOString(),attempts:Ae,trusted:true},t.push({id:`mirror.prefetch.${S}`,status:"passed",message:Ae>1?`Prefetched artifact ${S} from ${U} after ${Ae} attempts.`:`Prefetched artifact ${S} from ${U}.`});break}catch(ut){if(ne=ut,Ee<=m){await nr(w*Ee);continue}}}if(!ie){t.push({id:`mirror.prefetch.${S}`,status:"failed",message:`Failed to prefetch ${S} after ${m+1} attempt(s): ${ne?.message||"unknown error"}`});continue}}if(!ie){t.push({id:`mirror.prefetch.${S}`,status:"failed",message:`Failed to prefetch ${S}.`});continue}}if(!ie){L.required||o.offlineMode?t.push({id:`mirror.sync.${S}`,status:"failed",message:`Mirror source missing for ${S}${se?`: ${se}`:""}`}):t.push({id:`mirror.sync.${S}`,status:"skipped",message:`Mirror source not found for optional artifact ${S}.`});continue}let I=await ts(H);if(L.sha256&&L.sha256.toLowerCase()!==I.toLowerCase()){t.push({id:`mirror.verify.${S}`,status:"failed",message:`Checksum mismatch for ${S}.`});continue}r.verifiedArtifacts+=1,t.push({id:`mirror.verify.${S}`,status:"passed",message:`Checksum verified for ${S}.`});let O=L.attestation?await cs(e,H,L.attestation):null;if(L.attestation){if(t.push({id:`mirror.attest.${S}`,status:O?.verified?"passed":"failed",message:O?.message||"Attestation verification failed."}),!O?.verified)continue}else if(g){t.push({id:`mirror.attest.${S}`,status:"failed",message:`Attestation is required but missing for ${S}.`});continue}else t.push({id:`mirror.attest.${S}`,status:"skipped",message:`No attestation provided for ${S}.`});let M=L.attestation?.sigstore,j=M?await ls(e,H,M,{requireTransparencyLog:$}):null;if(M){if(t.push({id:`mirror.sigstore.${S}`,status:j?.verified?"passed":"failed",message:j?.message||"Sigstore verification failed."}),Re.push({artifactId:S,verified:!!j?.verified,tlogVerified:!!j?.tlogVerified,identity:j?.identity||null,issuer:j?.issuer||null,rekorUrl:j?.rekorUrl||null,timestamp:new Date().toISOString(),environment:E}),!j?.verified)continue}else if(R){t.push({id:`mirror.sigstore.${S}`,status:"failed",message:`Sigstore attestation is required but missing for ${S}.`});continue}else t.push({id:`mirror.sigstore.${S}`,status:"skipped",message:`No Sigstore attestation provided for ${S}.`});if(M&&j?.verified&&N){let U=N.allowedIdentities||[];if(U.length>0){let ne=!!j.identity&&U.includes(j.identity);if(t.push({id:`mirror.sigstore.policy.identity.${S}`,status:ne?"passed":"failed",message:ne?`Sigstore identity policy passed for ${S} in ${E}.`:`Sigstore identity policy failed for ${S} in ${E}.`}),!ne)continue}let Te=N.allowedIssuers||[];if(Te.length>0){let ne=!!j.issuer&&Te.includes(j.issuer);if(t.push({id:`mirror.sigstore.policy.issuer.${S}`,status:ne?"passed":"failed",message:ne?`Sigstore issuer policy passed for ${S} in ${E}.`:`Sigstore issuer policy failed for ${S} in ${E}.`}),!ne)continue}let Pe=N.allowedRekorUrls||[];if(Pe.length>0){let ne=!!j.rekorUrl&&Pe.includes(j.rekorUrl);if(t.push({id:`mirror.sigstore.policy.rekor.${S}`,status:ne?"passed":"failed",message:ne?`Sigstore Rekor policy passed for ${S} in ${E}.`:`Sigstore Rekor policy failed for ${S} in ${E}.`}),!ne)continue}}else N&&t.push({id:`mirror.sigstore.policy.${S}`,status:"skipped",message:`Sigstore governance policy configured for ${E} but no verified Sigstore attestation for ${S}.`});let ge=await promises.stat(H);we.push({id:S,path:h.relative(e,H),sha256:I,size:ge.size,provenance:le,attestation:{detached:{provided:!!L.attestation,verified:O?.verified||false,algorithm:O?.algorithm||null,publicKeyPath:O?.publicKeyPath||null,publicKeyFingerprint:O?.publicKeyFingerprint||null,signature:O?.signature||null,verifiedAt:O?.verified?new Date().toISOString():null},sigstore:{provided:!!M,verified:j?.verified||false,tlogVerified:j?.tlogVerified||false,identity:j?.identity||null,issuer:j?.issuer||null,rekorUrl:j?.rekorUrl||null,bundlePath:j?.bundlePath||null,certificatePath:j?.certificatePath||null,signaturePath:j?.signaturePath||null,verifiedAt:j?.verified?new Date().toISOString():null}}});}let fe=d.retention?.keepLast;if(typeof fe=="number"&&fe>0){let L=(await promises.readdir(s,{withFileTypes:true})).filter(S=>S.isFile()).map(S=>h.join(s,S.name));if(L.length>fe){let S=await Promise.all(L.map(async ae=>({filePath:ae,stat:await promises.stat(ae)})));S.sort((ae,H)=>H.stat.mtimeMs-ae.stat.mtimeMs);let se=S.slice(fe);for(let ae of se)await promises.unlink(ae.filePath),r.rotatedFiles+=1;}}t.push({id:"mirror.rotate",status:"passed",message:r.rotatedFiles>0?`Mirror retention rotation removed ${r.rotatedFiles} file(s).`:"Mirror retention rotation completed with no removals."});let Ve={schemaVersion:"1.0",generatedAt:new Date().toISOString(),mode:d.mode||null,environment:E,artifacts:we};if(await promises.writeFile(a,`${JSON.stringify(Ve,null,2)}
3504
+ `,"utf-8"),r.lockWritten=true,t.push({id:"mirror.lock.write",status:"passed",message:`Mirror lock updated at ${h.relative(e,a)}.`}),r.transparencyEvidenceRecords=Re.length,Re.length>0){let z={schemaVersion:"1.0",generatedAt:new Date().toISOString(),environment:E,records:Re},L=new Date().toISOString().replace(/[:.]/g,"-"),S=h.join(c,`transparency-evidence-${L}.json`),se=h.join(c,"transparency-evidence.latest.json");if(await b.ensureDir(c),await ir(S,z),await ir(se,z),r.transparencyEvidenceWritten=true,t.push({id:"sigstore.evidence.write",status:"passed",message:`Transparency evidence written to ${h.relative(e,se)}.`}),C?.enabled){let ae=Math.max(1e3,C.timeoutMs??1e4);if(C.target==="file")if(!C.filePath)t.push({id:"sigstore.evidence.export.file",status:"failed",message:"Evidence export target=file requires security.evidenceExport.filePath."});else try{let H=be(e,C.filePath);await b.ensureDir(h.dirname(H)),await promises.appendFile(H,`${JSON.stringify(z)}
3505
+ `,"utf-8"),r.evidenceExported=true,r.evidenceExportTarget=H,t.push({id:"sigstore.evidence.export.file",status:"passed",message:`Transparency evidence exported to file sink ${H}.`});}catch(H){t.push({id:"sigstore.evidence.export.file",status:"failed",message:`Evidence file export failed: ${H.message}`});}else if(C.target==="http")if(!C.endpoint)t.push({id:"sigstore.evidence.export.http",status:"failed",message:"Evidence export target=http requires security.evidenceExport.endpoint."});else {let H=Math.max(0,C.retries??0),ie=Math.max(0,C.backoffMs??500),le=as(z,C.signing);le.error&&t.push({id:"sigstore.evidence.export.http",status:"failed",message:le.error});try{let I=C.authTokenEnv?process.env[C.authTokenEnv]:void 0,O=false,M=null;for(let j=1;j<=H+1;j+=1)try{if(le.error)throw new Error(le.error);await ns(C.endpoint,z,ae,I,le.headers),r.evidenceExported=true,r.evidenceExportTarget=C.endpoint,t.push({id:"sigstore.evidence.export.http",status:"passed",message:j>1?`Transparency evidence exported to HTTP endpoint ${C.endpoint} after ${j} attempts.`:`Transparency evidence exported to HTTP endpoint ${C.endpoint}.`}),O=true;break}catch(ge){M=ge,j<=H&&await nr(ie*j);}if(!O)throw M||new Error("unknown evidence export error")}catch(I){let O=`Evidence HTTP export failed: ${I.message}`;t.push({id:"sigstore.evidence.export.http",status:"failed",message:O});try{let M=await ss(e,C.deadLetterPath,z,O);t.push({id:"sigstore.evidence.export.deadletter",status:"passed",message:`Evidence export failure persisted to dead-letter sink ${M}.`});}catch(M){t.push({id:"sigstore.evidence.export.deadletter",status:"failed",message:`Evidence dead-letter write failed: ${M.message}`});}}}if(C.failOnError&&t.some(ie=>ie.status==="failed"&&(ie.id==="sigstore.evidence.export.file"||ie.id==="sigstore.evidence.export.http")))return {checks:t,details:r}}else t.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export not configured (security.evidenceExport.enabled=false)."});}else t.push({id:"sigstore.evidence.write",status:"skipped",message:"No Sigstore records available for transparency evidence output."}),t.push({id:"sigstore.evidence.export",status:"skipped",message:"Central evidence export skipped because no transparency evidence records exist."});return {checks:t,details:r}}function oo(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 us(e){let o=e.trim().toLowerCase();return o?o.startsWith("fastapi")?"fastapi":o.startsWith("nestjs")?"nestjs":null:null}function qt(e){let o=e.trim().toLowerCase();return o.startsWith("gofiber")||o==="go"||o==="go.standard"||o==="fiber"}function lt(e){let o=e.trim().toLowerCase();return o.startsWith("gogin")||o==="gin"}function pt(e,o){let t=e.indexOf(o);if(t>=0&&t+1<e.length)return e[t+1];let r=e.find(i=>i.startsWith(`${o}=`));if(r)return r.slice(o.length+1)}function co(){return d$2()}function pr(){let e={...process.env},o=e.PATH||"";return o&&(e.PATH=o.split(h.delimiter).filter(t=>!t.replace(/\\/g,"/").includes("/.pyenv/shims")).join(h.delimiter)),e.PYENV_VERSION="system",e.POETRY_PYTHON||(e.POETRY_PYTHON=c$3()),e.RAPIDKIT_SKIP_LOCK_SYNC||(e.RAPIDKIT_SKIP_LOCK_SYNC="1"),e.POETRY_KEYRING_ENABLED||(e.POETRY_KEYRING_ENABLED="false"),e.PYTHON_KEYRING_BACKEND||(e.PYTHON_KEYRING_BACKEND="keyring.backends.null.Keyring"),e.POETRY_NO_INTERACTION||(e.POETRY_NO_INTERACTION="1"),e}function gs(e){return f$1(h.join(e,".venv"))}async function _r(e,o){return await W(e,["--version"],o)===0}async function ro(e){let o=h.join(e,"go.mod");if(await b.pathExists(o))return "go";let t=h.join(e,"package.json");if(await b.pathExists(t))return "node";let r=h.join(e,"pyproject.toml"),i=h.join(e,"requirements.txt"),n=h.join(e,"poetry.lock");return await b.pathExists(r)||await b.pathExists(i)||await b.pathExists(n)?"python":null}async function ms(e){for(let o of co())if(await W(o,o==="py"?["-3","-m","venv",".venv"]:["-m","venv",".venv"],e)===0)return 0;return 1}async function Cr(e){for(let o of co())if(await W(o,o==="py"?["-3","-m","venv",".venv"]:["-m","venv",".venv"],e)===0)return 0;return 1}async function fs(e){let o=f$1(h.join(e,".venv"));if(!await b.pathExists(o)){let n=await Cr(e);if(n!==0)return n}if(!await _r("poetry",e))return 0;let r=await W("poetry",["config","virtualenvs.in-project","true","--local"],e);if(r!==0)return r;let i=await W("poetry",["env","use",o],e);return i!==0?i:0}async function hs(e){let o=f$1(h.join(e,".venv"));if(!await b.pathExists(o)){let i=await Cr(e);if(i!==0)return i}await W(o,["-m","pip","install","--upgrade","pip","setuptools","wheel"],e);let t=h.join(e,"requirements.txt");if(await b.pathExists(t)&&await W(o,["-m","pip","install","-r","requirements.txt"],e)===0)return 0;let r=h.join(e,"pyproject.toml");return await b.pathExists(r)&&(await W(o,["-m","pip","install","-e","."],e)===0||await W(o,["-m","pip","install","."],e)===0)?0:1}async function Dt(e,o){return await fs(e)!==0&&console.log(l.yellow("\u26A0\uFE0F Could not fully configure Poetry local venv. Trying fallback installer...")),(await o.initProject(e)).exitCode===0&&await b.pathExists(h.join(e,".venv"))?0:(console.log(l.yellow("\u26A0\uFE0F Python init fallback: installing dependencies directly into project .venv")),await hs(e))}async function Gt(e){let o=await dt("init",e);if(o===0)return 0;let t=["npm","pnpm","yarn"];for(let r of t){if(!await _r(r,e))continue;if(await W(r,["install"],e)===0)return console.log(l.green(`\u2705 Node init fallback succeeded with ${r} install`)),0}return o}async function ur(e){if(e[0]!=="create"||e[1]!=="project")return 1;let o=e[2],t=e[3];if(!o||!t)return process.stderr.write(`Usage: rapidkit create project gofiber.standard <name> [--output <dir>]
3506
3506
  `),1;let r=pt(e,"--output")||process.cwd(),i=h.resolve(r,t),n=e.includes("--skip-git")||e.includes("--no-git");try{let{default:a}=await import('fs-extra');if(await a.ensureDir(h.dirname(i)),await a.pathExists(i))return process.stderr.write(`\u274C Directory "${i}" already exists
3507
3507
  `),1;await a.ensureDir(i),await Vt(i,{project_name:t,module_path:t,skipGit:n});let s=Y(process.cwd());if(s){let{syncWorkspaceProjects:c}=await import('./workspace-KRZ3DWL4.js');await c(s,true);}return 0}catch(a){return process.stderr.write(`RapidKit Go/Fiber generator failed: ${a?.message??a}
3508
3508
  `),1}}async function gr(e){if(e[0]!=="create"||e[1]!=="project")return 1;let o=e[2],t=e[3];if(!o||!t)return process.stderr.write(`Usage: rapidkit create project gogin.standard <name> [--output <dir>]
@@ -3527,43 +3527,43 @@ Install Python 3.10+ to access all kits.
3527
3527
  `),1}try{if(e[0]==="create"&&e[1]==="project"){if(e.includes("--help")||e.includes("-h"))try{return await c$2(),await d$1(["create","project","--help"],{cwd:process.cwd()})}catch(f){return process.stderr.write(`RapidKit (npm) failed to run the Python core engine: ${f?.message??f}
3528
3528
  `),1}if(!e[2]||e[2].startsWith("-")){console.log(l.bold(`
3529
3529
  \u{1F680} RapidKit
3530
- `));let{kitChoice:f}=await xe.prompt([{type:"rawlist",name:"kitChoice",message:"Select a kit to scaffold:",choices:[{name:"fastapi \u2014 FastAPI Standard Kit",value:"fastapi.standard"},{name:"fastapi \u2014 FastAPI DDD Kit",value:"fastapi.ddd"},{name:"nestjs \u2014 NestJS Standard Kit",value:"nestjs.standard"},{name:"go/fiber \u2014 Go Fiber Standard Kit",value:"gofiber.standard"},{name:"go/gin \u2014 Go Gin Standard Kit",value:"gogin.standard"}]}]);if(qt(f)||lt(f)){let{projectName:R}=await xe.prompt([{type:"input",name:"projectName",message:"Project name:",validate:T=>T.trim().length>0||"Project name is required"}]),x=e.slice(2).filter(T=>T.startsWith("-"));return lt(f)?await gr(["create","project",f,R.trim(),...x]):await ur(["create","project",f,R.trim(),...x])}let{projectName:g}=await xe.prompt([{type:"input",name:"projectName",message:"Project name:",validate:R=>R.trim().length>0||"Project name is required"}]);e.splice(2,0,f,g.trim());}{let f=Y(process.cwd()),g=(e[2]||"").toLowerCase();if(f&&g){let R=h.join(f,".rapidkit","workspace.json"),x=h.join(f,".rapidkit","policies.yml");try{let[T,C]=await Promise.all([b.pathExists(R).then(fe=>fe?_.promises.readFile(R,"utf-8"):"{}"),b.pathExists(x).then(fe=>fe?_.promises.readFile(x,"utf-8"):"")]),P=JSON.parse(T).profile,N=C.match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m)?.[1]??"warn",$=qt(g)||lt(g)||g.startsWith("go"),Re=["nestjs","react","vue","nextjs","next","vite","angular","svelte","express","koa","fastify"].some(fe=>g.includes(fe)),Ze=!$&&!Re,we=null;if(P==="python-only"&&!Ze?we=`Kit "${g}" is not a Python kit, but workspace profile is "python-only".`:P==="node-only"&&!Re?we=`Kit "${g}" is not a Node kit, but workspace profile is "node-only".`:P==="go-only"&&!$&&(we=`Kit "${g}" is not a Go kit, but workspace profile is "go-only".`),we){if(N==="strict")return console.log(l.red(`\u274C Profile violation (strict mode): ${we}`)),console.log(l.gray("\u{1F4A1} Change workspace profile or use --no-workspace to skip enforcement.")),1;console.log(l.yellow(`\u26A0\uFE0F Profile warning: ${we}`)),console.log(l.gray('\u{1F4A1} Consider using a "polyglot" workspace profile for multi-language projects.'));}}catch{}}}if(qt(e[2]||""))return await ur(e);if(lt(e[2]||""))return await gr(e);let r=e.includes("--create-workspace"),i$1=e.includes("--no-workspace"),n=e.includes("--yes")||e.includes("-y"),a=e.includes("--skip-git")||e.includes("--no-git");if(!!!so(process.cwd())){if(r)await i(process.cwd(),{skipGit:a,yes:n,userConfig:await a$2()});else if(!i$1)if(n)await i(process.cwd(),{skipGit:a,yes:true,userConfig:await a$2()});else {let{createWs:f}=await xe.prompt([{type:"confirm",name:"createWs",message:"This project will be created outside a RapidKit workspace. Create and register a workspace here?",default:true}]);f&&await i(process.cwd(),{skipGit:a,yes:false,userConfig:await a$2()});}}let p=[...e.filter(f=>{let g=f.split("=")[0];return !o.has(f)&&!o.has(g)})],d=Y(process.cwd()),w=e.includes("--skip-install")||!!d?{...process.env,RAPIDKIT_SKIP_LOCKS:"1",RAPIDKIT_GENERATE_LOCKS:"0"}:void 0;try{await c$2();let f=await d$1(p,{cwd:process.cwd(),env:w});if(f===0&&d&&!e.includes("--skip-install")&&(console.log(l.gray("\u2139\uFE0F Fast create mode (workspace): dependencies were deferred.")),console.log(l.white(" Next: cd <project-name> && npx rapidkit init"))),f===0){let g=d||Y(process.cwd());if(g){try{let x=e[3];if(x){let T=e.indexOf("--output"),C=T>=0?e[T+1]:".",P=h.resolve(process.cwd(),C,x),G=h.join(g,".python-version"),N=h.join(P,".python-version");if(_.existsSync(G)&&_.existsSync(P)){let $=_.readFileSync(G,"utf-8");_.writeFileSync(N,$.trim()+`
3530
+ `));let{kitChoice:f}=await xe.prompt([{type:"rawlist",name:"kitChoice",message:"Select a kit to scaffold:",choices:[{name:"fastapi \u2014 FastAPI Standard Kit",value:"fastapi.standard"},{name:"fastapi \u2014 FastAPI DDD Kit",value:"fastapi.ddd"},{name:"nestjs \u2014 NestJS Standard Kit",value:"nestjs.standard"},{name:"go/fiber \u2014 Go Fiber Standard Kit",value:"gofiber.standard"},{name:"go/gin \u2014 Go Gin Standard Kit",value:"gogin.standard"}]}]);if(qt(f)||lt(f)){let{projectName:R}=await xe.prompt([{type:"input",name:"projectName",message:"Project name:",validate:T=>T.trim().length>0||"Project name is required"}]),x=e.slice(2).filter(T=>T.startsWith("-"));return lt(f)?await gr(["create","project",f,R.trim(),...x]):await ur(["create","project",f,R.trim(),...x])}let{projectName:g}=await xe.prompt([{type:"input",name:"projectName",message:"Project name:",validate:R=>R.trim().length>0||"Project name is required"}]);e.splice(2,0,f,g.trim());}{let f=Y(process.cwd()),g=(e[2]||"").toLowerCase();if(f&&g){let R=h.join(f,".rapidkit","workspace.json"),x=h.join(f,".rapidkit","policies.yml");try{let[T,C]=await Promise.all([b.pathExists(R).then(fe=>fe?_.promises.readFile(R,"utf-8"):"{}"),b.pathExists(x).then(fe=>fe?_.promises.readFile(x,"utf-8"):"")]),E=JSON.parse(T).profile,N=C.match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m)?.[1]??"warn",$=qt(g)||lt(g)||g.startsWith("go"),Re=["nestjs","react","vue","nextjs","next","vite","angular","svelte","express","koa","fastify"].some(fe=>g.includes(fe)),et=!$&&!Re,we=null;if(E==="python-only"&&!et?we=`Kit "${g}" is not a Python kit, but workspace profile is "python-only".`:E==="node-only"&&!Re?we=`Kit "${g}" is not a Node kit, but workspace profile is "node-only".`:E==="go-only"&&!$&&(we=`Kit "${g}" is not a Go kit, but workspace profile is "go-only".`),we){if(N==="strict")return console.log(l.red(`\u274C Profile violation (strict mode): ${we}`)),console.log(l.gray("\u{1F4A1} Change workspace profile or use --no-workspace to skip enforcement.")),1;console.log(l.yellow(`\u26A0\uFE0F Profile warning: ${we}`)),console.log(l.gray('\u{1F4A1} Consider using a "polyglot" workspace profile for multi-language projects.'));}}catch{}}}if(qt(e[2]||""))return await ur(e);if(lt(e[2]||""))return await gr(e);let r=e.includes("--create-workspace"),i$1=e.includes("--no-workspace"),n=e.includes("--yes")||e.includes("-y"),a=e.includes("--skip-git")||e.includes("--no-git");if(!!!so(process.cwd())){if(r)await i(process.cwd(),{skipGit:a,yes:n,userConfig:await a$2()});else if(!i$1)if(n)await i(process.cwd(),{skipGit:a,yes:true,userConfig:await a$2()});else {let{createWs:f}=await xe.prompt([{type:"confirm",name:"createWs",message:"This project will be created outside a RapidKit workspace. Create and register a workspace here?",default:true}]);f&&await i(process.cwd(),{skipGit:a,yes:false,userConfig:await a$2()});}}let p=[...e.filter(f=>{let g=f.split("=")[0];return !o.has(f)&&!o.has(g)})],d=Y(process.cwd()),w=e.includes("--skip-install")||!!d?{...process.env,RAPIDKIT_SKIP_LOCKS:"1",RAPIDKIT_GENERATE_LOCKS:"0"}:void 0;try{await c$2();let f=await d$1(p,{cwd:process.cwd(),env:w});if(f===0&&d&&!e.includes("--skip-install")&&(console.log(l.gray("\u2139\uFE0F Fast create mode (workspace): dependencies were deferred.")),console.log(l.white(" Next: cd <project-name> && npx rapidkit init"))),f===0){let g=d||Y(process.cwd());if(g){try{let x=e[3];if(x){let T=e.indexOf("--output"),C=T>=0?e[T+1]:".",E=h.resolve(process.cwd(),C,x),G=h.join(g,".python-version"),N=h.join(E,".python-version");if(_.existsSync(G)&&_.existsSync(E)){let $=_.readFileSync(G,"utf-8");_.writeFileSync(N,$.trim()+`
3531
3531
  `),a$1.debug(`Synced Python version ${$.trim()} from workspace to ${x}`);}}}catch(x){a$1.debug("Could not sync Python version from workspace:",x);}let{syncWorkspaceProjects:R}=await import('./workspace-KRZ3DWL4.js');await R(g,true);}}return f}catch(f){let g=oo(f);return g?await io(p,g):(process.stderr.write(`RapidKit (npm) failed to run the Python core engine: ${f?.message??f}
3532
3532
  `),1)}}if(e[0]==="create"&&e[1]!=="project")try{await c$2();let t=await d$1(e,{cwd:process.cwd()});if(t===0){let r=Y(process.cwd());if(r){let{syncWorkspaceProjects:i}=await import('./workspace-KRZ3DWL4.js');await i(r,true);}}return t}catch(t){let r=oo(t);return r?await io(e,r):(process.stderr.write(`RapidKit (npm) failed to run the Python core engine: ${t?.message??t}
3533
3533
  `),1)}return await c$2(),await d$1(e,{cwd:process.cwd()})}catch(t){let r=oo(t);return r?await io(e,r):(process.stderr.write(`RapidKit (npm) failed to run the Python core engine: ${t?.message??t}
3534
- `),1)}}var mr=["init","dev","start","build","test","docs","lint","format","create","help","--help","-h"],ys=["doctor","workspace","bootstrap","setup","cache","mirror","ai","config","shell"],ws=["doctor","workspace","ai","config","shell"],vs=["bootstrap","setup","cache","mirror"],xr=["lint","format","docs"],ks=["init"],Pr=["build","dev","start","test"],fr=[...Pr,...xr];function Ft(e){return !!e&&ys.includes(e)}function hr(e){return !!e&&ws.includes(e)}function bs(e){return !!e&&vs.includes(e)}function Er(e){return _.existsSync(h.join(e,".rapidkit-workspace"))||_.existsSync(h.join(e,".rapidkit","workspace.json"))}function Ir(e){let o=e;for(;;){let t=h.join(o,".rapidkit","context.json");if(_.existsSync(t))return t;let r=h.dirname(o);if(r===o)break;o=r;}return null}function so(e){let o=e;for(;;){let t=h.join(o,".rapidkit-workspace");if(_.existsSync(t))return t;let r=h.dirname(o);if(r===o)break;o=r;}return null}function Y(e){let o=e;for(;;){let t=h.join(o,".rapidkit-workspace");if(_.existsSync(t))return o;let r=h.dirname(o);if(r===o)break;o=r;}return null}function Rs(e){let o=e;for(;;){let t=h.join(o,".rapidkit-workspace"),r=h.join(o,".rapidkit","workspace.json");if(!_.existsSync(t)&&_.existsSync(r))return o;let i=h.dirname(o);if(i===o)break;o=i;}return null}var Tr={enforce_workspace_marker:true,enforce_toolchain_lock:false,disallow_untrusted_tool_sources:false,enforce_compatibility_matrix:false,require_mirror_lock_for_offline:true};function _s(e){return e&&e.match(/^[\t ]*mode:\s*(warn|strict)\s*(?:#.*)?$/m)?.[1]==="strict"?"strict":"warn"}function ct(e,o){let t=e.match(new RegExp(`^[\\t ]*${o}:\\s*(true|false)\\s*(?:#.*)?$`,"m"));return t?t[1]==="true":Tr[o]}function yr(e){let o=e??"";return {mode:_s(o),dependency_sharing_mode:Ar(o),rules:{enforce_workspace_marker:ct(o,"enforce_workspace_marker"),enforce_toolchain_lock:ct(o,"enforce_toolchain_lock"),disallow_untrusted_tool_sources:ct(o,"disallow_untrusted_tool_sources"),enforce_compatibility_matrix:ct(o,"enforce_compatibility_matrix"),require_mirror_lock_for_offline:ct(o,"require_mirror_lock_for_offline")}}}function wr(e,o,t){let r=`${o}: ${t}`,i=o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`^[\\t ]*${i}:\\s*.*$`,"m");if(n.test(e))return e.replace(n,r);let a=/^[\t ]*rules:\s*(?:#.*)?$/m;return a.test(e)?e.replace(a,`${r}
3534
+ `),1)}}var mr=["init","dev","start","build","test","docs","lint","format","create","help","--help","-h"],ys=["doctor","workspace","bootstrap","setup","cache","mirror","ai","config","shell"],ws=["doctor","workspace","ai","config","shell"],vs=["bootstrap","setup","cache","mirror"],xr=["lint","format","docs"],ks=["init"],Pr=["build","dev","start","test"],fr=[...Pr,...xr];function Ft(e){return !!e&&ys.includes(e)}function hr(e){return !!e&&ws.includes(e)}function bs(e){return !!e&&vs.includes(e)}function Er(e){return _.existsSync(h.join(e,".rapidkit-workspace"))||_.existsSync(h.join(e,".rapidkit","workspace.json"))}function Ir(e){let o=e;for(;;){let t=h.join(o,".rapidkit","context.json");if(_.existsSync(t))return t;let r=h.dirname(o);if(r===o)break;o=r;}return null}function so(e){let o=e;for(;;){let t=h.join(o,".rapidkit-workspace");if(_.existsSync(t))return t;let r=h.dirname(o);if(r===o)break;o=r;}return null}function Y(e){let o=e;for(;;){let t=h.join(o,".rapidkit-workspace");if(_.existsSync(t))return o;let r=h.dirname(o);if(r===o)break;o=r;}return null}async function Rs(e,o=process.cwd(),t=process.platform){if(!a(t))return {detected:false};if(!(e.workspaceFlag||e.scope==="workspace"))return {detected:false};let i=i$1(o,t);for(let n of i){if(!await b.pathExists(n))continue;let a=n.toLowerCase();if(a.endsWith("rapidkit.cmd")||a.endsWith("rapidkit.exe"))return {detected:true,candidatePath:n,reason:"Found workspace-local rapidkit launcher on Windows."}}return {detected:false}}function _s(e){let o=e;for(;;){let t=h.join(o,".rapidkit-workspace"),r=h.join(o,".rapidkit","workspace.json");if(!_.existsSync(t)&&_.existsSync(r))return o;let i=h.dirname(o);if(i===o)break;o=i;}return null}var Tr={enforce_workspace_marker:true,enforce_toolchain_lock:false,disallow_untrusted_tool_sources:false,enforce_compatibility_matrix:false,require_mirror_lock_for_offline:true};function Cs(e){return e&&e.match(/^[\t ]*mode:\s*(warn|strict)\s*(?:#.*)?$/m)?.[1]==="strict"?"strict":"warn"}function ct(e,o){let t=e.match(new RegExp(`^[\\t ]*${o}:\\s*(true|false)\\s*(?:#.*)?$`,"m"));return t?t[1]==="true":Tr[o]}function yr(e){let o=e??"";return {mode:Cs(o),dependency_sharing_mode:Ar(o),rules:{enforce_workspace_marker:ct(o,"enforce_workspace_marker"),enforce_toolchain_lock:ct(o,"enforce_toolchain_lock"),disallow_untrusted_tool_sources:ct(o,"disallow_untrusted_tool_sources"),enforce_compatibility_matrix:ct(o,"enforce_compatibility_matrix"),require_mirror_lock_for_offline:ct(o,"require_mirror_lock_for_offline")}}}function wr(e,o,t){let r=`${o}: ${t}`,i=o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`^[\\t ]*${i}:\\s*.*$`,"m");if(n.test(e))return e.replace(n,r);let a=/^[\t ]*rules:\s*(?:#.*)?$/m;return a.test(e)?e.replace(a,`${r}
3535
3535
  rules:`):`${e.endsWith(`
3536
3536
  `)?e:`${e}
3537
3537
  `}${r}
3538
- `}function Cs(e,o,t){let r=` ${o}: ${t?"true":"false"}`,i=o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`^[\\t ]+${i}:\\s*.*$`,"m");if(n.test(e))return e.replace(n,r);let a=/^[\t ]*rules:\s*(?:#.*)?$/m;return a.test(e)?e.replace(a,`rules:
3538
+ `}function Ss(e,o,t){let r=` ${o}: ${t?"true":"false"}`,i=o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`^[\\t ]+${i}:\\s*.*$`,"m");if(n.test(e))return e.replace(n,r);let a=/^[\t ]*rules:\s*(?:#.*)?$/m;return a.test(e)?e.replace(a,`rules:
3539
3539
  ${r}`):`${e.endsWith(`
3540
3540
  `)?e:`${e}
3541
3541
  `}rules:
3542
3542
  ${r}
3543
- `}function Ss(){return ['version: "1.0"','mode: warn # "warn" or "strict"','dependency_sharing_mode: isolated # "isolated" or "shared-runtime-caches" or "shared-node-deps"',"# change profile (recommended): npx rapidkit bootstrap --profile polyglot","# change mode/dependency manually: edit this file and rerun npx rapidkit init","rules:"," enforce_workspace_marker: true"," enforce_toolchain_lock: false"," disallow_untrusted_tool_sources: false"," enforce_compatibility_matrix: false"," require_mirror_lock_for_offline: true",""].join(`
3544
- `)}async function vr(e){let o=h.join(e,".rapidkit","policies.yml");return await b.pathExists(o)?_.promises.readFile(o,"utf-8"):Ss()}async function xs(e,o){let t=h.join(e,".rapidkit"),r=h.join(t,"policies.yml");await b.ensureDir(t);let i=o.endsWith(`
3543
+ `}function xs(){return ['version: "1.0"','mode: warn # "warn" or "strict"','dependency_sharing_mode: isolated # "isolated" or "shared-runtime-caches" or "shared-node-deps"',"# change profile (recommended): npx rapidkit bootstrap --profile polyglot","# change mode/dependency manually: edit this file and rerun npx rapidkit init","rules:"," enforce_workspace_marker: true"," enforce_toolchain_lock: false"," disallow_untrusted_tool_sources: false"," enforce_compatibility_matrix: false"," require_mirror_lock_for_offline: true",""].join(`
3544
+ `)}async function vr(e){let o=h.join(e,".rapidkit","policies.yml");return await b.pathExists(o)?_.promises.readFile(o,"utf-8"):xs()}async function Ps(e,o){let t=h.join(e,".rapidkit"),r=h.join(t,"policies.yml");await b.ensureDir(t);let i=o.endsWith(`
3545
3545
  `)?o:`${o}
3546
- `;await _.promises.writeFile(r,i,"utf-8");}function Ps(e){let o=e.trim().toLowerCase();return o==="true"||o==="1"||o==="on"?true:o==="false"||o==="0"||o==="off"?false:null}function Ar(e){if(!e)return "isolated";let t=e.match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();return t==="shared-runtime-caches"||t==="shared-node-deps"||t==="isolated"?t:"isolated"}function Or(e){if(!e)return {mode:"isolated",status:"skipped",message:"No policies.yml found; dependency_sharing_mode defaults to isolated."};let o=e.match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m);if(!o)return {mode:"isolated",status:"skipped",message:"dependency_sharing_mode is not set; defaulting to isolated."};let t=o[1].toLowerCase();return t==="isolated"||t==="shared-runtime-caches"||t==="shared-node-deps"?{mode:t,status:"passed",message:`dependency_sharing_mode is valid: ${t}.`}:{mode:"isolated",status:"failed",message:`Invalid dependency_sharing_mode: ${t}. Use one of: isolated, shared-runtime-caches, shared-node-deps.`}}async function Nr(e,o){let t=Y(e),r=t?h.join(t,".rapidkit","policies.yml"):null,i="isolated";if(r&&await b.pathExists(r))try{let s=await _.promises.readFile(r,"utf-8"),c=Or(s);if(c.status==="failed")return console.log(l.red(`\u274C ${c.message}`)),{ok:false,code:1};i=c.mode;}catch{return console.log(l.red("\u274C Failed to read workspace policy file (.rapidkit/policies.yml).")),{ok:false,code:1}}let n=process.env.RAPIDKIT_DEP_SHARING_MODE,a=process.env.RAPIDKIT_WORKSPACE_PATH;process.env.RAPIDKIT_DEP_SHARING_MODE=i,t&&(process.env.RAPIDKIT_WORKSPACE_PATH=t);try{return {ok:true,value:await o()}}finally{typeof n>"u"?delete process.env.RAPIDKIT_DEP_SHARING_MODE:process.env.RAPIDKIT_DEP_SHARING_MODE=n,typeof a>"u"?delete process.env.RAPIDKIT_WORKSPACE_PATH:process.env.RAPIDKIT_WORKSPACE_PATH=a;}}async function W(e,o,t){return await new Promise(r=>{let i=spawn(e,o,{stdio:"inherit",cwd:t,shell:b$3()});i.on("close",n=>r(n??1)),i.on("error",()=>r(1));})}async function Xe(e,o){await b.outputFile(e,`${JSON.stringify(o,null,2)}
3547
- `,"utf-8");}async function Es(e){let o=new Set(["go-only"]);try{let r=h.join(e,".rapidkit","workspace.json"),i=JSON.parse(await _.promises.readFile(r,"utf-8"));if(o.has(i.profile??""))return 0}catch{}let t="poetry";try{let{readWorkspaceMarker:r}=await import('./workspace-marker-IOPQ42A7.js'),n=(await r(e))?.metadata?.npm?.installMethod;(n==="poetry"||n==="venv"||n==="pipx"||n==="pip")&&(t=n);}catch{}if(t==="poetry"||t==="venv"){let r=h.join(e,"pyproject.toml"),i=false;try{i=(await _.promises.readFile(r,"utf-8")).includes("rapidkit-core");}catch{i=false;}let n=process.env.RAPIDKIT_DEV_PATH,a=n?await b.pathExists(n):false;if(i){let s=gs(e);if(!await b.pathExists(s)){let d=await ms(e);if(d!==0)return d}let p=await W(s,a&&n?["-m","pip","install",n,"--quiet","--disable-pip-version-check"]:["-m","pip","install","rapidkit-core","--quiet","--disable-pip-version-check"],e);if(p!==0)return p}else {let s=await W("poetry",["install","--no-root"],e);if(s!==0)return s;let c=await W("poetry",["add","rapidkit-core"],e);if(c!==0)return c}try{let{writeWorkspaceLauncher:s}=await import('./create-PIVSRLDS.js');await s(e,"poetry");}catch{}return 0}return 0}async function jr(e){let o=await _.promises.readdir(e,{withFileTypes:true}),t=[];for(let r of o){if(!r.isDirectory()||r.name.startsWith("."))continue;let i=h.join(e,r.name),n=h.join(i,".rapidkit","context.json"),a=h.join(i,".rapidkit","project.json");(await b.pathExists(n)||await b.pathExists(a))&&t.push(i);}return t}function Is(e){let o="my-workspace",t=1;for(;;){let r=t===1?o:`${o}-${t}`,i=h.join(e,r);if(!_.existsSync(i))return {name:r,targetPath:i};t+=1;}}async function Mt(e){let t=await He("go",{runCommandInCwd:W,runCoreRapidkit:d$1}).initProject(e);return t.message&&console.log(l.red(`\u274C ${t.message}`)),t.exitCode}async function dt(e,o){let t=He("node",{runCommandInCwd:W,runCoreRapidkit:d$1});return e==="init"?(await t.initProject(o)).exitCode:e==="dev"?(await t.runDev(o)).exitCode:e==="test"?(await t.runTest(o)).exitCode:e==="build"?(await t.runBuild(o)).exitCode:(await t.runStart(o)).exitCode}async function Ts(e,o=ao){let t=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof t>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let n=function(I){if(!I)return null;let O=I.trim().toLowerCase();return O==="minimal"||O==="go-only"||O==="python-only"||O==="node-only"||O==="polyglot"||O==="enterprise"?O:null},a=function(I){let j=I.match(/^\s*mode:\s*([a-zA-Z]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase()==="strict"?"strict":"warn",ge=(U,Te)=>{let Pe=I.match(new RegExp(`^\\s*${U}:\\s*(true|false)\\s*(?:#.*)?$`,"m"));return Pe?Pe[1].toLowerCase()==="true":Te};return {mode:j,dependency_sharing_mode:Ar(I),rules:{enforce_workspace_marker:ge("enforce_workspace_marker",true),enforce_toolchain_lock:ge("enforce_toolchain_lock",false),disallow_untrusted_tool_sources:ge("disallow_untrusted_tool_sources",false),enforce_compatibility_matrix:ge("enforce_compatibility_matrix",false),require_mirror_lock_for_offline:ge("require_mirror_lock_for_offline",true)}}};let s=["init"],c,p=false,d=false,u=false;for(let I=1;I<e.length;I+=1){let O=e[I];if(O==="--ci"){p=true;continue}if(O==="--offline"){d=true;continue}if(O==="--json"){u=true;continue}if(O==="--profile"){let M=e[I+1];if(!M||M.startsWith("-"))return console.log(l.yellow("Usage: rapidkit bootstrap [path] [--profile <minimal|go-only|python-only|node-only|polyglot|enterprise>] [--ci] [--offline] [--json]")),1;c=M,I+=1;continue}if(O.startsWith("--profile=")){c=O.slice(10);continue}s.push(O);}let m=n(c);if(c&&!m)return console.log(l.red(`Invalid profile: ${c}. Use one of: minimal, go-only, python-only, node-only, polyglot, enterprise.`)),1;let w=process.cwd(),f$1=Y(w);f$1||(f$1=Rs(w));let g=[],R=null,x=null;if(f$1)try{let I=h.join(f$1,".rapidkit","workspace.json"),O=await _.promises.readFile(I,"utf-8"),M=JSON.parse(O);x=n(M.profile);}catch{x=null;}let T=["minimal","python-only","node-only","go-only","polyglot","enterprise"],C={minimal:"minimal \u2014 Foundation files only (fastest bootstrap, mixed projects)","python-only":"python-only \u2014 Python + Poetry (FastAPI, Django, ML pipelines)","node-only":"node-only \u2014 Node.js runtime (NestJS, Express, Next.js)","go-only":"go-only \u2014 Go runtime (Fiber, Gin, gRPC, microservices)",polyglot:"polyglot \u2014 Python + Node.js + Go multi-runtime workspace",enterprise:"enterprise \u2014 Polyglot + governance + Sigstore verification"},P=m;if(!!f$1&&!m&&!p&&!u&&!!process.stdin.isTTY&&!!process.stdout.isTTY){let I=x||"minimal",{chosenProfile:O}=await xe.prompt([{type:"rawlist",name:"chosenProfile",message:`Select workspace profile for bootstrap (current: ${I})`,choices:T.map(M=>({name:M===I?`${C[M]} \u2190 current`:C[M],value:M})),default:T.indexOf(I)}]);P=O;}let N=P||x||"minimal";if(f$1)try{let O=N==="python-only"||N==="polyglot"||N==="enterprise"?"poetry":"venv",M;try{let U=(await _.promises.readFile(h.join(f$1,".python-version"),"utf-8")).trim();U&&(M=U);}catch{}let j=await f(f$1,{workspaceName:h.basename(f$1),installMethod:O,pythonVersion:M,profile:N,writeMarker:true,writeGitignore:true,onlyIfMissing:true});g.push({id:"workspace.legacy.sync",status:j.length>0?"passed":"skipped",message:j.length>0?`Legacy workspace foundation synchronized: ${j.join(", ")}`:"Workspace foundation files are already up to date."});}catch(I){g.push({id:"workspace.legacy.sync",status:"failed",message:`Failed to synchronize legacy workspace foundation files: ${I.message}`});}if(f$1&&P&&P!==x)try{let I=h.join(f$1,".rapidkit","workspace.json"),O=await _.promises.readFile(I,"utf-8"),M=JSON.parse(O);M.profile=P,await _.promises.writeFile(I,JSON.stringify(M,null,2)+`
3548
- `,"utf-8");}catch{}let $={mode:"warn",dependency_sharing_mode:"isolated",rules:{enforce_workspace_marker:true,enforce_toolchain_lock:false,disallow_untrusted_tool_sources:false,enforce_compatibility_matrix:false,require_mirror_lock_for_offline:true}},Re=null;if(f$1)try{let I=await _.promises.readFile(h.join(f$1,".rapidkit","policies.yml"),"utf-8");Re=I,$=a(I);}catch{g.push({id:"policy.file",status:"skipped",message:"No workspace policy file found; using default bootstrap policy."});}else g.push({id:"workspace.detect",status:"skipped",message:"No workspace marker found; bootstrap runs in project/single-path mode."});if(f$1){let I=Or(Re);$.dependency_sharing_mode=I.mode,g.push({id:"policy.schema.dependency_sharing_mode",status:I.status,message:I.message}),g.push({id:"policy.dependency_sharing_mode.effective",status:"passed",message:$.dependency_sharing_mode==="isolated"?"Effective dependency mode: isolated (default secure mode).":$.dependency_sharing_mode==="shared-node-deps"?"Effective dependency mode: shared-node-deps (Node projects share workspace-level caches).":"Effective dependency mode: shared-runtime-caches (Node/Python/Go share workspace-level caches)."});let O=_.existsSync(h.join(f$1,".rapidkit-workspace"));g.push({id:"policy.enforce_workspace_marker",status:!$.rules.enforce_workspace_marker||O?"passed":"failed",message:!$.rules.enforce_workspace_marker||O?"Workspace marker policy satisfied.":"Workspace marker policy failed: .rapidkit-workspace is missing."});let M=_.existsSync(h.join(f$1,".rapidkit","toolchain.lock"));g.push({id:"policy.enforce_toolchain_lock",status:!$.rules.enforce_toolchain_lock||M?"passed":"failed",message:!$.rules.enforce_toolchain_lock||M?"Toolchain lock policy satisfied.":"Toolchain lock policy failed: .rapidkit/toolchain.lock is missing."});let j=process.env.RAPIDKIT_TRUSTED_SOURCES==="1"||_.existsSync(h.join(f$1,".rapidkit","trusted-sources.lock"));g.push({id:"policy.disallow_untrusted_tool_sources",status:!$.rules.disallow_untrusted_tool_sources||j?"passed":"failed",message:!$.rules.disallow_untrusted_tool_sources||j?"Trusted tool sources policy satisfied.":"Trusted tool sources policy failed: set RAPIDKIT_TRUSTED_SOURCES=1 or provide .rapidkit/trusted-sources.lock."});let ge=h.join(f$1,".rapidkit","compatibility-matrix.json"),U=_.existsSync(ge),Te=$.rules.enforce_compatibility_matrix;if(g.push({id:"policy.enforce_compatibility_matrix",status:!Te||U?"passed":"failed",message:!Te||U?"Compatibility matrix policy satisfied.":"Compatibility matrix policy failed: .rapidkit/compatibility-matrix.json is missing."}),U)try{let F=await _.promises.readFile(ge,"utf-8"),X=JSON.parse(F),gt=!!X&&typeof X=="object";g.push({id:"compatibility.matrix.parse",status:gt?"passed":"failed",message:gt?"Compatibility matrix parsed successfully.":"Compatibility matrix parse failed: invalid JSON object."});}catch{g.push({id:"compatibility.matrix.parse",status:"failed",message:"Compatibility matrix parse failed: invalid JSON."});}let Pe=h.join(f$1,".rapidkit","mirror-config.json"),ie=h.join(f$1,".rapidkit","mirror.lock"),Ae=_.existsSync(Pe),Ee=_.existsSync(ie),ut={};if(Ae)try{ut=JSON.parse(await _.promises.readFile(Pe,"utf-8")),g.push({id:"mirror.config.parse",status:"passed",message:"Mirror configuration parsed successfully."});}catch{g.push({id:"mirror.config.parse",status:"failed",message:"Mirror configuration parse failed: invalid JSON in .rapidkit/mirror-config.json."});}let Ht=await to(f$1,{ciMode:p,offlineMode:d});if(g.push(...Ht.checks.map(F=>({id:F.id,status:F.status,message:F.message}))),R=Ht.details,Ht.details.lockWritten&&(Ee=true),d){let F=process.env.RAPIDKIT_MIRROR_ENABLED==="1"||ut.enabled===true;g.push({id:"offline.mirror.enabled",status:F?"passed":"failed",message:F?"Offline mode mirror is enabled.":'Offline mode requires mirror enablement (set RAPIDKIT_MIRROR_ENABLED=1 or .rapidkit/mirror-config.json {"enabled": true}).'});let X=$.rules.require_mirror_lock_for_offline;g.push({id:"offline.mirror.lock",status:!X||Ee?"passed":"failed",message:!X||Ee?"Offline mode mirror lock policy satisfied.":"Offline mode mirror lock policy failed: .rapidkit/mirror.lock is missing."});}else g.push({id:"offline.mirror.enabled",status:"skipped",message:"Offline mirror checks skipped (offline mode is disabled)."});let Dr=await jr(f$1),de=new Set;for(let F of Dr){let X=Se(F);if(pe(X,F)){de.add("go");continue}if(ue(X,F)){de.add("node");continue}if(me(X,F)){de.add("python");continue}de.add("unknown");}if(N==="go-only"){let F=de.size===0||[...de].every(X=>X==="go");g.push({id:"profile.go-only",status:F?"passed":"failed",message:F?"go-only profile validated for discovered projects.":`go-only profile mismatch: detected runtimes [${[...de].join(", ")}].`});}else if(N==="python-only"){let F=de.size===0||[...de].every(X=>X==="python");g.push({id:"profile.python-only",status:F?"passed":"failed",message:F?"python-only profile validated for discovered projects.":`python-only profile mismatch: detected runtimes [${[...de].join(", ")}].`});}else if(N==="node-only"){let F=de.size===0||[...de].every(X=>X==="node");g.push({id:"profile.node-only",status:F?"passed":"failed",message:F?"node-only profile validated for discovered projects.":`node-only profile mismatch: detected runtimes [${[...de].join(", ")}].`});}else if(N==="minimal"){let F=[...de].filter(gt=>gt!=="unknown"),X=F.length<=1;g.push({id:"profile.minimal",status:X?"passed":"failed",message:X?"minimal profile is compatible with detected runtime mix.":`minimal profile mismatch: multiple runtimes detected [${F.join(", ")}].`});}else N==="enterprise"&&(g.push({id:"profile.enterprise.ci",status:p?"passed":"failed",message:p?"enterprise profile running with --ci.":"enterprise profile expects --ci for deterministic non-interactive mode."}),g.push({id:"profile.enterprise.compatibility-matrix",status:U?"passed":"failed",message:U?"enterprise profile has compatibility matrix.":"enterprise profile requires .rapidkit/compatibility-matrix.json."}),g.push({id:"profile.enterprise.mirror-config",status:Ae?"passed":"failed",message:Ae?"enterprise profile has mirror configuration.":"enterprise profile requires .rapidkit/mirror-config.json."}));}p&&(process.env.RAPIDKIT_BOOTSTRAP_CI="1"),d&&(process.env.RAPIDKIT_OFFLINE_MODE="1");let we=g.some(I=>I.id.startsWith("policy.schema.")&&I.status==="failed")||$.mode==="strict"&&g.some(I=>I.status==="failed"),fe=f$1||w,Ve=h.join(fe,".rapidkit","reports"),z=new Date().toISOString().replace(/[:.]/g,"-"),L=h.join(Ve,`bootstrap-compliance-${z}.json`),S=h.join(Ve,"bootstrap-compliance.latest.json"),se={command:"bootstrap",timestamp:new Date().toISOString(),workspacePath:f$1,profile:N,options:{ci:p,offline:d,strict:$.mode==="strict"},policyMode:$.mode,policyRules:$.rules,mirrorLifecycle:R,checks:g};if(we){let I={...se,result:"blocked",initExitCode:null};return await b.ensureDir(Ve),await Xe(L,I),await Xe(S,I),u?process.stdout.write(`${JSON.stringify(I,null,2)}
3549
- `):(console.log(l.red("\u274C Bootstrap blocked by strict policy checks.")),console.log(l.gray(`Compliance report: ${L}`))),1}let ae=0;u||(ae=await o(s));let H=g.filter(I=>I.status==="failed").length,re=ae!==0?"failed":H>0?"ok_with_warnings":"ok",le={...se,result:re,initExitCode:ae};if(await b.ensureDir(Ve),await Xe(L,le),await Xe(S,le),u)process.stdout.write(`${JSON.stringify(le,null,2)}
3550
- `);else {let I=g.filter(O=>O.status==="failed").length;I>0&&console.log(l.yellow(`\u26A0\uFE0F Bootstrap completed with ${I} policy/profile warnings.`)),console.log(l.gray(`Compliance report: ${L}`));}return ae}finally{typeof t>"u"?delete process.env.RAPIDKIT_SKIP_LOCK_SYNC:process.env.RAPIDKIT_SKIP_LOCK_SYNC=t;}}async function As(e){let o=(e[1]||"").toLowerCase(),t=e.includes("--warm-deps")||e.includes("--warm-dependencies");if(!o||!["python","node","go"].includes(o))return console.log(l.yellow("Usage: rapidkit setup <python|node|go> [--warm-deps]")),1;let r=async(p,d)=>{if(p==="node"){if(!_.existsSync(h.join(d,"package.json")))return {exitCode:0,message:"Node warm-up skipped: package.json not found in current directory."};let m=_.existsSync(h.join(d,"pnpm-lock.yaml")),w=_.existsSync(h.join(d,"yarn.lock"));return m?{exitCode:await W("pnpm",["install","--lockfile-only","--ignore-scripts"],d)}:w?{exitCode:await W("yarn",["install","--ignore-scripts"],d)}:{exitCode:await W("npm",["install","--package-lock-only","--ignore-scripts"],d)}}return p==="go"?_.existsSync(h.join(d,"go.mod"))?{exitCode:await W("go",["mod","download"],d)}:{exitCode:0,message:"Go warm-up skipped: go.mod not found in current directory."}:{exitCode:0,message:"Dependency warm-up currently applies to node/go runtimes."}},i=He(o,{runCommandInCwd:W,runCoreRapidkit:(p,d)=>d$1(p,{...d,cwd:void 0})}),n=await i.checkPrereqs(),a=await i.doctorHints(process.cwd()),s=Y(process.cwd()),c=s||process.cwd();if(n.exitCode===0){console.log(l.green(`\u2705 ${o} prerequisites look good.`));let p=["python","node","go"].filter(d=>d!==o).join("/");if(console.log(l.gray(` Scope: validated ${o} runtime only. ${p} checks are optional unless your workspace profile uses them.`)),o==="python"&&console.log(l.gray(" Note: Poetry is recommended, but venv/pipx-based flows are supported in workspace creation.")),i.warmSetupCache&&((await i.warmSetupCache(c)).exitCode===0?console.log(l.gray(` ${o} cache warm-up completed.`)):console.log(l.yellow(` ${o} cache warm-up skipped (non-fatal).`))),t){let d=await r(o,c),u=/skipped/i.test(d.message||"");d.message&&console.log(l.gray(` ${d.message}`)),d.exitCode===0&&!u?console.log(l.gray(` ${o} dependency warm-up completed (--warm-deps).`)):d.exitCode!==0&&console.log(l.yellow(` ${o} dependency warm-up failed (non-fatal).`));}if(s)try{let d=h.join(s,".rapidkit","toolchain.lock"),u={};try{u=JSON.parse(await _.promises.readFile(d,"utf-8"));}catch{}(!u.runtime||typeof u.runtime!="object")&&(u.runtime={});let m=u.runtime;if(o==="python"){let w=null;try{let{execa:f}=await import('execa');for(let g of co()){let x=await f(g,g==="py"?["-3","--version"]:["--version"],{cwd:s,stdio:"pipe",reject:false,timeout:3e3});if(x.exitCode===0){let C=(x.stdout||x.stderr||"").match(/Python\s+(\S+)/);if(w=C?C[1]:null,w)break}}}catch{}m.python={...m.python||{},version:w,last_setup:new Date().toISOString()};}else if(o==="node")m.node={...m.node||{},version:process.version,last_setup:new Date().toISOString()};else if(o==="go"){let w=null;try{let{execa:f}=await import('execa'),R=((await f("go",["version"],{cwd:s,stdio:"pipe"})).stdout||"").match(/go(\d+\.\d+(?:\.\d+)?)/i);w=R?R[1]:null;}catch{}m.go={...m.go||{},version:w,last_setup:new Date().toISOString()};}u.updated_at=new Date().toISOString(),await _.promises.writeFile(d,JSON.stringify(u,null,2)+`
3546
+ `;await _.promises.writeFile(r,i,"utf-8");}function Es(e){let o=e.trim().toLowerCase();return o==="true"||o==="1"||o==="on"?true:o==="false"||o==="0"||o==="off"?false:null}function Ar(e){if(!e)return "isolated";let t=e.match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase();return t==="shared-runtime-caches"||t==="shared-node-deps"||t==="isolated"?t:"isolated"}function Or(e){if(!e)return {mode:"isolated",status:"skipped",message:"No policies.yml found; dependency_sharing_mode defaults to isolated."};let o=e.match(/^\s*dependency_sharing_mode:\s*([a-zA-Z\-]+)\s*(?:#.*)?$/m);if(!o)return {mode:"isolated",status:"skipped",message:"dependency_sharing_mode is not set; defaulting to isolated."};let t=o[1].toLowerCase();return t==="isolated"||t==="shared-runtime-caches"||t==="shared-node-deps"?{mode:t,status:"passed",message:`dependency_sharing_mode is valid: ${t}.`}:{mode:"isolated",status:"failed",message:`Invalid dependency_sharing_mode: ${t}. Use one of: isolated, shared-runtime-caches, shared-node-deps.`}}async function Nr(e,o){let t=Y(e),r=t?h.join(t,".rapidkit","policies.yml"):null,i="isolated";if(r&&await b.pathExists(r))try{let s=await _.promises.readFile(r,"utf-8"),c=Or(s);if(c.status==="failed")return console.log(l.red(`\u274C ${c.message}`)),{ok:false,code:1};i=c.mode;}catch{return console.log(l.red("\u274C Failed to read workspace policy file (.rapidkit/policies.yml).")),{ok:false,code:1}}let n=process.env.RAPIDKIT_DEP_SHARING_MODE,a=process.env.RAPIDKIT_WORKSPACE_PATH;process.env.RAPIDKIT_DEP_SHARING_MODE=i,t&&(process.env.RAPIDKIT_WORKSPACE_PATH=t);try{return {ok:true,value:await o()}}finally{typeof n>"u"?delete process.env.RAPIDKIT_DEP_SHARING_MODE:process.env.RAPIDKIT_DEP_SHARING_MODE=n,typeof a>"u"?delete process.env.RAPIDKIT_WORKSPACE_PATH:process.env.RAPIDKIT_WORKSPACE_PATH=a;}}async function W(e,o,t){return await new Promise(r=>{let i=spawn(e,o,{stdio:"inherit",cwd:t,shell:b$3()});i.on("close",n=>r(n??1)),i.on("error",()=>r(1));})}async function Ze(e,o){await b.outputFile(e,`${JSON.stringify(o,null,2)}
3547
+ `,"utf-8");}async function Is(e){let o=new Set(["go-only"]);try{let r=h.join(e,".rapidkit","workspace.json"),i=JSON.parse(await _.promises.readFile(r,"utf-8"));if(o.has(i.profile??""))return 0}catch{}let t="poetry";try{let{readWorkspaceMarker:r}=await import('./workspace-marker-IOPQ42A7.js'),n=(await r(e))?.metadata?.npm?.installMethod;(n==="poetry"||n==="venv"||n==="pipx"||n==="pip")&&(t=n);}catch{}if(t==="poetry"||t==="venv"){let r=h.join(e,"pyproject.toml"),i=false;try{i=(await _.promises.readFile(r,"utf-8")).includes("rapidkit-core");}catch{i=false;}let n=process.env.RAPIDKIT_DEV_PATH,a=n?await b.pathExists(n):false;if(i){let s=gs(e);if(!await b.pathExists(s)){let d=await ms(e);if(d!==0)return d}let p=await W(s,a&&n?["-m","pip","install",n,"--quiet","--disable-pip-version-check"]:["-m","pip","install","rapidkit-core","--quiet","--disable-pip-version-check"],e);if(p!==0)return p}else {let s=await W("poetry",["install","--no-root"],e);if(s!==0)return s;let c=await W("poetry",["add","rapidkit-core"],e);if(c!==0)return c}try{let{writeWorkspaceLauncher:s}=await import('./create-PIVSRLDS.js');await s(e,"poetry");}catch{}return 0}return 0}async function jr(e){let o=await _.promises.readdir(e,{withFileTypes:true}),t=[];for(let r of o){if(!r.isDirectory()||r.name.startsWith("."))continue;let i=h.join(e,r.name),n=h.join(i,".rapidkit","context.json"),a=h.join(i,".rapidkit","project.json");(await b.pathExists(n)||await b.pathExists(a))&&t.push(i);}return t}function Ts(e){let o="my-workspace",t=1;for(;;){let r=t===1?o:`${o}-${t}`,i=h.join(e,r);if(!_.existsSync(i))return {name:r,targetPath:i};t+=1;}}async function Mt(e){let t=await He("go",{runCommandInCwd:W,runCoreRapidkit:d$1}).initProject(e);return t.message&&console.log(l.red(`\u274C ${t.message}`)),t.exitCode}async function dt(e,o){let t=He("node",{runCommandInCwd:W,runCoreRapidkit:d$1});return e==="init"?(await t.initProject(o)).exitCode:e==="dev"?(await t.runDev(o)).exitCode:e==="test"?(await t.runTest(o)).exitCode:e==="build"?(await t.runBuild(o)).exitCode:(await t.runStart(o)).exitCode}async function As(e,o=ao){let t=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof t>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let n=function(I){if(!I)return null;let O=I.trim().toLowerCase();return O==="minimal"||O==="go-only"||O==="python-only"||O==="node-only"||O==="polyglot"||O==="enterprise"?O:null},a=function(I){let j=I.match(/^\s*mode:\s*([a-zA-Z]+)\s*(?:#.*)?$/m)?.[1]?.toLowerCase()==="strict"?"strict":"warn",ge=(U,Te)=>{let Pe=I.match(new RegExp(`^\\s*${U}:\\s*(true|false)\\s*(?:#.*)?$`,"m"));return Pe?Pe[1].toLowerCase()==="true":Te};return {mode:j,dependency_sharing_mode:Ar(I),rules:{enforce_workspace_marker:ge("enforce_workspace_marker",true),enforce_toolchain_lock:ge("enforce_toolchain_lock",false),disallow_untrusted_tool_sources:ge("disallow_untrusted_tool_sources",false),enforce_compatibility_matrix:ge("enforce_compatibility_matrix",false),require_mirror_lock_for_offline:ge("require_mirror_lock_for_offline",true)}}};let s=["init"],c,p=false,d=false,u=false;for(let I=1;I<e.length;I+=1){let O=e[I];if(O==="--ci"){p=true;continue}if(O==="--offline"){d=true;continue}if(O==="--json"){u=true;continue}if(O==="--profile"){let M=e[I+1];if(!M||M.startsWith("-"))return console.log(l.yellow("Usage: rapidkit bootstrap [path] [--profile <minimal|go-only|python-only|node-only|polyglot|enterprise>] [--ci] [--offline] [--json]")),1;c=M,I+=1;continue}if(O.startsWith("--profile=")){c=O.slice(10);continue}s.push(O);}let m=n(c);if(c&&!m)return console.log(l.red(`Invalid profile: ${c}. Use one of: minimal, go-only, python-only, node-only, polyglot, enterprise.`)),1;let w=process.cwd(),f$1=Y(w);f$1||(f$1=_s(w));let g=[],R=null,x=null;if(f$1)try{let I=h.join(f$1,".rapidkit","workspace.json"),O=await _.promises.readFile(I,"utf-8"),M=JSON.parse(O);x=n(M.profile);}catch{x=null;}let T=["minimal","python-only","node-only","go-only","polyglot","enterprise"],C={minimal:"minimal \u2014 Foundation files only (fastest bootstrap, mixed projects)","python-only":"python-only \u2014 Python + Poetry (FastAPI, Django, ML pipelines)","node-only":"node-only \u2014 Node.js runtime (NestJS, Express, Next.js)","go-only":"go-only \u2014 Go runtime (Fiber, Gin, gRPC, microservices)",polyglot:"polyglot \u2014 Python + Node.js + Go multi-runtime workspace",enterprise:"enterprise \u2014 Polyglot + governance + Sigstore verification"},E=m;if(!!f$1&&!m&&!p&&!u&&!!process.stdin.isTTY&&!!process.stdout.isTTY){let I=x||"minimal",{chosenProfile:O}=await xe.prompt([{type:"rawlist",name:"chosenProfile",message:`Select workspace profile for bootstrap (current: ${I})`,choices:T.map(M=>({name:M===I?`${C[M]} \u2190 current`:C[M],value:M})),default:T.indexOf(I)}]);E=O;}let N=E||x||"minimal";if(f$1)try{let O=N==="python-only"||N==="polyglot"||N==="enterprise"?"poetry":"venv",M;try{let U=(await _.promises.readFile(h.join(f$1,".python-version"),"utf-8")).trim();U&&(M=U);}catch{}let j=await f(f$1,{workspaceName:h.basename(f$1),installMethod:O,pythonVersion:M,profile:N,writeMarker:true,writeGitignore:true,onlyIfMissing:true});g.push({id:"workspace.legacy.sync",status:j.length>0?"passed":"skipped",message:j.length>0?`Legacy workspace foundation synchronized: ${j.join(", ")}`:"Workspace foundation files are already up to date."});}catch(I){g.push({id:"workspace.legacy.sync",status:"failed",message:`Failed to synchronize legacy workspace foundation files: ${I.message}`});}if(f$1&&E&&E!==x)try{let I=h.join(f$1,".rapidkit","workspace.json"),O=await _.promises.readFile(I,"utf-8"),M=JSON.parse(O);M.profile=E,await _.promises.writeFile(I,JSON.stringify(M,null,2)+`
3548
+ `,"utf-8");}catch{}let $={mode:"warn",dependency_sharing_mode:"isolated",rules:{enforce_workspace_marker:true,enforce_toolchain_lock:false,disallow_untrusted_tool_sources:false,enforce_compatibility_matrix:false,require_mirror_lock_for_offline:true}},Re=null;if(f$1)try{let I=await _.promises.readFile(h.join(f$1,".rapidkit","policies.yml"),"utf-8");Re=I,$=a(I);}catch{g.push({id:"policy.file",status:"skipped",message:"No workspace policy file found; using default bootstrap policy."});}else g.push({id:"workspace.detect",status:"skipped",message:"No workspace marker found; bootstrap runs in project/single-path mode."});if(f$1){let I=Or(Re);$.dependency_sharing_mode=I.mode,g.push({id:"policy.schema.dependency_sharing_mode",status:I.status,message:I.message}),g.push({id:"policy.dependency_sharing_mode.effective",status:"passed",message:$.dependency_sharing_mode==="isolated"?"Effective dependency mode: isolated (default secure mode).":$.dependency_sharing_mode==="shared-node-deps"?"Effective dependency mode: shared-node-deps (Node projects share workspace-level caches).":"Effective dependency mode: shared-runtime-caches (Node/Python/Go share workspace-level caches)."});let O=_.existsSync(h.join(f$1,".rapidkit-workspace"));g.push({id:"policy.enforce_workspace_marker",status:!$.rules.enforce_workspace_marker||O?"passed":"failed",message:!$.rules.enforce_workspace_marker||O?"Workspace marker policy satisfied.":"Workspace marker policy failed: .rapidkit-workspace is missing."});let M=_.existsSync(h.join(f$1,".rapidkit","toolchain.lock"));g.push({id:"policy.enforce_toolchain_lock",status:!$.rules.enforce_toolchain_lock||M?"passed":"failed",message:!$.rules.enforce_toolchain_lock||M?"Toolchain lock policy satisfied.":"Toolchain lock policy failed: .rapidkit/toolchain.lock is missing."});let j=process.env.RAPIDKIT_TRUSTED_SOURCES==="1"||_.existsSync(h.join(f$1,".rapidkit","trusted-sources.lock"));g.push({id:"policy.disallow_untrusted_tool_sources",status:!$.rules.disallow_untrusted_tool_sources||j?"passed":"failed",message:!$.rules.disallow_untrusted_tool_sources||j?"Trusted tool sources policy satisfied.":"Trusted tool sources policy failed: set RAPIDKIT_TRUSTED_SOURCES=1 or provide .rapidkit/trusted-sources.lock."});let ge=h.join(f$1,".rapidkit","compatibility-matrix.json"),U=_.existsSync(ge),Te=$.rules.enforce_compatibility_matrix;if(g.push({id:"policy.enforce_compatibility_matrix",status:!Te||U?"passed":"failed",message:!Te||U?"Compatibility matrix policy satisfied.":"Compatibility matrix policy failed: .rapidkit/compatibility-matrix.json is missing."}),U)try{let F=await _.promises.readFile(ge,"utf-8"),X=JSON.parse(F),gt=!!X&&typeof X=="object";g.push({id:"compatibility.matrix.parse",status:gt?"passed":"failed",message:gt?"Compatibility matrix parsed successfully.":"Compatibility matrix parse failed: invalid JSON object."});}catch{g.push({id:"compatibility.matrix.parse",status:"failed",message:"Compatibility matrix parse failed: invalid JSON."});}let Pe=h.join(f$1,".rapidkit","mirror-config.json"),ne=h.join(f$1,".rapidkit","mirror.lock"),Ae=_.existsSync(Pe),Ee=_.existsSync(ne),ut={};if(Ae)try{ut=JSON.parse(await _.promises.readFile(Pe,"utf-8")),g.push({id:"mirror.config.parse",status:"passed",message:"Mirror configuration parsed successfully."});}catch{g.push({id:"mirror.config.parse",status:"failed",message:"Mirror configuration parse failed: invalid JSON in .rapidkit/mirror-config.json."});}let Ht=await to(f$1,{ciMode:p,offlineMode:d});if(g.push(...Ht.checks.map(F=>({id:F.id,status:F.status,message:F.message}))),R=Ht.details,Ht.details.lockWritten&&(Ee=true),d){let F=process.env.RAPIDKIT_MIRROR_ENABLED==="1"||ut.enabled===true;g.push({id:"offline.mirror.enabled",status:F?"passed":"failed",message:F?"Offline mode mirror is enabled.":'Offline mode requires mirror enablement (set RAPIDKIT_MIRROR_ENABLED=1 or .rapidkit/mirror-config.json {"enabled": true}).'});let X=$.rules.require_mirror_lock_for_offline;g.push({id:"offline.mirror.lock",status:!X||Ee?"passed":"failed",message:!X||Ee?"Offline mode mirror lock policy satisfied.":"Offline mode mirror lock policy failed: .rapidkit/mirror.lock is missing."});}else g.push({id:"offline.mirror.enabled",status:"skipped",message:"Offline mirror checks skipped (offline mode is disabled)."});let Dr=await jr(f$1),de=new Set;for(let F of Dr){let X=Se(F);if(pe(X,F)){de.add("go");continue}if(ue(X,F)){de.add("node");continue}if(me(X,F)){de.add("python");continue}de.add("unknown");}if(N==="go-only"){let F=de.size===0||[...de].every(X=>X==="go");g.push({id:"profile.go-only",status:F?"passed":"failed",message:F?"go-only profile validated for discovered projects.":`go-only profile mismatch: detected runtimes [${[...de].join(", ")}].`});}else if(N==="python-only"){let F=de.size===0||[...de].every(X=>X==="python");g.push({id:"profile.python-only",status:F?"passed":"failed",message:F?"python-only profile validated for discovered projects.":`python-only profile mismatch: detected runtimes [${[...de].join(", ")}].`});}else if(N==="node-only"){let F=de.size===0||[...de].every(X=>X==="node");g.push({id:"profile.node-only",status:F?"passed":"failed",message:F?"node-only profile validated for discovered projects.":`node-only profile mismatch: detected runtimes [${[...de].join(", ")}].`});}else if(N==="minimal"){let F=[...de].filter(gt=>gt!=="unknown"),X=F.length<=1;g.push({id:"profile.minimal",status:X?"passed":"failed",message:X?"minimal profile is compatible with detected runtime mix.":`minimal profile mismatch: multiple runtimes detected [${F.join(", ")}].`});}else N==="enterprise"&&(g.push({id:"profile.enterprise.ci",status:p?"passed":"failed",message:p?"enterprise profile running with --ci.":"enterprise profile expects --ci for deterministic non-interactive mode."}),g.push({id:"profile.enterprise.compatibility-matrix",status:U?"passed":"failed",message:U?"enterprise profile has compatibility matrix.":"enterprise profile requires .rapidkit/compatibility-matrix.json."}),g.push({id:"profile.enterprise.mirror-config",status:Ae?"passed":"failed",message:Ae?"enterprise profile has mirror configuration.":"enterprise profile requires .rapidkit/mirror-config.json."}));}p&&(process.env.RAPIDKIT_BOOTSTRAP_CI="1"),d&&(process.env.RAPIDKIT_OFFLINE_MODE="1");let we=g.some(I=>I.id.startsWith("policy.schema.")&&I.status==="failed")||$.mode==="strict"&&g.some(I=>I.status==="failed"),fe=f$1||w,Ve=h.join(fe,".rapidkit","reports"),z=new Date().toISOString().replace(/[:.]/g,"-"),L=h.join(Ve,`bootstrap-compliance-${z}.json`),S=h.join(Ve,"bootstrap-compliance.latest.json"),se={command:"bootstrap",timestamp:new Date().toISOString(),workspacePath:f$1,profile:N,options:{ci:p,offline:d,strict:$.mode==="strict"},policyMode:$.mode,policyRules:$.rules,mirrorLifecycle:R,checks:g};if(we){let I={...se,result:"blocked",initExitCode:null};return await b.ensureDir(Ve),await Ze(L,I),await Ze(S,I),u?process.stdout.write(`${JSON.stringify(I,null,2)}
3549
+ `):(console.log(l.red("\u274C Bootstrap blocked by strict policy checks.")),console.log(l.gray(`Compliance report: ${L}`))),1}let ae=0;u||(ae=await o(s));let H=g.filter(I=>I.status==="failed").length,ie=ae!==0?"failed":H>0?"ok_with_warnings":"ok",le={...se,result:ie,initExitCode:ae};if(await b.ensureDir(Ve),await Ze(L,le),await Ze(S,le),u)process.stdout.write(`${JSON.stringify(le,null,2)}
3550
+ `);else {let I=g.filter(O=>O.status==="failed").length;I>0&&console.log(l.yellow(`\u26A0\uFE0F Bootstrap completed with ${I} policy/profile warnings.`)),console.log(l.gray(`Compliance report: ${L}`));}return ae}finally{typeof t>"u"?delete process.env.RAPIDKIT_SKIP_LOCK_SYNC:process.env.RAPIDKIT_SKIP_LOCK_SYNC=t;}}async function Os(e){let o=(e[1]||"").toLowerCase(),t=e.includes("--warm-deps")||e.includes("--warm-dependencies");if(!o||!["python","node","go"].includes(o))return console.log(l.yellow("Usage: rapidkit setup <python|node|go> [--warm-deps]")),1;let r=async(p,d)=>{if(p==="node"){if(!_.existsSync(h.join(d,"package.json")))return {exitCode:0,message:"Node warm-up skipped: package.json not found in current directory."};let m=_.existsSync(h.join(d,"pnpm-lock.yaml")),w=_.existsSync(h.join(d,"yarn.lock"));return m?{exitCode:await W("pnpm",["install","--lockfile-only","--ignore-scripts"],d)}:w?{exitCode:await W("yarn",["install","--ignore-scripts"],d)}:{exitCode:await W("npm",["install","--package-lock-only","--ignore-scripts"],d)}}return p==="go"?_.existsSync(h.join(d,"go.mod"))?{exitCode:await W("go",["mod","download"],d)}:{exitCode:0,message:"Go warm-up skipped: go.mod not found in current directory."}:{exitCode:0,message:"Dependency warm-up currently applies to node/go runtimes."}},i=He(o,{runCommandInCwd:W,runCoreRapidkit:(p,d)=>d$1(p,{...d,cwd:void 0})}),n=await i.checkPrereqs(),a=await i.doctorHints(process.cwd()),s=Y(process.cwd()),c=s||process.cwd();if(n.exitCode===0){console.log(l.green(`\u2705 ${o} prerequisites look good.`));let p=["python","node","go"].filter(d=>d!==o).join("/");if(console.log(l.gray(` Scope: validated ${o} runtime only. ${p} checks are optional unless your workspace profile uses them.`)),o==="python"&&console.log(l.gray(" Note: Poetry is recommended, but venv/pipx-based flows are supported in workspace creation.")),i.warmSetupCache&&((await i.warmSetupCache(c)).exitCode===0?console.log(l.gray(` ${o} cache warm-up completed.`)):console.log(l.yellow(` ${o} cache warm-up skipped (non-fatal).`))),t){let d=await r(o,c),u=/skipped/i.test(d.message||"");d.message&&console.log(l.gray(` ${d.message}`)),d.exitCode===0&&!u?console.log(l.gray(` ${o} dependency warm-up completed (--warm-deps).`)):d.exitCode!==0&&console.log(l.yellow(` ${o} dependency warm-up failed (non-fatal).`));}if(s)try{let d=h.join(s,".rapidkit","toolchain.lock"),u={};try{u=JSON.parse(await _.promises.readFile(d,"utf-8"));}catch{}(!u.runtime||typeof u.runtime!="object")&&(u.runtime={});let m=u.runtime;if(o==="python"){let w=null;try{let{execa:f}=await import('execa');for(let g of co()){let x=await f(g,g==="py"?["-3","--version"]:["--version"],{cwd:s,stdio:"pipe",reject:false,timeout:3e3});if(x.exitCode===0){let C=(x.stdout||x.stderr||"").match(/Python\s+(\S+)/);if(w=C?C[1]:null,w)break}}}catch{}m.python={...m.python||{},version:w,last_setup:new Date().toISOString()};}else if(o==="node")m.node={...m.node||{},version:process.version,last_setup:new Date().toISOString()};else if(o==="go"){let w=null;try{let{execa:f}=await import('execa'),R=((await f("go",["version"],{cwd:s,stdio:"pipe"})).stdout||"").match(/go(\d+\.\d+(?:\.\d+)?)/i);w=R?R[1]:null;}catch{}m.go={...m.go||{},version:w,last_setup:new Date().toISOString()};}u.updated_at=new Date().toISOString(),await _.promises.writeFile(d,JSON.stringify(u,null,2)+`
3551
3551
  `,"utf-8"),console.log(l.gray(" toolchain.lock updated (.rapidkit/toolchain.lock)"));}catch{}}else console.log(l.red(`\u274C ${o} prerequisites check failed.`));if(a.length>0){console.log(l.gray(`
3552
- Hints:`));for(let p of a)console.log(l.gray(`- ${p}`));}return n.exitCode}function Os(e){let o={strategy:"shared",prune_on_bootstrap:false,self_heal:true,verify_integrity:false};for(let t of e.split(`
3553
- `)){let r=t.trim(),i=r.match(/^strategy:\s*(\S+)/);i&&(o.strategy=i[1].replace(/['"]]/g,""));let n=r.match(/^prune_on_bootstrap:\s*(true|false)/);n&&(o.prune_on_bootstrap=n[1]==="true");let a=r.match(/^self_heal:\s*(true|false)/);a&&(o.self_heal=a[1]==="true");let s=r.match(/^verify_integrity:\s*(true|false)/);s&&(o.verify_integrity=s[1]==="true");}return o}async function Ns(e){let o=(e[1]||"status").toLowerCase(),t=$t.getInstance(),r=Y(process.cwd()),i={strategy:"shared",prune_on_bootstrap:false,self_heal:true,verify_integrity:false};if(r)try{let n=await _.promises.readFile(h.join(r,".rapidkit","cache-config.yml"),"utf-8");i=Os(n);}catch{}return o==="status"?(console.log(l.cyan("RapidKit cache is enabled")),console.log(l.cyan("RapidKit cache status")),r?(console.log(l.gray(` Workspace: ${r}`)),console.log(l.gray(` Strategy: ${i.strategy}`)),console.log(l.gray(` Self-heal: ${i.self_heal}`)),console.log(l.gray(` Prune on bootstrap:${i.prune_on_bootstrap}`)),console.log(l.gray(` Verify integrity: ${i.verify_integrity}`))):console.log(l.gray(" (not inside a workspace \u2014 showing in-memory cache only)")),console.log(l.gray(" In-memory cache: enabled")),console.log(l.gray(" Use: rapidkit cache clear|prune|repair")),0):o==="clear"?(await t.clear(),console.log(l.green("Cache clear completed")),console.log(l.green("\u2705 Cache cleared (all entries removed).")),0):o==="prune"?(await t.clear(),console.log(l.green("\u2705 Cache pruned (stale entries removed).")),i.prune_on_bootstrap||console.log(l.gray(" Tip: set prune_on_bootstrap: true in .rapidkit/cache-config.yml to auto-prune on every bootstrap.")),0):o==="repair"?i.self_heal?(await t.clear(),console.log(l.green("\u2705 Cache repaired (self-heal applied, stale entries evicted).")),i.verify_integrity&&console.log(l.gray(" Integrity verification is enabled in cache-config.yml.")),0):(console.log(l.yellow("\u26A0\uFE0F self_heal is disabled in .rapidkit/cache-config.yml \u2014 skipping repair.")),0):(console.log(l.yellow("Usage: rapidkit cache <status|clear|prune|repair>")),1)}async function js(e,o,t,r){let i=(o||"show").toLowerCase(),n=h.join(e,".rapidkit","policies.yml");if(i==="show"||i==="status"||i==="get"){let d=await vr(e),u=yr(d);return console.log(l.cyan(`Policy file: ${n}`)),console.log(l.gray(` mode: ${u.mode}`)),console.log(l.gray(` dependency_sharing_mode: ${u.dependency_sharing_mode}`)),console.log(l.gray(" rules:")),console.log(l.gray(` enforce_workspace_marker: ${u.rules.enforce_workspace_marker}`)),console.log(l.gray(` enforce_toolchain_lock: ${u.rules.enforce_toolchain_lock}`)),console.log(l.gray(` disallow_untrusted_tool_sources: ${u.rules.disallow_untrusted_tool_sources}`)),console.log(l.gray(` enforce_compatibility_matrix: ${u.rules.enforce_compatibility_matrix}`)),console.log(l.gray(` require_mirror_lock_for_offline: ${u.rules.require_mirror_lock_for_offline}`)),console.log(l.gray("Examples:")),console.log(l.gray(" npx rapidkit workspace policy set mode strict")),console.log(l.gray(" npx rapidkit workspace policy set dependency_sharing_mode shared-runtime-caches")),console.log(l.gray(" npx rapidkit workspace policy set rules.enforce_toolchain_lock true")),0}if(i!=="set")return console.log(l.red(`Unknown workspace policy action: ${o||""}`)),console.log(l.gray("Available: show, set")),1;if(!t||typeof r>"u")return console.log(l.yellow("Usage: rapidkit workspace policy set <key> <value>")),console.log(l.gray("Allowed keys:")),console.log(l.gray(" mode (warn|strict)")),console.log(l.gray(" dependency_sharing_mode (isolated|shared-runtime-caches|shared-node-deps)")),console.log(l.gray(" rules.enforce_workspace_marker (true|false)")),console.log(l.gray(" rules.enforce_toolchain_lock (true|false)")),console.log(l.gray(" rules.disallow_untrusted_tool_sources (true|false)")),console.log(l.gray(" rules.enforce_compatibility_matrix (true|false)")),console.log(l.gray(" rules.require_mirror_lock_for_offline (true|false)")),1;let a=t.trim(),c=await vr(e);if(a==="mode"){let d=r.trim().toLowerCase();if(d!=="warn"&&d!=="strict")return console.log(l.red("\u274C Invalid mode. Use: warn | strict")),1;c=wr(c,"mode",`${d} # "warn" or "strict"`);}else if(a==="dependency_sharing_mode"){let d=r.trim().toLowerCase();if(d!=="isolated"&&d!=="shared-runtime-caches"&&d!=="shared-node-deps")return console.log(l.red("\u274C Invalid dependency_sharing_mode. Use: isolated | shared-runtime-caches | shared-node-deps")),1;c=wr(c,"dependency_sharing_mode",`${d} # "isolated" or "shared-runtime-caches" or "shared-node-deps"`);}else if(a.startsWith("rules.")){let d=a.slice(6);if(!(d in Tr))return console.log(l.red(`\u274C Unknown policy rule: ${d}`)),1;let u=Ps(r);if(u===null)return console.log(l.red("\u274C Rule values must be boolean: true | false")),1;c=Cs(c,d,u);}else return console.log(l.red(`\u274C Unknown policy key: ${a}`)),1;await xs(e,c);let p=yr(c);return console.log(l.green(`\u2705 Updated ${a} in .rapidkit/policies.yml`)),console.log(l.gray(` mode: ${p.mode}`)),console.log(l.gray(` dependency_sharing_mode: ${p.dependency_sharing_mode}`)),console.log(l.gray(" Tip: run `npx rapidkit workspace policy show` to inspect all values.")),0}async function $s(e){let o=(e[1]||"status").toLowerCase(),t=e.includes("--json"),r=Y(process.cwd());if(!r)return console.log(l.red("\u274C Not inside a RapidKit workspace")),console.log(l.gray("\u{1F4A1} Run this command from within a workspace directory")),1;let i=h.join(r,".rapidkit"),n=h.join(i,"mirror-config.json"),a=h.join(i,"mirror.lock"),s=h.join(i,"mirror","artifacts"),c=h.join(i,"reports");async function p(d){let u=new Date().toISOString().replace(/[:.]/g,"-"),m=h.join(c,`mirror-ops-${u}.json`),w=h.join(c,"mirror-ops.latest.json");await b.ensureDir(c),await Xe(m,d),await Xe(w,d);}if(o==="status"){if(!await b.pathExists(n))try{let R={schema_version:"1.0",enabled:false,strategy:"on-demand",artifacts:[],created_at:new Date().toISOString(),note:"Auto-generated by rapidkit mirror status. Set enabled: true and add artifact entries to activate mirroring."};await b.ensureDir(i),await _.promises.writeFile(n,JSON.stringify(R,null,2)+`
3552
+ Hints:`));for(let p of a)console.log(l.gray(`- ${p}`));}return n.exitCode}function Ns(e){let o={strategy:"shared",prune_on_bootstrap:false,self_heal:true,verify_integrity:false};for(let t of e.split(`
3553
+ `)){let r=t.trim(),i=r.match(/^strategy:\s*(\S+)/);i&&(o.strategy=i[1].replace(/['"]]/g,""));let n=r.match(/^prune_on_bootstrap:\s*(true|false)/);n&&(o.prune_on_bootstrap=n[1]==="true");let a=r.match(/^self_heal:\s*(true|false)/);a&&(o.self_heal=a[1]==="true");let s=r.match(/^verify_integrity:\s*(true|false)/);s&&(o.verify_integrity=s[1]==="true");}return o}async function js(e){let o=(e[1]||"status").toLowerCase(),t=$t.getInstance(),r=Y(process.cwd()),i={strategy:"shared",prune_on_bootstrap:false,self_heal:true,verify_integrity:false};if(r)try{let n=await _.promises.readFile(h.join(r,".rapidkit","cache-config.yml"),"utf-8");i=Ns(n);}catch{}return o==="status"?(console.log(l.cyan("RapidKit cache is enabled")),console.log(l.cyan("RapidKit cache status")),r?(console.log(l.gray(` Workspace: ${r}`)),console.log(l.gray(` Strategy: ${i.strategy}`)),console.log(l.gray(` Self-heal: ${i.self_heal}`)),console.log(l.gray(` Prune on bootstrap:${i.prune_on_bootstrap}`)),console.log(l.gray(` Verify integrity: ${i.verify_integrity}`))):console.log(l.gray(" (not inside a workspace \u2014 showing in-memory cache only)")),console.log(l.gray(" In-memory cache: enabled")),console.log(l.gray(" Use: rapidkit cache clear|prune|repair")),0):o==="clear"?(await t.clear(),console.log(l.green("Cache clear completed")),console.log(l.green("\u2705 Cache cleared (all entries removed).")),0):o==="prune"?(await t.clear(),console.log(l.green("\u2705 Cache pruned (stale entries removed).")),i.prune_on_bootstrap||console.log(l.gray(" Tip: set prune_on_bootstrap: true in .rapidkit/cache-config.yml to auto-prune on every bootstrap.")),0):o==="repair"?i.self_heal?(await t.clear(),console.log(l.green("\u2705 Cache repaired (self-heal applied, stale entries evicted).")),i.verify_integrity&&console.log(l.gray(" Integrity verification is enabled in cache-config.yml.")),0):(console.log(l.yellow("\u26A0\uFE0F self_heal is disabled in .rapidkit/cache-config.yml \u2014 skipping repair.")),0):(console.log(l.yellow("Usage: rapidkit cache <status|clear|prune|repair>")),1)}async function $s(e,o,t,r){let i=(o||"show").toLowerCase(),n=h.join(e,".rapidkit","policies.yml");if(i==="show"||i==="status"||i==="get"){let d=await vr(e),u=yr(d);return console.log(l.cyan(`Policy file: ${n}`)),console.log(l.gray(` mode: ${u.mode}`)),console.log(l.gray(` dependency_sharing_mode: ${u.dependency_sharing_mode}`)),console.log(l.gray(" rules:")),console.log(l.gray(` enforce_workspace_marker: ${u.rules.enforce_workspace_marker}`)),console.log(l.gray(` enforce_toolchain_lock: ${u.rules.enforce_toolchain_lock}`)),console.log(l.gray(` disallow_untrusted_tool_sources: ${u.rules.disallow_untrusted_tool_sources}`)),console.log(l.gray(` enforce_compatibility_matrix: ${u.rules.enforce_compatibility_matrix}`)),console.log(l.gray(` require_mirror_lock_for_offline: ${u.rules.require_mirror_lock_for_offline}`)),console.log(l.gray("Examples:")),console.log(l.gray(" npx rapidkit workspace policy set mode strict")),console.log(l.gray(" npx rapidkit workspace policy set dependency_sharing_mode shared-runtime-caches")),console.log(l.gray(" npx rapidkit workspace policy set rules.enforce_toolchain_lock true")),0}if(i!=="set")return console.log(l.red(`Unknown workspace policy action: ${o||""}`)),console.log(l.gray("Available: show, set")),1;if(!t||typeof r>"u")return console.log(l.yellow("Usage: rapidkit workspace policy set <key> <value>")),console.log(l.gray("Allowed keys:")),console.log(l.gray(" mode (warn|strict)")),console.log(l.gray(" dependency_sharing_mode (isolated|shared-runtime-caches|shared-node-deps)")),console.log(l.gray(" rules.enforce_workspace_marker (true|false)")),console.log(l.gray(" rules.enforce_toolchain_lock (true|false)")),console.log(l.gray(" rules.disallow_untrusted_tool_sources (true|false)")),console.log(l.gray(" rules.enforce_compatibility_matrix (true|false)")),console.log(l.gray(" rules.require_mirror_lock_for_offline (true|false)")),1;let a=t.trim(),c=await vr(e);if(a==="mode"){let d=r.trim().toLowerCase();if(d!=="warn"&&d!=="strict")return console.log(l.red("\u274C Invalid mode. Use: warn | strict")),1;c=wr(c,"mode",`${d} # "warn" or "strict"`);}else if(a==="dependency_sharing_mode"){let d=r.trim().toLowerCase();if(d!=="isolated"&&d!=="shared-runtime-caches"&&d!=="shared-node-deps")return console.log(l.red("\u274C Invalid dependency_sharing_mode. Use: isolated | shared-runtime-caches | shared-node-deps")),1;c=wr(c,"dependency_sharing_mode",`${d} # "isolated" or "shared-runtime-caches" or "shared-node-deps"`);}else if(a.startsWith("rules.")){let d=a.slice(6);if(!(d in Tr))return console.log(l.red(`\u274C Unknown policy rule: ${d}`)),1;let u=Es(r);if(u===null)return console.log(l.red("\u274C Rule values must be boolean: true | false")),1;c=Ss(c,d,u);}else return console.log(l.red(`\u274C Unknown policy key: ${a}`)),1;await Ps(e,c);let p=yr(c);return console.log(l.green(`\u2705 Updated ${a} in .rapidkit/policies.yml`)),console.log(l.gray(` mode: ${p.mode}`)),console.log(l.gray(` dependency_sharing_mode: ${p.dependency_sharing_mode}`)),console.log(l.gray(" Tip: run `npx rapidkit workspace policy show` to inspect all values.")),0}async function Ds(e){let o=(e[1]||"status").toLowerCase(),t=e.includes("--json"),r=Y(process.cwd());if(!r)return console.log(l.red("\u274C Not inside a RapidKit workspace")),console.log(l.gray("\u{1F4A1} Run this command from within a workspace directory")),1;let i=h.join(r,".rapidkit"),n=h.join(i,"mirror-config.json"),a=h.join(i,"mirror.lock"),s=h.join(i,"mirror","artifacts"),c=h.join(i,"reports");async function p(d){let u=new Date().toISOString().replace(/[:.]/g,"-"),m=h.join(c,`mirror-ops-${u}.json`),w=h.join(c,"mirror-ops.latest.json");await b.ensureDir(c),await Ze(m,d),await Ze(w,d);}if(o==="status"){if(!await b.pathExists(n))try{let R={schema_version:"1.0",enabled:false,strategy:"on-demand",artifacts:[],created_at:new Date().toISOString(),note:"Auto-generated by rapidkit mirror status. Set enabled: true and add artifact entries to activate mirroring."};await b.ensureDir(i),await _.promises.writeFile(n,JSON.stringify(R,null,2)+`
3554
3554
  `,"utf-8"),console.log(l.gray(" mirror-config.json created with defaults (.rapidkit/mirror-config.json)"));}catch{}let u=await b.pathExists(n),m=await b.pathExists(s),w=await b.pathExists(a),f=m?(await _.promises.readdir(s,{withFileTypes:true})).filter(R=>R.isFile()).length:0,g={command:"mirror",action:o,result:"ok",timestamp:new Date().toISOString(),workspacePath:r,mirror:{configExists:u,lockExists:w,artifactsCount:f}};return await p(g),t?(process.stdout.write(`${JSON.stringify(g,null,2)}
3555
3555
  `),0):(console.log(l.cyan("RapidKit mirror status")),console.log(l.gray(`Workspace: ${r}`)),console.log(l.gray(`Config: ${u?"present":"missing"} (${n})`)),console.log(l.gray(`Lock: ${w?"present":"missing"} (${a})`)),console.log(l.gray(`Artifacts: ${f}`)),0)}if(o==="sync"||o==="verify"||o==="rotate"){let d=await to(r,{ciMode:true,offlineMode:o==="verify",forceRun:true}),u=d.checks.filter(f=>f.status==="failed"),m=d.checks.some(f=>f.id.startsWith("mirror.verify.")&&f.status==="failed");if(o==="verify"&&m){let f={command:"mirror",action:o,result:"failed",timestamp:new Date().toISOString(),workspacePath:r,details:d.details,checks:d.checks};if(await p(f),t)return process.stdout.write(`${JSON.stringify(f,null,2)}
3556
3556
  `),1;console.log(l.red("\u274C Mirror verify failed."));for(let g of d.checks.filter(R=>R.id.startsWith("mirror.verify.")))console.log(l.gray(`- ${g.id}: ${g.message}`));return 1}if(u.length>0){let f={command:"mirror",action:o,result:"failed",timestamp:new Date().toISOString(),workspacePath:r,details:d.details,checks:d.checks};if(await p(f),t)return process.stdout.write(`${JSON.stringify(f,null,2)}
3557
3557
  `),1;console.log(l.yellow(`\u26A0\uFE0F Mirror ${o} completed with ${u.length} issue(s).`));for(let g of u)console.log(l.gray(`- ${g.id}: ${g.message}`));return 1}let w={command:"mirror",action:o,result:"ok",timestamp:new Date().toISOString(),workspacePath:r,details:d.details,checks:d.checks};return await p(w),t?(process.stdout.write(`${JSON.stringify(w,null,2)}
3558
- `),0):o==="rotate"?(console.log(l.green(`\u2705 Mirror rotate completed. Rotated files: ${d.details.rotatedFiles}.`)),0):o==="verify"?(console.log(l.green(`\u2705 Mirror verify completed. Verified artifacts: ${d.details.verifiedArtifacts}.`)),0):(console.log(l.green(`\u2705 Mirror sync completed. Synced artifacts: ${d.details.syncedArtifacts}.`)),0)}return console.log(l.yellow("Usage: rapidkit mirror <status|sync|verify|rotate> [--json]")),1}async function ao(e){let o=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof o>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let t=process.cwd(),r=await Nr(t,async()=>{let i=Y(t),n=He("python",{runCommandInCwd:W,runCoreRapidkit:d$1});if(e.length>1){let m=h.resolve(t,e[1]),w=Se(m),f=await ro(m);return pe(w,m)||f==="go"?await Mt(m):ue(w,m)||f==="node"?await Gt(m):me(w,m)||f==="python"?await Dt(m,n):await d$1(e,{cwd:t})}let a=Se(t),s=!!Y(t)&&t===Y(t);if(!s&&pe(a,t))return await Mt(t);let c=await ro(t);if(!s&&(ue(a,t)||c==="node"))return await Gt(t);if(!s&&(me(a,t)||c==="python"))return await Dt(t,n);let p=i||Y(t),d=Ir(t),u=d?h.dirname(h.dirname(d)):null;if(u&&u!==p){let m=Se(u),w=await ro(u);return pe(m,u)||w==="go"?await Mt(u):ue(m,u)||w==="node"?await Gt(u):me(m,u)||w==="python"?await Dt(u,n):await d$1(["init"],{cwd:u})}if(p&&t===p){let m=await Es(p);if(m!==0)return m;let w=await jr(p);if(w.length===0){let f="minimal";try{f=JSON.parse(await _.promises.readFile(h.join(p,".rapidkit","workspace.json"),"utf-8")).profile??"minimal";}catch{}return f==="go-only"?(console.log(l.green("\u2714 Go workspace ready")),console.log(l.gray(`
3558
+ `),0):o==="rotate"?(console.log(l.green(`\u2705 Mirror rotate completed. Rotated files: ${d.details.rotatedFiles}.`)),0):o==="verify"?(console.log(l.green(`\u2705 Mirror verify completed. Verified artifacts: ${d.details.verifiedArtifacts}.`)),0):(console.log(l.green(`\u2705 Mirror sync completed. Synced artifacts: ${d.details.syncedArtifacts}.`)),0)}return console.log(l.yellow("Usage: rapidkit mirror <status|sync|verify|rotate> [--json]")),1}async function ao(e){let o=process.env.RAPIDKIT_SKIP_LOCK_SYNC;typeof o>"u"&&(process.env.RAPIDKIT_SKIP_LOCK_SYNC="1");try{let t=process.cwd(),r=await Nr(t,async()=>{let i=Y(t),n=He("python",{runCommandInCwd:W,runCoreRapidkit:d$1});if(e.length>1){let m=h.resolve(t,e[1]),w=Se(m),f=await ro(m);return pe(w,m)||f==="go"?await Mt(m):ue(w,m)||f==="node"?await Gt(m):me(w,m)||f==="python"?await Dt(m,n):await d$1(e,{cwd:t})}let a=Se(t),s=!!Y(t)&&t===Y(t);if(!s&&pe(a,t))return await Mt(t);let c=await ro(t);if(!s&&(ue(a,t)||c==="node"))return await Gt(t);if(!s&&(me(a,t)||c==="python"))return await Dt(t,n);let p=i||Y(t),d=Ir(t),u=d?h.dirname(h.dirname(d)):null;if(u&&u!==p){let m=Se(u),w=await ro(u);return pe(m,u)||w==="go"?await Mt(u):ue(m,u)||w==="node"?await Gt(u):me(m,u)||w==="python"?await Dt(u,n):await d$1(["init"],{cwd:u})}if(p&&t===p){let m=await Is(p);if(m!==0)return m;let w=await jr(p);if(w.length===0){let f="minimal";try{f=JSON.parse(await _.promises.readFile(h.join(p,".rapidkit","workspace.json"),"utf-8")).profile??"minimal";}catch{}return f==="go-only"?(console.log(l.green("\u2714 Go workspace ready")),console.log(l.gray(`
3559
3559
  No projects yet \u2014 create one and then run init inside it:`)),console.log(l.white(" npx rapidkit create project gofiber.standard my-api")),console.log(l.white(" cd my-api && npx rapidkit init")),console.log(l.gray(`
3560
3560
  \u{1F4A1} Go dependencies are managed per-project (go.mod / go mod tidy).`))):(console.log(l.green("\u2714 Workspace ready")),console.log(l.gray(`
3561
- No projects yet \u2014 create one to get started:`)),console.log(l.white(" npx rapidkit create project"))),0}for(let f of w){let g=Se(f);if(pe(g,f)){let R=await Mt(f);if(R!==0)return R}else {if(ue(g,f)){let x=await Gt(f);if(x!==0)return x;continue}if(me(g,f)){let x=await Dt(f,n);if(x!==0)return x;continue}let R=await d$1(["init"],{cwd:f});if(R!==0)return R}}return 0}if(!p){let m=await a$2(),{name:w}=Is(t);return await h$1(w,{yes:true,userConfig:m}),0}return await d$1(e,{cwd:t})});return r.ok?r.value:r.code}finally{typeof o>"u"?delete process.env.RAPIDKIT_SKIP_LOCK_SYNC:process.env.RAPIDKIT_SKIP_LOCK_SYNC=o;}}async function kr(e){let o=Y(e);if(!o)return [];let t="warn";try{(await _.promises.readFile(h.join(o,".rapidkit","policies.yml"),"utf-8")).match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m)?.[1]==="strict"&&(t="strict");}catch{return []}if(t!=="strict")return [];let r=[],i=h.join(o,".rapidkit","toolchain.lock");if(!_.existsSync(i))return r.push("toolchain.lock is missing \u2014 run `rapidkit bootstrap` first (strict mode requires a reproducible toolchain)."),r;let n={};try{n=JSON.parse(await _.promises.readFile(i,"utf-8"));}catch{return []}let a=n.runtime??{},s=Se(e);pe(s,e)&&!a.go?.version?r.push("go.version is not pinned in toolchain.lock \u2014 run `rapidkit setup go` first."):ue(s,e)&&!a.node?.version?r.push("node.version is not pinned in toolchain.lock \u2014 run `rapidkit setup node` first."):me(s,e)&&!a.python?.version&&r.push("python.version is not pinned in toolchain.lock \u2014 run `rapidkit setup python` first.");try{let p=JSON.parse(await _.promises.readFile(h.join(o,".rapidkit","workspace.json"),"utf-8")).profile??"";p==="python-only"&&(pe(s,e)||ue(s,e))?r.push('Workspace profile is "python-only" but this project is not Python.'):p==="node-only"&&(pe(s,e)||me(s,e))?r.push('Workspace profile is "node-only" but this project is not Node.'):p==="go-only"&&(ue(s,e)||me(s,e))&&r.push('Workspace profile is "go-only" but this project is not Go.');}catch{}return r}async function Ds(){let e=async x=>{if(!a()||!x.toLowerCase().endsWith(".cmd"))return false;try{let C=(await b.readFile(x,"utf8")).replace(/\r\n/g,`
3562
- `).toLowerCase(),P=C.includes("\\.rapidkit\\rapidkit"),G=C.includes("\\.rapidkit\\rapidkit.cmd")||C.includes("\\.rapidkit\\rapidkit.exe")||C.includes("\\.venv\\scripts\\rapidkit.exe");return P&&!G}catch{return false}},o=process.cwd(),t=process.argv.slice(2),r=t[0],i=r==="init",n=new Set(["dev","start","build","test"]),a$2=!r||r==="--help"||r==="-h"||r==="help",s=Er(o),c=_.existsSync(h.join(o,".rapidkit","project.json")),p=Se(o),d=pe(p,o)||ue(p,o),u=!!r&&n.has(r)&&d;if(Ft(t[0])||t[0]==="create"||t[0]==="init"&&s&&!c)return false;try{let x=r==="shell"&&t[1]==="activate",T=r==="create",C=await vo(o,{cwd:o,timeoutMs:1200});if(C.ok&&C.data?.isRapidkitProject&&C.data.engine==="python"){let P=T||Ft(r);if(!a$2&&!x&&!P&&!i&&!u){if(r&&fr.includes(r)){let N=await kr(o).catch(()=>[]);if(N.length>0){process.stderr.write(l.red("\u274C Strict policy violations prevent running this command:")+`
3561
+ No projects yet \u2014 create one to get started:`)),console.log(l.white(" npx rapidkit create project"))),0}for(let f of w){let g=Se(f);if(pe(g,f)){let R=await Mt(f);if(R!==0)return R}else {if(ue(g,f)){let x=await Gt(f);if(x!==0)return x;continue}if(me(g,f)){let x=await Dt(f,n);if(x!==0)return x;continue}let R=await d$1(["init"],{cwd:f});if(R!==0)return R}}return 0}if(!p){let m=await a$2(),{name:w}=Ts(t);return await h$1(w,{yes:true,userConfig:m}),0}return await d$1(e,{cwd:t})});return r.ok?r.value:r.code}finally{typeof o>"u"?delete process.env.RAPIDKIT_SKIP_LOCK_SYNC:process.env.RAPIDKIT_SKIP_LOCK_SYNC=o;}}async function kr(e){let o=Y(e);if(!o)return [];let t="warn";try{(await _.promises.readFile(h.join(o,".rapidkit","policies.yml"),"utf-8")).match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m)?.[1]==="strict"&&(t="strict");}catch{return []}if(t!=="strict")return [];let r=[],i=h.join(o,".rapidkit","toolchain.lock");if(!_.existsSync(i))return r.push("toolchain.lock is missing \u2014 run `rapidkit bootstrap` first (strict mode requires a reproducible toolchain)."),r;let n={};try{n=JSON.parse(await _.promises.readFile(i,"utf-8"));}catch{return []}let a=n.runtime??{},s=Se(e);pe(s,e)&&!a.go?.version?r.push("go.version is not pinned in toolchain.lock \u2014 run `rapidkit setup go` first."):ue(s,e)&&!a.node?.version?r.push("node.version is not pinned in toolchain.lock \u2014 run `rapidkit setup node` first."):me(s,e)&&!a.python?.version&&r.push("python.version is not pinned in toolchain.lock \u2014 run `rapidkit setup python` first.");try{let p=JSON.parse(await _.promises.readFile(h.join(o,".rapidkit","workspace.json"),"utf-8")).profile??"";p==="python-only"&&(pe(s,e)||ue(s,e))?r.push('Workspace profile is "python-only" but this project is not Python.'):p==="node-only"&&(pe(s,e)||me(s,e))?r.push('Workspace profile is "node-only" but this project is not Node.'):p==="go-only"&&(ue(s,e)||me(s,e))&&r.push('Workspace profile is "go-only" but this project is not Go.');}catch{}return r}async function Gs(){let e=async x=>{if(!a()||!x.toLowerCase().endsWith(".cmd"))return false;try{let C=(await b.readFile(x,"utf8")).replace(/\r\n/g,`
3562
+ `).toLowerCase(),E=C.includes("\\.rapidkit\\rapidkit"),G=C.includes("\\.rapidkit\\rapidkit.cmd")||C.includes("\\.rapidkit\\rapidkit.exe")||C.includes("\\.venv\\scripts\\rapidkit.exe");return E&&!G}catch{return false}},o=process.cwd(),t=process.argv.slice(2),r=t[0],i=r==="init",n=new Set(["dev","start","build","test"]),a$2=!r||r==="--help"||r==="-h"||r==="help",s=Er(o),c=_.existsSync(h.join(o,".rapidkit","project.json")),p=Se(o),d=pe(p,o)||ue(p,o),u=!!r&&n.has(r)&&d;if(Ft(t[0])||t[0]==="create"||t[0]==="init"&&s&&!c)return false;try{let x=r==="shell"&&t[1]==="activate",T=r==="create",C=await vo(o,{cwd:o,timeoutMs:1200});if(C.ok&&C.data?.isRapidkitProject&&C.data.engine==="python"){let E=T||Ft(r);if(!a$2&&!x&&!E&&!i&&!u){if(r&&fr.includes(r)){let N=await kr(o).catch(()=>[]);if(N.length>0){process.stderr.write(l.red("\u274C Strict policy violations prevent running this command:")+`
3563
3563
  `);for(let $ of N)process.stderr.write(l.red(` \u2022 ${$}`)+`
3564
3564
  `);process.exit(1);}}let G=await d$1(process.argv.slice(2),{cwd:o});process.exit(G);}}}catch{}let m=Ir(o),w=a(),f=i$1(o),g=null;for(let x of f)if(await b.pathExists(x)){if(await e(x)){a$1.warn(`Skipping legacy/broken Windows launcher candidate: ${x}. Falling back to core bridge.`);continue}g=x;break}let R=r==="create";if(r==="init"&&s&&!c)return false;if(r&&fr.includes(r)){let x=await kr(o);if(x.length>0){process.stderr.write(l.red("\u274C Strict policy violations prevent running this command:")+`
3565
3565
  `);for(let T of x)process.stderr.write(l.red(` \u2022 ${T}`)+`
3566
- `);process.exit(1);}}if(g&&r&&mr.includes(r)&&!R&&!i&&!u){a$1.debug(`Delegating to local CLI: ${g} ${t.join(" ")}`);let x=r==="init"?pr():process.env,T=spawn(g,t,{stdio:"inherit",cwd:o,shell:w,env:x});return T.on("close",C=>{process.exit(C??0);}),T.on("error",C=>{a$1.error(`Failed to run local rapidkit: ${C.message}`),process.exit(1);}),true}if(m&&await b.pathExists(m))try{if((await b.readJson(m)).engine==="pip"){let T=t[0],C=i$1(o),P=null;for(let G of C)if(await b.pathExists(G)){if(await e(G)){a$1.warn(`Skipping legacy/broken Windows launcher candidate: ${G}. Falling back to core bridge.`);continue}P=G;break}if(P&&T&&mr.includes(T)&&T!=="init"&&!u){a$1.debug(`Delegating to local CLI (early detection): ${P} ${t.join(" ")}`);let G=T==="init"?pr():process.env,N=spawn(P,t,{stdio:"inherit",cwd:o,env:G});return N.on("close",$=>process.exit($??0)),N.on("error",$=>{a$1.error(`Failed to run local rapidkit: ${$.message}`),process.exit(1);}),true}if(T==="shell"&&t[1]==="activate"){let G=a()?`# RapidKit: activation snippet (PowerShell)
3566
+ `);process.exit(1);}}if(g&&r&&mr.includes(r)&&!R&&!i&&!u){a$1.debug(`Delegating to local CLI: ${g} ${t.join(" ")}`);let x=r==="init"?pr():process.env,T=spawn(g,t,{stdio:"inherit",cwd:o,shell:w,env:x});return T.on("close",C=>{process.exit(C??0);}),T.on("error",C=>{a$1.error(`Failed to run local rapidkit: ${C.message}`),process.exit(1);}),true}if(m&&await b.pathExists(m))try{if((await b.readJson(m)).engine==="pip"){let T=t[0],C=i$1(o),E=null;for(let G of C)if(await b.pathExists(G)){if(await e(G)){a$1.warn(`Skipping legacy/broken Windows launcher candidate: ${G}. Falling back to core bridge.`);continue}E=G;break}if(E&&T&&mr.includes(T)&&T!=="init"&&!u){a$1.debug(`Delegating to local CLI (early detection): ${E} ${t.join(" ")}`);let G=T==="init"?pr():process.env,N=spawn(E,t,{stdio:"inherit",cwd:o,env:G});return N.on("close",$=>process.exit($??0)),N.on("error",$=>{a$1.error(`Failed to run local rapidkit: ${$.message}`),process.exit(1);}),true}if(T==="shell"&&t[1]==="activate"){let G=a()?`# RapidKit: activation snippet (PowerShell)
3567
3567
  $venv = ".venv"
3568
3568
  if (Test-Path "$venv\\Scripts\\Activate.ps1") { . "$venv\\Scripts\\Activate.ps1" }
3569
3569
  $env:RAPIDKIT_PROJECT_ROOT = (Get-Location).Path
@@ -3585,7 +3585,7 @@ export PATH="$(pwd)/.rapidkit:$(pwd):$PATH"
3585
3585
  \u2705 Activation snippet \u2014 run the following to activate this project in your current shell:
3586
3586
  `)),console.log(G),console.log(l.gray(`
3587
3587
  \u{1F4A1} After activation you can run: rapidkit dev
3588
- `)),process.exit(0);}if(!a$2&&!Ft(T)&&T!=="init"&&!u){let G=await d$1(t,{cwd:o});process.exit(G);}}}catch{}return false}var $e=null,Lt=false,ye=new Command,Gs=process.env.RAPIDKIT_SHOW_LEGACY==="1"||process.env.RAPIDKIT_SHOW_LEGACY?.toLowerCase()==="true";async function Ms(e){if(e.length===0)return false;let o=e[0],t=e[1];if(ks.includes(o))return false;if(xr.includes(o))return true;if(Ft(o)||o==="shell"&&t==="activate")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 r=new Set(["--yes","-y","--skip-git","--skip-install","--debug","--dry-run","--no-update-check","--create-workspace","--no-workspace"]);if(e.some(n=>r.has(n)))return false;let i=await h$3();return i?i.has(o):!!(a$3.has(o)||e.length>1)}ye.name("rapidkit").description("Create RapidKit workspaces and projects").version(c());var Ls=a()?"npx rapidkit init; npx rapidkit dev":"npx rapidkit init && npx rapidkit dev";ye.addHelpText("beforeAll",`RapidKit NPM CLI
3588
+ `)),process.exit(0);}if(!a$2&&!Ft(T)&&T!=="init"&&!u){let G=await d$1(t,{cwd:o});process.exit(G);}}}catch{}return false}var $e=null,Lt=false,ye=new Command,Ms=process.env.RAPIDKIT_SHOW_LEGACY==="1"||process.env.RAPIDKIT_SHOW_LEGACY?.toLowerCase()==="true";async function Ls(e){if(e.length===0)return false;let o=e[0],t=e[1];if(ks.includes(o))return false;if(xr.includes(o))return true;if(Ft(o)||o==="shell"&&t==="activate")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 r=new Set(["--yes","-y","--skip-git","--skip-install","--debug","--dry-run","--no-update-check","--create-workspace","--no-workspace"]);if(e.some(n=>r.has(n)))return false;let i=await h$3();return i?i.has(o):!!(a$3.has(o)||e.length>1)}ye.name("rapidkit").description("Create RapidKit workspaces and projects").version(c());var qs=a()?"npx rapidkit init; npx rapidkit dev":"npx rapidkit init && npx rapidkit dev";ye.addHelpText("beforeAll",`RapidKit NPM CLI
3589
3589
 
3590
3590
  Create workspaces, scaffold projects, and manage your development toolchain.
3591
3591
  `);ye.addHelpText("afterAll",`
@@ -3607,7 +3607,7 @@ Quick start:
3607
3607
  npx rapidkit my-workspace # Create + bootstrap workspace
3608
3608
  cd my-workspace
3609
3609
  npx rapidkit create project # Interactive kit picker
3610
- ${Ls} # Install deps + run
3610
+ ${qs} # Install deps + run
3611
3611
 
3612
3612
  Notes:
3613
3613
  --skip-install (npm wrapper) enables fast-path for lock/dependency steps.
@@ -3624,11 +3624,11 @@ Use "rapidkit help <command>" for more information.
3624
3624
  `)),process.exit(1));let a=!!o.template;if(o.dryRun){console.log(l.cyan(`
3625
3625
  \u{1F50D} Dry-run mode - showing what would be created:
3626
3626
  `)),console.log(l.white("\u{1F4C2} Path:"),n),console.log(l.white("\u{1F4E6} Type:"),a?`Project (${o.template})`:"Workspace"),console.log();return}if(!o.yes&&!a?await xe.prompt([{type:"input",name:"author",message:"Author name:",default:process.env.USER||"RapidKit User"}]):o.yes&&console.log(l.gray(`Using default values (--yes flag)
3627
- `)),a){let s=String(o.template||"").trim(),c=s.toLowerCase(),p=c==="fastapi"?"fastapi.standard":c==="nestjs"?"nestjs.standard":c==="go"||c==="fiber"?"gofiber.standard":c==="gin"?"gogin.standard":s;if(qt(p)){let T=h.resolve(process.cwd(),e$1);await Vt(T,{project_name:e$1,module_path:e$1,skipGit:o.skipGit});return}if(lt(p)){let T=h.resolve(process.cwd(),e$1);await Bt(T,{project_name:e$1,module_path:e$1,skipGit:o.skipGit});return}if(!!!so(process.cwd())){if(o.createWorkspace)await i(process.cwd(),{skipGit:o.skipGit,yes:o.yes,userConfig:t});else if(!o.noWorkspace)if(o.yes)await i(process.cwd(),{skipGit:o.skipGit,yes:true,userConfig:t});else {let{createWs:T}=await xe.prompt([{type:"confirm",name:"createWs",message:"This project will be created outside a RapidKit workspace. Create and register a workspace here?",default:true}]);T&&await i(process.cwd(),{skipGit:o.skipGit,yes:false,userConfig:t});}}let u=["create","project",p,e$1,"--output",process.cwd()];o.yes&&u.push("--yes");let m=Y(process.cwd()),w=!!o.skipInstall,f=w||!!m;w&&u.push("--skip-essentials");let g=f?{...process.env,RAPIDKIT_SKIP_LOCKS:"1",RAPIDKIT_GENERATE_LOCKS:"0"}:void 0,R=await e(u,{cwd:process.cwd(),env:g});R!==0&&process.exit(R),m&&!o.skipInstall&&(console.log(l.gray("\u2139\uFE0F Fast create mode (workspace): dependencies were deferred.")),console.log(l.white(" Next: cd <project-name> && npx rapidkit init")));let x=so(process.cwd());if(x){let T=h.dirname(x),C=h.join(T,".python-version"),P=h.join(n,".python-version");try{if(await b.pathExists(C)){let G=_.readFileSync(C,"utf-8");_.writeFileSync(P,G.trim()+`
3628
- `),a$1.debug(`Synced Python version ${G.trim()} from workspace to project`);}}catch(G){a$1.debug("Could not sync Python version from workspace:",G);}}if(!o.skipInstall){let T=await d$1(["init",n],{cwd:process.cwd()});if(T!==0&&process.exit(T),x){let C=h.dirname(x),P=h.join(C,".python-version"),G=h.join(n,".python-version");try{if(await b.pathExists(P)){let N=_.readFileSync(P,"utf-8");_.writeFileSync(G,N.trim()+`
3627
+ `)),a){let s=String(o.template||"").trim(),c=s.toLowerCase(),p=c==="fastapi"?"fastapi.standard":c==="nestjs"?"nestjs.standard":c==="go"||c==="fiber"?"gofiber.standard":c==="gin"?"gogin.standard":s;if(qt(p)){let T=h.resolve(process.cwd(),e$1);await Vt(T,{project_name:e$1,module_path:e$1,skipGit:o.skipGit});return}if(lt(p)){let T=h.resolve(process.cwd(),e$1);await Bt(T,{project_name:e$1,module_path:e$1,skipGit:o.skipGit});return}if(!!!so(process.cwd())){if(o.createWorkspace)await i(process.cwd(),{skipGit:o.skipGit,yes:o.yes,userConfig:t});else if(!o.noWorkspace)if(o.yes)await i(process.cwd(),{skipGit:o.skipGit,yes:true,userConfig:t});else {let{createWs:T}=await xe.prompt([{type:"confirm",name:"createWs",message:"This project will be created outside a RapidKit workspace. Create and register a workspace here?",default:true}]);T&&await i(process.cwd(),{skipGit:o.skipGit,yes:false,userConfig:t});}}let u=["create","project",p,e$1,"--output",process.cwd()];o.yes&&u.push("--yes");let m=Y(process.cwd()),w=!!o.skipInstall,f=w||!!m;w&&u.push("--skip-essentials");let g=f?{...process.env,RAPIDKIT_SKIP_LOCKS:"1",RAPIDKIT_GENERATE_LOCKS:"0"}:void 0,R=await e(u,{cwd:process.cwd(),env:g});R!==0&&process.exit(R),m&&!o.skipInstall&&(console.log(l.gray("\u2139\uFE0F Fast create mode (workspace): dependencies were deferred.")),console.log(l.white(" Next: cd <project-name> && npx rapidkit init")));let x=so(process.cwd());if(x){let T=h.dirname(x),C=h.join(T,".python-version"),E=h.join(n,".python-version");try{if(await b.pathExists(C)){let G=_.readFileSync(C,"utf-8");_.writeFileSync(E,G.trim()+`
3628
+ `),a$1.debug(`Synced Python version ${G.trim()} from workspace to project`);}}catch(G){a$1.debug("Could not sync Python version from workspace:",G);}}if(!o.skipInstall){let T=await d$1(["init",n],{cwd:process.cwd()});if(T!==0&&process.exit(T),x){let C=h.dirname(x),E=h.join(C,".python-version"),G=h.join(n,".python-version");try{if(await b.pathExists(E)){let N=_.readFileSync(E,"utf-8");_.writeFileSync(G,N.trim()+`
3629
3629
  `),a$1.debug(`Re-synced Python version ${N.trim()} after init`);}}catch(N){a$1.debug("Could not re-sync Python version after init:",N);}}}}else await h$1(e$1,{skipGit:o.skipGit,dryRun:o.dryRun,yes:o.yes,userConfig:i$1,installMethod:o.installMethod,profile:o.profile});}catch(t){t instanceof d?(a$1.error(`
3630
3630
  \u274C ${t.message}`),t.details&&a$1.warn(`\u{1F4A1} ${t.details}`),a$1.debug("Error code:",t.code)):(a$1.error(`
3631
- \u274C An unexpected error occurred:`),console.error(t)),process.exit(1);}finally{$e=null;}});er(ye);$o(ye);ye.command("shell <action>").description("Shell helpers (activate virtualenv in current shell)").action(async e=>{e!=="activate"&&(console.log(l.red(`Unknown shell command: ${e}`)),process.exit(1));let o=process.cwd();function t(c){let p=c;for(;;){let d=h.join(p,".rapidkit","context.json");if(_.existsSync(d))return d;let u=h.dirname(p);if(u===p)break;p=u;}return null}let r=t(o);function i(c){let p=c;for(;;){let d=h.join(p,".venv"),u=h.join(p,".rapidkit","activate");if(_.existsSync(u)||_.existsSync(d))return {venv:d,activateFile:u};let m=h.dirname(p);if(m===p)break;p=m;}return null}let n=i(o);!r&&!n&&(console.log(l.yellow("No RapidKit project found in this directory")),process.exit(1));let a$1;n&&_.existsSync(n.activateFile)?a$1=n.activateFile:n&&_.existsSync(n.venv)?a$1=h$2(n.venv):(console.log(l.yellow("No virtual environment found")),process.exit(1));let s=a();console.log(s?`call "${a$1}"`:`. "${a$1}"`);});ye.command("doctor [scope]").description("\u{1FA7A} Check RapidKit system health by default; use workspace for full workspace checks").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,o)=>{e&&e!=="workspace"&&(console.log(l.red(`Unknown doctor scope: ${e}`)),console.log(l.gray("Available: workspace")),console.log(l.gray("Usage: npx rapidkit doctor or npx rapidkit doctor workspace")),process.exit(1)),await Oo({...o,workspace:o.workspace||e==="workspace"});});ye.command("workspace <action> [subaction] [key] [value]").description("Manage RapidKit workspaces (list, sync, policy)").action(async(e,o,t,r)=>{if(e==="list"){let{listWorkspaces:i}=await import('./workspace-KRZ3DWL4.js');await i();}else if(e==="sync"){let i=Y(process.cwd());i||(console.log(l.red("\u274C Not inside a RapidKit workspace")),console.log(l.gray("\u{1F4A1} Run this command from within a workspace directory")),process.exit(1));let{syncWorkspaceProjects:n}=await import('./workspace-KRZ3DWL4.js');console.log(l.cyan(`\u{1F4C2} Scanning workspace: ${h.basename(i)}`)),await n(i);}else if(e==="policy"){let i=Y(process.cwd());i||(console.log(l.red("\u274C Not inside a RapidKit workspace")),console.log(l.gray("\u{1F4A1} Run this command from within a workspace directory")),process.exit(1));let n=await js(i,o,t,r);n!==0&&process.exit(n);}else console.log(l.red(`Unknown workspace action: ${e}`)),console.log(l.gray("Available: list, sync, policy")),process.exit(1);});function $r(){let e=a()?"npx rapidkit init; npx rapidkit dev":"npx rapidkit init && npx rapidkit dev";console.log(l.white(`Usage:
3631
+ \u274C An unexpected error occurred:`),console.error(t)),process.exit(1);}finally{$e=null;}});er(ye);$o(ye);ye.command("shell <action>").description("Shell helpers (activate virtualenv in current shell)").action(async e=>{e!=="activate"&&(console.log(l.red(`Unknown shell command: ${e}`)),process.exit(1));let o=process.cwd();function t(c){let p=c;for(;;){let d=h.join(p,".rapidkit","context.json");if(_.existsSync(d))return d;let u=h.dirname(p);if(u===p)break;p=u;}return null}let r=t(o);function i(c){let p=c;for(;;){let d=h.join(p,".venv"),u=h.join(p,".rapidkit","activate");if(_.existsSync(u)||_.existsSync(d))return {venv:d,activateFile:u};let m=h.dirname(p);if(m===p)break;p=m;}return null}let n=i(o);!r&&!n&&(console.log(l.yellow("No RapidKit project found in this directory")),process.exit(1));let a$1;n&&_.existsSync(n.activateFile)?a$1=n.activateFile:n&&_.existsSync(n.venv)?a$1=h$2(n.venv):(console.log(l.yellow("No virtual environment found")),process.exit(1));let s=a();console.log(s?`call "${a$1}"`:`. "${a$1}"`);});ye.command("doctor [scope]").description("\u{1FA7A} Check RapidKit system health by default; use workspace for full workspace checks").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,o)=>{e&&e!=="workspace"&&(console.log(l.red(`Unknown doctor scope: ${e}`)),console.log(l.gray("Available: workspace")),console.log(l.gray("Usage: npx rapidkit doctor or npx rapidkit doctor workspace")),process.exit(1));let t=await Rs({scope:e,workspaceFlag:o.workspace});t.detected&&!o.json&&(console.log(l.yellow("\u26A0\uFE0F Windows launcher shadow detected for doctor workspace checks.")),t.candidatePath&&console.log(l.gray(` Candidate: ${t.candidatePath}`)),console.log(l.gray(" Running npm-wrapper doctor workflow directly as safe fallback to avoid ambiguous rapidkit binary resolution."))),await Oo({...o,workspace:o.workspace||e==="workspace"});});ye.command("workspace <action> [subaction] [key] [value]").description("Manage RapidKit workspaces (list, sync, policy)").action(async(e,o,t,r)=>{if(e==="list"){let{listWorkspaces:i}=await import('./workspace-KRZ3DWL4.js');await i();}else if(e==="sync"){let i=Y(process.cwd());i||(console.log(l.red("\u274C Not inside a RapidKit workspace")),console.log(l.gray("\u{1F4A1} Run this command from within a workspace directory")),process.exit(1));let{syncWorkspaceProjects:n}=await import('./workspace-KRZ3DWL4.js');console.log(l.cyan(`\u{1F4C2} Scanning workspace: ${h.basename(i)}`)),await n(i);}else if(e==="policy"){let i=Y(process.cwd());i||(console.log(l.red("\u274C Not inside a RapidKit workspace")),console.log(l.gray("\u{1F4A1} Run this command from within a workspace directory")),process.exit(1));let n=await $s(i,o,t,r);n!==0&&process.exit(n);}else console.log(l.red(`Unknown workspace action: ${e}`)),console.log(l.gray("Available: list, sync, policy")),process.exit(1);});function $r(){let e=a()?"npx rapidkit init; npx rapidkit dev":"npx rapidkit init && npx rapidkit dev";console.log(l.white(`Usage:
3632
3632
  `)),console.log(l.cyan(` npx rapidkit <workspace-name> [options]
3633
3633
  `)),console.log(l.bold("Quick start \u2014 workspace workflow:")),console.log(l.cyan(" npx rapidkit my-workspace ")+l.gray("# Create workspace (interactive profile picker)")),console.log(l.cyan(" cd my-workspace")),console.log(l.cyan(" npx rapidkit bootstrap ")+l.gray("# Bootstrap all runtime toolchains")),console.log(l.cyan(" npx rapidkit create project ")+l.gray("# Interactive kit picker")),console.log(l.cyan(" cd my-api")),console.log(l.cyan(` ${e}
3634
3634
  `)),console.log(l.bold("Workspace profiles (asked during creation):")),console.log(l.gray(" minimal Foundation files only \u2014 fastest bootstrap (default)")),console.log(l.gray(" python-only Python + Poetry (FastAPI, Django, ML)")),console.log(l.gray(" node-only Node.js runtime (NestJS, Express, Next.js)")),console.log(l.gray(" go-only Go runtime (Fiber, Gin, gRPC)")),console.log(l.gray(" polyglot Python + Node.js + Go multi-runtime")),console.log(l.gray(` enterprise Polyglot + governance + Sigstore
@@ -3636,13 +3636,13 @@ Use "rapidkit help <command>" for more information.
3636
3636
  `)),console.log(l.bold("Options (workspace creation):")),console.log(l.gray(" -y, --yes Skip prompts and use defaults")),console.log(l.gray(" --author <name> Author/team name for workspace metadata")),console.log(l.gray(" --skip-git Skip git initialization")),console.log(l.gray(" --debug Enable debug logging")),console.log(l.gray(" --dry-run Show what would be created")),console.log(l.gray(" --create-workspace When creating a project outside a workspace: create and register a workspace in the current directory")),console.log(l.gray(" --no-workspace When creating a project outside a workspace: do not create a workspace")),console.log(l.gray(` --no-update-check Skip checking for updates
3637
3637
  `)),console.log(l.bold("Project commands (inside a project):")),console.log(l.gray(" npx rapidkit create project Scaffold a new project")),console.log(l.gray(" cd my-api Change directory to the new project")),console.log(l.gray(" npx rapidkit init Install project dependencies")),console.log(l.gray(" npx rapidkit dev Start dev server")),console.log(l.gray(" npx rapidkit build Build for production")),console.log(l.gray(` npx rapidkit test Run tests
3638
3638
  `)),console.log(l.bold("Flags clarification:")),console.log(l.gray(" --skip-install npm fast-path for lock/dependency steps")),console.log(l.gray(` --skip-essentials core flag for skipping essential module installation
3639
- `)),Gs?(console.log(l.bold("Legacy (shown because RAPIDKIT_SHOW_LEGACY=1):")),console.log(l.gray(" npx rapidkit my-project --template fastapi")),console.log(l.gray(" npx rapidkit my-project --template nestjs")),console.log(l.gray(` --skip-install Fast-path lock/deps (legacy template mode) \u2014 not same as --skip-essentials
3639
+ `)),Ms?(console.log(l.bold("Legacy (shown because RAPIDKIT_SHOW_LEGACY=1):")),console.log(l.gray(" npx rapidkit my-project --template fastapi")),console.log(l.gray(" npx rapidkit my-project --template nestjs")),console.log(l.gray(` --skip-install Fast-path lock/deps (legacy template mode) \u2014 not same as --skip-essentials
3640
3640
  `))):console.log(l.gray(`Tip: set RAPIDKIT_SHOW_LEGACY=1 to show legacy template flags in help.
3641
3641
  `));}var br="__rapidkit_signal_handlers_registered__",Rr=globalThis;Rr[br]||(Rr[br]=true,process.on("SIGINT",async()=>{if(!Lt){if(Lt=true,console.log(l.yellow(`
3642
3642
 
3643
- \u26A0\uFE0F Interrupted by user`)),$e&&await b.pathExists($e)){console.log(l.gray("Cleaning up partial installation..."));try{await b.remove($e),console.log(l.green("\u2713 Cleanup complete"));}catch(e){a$1.debug("Cleanup failed:",e);}}process.exit(130);}}),process.on("SIGTERM",async()=>{if(!Lt){if(Lt=true,a$1.debug("Received SIGTERM"),$e&&await b.pathExists($e))try{await b.remove($e);}catch(e){a$1.debug("Cleanup failed:",e);}process.exit(143);}}));var qs=process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test",Fs=(()=>{let e=process.argv[1];if(!e)return false;try{return _.realpathSync(e)===_.realpathSync(fileURLToPath(import.meta.url))}catch{return h.resolve(e)===h.resolve(fileURLToPath(import.meta.url))}})(),Hs=!qs||Fs;if(Hs){let e=process.argv.slice(2),o=e[0],t=process.cwd(),r=Er(t),i=_.existsSync(h.join(t,".rapidkit","project.json")),n=hr(o),a=o==="init"&&r&&!i;(e.length===0||e.length===1&&(o==="--help"||o==="-h"||o==="help"))&&(console.log(l.blue.bold(`
3643
+ \u26A0\uFE0F Interrupted by user`)),$e&&await b.pathExists($e)){console.log(l.gray("Cleaning up partial installation..."));try{await b.remove($e),console.log(l.green("\u2713 Cleanup complete"));}catch(e){a$1.debug("Cleanup failed:",e);}}process.exit(130);}}),process.on("SIGTERM",async()=>{if(!Lt){if(Lt=true,a$1.debug("Received SIGTERM"),$e&&await b.pathExists($e))try{await b.remove($e);}catch(e){a$1.debug("Cleanup failed:",e);}process.exit(143);}}));var Fs=process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test",Hs=(()=>{let e=process.argv[1];if(!e)return false;try{return _.realpathSync(e)===_.realpathSync(fileURLToPath(import.meta.url))}catch{return h.resolve(e)===h.resolve(fileURLToPath(import.meta.url))}})(),Ks=!Fs||Hs;if(Ks){let e=process.argv.slice(2),o=e[0],t=process.cwd(),r=Er(t),i=_.existsSync(h.join(t,".rapidkit","project.json")),n=hr(o),a=o==="init"&&r&&!i;(e.length===0||e.length===1&&(o==="--help"||o==="-h"||o==="help"))&&(console.log(l.blue.bold(`
3644
3644
  \u{1F680} Welcome to RapidKit NPM CLI!
3645
3645
  `)),$r(),process.exit(0)),n?ye.parse():a?ao(e).then(c=>process.exit(c)).catch(c=>{process.stderr.write(`RapidKit (npm) failed to run workspace init: ${c?.message??c}
3646
- `),process.exit(1);}):Ds().then(async c=>{if(!c){let p=process.argv.slice(2);if(process.env.RAPIDKIT_NPM_DEBUG_ARGS==="1"&&process.stderr.write(`[rapidkit-npm] argv=${JSON.stringify(p)}
3647
- `),hr(p[0])){ye.parse();return}if(p[0]==="create"){let u=await Sr(p);process.exit(u);}if(p[0]==="init"){let u=await ao(p);process.exit(u);}if(bs(p[0])){if(p[0]==="bootstrap"){let m=await Ts(p);process.exit(m);}if(p[0]==="setup"){let m=await As(p);process.exit(m);}if(p[0]==="cache"){let m=await Ns(p);process.exit(m);}let u=await $s(p);process.exit(u);}if(Pr.includes(p[0])){let u=p[0],m=Se(process.cwd()),w=Y(process.cwd());if(w){let g=h.join(w,".rapidkit","policies.yml");if(await b.pathExists(g))try{let R=await _.promises.readFile(g,"utf-8");if(((R.match(/^\s*enforcement_mode:\s*(warn|strict)\s*(?:#.*)?$/m)??R.match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m))?.[1]??"warn")==="strict"){let C=h.join(w,".rapidkit","toolchain.lock"),P=[];if(!await b.pathExists(C))P.push("toolchain.lock is missing \u2014 run `rapidkit bootstrap` first (strict mode requires a reproducible toolchain).");else try{let $=JSON.parse(await _.promises.readFile(C,"utf-8")).runtime??{};pe(m,process.cwd())&&!$.go?.version&&P.push("Go runtime version is not pinned in toolchain.lock \u2014 run `rapidkit setup go` first."),ue(m,process.cwd())&&!$.node?.version&&P.push("Node runtime version is not pinned in toolchain.lock \u2014 run `rapidkit setup node` first."),me(m,process.cwd())&&!$.python?.version&&P.push("Python runtime version is not pinned in toolchain.lock \u2014 run `rapidkit setup python` first.");}catch{}let G=h.join(w,".rapidkit","workspace.json");if(await b.pathExists(G))try{let $=JSON.parse(await _.promises.readFile(G,"utf-8")).profile??"";$==="python-only"&&(pe(m,process.cwd())||ue(m,process.cwd()))&&P.push('Workspace profile is "python-only" but this project is not Python. Update the workspace profile or use a polyglot workspace.'),$==="node-only"&&(pe(m,process.cwd())||me(m,process.cwd()))&&P.push('Workspace profile is "node-only" but this project is not Node. Update the workspace profile or use a polyglot workspace.'),$==="go-only"&&(me(m,process.cwd())||ue(m,process.cwd()))&&P.push('Workspace profile is "go-only" but this project is not Go. Update the workspace profile or use a polyglot workspace.');}catch{}if(P.length>0){console.log(l.red(`\u274C Strict policy violations block \`${u}\`:`));for(let N of P)console.log(l.red(` \u2022 ${N}`));console.log(l.gray("\u{1F4A1} Fix violations or switch to warn mode: set mode: warn in .rapidkit/policies.yml")),process.exit(1);}}}catch{}}let f=await Nr(process.cwd(),async()=>{if(pe(m,process.cwd())){let g=He("go",{runCommandInCwd:W,runCoreRapidkit:d$1}),R=u==="dev"?await g.runDev(process.cwd()):u==="test"?await g.runTest(process.cwd()):u==="build"?await g.runBuild(process.cwd()):await g.runStart(process.cwd());return R.message&&console.log(l.red(`\u274C ${R.message}`)),R.exitCode}if(ue(m,process.cwd()))return u==="dev"?await dt("dev",process.cwd()):u==="test"?await dt("test",process.cwd()):u==="build"?await dt("build",process.cwd()):await dt("start",process.cwd());if(me(m,process.cwd())){let g=He("python",{runCommandInCwd:W,runCoreRapidkit:d$1});return u==="dev"?(await g.runDev(process.cwd())).exitCode:u==="test"?(await g.runTest(process.cwd())).exitCode:u==="build"?(await g.runBuild(process.cwd())).exitCode:(await g.runStart(process.cwd())).exitCode}return -1});f.ok||process.exit(f.code),f.value>=0&&process.exit(f.value);}if(p[0]==="add"||p[0]==="module"&&p[1]==="add"){let u=Se(process.cwd());(u?.runtime==="go"||u?.module_support===false)&&(console.error(l.red("\u274C RapidKit modules are not available for Go projects.")),console.error(l.gray(" The module system requires Python and is only supported for FastAPI and NestJS projects.")),process.exit(1));}let d=await Ms(p);if(process.env.RAPIDKIT_NPM_DEBUG_ARGS==="1"&&process.stderr.write(`[rapidkit-npm] shouldForwardToCore=${d}
3648
- `),d){let u=await d$1(p,{cwd:process.cwd()});process.exit(u);}ye.parse();}});}export{ys as NPM_ONLY_TOP_LEVEL_COMMANDS,ks as WRAPPER_ORCHESTRATED_PROJECT_COMMANDS,Ts as handleBootstrapCommand,Ns as handleCacheCommand,Sr as handleCreateOrFallback,ao as handleInitCommand,$s as handleMirrorCommand,As as handleSetupCommand,Ms as shouldForwardToCore};
3646
+ `),process.exit(1);}):Gs().then(async c=>{if(!c){let p=process.argv.slice(2);if(process.env.RAPIDKIT_NPM_DEBUG_ARGS==="1"&&process.stderr.write(`[rapidkit-npm] argv=${JSON.stringify(p)}
3647
+ `),hr(p[0])){ye.parse();return}if(p[0]==="create"){let u=await Sr(p);process.exit(u);}if(p[0]==="init"){let u=await ao(p);process.exit(u);}if(bs(p[0])){if(p[0]==="bootstrap"){let m=await As(p);process.exit(m);}if(p[0]==="setup"){let m=await Os(p);process.exit(m);}if(p[0]==="cache"){let m=await js(p);process.exit(m);}let u=await Ds(p);process.exit(u);}if(Pr.includes(p[0])){let u=p[0],m=Se(process.cwd()),w=Y(process.cwd());if(w){let g=h.join(w,".rapidkit","policies.yml");if(await b.pathExists(g))try{let R=await _.promises.readFile(g,"utf-8");if(((R.match(/^\s*enforcement_mode:\s*(warn|strict)\s*(?:#.*)?$/m)??R.match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m))?.[1]??"warn")==="strict"){let C=h.join(w,".rapidkit","toolchain.lock"),E=[];if(!await b.pathExists(C))E.push("toolchain.lock is missing \u2014 run `rapidkit bootstrap` first (strict mode requires a reproducible toolchain).");else try{let $=JSON.parse(await _.promises.readFile(C,"utf-8")).runtime??{};pe(m,process.cwd())&&!$.go?.version&&E.push("Go runtime version is not pinned in toolchain.lock \u2014 run `rapidkit setup go` first."),ue(m,process.cwd())&&!$.node?.version&&E.push("Node runtime version is not pinned in toolchain.lock \u2014 run `rapidkit setup node` first."),me(m,process.cwd())&&!$.python?.version&&E.push("Python runtime version is not pinned in toolchain.lock \u2014 run `rapidkit setup python` first.");}catch{}let G=h.join(w,".rapidkit","workspace.json");if(await b.pathExists(G))try{let $=JSON.parse(await _.promises.readFile(G,"utf-8")).profile??"";$==="python-only"&&(pe(m,process.cwd())||ue(m,process.cwd()))&&E.push('Workspace profile is "python-only" but this project is not Python. Update the workspace profile or use a polyglot workspace.'),$==="node-only"&&(pe(m,process.cwd())||me(m,process.cwd()))&&E.push('Workspace profile is "node-only" but this project is not Node. Update the workspace profile or use a polyglot workspace.'),$==="go-only"&&(me(m,process.cwd())||ue(m,process.cwd()))&&E.push('Workspace profile is "go-only" but this project is not Go. Update the workspace profile or use a polyglot workspace.');}catch{}if(E.length>0){console.log(l.red(`\u274C Strict policy violations block \`${u}\`:`));for(let N of E)console.log(l.red(` \u2022 ${N}`));console.log(l.gray("\u{1F4A1} Fix violations or switch to warn mode: set mode: warn in .rapidkit/policies.yml")),process.exit(1);}}}catch{}}let f=await Nr(process.cwd(),async()=>{if(pe(m,process.cwd())){let g=He("go",{runCommandInCwd:W,runCoreRapidkit:d$1}),R=u==="dev"?await g.runDev(process.cwd()):u==="test"?await g.runTest(process.cwd()):u==="build"?await g.runBuild(process.cwd()):await g.runStart(process.cwd());return R.message&&console.log(l.red(`\u274C ${R.message}`)),R.exitCode}if(ue(m,process.cwd()))return u==="dev"?await dt("dev",process.cwd()):u==="test"?await dt("test",process.cwd()):u==="build"?await dt("build",process.cwd()):await dt("start",process.cwd());if(me(m,process.cwd())){let g=He("python",{runCommandInCwd:W,runCoreRapidkit:d$1});return u==="dev"?(await g.runDev(process.cwd())).exitCode:u==="test"?(await g.runTest(process.cwd())).exitCode:u==="build"?(await g.runBuild(process.cwd())).exitCode:(await g.runStart(process.cwd())).exitCode}return -1});f.ok||process.exit(f.code),f.value>=0&&process.exit(f.value);}if(p[0]==="add"||p[0]==="module"&&p[1]==="add"){let u=Se(process.cwd());(u?.runtime==="go"||u?.module_support===false)&&(console.error(l.red("\u274C RapidKit modules are not available for Go projects.")),console.error(l.gray(" The module system requires Python and is only supported for FastAPI and NestJS projects.")),process.exit(1));}let d=await Ls(p);if(process.env.RAPIDKIT_NPM_DEBUG_ARGS==="1"&&process.stderr.write(`[rapidkit-npm] shouldForwardToCore=${d}
3648
+ `),d){let u=await d$1(p,{cwd:process.cwd()});process.exit(u);}ye.parse();}});}export{ys as NPM_ONLY_TOP_LEVEL_COMMANDS,ks as WRAPPER_ORCHESTRATED_PROJECT_COMMANDS,Rs as detectWindowsDoctorWorkspaceShadow,As as handleBootstrapCommand,js as handleCacheCommand,Sr as handleCreateOrFallback,ao as handleInitCommand,Ds as handleMirrorCommand,Os as handleSetupCommand,Ls as shouldForwardToCore};
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rapidkit",
3
- "version": "0.25.4",
3
+ "version": "0.25.5",
4
4
  "type": "module",
5
5
  "description": "Official CLI for RapidKit, an open-source workspace platform that standardizes how teams build, scale, and deploy backend services.",
6
6
  "keywords": [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rapidkit",
3
- "version": "0.25.4",
3
+ "version": "0.25.5",
4
4
  "type": "module",
5
5
  "description": "Official CLI for RapidKit, an open-source workspace platform that standardizes how teams build, scale, and deploy backend services.",
6
6
  "keywords": [