@flisk-sh/flisk 1.3.200 → 1.3.204

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.
Files changed (32) hide show
  1. package/cli/dist/cli.js +9 -0
  2. package/cli/dist/commands/doctor.js +22 -0
  3. package/cli/dist/commands/open.js +24 -3
  4. package/cli/dist/utils/cold-preflight.js +14 -0
  5. package/cli/dist/utils/colima.js +144 -0
  6. package/cli/dist/utils/doctor-fix.js +78 -1
  7. package/cli/dist/utils/stack-progress.js +8 -5
  8. package/cli/dist/utils/up-readiness.js +9 -2
  9. package/cli/dist-bundle/{chunk-RMZQU74X.js → chunk-BS6G2SLM.js} +1 -1
  10. package/cli/dist-bundle/{chunk-LMHKXU2Q.js → chunk-CBFVK3TF.js} +1 -1
  11. package/cli/dist-bundle/{chunk-GEXOZCEQ.js → chunk-EPBYRJE3.js} +1 -1
  12. package/cli/dist-bundle/chunk-GD5676UE.js +52 -0
  13. package/cli/dist-bundle/chunk-MKJNQTIN.js +2 -0
  14. package/cli/dist-bundle/{chunk-IYZENTVI.js → chunk-QSPFSZCS.js} +2 -2
  15. package/cli/dist-bundle/{chunk-WUO7C6WO.js → chunk-RFHMXJTK.js} +1 -1
  16. package/cli/dist-bundle/{chunk-DS47LHYF.js → chunk-WMF4AFAE.js} +1 -1
  17. package/cli/dist-bundle/chunk-Z6UD7UZH.js +24 -0
  18. package/cli/dist-bundle/chunk-ZVGY7COV.js +4 -0
  19. package/cli/dist-bundle/cli.js +80 -80
  20. package/cli/dist-bundle/cold-preflight-FXOZ5SR5.js +2 -0
  21. package/cli/dist-bundle/colima-4ID4BGHC.js +2 -0
  22. package/cli/dist-bundle/{open-PF6BGKCR.js → open-UQ6DF3XN.js} +1 -1
  23. package/cli/dist-bundle/{project-2TVWT57J.js → project-GTYHCCFG.js} +1 -1
  24. package/cli/dist-bundle/stack-progress-6GO2TCRH.js +2 -0
  25. package/cli/dist-bundle/{tilt-port-owner-7O5FOW5C.js → tilt-port-owner-KLNX2ZI2.js} +1 -1
  26. package/cli/package.json +1 -1
  27. package/package.json +1 -1
  28. package/cli/dist-bundle/chunk-EICMGZXL.js +0 -5
  29. package/cli/dist-bundle/chunk-H446NBVS.js +0 -71
  30. package/cli/dist-bundle/chunk-RWNIFXXG.js +0 -4
  31. package/cli/dist-bundle/cold-preflight-LPH7WF3B.js +0 -2
  32. package/cli/dist-bundle/stack-progress-UVREHNNB.js +0 -2
