@flisk-sh/flisk 1.3.192 → 1.3.198

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 (37) hide show
  1. package/CHANGELOG.md +1 -1
  2. package/README.md +4 -4
  3. package/cli/dist/cli.js +33 -9
  4. package/cli/dist/commands/help.js +1 -0
  5. package/cli/dist/commands/mcp.js +4 -1
  6. package/cli/dist/commands/open.js +104 -0
  7. package/cli/dist/commands/registry.js +2 -0
  8. package/cli/dist/commands/ui.js +1 -1
  9. package/cli/dist/commands/upgrade.js +2 -3
  10. package/cli/dist/mcp/tools.js +5 -2
  11. package/cli/dist/utils/cli-command.js +11 -2
  12. package/cli/dist/utils/doctor-fix.js +1 -1
  13. package/cli/dist/utils/one-command.js +66 -19
  14. package/cli/dist/utils/service-urls.js +6 -3
  15. package/cli/dist-bundle/chunk-CF46CD6R.js +6 -0
  16. package/cli/dist-bundle/chunk-DTIHDMED.js +5 -0
  17. package/cli/dist-bundle/chunk-DWHA5YKT.js +435 -0
  18. package/cli/dist-bundle/chunk-KBGQ4NJE.js +52 -0
  19. package/cli/dist-bundle/chunk-SB5WAMSU.js +5 -0
  20. package/cli/dist-bundle/chunk-US4D5GJJ.js +21 -0
  21. package/cli/dist-bundle/chunk-WPQOTHB5.js +4 -0
  22. package/cli/dist-bundle/{chunk-QR6O2A7L.js → chunk-YUARXGF4.js} +2 -2
  23. package/cli/dist-bundle/cli.js +251 -257
  24. package/cli/dist-bundle/cold-preflight-5TVSNLIV.js +2 -0
  25. package/cli/dist-bundle/one-command-TKXMWXCK.js +4 -0
  26. package/cli/dist-bundle/open-5SUD6LKB.js +2 -0
  27. package/cli/dist-bundle/project-5GTJYFAE.js +2 -0
  28. package/cli/dist-bundle/spinner-YLB6FYQH.js +2 -0
  29. package/cli/package.json +1 -1
  30. package/package.json +1 -1
  31. package/cli/dist-bundle/chunk-GOEBYLFN.js +0 -2
  32. package/cli/dist-bundle/chunk-RHSMS45X.js +0 -438
  33. package/cli/dist-bundle/chunk-XYFVXSEO.js +0 -75
  34. package/cli/dist-bundle/cold-preflight-ZJAU3E7K.js +0 -2
  35. package/cli/dist-bundle/one-command-A4R272U3.js +0 -4
  36. package/cli/dist-bundle/project-FOAR7E55.js +0 -2
  37. package/cli/dist-bundle/url-actions-D6ROTHZG.js +0 -2