@@ -0,0 +1,52 @@
1
+ import{createRequire as __tdkRequire}from'node:module';const require=__tdkRequire(import.meta.url);
2
+ import{f as O,g as ht,h as gt,i as kt,j as Q,k as St,l as yt,m as xt,n as Pt,o as wt,p as Z,q as vt,s as bt,t as Dt}from"./chunk-BS6G2SLM.js";import{b as H,c as Tt,d as ge}from"./chunk-MKJNQTIN.js";import{a as dt,f as ut,g as Y,j as Ct,k as $t,l as Nt,n as Et,o as ke,p as Se,r as ye,s as xe,t as Rt,u as Pe,v as Ot}from"./chunk-Z6UD7UZH.js";import{i as ft,o as mt}from"./chunk-WMF4AFAE.js";import{c as pt}from"./chunk-42IVF3YT.js";import{Aa as ct,Ba as lt,Ca as he,G as Ze,O as C,Ta as x,b as v,fa as et,h as F,ja as tt,k as M,l as W,m as ue,ma as st,na as fe,o as pe,oa as z,pa as nt,qa as rt,s as g,t as Ye,ua as me,va as ot,wa as X,x as $,xa as it,y as Qe,ya as at}from"./chunk-CBFVK3TF.js";import{b as h}from"./chunk-CF46CD6R.js";import{execFileSync as Ds}from"node:child_process";import{readFileSync as _r}from"node:fs";import{join as Ar}from"node:path";import{execFileSync as Vn,execSync as ls}from"node:child_process";import{existsSync as D,readdirSync as Wn,readFileSync as L}from"node:fs";import{join as P,normalize as Le,relative as Be}from"node:path";import{Command as Un}from"commander";import{existsSync as Rs}from"node:fs";var ee="docs/agent-hosts.md",we=`WebContainers cannot run Flisk: there is no Docker daemon or Tilt. Run \`flisk up\` on a machine with Docker. See ${ee}.`,_t=`Docker is not reachable from this Dev Container. Mount the host Docker socket (-v /var/run/docker.sock:/var/run/docker.sock) or add the docker-outside-of-docker feature to devcontainer.json, then retry. Docker-in-docker is not supported. See ${ee}.`;function Os(){return{env:process.env,versions:process.versions,platform:process.platform,fileExists:Rs}}function At(e=Os()){let{env:t,versions:s,platform:n,fileExists:r}=e;return s.webcontainer?{kind:"webcontainer",canUp:!1}:t.CODESPACES==="true"?{kind:"codespaces",canUp:!0}:t.REMOTE_CONTAINERS||r("/.dockerenv")&&t.DEVCONTAINER?{kind:"devcontainer",canUp:!0}:n==="win32"?{kind:"native-windows",canUp:t.TDK_ALLOW_NATIVE_WINDOWS==="1"}:n==="linux"&&t.WSL_DISTRO_NAME?{kind:"wsl2",canUp:!0}:{kind:"local",canUp:!0}}function jt(e){return e==="devcontainer"||e==="codespaces"}function te(e){return e.some(t=>et(t.config?.appType)||t.config?.appType==="frontend"||t.config?.appType==="worker")}import{existsSync as _s,readFileSync as As}from"node:fs";import{join as js,relative as It,resolve as Ft,sep as Is}from"node:path";var Fs=2,Mt=["services/*/*"];function Ht(e){return e.split(Is).filter(Boolean)}function Ms(e,t){let s=0,n=0,r=-1,o=0;for(;n<t.length;)if(s<e.length&&e[s]!=="*"&&(e[s]==="?"||e[s]===t[n]))s++,n++;else if(s<e.length&&e[s]==="*")r=s++,o=n;else if(r!==-1)s=r+1,n=++o;else return!1;for(;s<e.length&&e[s]==="*";)s++;return s===e.length}function Hs(e,t){return e.length===t.length&&e.every((s,n)=>Ms(s,t[n]))}function ve(e){let t=js(e,".tdk",M);if(!_s(t))return Mt;try{let s=JSON.parse(As(t,"utf-8"))?.discovery?.paths;if(Array.isArray(s)&&s.every(n=>typeof n=="string"))return s}catch{}return Mt}function se(e,t,s){let n=Ht(It(e,Ft(e,t)));return s.some(r=>{let o=Ht(It(e,Ft(e,r)));for(let i=0;i<=Fs;i++){let a=n.length-i;if(a>0&&Hs(o,n.slice(0,a)))return!0}return!1})}function qr(e,t,s,n){let r=ve(e);if(se(e,t,r))return{path:t};let o=`services/${s}/${n}`;return se(e,o,r)?{path:o,adjustedFrom:t}:{path:t}}import{execFile as Ls}from"node:child_process";import{promisify as Bs}from"node:util";var Vs=Bs(Ls),Ws=1e4,Us=5,Lt=10*6e4,Gs=3,Ks=200,Js=async e=>{let{stdout:t,stderr:s}=await Vs("docker",e,{encoding:"utf-8",timeout:Ws,windowsHide:!0});return`${t}${s}`};function qs(e,t){let s=Ct(t).toLowerCase(),n=e.replace(/-/g,"_").toLowerCase();return n===s||n.startsWith(`${s}_`)}function zs(e,t=Date.now()){if(e.status==="restarting")return!0;if(e.restartCount<Us)return!1;if(e.status==="running"){let n=Date.parse(e.startedAt);return Number.isNaN(n)||t-n<Lt}let s=Date.parse(e.finishedAt??"");return e.exitCode!==0&&!Number.isNaN(s)&&t-s<Lt}function Xs(e,t){let s=/database "([^"]+)" does not exist/i.exec(e);return s?`database "${s[1]}" does not exist: re-run the project's database provisioning (flisk up) or create it`:/Cannot find module|MODULE_NOT_FOUND|module not found/i.test(e)?"a module is missing from the image: rebuild it (flisk up --force) after checking the resource's dependencies":/EADDRINUSE|address already in use/i.test(e)?"the port inside the container is already in use: check for two processes started by the same command":/ECONNREFUSED|connection refused|could not connect/i.test(e)?"a dependency is not reachable: check that the service it connects to is running and healthy":/\b(?:environment variable|env var)\b.*\b(?:missing|not set|required|undefined)\b/i.test(e)||/\b[A-Z][A-Z0-9_]{2,}\b (?:is )?(?:not set|required|missing)\b/.test(e)?"a required environment variable is missing: check the project's .env":t.exitCode===137?"killed (exit 137), usually out of memory: raise the container's memory limit":null}function Ys(e){let t=[];for(let s of e.split(/\r?\n/)){let[n,r,o,i,a,c]=s.split(" ");!n||r===void 0||t.push({name:n.replace(/^\//,""),restartCount:Number(r)||0,status:o??"",startedAt:i??"",exitCode:Number(a)||0,finishedAt:c??""})}return t}async function Bt(e,t=[],s=Js,n=Date.now()){let r="Crash-looping containers",o;try{o=(await s(["ps","-a","--format",'{{.ID}} {{.Label "com.docker.compose.project"}}'])).split(/\r?\n/).map(m=>m.split(" ")).filter(([m,u])=>m&&u&&qs(u,e)).map(([m])=>m)}catch{return{name:r,didPass:!0,isSkipped:!0,message:"Docker not available - skipped crash-loop check"}}if(o.length===0)return{name:r,didPass:!0,isSkipped:!0,message:"No project containers to check"};let i;try{i=Ys(await s(["inspect","--format","{{.Name}} {{.RestartCount}} {{.State.Status}} {{.State.StartedAt}} {{.State.ExitCode}} {{.State.FinishedAt}}",...o]))}catch{return{name:r,didPass:!0,isSkipped:!0,message:"Containers changed while checking - skipped crash-loop check"}}let a=i.filter(f=>zs(f,n));if(a.length===0)return{name:r,didPass:!0,message:"No project container is crash-looping"};let c=[],l=new Set;for(let f of a){let m="";try{m=await s(["logs","--tail",String(Gs),f.name])}catch{}let u=z(m,t).split(/\r?\n/).map(k=>k.trim().slice(0,Ks)).filter(Boolean),S=Xs(m,f);S&&l.add(S),c.push([`${f.name}: ${f.status}, restarted ${f.restartCount} times`,...u.map(k=>` | ${k}`)].join(`
3
+ `))}return{name:r,didPass:!1,message:`${a.length} container${a.length===1?" is":"s are"} crash-looping:
4
+ ${c.join(`
5
+ `)}`,fix:[...l,"Read the full log: docker logs <container>"].join("; ")}}import{execFile as un,execFileSync as pn}from"node:child_process";import{realpathSync as Jt,statfsSync as fn}from"node:fs";import{homedir as mn}from"node:os";import{join as hn}from"node:path";import{promisify as gn}from"node:util";import{statfsSync as Qs}from"node:fs";import{homedir as Zs}from"node:os";var ne="Disk Space",en=1024**3,tn=2,be=10,Vt=["Free disk space, then retry: flisk doctor"," docker system prune -af # unused images and build cache (needs Docker running)"," npm cache clean --force"," bun pm cache rm"," brew cleanup -s"].join(`
6
+ `);function Wt(e=Qs,t=Zs()){let s;try{let r=e(t);s=Number(r.bavail)*Number(r.bsize)/en}catch{return{name:ne,didPass:!0,isSkipped:!0,message:"Could not read free disk space"}}let n=`${s.toFixed(1)} GB free`;return s<tn?{name:ne,didPass:!1,message:`${n}: Docker cannot build or start containers`,fix:Vt}:s<be?{name:ne,didPass:!1,isWarning:!0,message:`${n}: image builds may fail`,fix:Vt}:{name:ne,didPass:!0,message:n}}var sn="Quit Docker Desktop completely (whale icon > Quit Docker Desktop), reopen it, and wait until it shows Running. If it keeps getting stuck, check free disk space. Then retry: flisk doctor";function Ut(e,t=process.platform){return t!=="darwin"||!e?null:{name:"Container Runtime",didPass:!1,message:"Docker Desktop is open, but its engine is not responding",fix:sn}}import{execFileSync as nn}from"node:child_process";var De=(e,t)=>nn(e,t,{encoding:"utf-8",stdio:"pipe",windowsHide:!0}),Gt=["traefik-public","traefik-private","backend","database","infisical-network","verdaccio-network","proxy"];function Te(e){let t=e.replace(/-/g,"_");return Gt.map(s=>`${t}_${s}`)}function Kt(e){let t=new Set;for(let s of e)for(let n of["traefik-public","traefik-private"])s.endsWith(`_${n}`)&&t.add(s.slice(0,-(n.length+1)));return t}function Ce(e,t){for(let s of Gt)if(e.endsWith(`_${s}`)){let n=e.slice(0,-(s.length+1));if(t.has(n))return n}return null}function oo(e,t=De){let s=new Set(t("docker",["network","ls","--format","{{.Name}}"]).split(/\r?\n/).map(r=>r.trim()).filter(Boolean)),n={removed:[],kept:[]};for(let r of Te(e))if(s.has(r))try{t("docker",["network","rm",r]),n.removed.push(r)}catch(o){let i=String(o.stderr??o).trim();n.kept.push({name:r,reason:i.split(/\r?\n/)[0]??""})}return n}function re(e,t=process.platform,s=De){if(t==="win32")return[];let n;try{n=s("ps",["-axo","pid=,command="])}catch{return[]}let r=[];for(let o of n.split(/\r?\n/)){let i=/^\s*(\d+)\s+(.*)$/.exec(o);if(!i)continue;let a=i[2]??"",c=(a.split(/\s+/)[0]??"").split("/").at(-1),l=` -f ${e}`,f=a.indexOf(l),m=a[f+l.length];c==="tilt"&&/^\S+\s+up\s/.test(a)&&f>0&&(m===void 0||m===" ")&&r.push(Number(i[1]))}return r}function io(e,t=process.platform,s=De){let n=re(e,t,s);for(let r of n)try{s("kill",["-TERM",String(r)])}catch{}return n}async function ao(e,t=8e3,s=re){let n=Date.now()+t;for(;s(e).length>0;){if(Date.now()>=n)return!1;await new Promise(r=>setTimeout(r,250))}return!0}import{execFile as rn}from"node:child_process";function $e(e){return new Promise(t=>{rn($("tilt")??"tilt",["get","uiresources","-o","json","--port",String(e)],{timeout:15e3,maxBuffer:16*1024*1024},(s,n)=>t(s?null:n))})}function on(e){let s=(JSON.parse(e).items??[]).filter(n=>n.status?.disableStatus?.state!=="Disabled").map(n=>n.status?.updateStatus==="not_applicable"?{...n,status:{...n.status,updateStatus:"ok"}}:n);return JSON.stringify({items:s})}function an(e){return(JSON.parse(e).items??[]).filter(t=>t.status?.disableStatus?.state!=="Disabled").flatMap(t=>t.metadata?.name?[t.metadata.name]:[])}function cn(e,t){let s=JSON.parse(e).items??[],n=new Map(s.map(r=>[r.metadata?.name,r]));return{missing:t.filter(r=>!n.has(r)),disabled:t.filter(r=>n.get(r)?.status?.disableStatus?.state==="Disabled")}}function ln(e){return e.endsWith("-typecheck")}function dn(e,t,s){let n=Nt(on(e),t),r=n.failures.filter(i=>!ln(i.name)),o={ready:r.length===0&&n.pendingCount===0&&n.okCount>0,failures:r.map(i=>({name:i.name,message:i.error||`${i.updateStatus}/${i.runtimeStatus}`})),pending:n.pendingCount,timedOut:!1,enabled:an(e)};if(s&&s.length>0){let{missing:i,disabled:a}=cn(e,s);if(i.length>0&&(o={...o,ready:!1,pending:o.pending+i.length}),a.length>0)return{settled:!0,result:{...o,ready:!1,failures:[...o.failures,...a.map(c=>({name:c,message:"disabled in Tilt"}))]}}}return{result:o,settled:o.ready||o.failures.length>0&&o.pending===0}}async function fo(e,t={}){let s=t.timeoutMs??Number(process.env.TDK_UP_READY_TIMEOUT_MS??9e5),n=t.intervalMs??2e3,r=t.fetchJson??$e,o=t.deferred??$t(),i=Date.now()+s,a={ready:!1,failures:[],pending:0,timedOut:!1,enabled:[]};for(;;){let c=await r(e);if(c)try{let l=dn(c,o,t.expected);if(a=l.result,l.settled||a.failures.length>0&&t.isStalled?.(c))return a}catch{}if(Date.now()>=i)return{...a,ready:!1,timedOut:!0};await new Promise(l=>setTimeout(l,n))}}var U=gn(un),kn=15e3,Sn=/^tdk_doctor_probe_(\d+)$/,yn=async e=>{let{stdout:t}=await U("docker",e,{encoding:"utf-8",timeout:kn,windowsHide:!0});return t};function xn(){try{return pn("docker",["info","--format","{{.ServerVersion}}"],{encoding:"utf-8",timeout:15e3,stdio:["ignore","pipe","ignore"]}),!0}catch{return!1}}function Ne(e){return String(e.stderr??e).trim().split(/\r?\n/)[0]??""}var Pn=120;function wn(e){let t=/^\s*(?:(?:(\d+)-)?(\d+):)?(\d+):(\d+)\s*$/.exec(e);if(!t)return null;let[,s="0",n="0",r="0",o="0"]=t;return((Number(s)*24+Number(n))*60+Number(r))*60+Number(o)}async function vn(e,t=$e,s=2,n=r=>new Promise(o=>setTimeout(o,r))){for(let r=0;r<s;r++){r>0&&await n(1e3);for(let o of e)if(await t(o)!==null)return!0}return!1}async function bn(e){if(process.platform==="win32")return"unknown";try{let{stdout:t}=await U("ps",["-p",String(e),"-o","etime="],{encoding:"utf-8",timeout:5e3}),s=wn(t);if(s===null||s<Pn)return"unknown";let{stdout:n}=await U("lsof",["-nP","-a","-p",String(e),"-iTCP","-sTCP:LISTEN","-Fn"],{encoding:"utf-8",timeout:5e3}),r=[...n.matchAll(/^n.*:(\d+)$/gm)].map(o=>Number(o[1]));return await vn(r)?"healthy":"stale"}catch{return"unknown"}}function Dn(e=yn){return{colima:Tn,colimaStatus:()=>H(),dockerAnswers:xn,async listNetworks(){let t=(await e(["network","ls","--format","{{.Name}}"])).split(/\r?\n/).map(n=>n.trim()).filter(Boolean);return(await Promise.all(t.map(async n=>{try{let r=await e(["network","inspect","--format","{{len .Containers}}",n]);return{name:n,containers:Number(r.trim())||0}}catch(r){if(/no such network|not found/i.test(String(r)))return null;throw r}}))).filter(n=>n!==null)},async removeNetwork(t){try{await e(["network","rm",t])}catch(s){throw new Error(Ne(s))}},freeDiskGib(){try{let t=fn(mn());return Number(t.bavail)*Number(t.bsize)/1024**3}catch{return null}},async reclaimable(){let t=null;try{let n=await e(["system","df","--format","{{.Type}} {{.Reclaimable}}"]);for(let r of n.split(/\r?\n/)){let[o,i]=r.split(" ");o==="Build Cache"&&i&&(t=i.replace(/\s*\(.*\)/,"").trim())}}catch{}let s=0;try{s=(await e(["images","-q","-f","dangling=true"])).split(/\r?\n/).filter(Boolean).length}catch{}return{buildCache:t,danglingImages:s}},async prune(t){try{await e(t==="builder"?["builder","prune","-f"]:["image","prune","-f"])}catch(s){throw new Error(Ne(s))}},async tiltStatus(t){return bn(t)},stopProcess(t){process.kill(t,"SIGTERM")},isProcessAlive(t){try{return process.kill(t,0),!0}catch(s){return s.code==="EPERM"}}}}var qt=Dn();async function Tn(e){let t=ge(),s=t?{...process.env,PATH:`${t}:${process.env.PATH??""}`}:process.env;await U("colima",[e],{encoding:"utf-8",timeout:3e5,env:s})}async function zt(e,t=qt,s={}){let n=[],r=[];for(let u of s.tiltPids??[])await t.tiltStatus(u)==="stale"?n.push({id:`stop-tilt:${u}`,check:"Tilt processes",scope:"project",command:`kill -TERM ${u}`,status:"planned",reason:"this project's Tilt is running but its UI does not answer"}):r.push(u);let o=r.length>0?`Tilt is running for this project (pid ${r.join(", ")}); run flisk down first`:void 0,i=t.colimaStatus(),a=Tt(i,t.dockerAnswers());if(a==="start")n.push({id:"colima:start",check:"Colima",scope:"host",command:"colima start",status:"planned",reason:i.problem??"the Colima VM is not running"});else if(a==="restart")n.push({id:"colima:restart",check:"Colima",scope:"host",command:"colima restart",status:"planned",reason:"the Colima VM is running but its Docker daemon does not answer"});else if(a==="native-lima"){let u=ge();n.push({id:"colima:native-lima",check:"Colima",scope:"host",command:u?`PATH="${u}:$PATH" colima status`:"brew reinstall lima",status:u?"skipped":"planned",reason:u?`the colima CLI on this PATH cannot see the VM; a native limactl is installed in ${u} (add it to PATH)`:"the colima CLI on this PATH cannot see the VM; lima is installed as an x86_64 build (brew reinstall lima)"})}let c=await t.listNetworks(),l=t.freeDiskGib();if(l!==null&&l<be){let{buildCache:u,danglingImages:S}=await t.reclaimable(),k=`${l.toFixed(1)} GB free`;u&&!/^0(\.0+)?\s*B$/i.test(u)&&n.push({id:"prune:builder",check:"Disk Space",scope:"host",command:"docker builder prune -f",status:"planned",reason:`${k}; ${u} of build cache reclaimable`}),S>0&&n.push({id:"prune:images",check:"Disk Space",scope:"host",command:"docker image prune -f",status:"planned",reason:`${k}; ${S} untagged image${S===1?"":"s"}`})}let f=new Set(e?Te(e):[]),m=Kt(c.map(u=>u.name));for(let u of c){let S=Sn.exec(u.name),k,y,p="unused network";if(S)k="probe",y="Orphaned probe networks";else if(f.has(u.name))k="project",y="Docker networks";else if(s.machine&&Ce(u.name,m))k="machine",y="Docker networks",p=`unused network of project "${Ce(u.name,m)}"`;else continue;let b={id:`remove-network:${u.name}`,check:y,scope:k,command:`docker network rm ${u.name}`,status:"planned",reason:p};u.containers>0?(b.status="skipped",b.reason=`${u.containers} container(s) still attached`):k==="project"&&o?(b.status="skipped",b.reason=o):S&&t.isProcessAlive(Number(S[1]))&&(b.status="skipped",b.reason=`probe of a running process (pid ${S[1]})`),n.push(b)}return n}async function Xt(e,t,s=qt){let n=[];for(let r of e){if(r.status!=="planned"||t.dryRun){n.push(r);continue}if(!t.confirm){n.push({...r,status:"skipped",reason:"confirmation required; run in a terminal or pass --yes"});continue}let o=!1;try{o=await t.confirm(r)}catch{}if(!o){n.push({...r,status:"skipped",reason:"not confirmed"});continue}try{if(r.id.startsWith("prune:")){await s.prune(r.id==="prune:builder"?"builder":"images"),n.push({...r,status:"applied",reason:"pruned"});continue}if(r.id.startsWith("colima:")){let i=r.id.slice(7);if(i==="start"||i==="restart"){await s.colima(i),n.push({...r,status:"applied",reason:`colima ${i} ran`});continue}n.push({...r,status:"skipped",reason:"needs a native lima: see the command"});continue}if(r.id.startsWith("stop-tilt:")){s.stopProcess(Number(r.id.slice(10))),n.push({...r,status:"applied",reason:"stopped"});continue}await s.removeNetwork(r.id.slice(15)),n.push({...r,status:"applied",reason:"removed"})}catch(i){n.push({...r,status:"failed",reason:Ne(i)})}}return n}function Yt(e){return e.some(t=>t.status==="failed")}async function Cn(e){try{let{stdout:t}=await U(e,["--version"],{encoding:"utf-8",timeout:5e3,windowsHide:!0});return t.trim().split(/\r?\n/)[0]||null}catch{return null}}async function $n(e=Qe("flisk"),t=Cn){let s=new Set,n=[];for(let r of e){let o=r;try{o=Jt(r)}catch{}s.has(o)||(s.add(o),n.push({path:r,version:await t(r)}))}return n}async function Qt(e){let t=e??await $n();if(t.length<=1)return{name:"Flisk installs",didPass:!0,message:"One flisk install on PATH"};let s=t.map(r=>`${r.path} (${r.version??"version unknown"})`).join(", "),n=new Set(t.map(r=>r.version));return{name:"Flisk installs",didPass:!1,isWarning:!0,message:`${t.length} flisk installs on PATH${n.size>1?" with different versions":""}: ${s}`,fix:"Keep one: remove the others, or run flisk upgrade. The first on PATH is the one your shell runs; tools that launch /usr/local/bin/flisk directly may use another"}}function Zt(e,t=re){let s=new Set([e]);try{s.add(Jt(e))}catch{}let n=new Set;for(let r of s)for(let o of t(hn(r,".tdk",".tdk-out","Tiltfile")))n.add(o);return[...n]}var Ee=1;function Nn(e,t=[]){return{schemaVersion:Ee,data:e,errors:t}}function En(e){return e instanceof Ze?{error:{code:"COMMAND_FAILED",message:e.message,...e.suggestions.length>0?{suggestions:e.suggestions}:{}},exitCode:e.exitCode}:{error:{code:"INTERNAL",message:e instanceof Error?e.message:String(e)},exitCode:2}}function Co(e){let t=En(e);console.log(JSON.stringify(Nn(null,[t.error]))),console.error(t.error.message),process.exit(t.exitCode)}async function ts(e,t){let s=[],n=[],r=o=>{o.status==="fulfilled"?s.push(o.value):n.push({code:"INTERNAL",message:o.reason instanceof Error?o.reason.message:String(o.reason)})};for(let o of await Promise.allSettled(e.map(i=>Promise.resolve().then(i))))r(o);for(let o of t)for(let i of await Promise.allSettled([Promise.resolve().then(o)]))r(i);return{checks:s,errors:n}}function es(e){let t=e.find(s=>s.name===v);return t?t.didPass:null}function j(e,t,s=[],n,r){return{schemaVersion:Ee,data:{ready:s.length===0&&e.every(o=>o.didPass||o.isSkipped||o.isWarning),inProject:t,checks:e,...r?{host:{...r,containerRuntimeReachable:es(e),canUp:r.canUp&&es(e)!==!1}}:{},...n!==void 0?{ports:{http:{requested:n?.requested.ingressHttp??80,chosen:n?.ingressHttp??null,explicit:n?.explicit.ingressHttp??!!process.env.TDK_HTTP_PORT,reason:n?.reason.ingressHttp??"port planning failed"},https:{requested:n?.requested.ingressHttps??443,chosen:n?.ingressHttps??null,explicit:n?.explicit.ingressHttps??!!process.env.TDK_HTTPS_PORT,reason:n?.reason.ingressHttps??"port planning failed"},postgres:{requested:n?.requested.postgres??5432,chosen:n?.postgres??null,explicit:n?.explicit.postgres??!!process.env.TDK_POSTGRES_PORT,reason:n?.reason.postgres??"port planning failed"}}}:{}},errors:s}}function ss(e){return e.errors.length>0?2:e.data.ready?0:1}import{existsSync as Oe,readFileSync as ns}from"node:fs";import{dirname as Rn,join as Re,normalize as On}from"node:path";function _n(e){let t=new Set,s=/^load\s*\(([\s\S]*?)\)/gm;for(let n of e.matchAll(s)){let r=n[1]??"",o=/["']([^"']+)["']/g,i=Array.from(r.matchAll(o),a=>a[1]);for(let a of i.slice(1))a.startsWith("_")&&t.add(a)}return Array.from(t).sort()}function rs(e,t,s){return t==="ext://tdk-cli"?Re(s,".tdk",".tdk-out","tdk-cli-ext","Tiltfile"):t.startsWith(".")||!t.includes("://")&&!t.startsWith("@")?On(Re(Rn(e),t)):null}function An(e,t,s){let n=[],r=/^load\s*\(([\s\S]*?)\)/gm;for(let o of t.matchAll(r)){let c=(o[1]??"").match(/["']([^"']+)["']/)?.[1];if(!c)continue;let l=rs(e,c,s);l&&(Oe(l)||n.push(`${e}: ${c} -> ${l}`))}return n}function jn(e,t,s){let n=[],r=/^load\s*\(([\s\S]*?)\)/gm;for(let o of t.matchAll(r)){let c=(o[1]??"").match(/["']([^"']+)["']/)?.[1];if(c){let l=rs(e,c,s);l&&n.push(l)}}return n}function In(e,t){let s=new Set,n=[e];for(;n.length>0;){let r=n.pop();if(!r||s.has(r)||!Oe(r))continue;s.add(r);let o=ns(r,"utf-8");for(let i of jn(r,o,t))s.has(i)||n.push(i)}return Array.from(s).sort()}function os(){let e=g()??process.cwd(),t=Re(e,".tdk",".tdk-out","Tiltfile");if(!Oe(t))return{name:"Starlark Load Exports",didPass:!0,isSkipped:!0,message:"No generated Tiltfile to check"};let s=[],n=[],r=In(t,e);for(let i of r){let a=ns(i,"utf-8"),c=_n(a);c.length>0&&s.push(`${i}: ${c.join(", ")}`);for(let l of An(i,a,e))n.push(l)}if(s.length===0&&n.length===0)return{name:"Starlark Load Exports",didPass:!0,message:`${C(r.length,"reachable Starlark file")} ${r.length===1?"has":"have"} valid load exports and paths`};let o=[];return s.length>0&&o.push(`Private exported symbols:
7
+ ${s.join(`
8
+ `)}`),n.length>0&&o.push(`Missing relative load targets:
9
+ ${n.join(`
10
+ `)}`),{name:"Starlark Load Exports",didPass:!1,message:`Starlark load() issues will stop Tilt before services start:
11
+ ${o.join(`
12
+
13
+ `)}`,fix:"Regenerate with a current Flisk (`flisk config regenerate`). If the issue remains, rename loaded symbols without leading underscores and update stale load paths."}}import{relative as Fn}from"node:path";function oe(e,t){return Fn(e,t.configPath)||t.configPath}function is(e){let t=e.config?.dependsOn;return t===void 0?[]:Array.isArray(t)&&t.every(s=>typeof s=="string")?t:null}function Mn(e){let t=new Set(e.map(a=>a.name)),s=new Map(e.map(a=>[a.name,(is(a)??[]).filter(c=>t.has(c))])),n=new Map,r=new Map,o=[],i=a=>{r.set(a,"visiting"),o.push(a);for(let c of s.get(a)??[])if(r.get(c)==="visiting"){let l=o.slice(o.indexOf(c)),f=l.indexOf([...l].sort()[0]??c),m=[...l.slice(f),...l.slice(0,f)];n.set(m.join(">"),[...m,m[0]??c])}else r.has(c)||i(c);o.pop(),r.set(a,"done")};for(let a of[...s.keys()].sort())r.has(a)||i(a);return[...n.values()]}function _e(e=g()??process.cwd(),t=x(e)){let s=t.flatMap(n=>is(n)===null?[`${oe(e,n)} dependsOn ${JSON.stringify(n.config?.dependsOn)}: expected an array of service names`]:[]);return s.length===0?{name:"dependsOn",didPass:!0,message:"Every dependsOn is a list of service names"}:{name:"dependsOn",didPass:!1,message:`${C(s.length,"invalid dependsOn","invalid dependsOn")}:
14
+ ${s.join(`
15
+ `)}`,fix:'Write "dependsOn" as an array of service names, for example ["postgres", "api"]'}}function Ae(e=g()??process.cwd(),t=x(e)){let s=new Map(t.map(o=>[o.name,o])),n=Mn(t);if(n.length===0)return{name:"Circular dependencies",didPass:!0,message:"No service depends on itself through dependsOn"};let r=n.map(o=>{let i=s.get(o[0]??""),a=o[1]??"";return`${i?oe(e,i):o[0]} dependsOn "${a}": circular dependency ${o.join(" -> ")}`});return{name:"Circular dependencies",didPass:!1,message:`${n.length} ${n.length===1?"circular dependency":"circular dependencies"}:
16
+ ${r.join(`
17
+ `)}`,fix:'Remove one "dependsOn" entry in each cycle so the services no longer wait on each other, or move what they share into a third service'}}function je(e=g()??process.cwd(),t=x(e)){let s=t.flatMap(n=>{let r=n.config?.port;return r===void 0?[]:typeof r=="number"&&Number.isInteger(r)&&r>=1&&r<=65535?[]:[`${oe(e,n)} port ${JSON.stringify(r)}: not an integer from 1 to 65535`]});return s.length===0?{name:"Service ports",didPass:!0,message:"Every declared port is valid"}:{name:"Service ports",didPass:!1,message:`${C(s.length,"invalid port")}:
18
+ ${s.join(`
19
+ `)}`,fix:'Set "port" to the port the service listens on, an integer from 1 to 65535'}}function Ie(e=g()??process.cwd(),t=!1,s=x(e)){let n=[],r=[];for(let i of s){let a=i.config?.schemaVersion;if(a===he)continue;let c=oe(e,i);a===void 0?n.push(`${c} schemaVersion: missing`):r.push(`${c} schemaVersion ${JSON.stringify(a)}: this flisk supports ${he}`)}if(n.length===0&&r.length===0)return{name:"schemaVersion",didPass:!0,message:"Every service.json has a supported schemaVersion"};let o=[...n.length>0?["Run `flisk config migrate` to add the missing schemaVersion"]:[],...r.length>0?["A version this flisk does not support cannot be migrated: upgrade flisk"]:[]];return{name:"schemaVersion",didPass:!1,isWarning:!t,message:`${C(n.length+r.length,"service.json file")} without a supported schemaVersion:
20
+ ${[...n,...r].join(`
21
+ `)}`,fix:o.join(". ")}}function Uo(e,t){let s=Ie(e,!1,t);s.didPass||(console.warn(h.yellow(`\u26A0 ${s.message}`)),s.fix&&console.warn(h.gray(` ${s.fix}`)))}function Go(e,t={},s=process.exit){let n=t.resources??x(e),r=[Q(e,n),_e(e,n),Ae(e,n),je(e,n)].filter(i=>!i.didPass);if(r.length===0)return;let o=r.map(i=>`${i.message}${i.fix?`
22
+ Fix: ${i.fix}`:""}`).join(`
23
+ `);t.onInvalid?.(o);for(let i of r)console.error(h.red(`\u2717 ${i.message}`)),i.fix&&console.error(h.gray(` Fix: ${i.fix}`));s(1)}import{readFileSync as Hn}from"node:fs";import{join as Ln}from"node:path";function as(e){let t=e.trim().match(/(\d+)\.(\d+)(?:\.(\d+))?/);return t?[Number(t[1]),Number(t[2]),Number(t[3]??0)]:null}function Bn(e){try{return JSON.parse(Hn(Ln(e,".tdk",M),"utf-8"))?.minTdkVersion}catch{return}}function cs(e,t){let s=Bn(e);if(s===void 0)return{status:"none"};let n=typeof s=="string"?as(s):null;if(!n||!/^\d+\.\d+\.\d+$/.test(String(s).trim()))return{status:"malformed",message:`.tdk/project.json minTdkVersion ${JSON.stringify(s)} is not a version like "1.3.80"`,fix:'Set minTdkVersion to a MAJOR.MINOR.PATCH string, for example "1.3.80".'};let r=as(t),o=r!==null&&(()=>{for(let[a,c]of n.entries()){let l=r[a]??0;if(l!==c)return l>c}return!0})(),i=n.join(".");return o?{status:"ok",required:i}:{status:"too-old",required:i,message:`flisk ${t} is older than the ${i} this project requires (minTdkVersion)`,fix:"Run: flisk upgrade"}}var R=1e4,E={dockerMissing:"See https://docs.docker.com/get-docker/",dockerDaemonDown:"Start Docker Desktop, OrbStack, or Colima, then retry: flisk doctor",tiltMissing:"curl -fsSL https://raw.githubusercontent.com/tilt-dev/tilt/master/scripts/install.sh | bash",bunMissing:"curl -fsSL https://bun.sh/install | bash",port80:"Stop the process bound to port 80, or stop local nginx/caddy. Then: flisk doctor",port5432:"Stop local Postgres or change the host port. Then: flisk doctor",notProject:"flisk project --yes"},ds="WSL2 detected. Use Docker Desktop WSL integration. Guide: docs/wsl2.md",us="Native Windows landscape boot is unsupported. Use WSL2 Ubuntu with Docker Desktop integration. Guide: docs/wsl2.md",Fe=[0,25,0],I=[1,2,0];function ie(e,t){let s=We(e);return s?Ue(s,t):!1}function Gn(e,t,s=process.platform==="linux"&&!!process.env.WSL_DISTRO_NAME){if(!s)return{name:"WSL project location",didPass:!0,isSkipped:!0,message:"Not running in WSL2 - skipped project filesystem check"};let n=e.replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase();if(n!=="/mnt/c"&&!n.startsWith("/mnt/c/"))return{name:"WSL project location",didPass:!0,message:`${ds} Project is on the WSL filesystem.`};let r=`${ds} Project is under /mnt/c (${e}); hot reload may be broken. Move it into the WSL filesystem, such as ~/projects.`;return{name:"WSL project location",didPass:!t,isWarning:!t,message:r,fix:"Move the repository under your WSL home directory (for example, ~/projects) and retry flisk doctor."}}function Kn(e){let t=e.replace(/^\[(.*)\]$/,"$1");return t==="0.0.0.0"||/^[0:]*:0\.0\.0\.0$/.test(t)?!0:t.includes(":")&&/^[0:]+$/.test(t)}function Jn(e=process.env,t=!1){let s=(e.TDK_BIND_ADDRESS??"").trim();return Kn(s)?{name:"Dev Port Bind Address",didPass:!t,isWarning:!t,message:`TDK_BIND_ADDRESS is ${s}: Traefik and Postgres are reachable from other machines on the network.`,fix:"Unset TDK_BIND_ADDRESS to keep dev ports on 127.0.0.1. Keep it only when you test from another device on purpose."}:{name:"Dev Port Bind Address",didPass:!0,message:s?`Dev ports bind to ${s}`:"Dev ports bind to 127.0.0.1 (this machine only)"}}function ms(e){let t=e.filter(n=>!n.didPass&&!n.isSkipped&&!n.isWarning),s=e.filter(n=>n.didPass||n.isSkipped||n.isWarning);return t.sort((n,r)=>{let o=i=>i.name==="Host Ports"&&/\b5432\b/.test(i.message)?0:i.name==="Host Ports"?1:i.name==="Ingress Ports"?2:3;return o(n)-o(r)}),[...t,...s]}function qn(e,t){return t?e?"Doctor passed. Next: flisk up":"Doctor passed. Next: flisk project example":"Doctor failed. Fix the items above, then run: flisk doctor"}var Ve={checkDockerOperatingSystem:"Docker OS",checkDockerCompose:"Docker Compose",checkDockerVersions:"Docker Versions",checkDockerNetworkCapacity:"Docker Network Pool",checkContainerResourceHealth:"Container Resource Health",checkCrashLoopingContainers:"Crash-looping containers",checkTiltResourceHealth:"Tilt Resources",checkServiceHealth:"Service Health",checkServiceSmoke:"Service Smoke",checkAdvertisedEndpoints:"Advertised Endpoints"},ps=new Set(["Docker OS","Docker Compose","Docker Versions","Docker Network Pool","Container Resource Health","Crash-looping containers","Tilt Resources","Service Health","Service Smoke","Advertised Endpoints",...Object.keys(Ve)]);function zn(e){return!!(e.requiresContainerRuntime||e.checkName&&ps.has(e.checkName)||e.name&&ps.has(e.name))}function N(e,t){let s=()=>t();return s.requiresContainerRuntime=!0,s.checkName=e,s}async function Xn(e,t={}){let s=[],n=!!t.containerRuntimeFailed;for(let r of e){if(n&&zn(r)){let i=r.checkName??(r.name&&Ve[r.name]?Ve[r.name]:r.name&&r.name!=="check"&&r.name!=="fn"?r.name:"Container check");s.push({name:i,didPass:!0,isSkipped:!0,message:`Docker not running - skipped ${i} check`});continue}let o=await r();if(s.push(o),o.name===v&&!o.didPass&&(n=!0),!t.all&&!o.didPass&&!o.isSkipped&&!o.isWarning)break}return s}function Yn(e){let t=0,s=0,n=0,r=0;for(let o of e)o.isSkipped?n++:o.isWarning?r++:o.didPass?t++:s++;return r>0?`${t} passed, ${r} warned, ${s} failed, ${n} skipped`:`${t} passed, ${s} failed, ${n} skipped`}function Ke(e){return ht(e)}function Qn(e,t,s,n,r){return async(o=O)=>{try{return await o(t,R),{name:e,didPass:!0,message:s}}catch(i){return Ke(i)?{name:e,didPass:!1,message:`${e} did not respond within ${R/1e3}s`,fix:r}:{name:e,didPass:!1,message:n,fix:r}}}}async function Me(e){try{return await O(e,R),!0}catch{return!1}}async function Zn(){let e=H();return e.isColima?e.running&&!e.problem?{name:"Colima",didPass:!0,message:`Colima VM is running${e.arch?` (${e.arch})`:""}`}:{name:"Colima",didPass:!1,message:e.problem??"The Colima VM is not running",fix:e.fix}:{name:"Colima",didPass:!0,message:"Docker does not run on Colima"}}async function Je(){if(process.platform==="win32")try{return await O("docker ps",R),{name:v,didPass:!0,message:"Docker Desktop Linux container engine is running"}}catch{return{name:v,didPass:!1,message:"Docker is not running",fix:E.dockerDaemonDown}}let e=!!$("docker");try{return await O("docker ps",R),{name:v,didPass:!0,message:"Docker daemon is running"}}catch(s){if(Ke(s))return{name:v,didPass:!1,message:"Docker daemon is not responding",fix:E.dockerDaemonDown}}let t=Ut(await Me("pgrep -f com.docker.backend"));return t||(await Me("colima status")?{name:v,didPass:!0,message:"Colima (Docker runtime) is running"}:$("colima")?{name:v,didPass:!1,message:"Colima is installed but not running",fix:E.dockerDaemonDown}:await Me("podman ps")?{name:v,didPass:!0,message:"Podman is running"}:e?{name:v,didPass:!1,message:"Docker daemon is not running",fix:E.dockerDaemonDown}:{name:v,didPass:!1,message:"Docker is not running",fix:E.dockerMissing})}var G=Qn("Docker Compose","docker compose version","Docker Compose plugin available","Docker Compose plugin not found","Install Docker Compose: https://docs.docker.com/compose/install/");G.requiresContainerRuntime=!0;G.checkName="Docker Compose";var er=[25,0,0],tr=[2,20,2];function We(e){let t=e.trim().match(/(\d+)\.(\d+)(?:\.(\d+))?/);return t?[Number(t[1]),Number(t[2]),Number(t[3]??0)]:null}function Ue(e,t){for(let[s,n]of t.entries()){let r=e[s]??0;if(r!==n)return r>n}return!0}async function K(e=O){let t=async a=>String(await e(a,R)).trim(),s,n;try{[s,n]=await Promise.all([t("docker version --format '{{.Server.Version}}'"),t("docker compose version --short")])}catch{return{name:"Docker Versions",didPass:!0,isSkipped:!0,message:"Could not read Docker Engine/Compose versions - skipped version check"}}let r=We(s),o=We(n);if(!r||!o)return{name:"Docker Versions",didPass:!0,isSkipped:!0,message:`Unrecognized Docker version output (engine "${s}", compose "${n}") - skipped version check`};let i=[];return Ue(r,er)||i.push(`Docker Engine ${s} (need 25.0+)`),Ue(o,tr)||i.push(`Docker Compose ${n} (need 2.20.2+)`),i.length===0?{name:"Docker Versions",didPass:!0,message:`Docker Engine ${s} and Compose ${n} support generated healthchecks`}:{name:"Docker Versions",didPass:!1,message:`Docker is too old for generated healthchecks (they use start_interval):
24
+ ${i.join(`
25
+ `)}`,fix:"Update Docker Desktop, or on Linux update docker-ce and the docker-compose-plugin package"}}K.requiresContainerRuntime=!0;K.checkName="Docker Versions";async function qe(e=O){let t;try{t=String(await e("tilt version",R)).trim()}catch{return{name:"Tilt CLI",didPass:!1,message:"Tilt CLI not found",fix:E.tiltMissing}}return ie(t,Fe)?{name:"Tilt CLI",didPass:!0,message:`Tilt ${t} is available`}:{name:"Tilt CLI",didPass:!1,message:`Tilt ${t||"version unknown"} is below the required v${Fe.join(".")} floor`,fix:`Install Tilt v${Fe.join(".")} or newer: https://docs.tilt.dev/install.html`}}async function ze(e=O){let t;try{t=String(await e("docker info --format '{{.OSType}}'",R)).trim().toLowerCase()}catch{return{name:"Docker OS",didPass:!0,isSkipped:!0,message:"Docker OS unavailable - daemon failure reported separately"}}return t!=="linux"?{name:"Docker OS",didPass:!1,message:`Docker is using the ${t||"unknown"} engine; Flisk requires Linux containers`,fix:"Switch Docker Desktop to Linux containers, enable WSL2 integration, then retry flisk doctor."}:{name:"Docker OS",didPass:!0,message:"Docker is using Linux containers"}}ze.requiresContainerRuntime=!0;ze.checkName="Docker OS";async function sr(e=O){let t=g();if(!t)return{name:"Bun",didPass:!0,isSkipped:!0,message:"Not in a project - skipping Bun check"};if(!te(x(t)))return{name:"Bun",didPass:!0,isSkipped:!0,message:"No generated JS services - skipping Bun check"};try{let s=String(await e("bun --version",R)).trim();return ie(s,I)?{name:"Bun",didPass:!0,message:`Bun ${s} is available`}:{name:"Bun",didPass:!1,message:`Bun ${s||"version unknown"} is below the required ${I.join(".")} floor`,fix:`Install Bun ${I.join(".")} or newer: https://bun.sh/install`}}catch{return{name:"Bun",didPass:!1,message:"Bun is not available",fix:E.bunMissing}}}function nr(){let e=g()??process.cwd(),t=tt(e);if(t.missing.length>0)return{name:"Environment Variables",didPass:!1,message:`Missing required env variables: ${t.missing.join(", ")}`,fix:D(P(e,".env"))?`Edit .env and set these values:
26
+ ${t.missing.map(n=>`${n}=<value>`).join(`
27
+ `)}`:"No .env file yet. Run `flisk project` to create one with working defaults."};if(t.invalid.length>0)return{name:"Environment Variables",didPass:!1,message:`Invalid env variables: ${t.invalid.join(", ")}`,fix:"Edit .env and provide values for empty variables"};let s=t.warnings.filter(n=>!n.startsWith(".env file not found"));return{name:"Environment Variables",didPass:!0,message:s.length>0?`All required environment variables are set (warning: ${s.join("; ")})`:"All required environment variables are set"}}function rr(){let e=g()??process.cwd(),t=P(e,".tdk",".tdk-out"),s=ue.filter(n=>!D(P(t,n)));return s.length===0?{name:"Master Configs",didPass:!0,message:`${ue.join(", ")} found`}:{name:"Master Configs",didPass:!1,message:`Master configs missing: ${s.join(", ")}`,fix:"Run: flisk project"}}function or(e=Ye()){let t=g();if(!t)return{name:"Flisk version",didPass:!0,isSkipped:!0,message:"Not in a project - skipping Flisk version check"};let s=cs(t,e);return s.status==="none"?{name:"Flisk version",didPass:!0,isSkipped:!0,message:`flisk ${e} (no minTdkVersion in .tdk/project.json)`}:s.status==="malformed"||s.status==="too-old"?{name:"Flisk version",didPass:!1,message:s.message,fix:s.fix}:{name:"Flisk version",didPass:!0,message:`flisk ${e} meets minTdkVersion ${s.required}`}}function ir(){let e=g()??process.cwd(),t=ve(e),s=x(e).filter(r=>!se(e,r.path,t));if(s.length===0)return{name:"Resource Discovery",didPass:!0,message:`All resources are covered by discovery.paths ${JSON.stringify(t)}`};let n=s.map(r=>Le(Be(e,r.path))).join(", ");return{name:"Resource Discovery",didPass:!1,message:`${C(s.length,"resource")} outside discovery.paths ${JSON.stringify(t)}: ${n}. \`flisk up\` will not start them`,fix:"Move each under services/<stack>/<name>, or add a matching pattern to discovery.paths in .tdk/project.json and run: flisk config regenerate"}}var ar=["install-deps.sh","bun-hoisted-symlink-fix.sh","prisma-bun-client-link-fix.sh","prisma-normalize-client.sh","infisical-entrypoint.sh"],cr=/shared-platform-engineering\/docker-templates\/([\w.-]+)/g;function lr(e){let t=new Set;for(let s of x(e)){let n=P(s.path,F);if(D(n)){for(let r of Wn(n))if(!(!r.startsWith("Dockerfile")||r.endsWith(".dockerignore")))for(let o of L(P(n,r),"utf-8").matchAll(cr))t.add(o[1])}}return[...t]}function dr(){let e=g()??process.cwd(),t=[];D(P(e,W))||t.push(`${W} (workspace root manifest)`);let s=P(e,"shared-platform-engineering","docker-templates"),n=[];try{n=lr(e)}catch{}for(let r of new Set([...ar,...n]))D(P(s,r))||t.push(`shared-platform-engineering/docker-templates/${r}`);return t.length===0?{name:"Generated Runtime Assets",didPass:!0,message:"Generated Docker runtime assets are present"}:{name:"Generated Runtime Assets",didPass:!1,message:`Generated Dockerfiles reference missing project runtime assets:
28
+ ${t.join(`
29
+ `)}`,fix:"Run `flisk project --yes` (or `flisk config regenerate`) with an updated Flisk. `flisk up` also refreshes these assets before starting Tilt."}}function ur(){let e=g()??process.cwd(),t=x(e),s=[];for(let n of t){let r=P(n.path,W);if(!D(r))continue;let o=n.config?.appType??"backend",i=pe[o]??pe.backend,a;try{a=JSON.parse(L(r,"utf-8")).scripts??{}}catch{s.push(`${n.name} (package.json is invalid JSON)`);continue}let c=i.filter(l=>!a[l]);c.length>0&&s.push(`${n.name}: missing "${c.join('", "')}"`)}return s.length===0?{name:"Startup Scripts",didPass:!0,message:"All services have required package.json scripts"}:{name:"Startup Scripts",didPass:!1,message:`Services missing required package.json scripts:
30
+ ${s.join(`
31
+ `)}`,fix:`Add the missing scripts to each service's package.json, e.g.:
32
+ "dev": "bun run src/index.ts",
33
+ "build": "tsc",
34
+ "start": "bun run dist/index.js"`}}function hs(e){if(e.startsWith("@"))return[e.split("/").slice(0,2).join("/")];let t=e.split("/")[0]??e;return[`@types/${t}`,t]}function gs(e,t,s=0){let n=e[t];if(typeof n!="string"||s>3)return!1;if(/(^|[\s;&|(])tsc(\s|$)/.test(n))return!0;for(let r of n.matchAll(/\b(?:bun|npm|pnpm|yarn)\s+run\s+([\w:.-]+)/g))if(gs(e,r[1],s+1))return!0;return!1}function fs(e){let t=hs(e);return e.includes("/")||e.startsWith("@")?t[t.length-1]:t[0]}var pr={"@types/bun":"^1.4.2","@types/node":"^20.0.0"};function fr(e,t){return(t.includes("bun")||e.has("@types/bun"))&&!e.has("@types/node")}function mr(){let e=g()??process.cwd(),t=x(e),s=[],n=new Set;for(let o of t){let i=P(o.path,W),a=P(o.path,F,"tsconfig.docker.autogenerated.json");if(!D(i)||!D(a))continue;let f=Ge(a)?.compilerOptions?.types;if(!Array.isArray(f))continue;let m=Ge(i),u=m?.scripts??{};if(!gs(u,"build"))continue;let S=new Set([...Object.keys(m?.devDependencies??{}),...Object.keys(m?.dependencies??{})]),k=f.filter(y=>typeof y=="string").filter(y=>!hs(y).some(p=>S.has(p)));for(let y of k)n.add(fs(y));if(k.length>0){let y=k.map(p=>`"${p}" (needs ${fs(p)})`).join(", ");s.push(`${o.name}: "types" lists ${y}`)}fr(S,f)&&(n.add("@types/node"),s.push(`${o.name}: uses @types/bun, which references node types internally, but @types/node is not a direct dependency`))}if(s.length===0)return{name:"TypeScript Type Dependencies",didPass:!0,message:`Every service's Docker tsconfig "types" entry has its @types package installed`};let r=[...n].map(o=>{let i=pr[o];return i?`"${o}": "${i}"`:`${o} (bun add -d ${o})`});return{name:"TypeScript Type Dependencies",didPass:!1,message:`\`bun run build\` will fail with TS2688 (Cannot find type definition file) because a @types package it needs is not a direct dependency:
35
+ ${s.join(`
36
+ `)}`,fix:`Add to each service's package.json devDependencies: ${r.join(", ")}`}}function Ge(e){try{return JSON.parse(L(e,"utf-8"))}catch{return null}}function hr(e){let s=Ge(e)?.compilerOptions;return s?.allowSyntheticDefaultImports===!0||s?.esModuleInterop===!0}function gr(){let e=g()??process.cwd(),t=x(e).filter(n=>n.config?.appType==="frontend");if(t.length===0)return{name:"Frontend Docker Preflight",didPass:!0,isSkipped:!0,message:"No frontend services to check"};let s=[];for(let n of t){D(P(n.path,"public"))||s.push(`${n.name}: no public/ folder, but the Docker build copies it. Create it: mkdir -p ${Le(Be(e,P(n.path,"public")))} && touch ${Le(Be(e,P(n.path,"public",".gitkeep")))}`);let r=P(n.path,F,"Dockerfile.app.autogenerated"),o=P(n.path,F,"tsconfig.docker.autogenerated.json");if(D(r)){let i=L(r,"utf-8"),a=/\bEXPOSE\s+80\b/.test(i),c=n.config?.stack,l=c?P(e,"services",c,F,"docker-compose.app.autogenerated.yml"):"";if(a&&l&&D(l)){let f=L(l,"utf-8"),m=n.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),u=new RegExp(`traefik\\.http\\.services\\.${m}\\.loadbalancer\\.server\\.port=(\\d+)`),k=f.match(u)?.[1];k&&k!=="80"&&s.push(`${n.name}: nginx runtime exposes 80, but generated Traefik routes to ${k}`)}}if(D(o)&&!hr(o)){let i=P(n.path,"src","main.tsx");if(D(i)){let a=L(i,"utf-8"),c=[/import\s+\w+\s+from\s+["']react["']/,/import\s+\w+\s+from\s+["']react-dom\/client["']/].filter(l=>l.test(a)).map(l=>l.source.includes("react-dom")?"react-dom/client":"react");c.length>0&&s.push(`${n.name}: Docker tsconfig does not allow synthetic default imports, but src/main.tsx default-imports ${c.join(" and ")}`)}}}return s.length===0?{name:"Frontend Docker Preflight",didPass:!0,message:`${C(t.length,"frontend")} ${t.length===1?"has":"have"} compatible Docker build/routing metadata`}:{name:"Frontend Docker Preflight",didPass:!1,message:`Frontend Docker metadata has issues that will make \`flisk up\` fail or route 404:
37
+ ${s.join(`
38
+ `)}`,fix:'Regenerate with a current Flisk (`flisk config regenerate`) and ensure frontend nginx runtimes route to port 80. For React entrypoints, prefer named imports: `import { StrictMode } from "react"` and `import { createRoot } from "react-dom/client"`.'}}var kr=90,Sr=80;function yr(e){return e.split(`
39
+ `).map(t=>t.trim()).filter(Boolean).map(t=>{let[s,n,r]=t.split(",");return{name:s??"unknown",memPct:Number.parseFloat((n??"").replace(/%/g,"")),cpuPct:Number.parseFloat((r??"").replace(/%/g,""))}}).filter(t=>Number.isFinite(t.memPct)&&Number.isFinite(t.cpuPct))}var xr=Object.assign(function(){let t;try{t=Vn($("docker")??"docker",["stats","--no-stream","--format","{{.Name}},{{.MemPerc}},{{.CPUPerc}}"],{stdio:"pipe",encoding:"utf-8",timeout:R,windowsHide:process.platform==="win32"})}catch(o){return{name:"Container Resource Health",didPass:!0,isSkipped:!0,message:Ke(o)?"Docker not responding - skipped container resource check":"Docker not running - skipped container resource check"}}let s=yr(t);if(s.length===0)return{name:"Container Resource Health",didPass:!0,isSkipped:!0,message:"No running containers to check"};let n=s.filter(o=>o.memPct>=kr&&o.cpuPct>=Sr);if(n.length===0)return{name:"Container Resource Health",didPass:!0,message:`${C(s.length,"container")} within normal resource usage`};let r=n.map(o=>`${o.name} (mem ${o.memPct.toFixed(0)}%, cpu ${o.cpuPct.toFixed(0)}%)`).join(`
40
+ `);return{name:"Container Resource Health",didPass:!1,message:`${C(n.length,"container")} pinned near its memory limit while burning CPU -- likely stuck in a boot-time retry/fetch loop, not a normal crash:
41
+ ${r}`,fix:"Check the container's boot logs for a network fetch loop (e.g. `bunx <pkg>` re-downloading a CLI on every start instead of using one already installed): docker logs <container>. If a Prisma auto-migration is the cause, set AUTO_MIGRATE=false in the project's .env as a temporary unblock."}},{requiresContainerRuntime:!0,checkName:"Container Resource Health"}),Pr=5e3;async function wr(e,t){let s=g()??process.cwd(),n=me(x(s),t);return n.length===0?{name:"Service Health",didPass:!0,isSkipped:!0,message:"No routable services to ping"}:ye(await X(n,e))}async function vr(e,t){let s=g()??process.cwd(),n=x(s),r=at(it(n,t),{timeoutSeconds:Math.ceil(e/1e3)});return r.length===0?xe([]):(await X(me(n,t),e)).some(i=>i.status!==void 0)?xe(await lt(r,ct(s))):{name:"Service Smoke",didPass:!0,isSkipped:!0,message:"No services responded - skipped smoke checks"}}async function br(e,t){let s=g()??process.cwd(),n=x(s),r=ot(n,t);return r.length===0?{name:"Advertised Endpoints",didPass:!0,isSkipped:!0,message:"No routable services to check"}:Rt(await X(r,e))}function Dr(e,t){if(e.length===0){console.log(`${h.green("\u2713")} Nothing to repair
42
+ `);return}for(let s of e){let n=s.status==="planned"?`${h.cyan("would run")}`:s.status==="applied"?h.green("ran"):s.status==="failed"?h.red("failed"):h.gray("skipped"),r=s.status==="planned"?"":` (${s.reason})`;console.log(`${n}: ${s.command}${r}`)}t&&console.log(h.gray(`
43
+ Dry run: nothing was changed.`)),console.log("")}function He(e){for(let t of ms(e))!t.didPass&&!t.isSkipped&&!t.isWarning?(console.log(`${h.red("\u2717")} ${t.message}`),t.fix&&console.log(`${h.blue("\u2139")} Fix: ${t.fix}`)):t.isWarning?(console.log(`${h.yellow("\u26A0")} ${h.yellow(t.message)}`),t.fix&&console.log(`${h.blue("\u2139")} Fix: ${t.fix}`)):t.isSkipped?(console.log(`${h.gray("\u25CB")} ${h.gray(t.message)}`),t.fix&&console.log(`${h.blue("\u2139")} ${t.fix}`)):console.log(`${h.green("\u2713")} ${t.message}`)}function Tr(e,t,s,n={},r){let o=r??[...e,...t];n.all?(console.log(h.bold("Machine")),He(e),console.log(`
44
+ ${h.bold("Project")}`),s?t.length>0&&He(t):console.log(`${h.gray("\u25CB")} ${h.gray("Not in a Flisk project, so project checks were skipped")}`),console.log(""),console.log(Yn(o))):(He(o),console.log(""),o.every(a=>a.didPass||a.isSkipped||a.isWarning)&&!s&&(console.log(`${h.gray("\u25CB")} ${h.gray("Not in a Flisk project, so project checks were skipped")}`),console.log("")))}var Cr=new Un("doctor").description("Check environment readiness for Flisk").option("--all","Run every check and show Machine and Project sections with a summary",!1).option("--json","Output a versioned JSON readiness report",!1).exitOverride(e=>{e.exitCode===0&&process.exit(0),Cr.opts().json&&console.log(JSON.stringify(j([],!1,[{code:"USAGE",message:e.message}]))),process.exit(2)}).option("--no-ping","Skip pinging running services' /health endpoints").option("--strict","Fail warnings such as a WSL project under /mnt/c").option("--fix","Repair this project's unused Docker networks and leftover doctor probes",!1).option("--dry-run","With --fix: list the repairs without changing anything",!1).option("--scope <scope>","With --fix: project (default) or machine, which also removes unused networks of other Flisk projects","project").option("-y, --yes","With --fix: apply every repair without asking",!1).option("--ping-timeout <ms>","Per-service ping timeout in milliseconds",String(Pr)).action(async e=>{let t=Number(e.pingTimeout);if(!/^\d+$/.test(e.pingTimeout)||!Number.isSafeInteger(t)||t<=0){let d="--ping-timeout must be a positive integer number of milliseconds";e.json&&console.log(JSON.stringify(j([],!1,[{code:"USAGE",message:d}]))),console.error(d),process.exit(2);return}let s=!["project","machine"].includes(e.scope),n=e.scope!=="project"&&!e.fix;if(s||n||(e.dryRun||e.yes)&&!e.fix){let d=s?`--scope must be project or machine, got "${e.scope}"`:n?"--scope only applies with --fix":`${e.dryRun?"--dry-run":"--yes"} only applies with --fix`;e.json&&console.log(JSON.stringify(j([],!1,[{code:"USAGE",message:d}]))),console.error(d),process.exit(2);return}e.json||console.log("Flisk doctor checks your local Docker + Tilt development environment; it does not check cluster deployments.");let r=At();if(process.platform==="win32"){if(e.json){let d=null;try{d=await dt()}catch{}console.log(JSON.stringify(j([{name:"Native Windows support",didPass:!1,message:us,fix:"Use WSL2 Ubuntu with Docker Desktop integration. Guide: docs/wsl2.md"}],!!g(),[],d,{...r,canUp:!1})))}console.error(us),process.exit(1);return}if(r.kind==="webcontainer"){let d=j([{name:"Host",didPass:!1,message:we,fix:`Use a machine with Docker. Guide: ${ee}`}],!!g(),[],void 0,r);e.json&&console.log(JSON.stringify(d)),console.error(we),process.exit(1);return}e.json||(console.log(`
45
+ ${h.bold("\u{1F50D} Flisk Doctor")}
46
+ `),console.log(`Checking environment...
47
+ `));let o=g(),i;if(e.fix){try{let d;if(o)try{d=ft(o).project.name}catch{}let w=o?Zt(o):[],ce=await zt(d,void 0,{tiltPids:w,machine:e.scope==="machine"});i=await Xt(ce,{dryRun:e.dryRun,confirm:e.yes||!e.json&&process.stdin.isTTY?async T=>e.yes||await mt({message:`Run \`${T.command}\` (${T.check}, ${T.reason})?`}):void 0})}catch(d){i=[{id:"plan-fixes",check:"Docker networks",scope:"project",command:"docker network ls",status:"failed",reason:`could not list Docker networks: ${(d instanceof Error?d.message:String(d)).split(/\r?\n/)[0]}`}]}e.json||Dr(i,e.dryRun)}let a,c;try{a=await Y(o??process.cwd())}catch(d){a=null,c=d instanceof Error?d.message:String(d)}let l=[()=>a?{name:"Host Ports",didPass:!0,message:`HTTP ${a.ingressHttp}, HTTPS ${a.ingressHttps}, Postgres ${a.postgres}`}:{name:"Host Ports",didPass:!1,message:c??"Could not select host ports",fix:"Set TDK_HTTP_PORT, TDK_HTTPS_PORT, or TDK_POSTGRES_PORT to available host ports."},()=>a?Se(ls,void 0,[a.ingressHttp,a.ingressHttps]):{name:"Ingress Ports",didPass:!1,message:"Ingress port plan is unavailable"},Zn,Je,()=>Wt(),N("Docker OS",ze),qe,N("Docker Compose",G),N("Docker Versions",K),sr,()=>Gn(g()??process.cwd(),e.strict),()=>Jn(process.env,e.strict),N("Docker Network Pool",()=>Dt()),()=>Qt()],f=[()=>or(),rr,dr,os,ur,()=>Ot(),mr,gr,ir,()=>kt(),()=>Q(),()=>_e(),()=>Ae(),()=>je(),()=>Ie(void 0,e.strict),()=>St(),()=>yt(),()=>Pt(),()=>xt(),()=>Z(),()=>gt(),()=>vt(),()=>wt(),()=>bt(),nr,async()=>{let d=g()??process.cwd(),w=Et(d)?await pt(d):!0;return ke(ls,d,void 0,w)},N("Container Resource Health",xr),N("Crash-looping containers",()=>{let d=g()??process.cwd(),w=[];try{w=fe(d)}catch{return{name:"Crash-looping containers",didPass:!0,isSkipped:!0,message:"Could not read .env - skipped crash-loop check"}}return Bt(rt(),w)}),N("Tilt Resources",Pe)];if(e.ping){let d=o?ut(o,a?.ingressHttp):a?.ingressHttp;f.push(N("Service Health",()=>wr(t,d))),f.push(N("Service Smoke",()=>vr(t,d))),f.push(N("Advertised Endpoints",()=>br(t,d)))}let m=!!o,u=[],S=[],k,y=[];if(e.json||!e.all){let d=await ts(l,m?f:[]);k=d.checks,y=d.errors}else{let d=async(T,Ns=!1)=>{let Es=T.map(q=>{let le=async()=>{try{return await q()}catch(de){return y.push({code:"INTERNAL",message:de instanceof Error?de.message:String(de)}),{name:q.checkName??"Doctor check",didPass:!1,isSkipped:!1,message:"Check failed with an internal error"}}};return le.requiresContainerRuntime=q.requiresContainerRuntime,le.checkName=q.checkName,le});return Xn(Es,{all:!!e.all,containerRuntimeFailed:Ns})};u=await d(l);let w=u.some(T=>!T.didPass&&!T.isSkipped&&!T.isWarning),ce=u.some(T=>T.name===v&&!T.didPass);m&&(e.all||!w)&&(S=await d(f,ce)),k=[...u,...S]}if(jt(r.kind))for(let d of k)d.name===v&&!d.didPass&&(d.fix=_t);let p=j(ms(k),m,y,a,r);i&&(p.data.actions=i),i&&Yt(i)&&(p.data.ready=!1);let A=ss(p),V=p.data.ready;if(e.json){let d;try{d=fe(g()??process.cwd())}catch(w){if(!(w instanceof st))throw w;console.log(JSON.stringify(j([],m,[...y,{code:"ENV_UNREADABLE",message:w.message}]))),console.error(w.message),process.exit(1)}console.log(JSON.stringify(nt(p,d)));for(let w of y)console.error(z(w.message,d));A!==0&&process.exit(A);return}for(let d of y)console.error(`${h.red("\u2717")} Doctor check failed: ${d.message}`);Tr(u,S,m,e,k);let Xe=qn(m,V);console.log(`${V?h.green(h.bold("\u2713")):h.red(h.bold("\u2717"))} ${Xe}`),A!==0&&process.exit(A)});function ks(e){return ie(e,I)}var J=`${I[0]}.${I[1]}+`;import{execFileSync as Ss}from"node:child_process";import{accessSync as ys,constants as xs,readdirSync as $r}from"node:fs";import{delimiter as Nr,join as B}from"node:path";var _="flisk",Ps="@flisk-sh/flisk",Er="https://github.com/flisk-sh/flisk",ws="@tdk-landscape/tdk-cli-core";function vs(e=_,t=process.env){let s=t.PATH??t.Path??"";for(let n of s.split(Nr)){if(!n)continue;let r=[B(n,e),B(n,`${e}.cmd`),B(n,`${e}.exe`)];for(let o of r)try{return ys(o,xs.X_OK),!0}catch{}}return!1}function Rr(e=process.env){let t=e.HOME??e.USERPROFILE??"";if(!t)return"flisk-workspace";let s=B(t,"Documents");try{return ys(s,xs.F_OK),B(s,"flisk")}catch{return B(t,"flisk")}}function Or(e){try{return $r(e).every(t=>t.startsWith("."))}catch{return!0}}function bs(e=process.env,t=process.cwd()){if(!vs(_,e))return`The \`${_}\` command is not on PATH (this run is not a global install). Install it with \`npm install -g ${Ps}\`, then run \`${_} project --yes\`. If npm reports EEXIST for \`flisk\`, the old package still owns that command: run \`npm uninstall -g ${ws}\` first. The current release is published from ${Er}.`;if(Or(t))return`Next: ${_} project --yes`;let s=Rr(e);return`Next: mkdir -p ${s} && cd ${s} && ${_} project --yes
48
+ (${_} project writes .tdk/ and the master configs into the current folder, so it starts clean in a folder of its own. Or clone a starter: ${_} project example)`}function Mi(e=process.env){if(vs(_,e))return"present";let t=e.npm_execpath?.includes("bun")?"bun":"npm",s=t==="bun"?"bun remove -g":"npm uninstall -g";try{Ss(s,[ws],{stdio:"ignore",timeout:12e4})}catch{}try{return Ss(t,["install","-g",Ps],{stdio:"inherit",timeout:3e5}),"installed"}catch{return"failed"}}var jr=["docker","compose","tilt"],Cs=["node","bun","ports"],$s=["node",...jr,"bun","ports"];function Ir(e,t){return{id:e,ok:t.didPass||!!t.isSkipped,message:t.message,fix:t.fix}}function Ts(e){let[t=0,s=0]=String(e).split(".").map(n=>Number.parseInt(n,10));return!Number.isFinite(t)||!Number.isFinite(s)||t<22||t===22&&s<12}async function ae(e,t,s){try{return Ir(e,await t())}catch{return{id:e,ok:!1,message:s}}}function Fr(e){return e.isSkipped?{...e,didPass:!1,isSkipped:!1,message:`Could not verify Docker Engine/Compose minimum versions: ${e.message}`,fix:e.fix??"Start Docker and ensure Docker Engine 25+ and Compose 2.20.2+ are installed."}:e}function Mr(e){try{return x(e).some(t=>t.config?.featuresEnabled?.includes("prisma")??!1)}catch{return!1}}async function Hr(e={}){let t=e.cwd??process.cwd(),s=e.scope??"runtime",n=g(t),r=!!n,o=[],i=process.versions.node;if(o.push({id:"node",ok:!Ts(i),message:i,fix:Ts(i)?`Install Node.js 22.12+ (current: ${i}). https://nodejs.org`:void 0}),s==="runtime"){let p=H();p.isColima&&o.push({id:"colima",ok:p.running,message:p.running?`Colima VM is running${p.arch?` (${p.arch})`:""}`:p.problem??"The Colima VM is not running",fix:p.running?void 0:p.fix}),o.push(await ae("docker",Je,"Docker daemon is not running")),o.push(await ae("compose",async()=>{let[b,A]=await Promise.all([G(),K()]);return b.didPass?Fr(A):b},"Docker Engine or Compose version check failed")),o.push(await ae("tilt",qe,"Tilt CLI not found"))}let a=n?te(x(n)):!0,c=!1,l=a?$("bun"):void 0;if(l)try{let p=Ds(l,["--version"],{encoding:"utf-8",timeout:3e3}).trim();c=ks(p)}catch{}o.push(a?{id:"bun",ok:c,message:c?`Bun ${J} is available on PATH`:`Bun ${J} not found on PATH`,fix:c?void 0:"curl -fsSL https://bun.sh/install | bash"}:{id:"bun",ok:!0,message:"Bun not needed: no generated JS services"});try{let p=await Y(n??t,s==="scaffold"?{inspectDocker:!1}:{});o.push({id:"ports",ok:!0,message:`HTTP ${p.ingressHttp}, HTTPS ${p.ingressHttps}, Postgres ${p.postgres}`})}catch(p){o.push({id:"ports",ok:!1,message:p instanceof Error?p.message:String(p),fix:"Set TDK_HTTP_PORT, TDK_HTTPS_PORT, or TDK_POSTGRES_PORT to available host ports."})}if(n&&s==="runtime"){let p=await ae("nats",()=>Z(n),"NATS broker check failed");if(p.ok||o.push(p),Mr(n)){let b=!1;try{let A=JSON.parse(_r(Ar(n,".tdk",M),"utf-8")),V=String(A?.project?.name??"").replace(/-/g,"_");V&&(b=Ds($("docker")??"docker",["ps","--filter",`label=com.docker.compose.project=${V}`,"--filter","label=com.docker.compose.service=postgres","--filter","health=healthy","--format","{{.Names}}"],{encoding:"utf-8",timeout:3e3}).trim().length>0)}catch{}b||o.push({id:"prisma",ok:!1,message:"A Prisma resource is configured, but the project Postgres service is not healthy",fix:"Run `flisk up` to start the bundled Postgres, then check `flisk doctor`."})}}let f=o.filter(p=>!p.ok).slice(0,8),m=s==="scaffold"?Cs:$s,u=f.some(p=>m.includes(p.id)),S=f.some(p=>p.id==="bun"),k=f.length?u?s==="scaffold"?S?`Project setup blocked. Bun ${J} must be installed on PATH.
49
+ Fix the machine checks below.`:"Project setup blocked. Fix the machine checks below.":S?`Cold start blocked. Bun ${J} must be installed on PATH.
50
+ Prisma/NATS configuration is project-specific and generated after \`flisk project\`. Fix the machine checks below.`:"Cold start blocked. Bun/Prisma/NATS are not the first failure.\nThey are generated after `flisk project`. Fix the machine checks below.":"Machine is ready. Project wiring is not.":"",y=f.length?"":r?"Environment ready for Flisk":`This machine is ready for Flisk.
51
+ ${bs()}`;return{ok:f.length===0,inProject:r,items:f,header:k,footer:y}}function Lr(e,t={}){let s=[e.header];for(let n of e.items)s.push(`FAIL ${n.id.padEnd(7)} ${n.message}`),n.fix&&s.push(` ${n.fix}`);return e.footer&&(t.includeSuccessFooter??!0)&&s.push(e.footer),s.filter(Boolean).join(`
52
+ `)}async function ea(e={}){let t=e.scope??"runtime",s=await Hr({scope:t}),n=t==="scaffold"?Cs:$s;s.items.some(o=>n.includes(o.id))&&(console.error(Lr(s)),process.exit(1))}function ta(e=$){return{hasDockerCli:!!e("docker"),hasTiltCli:!!e("tilt")}}function sa(e){let t=[];return e.hasDockerCli||t.push(`Docker is not installed. ${E.dockerMissing}`),e.hasTiltCli||t.push(`Tilt is not installed. ${E.tiltMissing}`),t.push("Docker and Tilt are only needed to start the stack: start them, then run `flisk doctor` (readiness) and `flisk up`."),t}export{Nn as a,En as b,Co as c,we as d,_t as e,At as f,jt as g,ve as h,se as i,qr as j,oo as k,io as l,ao as m,$e as n,on as o,dn as p,fo as q,Uo as r,Go as s,cs as t,Cr as u,ws as v,Mi as w,jr as x,Cs as y,$s as z,Ts as A,Fr as B,Hr as C,Lr as D,ea as E,ta as F,sa as G};
@@ -0,0 +1,2 @@
1
+ import{createRequire as __tdkRequire}from'node:module';const require=__tdkRequire(import.meta.url);
2
+ import{execFileSync as l,spawnSync as u}from"node:child_process";import{existsSync as r}from"node:fs";import{join as o}from"node:path";var a=()=>({env:process.env,dockerAnswers:()=>{try{return l("docker",["info","--format","{{.ServerVersion}}"],{encoding:"utf-8",timeout:1e4,stdio:["ignore","pipe","ignore"]}),!0}catch{return!1}},run:(t,n)=>{let e=u(t,n,{encoding:"utf-8",timeout:2e4,stdio:["ignore","pipe","pipe"]});return`${e.stdout??""}${e.stderr??""}`},exists:r,home:process.env.HOME??""});function c(t=a()){let n=t.env.DOCKER_HOST??"";if(n.includes(".colima"))return!0;let e=o(t.home,".colima","default","docker.sock");return t.exists(e)&&n.includes("docker.sock")===!1&&n!==""}function h(t=a()){if(!c(t))return{isColima:!1,running:!0};let n="";try{n=t.run("colima",["status"])}catch(e){let i=String(e?.stderr??e);return/rosetta|native arch/i.test(i)?{isColima:!0,running:!1,problem:"Lima is installed as an x86_64 build, so it cannot start the Colima VM on this Mac",fix:"Install a native Lima (brew reinstall lima, or use a native limactl on PATH) and run `colima start`"}:t.dockerAnswers()?{isColima:!0,running:!0,problem:"The Colima VM is running, but the colima CLI on this PATH cannot see it",fix:"Use a native limactl (a Rosetta x86_64 limactl cannot talk to the VM): brew reinstall lima, or put a native limactl first on PATH"}:/not running/i.test(i)?{isColima:!0,running:!1,problem:"The Colima VM is not running",fix:"Run `colima start`"}:{isColima:!0,running:!1,problem:"The state of the Colima VM could not be read",fix:"Run `colima status` to see what it says"}}return/is running/i.test(n)?{isColima:!0,running:!0,arch:/arch:\s*(\S+)/.exec(n)?.[1]}:t.dockerAnswers()?{isColima:!0,running:!0,problem:"The Colima VM is running, but the colima CLI on this PATH cannot see it",fix:"Use a native limactl (a Rosetta x86_64 limactl cannot talk to the VM): brew reinstall lima, or put a native limactl first on PATH"}:{isColima:!0,running:!1,problem:"The Colima VM is not running",fix:"Run `colima start`"}}function p(t,n){if(t.isColima){if(!t.running)return"start";if(t.problem?.includes("cannot see it"))return"native-lima";if(!n)return"restart"}}function g(t=process.env){let n=t.HOME??"",e=[n?`${n}/.local/bin`:"",n?`${n}/bin`:"","/opt/homebrew/bin"].filter(Boolean);for(let i of e){let s=o(i,"limactl");try{if(r(s))return i}catch{}}}export{c as a,h as b,p as c,g as d};
@@ -1,12 +1,12 @@
1
1
  import{createRequire as __tdkRequire}from'node:module';const require=__tdkRequire(import.meta.url);