@@ -1,438 +0,0 @@
1
- import{createRequire as __tdkRequire}from'node:module';const require=__tdkRequire(import.meta.url);
2
- import{Aa as Ut,Ba as Bt,Ca as je,H as X,P as S,Ra as b,Sa as Gt,b as P,d as T,e as de,f as U,fb as Ie,ga as I,h as Rt,i as _,ja as jt,jb as Vt,l as v,m as R,ma as It,n as Re,na as Ce,oa as le,p as Oe,pa as Ft,pb as Jt,qa as Z,r as Ot,t as h,u as Ct,ua as Ae,va as Ht,wa as ue,xa as Mt,y as $,ya as Lt,z as At}from"./chunk-XYFVXSEO.js";import{c as Wt}from"./chunk-42IVF3YT.js";import{execFileSync as Fn}from"node:child_process";import{readFileSync as zi}from"node:fs";import{join as Yi}from"node:path";import{execFileSync as ii,execSync as bn}from"node:child_process";import{existsSync as N,readdirSync as ai,readFileSync as q}from"node:fs";import{join as w,normalize as Pt,relative as bt}from"node:path";import{Command as ci}from"commander";import{existsSync as Gn}from"node:fs";var pe="docs/agent-hosts.md",Fe=`WebContainers cannot run Flisk: there is no Docker daemon or Tilt. Run \`flisk up\` on a machine with Docker. See ${pe}.`,Kt=`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 ${pe}.`;function Wn(){return{env:process.env,versions:process.versions,platform:process.platform,fileExists:Gn}}function qt(e=Wn()){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 zt(e){return e==="devcontainer"||e==="codespaces"}function fe(e){return e.some(t=>I(t.config?.appType)||t.config?.appType==="frontend"||t.config?.appType==="worker")}import{existsSync as Vn,readFileSync as Jn}from"node:fs";import{join as Kn,relative as Yt,resolve as Xt,sep as qn}from"node:path";var zn=2,Zt=["services/*/*"];function Qt(e){return e.split(qn).filter(Boolean)}function Yn(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 Xn(e,t){return e.length===t.length&&e.every((s,n)=>Yn(s,t[n]))}function He(e){let t=Kn(e,".tdk",v);if(!Vn(t))return Zt;try{let s=JSON.parse(Jn(t,"utf-8"))?.discovery?.paths;if(Array.isArray(s)&&s.every(n=>typeof n=="string"))return s}catch{}return Zt}function me(e,t,s){let n=Qt(Yt(e,Xt(e,t)));return s.some(r=>{let o=Qt(Yt(e,Xt(e,r)));for(let i=0;i<=zn;i++){let a=n.length-i;if(a>0&&Xn(o,n.slice(0,a)))return!0}return!1})}function la(e,t,s,n){let r=He(e);if(me(e,t,r))return{path:t};let o=`services/${s}/${n}`;return me(e,o,r)?{path:o,adjustedFrom:t}:{path:t}}import{execFile as mr}from"node:child_process";import{promisify as hr}from"node:util";import{execFileSync as is,execSync as te}from"node:child_process";import{existsSync as Me,readdirSync as Zn,readFileSync as Le}from"node:fs";import{join as W}from"node:path";function es(e,t){return e==="pending"||e==="in_progress"||e==="none"||t==="pending"||t==="none"}var ts="container is running, but its health check is failing";function ss(e){let t=e?.runtimeStatus??"";if(t!=="ok")return t;let s=e?.composeResourceInfo?.healthStatus;return s==="unhealthy"?"error":s==="starting"?"pending":t}var Q=1e4,ns=3e3,Qn="http://localhost:4873";function as(e){return`'${e.replace(/'/g,"'\\''")}'`}function ee(e,t,s,n,r){return process.platform==="win32"?is($(t)??t,s,{...r,windowsHide:!0}):e(n,r)}var er=[80,443];function Ue(e){return e.replace(/-/g,"_")}function tr(e,t){let s=new Set(t),n=[];for(let r of e.split(`
3
- `)){let o=r.trim();if(!o)continue;let i=o.indexOf(" "),a=i>=0?o.slice(0,i):o,d=i>=0?o.slice(i+1):"",c=[];for(let l of s)d.split(/[\s,]+/).some(f=>f.startsWith(`${l}->`)||f.includes(`:${l}->`))&&c.push(l);c.length>0&&n.push({name:a,ports:d,publishedPorts:c})}return n}function cs(e,t){let s=e.toLowerCase(),n=t.toLowerCase();return s===`${n}_traefik`||s.startsWith(`${n}_traefik`)}function sr(e,t){return e.filter(s=>!cs(s.name,t))}function Be(e){try{let t=e??Gt();return new Set(t.filter(s=>s.config?.sablier?.enable&&s.config?.sablier?.deferStart).map(s=>s.name))}catch{return new Set}}function Ge(e,t=new Set){let n=JSON.parse(e).items??[],r=[],o=0,i=0,a=0;for(let d of n){let c=d.metadata?.name??"unknown",l=d.status?.updateStatus??"",u=ss(d.status),f=u==="error"&&d.status?.runtimeStatus==="ok",y=(d.status?.buildHistory?.[0]?.error??"").trim()||(f?ts:"");if(l==="error"||u==="error"){r.push({name:c,updateStatus:l,runtimeStatus:u,error:y.replace(/\s+/g," ").slice(0,800)});continue}if(l==="ok"&&(u==="ok"||u==="not_applicable")){a+=1;continue}c!=="(Tiltfile)"&&es(l,u)&&(t.has(c)?i+=1:o+=1)}return{failures:r,pendingCount:o,deferredCount:i,okCount:a,total:n.length}}var nr=/failed to resolve source metadata for docker\.io\/library\/([A-Za-z0-9._-]+-l[1-4](?:-[a-z]+)*)(?::[^\s:]+)?:/i;function We(e){let t=e.replace(/\s+/g," ").trim(),s=t.match(/Bind for [^ ]+:(\d+) failed: port is already allocated/i);if(s)return`host port ${s[1]} is already allocated`;if(/port is already allocated/i.test(t))return"a required host port is already allocated";let n=[...t.matchAll(/ConnectionRefused downloading package manifest (@[A-Za-z0-9._/-]+)/gi)].map(a=>a[1]);if(n.length>0){let a=[...new Set(n)],d=a.slice(0,4).join(", "),c=a.length>4?` (+${a.length-4} more)`:"";return`private registry ConnectionRefused for ${d}${c} \u2014 Verdaccio (:4873) is down or unreachable from the build`}let r=t.match(nr);if(r)return`base image ${r[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,i=t.match(/\bup\s+-d\s+--no-build\s+([A-Za-z0-9._-]+)/i)?.[1];if(o||i||/docker compose .*\bup\s+-d\s+--no-build\b/i.test(t)){let a=o??`${i??"service"}:dev`,d=i?` for ${i}`:"";return`compose run failed because image is missing (${a})${d} \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 rs(e){return/ConnectionRefused downloading package manifest|Verdaccio|private registry|dependency install failed during ImageBuild|install-deps\.sh|bun install/i.test(e)}function Ve(e=h()??process.cwd()){let t=W(e,".tdk",v);if(!Me(t))return!1;try{let s=JSON.parse(Le(t,"utf-8"));return s.optional_infra?.verdaccio===!0||Object.values(s.phases??{}).some(n=>(n.enabledStacks??[]).includes("verdaccio"))}catch{return!1}}function ds(e){for(let t of[W(e,".npmrc"),W(e,R)])if(Me(t))try{let s=Le(t,"utf-8");if(/:4873\b/.test(s)||/verdaccio/i.test(s))return!0}catch{}return!1}function rr(e=h()??process.cwd()){return Ve(e)||ds(e)}function Je(e=te,t=h()??process.cwd(),s=process.env.VERDACCIO_URL??process.env.NPM_REGISTRY_URL??Qn,n=!0){if(!n&&!ds(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(!rr(t))return{name:"Private npm registry",didPass:!0,isSkipped:!0,message:"Private npm registry (Verdaccio) not enabled for this project - skipped"};let r=!1;try{let a=ee(e,"docker",["ps","--format","{{.Names}}"],"docker ps --format '{{.Names}}'",{stdio:"pipe",encoding:"utf-8",timeout:Q});r=/verdaccio/i.test(a)}catch{}let o=!1,i="";try{let a=process.platform==="win32"?is("curl.exe",["-fsS","-o","NUL","-w","%{http_code}","--max-time","2",s],{stdio:"pipe",encoding:"utf-8",timeout:ns+1e3,windowsHide:!0}).trim():e(`curl -fsS -o /dev/null -w '%{http_code}' --max-time 2 ${as(s)}`,{stdio:"pipe",encoding:"utf-8",timeout:ns+1e3}).trim();o=/^[23]\d\d$/.test(a),i=`HTTP ${a}`}catch(a){i=a instanceof Error?a.message.slice(0,120):"request failed"}return o?{name:"Private npm registry",didPass:!0,message:`Private npm registry reachable at ${s}${r?" (verdaccio container running)":""}`}:r?{name:"Private npm registry",didPass:!1,message:`Verdaccio container is running but ${s} is not responding (${i}). 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 ${s}. 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 Ke(e=te,t=Z(),s=er){let n=Ue(t),r="";try{r=ee(e,"docker",["ps","--format","{{.Names}}\\t{{.Ports}}"],"docker ps --format '{{.Names}}\\t{{.Ports}}'",{stdio:"pipe",encoding:"utf-8",timeout:Q})}catch{return{name:"Ingress Ports",didPass:!0,isSkipped:!0,message:"Docker not available - skipped ingress port check"}}let o=tr(r,s),i=sr(o,n);if(i.length===0){let d=o.filter(c=>cs(c.name,n));return d.length>0?{name:"Ingress Ports",didPass:!0,message:`Ingress ports ${s.join("/")} held by this project's Traefik (${d.map(c=>c.name).join(", ")})`}:{name:"Ingress Ports",didPass:!0,message:`Ingress ports ${s.join("/")} are free for Traefik`}}return{name:"Ingress Ports",didPass:!1,message:`Traefik cannot bind ingress ports because another container already owns them:
4
- ${i.map(d=>{let c=d.publishedPorts.join(", ");return`${d.name} (host ports ${c})`}).join(`
5
- `)}`,fix:`Stop the foreign container(s), e.g. \`docker stop ${i[0]?.name}\`, or shut down the other Flisk/Tilt project using that Traefik. Then re-run \`flisk up\`.`}}function or(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 qe(e){let t=e.filter(o=>o.status!==void 0),s=e.filter(o=>!o.ok);if(t.length===0)return{name:"Service Health",didPass:!0,isSkipped:!0,message:`No services responded - skipped ping of ${S(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(s.length===0)return{name:"Service Health",didPass:!0,message:`All ${S(e.length,"service")} responding on /health`};let n=s.map(o=>`${o.name} (${or(o)})
6
- ${o.url}`).join(`
7
- `),r=s.some(o=>o.status===404);return{name:"Service Health",didPass:!1,message:`${S(s.length,"service")} not healthy (${e.length-s.length}/${e.length} healthy):
8
- ${n}`,fix:r?"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 ze(e){if(e.length===0)return{name:"Service Smoke",didPass:!0,isSkipped:!0,message:"No read-only smoke checks declared"};let t=e.filter(n=>!n.ok);if(t.length===0)return{name:"Service Smoke",didPass:!0,message:`All ${S(e.length,"service")} pass their smoke checks`};let s=t.map(n=>n.failure??`${n.name}: failed`).join(`
9
- `);return{name:"Service Smoke",didPass:!1,message:`${S(t.length,"service")} failing a smoke check (${e.length-t.length}/${e.length} passing):
10
- ${s}`,fix:'Add the route the smoke step expects, or correct its "path" in the service.json "smoke" block. Then re-run flisk doctor.'}}function ls(e){let t=e.filter(r=>r.status!==void 0);if(t.length===0)return{name:"Advertised Endpoints",didPass:!0,isSkipped:!0,message:"No services responded - skipped advertised endpoint check"};let s=t.filter(r=>r.status===404);if(s.length===0)return{name:"Advertised Endpoints",didPass:!0,message:`${S(t.length,"advertised endpoint")} reachable`};let n=s.map(r=>`${r.name} (404)
11
- ${r.url}`).join(`
12
- `);return{name:"Advertised Endpoints",didPass:!0,isWarning:!0,message:`${S(s.length,"advertised link")} ${s.length===1?"returns":"return"} 404 (the service may be healthy, but nothing answers at this exact path):
13
- ${n}`,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 Ye(e=te){let t="";try{t=ee(e,"tilt",["get","uiresources","-o","json"],"tilt get uiresources -o json",{stdio:"pipe",encoding:"utf-8",timeout:Q})}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 s;try{s=Ge(t,Be())}catch{return{name:"Tilt Resources",didPass:!0,isSkipped:!0,message:"Could not parse Tilt resource status - skipped"}}if(s.total===0)return{name:"Tilt Resources",didPass:!0,isSkipped:!0,message:"No Tilt UIResources found"};if(s.failures.length===0){let p=s.deferredCount>0?`, ${s.deferredCount} deferred`:"";return{name:"Tilt Resources",didPass:!0,message:`Tilt resources healthy (${s.okCount} ok, ${s.pendingCount} pending${p})`}}let n=ar(s.failures),o=n.slice(0,20),i=n.length-o.length,a=o.map(p=>({failure:p,why:dr(p,e)})),d=a.map(({failure:p,why:L})=>`${p.name}: ${L}`).join(`
14
- `),c=i>0?`
15
- \u2026and ${S(i,"more failed resource")}`:"",l=s.pendingCount>0?`
16
- ${S(s.pendingCount,"resource")} still pending/not started \u2014 often blocked by the failures above.`:"",u=s.deferredCount>0?`
17
- ${S(s.deferredCount,"resource")} intentionally deferred (sablier.deferStart) \u2014 not started until first request, unrelated to the failures above.`:"",f=n.some(p=>/port is already allocated/i.test(p.error)),g=n.some(p=>rs(p.error)||rs(We(p.error))),y=a.some(({why:p})=>/Kafka broker unreachable|kafka:9092/i.test(p)),k="Open the Tilt UI URL printed by flisk up (default port "+Ot.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.":g?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.":y&&(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 ${S(s.failures.length,"failed resource")}:
18
- ${d}${c}${l}${u}`,fix:k}}var ir=/^(traefik|postgres|nats|infisical|verdaccio|proxy)([.-]|$)/i;function os(e){return ir.test(e)}function ar(e){return[...e].sort((t,s)=>{let n=os(t.name)?0:1,r=os(s.name)?0:1;return n!==r?n-r:t.name.localeCompare(s.name)})}function cr(e,t=te,s=Z()){try{let n=ee(t,"docker",["ps","-a","--format","{{.Names}}"],"docker ps -a --format '{{.Names}}'",{stdio:"pipe",encoding:"utf-8",timeout:Q}).split(`
19
- `).map(c=>c.trim()).filter(Boolean),r=`-autogenerated-${e}-1`,o=n.find(c=>c===e)??n.find(c=>c.startsWith(`${s}-`)&&c.endsWith(r))??n.find(c=>c.endsWith(r))??n.find(c=>c.includes(e));if(!o)return null;let i=ee(t,"docker",["logs","--tail","120",o],`docker logs --tail 120 ${as(o)} 2>&1`,{stdio:"pipe",encoding:"utf-8",timeout:Q});if(/getaddrinfo ENOTFOUND/i.test(i)&&/kafka:9092/i.test(i))return"runtime crash: Kafka broker unreachable (getaddrinfo ENOTFOUND kafka:9092)";if(/ECONNREFUSED/i.test(i)&&/kafka/i.test(i))return"runtime crash: Kafka connection refused";let a=i.match(/ConnectionRefused downloading package manifest (@[A-Za-z0-9._/-]+)/i);if(a?.[1])return`runtime/build log: private registry ConnectionRefused for ${a[1]}`;if(/ZodError/i.test(i)){let c=[...i.matchAll(/"path"\s*:\s*\[\s*"([^"]+)"\s*\]/g)].map(u=>u[1]),l=[...new Set(c)].slice(0,6);return l.length>0?`runtime crash: ZodError missing required config/env: ${l.join(", ")}`:"runtime crash: ZodError during config/env validation"}let d=i.match(/error:\s+Failed to [^:\n]+[^\n]{0,120}/i)?.[0]??i.match(/Failed to (?:start|initialize) [^\n]{0,120}/i)?.[0]??i.match(/^\s*error:\s+[^\n]{0,160}/im)?.[0];if(d)return`runtime crash: ${d.replace(/\s+/g," ").trim().slice(0,180)}`}catch{return null}return null}function dr(e,t=te){return e.error?We(e.error):e.runtimeStatus==="error"?cr(e.name,t)??"runtime error (container crashed or unhealthy \u2014 check Tilt/docker logs)":e.updateStatus||e.runtimeStatus||"unknown error"}var lr=/\.(ts|tsx|mts|js|mjs|cjs)$/,ur=new Set(["node_modules","dist",_,"tests","__tests__"]);function us(e){let t=[];for(let s of Zn(e,{withFileTypes:!0}))s.isDirectory()?ur.has(s.name)||t.push(...us(W(e,s.name))):lr.test(s.name)&&!/\.(test|spec)\./.test(s.name)&&t.push(W(e,s.name));return t}function pr(e){let t=e?.healthCheckPath||"/health";return{container:t,traefik:e?.traefik?.healthCheck||t}}function fr(e){let t=[];for(let s of e){if(!I(s.config?.appType))continue;let n=W(s.path,"src");if(!Me(n))continue;let r=us(n);if(r.length===0)continue;let o=r.map(c=>Le(c,"utf-8")),{container:i,traefik:a}=pr(s.config),d=i===a?[{path:i,usedBy:"container and Traefik healthchecks"}]:[{path:i,usedBy:"container healthcheck"},{path:a,usedBy:"Traefik healthcheck"}];for(let{path:c,usedBy:l}of d){let u=["'",'"',"`"].map(f=>`${f}${c}${f}`);o.some(f=>u.some(g=>f.includes(g)))||t.push({name:s.name,healthPath:c,usedBy:l})}}return t}function ps(e=h()??process.cwd()){let t=[];try{t=b(e)}catch{return{name:"Health Routes",didPass:!0,isSkipped:!0,message:"Could not read services - skipped health route check"}}let s=t.filter(o=>I(o.config?.appType));if(s.length===0)return{name:"Health Routes",didPass:!0,isSkipped:!0,message:"No backend services to check"};let n=fr(s);return n.length===0?{name:"Health Routes",didPass:!0,message:`All ${S(s.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):
20
- ${n.map(o=>`${o.name}: no "${o.healthPath}" route in src/ (probed by the ${o.usedBy})`).join(`
21
- `)}`,fix:`Add the route, e.g. for Hono: app.get("${n[0]?.healthPath}", (c) => c.json({ status: "ok" })). To use a different path, set "healthCheckPath" (container healthcheck) or "traefik.healthCheck" (Traefik) in its service.json.`}}var gr=hr(mr),kr=1e4,yr=5,fs=10*6e4,Sr=3,Pr=200,br=async e=>{let{stdout:t,stderr:s}=await gr("docker",e,{encoding:"utf-8",timeout:kr,windowsHide:!0});return`${t}${s}`};function wr(e,t){let s=Ue(t).toLowerCase(),n=e.replace(/-/g,"_").toLowerCase();return n===s||n.startsWith(`${s}_`)}function xr(e,t=Date.now()){if(e.status==="restarting")return!0;if(e.restartCount<yr)return!1;if(e.status==="running"){let n=Date.parse(e.startedAt);return Number.isNaN(n)||t-n<fs}let s=Date.parse(e.finishedAt??"");return e.exitCode!==0&&!Number.isNaN(s)&&t-s<fs}function Tr(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 vr(e){let t=[];for(let s of e.split(/\r?\n/)){let[n,r,o,i,a,d]=s.split(" ");!n||r===void 0||t.push({name:n.replace(/^\//,""),restartCount:Number(r)||0,status:o??"",startedAt:i??"",exitCode:Number(a)||0,finishedAt:d??""})}return t}async function ms(e,t=[],s=br,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(u=>u.split(" ")).filter(([u,f])=>u&&f&&wr(f,e)).map(([u])=>u)}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=vr(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(l=>xr(l,n));if(a.length===0)return{name:r,didPass:!0,message:"No project container is crash-looping"};let d=[],c=new Set;for(let l of a){let u="";try{u=await s(["logs","--tail",String(Sr),l.name])}catch{}let f=le(u,t).split(/\r?\n/).map(y=>y.trim().slice(0,Pr)).filter(Boolean),g=Tr(u,l);g&&c.add(g),d.push([`${l.name}: ${l.status}, restarted ${l.restartCount} times`,...f.map(y=>` | ${y}`)].join(`
22
- `))}return{name:r,didPass:!1,message:`${a.length} container${a.length===1?" is":"s are"} crash-looping:
23
- ${d.join(`
24
- `)}`,fix:[...c,"Read the full log: docker logs <container>"].join("; ")}}import{execFile as Fr}from"node:child_process";import{realpathSync as Ps,statfsSync as Hr}from"node:fs";import{homedir as Mr}from"node:os";import{join as Lr}from"node:path";import{promisify as Ur}from"node:util";import{statfsSync as $r}from"node:fs";import{homedir as Er}from"node:os";var he="Disk Space",Nr=1024**3,Dr=2,Xe=10,hs=["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(`
25
- `);function gs(e=$r,t=Er()){let s;try{let r=e(t);s=Number(r.bavail)*Number(r.bsize)/Nr}catch{return{name:he,didPass:!0,isSkipped:!0,message:"Could not read free disk space"}}let n=`${s.toFixed(1)} GB free`;return s<Dr?{name:he,didPass:!1,message:`${n}: Docker cannot build or start containers`,fix:hs}:s<Xe?{name:he,didPass:!1,isWarning:!0,message:`${n}: image builds may fail`,fix:hs}:{name:he,didPass:!0,message:n}}var _r="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 ks(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:_r}}import{execFileSync as Rr}from"node:child_process";var Ze=(e,t)=>Rr(e,t,{encoding:"utf-8",stdio:"pipe",windowsHide:!0}),ys=["traefik-public","traefik-private","backend","database","infisical-network","verdaccio-network","proxy"];function Qe(e){let t=e.replace(/-/g,"_");return ys.map(s=>`${t}_${s}`)}function Ss(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 et(e,t){for(let s of ys)if(e.endsWith(`_${s}`)){let n=e.slice(0,-(s.length+1));if(t.has(n))return n}return null}function Aa(e,t=Ze){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 Qe(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 ge(e,t=process.platform,s=Ze){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]??"",d=(a.split(/\s+/)[0]??"").split("/").at(-1),c=` -f ${e}`,l=a.indexOf(c),u=a[l+c.length];d==="tilt"&&/^\S+\s+up\s/.test(a)&&l>0&&(u===void 0||u===" ")&&r.push(Number(i[1]))}return r}function ja(e,t=process.platform,s=Ze){let n=ge(e,t,s);for(let r of n)try{s("kill",["-TERM",String(r)])}catch{}return n}async function Ia(e,t=8e3,s=ge){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 Or}from"node:child_process";function tt(e){return new Promise(t=>{Or($("tilt")??"tilt",["get","uiresources","-o","json","--port",String(e)],{timeout:15e3,maxBuffer:16*1024*1024},(s,n)=>t(s?null:n))})}function Cr(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 Ar(e){return(JSON.parse(e).items??[]).filter(t=>t.status?.disableStatus?.state!=="Disabled").flatMap(t=>t.metadata?.name?[t.metadata.name]:[])}function jr(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 Ir(e,t,s){let n=Ge(Cr(e),t),r={ready:n.failures.length===0&&n.pendingCount===0&&n.okCount>0,failures:n.failures.map(o=>({name:o.name,message:o.error||`${o.updateStatus}/${o.runtimeStatus}`})),pending:n.pendingCount,timedOut:!1,enabled:Ar(e)};if(s&&s.length>0){let{missing:o,disabled:i}=jr(e,s);if(o.length>0&&(r={...r,ready:!1,pending:r.pending+o.length}),i.length>0)return{settled:!0,result:{...r,ready:!1,failures:[...r.failures,...i.map(a=>({name:a,message:"disabled in Tilt"}))]}}}return{result:r,settled:r.ready||r.failures.length>0&&r.pending===0}}async function Ua(e,t={}){let s=t.timeoutMs??Number(process.env.TDK_UP_READY_TIMEOUT_MS??9e5),n=t.intervalMs??2e3,r=t.fetchJson??tt,o=t.deferred??Be(),i=Date.now()+s,a={ready:!1,failures:[],pending:0,timedOut:!1,enabled:[]};for(;;){let d=await r(e);if(d)try{let c=Ir(d,o,t.expected);if(a=c.result,c.settled||a.failures.length>0&&t.isStalled?.(d))return a}catch{}if(Date.now()>=i)return{...a,ready:!1,timedOut:!0};await new Promise(c=>setTimeout(c,n))}}var ke=Ur(Fr),Br=15e3,Gr=/^tdk_doctor_probe_(\d+)$/,Wr=async e=>{let{stdout:t}=await ke("docker",e,{encoding:"utf-8",timeout:Br,windowsHide:!0});return t};function st(e){return String(e.stderr??e).trim().split(/\r?\n/)[0]??""}var Vr=120;function Jr(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 Kr(e,t=tt,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 qr(e){if(process.platform==="win32")return"unknown";try{let{stdout:t}=await ke("ps",["-p",String(e),"-o","etime="],{encoding:"utf-8",timeout:5e3}),s=Jr(t);if(s===null||s<Vr)return"unknown";let{stdout:n}=await ke("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 Kr(r)?"healthy":"stale"}catch{return"unknown"}}function zr(e=Wr){return{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(st(s))}},freeDiskGib(){try{let t=Hr(Mr());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(st(s))}},async tiltStatus(t){return qr(t)},stopProcess(t){process.kill(t,"SIGTERM")},isProcessAlive(t){try{return process.kill(t,0),!0}catch(s){return s.code==="EPERM"}}}}var bs=zr();async function ws(e,t=bs,s={}){let n=[],r=[];for(let l of s.tiltPids??[])await t.tiltStatus(l)==="stale"?n.push({id:`stop-tilt:${l}`,check:"Tilt processes",scope:"project",command:`kill -TERM ${l}`,status:"planned",reason:"this project's Tilt is running but its UI does not answer"}):r.push(l);let o=r.length>0?`Tilt is running for this project (pid ${r.join(", ")}); run flisk down first`:void 0,i=await t.listNetworks(),a=t.freeDiskGib();if(a!==null&&a<Xe){let{buildCache:l,danglingImages:u}=await t.reclaimable(),f=`${a.toFixed(1)} GB free`;l&&!/^0(\.0+)?\s*B$/i.test(l)&&n.push({id:"prune:builder",check:"Disk Space",scope:"host",command:"docker builder prune -f",status:"planned",reason:`${f}; ${l} of build cache reclaimable`}),u>0&&n.push({id:"prune:images",check:"Disk Space",scope:"host",command:"docker image prune -f",status:"planned",reason:`${f}; ${u} untagged image${u===1?"":"s"}`})}let d=new Set(e?Qe(e):[]),c=Ss(i.map(l=>l.name));for(let l of i){let u=Gr.exec(l.name),f,g,y="unused network";if(u)f="probe",g="Orphaned probe networks";else if(d.has(l.name))f="project",g="Docker networks";else if(s.machine&&et(l.name,c))f="machine",g="Docker networks",y=`unused network of project "${et(l.name,c)}"`;else continue;let k={id:`remove-network:${l.name}`,check:g,scope:f,command:`docker network rm ${l.name}`,status:"planned",reason:y};l.containers>0?(k.status="skipped",k.reason=`${l.containers} container(s) still attached`):f==="project"&&o?(k.status="skipped",k.reason=o):u&&t.isProcessAlive(Number(u[1]))&&(k.status="skipped",k.reason=`probe of a running process (pid ${u[1]})`),n.push(k)}return n}async function xs(e,t,s=bs){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("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:st(i)})}}return n}function Ts(e){return e.some(t=>t.status==="failed")}async function Yr(e){try{let{stdout:t}=await ke(e,["--version"],{encoding:"utf-8",timeout:5e3,windowsHide:!0});return t.trim().split(/\r?\n/)[0]||null}catch{return null}}async function Xr(e=At("flisk"),t=Yr){let s=new Set,n=[];for(let r of e){let o=r;try{o=Ps(r)}catch{}s.has(o)||(s.add(o),n.push({path:r,version:await t(r)}))}return n}async function vs(e){let t=e??await Xr();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/tdk directly may use another"}}function $s(e,t=ge){let s=new Set([e]);try{s.add(Ps(e))}catch{}let n=new Set;for(let r of s)for(let o of t(Lr(r,".tdk",".tdk-out","Tiltfile")))n.add(o);return[...n]}var nt=1;function Zr(e,t=[]){return{schemaVersion:nt,data:e,errors:t}}function Qr(e){return e instanceof X?{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 ec(e){let t=Qr(e);console.log(JSON.stringify(Zr(null,[t.error]))),console.error(t.error.message),process.exit(t.exitCode)}async function Ns(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===T);return t?t.didPass:null}function H(e,t,s=[],n,r){return{schemaVersion:nt,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 Ds(e){return e.errors.length>0?2:e.data.ready?0:1}import{existsSync as ot,readFileSync as _s}from"node:fs";import{dirname as eo,join as rt,normalize as to}from"node:path";function so(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"?rt(s,".tdk",".tdk-out","tdk-cli-ext","Tiltfile"):t.startsWith(".")||!t.includes("://")&&!t.startsWith("@")?to(rt(eo(e),t)):null}function no(e,t,s){let n=[],r=/^load\s*\(([\s\S]*?)\)/gm;for(let o of t.matchAll(r)){let d=(o[1]??"").match(/["']([^"']+)["']/)?.[1];if(!d)continue;let c=Rs(e,d,s);c&&(ot(c)||n.push(`${e}: ${d} -> ${c}`))}return n}function ro(e,t,s){let n=[],r=/^load\s*\(([\s\S]*?)\)/gm;for(let o of t.matchAll(r)){let d=(o[1]??"").match(/["']([^"']+)["']/)?.[1];if(d){let c=Rs(e,d,s);c&&n.push(c)}}return n}function oo(e,t){let s=new Set,n=[e];for(;n.length>0;){let r=n.pop();if(!r||s.has(r)||!ot(r))continue;s.add(r);let o=_s(r,"utf-8");for(let i of ro(r,o,t))s.has(i)||n.push(i)}return Array.from(s).sort()}function Os(){let e=h()??process.cwd(),t=rt(e,".tdk",".tdk-out","Tiltfile");if(!ot(t))return{name:"Starlark Load Exports",didPass:!0,isSkipped:!0,message:"No generated Tiltfile to check"};let s=[],n=[],r=oo(t,e);for(let i of r){let a=_s(i,"utf-8"),d=so(a);d.length>0&&s.push(`${i}: ${d.join(", ")}`);for(let c of no(i,a,e))n.push(c)}if(s.length===0&&n.length===0)return{name:"Starlark Load Exports",didPass:!0,message:`${S(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:
26
- ${s.join(`
27
- `)}`),n.length>0&&o.push(`Missing relative load targets:
28
- ${n.join(`
29
- `)}`),{name:"Starlark Load Exports",didPass:!1,message:`Starlark load() issues will stop Tilt before services start:
30
- ${o.join(`
31
-
32
- `)}`,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{execFileSync as bo,execSync as wo}from"node:child_process";import{existsSync as ct,readdirSync as zs,readFileSync as ne}from"node:fs";import{basename as xo,dirname as To,join as E,relative as se}from"node:path";function lc(e){return Cs(e,!1)}function uc(e){return Cs(e,!0)}function Cs(e,t){return`import { Hono } from 'hono';
33
- ${t?`import { sql } from 'drizzle-orm';
34
- import { db } from './db.js';
35
- `:""}
36
- const app = new Hono();
37
-
38
- // Health check endpoint (required by TILT_RESOURCE_DEFAULTS.star)
39
- app.get('/health', (c) => {
40
- return c.json({ status: 'ok', service: '${e}' });
41
- });
42
-
43
- app.get('/health/live', (c) => {
44
- return c.json({ status: 'alive', timestamp: Date.now() });
45
- });
46
-
47
- app.get('/health/ready', async (c) => {
48
- const dependencies: Record<string, string> = {};
49
- let allReady = true;
50
-
51
- // Add dependency checks here (database, cache, etc.)
52
- // Mark allReady = false if any dependency is unhealthy
53
-
54
- const status = allReady ? 'ready' : 'not_ready';
55
- return c.json({ status, dependencies }, allReady ? 200 : 503);
56
- });
57
-
58
- ${t?`// Database check: runs a trivial query through the Drizzle client (src/db.ts).
59
- app.get('/health/db', async (c) => {
60
- try {
61
- await db.execute(sql\`select 1\`);
62
- return c.json({ status: 'ok', database: 'up' });
63
- } catch (error) {
64
- console.error('Database health check failed:', error);
65
- return c.json({ status: 'error', database: 'down' }, 503);
66
- }
67
- });
68
-
69
- `:""}app.get('/', (c) => {
70
- return c.json({
71
- service: '${e}',
72
- version: '1.0.0',
73
- endpoints: ['/health', '/health/live', '/health/ready'${t?", '/health/db'":""}]
74
- });
75
- });
76
-
77
- const port = process.env.PORT || 3000;
78
- console.log('\\n\u{1F680} ${e} running on http://localhost:' + port);
79
- console.log('\u{1F4CA} Health check: http://localhost:' + port + '/health\\n');
80
-
81
- export default {
82
- port,
83
- fetch: app.fetch,
84
- };
85
- `}var As={id:"bun",label:"Bun + Hono",installHint:"bun install"};var io="go run .",js={id:"go",label:"Go 1.23 (net/http)",devCommand:io,watch:["**/*.go","go.mod","go.sum"],installHint:"go mod tidy # optional: Docker builds the image for you",createFiles(e){return[{filename:"go.mod",content:`module ${e}
86
-
87
- go 1.23
88
- `,description:"Generating go.mod",emoji:"\u{1F4E6}"},{filename:"main.go",content:`package main
89
-
90
- import (
91
- "encoding/json"
92
- "log"
93
- "net/http"
94
- "os"
95
- )
96
-
97
- func writeJSON(w http.ResponseWriter, status int, body any) {
98
- w.Header().Set("Content-Type", "application/json")
99
- w.WriteHeader(status)
100
- _ = json.NewEncoder(w).Encode(body)
101
- }
102
-
103
- func newMux() *http.ServeMux {
104
- mux := http.NewServeMux()
105
-
106
- // Health check endpoint (required by TILT_RESOURCE_DEFAULTS.star)
107
- mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {
108
- writeJSON(w, http.StatusOK, map[string]string{"status": "ok", "service": "${e}"})
109
- })
110
-
111
- mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
112
- writeJSON(w, http.StatusOK, map[string]any{
113
- "service": "${e}",
114
- "version": "1.0.0",
115
- "endpoints": []string{"/health"},
116
- })
117
- })
118
-
119
- return mux
120
- }
121
-
122
- func main() {
123
- port := os.Getenv("PORT")
124
- if port == "" {
125
- port = "3000"
126
- }
127
-
128
- // ":" + port listens on every interface, which Traefik needs inside the container network.
129
- log.Printf("${e} listening on :%s", port)
130
- log.Fatal(http.ListenAndServe(":"+port, newMux()))
131
- }
132
- `,description:"Generating backend source",emoji:"\u{1F4BB}"},{filename:"main_test.go",content:`package main
133
-
134
- import (
135
- "encoding/json"
136
- "net/http"
137
- "net/http/httptest"
138
- "testing"
139
- )
140
-
141
- func TestHealth(t *testing.T) {
142
- rec := httptest.NewRecorder()
143
- newMux().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/health", nil))
144
-
145
- if rec.Code != http.StatusOK {
146
- t.Fatalf("GET /health = %d, want %d", rec.Code, http.StatusOK)
147
- }
148
- }
149
-
150
- func TestRoot(t *testing.T) {
151
- rec := httptest.NewRecorder()
152
- newMux().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
153
-
154
- if rec.Code != http.StatusOK {
155
- t.Fatalf("GET / = %d, want %d", rec.Code, http.StatusOK)
156
- }
157
- if got := rec.Header().Get("Content-Type"); got != "application/json" {
158
- t.Fatalf("GET / Content-Type = %q, want %q", got, "application/json")
159
- }
160
-
161
- var body map[string]any
162
- if err := json.NewDecoder(rec.Body).Decode(&body); err != nil {
163
- t.Fatalf("GET / body is not JSON: %v", err)
164
- }
165
- if body["service"] != "${e}" {
166
- t.Errorf("service = %v, want %q", body["service"], "${e}")
167
- }
168
- if body["version"] != "1.0.0" {
169
- t.Errorf("version = %v, want %q", body["version"], "1.0.0")
170
- }
171
- endpoints, ok := body["endpoints"].([]any)
172
- if !ok || len(endpoints) != 1 || endpoints[0] != "/health" {
173
- t.Errorf("endpoints = %v, want [/health]", body["endpoints"])
174
- }
175
- }
176
- `,description:"Generating smoke test",emoji:"\u{1F9EA}"}]}};var ao="node --watch src/index.js",Is={id:"node",label:"Node.js 22",devCommand:ao,watch:["src/**/*"],installHint:"npm install # optional: Docker builds the image for you",createFiles(e){return[{filename:"package.json",content:`{
177
- "name": "${e}",
178
- "version": "1.0.0",
179
- "type": "module",
180
- "scripts": {
181
- "dev": "node --watch src/index.js",
182
- "start": "node src/index.js",
183
- "test": "node --test"
184
- }
185
- }
186
- `,description:"Generating package.json",emoji:"\u{1F4E6}"},{filename:"package-lock.json",content:`{
187
- "name": "${e}",
188
- "version": "1.0.0",
189
- "lockfileVersion": 3,
190
- "requires": true,
191
- "packages": {
192
- "": {
193
- "name": "${e}",
194
- "version": "1.0.0"
195
- }
196
- }
197
- }
198
- `,description:"Generating package-lock.json",emoji:"\u{1F512}"},{filename:"src/index.js",content:`import http from "node:http";
199
-
200
- const name = "${e}";
201
- const port = Number(process.env.PORT) || 3000;
202
-
203
- function sendJson(res, status, data) {
204
- res.writeHead(status, { "Content-Type": "application/json" });
205
- res.end(JSON.stringify(data));
206
- }
207
-
208
- export const server = http.createServer((req, res) => {
209
- const url = new URL(req.url, \`http://\${req.headers.host || "localhost"}\`);
210
-
211
- // Health check endpoint (required by TILT_RESOURCE_DEFAULTS.star)
212
- if (req.method === "GET" && url.pathname === "/health") {
213
- return sendJson(res, 200, { status: "ok", service: name });
214
- }
215
-
216
- if (req.method === "GET" && url.pathname === "/") {
217
- return sendJson(res, 200, {
218
- service: name,
219
- version: "1.0.0",
220
- endpoints: ["/health"],
221
- });
222
- }
223
-
224
- return sendJson(res, 404, { error: "Not Found" });
225
- });
226
-
227
- if (process.env.NODE_ENV !== "test") {
228
- // "0.0.0.0" listens on every interface, which Traefik needs inside the container network.
229
- server.listen(port, "0.0.0.0", () => {
230
- console.log(\`\\n\u{1F680} \${name} running on http://localhost:\${port}\`);
231
- console.log(\`\u{1F4CA} Health check: http://localhost:\${port}/health\\n\`);
232
- });
233
- }
234
- `,description:"Generating backend source",emoji:"\u{1F4BB}"},{filename:"tests/health.test.js",content:`import assert from "node:assert/strict";
235
- import { after, before, describe, it } from "node:test";
236
- import { server } from "../src/index.js";
237
-
238
- describe("health check", () => {
239
- let baseUrl;
240
-
241
- before((_, done) => {
242
- server.listen(0, "127.0.0.1", () => {
243
- const address = server.address();
244
- baseUrl = \`http://127.0.0.1:\${address.port}\`;
245
- done();
246
- });
247
- });
248
-
249
- after((_, done) => {
250
- server.close(done);
251
- });
252
-
253
- it("GET /health returns 200 with ok status", async () => {
254
- const res = await fetch(\`\${baseUrl}/health\`);
255
- assert.equal(res.status, 200);
256
- const body = await res.json();
257
- assert.deepEqual(body, { status: "ok", service: "${e}" });
258
- });
259
- });
260
- `,description:"Generating smoke test",emoji:"\u{1F9EA}"}]}};var co="uvicorn main:app --app-dir src --host 0.0.0.0 --port ${PORT:-4000} --reload --reload-dir src",Fs={id:"python",label:"Python 3.12 + FastAPI",devCommand:co,watch:["src/**/*"],installHint:'pip install -e ".[dev]" # optional: Docker builds the image for you',createFiles(e){return[{filename:"pyproject.toml",content:`[project]
261
- name = "${e}"
262
- version = "0.0.1"
263
- requires-python = ">=3.12"
264
- dependencies = [
265
- "fastapi==0.115.6",
266
- "uvicorn[standard]==0.34.0",
267
- ]
268
-
269
- [project.optional-dependencies]
270
- dev = [
271
- "pytest==9.0.3",
272
- "httpx==0.28.1",
273
- ]
274
-
275
- [build-system]
276
- requires = ["setuptools>=68"]
277
- build-backend = "setuptools.build_meta"
278
-
279
- # Only the dependencies are installed into the image; the source is synced for live reload.
280
- [tool.setuptools]
281
- py-modules = []
282
-
283
- [tool.pytest.ini_options]
284
- pythonpath = ["src"]
285
- testpaths = ["tests"]
286
- `,description:"Generating pyproject.toml",emoji:"\u{1F4E6}"},{filename:"src/main.py",content:`import os
287
-
288
- from fastapi import FastAPI
289
-
290
- app = FastAPI(title="${e}")
291
-
292
-
293
- @app.get("/health")
294
- def health() -> dict[str, str]:
295
- return {"status": "ok", "service": "${e}"}
296
-
297
-
298
- @app.get("/")
299
- def root() -> dict[str, object]:
300
- return {"service": "${e}", "version": "1.0.0", "endpoints": ["/health"]}
301
-
302
-
303
- if __name__ == "__main__":
304
- import uvicorn
305
-
306
- uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", "3000")))
307
- `,description:"Generating backend source",emoji:"\u{1F4BB}"},{filename:"tests/test_health.py",content:`from fastapi.testclient import TestClient
308
-
309
- from main import app
310
-
311
- client = TestClient(app)
312
-
313
-
314
- def test_health() -> None:
315
- response = client.get("/health")
316
- assert response.status_code == 200
317
- assert response.json() == {"status": "ok", "service": "${e}"}
318
-
319
-
320
- def test_root() -> None:
321
- response = client.get("/")
322
- assert response.status_code == 200
323
- assert response.json() == {"service": "${e}", "version": "1.0.0", "endpoints": ["/health"]}
324
- `,description:"Generating test file",emoji:"\u{1F9EA}"}]}};var lo="cargo run",Hs={id:"rust",label:"Rust (axum)",devCommand:lo,watch:["src/**/*.rs","Cargo.toml","Cargo.lock"],installHint:"cargo build # optional: Docker builds the image for you",createFiles(e){return[{filename:"Cargo.toml",content:`[package]
325
- name = "${e}"
326
- version = "0.1.0"
327
- edition = "2021"
328
-
329
- # The image copies the release binary by this fixed name.
330
- [[bin]]
331
- name = "app"
332
- path = "src/main.rs"
333
-
334
- [dependencies]
335
- axum = "0.8"
336
- serde_json = "1"
337
- tokio = { version = "1", features = ["macros", "rt-multi-thread", "net"] }
338
- `,description:"Generating Cargo.toml",emoji:"\u{1F4E6}"},{filename:"src/main.rs",content:`use axum::{routing::get, Json, Router};
339
- use serde_json::{json, Value};
340
-
341
- fn app() -> Router {
342
- Router::new()
343
- .route("/", get(root))
344
- // Health check endpoint (required by TILT_RESOURCE_DEFAULTS.star)
345
- .route("/health", get(health))
346
- }
347
-
348
- async fn root() -> Json<Value> {
349
- Json(json!({ "service": "${e}", "version": "1.0.0", "endpoints": ["/health"] }))
350
- }
351
-
352
- async fn health() -> Json<Value> {
353
- Json(json!({ "status": "ok", "service": "${e}" }))
354
- }
355
-
356
- #[tokio::main]
357
- async fn main() {
358
- let port = std::env::var("PORT").unwrap_or_else(|_| "3000".to_string());
359
-
360
- // 0.0.0.0 listens on every interface, which Traefik needs inside the container network.
361
- let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{port}"))
362
- .await
363
- .expect("failed to bind the port");
364
- println!("${e} listening on 0.0.0.0:{port}");
365
- axum::serve(listener, app()).await.expect("server error");
366
- }
367
-
368
- #[cfg(test)]
369
- mod tests {
370
- use super::*;
371
-
372
- #[tokio::test]
373
- async fn health_reports_ok() {
374
- let Json(body) = health().await;
375
- assert_eq!(body["status"], "ok");
376
- }
377
- }
378
- `,description:"Generating backend source and smoke test",emoji:"\u{1F4BB}"}]}};var Ms="bun",V={bun:As,python:Fs,go:js,rust:Hs,node:Is};function uo(e){let t=(e??Ms).trim().toLowerCase(),s=Object.hasOwn(V,t)?V[t]:void 0;if(!s){let n=Object.keys(V).join(", ");throw new X(`Unknown backend language "${e}". Supported languages: ${n}.`,[`Use one of: ${n}`,`Omit --language to use ${Ms}`])}return s}function xc(e,t){if(e!=="backend"){if(t!==void 0)throw new X("--language can only be used with --type backend.",["Add --type backend, or drop --language for this resource type"]);return}return uo(t)}import{exec as po,execFile as fo}from"node:child_process";import{promisify as Ls}from"node:util";var mo=Ls(po),O=async(e,t)=>{if(process.platform==="win32"){let n=e.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g)??[],[r,...o]=n.map(d=>d.startsWith('"')||d.startsWith("'")?d.slice(1,-1):d);if(!r)throw new Error("Command is empty");let i=$(r)??r,{stdout:a}=await Ls(fo)(i,o,{encoding:"utf-8",timeout:t,windowsHide:!0,shell:!1});return a}let{stdout:s}=await mo(e,{encoding:"utf-8",timeout:t});return s};function Us(e){let t=e;return t?.code==="ETIMEDOUT"||t?.killed===!0}import{existsSync as ho,readFileSync as Bs}from"node:fs";import{join as M}from"node:path";var Gs=["postgres",U],Ws=["pre_alpha","alpha","beta","out_of_scope"];function go(e){return Gs.includes(e)}function Vs(e){try{return JSON.parse(Bs(M(e,".tdk",v),"utf-8"))}catch{return}}function J(e){try{return ho(e)?Bs(e,"utf-8"):void 0}catch{return}}function Js(e,t){let s=r=>{let o=r;for(;o<e.length&&/\s/.test(e[o]);)o+=1;return o},n=0;for(;;){let r=e.indexOf(t,n);if(r===-1)return;let o=s(r+t.length);if(e[o]==="="&&(o=s(o+1),e[o]==="[")){let i=e.indexOf("]",o+1);return i===-1?void 0:[...e.slice(o+1,i).matchAll(/"([^"]+)"|'([^']+)'/g)].map(a=>a[1]??a[2]??"")}n=r+t.length}}function Ks(e){let t=M(e,".tdk",".tdk-out","Tiltfile"),s=J(t);if(s)return Js(s,"ALWAYS_ENABLED_INFRA")}function ko(e){let t=M(e,".tdk",".tdk-out","spec.master"),s=J(t);if(s!==void 0)return/"database-management"\s*:\s*True/.test(s)}function yo(e){let t=M(e,".tdk",".tdk-out"),s=J(M(t,"Tiltfile")),n=J(M(t,"spec.master")),r=J(M(t,"tdk-cli-ext","discovery","config.star")),o=J(M(t,"tdk-cli-ext","engine","topologies","tilt","config","profiles.star"));if(!s||!n||!r||!o)return!1;let i=n.match(/PRE_ALPHA_RESOURCES\s*=\s*\{([^}]*)\}/)?.[1],a=Js(r,"CORE_INFRA");return/FOCUS_MODE\s*,\s*FOCUS_ENABLED_ALL\s*,\s*FOCUS_ENABLED_RESOURCES\s*=\s*Config\.apply_focus\(cfg\)/.test(s)&&/if FOCUS_MODE and FOCUS_ENABLED_ALL\s*:/.test(s)&&/"[^"]+"\s*:\s*True|'[^']+'\s*:\s*True/.test(i??"")&&(a?.includes("postgres")??!1)&&/["']postgres["']\s*:\s*["']database-management["']/.test(r)&&/for infra in CORE_INFRA_EXPORT\s*:/.test(o)&&/needed\[INFRA_STACK_MAP_EXPORT\[infra\]\]\s*=\s*True/.test(o)}function So(e){let t=Vs(e);if(!t)return!1;let s=t.phases??{};for(let r of Ws){let o=s[r]?.enabledStacks;if(Array.isArray(o)&&o.includes(U))return!0}let n=t.always_enabled_infra??Ie;return Array.isArray(n)&&n.includes(U)}function Po(e,t){let s=new Set;for(let o of Gs)s.add(o);for(let o of t)s.add(o.name),o.stack&&s.add(o.stack);let n=Vs(e);if(n){let o=n.phases??{};for(let a of Ws){let d=o[a]?.enabledStacks;if(Array.isArray(d))for(let c of d)s.add(c)}let i=n.always_enabled_infra??Ie;if(Array.isArray(i))for(let a of i)s.add(a)}let r=Ks(e);if(Array.isArray(r))for(let o of r)s.add(o);return s}function it(e,t=b(e)){let s=So(e),n=Ks(e),r=Array.isArray(n)&&n.includes(U),o=ko(e)===!0,i=s||r||o,a=!s&&yo(e),d=Po(e,t),c=[],l=[];for(let g of t){let y=g.config?.dependsOn??[],k=!1;for(let p of y){if(go(p)){k=!0;continue}d.has(p)||l.push({resource:g.name,name:p})}k&&c.push(g.name)}let u=i||c.length>0,f=i?"feature":c.length>0?"dependsOn":"none";return{featureOn:i,featureOnFromProjectJson:s,featureOnFromTiltfile:r,featureOnFromSpecMaster:o,focusWouldEnableDatabaseManagement:a,dependsOnUsers:c,willStart:u,reason:f,unknownDependsOnNames:l}}var Se=1e4,vo=/\.(?:[cm]?[jt]sx?|vue)$/,$o=/(?:\.test\.|\.spec\.|\/tests?\/|\/__tests__\/)/,Eo=7,No=new Set(["node_modules",_,"dist","tests","__tests__"]);function Ys(e){try{let t=JSON.parse(ne(E(e,".tdk",v),"utf-8"));return typeof t?.project?.name=="string"?t.project.name:void 0}catch{return}}function Do(e){try{let t=JSON.parse(ne(e,"utf-8")).params;return t&&typeof t=="object"?t:{}}catch{return{}}}function at(e){try{let t=JSON.parse(ne(E(e,R),"utf-8"));return t&&typeof t=="object"?t:{}}catch{return{}}}function qs(e){if(typeof e!="string")return;let t=e.match(/(?:^|[^0-9])(\d+)(?:\.|$)/);return t?Number(t[1]):void 0}function _o(e){let t=be(e);if(t===void 0)return["missing prisma/schema.prisma"];let s=t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/^\s*\/\/.*$/gm,""),n=[],r=s.match(/datasource\s+\w+\s*\{([^}]*)\}/)?.[1]??"";return/provider\s*=\s*["']postgresql["']/.test(r)||n.push("schema provider is not postgresql"),/\b(?:url|directUrl)\s*=/.test(s)&&n.push("schema still declares url/directUrl"),n}function Ro(e){let t=E(e,_,"prisma.config.autogenerated.ts"),n=[E(e,"prisma.config.ts"),t].find(i=>ct(i));if(!n)return["missing prisma.config.ts or generated Prisma config"];let o=(be(n)??"").match(/datasource\s*:\s*\{([^}]*)\}/)?.[1]??"";return/url\s*:\s*(?:env\(["']DATABASE_URL["']\)|process\.env\.DATABASE_URL)\s*,?/.test(o)?[]:['Prisma config datasource.url is not env("DATABASE_URL")']}function Xs(e=h()??process.cwd(),t=b(e)){let s=t.filter(o=>o.config?.featuresEnabled?.includes("prisma")),n=[],r=t.filter(o=>o.config?.appType==="migrator");for(let o of t){let i=o.config?.features;Array.isArray(i)&&i.includes("prisma")&&!o.config?.featuresEnabled?.includes("prisma")&&n.push(`${o.name}: use featuresEnabled, not features, for Prisma`)}if(s.length===0)return n.length===0?{name:"Prisma 7 consistency",didPass:!0,isSkipped:!0,message:"No resources enable Prisma; Prisma consistency checks were skipped"}:{name:"Prisma 7 consistency",didPass:!1,message:`${S(n.length,"Prisma consistency error")}:
379
- ${n.join(`
380
- `)}`,fix:"Use featuresEnabled to opt into the validated Prisma 7 shape"};for(let o of s){let i=at(o.path).dependencies,d={...at(o.path).devDependencies??{},...i??{}},c=qs(d.prisma),l=qs(d["@prisma/client"]);if(c===void 0||l===void 0?n.push(`${o.name}: prisma and @prisma/client are required`):(c!==l||c!==Eo)&&n.push(`${o.name}: prisma packages must both be major 7`),n.push(..._o(E(o.path,"prisma","schema.prisma")).map(f=>`${o.name}: ${f}`)),n.push(...Ro(o.path).map(f=>`${o.name}: ${f}`)),(o.config?.appType??o.type)==="migrator")o.config?.dependsOn?.some(g=>g==="postgres"||g===U)||n.push(`${o.name}: migrator must depend on postgres or database-management`);else{o.config?.dependsOn?.some(k=>r.some(p=>p.name===k))||n.push(`${o.name}: API must depend on its Prisma migrator, which depends on postgres or database-management`);let g=at(o.path).scripts;Object.entries(g??{}).some(([k,p])=>an.has(k)&&typeof p=="string"&&/prisma\s+migrate/.test(p))&&n.push(`${o.name}: API start script must not run prisma migrate`);let y=E(o.path,o.config?.dockerfile??"Dockerfile");ye(y,!0)&&n.push(`${o.name}: API image/startup must not run Prisma migrations`)}}return s.length>0&&!it(e,t).willStart&&n.push("shared platform Postgres will not start for the Prisma resources"),n.length===0?{name:"Prisma 7 consistency",didPass:!0,message:"Prisma resources use the validated Prisma 7 shape"}:{name:"Prisma 7 consistency",didPass:!1,message:`${S(n.length,"Prisma consistency error")}:
381
- ${n.join(`
382
- `)}`,fix:"Use Prisma 7 packages and config, put migrations in a migrator, and make the API depend on that migrator"}}function Zs(e){let t=new Map;for(let s of e){let n=s.config?.port;I(s.config?.appType)&&typeof n=="number"&&t.set(s.name,n)}return t}function Oo(e){let t=e.config?.language;return typeof t=="string"&&Object.hasOwn(V,t)&&V[t].createFiles!==void 0}function Co(e){return(e.config?.appType??e.type)===de}function Qs(e=h()??process.cwd()){let t=b(e).filter(s=>!Co(s)&&!Oo(s)&&!ct(E(s.path,R))).map(s=>s.name);return t.length===0?{name:"Resource package.json",didPass:!0,message:"Every resource has a package.json"}:{name:"Resource package.json",didPass:!1,message:`${S(t.length,"resource")} without a package.json: ${t.join(", ")}. The image build stops at "COPY .../package.json: not found"`,fix:"Add a package.json next to each service.json (copy one from a working resource), or delete the folder's service.json if it is not a service"}}function Pe(e=h()??process.cwd(),t=b(e)){let s=new Map;for(let o of t){let i=s.get(o.name)??[];i.push(se(e,o.configPath)||o.configPath),s.set(o.name,i)}let n=[...s].filter(([,o])=>o.length>1);if(n.length===0)return{name:"Duplicate resource names",didPass:!0,message:"Every resource has a unique appName"};let r=n.map(([o,i])=>`"${o}" in ${i.join(" and ")}`);return{name:"Duplicate resource names",didPass:!1,message:`${S(n.length,"appName")} used by more than one resource:
383
- ${r.join(`
384
- `)}`,fix:'Give each resource its own "appName" in its service.json. The name becomes the Compose service and the Traefik router, so two resources with one name collide'}}function Ao(e){let t=e.config?.appType;return I(t)?!0:t===de&&e.config?.exposeViaProxy!==!1}function en(e=h()??process.cwd()){let t=new Map;for(let r of b(e)){let o=r.config?.port;if(typeof o!="number"||!Ao(r))continue;let i=t.get(o)??[];i.push(r.name),t.set(o,i)}let s=[...t].filter(([,r])=>r.length>1);if(s.length===0)return{name:"Duplicate resource ports",didPass:!0,message:"No two routed resources use the same port"};let n=s.map(([r,o])=>`port ${r}: ${o.join(", ")}`);return{name:"Duplicate resource ports",didPass:!1,isWarning:!0,message:`${S(s.length,"port")} used by more than one routed resource:
385
- ${n.join(`
386
- `)}`,fix:'Usually a copied service.json. Each container can listen on the same port, but pick distinct "port" values (flisk resource assigns free ones) so URLs like http://<resource>:<port> and localhost checks stay unambiguous'}}var jo=/https?:\/\/([a-z][a-z0-9-]*):(\d+)/g;function tn(e=h()??process.cwd()){let t=b(e),s=Zs(t),n=new Map([...s].map(([o,i])=>[i,o])),r=[];for(let o of t)for(let[i,a]of Object.entries(Do(o.configPath)))for(let[,d,c]of String(a).matchAll(jo)){let l=Number(c),u=s.get(d);u!==void 0&&u!==l?r.push(`${o.name} param ${i}: ${d}:${l}, but ${d} listens on ${u}`):(d==="localhost"||d==="127.0.0.1")&&n.has(l)&&n.get(l)!==o.name&&r.push(`${o.name} param ${i}: localhost:${l} is ${o.name} itself inside its container; ${n.get(l)} is reached as ${n.get(l)}:${l}`)}return r.length===0?{name:"Service URL ports",didPass:!0,message:"Service URLs in params point at the ports the services listen on"}:{name:"Service URL ports",didPass:!1,message:`${S(r.length,"service URL")} in params that cannot connect:
387
- ${r.join(`
388
- `)}`,fix:'Flisk runs each backend on the "port" in its service.json, and containers reach each other by resource name (http://<resource>:<port>). Use that port in the URL'}}function dt(e){let t=[],s;try{s=zs(e,{withFileTypes:!0})}catch{return t}for(let n of s){let r=E(e,n.name);n.isDirectory()?No.has(n.name)||t.push(...dt(r)):vo.test(n.name)&&!$o.test(r)&&t.push(r)}return t}var Io=/(?:localhost|127\.0\.0\.1):(\d{2,5})\b/g,sn=/^\s*(?:\/\/|\/\*|\*|<!--|#)/;function nn(e=h()??process.cwd()){let t=new Map;for(let n of b(e)){let r=n.config;if(!(I(r?.appType)||r?.appType===de&&r.exposeViaProxy!==!1))continue;let i=To(n.path),a=r?.stack??xo(i),d=`${i}\0${a}`,c=t.get(d)??{stack:a,resources:[]};c.resources.push(n),t.set(d,c)}let s=[];for(let{stack:n,resources:r}of t.values()){if(r.length<2)continue;let o=a=>!!(a.config?.traefik?.host||a.config?.traefik?.pathPrefix),i=r.filter(a=>!o(a)).map(a=>a.name);i.length>0&&s.push(`stack "${n}": ${i.sort().join(", ")} lose the shared /api/${n}-management route because ${r.length} backends share the stack; they are routed at /api/<name> only`);for(let a of["host","pathPrefix"]){let d=new Map;for(let c of r){let l=c.config?.traefik?.[a];l&&d.set(l,[...d.get(l)??[],c.name])}for(let[c,l]of d)l.length>1&&s.push(`stack "${n}": ${l.sort().join(" and ")} both set traefik.${a} "${c}", so Traefik cannot tell them apart`)}}return s.length===0?{name:"Stack API routes",didPass:!0,message:"No two backends in one service directory compete for one stack route"}:{name:"Stack API routes",didPass:!1,isWarning:!0,message:s.join(`
389
- `),fix:'Call each backend at /api/<name>, move one backend to its own stack, or give each its own "traefik.pathPrefix" in service.json'}}function rn(e=h()??process.cwd()){let t=b(e),s=new Map([...Zs(t)].map(([o,i])=>[i,o])),n=[];for(let o of t.filter(i=>i.config?.appType==="frontend"))for(let i of dt(E(o.path,"src")))ne(i,"utf-8").split(`
390
- `).forEach((a,d)=>{if(!sn.test(a))for(let[,c]of a.matchAll(Io)){let l=s.get(Number(c));l&&n.push(`${se(e,i)}:${d+1} calls localhost:${c} (${l})`)}});if(n.length===0)return{name:"Frontend backend URLs",didPass:!0,message:"No frontend calls a backend through a localhost port"};let r=Ys(e)??"<project>";return{name:"Frontend backend URLs",didPass:!1,message:`${S(n.length,"frontend call")} to a backend port that Flisk does not publish on localhost:
391
- ${n.join(`
392
- `)}`,fix:`Backends are only reachable through Traefik: http://api.${r}.localhost/api/<name without -api>/... (for example catalog-api is /api/catalog). Use that URL, or the generated .autogenerated/env.ts`}}var on=/\b(?:prisma\s+(?:migrate\s+(?:deploy|dev|resolve)|db\s+push)|drizzle-kit\s+(?:migrate|push)|knex\s+migrate:\w+|typeorm\s+migration:run|mikro-orm\s+migration:up|sequelize(?:-cli)?\s+db:migrate|dbmate\s+(?:up|migrate)|atlas\s+migrate\s+apply|alembic\s+upgrade)\b/,an=new Set(["start","dev","serve","prestart","predev","preserve"]),Fo=/\.(?:sh|bash)$/,Ho=/^\s*(?:CMD|ENTRYPOINT)\b/i;function be(e){try{return ne(e,"utf-8")}catch{return}}function Mo(e){let t=be(E(e,R));if(t===void 0)return[];let s={};try{s=JSON.parse(t)?.scripts??{}}catch{return[]}return Object.entries(s).filter(([n,r])=>an.has(n)&&typeof r=="string"&&on.test(r)).map(([n])=>`package.json "${n}" script`)}function ye(e,t){let s=be(e);return s===void 0?!1:s.split(`
393
- `).some(n=>on.test(n.replace(/["'`,[\]]+/g," "))&&!sn.test(n)&&(!t||Ho.test(n)))}function cn(e=h()??process.cwd()){let t=[];for(let s of b(e)){let n=s.config?.appType??s.type;if(n!=="backend"&&n!=="worker")continue;let r=s.path;for(let a of Mo(r))t.push(`${s.name}: ${a}`);let o=E(r,s.config?.dockerfile??"Dockerfile");ye(o,!0)&&t.push(`${s.name}: ${se(e,o)} CMD or ENTRYPOINT`);let i=[];try{i=zs(r,{withFileTypes:!0})}catch{}for(let a of i){let d=E(r,a.name);a.isFile()&&Fo.test(a.name)&&ye(d,!1)&&t.push(`${s.name}: ${se(e,d)}`)}for(let a of dt(E(r,"src")))ye(a,!1)&&t.push(`${s.name}: ${se(e,a)}`)}return t.length===0?{name:"Migrations outside the API",didPass:!0,message:"No backend or worker runs a migration command from its own start-up"}:{name:"Migrations outside the API",didPass:!1,isWarning:!0,message:`${S(t.length,"migration command")} run from a backend or worker's own start-up:
394
- ${t.join(`
395
- `)}`,fix:"Move the migration into a `migrator` resource (appType migrator) that the service depends on, so it runs once before the service starts instead of on every start and restart"}}function we(e=h()??process.cwd()){let t=b(e).filter(n=>n.config?.featuresEnabled?.includes("nats")).map(n=>n.name);if(t.length===0)return{name:"NATS broker",didPass:!0,message:"No resource enables the nats feature",isSkipped:!0};if(ct(E(e,"services","platform","messaging",Rt)))return{name:"NATS broker",didPass:!0,message:`${S(t.length,"resource")} enable nats and services/platform/messaging/docker-compose.yml is present`};let s=(Ys(e)??"project").replace(/-/g,"_");return{name:"NATS broker",didPass:!1,message:`${t.join(", ")} enable the nats feature, but no NATS server will start: Flisk only starts one when services/platform/messaging/docker-compose.yml exists, and it does not generate that file`,fix:`Create it with a "nats" service (image nats with -js, container_name ${s}_nats, network ${s}_backend, external) and a "redis" service, which Flisk registers alongside it`}}function dn(e=h()??process.cwd()){let t=it(e),s=" (project resource set; flisk up may select a subset and not start Postgres)",n=t.focusWouldEnableDatabaseManagement?" Warning: generated Tiltfile default focus expands CORE_INFRA to database-management while project.json has it off; default flisk up takes the feature path.":"";if(t.unknownDependsOnNames.length>0){let o=t.unknownDependsOnNames.map(({resource:a,name:d})=>`"${d}" (from ${a})`).join(", "),i=t.willStart?` Postgres will start because ${t.reason==="feature"?"database-management is enabled":`resource(s) ${t.dependsOnUsers.join(", ")} depend on postgres/database-management`}${s}`:" Postgres will not start for this project.json/generated Tiltfile state.";return{name:"Shared platform Postgres",didPass:!1,message:`${S(t.unknownDependsOnNames.length,"unknown dependsOn name")}: ${o}. These are not known services or stacks, and are not the shared platform database names (postgres, database-management).${i}${n}`,fix:'Use "postgres" or "database-management" in dependsOn for the shared platform database, or fix the name to match an existing service'}}if(!t.willStart)return{name:"Shared platform Postgres",didPass:!0,isWarning:!!n,isSkipped:!n,message:n?n.trim():"Shared platform Postgres will not start: database-management is off and no resource depends on postgres or database-management."};if(t.reason==="feature"&&t.dependsOnUsers.length===0){let o=t.featureOnFromTiltfile||t.featureOnFromSpecMaster?" (generated Tiltfile/spec.master)":"";return{name:"Shared platform Postgres",didPass:!0,isWarning:!!n,message:`Shared platform Postgres will start because the database-management feature is enabled${o} (project-wide; not a flisk up selection).${n}`}}let r=t.reason==="feature"?`the database-management feature is enabled and resource(s) ${t.dependsOnUsers.join(", ")} depend on postgres/database-management`:`resource(s) ${t.dependsOnUsers.join(", ")} depend on postgres/database-management`;return{name:"Shared platform Postgres",didPass:!0,isWarning:!!n,message:`Shared platform Postgres will start because ${r}${s}${n}`}}function Lo(e){let t=[];for(let s of e.split(`
396
- `)){let n=s.match(/^\s*(\d+)\s+.*\btilt up\b.*?\s-f\s+(\S+)/i);n&&t.push({pid:Number(n[1]),root:n[2].split(/[\\/]\.tdk[\\/]/i)[0]})}return t}function ln(e=h()??process.cwd(),t=wo){let s;try{s=process.platform==="win32"?bo("powershell.exe",["-NoProfile","-Command","Get-CimInstance Win32_Process | Where-Object { $_.Name -eq 'tilt.exe' } | ForEach-Object { '{0} {1}' -f $_.ProcessId, $_.CommandLine }"],{encoding:"utf-8",timeout:Se,windowsHide:!0}):t("ps -Ao pid=,command=",{encoding:"utf-8",timeout:Se})}catch{return{name:"Tilt processes",didPass:!0,isSkipped:!0,message:"Could not list processes"}}let n=Lo(s),r=n.filter(i=>i.root===e),o=n.filter(i=>i.root!==e);return r.length>1?{name:"Tilt processes",didPass:!1,message:`${r.length} Tilt processes are running for this project (pids ${r.map(i=>i.pid).join(", ")}). They fight over ports and containers`,fix:`Stop them all, then start one: flisk down && kill ${r.map(i=>i.pid).join(" ")} && flisk up`}:o.length>0?{name:"Tilt processes",didPass:!0,isSkipped:!0,message:`Another project's Tilt is running: ${o.map(a=>`${a.root} (pid ${a.pid})`).join(", ")}`,fix:"flisk up will use the next free Tilt UI port (10351, ...). If it is a leftover, run flisk down in that project"}:{name:"Tilt processes",didPass:!0,message:"No stray Tilt processes"}}async function un(e=O){let t=`tdk_doctor_probe_${process.pid}`;try{await e(`docker network create ${t}`,Se)}catch(s){let n=String(s.stderr??s);return/address pools/i.test(n)?{name:"Docker networks",didPass:!1,message:"Docker cannot create another network: all predefined address pools are in use. Each Flisk project needs several",fix:"run flisk down --prune-networks in projects you are not using, or docker network prune (removes all unused networks)"}:{name:"Docker networks",didPass:!0,isSkipped:!0,message:"Could not test network creation"}}try{await e(`docker network rm ${t}`,Se)}catch{}return{name:"Docker networks",didPass:!0,message:"Docker can create networks"}}import{execFileSync as fn}from"node:child_process";import{existsSync as Jo,mkdirSync as Ko,readFileSync as mn,realpathSync as qo,writeFileSync as zo}from"node:fs";import{join as re,resolve as Yo,sep as Xo}from"node:path";import{createServer as Bo}from"node:net";import{connect as Uo}from"node:net";function pn(e,t=500){return new Promise(s=>{let n=Uo({port:e,host:"127.0.0.1"}),r=o=>{n.destroy(),s(o)};n.setTimeout(t,()=>r(!1)),n.once("connect",()=>r(!0)),n.once("error",()=>r(!1))})}var Go={ingressHttp:{start:8080,end:8180},ingressHttps:{start:8443,end:8543},postgres:{start:15432,end:15532}},xe={ingressHttp:"TDK_HTTP_PORT",ingressHttps:"TDK_HTTPS_PORT",postgres:"TDK_POSTGRES_PORT"},lt={ingressHttp:80,ingressHttps:443,postgres:5432},ut={ingressHttp:lt.ingressHttp,ingressHttps:lt.ingressHttps};function Wo(e,t){return e==="EACCES"&&t==="darwin"}async function pt(e){return await pn(e)?!1:new Promise(t=>{let s=Bo();s.once("error",n=>{t(Wo(n.code,process.platform))}),s.listen(e,"127.0.0.1",()=>s.close(()=>t(!0)))})}function Vo(e,t){let s=Number(t);if(!Number.isInteger(s)||s<1||s>65535)throw new Error(`${e} must be an integer between 1 and 65535 (received ${JSON.stringify(t)})`);return s}async function K(e={}){let t=e.env??process.env,s=e.isAvailable??pt,n={ingressHttp:!1,ingressHttps:!1,postgres:!1},r={ingressHttp:"",ingressHttps:"",postgres:""},o={explicit:n},i=new Set;for(let a of["ingressHttp","ingressHttps","postgres"]){let d=t[xe[a]],c=d!==void 0&&d.trim()!=="",l=e.ranges?.[a]??Go[a],u=ut[a],f=c?[Vo(xe[a],d)]:[...u===void 0?[]:[u],...Array.from({length:l.end-l.start+1},(y,k)=>l.start+k)],g;for(let y of f)if(!i.has(y)){if(await s(y)){g=y;break}if(c)throw new Error(`${xe[a]}=${y} is already in use. Choose a free host port and retry.`)}if(g===void 0)throw new Error(`No available host port in ${l.start}-${l.end} for ${a}. Set ${xe[a]} to a free port and retry.`);i.add(g),o[a]=g,n[a]=c,r[a]=c?"explicit override":g===u?"requested port is free":`selected from fallback range ${l.start}-${l.end}`}return{...o,requested:{...lt},reason:r}}function Xc(e){return`Host ports: HTTP ${e.ingressHttp}, HTTPS ${e.ingressHttps}, Postgres ${e.postgres}`}var hn=re(".tdk",".tdk-out","host-ports.json");function Zo(e,t,s){return e.split(`
397
- `).some(n=>{let[r="",o=""]=n.split("|"),i=r.toLowerCase(),a=t.toLowerCase();return(i.startsWith(`${a}_`)||i.startsWith(`${a}-`))&&o.includes(`:${s}->`)})}function gn(e){let t=re(e,hn);if(!Jo(t))return null;try{let s=JSON.parse(mn(t,"utf-8"));if(!s||typeof s!="object")return null;let n=s;return!Number.isInteger(n.ingressHttp)||!Number.isInteger(n.ingressHttps)||!Number.isInteger(n.postgres)||!n.requested||!n.explicit||!n.reason?null:n}catch{return null}}function rd(e,t){let s=re(e,hn);Ko(re(e,".tdk",".tdk-out"),{recursive:!0}),zo(s,`${JSON.stringify(t,null,2)}
398
- `,{encoding:"utf-8",mode:384})}function od(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 Qo="com.docker.compose.project.working_dir";function ei(e,t,s){let n=new Set([Yo(t)]);try{n.add(qo(t))}catch{}return e.split(`
399
- `).some(r=>{let[,o="",i=""]=r.split("|");return!i||!o.includes(`:${s}->`)?!1:[...n].some(a=>i===a||i.startsWith(`${a}${Xo}`))})}function kn(e,t,s=()=>fn("docker",["ps","--format",`{{.Names}}|{{.Ports}}|{{.Label "${Qo}"}}`],{encoding:"utf-8",timeout:5e3})){let n=gn(e);if(!n||n.ingressHttp===t)return t;try{if(ei(s(),e,n.ingressHttp))return n.ingressHttp}catch{}return t}async function Te(e,t={}){let s=gn(e),n=["TDK_HTTP_PORT","TDK_HTTPS_PORT","TDK_POSTGRES_PORT"].some(c=>process.env[c]);if(t.inspectDocker===!1&&s&&!n)return s;let r="";try{let c=JSON.parse(mn(re(e,".tdk",v),"utf-8"));r=String(c?.project?.name??"tdk-project").replace(/-/g,"_").toLowerCase()}catch{r="tdk_project"}let o="";if(t.inspectDocker!==!1)try{o=fn("docker",["ps","--format","{{.Names}}|{{.Ports}}"],{encoding:"utf-8",timeout:5e3})}catch{}let i=c=>Zo(o,r,c),a=t.isPortFree??pt,d=async c=>await a(c)||i(c);if(s&&!n){for(let c of[s.ingressHttp,s.ingressHttps,s.postgres])if(!await d(c))return K({isAvailable:d});for(let[c,l]of Object.entries(ut)){let u=s[c];if(l!==void 0&&u!==l&&await d(l))return K({isAvailable:d})}return s}return K({isAvailable:d})}import{relative as ti}from"node:path";function ve(e,t){return ti(e,t.configPath)||t.configPath}function yn(e){let t=e.config?.dependsOn;return t===void 0?[]:Array.isArray(t)&&t.every(s=>typeof s=="string")?t:null}function si(e){let t=new Set(e.map(a=>a.name)),s=new Map(e.map(a=>[a.name,(yn(a)??[]).filter(d=>t.has(d))])),n=new Map,r=new Map,o=[],i=a=>{r.set(a,"visiting"),o.push(a);for(let d of s.get(a)??[])if(r.get(d)==="visiting"){let c=o.slice(o.indexOf(d)),l=c.indexOf([...c].sort()[0]??d),u=[...c.slice(l),...c.slice(0,l)];n.set(u.join(">"),[...u,u[0]??d])}else r.has(d)||i(d);o.pop(),r.set(a,"done")};for(let a of[...s.keys()].sort())r.has(a)||i(a);return[...n.values()]}function ft(e=h()??process.cwd(),t=b(e)){let s=t.flatMap(n=>yn(n)===null?[`${ve(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:`${S(s.length,"invalid dependsOn","invalid dependsOn")}:
400
- ${s.join(`
401
- `)}`,fix:'Write "dependsOn" as an array of service names, for example ["postgres", "api"]'}}function mt(e=h()??process.cwd(),t=b(e)){let s=new Map(t.map(o=>[o.name,o])),n=si(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?ve(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"}:
402
- ${r.join(`
403
- `)}`,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 ht(e=h()??process.cwd(),t=b(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?[]:[`${ve(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:`${S(s.length,"invalid port")}:
404
- ${s.join(`
405
- `)}`,fix:'Set "port" to the port the service listens on, an integer from 1 to 65535'}}function gt(e=h()??process.cwd(),t=!1,s=b(e)){let n=[],r=[];for(let i of s){let a=i.config?.schemaVersion;if(a===je)continue;let d=ve(e,i);a===void 0?n.push(`${d} schemaVersion: missing`):r.push(`${d} schemaVersion ${JSON.stringify(a)}: this flisk supports ${je}`)}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:`${S(n.length+r.length,"service.json file")} without a supported schemaVersion:
406
- ${[...n,...r].join(`
407
- `)}`,fix:o.join(". ")}}function md(e,t){let s=gt(e,!1,t);s.didPass||(console.warn(P.yellow(`\u26A0 ${s.message}`)),s.fix&&console.warn(P.gray(` ${s.fix}`)))}function hd(e,t={},s=process.exit){let n=t.resources??b(e),r=[Pe(e,n),ft(e,n),mt(e,n),ht(e,n)].filter(i=>!i.didPass);if(r.length===0)return;let o=r.map(i=>`${i.message}${i.fix?`
408
- Fix: ${i.fix}`:""}`).join(`
409
- `);t.onInvalid?.(o);for(let i of r)console.error(P.red(`\u2717 ${i.message}`)),i.fix&&console.error(P.gray(` Fix: ${i.fix}`));s(1)}import{readFileSync as ni}from"node:fs";import{join as ri}from"node:path";function Sn(e){let t=e.trim().match(/(\d+)\.(\d+)(?:\.(\d+))?/);return t?[Number(t[1]),Number(t[2]),Number(t[3]??0)]:null}function oi(e){try{return JSON.parse(ni(ri(e,".tdk",v),"utf-8"))?.minTdkVersion}catch{return}}function Pn(e,t){let s=oi(e);if(s===void 0)return{status:"none"};let n=typeof s=="string"?Sn(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=Sn(t),o=r!==null&&(()=>{for(let[a,d]of n.entries()){let c=r[a]??0;if(c!==d)return c>d}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 j=1e4,A={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"},wn="WSL2 detected. Use Docker Desktop WSL integration. Guide: docs/wsl2.md",xn="Native Windows landscape boot is unsupported. Use WSL2 Ubuntu with Docker Desktop integration. Guide: docs/wsl2.md",kt=[0,25,0],B=[1,2,0];function $e(e,t){let s=xt(e);return s?Tt(s,t):!1}function di(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:`${wn} Project is on the WSL filesystem.`};let r=`${wn} 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 li(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 ui(e=process.env,t=!1){let s=(e.TDK_BIND_ADDRESS??"").trim();return li(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 $n(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 pi(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 wt={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"},Tn=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(wt)]);function fi(e){return!!(e.requiresContainerRuntime||e.checkName&&Tn.has(e.checkName)||e.name&&Tn.has(e.name))}function C(e,t){let s=()=>t();return s.requiresContainerRuntime=!0,s.checkName=e,s}async function mi(e,t={}){let s=[],n=!!t.containerRuntimeFailed;for(let r of e){if(n&&fi(r)){let i=r.checkName??(r.name&&wt[r.name]?wt[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===T&&!o.didPass&&(n=!0),!t.all&&!o.didPass&&!o.isSkipped&&!o.isWarning)break}return s}function hi(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 $t(e){return Us(e)}function gi(e,t,s,n,r){return async(o=O)=>{try{return await o(t,j),{name:e,didPass:!0,message:s}}catch(i){return $t(i)?{name:e,didPass:!1,message:`${e} did not respond within ${j/1e3}s`,fix:r}:{name:e,didPass:!1,message:n,fix:r}}}}async function yt(e){try{return await O(e,j),!0}catch{return!1}}async function Et(){if(process.platform==="win32")try{return await O("docker ps",j),{name:T,didPass:!0,message:"Docker Desktop Linux container engine is running"}}catch{return{name:T,didPass:!1,message:"Docker is not running",fix:A.dockerDaemonDown}}let e=!!$("docker");try{return await O("docker ps",j),{name:T,didPass:!0,message:"Docker daemon is running"}}catch(s){if($t(s))return{name:T,didPass:!1,message:"Docker daemon is not responding",fix:A.dockerDaemonDown}}let t=ks(await yt("pgrep -f com.docker.backend"));return t||(await yt("colima status")?{name:T,didPass:!0,message:"Colima (Docker runtime) is running"}:$("colima")?{name:T,didPass:!1,message:"Colima is installed but not running",fix:A.dockerDaemonDown}:await yt("podman ps")?{name:T,didPass:!0,message:"Podman is running"}:e?{name:T,didPass:!1,message:"Docker daemon is not running",fix:A.dockerDaemonDown}:{name:T,didPass:!1,message:"Docker is not running",fix:A.dockerMissing})}var oe=gi("Docker Compose","docker compose version","Docker Compose plugin available","Docker Compose plugin not found","Install Docker Compose: https://docs.docker.com/compose/install/");oe.requiresContainerRuntime=!0;oe.checkName="Docker Compose";var ki=[25,0,0],yi=[2,20,2];function xt(e){let t=e.trim().match(/(\d+)\.(\d+)(?:\.(\d+))?/);return t?[Number(t[1]),Number(t[2]),Number(t[3]??0)]:null}function Tt(e,t){for(let[s,n]of t.entries()){let r=e[s]??0;if(r!==n)return r>n}return!0}async function ie(e=O){let t=async a=>String(await e(a,j)).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=xt(s),o=xt(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 Tt(r,ki)||i.push(`Docker Engine ${s} (need 25.0+)`),Tt(o,yi)||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):
410
- ${i.join(`
411
- `)}`,fix:"Update Docker Desktop, or on Linux update docker-ce and the docker-compose-plugin package"}}ie.requiresContainerRuntime=!0;ie.checkName="Docker Versions";async function Nt(e=O){let t;try{t=String(await e("tilt version",j)).trim()}catch{return{name:"Tilt CLI",didPass:!1,message:"Tilt CLI not found",fix:A.tiltMissing}}return $e(t,kt)?{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${kt.join(".")} floor`,fix:`Install Tilt v${kt.join(".")} or newer: https://docs.tilt.dev/install.html`}}async function Dt(e=O){let t;try{t=String(await e("docker info --format '{{.OSType}}'",j)).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"}}Dt.requiresContainerRuntime=!0;Dt.checkName="Docker OS";async function Si(e=O){let t=h();if(!t)return{name:"Bun",didPass:!0,isSkipped:!0,message:"Not in a project - skipping Bun check"};if(!fe(b(t)))return{name:"Bun",didPass:!0,isSkipped:!0,message:"No generated JS services - skipping Bun check"};try{let s=String(await e("bun --version",j)).trim();return $e(s,B)?{name:"Bun",didPass:!0,message:`Bun ${s} is available`}:{name:"Bun",didPass:!1,message:`Bun ${s||"version unknown"} is below the required ${B.join(".")} floor`,fix:`Install Bun ${B.join(".")} or newer: https://bun.sh/install`}}catch{return{name:"Bun",didPass:!1,message:"Bun is not available",fix:A.bunMissing}}}function Pi(){let e=h()??process.cwd(),t=jt(e);if(t.missing.length>0)return{name:"Environment Variables",didPass:!1,message:`Missing required env variables: ${t.missing.join(", ")}`,fix:N(w(e,".env"))?`Edit .env and set these values:
412
- ${t.missing.map(n=>`${n}=<value>`).join(`
413
- `)}`:"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 bi(){let e=h()??process.cwd(),t=w(e,".tdk",".tdk-out"),s=Re.filter(n=>!N(w(t,n)));return s.length===0?{name:"Master Configs",didPass:!0,message:`${Re.join(", ")} found`}:{name:"Master Configs",didPass:!1,message:`Master configs missing: ${s.join(", ")}`,fix:"Run: flisk project"}}function wi(e=Ct()){let t=h();if(!t)return{name:"Flisk version",didPass:!0,isSkipped:!0,message:"Not in a project - skipping Flisk version check"};let s=Pn(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 xi(){let e=h()??process.cwd(),t=He(e),s=b(e).filter(r=>!me(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=>Pt(bt(e,r.path))).join(", ");return{name:"Resource Discovery",didPass:!1,message:`${S(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 Ti=["install-deps.sh","bun-hoisted-symlink-fix.sh","prisma-bun-client-link-fix.sh","prisma-normalize-client.sh","infisical-entrypoint.sh"],vi=/shared-platform-engineering\/docker-templates\/([\w.-]+)/g;function $i(e){let t=new Set;for(let s of b(e)){let n=w(s.path,_);if(N(n)){for(let r of ai(n))if(!(!r.startsWith("Dockerfile")||r.endsWith(".dockerignore")))for(let o of q(w(n,r),"utf-8").matchAll(vi))t.add(o[1])}}return[...t]}function Ei(){let e=h()??process.cwd(),t=[];N(w(e,R))||t.push(`${R} (workspace root manifest)`);let s=w(e,"shared-platform-engineering","docker-templates"),n=[];try{n=$i(e)}catch{}for(let r of new Set([...Ti,...n]))N(w(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:
414
- ${t.join(`
415
- `)}`,fix:"Run `flisk project --yes` (or `flisk config regenerate`) with an updated Flisk. `flisk up` also refreshes these assets before starting Tilt."}}function Ni(){let e=h()??process.cwd(),t=b(e),s=[];for(let n of t){let r=w(n.path,R);if(!N(r))continue;let o=n.config?.appType??"backend",i=Oe[o]??Oe.backend,a;try{a=JSON.parse(q(r,"utf-8")).scripts??{}}catch{s.push(`${n.name} (package.json is invalid JSON)`);continue}let d=i.filter(c=>!a[c]);d.length>0&&s.push(`${n.name}: missing "${d.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:
416
- ${s.join(`
417
- `)}`,fix:`Add the missing scripts to each service's package.json, e.g.:
418
- "dev": "bun run src/index.ts",
419
- "build": "tsc",
420
- "start": "bun run dist/index.js"`}}function En(e){if(e.startsWith("@"))return[e.split("/").slice(0,2).join("/")];let t=e.split("/")[0]??e;return[`@types/${t}`,t]}function Nn(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(Nn(e,r[1],s+1))return!0;return!1}function vn(e){let t=En(e);return e.includes("/")||e.startsWith("@")?t[t.length-1]:t[0]}var Di={"@types/bun":"^1.4.2","@types/node":"^20.0.0"};function _i(e,t){return(t.includes("bun")||e.has("@types/bun"))&&!e.has("@types/node")}function Ri(){let e=h()??process.cwd(),t=b(e),s=[],n=new Set;for(let o of t){let i=w(o.path,R),a=w(o.path,_,"tsconfig.docker.autogenerated.json");if(!N(i)||!N(a))continue;let l=vt(a)?.compilerOptions?.types;if(!Array.isArray(l))continue;let u=vt(i),f=u?.scripts??{};if(!Nn(f,"build"))continue;let g=new Set([...Object.keys(u?.devDependencies??{}),...Object.keys(u?.dependencies??{})]),y=l.filter(k=>typeof k=="string").filter(k=>!En(k).some(p=>g.has(p)));for(let k of y)n.add(vn(k));if(y.length>0){let k=y.map(p=>`"${p}" (needs ${vn(p)})`).join(", ");s.push(`${o.name}: "types" lists ${k}`)}_i(g,l)&&(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=Di[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:
421
- ${s.join(`
422
- `)}`,fix:`Add to each service's package.json devDependencies: ${r.join(", ")}`}}function vt(e){try{return JSON.parse(q(e,"utf-8"))}catch{return null}}function Oi(e){let s=vt(e)?.compilerOptions;return s?.allowSyntheticDefaultImports===!0||s?.esModuleInterop===!0}function Ci(){let e=h()??process.cwd(),t=b(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){N(w(n.path,"public"))||s.push(`${n.name}: no public/ folder, but the Docker build copies it. Create it: mkdir -p ${Pt(bt(e,w(n.path,"public")))} && touch ${Pt(bt(e,w(n.path,"public",".gitkeep")))}`);let r=w(n.path,_,"Dockerfile.app.autogenerated"),o=w(n.path,_,"tsconfig.docker.autogenerated.json");if(N(r)){let i=q(r,"utf-8"),a=/\bEXPOSE\s+80\b/.test(i),d=n.config?.stack,c=d?w(e,"services",d,_,"docker-compose.app.autogenerated.yml"):"";if(a&&c&&N(c)){let l=q(c,"utf-8"),u=n.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),f=new RegExp(`traefik\\.http\\.services\\.${u}\\.loadbalancer\\.server\\.port=(\\d+)`),y=l.match(f)?.[1];y&&y!=="80"&&s.push(`${n.name}: nginx runtime exposes 80, but generated Traefik routes to ${y}`)}}if(N(o)&&!Oi(o)){let i=w(n.path,"src","main.tsx");if(N(i)){let a=q(i,"utf-8"),d=[/import\s+\w+\s+from\s+["']react["']/,/import\s+\w+\s+from\s+["']react-dom\/client["']/].filter(c=>c.test(a)).map(c=>c.source.includes("react-dom")?"react-dom/client":"react");d.length>0&&s.push(`${n.name}: Docker tsconfig does not allow synthetic default imports, but src/main.tsx default-imports ${d.join(" and ")}`)}}}return s.length===0?{name:"Frontend Docker Preflight",didPass:!0,message:`${S(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:
423
- ${s.join(`
424
- `)}`,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 Ai=90,ji=80;function Ii(e){return e.split(`
425
- `).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 Fi=Object.assign(function(){let t;try{t=ii($("docker")??"docker",["stats","--no-stream","--format","{{.Name}},{{.MemPerc}},{{.CPUPerc}}"],{stdio:"pipe",encoding:"utf-8",timeout:j,windowsHide:process.platform==="win32"})}catch(o){return{name:"Container Resource Health",didPass:!0,isSkipped:!0,message:$t(o)?"Docker not responding - skipped container resource check":"Docker not running - skipped container resource check"}}let s=Ii(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>=Ai&&o.cpuPct>=ji);if(n.length===0)return{name:"Container Resource Health",didPass:!0,message:`${S(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(`
426
- `);return{name:"Container Resource Health",didPass:!1,message:`${S(n.length,"container")} pinned near its memory limit while burning CPU -- likely stuck in a boot-time retry/fetch loop, not a normal crash:
427
- ${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"}),Hi=5e3;async function Mi(e,t){let s=h()??process.cwd(),n=Ae(b(s),t);return n.length===0?{name:"Service Health",didPass:!0,isSkipped:!0,message:"No routable services to ping"}:qe(await ue(n,e))}async function Li(e,t){let s=h()??process.cwd(),n=b(s),r=Lt(Mt(n,t),{timeoutSeconds:Math.ceil(e/1e3)});return r.length===0?ze([]):(await ue(Ae(n,t),e)).some(i=>i.status!==void 0)?ze(await Bt(r,Ut(s))):{name:"Service Smoke",didPass:!0,isSkipped:!0,message:"No services responded - skipped smoke checks"}}async function Ui(e,t){let s=h()??process.cwd(),n=b(s),r=Ht(n,t);return r.length===0?{name:"Advertised Endpoints",didPass:!0,isSkipped:!0,message:"No routable services to check"}:ls(await ue(r,e))}function Bi(e,t){if(e.length===0){console.log(`${P.green("\u2713")} Nothing to repair
428
- `);return}for(let s of e){let n=s.status==="planned"?`${P.cyan("would run")}`:s.status==="applied"?P.green("ran"):s.status==="failed"?P.red("failed"):P.gray("skipped"),r=s.status==="planned"?"":` (${s.reason})`;console.log(`${n}: ${s.command}${r}`)}t&&console.log(P.gray(`
429
- Dry run: nothing was changed.`)),console.log("")}function St(e){for(let t of $n(e))!t.didPass&&!t.isSkipped&&!t.isWarning?(console.log(`${P.red("\u2717")} ${t.message}`),t.fix&&console.log(`${P.blue("\u2139")} Fix: ${t.fix}`)):t.isWarning?(console.log(`${P.yellow("\u26A0")} ${P.yellow(t.message)}`),t.fix&&console.log(`${P.blue("\u2139")} Fix: ${t.fix}`)):t.isSkipped?(console.log(`${P.gray("\u25CB")} ${P.gray(t.message)}`),t.fix&&console.log(`${P.blue("\u2139")} ${t.fix}`)):console.log(`${P.green("\u2713")} ${t.message}`)}function Gi(e,t,s,n={},r){let o=r??[...e,...t];n.all?(console.log(P.bold("Machine")),St(e),console.log(`
430
- ${P.bold("Project")}`),s?t.length>0&&St(t):console.log(`${P.gray("\u25CB")} ${P.gray("Not in a Flisk project, so project checks were skipped")}`),console.log(""),console.log(hi(o))):(St(o),console.log(""),o.every(a=>a.didPass||a.isSkipped||a.isWarning)&&!s&&(console.log(`${P.gray("\u25CB")} ${P.gray("Not in a Flisk project, so project checks were skipped")}`),console.log("")))}var Wi=new ci("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),Wi.opts().json&&console.log(JSON.stringify(H([],!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(Hi)).action(async e=>{let t=Number(e.pingTimeout);if(!/^\d+$/.test(e.pingTimeout)||!Number.isSafeInteger(t)||t<=0){let m="--ping-timeout must be a positive integer number of milliseconds";e.json&&console.log(JSON.stringify(H([],!1,[{code:"USAGE",message:m}]))),console.error(m),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 m=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(H([],!1,[{code:"USAGE",message:m}]))),console.error(m),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=qt();if(process.platform==="win32"){if(e.json){let m=null;try{m=await K()}catch{}console.log(JSON.stringify(H([{name:"Native Windows support",didPass:!1,message:xn,fix:"Use WSL2 Ubuntu with Docker Desktop integration. Guide: docs/wsl2.md"}],!!h(),[],m,{...r,canUp:!1})))}console.error(xn),process.exit(1);return}if(r.kind==="webcontainer"){let m=H([{name:"Host",didPass:!1,message:Fe,fix:`Use a machine with Docker. Guide: ${pe}`}],!!h(),[],void 0,r);e.json&&console.log(JSON.stringify(m)),console.error(Fe),process.exit(1);return}e.json||(console.log(`
431
- ${P.bold("\u{1F50D} Flisk Doctor")}
432
- `),console.log(`Checking environment...
433
- `));let o=h(),i;if(e.fix){try{let m;if(o)try{m=Vt(o).project.name}catch{}let x=o?$s(o):[],Ne=await ws(m,void 0,{tiltPids:x,machine:e.scope==="machine"});i=await xs(Ne,{dryRun:e.dryRun,confirm:e.yes||!e.json&&process.stdin.isTTY?async D=>e.yes||await Jt({message:`Run \`${D.command}\` (${D.check}, ${D.reason})?`}):void 0})}catch(m){i=[{id:"plan-fixes",check:"Docker networks",scope:"project",command:"docker network ls",status:"failed",reason:`could not list Docker networks: ${(m instanceof Error?m.message:String(m)).split(/\r?\n/)[0]}`}]}e.json||Bi(i,e.dryRun)}let a,d;try{a=await Te(o??process.cwd())}catch(m){a=null,d=m instanceof Error?m.message:String(m)}let c=[()=>a?{name:"Host Ports",didPass:!0,message:`HTTP ${a.ingressHttp}, HTTPS ${a.ingressHttps}, Postgres ${a.postgres}`}:{name:"Host Ports",didPass:!1,message:d??"Could not select host ports",fix:"Set TDK_HTTP_PORT, TDK_HTTPS_PORT, or TDK_POSTGRES_PORT to available host ports."},()=>a?Ke(bn,void 0,[a.ingressHttp,a.ingressHttps]):{name:"Ingress Ports",didPass:!1,message:"Ingress port plan is unavailable"},Et,()=>gs(),C("Docker OS",Dt),Nt,C("Docker Compose",oe),C("Docker Versions",ie),Si,()=>di(h()??process.cwd(),e.strict),()=>ui(process.env,e.strict),C("Docker Network Pool",()=>un()),()=>vs()],l=[()=>wi(),bi,Ei,Os,Ni,()=>ps(),Ri,Ci,xi,()=>Qs(),()=>Pe(),()=>ft(),()=>mt(),()=>ht(),()=>gt(void 0,e.strict),()=>en(),()=>tn(),()=>rn(),()=>nn(),()=>we(),()=>Xs(),()=>dn(),()=>cn(),()=>ln(),Pi,async()=>{let m=h()??process.cwd(),x=Ve(m)?await Wt(m):!0;return Je(bn,m,void 0,x)},C("Container Resource Health",Fi),C("Crash-looping containers",()=>{let m=h()??process.cwd(),x=[];try{x=Ce(m)}catch{return{name:"Crash-looping containers",didPass:!0,isSkipped:!0,message:"Could not read .env - skipped crash-loop check"}}return ms(Z(),x)}),C("Tilt Resources",Ye)];if(e.ping){let m=o?kn(o,a?.ingressHttp):a?.ingressHttp;l.push(C("Service Health",()=>Mi(t,m))),l.push(C("Service Smoke",()=>Li(t,m))),l.push(C("Advertised Endpoints",()=>Ui(t,m)))}let u=!!o,f=[],g=[],y,k=[];if(e.json||!e.all){let m=await Ns(c,u?l:[]);y=m.checks,k=m.errors}else{let m=async(D,Un=!1)=>{let Bn=D.map(ce=>{let De=async()=>{try{return await ce()}catch(_e){return k.push({code:"INTERNAL",message:_e instanceof Error?_e.message:String(_e)}),{name:ce.checkName??"Doctor check",didPass:!1,isSkipped:!1,message:"Check failed with an internal error"}}};return De.requiresContainerRuntime=ce.requiresContainerRuntime,De.checkName=ce.checkName,De});return mi(Bn,{all:!!e.all,containerRuntimeFailed:Un})};f=await m(c);let x=f.some(D=>!D.didPass&&!D.isSkipped&&!D.isWarning),Ne=f.some(D=>D.name===T&&!D.didPass);u&&(e.all||!x)&&(g=await m(l,Ne)),y=[...f,...g]}if(zt(r.kind))for(let m of y)m.name===T&&!m.didPass&&(m.fix=Kt);let p=H($n(y),u,k,a,r);i&&(p.data.actions=i),i&&Ts(i)&&(p.data.ready=!1);let G=Ds(p),Y=p.data.ready;if(e.json){let m;try{m=Ce(h()??process.cwd())}catch(x){if(!(x instanceof It))throw x;console.log(JSON.stringify(H([],u,[...k,{code:"ENV_UNREADABLE",message:x.message}]))),console.error(x.message),process.exit(1)}console.log(JSON.stringify(Ft(p,m)));for(let x of k)console.error(le(x.message,m));G!==0&&process.exit(G);return}for(let m of k)console.error(`${P.red("\u2717")} Doctor check failed: ${m.message}`);Gi(f,g,u,e,y);let _t=pi(u,Y);console.log(`${Y?P.green(P.bold("\u2713")):P.red(P.bold("\u2717"))} ${_t}`),G!==0&&process.exit(G)});function Dn(e){return $e(e,B)}var ae=`${B[0]}.${B[1]}+`;import{execFileSync as _n}from"node:child_process";import{accessSync as Rn,constants as On,readdirSync as Vi}from"node:fs";import{delimiter as Ji,join as z}from"node:path";var F="flisk",Cn="@flisk-sh/flisk",An="@tdk-landscape/tdk-cli-core";function jn(e=F,t=process.env){let s=t.PATH??t.Path??"";for(let n of s.split(Ji)){if(!n)continue;let r=[z(n,e),z(n,`${e}.cmd`),z(n,`${e}.exe`)];for(let o of r)try{return Rn(o,On.X_OK),!0}catch{}}return!1}function Ki(e=process.env){let t=e.HOME??e.USERPROFILE??"";if(!t)return"flisk-workspace";let s=z(t,"Documents");try{return Rn(s,On.F_OK),z(s,"flisk")}catch{return z(t,"flisk")}}function qi(e){try{return Vi(e).every(t=>t.startsWith("."))}catch{return!0}}function In(e=process.env,t=process.cwd()){if(!jn(F,e))return`The \`${F}\` command is not on PATH (this run is not a global install). Install it with \`npm install -g ${Cn}\`, then run \`${F} project --yes\`. If npm reports EEXIST for \`flisk\`, the old package still owns that command: run \`npm uninstall -g ${An}\` first.`;if(qi(t))return`Next: ${F} project --yes`;let s=Ki(e);return`Next: mkdir -p ${s} && cd ${s} && ${F} project --yes
434
- (${F} 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: ${F} project example)`}function il(e=process.env){if(jn(F,e))return"present";let t=e.npm_execpath?.includes("bun")?"bun":"npm",s=t==="bun"?"bun remove -g":"npm uninstall -g";try{_n(s,[An],{stdio:"ignore",timeout:12e4})}catch{}try{return _n(t,["install","-g",Cn],{stdio:"inherit",timeout:3e5}),"installed"}catch{return"failed"}}var Xi=["docker","compose","tilt"],Mn=["node","bun","ports"],Ln=["node",...Xi,"bun","ports"];function Zi(e,t){return{id:e,ok:t.didPass||!!t.isSkipped,message:t.message,fix:t.fix}}function Hn(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 Ee(e,t,s){try{return Zi(e,await t())}catch{return{id:e,ok:!1,message:s}}}function Qi(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 ea(e){try{return b(e).some(t=>t.config?.featuresEnabled?.includes("prisma")??!1)}catch{return!1}}async function ta(e={}){let t=e.cwd??process.cwd(),s=e.scope??"runtime",n=h(t),r=!!n,o=[],i=process.versions.node;o.push({id:"node",ok:!Hn(i),message:i,fix:Hn(i)?`Install Node.js 22.12+ (current: ${i}). https://nodejs.org`:void 0}),s==="runtime"&&(o.push(await Ee("docker",Et,"Docker daemon is not running")),o.push(await Ee("compose",async()=>{let[p,L]=await Promise.all([oe(),ie()]);return p.didPass?Qi(L):p},"Docker Engine or Compose version check failed")),o.push(await Ee("tilt",Nt,"Tilt CLI not found")));let a=n?fe(b(n)):!0,d=!1,c=a?$("bun"):void 0;if(c)try{let p=Fn(c,["--version"],{encoding:"utf-8",timeout:3e3}).trim();d=Dn(p)}catch{}o.push(a?{id:"bun",ok:d,message:d?`Bun ${ae} is available on PATH`:`Bun ${ae} not found on PATH`,fix:d?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 Te(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 Ee("nats",()=>we(n),"NATS broker check failed");if(p.ok||o.push(p),ea(n)){let L=!1;try{let G=JSON.parse(zi(Yi(n,".tdk",v),"utf-8")),Y=String(G?.project?.name??"").replace(/-/g,"_");Y&&(L=Fn($("docker")??"docker",["ps","--filter",`label=com.docker.compose.project=${Y}`,"--filter","label=com.docker.compose.service=postgres","--filter","health=healthy","--format","{{.Names}}"],{encoding:"utf-8",timeout:3e3}).trim().length>0)}catch{}L||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 l=o.filter(p=>!p.ok).slice(0,8),u=s==="scaffold"?Mn:Ln,f=l.some(p=>u.includes(p.id)),g=l.some(p=>p.id==="bun"),y=l.length?f?s==="scaffold"?g?`Project setup blocked. Bun ${ae} must be installed on PATH.
435
- Fix the machine checks below.`:"Project setup blocked. Fix the machine checks below.":g?`Cold start blocked. Bun ${ae} must be installed on PATH.
436
- 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.":"",k=l.length?"":r?"Environment ready for Flisk":`This machine is ready for Flisk.
437
- ${In()}`;return{ok:l.length===0,inProject:r,items:l,header:y,footer:k}}function sa(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(`
438
- `)}async function bl(e={}){let t=e.scope??"runtime",s=await ta({scope:t}),n=t==="scaffold"?Mn:Ln;s.items.some(o=>n.includes(o.id))&&(console.error(sa(s)),process.exit(1))}function wl(e=$){return{hasDockerCli:!!e("docker"),hasTiltCli:!!e("tilt")}}function xl(e){let t=[];return e.hasDockerCli||t.push(`Docker is not installed. ${A.dockerMissing}`),e.hasTiltCli||t.push(`Tilt is not installed. ${A.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{K as a,Xc as b,gn as c,rd as d,od as e,Te as f,Zr as g,Qr as h,ec as i,lc as j,uc as k,V as l,uo as m,xc as n,Gs as o,it as p,Xs as q,Lo as r,Fe as s,Kt as t,qt as u,zt as v,He as w,me as x,la as y,es as z,ss as A,Be as B,Ge as C,We as D,Aa as E,ja as F,Ia as G,tt as H,Cr as I,Ir as J,Ua as K,md as L,hd as M,Pn as N,Wi as O,il as P,Xi as Q,Mn as R,Ln as S,Hn as T,Qi as U,ta as V,sa as W,bl as X,wl as Y,xl as Z};