2
- import{b as N,c as pe,d as H,i as D,j as q,n as J,o as I,q as C}from"./chunk-DS47LHYF.js";import{H as B,J as V,L as A,Na as ne,Ra as ae,Sa as se,Ua as ie,V as F,W as z,Wa as ce,Xa as le,Ya as de,aa as f,ba as v,ca as t,d as P,ja as re,k as U,ka as G,la as W,m as E,s as T}from"./chunk-LMHKXU2Q.js";import{b as p}from"./chunk-CF46CD6R.js";import{execFileSync as ve}from"node:child_process";import{cpSync as ye,existsSync as y,readdirSync as Se,readFileSync as Y,writeFileSync as je}from"node:fs";import{basename as _e,dirname as we,join as _,resolve as M}from"node:path";import{cwd as ue}from"node:process";import{fileURLToPath as xe}from"node:url";import{Command as Pe}from"commander";var he="-y, --yes",ke="Skip prompts and confirmations; use defaults";function fe(e,o=ke){return e.option(he,o,!1)}async function be(e,o=!0){let c=await I({message:e,initial:o});return c||F(),c}function Ne(e,o=1){e.valid||A(e.error??"Validation failed",o)}function De(e,o,c,a){return e.dryRun?(a?a():(console.log(`Dry run - ${o}`),console.log(`Would run: ${c}`)),!0):!1}async function Je(e,o){return await be(e,!0)?!0:(o&&o(),!1)}var L=new Map;function me(e){e!==void 0?L.delete(e):L.clear()}function Ue(e=!1){let o=T(),c=o??"";if(!e){let n=L.get(c);if(n)return n}let{resources:a,problems:l}=o?ae(o):{resources:ie(),problems:[]},d=de(a),r=le(a);se(l);let g=a.filter(n=>!n.stack),m=new Map;for(let n of a)if(n.stack){let w=m.get(n.stack)||[];w.push(n),m.set(n.stack,w)}let k={resources:a,problems:l,stacks:d,stackNames:r,unassignedResources:g,resourcesByStack:m};return L.set(c,k),k}var O={proxy:{name:"proxy",description:"Traefik reverse proxy and API gateway for routing all services",category:"core",phase:"pre_alpha",enabled_by_default:!0,dependsOn:[]},verdaccio:{name:"verdaccio",description:"Verdaccio npm registry for package management and local publishing (Premium - requires TDK_LICENSE_KEY)",category:"premium",phase:"pre_alpha",enabled_by_default:!1,dependsOn:[]},[P]:{name:P,description:"PostgreSQL database for data persistence and SQL operations",category:"core",phase:"pre_alpha",enabled_by_default:!0,dependsOn:[]},monitoring:{name:"monitoring",description:"SigNoz or SkyWalking observability platform for monitoring and tracing",category:"optional",phase:"pre_alpha",enabled_by_default:!1,dependsOn:[P]},elk:{name:"elk",description:"Elasticsearch, Logstash, Kibana stack for log aggregation and analysis",category:"optional",phase:"pre_alpha",enabled_by_default:!1,dependsOn:[]},debezium:{name:"debezium",description:"Change Data Capture for real-time data streaming from databases",category:"optional",phase:"pre_alpha",enabled_by_default:!1,dependsOn:[P]},"golden-image":{name:"golden-image",description:"Pre-built Docker image layer for faster builds and smaller deployments",category:"optional",phase:"pre_alpha",enabled_by_default:!0,dependsOn:[]}};var j={demo:{repo:"https://github.com/flisk-sh/tdk-restaurant-example.git",description:"The demo stack: restaurant ops with reservations, kitchen and floor control"},restaurant:{repo:"https://github.com/flisk-sh/tdk-restaurant-example.git",description:"Restaurant ops: reservations, kitchen, floor control (Hono + Vite + Bun)"},saas:{repo:"https://github.com/flisk-sh/tdk-saas-starter.git",description:"SaaS starter: account dashboard and a working checkout button (Hono + Vite + Bun)"},erp:{repo:"https://github.com/flisk-sh/tdk-erp-system.git",description:"Enterprise ERP: 100 microservices across 7 business domains"},"user-management":{repo:"https://github.com/flisk-sh/tdk-user-management.git",description:"User/auth management services"},ecommerce:{repo:"https://github.com/flisk-sh/tdk-ecommerce-example.git",description:"Vue 3 storefront and Hono catalog API (needs Flisk 1.3.75+ for --framework vue)"},example:{repo:"https://github.com/flisk-sh/tdk-example.git",bundledPath:"examples/tdk-example",description:"Hono + Postgres + NATS worker + Vite example with a routed write path"},"agent-stack":{repo:"https://github.com/flisk-sh/tdk-agent-stack.git",description:"AI agent stack: Bun agent + MCP tool server + Postgres + NATS"}};function Ge(e){let o=e[2];if(!(!o||o.startsWith("-")))return o in j?o:void 0}function K(e,o){try{return ce(e,o)}catch{return[]}}function Ee(e){return new Set([...e.phases.pre_alpha.enabledStacks,...e.phases.alpha.enabledStacks,...e.phases.beta.enabledStacks,...e.phases.out_of_scope.enabledStacks])}function Q(e,o){let c=Ee(e),a=o.filter(l=>!c.has(l));return a.length===0?(e.phases.pre_alpha.enabledStacks=Array.from(new Set(e.phases.pre_alpha.enabledStacks)),[]):(e.phases.pre_alpha.enabledStacks=Array.from(new Set([...e.phases.pre_alpha.enabledStacks,...a])),a)}function ut(e,o){let c=_(e,".tdk",U);if(!y(c))return[];let a=D(e),l=Q(a,K(e,o));return l.length>0&&N(c,a),l}function Ae(){return Object.values(O).filter(e=>e.enabled_by_default&&e.category==="core").map(e=>e.name)}function Ce(e,o){return o||(j[e]?.repo.split("/").pop()??e).replace(/\.git$/,"")}async function Oe(e,o,c){let a=j[e];if(!a){console.log(p.red(`
2
+ import{b as N,c as pe,d as H,i as D,j as q,n as J,o as I,q as C}from"./chunk-WMF4AFAE.js";import{H as B,J as V,L as A,Na as ne,Ra as ae,Sa as se,Ua as ie,V as F,W as z,Wa as ce,Xa as le,Ya as de,aa as f,ba as v,ca as t,d as P,ja as re,k as U,ka as G,la as W,m as E,s as T}from"./chunk-CBFVK3TF.js";import{b as p}from"./chunk-CF46CD6R.js";import{execFileSync as ve}from"node:child_process";import{cpSync as ye,existsSync as y,readdirSync as Se,readFileSync as Y,writeFileSync as je}from"node:fs";import{basename as _e,dirname as we,join as _,resolve as M}from"node:path";import{cwd as ue}from"node:process";import{fileURLToPath as xe}from"node:url";import{Command as Pe}from"commander";var he="-y, --yes",ke="Skip prompts and confirmations; use defaults";function fe(e,o=ke){return e.option(he,o,!1)}async function be(e,o=!0){let c=await I({message:e,initial:o});return c||F(),c}function Ne(e,o=1){e.valid||A(e.error??"Validation failed",o)}function De(e,o,c,a){return e.dryRun?(a?a():(console.log(`Dry run - ${o}`),console.log(`Would run: ${c}`)),!0):!1}async function Je(e,o){return await be(e,!0)?!0:(o&&o(),!1)}var L=new Map;function me(e){e!==void 0?L.delete(e):L.clear()}function Ue(e=!1){let o=T(),c=o??"";if(!e){let n=L.get(c);if(n)return n}let{resources:a,problems:l}=o?ae(o):{resources:ie(),problems:[]},d=de(a),r=le(a);se(l);let g=a.filter(n=>!n.stack),m=new Map;for(let n of a)if(n.stack){let w=m.get(n.stack)||[];w.push(n),m.set(n.stack,w)}let k={resources:a,problems:l,stacks:d,stackNames:r,unassignedResources:g,resourcesByStack:m};return L.set(c,k),k}var O={proxy:{name:"proxy",description:"Traefik reverse proxy and API gateway for routing all services",category:"core",phase:"pre_alpha",enabled_by_default:!0,dependsOn:[]},verdaccio:{name:"verdaccio",description:"Verdaccio npm registry for package management and local publishing (Premium - requires TDK_LICENSE_KEY)",category:"premium",phase:"pre_alpha",enabled_by_default:!1,dependsOn:[]},[P]:{name:P,description:"PostgreSQL database for data persistence and SQL operations",category:"core",phase:"pre_alpha",enabled_by_default:!0,dependsOn:[]},monitoring:{name:"monitoring",description:"SigNoz or SkyWalking observability platform for monitoring and tracing",category:"optional",phase:"pre_alpha",enabled_by_default:!1,dependsOn:[P]},elk:{name:"elk",description:"Elasticsearch, Logstash, Kibana stack for log aggregation and analysis",category:"optional",phase:"pre_alpha",enabled_by_default:!1,dependsOn:[]},debezium:{name:"debezium",description:"Change Data Capture for real-time data streaming from databases",category:"optional",phase:"pre_alpha",enabled_by_default:!1,dependsOn:[P]},"golden-image":{name:"golden-image",description:"Pre-built Docker image layer for faster builds and smaller deployments",category:"optional",phase:"pre_alpha",enabled_by_default:!0,dependsOn:[]}};var j={demo:{repo:"https://github.com/flisk-sh/tdk-restaurant-example.git",description:"The demo stack: restaurant ops with reservations, kitchen and floor control"},restaurant:{repo:"https://github.com/flisk-sh/tdk-restaurant-example.git",description:"Restaurant ops: reservations, kitchen, floor control (Hono + Vite + Bun)"},saas:{repo:"https://github.com/flisk-sh/tdk-saas-starter.git",description:"SaaS starter: account dashboard and a working checkout button (Hono + Vite + Bun)"},erp:{repo:"https://github.com/flisk-sh/tdk-erp-system.git",description:"Enterprise ERP: 100 microservices across 7 business domains"},"user-management":{repo:"https://github.com/flisk-sh/tdk-user-management.git",description:"User/auth management services"},ecommerce:{repo:"https://github.com/flisk-sh/tdk-ecommerce-example.git",description:"Vue 3 storefront and Hono catalog API (needs Flisk 1.3.75+ for --framework vue)"},example:{repo:"https://github.com/flisk-sh/tdk-example.git",bundledPath:"examples/tdk-example",description:"Hono + Postgres + NATS worker + Vite example with a routed write path"},"agent-stack":{repo:"https://github.com/flisk-sh/tdk-agent-stack.git",description:"AI agent stack: Bun agent + MCP tool server + Postgres + NATS"}};function Ge(e){let o=e[2];if(!(!o||o.startsWith("-")))return o in j?o:void 0}function K(e,o){try{return ce(e,o)}catch{return[]}}function Ee(e){return new Set([...e.phases.pre_alpha.enabledStacks,...e.phases.alpha.enabledStacks,...e.phases.beta.enabledStacks,...e.phases.out_of_scope.enabledStacks])}function Q(e,o){let c=Ee(e),a=o.filter(l=>!c.has(l));return a.length===0?(e.phases.pre_alpha.enabledStacks=Array.from(new Set(e.phases.pre_alpha.enabledStacks)),[]):(e.phases.pre_alpha.enabledStacks=Array.from(new Set([...e.phases.pre_alpha.enabledStacks,...a])),a)}function ut(e,o){let c=_(e,".tdk",U);if(!y(c))return[];let a=D(e),l=Q(a,K(e,o));return l.length>0&&N(c,a),l}function Ae(){return Object.values(O).filter(e=>e.enabled_by_default&&e.category==="core").map(e=>e.name)}function Ce(e,o){return o||(j[e]?.repo.split("/").pop()??e).replace(/\.git$/,"")}async function Oe(e,o,c){let a=j[e];if(!a){console.log(p.red(`
3
3
  \u274C Unknown template: "${e}"`)),console.log(p.yellow(`
4
4
  Available templates:`));for(let[r,g]of Object.entries(j))console.log(` ${p.cyan(r)} ${p.gray(`- ${g.description}`)}`);console.log(p.gray("\nOr run `flisk project` with no template for a blank project.")),process.exit(1)}let l=Ce(e,o);ne(l)||B.invalidPath(l).exit();let d=M(ue(),l);y(d)&&Se(d).length>0&&B.directoryExists(d).exit(),z(`Cloning template: ${e}`),t(`${a.description}
5
5
  `,0),t(`Source: ${a.bundledPath?"bundled Flisk example":a.repo}`,0),t(`Destination: ${d}
6
6
  `,0);try{if(a.bundledPath){let r=M(we(xe(new URL("../dist/commands/project.js",import.meta.url).href)),"../../../");ye(M(r,a.bundledPath),d,{recursive:!0});let g=_e(d).replace(/-/g,"_");for(let m of["services/platform/messaging/docker-compose.yml","services/shop/orders-api/service.json","services/shop/orders-api/src/index.ts","services/shop/orders-worker/service.json","services/shop/orders-worker/src/index.ts"]){let k=_(d,m),n=Y(k,"utf-8");je(k,n.replaceAll("tdk_example",g))}}else ve("git",["clone",a.repo,d],{stdio:"inherit"})}catch{A(a.bundledPath?"Bundled example copy failed. Reinstall the Flisk CLI package and try again.":"git clone failed. Check you have git installed and network access.")}me(),console.log(p.green(`
7
7
  \u2705 Cloned "${e}" into ${l}/`)),t(`
8
8
  Next steps:`,0),t(`1. cd ${l}`),t("2. flisk doctor # check Docker/Tilt are ready"),t("3. flisk up # start the stack"),t(`
9
- Runtime readiness:`,0);for(let r of c)t(r,0)}var R={version:"1.0",project:{name:"",version:"1.0.0"},phases:{pre_alpha:{name:"Pre-Alpha",description:"Core infrastructure and MVP services",enabledStacks:Ae()},alpha:{name:"Alpha",description:"Essential business services",enabledStacks:[]},beta:{name:"Beta",description:"Extended features",enabledStacks:[]},out_of_scope:{name:"Out of Scope",description:"Future releases",enabledStacks:[]}},optional_infra:{monitoring:!1,elk:!1,debezium:!1,golden_image:!0,verdaccio:!1},discovery:{paths:["services/*/*"]},overrides:{}},gt=fe(new Pe("project")).description("Initialize or validate project-level master configuration").argument("[template]",`Clone a starter example instead of a blank project (${Object.keys(j).join(", ")})`).option("--path <dir>","Directory to clone the template into (default: the template's repo name)").option("--check","Check if master configs exist and are in sync").option("--force","Overwrite existing configuration (dangerous)").option("--config-file <path>","Load project config from existing JSON file").action(async(e,o)=>{let{assertMachineReadyOrExit:c,detectRuntimePrerequisites:a,formatRuntimeNextSteps:l}=await import("./cold-preflight-LPH7WF3B.js");await c({scope:"scaffold"});let d=l(a());if(e){await V(async()=>Oe(e,o.path,d));return}await V(async()=>{let r=T();r||(r=ue(),v(`\u{1F680} Initializing new Flisk project...
9
+ Runtime readiness:`,0);for(let r of c)t(r,0)}var R={version:"1.0",project:{name:"",version:"1.0.0"},phases:{pre_alpha:{name:"Pre-Alpha",description:"Core infrastructure and MVP services",enabledStacks:Ae()},alpha:{name:"Alpha",description:"Essential business services",enabledStacks:[]},beta:{name:"Beta",description:"Extended features",enabledStacks:[]},out_of_scope:{name:"Out of Scope",description:"Future releases",enabledStacks:[]}},optional_infra:{monitoring:!1,elk:!1,debezium:!1,golden_image:!0,verdaccio:!1},discovery:{paths:["services/*/*"]},overrides:{}},gt=fe(new Pe("project")).description("Initialize or validate project-level master configuration").argument("[template]",`Clone a starter example instead of a blank project (${Object.keys(j).join(", ")})`).option("--path <dir>","Directory to clone the template into (default: the template's repo name)").option("--check","Check if master configs exist and are in sync").option("--force","Overwrite existing configuration (dangerous)").option("--config-file <path>","Load project config from existing JSON file").action(async(e,o)=>{let{assertMachineReadyOrExit:c,detectRuntimePrerequisites:a,formatRuntimeNextSteps:l}=await import("./cold-preflight-FXOZ5SR5.js");await c({scope:"scaffold"});let d=l(a());if(e){await V(async()=>Oe(e,o.path,d));return}await V(async()=>{let r=T();r||(r=ue(),v(`\u{1F680} Initializing new Flisk project...
10
10
  `),t(`Location: ${r}
11
11
  `,0));let g=_(r,".tdk"),m=_(g,U);if(o.check){let i=E.every(u=>y(_(r,".tdk",".tdk-out",u))),h=y(m);if(i&&h){let u=D(r);f("Project configuration is valid"),t(`Project: ${u.project.name}`,3),t(`Phases: ${Object.keys(u.phases).join(", ")}`,3),process.exit(0)}else{if(console.log(p.yellow("\u26A0\uFE0F Project configuration incomplete:")),h||t(".tdk/project.json (not found)",3),!i)for(let u of E.filter(S=>!y(_(r,".tdk/.tdk-out",S))))t(`.tdk/.tdk-out/${u} (not found)`,3);t("Run `flisk project` to create them."),process.exit(1)}}z("Project Configuration"),t(`Project root: ${r}
12
12
  `,0),y(g)||(pe(g),f("Created: .tdk/ directory"));let k=y(m);if(k&&!o.force){f(".tdk/project.json exists");let i=JSON.parse(Y(m,"utf-8")),h=D(r),u=K(r),S=Q(h,u);if((S.length>0||!i.phases)&&N(m,h),S.length>0&&t(`Auto-enabled discovered service stacks: ${S.join(", ")}`,0),v(`
@@ -1,2 +1,2 @@
1
1
  import{createRequire as __tdkRequire}from'node:module';const require=__tdkRequire(import.meta.url);
2
- import{r as c}from"./chunk-RMZQU74X.js";import{execFileSync as u}from"node:child_process";import{realpathSync as l}from"node:fs";import{resolve as p}from"node:path";var m=(o,t)=>u(o,t,{encoding:"utf-8",stdio:"pipe",timeout:5e3,windowsHide:!0});function a(o,t=process.platform,e=m){if(t==="win32")return null;try{let s=e("lsof",["-nP",`-iTCP:${o}`,"-sTCP:LISTEN","-t"]).split(/\r?\n/).map(r=>r.trim()).filter(Boolean);for(let r of s){let n=e("ps",["-p",r,"-o","command="]).trim(),[i]=c(`${r} ${n}`);if(i)return i}}catch{}return null}function f(o){try{return l(o)}catch{return p(o)}}function d(o,t){return o!==null&&f(o.root)!==f(t)}async function P(o,t,e,s=a){let r={running:[],foreign:[]};for(let n of o){if(!await e(n))continue;let i=s(n);i&&d(i,t)?r.foreign.push({port:n,root:i.root}):r.running.push(n)}return r}export{a,d as b,P as c};
2
+ import{r as c}from"./chunk-BS6G2SLM.js";import{execFileSync as u}from"node:child_process";import{realpathSync as l}from"node:fs";import{resolve as p}from"node:path";var m=(o,t)=>u(o,t,{encoding:"utf-8",stdio:"pipe",timeout:5e3,windowsHide:!0});function a(o,t=process.platform,e=m){if(t==="win32")return null;try{let s=e("lsof",["-nP",`-iTCP:${o}`,"-sTCP:LISTEN","-t"]).split(/\r?\n/).map(r=>r.trim()).filter(Boolean);for(let r of s){let n=e("ps",["-p",r,"-o","command="]).trim(),[i]=c(`${r} ${n}`);if(i)return i}}catch{}return null}function f(o){try{return l(o)}catch{return p(o)}}function d(o,t){return o!==null&&f(o.root)!==f(t)}async function P(o,t,e,s=a){let r={running:[],foreign:[]};for(let n of o){if(!await e(n))continue;let i=s(n);i&&d(i,t)?r.foreign.push({port:n,root:i.root}):r.running.push(n)}return r}export{a,d as b,P as c};
@@ -1,5 +1,5 @@
1
1
  import{createRequire as __tdkRequire}from'node:module';const require=__tdkRequire(import.meta.url);
2
- import{c as z,e as Q}from"./chunk-42IVF3YT.js";import{Fa as J,Ga as B,Qa as O,Ta as Y,cb as X,d as v,e as k,g as q,ga as L,h as x,i as P,j as F,k as W,l as A,p as d,q as N}from"./chunk-LMHKXU2Q.js";import{b as V}from"./chunk-CF46CD6R.js";import{a as $}from"./chunk-6EA4DGCY.js";import{appendFileSync as le,existsSync as C,mkdirSync as fe,readFileSync as de,writeFileSync as Z}from"node:fs";import{dirname as pe,resolve as w}from"node:path";function ft(t,e,n){for(let[r,s]of e.entries())console.log(V.blue(`${s.emoji} ${s.description}...`)),s.type==="json"?me(t,s.filename,s.content):he(t,s.filename,String(s.content)),n&&n(s,r,e.length)}function ue(t,e,n=2){let r=`${JSON.stringify(e,null,n)}
2
+ import{c as z,e as Q}from"./chunk-42IVF3YT.js";import{Fa as J,Ga as B,Qa as O,Ta as Y,cb as X,d as v,e as k,g as q,ga as L,h as x,i as P,j as F,k as W,l as A,p as d,q as N}from"./chunk-CBFVK3TF.js";import{b as V}from"./chunk-CF46CD6R.js";import{a as $}from"./chunk-6EA4DGCY.js";import{appendFileSync as le,existsSync as C,mkdirSync as fe,readFileSync as de,writeFileSync as Z}from"node:fs";import{dirname as pe,resolve as w}from"node:path";function ft(t,e,n){for(let[r,s]of e.entries())console.log(V.blue(`${s.emoji} ${s.description}...`)),s.type==="json"?me(t,s.filename,s.content):he(t,s.filename,String(s.content)),n&&n(s,r,e.length)}function ue(t,e,n=2){let r=`${JSON.stringify(e,null,n)}
3
3
  `;Z(t,r,"utf-8")}function me(t,e,n,r=2){let s=w(t,e);ue(s,n,r)}function U(t,e){Z(t,e,"utf-8")}function he(t,e,n){let r=w(t,e);U(r,n)}function dt(t){C(t)||fe(t,{recursive:!0})}var ge=[".env",".tdk/.tdk-out/",".tdk/.project-id",".tdk/smoke/","node_modules/"];function Se(t){let e=w(t,".gitignore"),n=C(e)?de(e,"utf-8"):"",r=new Set(n.split(`
4
4
  `).map(f=>f.trim().replace(/\/$/,""))),s=ge.filter(f=>!r.has(f.replace(/\/$/,"")));if(s.length===0)return[];let c=n&&!n.endsWith(`
5
5
  `)?`
@@ -0,0 +1,24 @@
1
+ import{createRequire as __tdkRequire}from'node:module';const require=__tdkRequire(import.meta.url);
2
+ import{O as h,Ta as D,Ua as L,fa as _,h as I,k as w,l as A,q as j,qa as x,s as T,x as F}from"./chunk-CBFVK3TF.js";import{execFileSync as B}from"node:child_process";import{existsSync as de,mkdirSync as le,readFileSync as K,realpathSync as fe,writeFileSync as pe}from"node:fs";import{join as S,resolve as he,sep as me}from"node:path";import{createServer as ie}from"node:net";import{connect as oe}from"node:net";function U(e,t=500){return new Promise(r=>{let s=oe({port:e,host:"127.0.0.1"}),n=o=>{s.destroy(),r(o)};s.setTimeout(t,()=>n(!1)),s.once("connect",()=>n(!0)),s.once("error",()=>n(!1))})}var ae={ingressHttp:{start:8080,end:8180},ingressHttps:{start:8443,end:8543},postgres:{start:15432,end:15532}},v={ingressHttp:"TDK_HTTP_PORT",ingressHttps:"TDK_HTTPS_PORT",postgres:"TDK_POSTGRES_PORT"},H={ingressHttp:80,ingressHttps:443,postgres:5432},E={ingressHttp:H.ingressHttp,ingressHttps:H.ingressHttps};function ce(e,t){return e==="EACCES"&&t==="darwin"}async function O(e){return await U(e)?!1:new Promise(t=>{let r=ie();r.once("error",s=>{t(ce(s.code,process.platform))}),r.listen(e,"127.0.0.1",()=>r.close(()=>t(!0)))})}function ue(e,t){let r=Number(t);if(!Number.isInteger(r)||r<1||r>65535)throw new Error(`${e} must be an integer between 1 and 65535 (received ${JSON.stringify(t)})`);return r}async function R(e={}){let t=e.env??process.env,r=e.isAvailable??O,s={ingressHttp:!1,ingressHttps:!1,postgres:!1},n={ingressHttp:"",ingressHttps:"",postgres:""},o={explicit:s},a=new Set;for(let c of["ingressHttp","ingressHttps","postgres"]){let u=t[v[c]],i=u!==void 0&&u.trim()!=="",d=e.ranges?.[c]??ae[c],l=E[c],f=i?[ue(v[c],u)]:[...l===void 0?[]:[l],...Array.from({length:d.end-d.start+1},(g,k)=>d.start+k)],m;for(let g of f)if(!a.has(g)){if(await r(g)){m=g;break}if(i)throw new Error(`${v[c]}=${g} is already in use. Choose a free host port and retry.`)}if(m===void 0)throw new Error(`No available host port in ${d.start}-${d.end} for ${c}. Set ${v[c]} to a free port and retry.`);a.add(m),o[c]=m,s[c]=i,n[c]=i?"explicit override":m===l?"requested port is free":`selected from fallback range ${d.start}-${d.end}`}return{...o,requested:{...H},reason:n}}function Ve(e){return`Host ports: HTTP ${e.ingressHttp}, HTTPS ${e.ingressHttps}, Postgres ${e.postgres}`}var G=S(".tdk",".tdk-out","host-ports.json");function ge(e,t,r){return e.split(`
3
+ `).some(s=>{let[n="",o=""]=s.split("|"),a=n.toLowerCase(),c=t.toLowerCase();return(a.startsWith(`${c}_`)||a.startsWith(`${c}-`))&&o.includes(`:${r}->`)})}function V(e){let t=S(e,G);if(!de(t))return null;try{let r=JSON.parse(K(t,"utf-8"));if(!r||typeof r!="object")return null;let s=r;return!Number.isInteger(s.ingressHttp)||!Number.isInteger(s.ingressHttps)||!Number.isInteger(s.postgres)||!s.requested||!s.explicit||!s.reason?null:s}catch{return null}}function Ye(e,t){let r=S(e,G);le(S(e,".tdk",".tdk-out"),{recursive:!0}),pe(r,`${JSON.stringify(t,null,2)}
4
+ `,{encoding:"utf-8",mode:384})}function Qe(e){process.env.TDK_HTTP_PORT=String(e.ingressHttp),process.env.TDK_HTTPS_PORT=String(e.ingressHttps),process.env.TDK_POSTGRES_PORT=String(e.postgres)}var ke="com.docker.compose.project.working_dir";function Pe(e,t,r){let s=new Set([he(t)]);try{s.add(fe(t))}catch{}return e.split(`
5
+ `).some(n=>{let[,o="",a=""]=n.split("|");return!a||!o.includes(`:${r}->`)?!1:[...s].some(c=>a===c||a.startsWith(`${c}${me}`))})}function Xe(e,t,r=()=>B("docker",["ps","--format",`{{.Names}}|{{.Ports}}|{{.Label "${ke}"}}`],{encoding:"utf-8",timeout:5e3})){let s=V(e);if(!s||s.ingressHttp===t)return t;try{if(Pe(r(),e,s.ingressHttp))return s.ingressHttp}catch{}return t}async function et(e,t={}){let r=V(e),s=["TDK_HTTP_PORT","TDK_HTTPS_PORT","TDK_POSTGRES_PORT"].some(i=>process.env[i]);if(t.inspectDocker===!1&&r&&!s)return r;let n="";try{let i=JSON.parse(K(S(e,".tdk",w),"utf-8"));n=String(i?.project?.name??"tdk-project").replace(/-/g,"_").toLowerCase()}catch{n="tdk_project"}let o="";if(t.inspectDocker!==!1)try{o=B("docker",["ps","--format","{{.Names}}|{{.Ports}}"],{encoding:"utf-8",timeout:5e3})}catch{}let a=i=>ge(o,n,i),c=t.isPortFree??O,u=async i=>await c(i)||a(i);if(r&&!s){for(let i of[r.ingressHttp,r.ingressHttps,r.postgres])if(!await u(i))return R({isAvailable:u});for(let[i,d]of Object.entries(E)){let l=r[i];if(d!==void 0&&l!==d&&await u(d))return R({isAvailable:u})}return r}return R({isAvailable:u})}import{execFileSync as Q,execSync as $}from"node:child_process";import{existsSync as C,readdirSync as Te,readFileSync as N}from"node:fs";import{createServer as Se}from"node:net";import{join as P}from"node:path";function W(e,t){return e==="pending"||e==="in_progress"||e==="none"||t==="pending"||t==="none"}var J="container is running, but its health check is failing";function M(e){let t=e?.runtimeStatus??"";if(t!=="ok")return t;let r=e?.composeResourceInfo?.healthStatus;return r==="unhealthy"?"error":r==="starting"?"pending":t}var b=1e4,z=3e3,be="http://localhost:4873";function X(e){return`'${e.replace(/'/g,"'\\''")}'`}function y(e,t,r,s,n){return process.platform==="win32"?Q(F(t)??t,r,{...n,windowsHide:!0}):e(s,n)}var ye=[80,443];function $e(e){return e.replace(/-/g,"_")}function we(e,t){let r=new Set(t),s=[];for(let n of e.split(`
6
+ `)){let o=n.trim();if(!o)continue;let a=o.indexOf(" "),c=a>=0?o.slice(0,a):o,u=a>=0?o.slice(a+1):"",i=[];for(let d of r)u.split(/[\s,]+/).some(f=>f.startsWith(`${d}->`)||f.includes(`:${d}->`))&&i.push(d);i.length>0&&s.push({name:c,ports:u,publishedPorts:i})}return s}function ee(e,t){let r=e.toLowerCase(),s=t.toLowerCase();return r===`${s}_traefik`||r.startsWith(`${s}_traefik`)}function ve(e,t){return e.filter(r=>!ee(r.name,t))}function Re(e){try{let t=e??L();return new Set(t.filter(r=>r.config?.sablier?.enable&&r.config?.sablier?.deferStart).map(r=>r.name))}catch{return new Set}}function _e(e,t=new Set){let s=JSON.parse(e).items??[],n=[],o=0,a=0,c=0;for(let u of s){let i=u.metadata?.name??"unknown",d=u.status?.updateStatus??"",l=M(u.status),f=l==="error"&&u.status?.runtimeStatus==="ok",g=(u.status?.buildHistory?.[0]?.error??"").trim()||(f?J:"");if(d==="error"||l==="error"){n.push({name:i,updateStatus:d,runtimeStatus:l,error:g.replace(/\s+/g," ").slice(0,800)});continue}if(d==="ok"&&(l==="ok"||l==="not_applicable")){c+=1;continue}i!=="(Tiltfile)"&&W(d,l)&&(t.has(i)?a+=1:o+=1)}return{failures:n,pendingCount:o,deferredCount:a,okCount:c,total:s.length}}var xe=/failed to resolve source metadata for docker\.io\/library\/([A-Za-z0-9._-]+-l[1-4](?:-[a-z]+)*)(?::[^\s:]+)?:/i;function te(e){let t=e.replace(/\s+/g," ").trim(),r=t.match(/Bind for [^ ]+:(\d+) failed: port is already allocated/i);if(r)return`host port ${r[1]} is already allocated`;if(/port is already allocated/i.test(t))return"a required host port is already allocated";let s=[...t.matchAll(/ConnectionRefused downloading package manifest (@[A-Za-z0-9._/-]+)/gi)].map(c=>c[1]);if(s.length>0){let c=[...new Set(s)],u=c.slice(0,4).join(", "),i=c.length>4?` (+${c.length-4} more)`:"";return`private registry ConnectionRefused for ${u}${i} \u2014 Verdaccio (:4873) is down or unreachable from the build`}let n=t.match(xe);if(n)return`base image ${n[1]} was missing when this build started (the golden layers weren't built yet, or golden-layers-build failed) - Tilt does not retry a failed build by itself`;if(/install-deps\.sh/i.test(t)||/bun install(?: --production)?/i.test(t)||/npm (?:ci|install)/i.test(t))return"dependency install failed during ImageBuild \u2014 usually Verdaccio (:4873) unreachable or missing @scoped packages (ConnectionRefused downloading package manifest)";let o=t.match(/No such image:\s*([^\s]+)/i)?.[1]??t.match(/pull access denied for ([^,:\s]+)/i)?.[1]??void 0,a=t.match(/\bup\s+-d\s+--no-build\s+([A-Za-z0-9._-]+)/i)?.[1];if(o||a||/docker compose .*\bup\s+-d\s+--no-build\b/i.test(t)){let c=o??`${a??"service"}:dev`,u=a?` for ${a}`:"";return`compose run failed because image is missing (${c})${u} \u2014 wait for the ImageBuild resource to finish, then re-trigger the *-run-only resource`}return/bun run build/i.test(t)?"ImageBuild failed during `bun run build` (compile/typecheck) \u2014 open the resource logs in Tilt for the TypeScript/build error":(/ImageBuild:/i.test(t)||/^Command "/i.test(t),t.slice(0,220))}function q(e){return/ConnectionRefused downloading package manifest|Verdaccio|private registry|dependency install failed during ImageBuild|install-deps\.sh|bun install/i.test(e)}function He(e=T()??process.cwd()){let t=P(e,".tdk",w);if(!C(t))return!1;try{let r=JSON.parse(N(t,"utf-8"));return r.optional_infra?.verdaccio===!0||Object.values(r.phases??{}).some(s=>(s.enabledStacks??[]).includes("verdaccio"))}catch{return!1}}function re(e){for(let t of[P(e,".npmrc"),P(e,A)])if(C(t))try{let r=N(t,"utf-8");if(/:4873\b/.test(r)||/verdaccio/i.test(r))return!0}catch{}return!1}function Ee(e=T()??process.cwd()){return He(e)||re(e)}function mt(e=$,t=T()??process.cwd(),r=process.env.VERDACCIO_URL??process.env.NPM_REGISTRY_URL??be,s=!0){if(!s&&!re(t))return{name:"Private npm registry",didPass:!0,isSkipped:!0,message:"Verdaccio is enabled in the project config but needs a Premium license, so Flisk will not start it - skipped"};if(!Ee(t))return{name:"Private npm registry",didPass:!0,isSkipped:!0,message:"Private npm registry (Verdaccio) not enabled for this project - skipped"};let n=!1;try{let c=y(e,"docker",["ps","--format","{{.Names}}"],"docker ps --format '{{.Names}}'",{stdio:"pipe",encoding:"utf-8",timeout:b});n=/verdaccio/i.test(c)}catch{}let o=!1,a="";try{let c=process.platform==="win32"?Q("curl.exe",["-fsS","-o","NUL","-w","%{http_code}","--max-time","2",r],{stdio:"pipe",encoding:"utf-8",timeout:z+1e3,windowsHide:!0}).trim():e(`curl -fsS -o /dev/null -w '%{http_code}' --max-time 2 ${X(r)}`,{stdio:"pipe",encoding:"utf-8",timeout:z+1e3}).trim();o=/^[23]\d\d$/.test(c),a=`HTTP ${c}`}catch(c){a=c instanceof Error?c.message.slice(0,120):"request failed"}return o?{name:"Private npm registry",didPass:!0,message:`Private npm registry reachable at ${r}${n?" (verdaccio container running)":""}`}:n?{name:"Private npm registry",didPass:!1,message:`Verdaccio container is running but ${r} is not responding (${a}). ImageBuilds that install @scoped packages will fail with ConnectionRefused downloading package manifest.`,fix:"Check `docker logs` for the verdaccio container, confirm port 4873 is published, then re-run `flisk doctor`."}:{name:"Private npm registry",didPass:!1,message:`Private npm registry (Verdaccio) is not reachable at ${r}. Docker ImageBuilds will fail with ConnectionRefused downloading package manifests for @flisk-sh/* and project-scoped packages.`,fix:"Start the registry with `bun run verdaccio:start` (or `docker compose -f docker-compose.verdaccio.yml up -d`), publish packages with `bun run publish:all` / `scripts/build/publish-to-verdaccio.sh`, then `tilt trigger` failed resources or re-run `flisk up`."}}function gt(e=$,t=x(),r=ye){let s=$e(t),n="";try{n=y(e,"docker",["ps","--format","{{.Names}}\\t{{.Ports}}"],"docker ps --format '{{.Names}}\\t{{.Ports}}'",{stdio:"pipe",encoding:"utf-8",timeout:b})}catch{return{name:"Ingress Ports",didPass:!0,isSkipped:!0,message:"Docker not available - skipped ingress port check"}}let o=we(n,r),a=ve(o,s);if(a.length===0){let u=o.filter(i=>ee(i.name,s));return u.length>0?{name:"Ingress Ports",didPass:!0,message:`Ingress ports ${r.join("/")} held by this project's Traefik (${u.map(i=>i.name).join(", ")})`}:{name:"Ingress Ports",didPass:!0,message:`Ingress ports ${r.join("/")} are free for Traefik`}}return{name:"Ingress Ports",didPass:!1,message:`Traefik cannot bind ingress ports because another container already owns them:
7
+ ${a.map(u=>{let i=u.publishedPorts.join(", ");return`${u.name} (host ports ${i})`}).join(`
8
+ `)}`,fix:`Stop the foreign container(s), e.g. \`docker stop ${a[0]?.name}\`, or shut down the other Flisk/Tilt project using that Traefik. Then re-run \`flisk up\`.`}}function Z(e,t){return new Promise(r=>{let s=Se();s.once("error",n=>r(n.code==="EADDRINUSE"?"in-use":"unknown")),s.once("listening",()=>s.close(()=>r("free"))),s.listen(e,t)})}async function kt(e){for(let t=0;t<2;t++){let r=await Z(e,"0.0.0.0");if(r==="unknown")return r;if(r==="free"){let s=await Z(e,"127.0.0.1");if(s==="free"||s==="unknown")return s}t===0&&await new Promise(s=>setTimeout(s,50))}return"in-use"}function Oe(e){let{status:t}=e;return t===void 0?e.error??"no response":t===404?"HTTP 404: Traefik is answering but has no route for this URL (container not started yet, or not running)":t===502||t===503||t===504?`HTTP ${t}: Traefik found the route but the container isn't answering (still starting, or unhealthy)`:`HTTP ${t}`}function Pt(e){let t=e.filter(o=>o.status!==void 0),r=e.filter(o=>!o.ok);if(t.length===0)return{name:"Service Health",didPass:!0,isSkipped:!0,message:`No services responded - skipped ping of ${h(e.length,"service")} (stack may be down, or Traefik never bound :80)`,fix:"If `flisk up` is already running, check Traefik/port 80 in the Tilt UI. Otherwise start with: flisk up"};if(r.length===0)return{name:"Service Health",didPass:!0,message:`All ${h(e.length,"service")} responding on /health`};let s=r.map(o=>`${o.name} (${Oe(o)})
9
+ ${o.url}`).join(`
10
+ `),n=r.some(o=>o.status===404);return{name:"Service Health",didPass:!1,message:`${h(r.length,"service")} not healthy (${e.length-r.length}/${e.length} healthy):
11
+ ${s}`,fix:n?"If `flisk up` just started, images may still be building: re-run `flisk doctor` in a minute. Otherwise check `docker ps` and the resource in the Tilt UI, and compare `flisk networks` with the URL above.":"Check container state and routing: docker ps, then flisk networks to compare the advertised URLs against Traefik's routers"}}function Tt(e){if(e.length===0)return{name:"Service Smoke",didPass:!0,isSkipped:!0,message:"No read-only smoke checks declared"};let t=e.filter(s=>!s.ok);if(t.length===0)return{name:"Service Smoke",didPass:!0,message:`All ${h(e.length,"service")} pass their smoke checks`};let r=t.map(s=>s.failure??`${s.name}: failed`).join(`
12
+ `);return{name:"Service Smoke",didPass:!1,message:`${h(t.length,"service")} failing a smoke check (${e.length-t.length}/${e.length} passing):
13
+ ${r}`,fix:'Add the route the smoke step expects, or correct its "path" in the service.json "smoke" block. Then re-run flisk doctor.'}}function St(e){let t=e.filter(n=>n.status!==void 0);if(t.length===0)return{name:"Advertised Endpoints",didPass:!0,isSkipped:!0,message:"No services responded - skipped advertised endpoint check"};let r=t.filter(n=>n.status===404);if(r.length===0)return{name:"Advertised Endpoints",didPass:!0,message:`${h(t.length,"advertised endpoint")} reachable`};let s=r.map(n=>`${n.name} (404)
14
+ ${n.url}`).join(`
15
+ `);return{name:"Advertised Endpoints",didPass:!0,isWarning:!0,message:`${h(r.length,"advertised link")} ${r.length===1?"returns":"return"} 404 (the service may be healthy, but nothing answers at this exact path):
16
+ ${s}`,fix:'Nothing handles this exact path, so opening the link shows a 404 even when /health is fine. If this API has no root route, you can leave it. Otherwise add a GET route for it (for example one that returns the service name), or declare a read-only "smoke" step on a real route in service.json. The URL flisk networks and the Flisk App print stays the same until the CLI changes how it reports it.'}}function bt(e=$){let t="";try{t=y(e,"tilt",["get","uiresources","-o","json"],"tilt get uiresources -o json",{stdio:"pipe",encoding:"utf-8",timeout:b})}catch{return{name:"Tilt Resources",didPass:!0,isSkipped:!0,message:"Tilt is not running - skipped resource status check",fix:"Start them with: flisk up"}}let r;try{r=_e(t,Re())}catch{return{name:"Tilt Resources",didPass:!0,isSkipped:!0,message:"Could not parse Tilt resource status - skipped"}}if(r.total===0)return{name:"Tilt Resources",didPass:!0,isSkipped:!0,message:"No Tilt UIResources found"};if(r.failures.length===0){let p=r.deferredCount>0?`, ${r.deferredCount} deferred`:"";return{name:"Tilt Resources",didPass:!0,message:`Tilt resources healthy (${r.okCount} ok, ${r.pendingCount} pending${p})`}}let s=Ne(r.failures),o=s.slice(0,20),a=s.length-o.length,c=o.map(p=>({failure:p,why:Ae(p,e)})),u=c.map(({failure:p,why:ne})=>`${p.name}: ${ne}`).join(`
17
+ `),i=a>0?`
18
+ \u2026and ${h(a,"more failed resource")}`:"",d=r.pendingCount>0?`
19
+ ${h(r.pendingCount,"resource")} still pending/not started \u2014 often blocked by the failures above.`:"",l=r.deferredCount>0?`
20
+ ${h(r.deferredCount,"resource")} intentionally deferred (sablier.deferStart) \u2014 not started until first request, unrelated to the failures above.`:"",f=s.some(p=>/port is already allocated/i.test(p.error)),m=s.some(p=>q(p.error)||q(te(p.error))),g=c.some(({why:p})=>/Kafka broker unreachable|kafka:9092/i.test(p)),k="Open the Tilt UI URL printed by flisk up (default port "+j.tiltUi+" when TILT_PORT is unset), inspect the red resources, fix the listed errors, then `tilt trigger <resource>` or re-run `flisk up`.";return f?k="Free the conflicting host port (usually 80/443): `docker ps --filter publish=80` then `docker stop <other-traefik>`. Re-trigger Traefik in the Tilt UI or run `flisk up` again.":m?k="Start Verdaccio (`bun run verdaccio:start`), ensure packages are published (`bun run publish:all` or `bash scripts/build/publish-to-verdaccio.sh`), confirm `curl http://localhost:4873` works, then `tilt trigger` the failed resources.":g&&(k="Kafka is not running (optional infra). Start it, point the bridge at a real broker, or disable Kafka-dependent resources until Kafka is enabled."),{name:"Tilt Resources",didPass:!1,message:`Tilt reports ${h(r.failures.length,"failed resource")}:
21
+ ${u}${i}${d}${l}`,fix:k}}var Ce=/^(traefik|postgres|nats|infisical|verdaccio|proxy)([.-]|$)/i;function Y(e){return Ce.test(e)}function Ne(e){return[...e].sort((t,r)=>{let s=Y(t.name)?0:1,n=Y(r.name)?0:1;return s!==n?s-n:t.name.localeCompare(r.name)})}function Ie(e,t=$,r=x()){try{let s=y(t,"docker",["ps","-a","--format","{{.Names}}"],"docker ps -a --format '{{.Names}}'",{stdio:"pipe",encoding:"utf-8",timeout:b}).split(`
22
+ `).map(i=>i.trim()).filter(Boolean),n=`-autogenerated-${e}-1`,o=s.find(i=>i===e)??s.find(i=>i.startsWith(`${r}-`)&&i.endsWith(n))??s.find(i=>i.endsWith(n))??s.find(i=>i.includes(e));if(!o)return null;let a=y(t,"docker",["logs","--tail","120",o],`docker logs --tail 120 ${X(o)} 2>&1`,{stdio:"pipe",encoding:"utf-8",timeout:b});if(/getaddrinfo ENOTFOUND/i.test(a)&&/kafka:9092/i.test(a))return"runtime crash: Kafka broker unreachable (getaddrinfo ENOTFOUND kafka:9092)";if(/ECONNREFUSED/i.test(a)&&/kafka/i.test(a))return"runtime crash: Kafka connection refused";let c=a.match(/ConnectionRefused downloading package manifest (@[A-Za-z0-9._/-]+)/i);if(c?.[1])return`runtime/build log: private registry ConnectionRefused for ${c[1]}`;if(/ZodError/i.test(a)){let i=[...a.matchAll(/"path"\s*:\s*\[\s*"([^"]+)"\s*\]/g)].map(l=>l[1]),d=[...new Set(i)].slice(0,6);return d.length>0?`runtime crash: ZodError missing required config/env: ${d.join(", ")}`:"runtime crash: ZodError during config/env validation"}let u=a.match(/error:\s+Failed to [^:\n]+[^\n]{0,120}/i)?.[0]??a.match(/Failed to (?:start|initialize) [^\n]{0,120}/i)?.[0]??a.match(/^\s*error:\s+[^\n]{0,160}/im)?.[0];if(u)return`runtime crash: ${u.replace(/\s+/g," ").trim().slice(0,180)}`}catch{return null}return null}function Ae(e,t=$){return e.error?te(e.error):e.runtimeStatus==="error"?Ie(e.name,t)??"runtime error (container crashed or unhealthy \u2014 check Tilt/docker logs)":e.updateStatus||e.runtimeStatus||"unknown error"}var je=/\.(ts|tsx|mts|js|mjs|cjs)$/,Fe=new Set(["node_modules","dist",I,"tests","__tests__"]);function se(e){let t=[];for(let r of Te(e,{withFileTypes:!0}))r.isDirectory()?Fe.has(r.name)||t.push(...se(P(e,r.name))):je.test(r.name)&&!/\.(test|spec)\./.test(r.name)&&t.push(P(e,r.name));return t}function De(e){let t=e?.healthCheckPath||"/health";return{container:t,traefik:e?.traefik?.healthCheck||t}}function Le(e){let t=[];for(let r of e){if(!_(r.config?.appType))continue;let s=P(r.path,"src");if(!C(s))continue;let n=se(s);if(n.length===0)continue;let o=n.map(i=>N(i,"utf-8")),{container:a,traefik:c}=De(r.config),u=a===c?[{path:a,usedBy:"container and Traefik healthchecks"}]:[{path:a,usedBy:"container healthcheck"},{path:c,usedBy:"Traefik healthcheck"}];for(let{path:i,usedBy:d}of u){let l=["'",'"',"`"].map(f=>`${f}${i}${f}`);o.some(f=>l.some(m=>f.includes(m)))||t.push({name:r.name,healthPath:i,usedBy:d})}}return t}function yt(e=T()??process.cwd()){let t=[];try{t=D(e)}catch{return{name:"Health Routes",didPass:!0,isSkipped:!0,message:"Could not read services - skipped health route check"}}let r=t.filter(o=>_(o.config?.appType));if(r.length===0)return{name:"Health Routes",didPass:!0,isSkipped:!0,message:"No backend services to check"};let s=Le(r);return s.length===0?{name:"Health Routes",didPass:!0,message:`All ${h(r.length,"backend")} define their health route`}:{name:"Health Routes",didPass:!1,message:`Backends without a health route (the container never turns healthy, so Traefik returns 404):
23
+ ${s.map(o=>`${o.name}: no "${o.healthPath}" route in src/ (probed by the ${o.usedBy})`).join(`
24
+ `)}`,fix:`Add the route, e.g. for Hono: app.get("${s[0]?.healthPath}", (c) => c.json({ status: "ok" })). To use a different path, set "healthCheckPath" (container healthcheck) or "traefik.healthCheck" (Traefik) in its service.json.`}}export{R as a,Ve as b,V as c,Ye as d,Qe as e,Xe as f,et as g,W as h,M as i,$e as j,Re as k,_e as l,te as m,He as n,mt as o,gt as p,kt as q,Pt as r,Tt as s,St as t,bt as u,yt as v};
@@ -0,0 +1,4 @@
1
+ import{createRequire as __tdkRequire}from'node:module';const require=__tdkRequire(import.meta.url);
2
+ import{a as S}from"./chunk-DTIHDMED.js";import{g as u,q as b}from"./chunk-Z6UD7UZH.js";import{a as P}from"./chunk-EPBYRJE3.js";import{Ra as x,ba as h,ca as w,d,k as m,ra as y,s as g,ta as k}from"./chunk-CBFVK3TF.js";import{b as a}from"./chunk-CF46CD6R.js";import{Command as R}from"commander";import{readFileSync as N}from"node:fs";import{join as O}from"node:path";function C(o){let e=o.config;return e?Array.isArray(e.featuresEnabled)&&e.featuresEnabled.includes(d)?!0:(Array.isArray(e.dependsOn)?e.dependsOn:[]).some(n=>P.includes(n)):!1}function J(o,e){let i=o.replace(/-/g,"_"),n=[];for(let t of[...e].sort((r,s)=>r.name.localeCompare(s.name))){let r=t.resources.filter(C).map(s=>s.name);r.length!==0&&n.push({name:`${i}_${t.name.replace(/-/g,"_")}`,stack:t.name,services:r.sort()})}return n.length===0?null:{name:"postgres",databases:n}}function $(o){try{let e=JSON.parse(N(O(o,".tdk",m),"utf-8"));return typeof e?.project?.name=="string"?e.project.name:null}catch{return null}}import{spawn as T}from"node:child_process";function F(o){try{let e=new URL(o);return e.protocol==="http:"||e.protocol==="https:"}catch{return!1}}function E(o,e=process.platform,i=T){if(!F(o))return Promise.resolve(!1);let n,t;return e==="darwin"?(n="open",t=[o]):e==="win32"?(n="rundll32.exe",t=["url.dll,FileProtocolHandler",o]):(n="xdg-open",t=[o]),new Promise(r=>{try{let s=i(n,t,{stdio:"ignore",detached:!0,windowsHide:!0});s.once("error",()=>r(!1)),s.once("spawn",()=>{typeof s.unref=="function"&&s.unref(),r(!0)})}catch{r(!1)}})}function V(o,e=process.platform,i=T){return new Promise(n=>{let t,r;e==="darwin"?(t="pbcopy",r=[]):e==="win32"?(t="clip",r=[]):(t="xclip",r=["-selection","clipboard"]);try{let s=i(t,r,{stdio:["pipe","ignore","ignore"],windowsHide:!0});s.on("error",()=>{n(!1)}),s.on("close",c=>{n(c===0)}),s.stdin?(s.stdin.on("error",()=>{n(!1)}),s.stdin.write(o,"utf-8"),s.stdin.end()):n(!1)}catch{n(!1)}})}async function j(o){let{resources:e}=x(o),i=await u(o,{inspectDocker:!1}),{appBase:n}=y(i?.ingressHttp,o);return e.filter(t=>t.config?.appType==="frontend").map(t=>({name:t.name,url:`${n}${k(t)}`}))}async function H(o,e=2e3){try{return(await fetch(o,{signal:AbortSignal.timeout(e)})).status<500}catch{return!1}}async function A(o,e=3e4,i){if(o.length===0)return;let n=Date.now(),t=n+e;for(;;){for(let s of o)if(await H(s.url))return s;let r=Date.now()-n;if(r>=e)return;i?.(r),await new Promise(s=>setTimeout(s,2e3))}}async function te(o,e=0,i){let n=await j(o);return A(n,e,i)}async function _(o){let e=o??g();if(!e)return console.log(a.yellow("Not in a Flisk project, so there is no frontend to open.")),console.log(a.gray("Run `flisk project --yes` first, or `flisk open` inside a project.")),null;let i=await j(e);if(i.length===0)return console.log(a.yellow("This project has no frontend service to open.")),console.log(a.gray("Start the stack with `flisk up` and add a frontend with `flisk resource`.")),null;let n=$(e);h(`Opening the first frontend of ${n??"this project"}`);for(let c of i)console.log(a.gray(` - ${c.name}: ${c.url}`));let t=S("Waiting for the frontend to answer..."),r=await A(i,12e4,c=>{t.text=`Waiting for the frontend to answer... ${Math.round(c/1e3)}s`});if(!r){t.fail("No frontend answered yet.");let l=(await u(e,{inspectDocker:!1}))?.ingressHttp,D=l?await b(l)==="in-use":!1;if(l&&!D){console.log(a.yellow(`The stack is running, but this machine cannot reach port ${l}.`)),console.log(a.gray(" Docker is not publishing the port to the host."));let{checkColima:p}=await import("./colima-4ID4BGHC.js"),f=p();f.isColima&&!f.running?(console.log(a.gray(` ${f.problem??"The Colima VM is not running"}`)),console.log(a.gray(` Fix: ${f.fix??"colima start"}`))):console.log(a.gray(" Restart the Docker runtime (Docker Desktop or Colima), then run `flisk open` again."))}else console.log(a.yellow("The stack is not serving the frontend yet.")),console.log(a.gray(" - Start the stack in another terminal: flisk up")),console.log(a.gray(" - Then run this again: flisk open"));for(let p of i)console.log(a.gray(` - ${p.name}: ${p.url}`));return null}t.succeed(`The frontend is up: ${r.name}`);let s=await E(r.url);return console.log(s?a.green(`
3
+ Opened ${r.url}`):a.yellow(`
4
+ Could not open a browser. Open ${r.url} yourself.`)),w("Run `flisk open` again to open the next frontend."),r.url}var re=new R("open").description("Open the first frontend of the project in your browser").action(async()=>{await _()});export{J as a,$ as b,E as c,V as d,j as e,H as f,A as g,te as h,_ as i,re as j};