@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
@@ -0,0 +1,435 @@
1
+ import{createRequire as __tdkRequire}from'node:module';const require=__tdkRequire(import.meta.url);
2
+ import{a as At,f as It,g as ae,i as Re}from"./chunk-SB5WAMSU.js";import{i as Mt,o as Lt}from"./chunk-KBGQ4NJE.js";import{c as Ft}from"./chunk-42IVF3YT.js";import{Aa as _t,Ba as jt,Ca as De,G as J,O as g,Ta as b,Ua as Ot,b as x,c as re,d as Pt,fa as I,g as wt,h as D,ja as Tt,k as _,l as R,m as $e,ma as Et,na as Ee,o as Te,oa as oe,pa as Nt,q as vt,qa as K,s as m,t as xt,ua as Ne,va as Dt,wa as ie,x as $,xa as Rt,y as $t,ya as Ct}from"./chunk-US4D5GJJ.js";import{b as y}from"./chunk-CF46CD6R.js";import{execFileSync as yn}from"node:child_process";import{readFileSync as ui}from"node:fs";import{join as pi}from"node:path";import{execFileSync as Po,execSync as tn}from"node:child_process";import{existsSync as E,readdirSync as wo,readFileSync as W}from"node:fs";import{join as w,normalize as lt,relative as ut}from"node:path";import{Command as vo}from"commander";import{existsSync as xn}from"node:fs";var ce="docs/agent-hosts.md",Ce=`WebContainers cannot run Flisk: there is no Docker daemon or Tilt. Run \`flisk up\` on a machine with Docker. See ${ce}.`,Ht=`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 ${ce}.`;function $n(){return{env:process.env,versions:process.versions,platform:process.platform,fileExists:xn}}function Ut(e=$n()){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 Bt(e){return e==="devcontainer"||e==="codespaces"}function de(e){return e.some(t=>I(t.config?.appType)||t.config?.appType==="frontend"||t.config?.appType==="worker")}import{existsSync as Tn,readFileSync as En}from"node:fs";import{join as Nn,relative as Gt,resolve as Wt,sep as Dn}from"node:path";var Rn=2,Vt=["services/*/*"];function qt(e){return e.split(Dn).filter(Boolean)}function Cn(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 _n(e,t){return e.length===t.length&&e.every((s,n)=>Cn(s,t[n]))}function _e(e){let t=Nn(e,".tdk",_);if(!Tn(t))return Vt;try{let s=JSON.parse(En(t,"utf-8"))?.discovery?.paths;if(Array.isArray(s)&&s.every(n=>typeof n=="string"))return s}catch{}return Vt}function le(e,t,s){let n=qt(Gt(e,Wt(e,t)));return s.some(r=>{let o=qt(Gt(e,Wt(e,r)));for(let i=0;i<=Rn;i++){let a=n.length-i;if(a>0&&_n(o,n.slice(0,a)))return!0}return!1})}function Ti(e,t,s,n){let r=_e(e);if(le(e,t,r))return{path:t};let o=`services/${s}/${n}`;return le(e,o,r)?{path:o,adjustedFrom:t}:{path:t}}import{execFile as zn}from"node:child_process";import{promisify as Yn}from"node:util";import{execFileSync as Qt,execSync as X}from"node:child_process";import{existsSync as je,readdirSync as jn,readFileSync as Oe}from"node:fs";import{join as B}from"node:path";function Jt(e,t){return e==="pending"||e==="in_progress"||e==="none"||t==="pending"||t==="none"}var Kt="container is running, but its health check is failing";function zt(e){let t=e?.runtimeStatus??"";if(t!=="ok")return t;let s=e?.composeResourceInfo?.healthStatus;return s==="unhealthy"?"error":s==="starting"?"pending":t}var z=1e4,Yt=3e3,On="http://localhost:4873";function es(e){return`'${e.replace(/'/g,"'\\''")}'`}function Y(e,t,s,n,r){return process.platform==="win32"?Qt($(t)??t,s,{...r,windowsHide:!0}):e(n,r)}var An=[80,443];function Ae(e){return e.replace(/-/g,"_")}function In(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,c=i>=0?o.slice(i+1):"",d=[];for(let l of s)c.split(/[\s,]+/).some(h=>h.startsWith(`${l}->`)||h.includes(`:${l}->`))&&d.push(l);d.length>0&&n.push({name:a,ports:c,publishedPorts:d})}return n}function ts(e,t){let s=e.toLowerCase(),n=t.toLowerCase();return s===`${n}_traefik`||s.startsWith(`${n}_traefik`)}function Fn(e,t){return e.filter(s=>!ts(s.name,t))}function Ie(e){try{let t=e??Ot();return new Set(t.filter(s=>s.config?.sablier?.enable&&s.config?.sablier?.deferStart).map(s=>s.name))}catch{return new Set}}function Fe(e,t=new Set){let n=JSON.parse(e).items??[],r=[],o=0,i=0,a=0;for(let c of n){let d=c.metadata?.name??"unknown",l=c.status?.updateStatus??"",u=zt(c.status),h=u==="error"&&c.status?.runtimeStatus==="ok",P=(c.status?.buildHistory?.[0]?.error??"").trim()||(h?Kt:"");if(l==="error"||u==="error"){r.push({name:d,updateStatus:l,runtimeStatus:u,error:P.replace(/\s+/g," ").slice(0,800)});continue}if(l==="ok"&&(u==="ok"||u==="not_applicable")){a+=1;continue}d!=="(Tiltfile)"&&Jt(l,u)&&(t.has(d)?i+=1:o+=1)}return{failures:r,pendingCount:o,deferredCount:i,okCount:a,total:n.length}}var Mn=/failed to resolve source metadata for docker\.io\/library\/([A-Za-z0-9._-]+-l[1-4](?:-[a-z]+)*)(?::[^\s:]+)?:/i;function Me(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)],c=a.slice(0,4).join(", "),d=a.length>4?` (+${a.length-4} more)`:"";return`private registry ConnectionRefused for ${c}${d} \u2014 Verdaccio (:4873) is down or unreachable from the build`}let r=t.match(Mn);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`,c=i?` for ${i}`:"";return`compose run failed because image is missing (${a})${c} \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 Xt(e){return/ConnectionRefused downloading package manifest|Verdaccio|private registry|dependency install failed during ImageBuild|install-deps\.sh|bun install/i.test(e)}function Le(e=m()??process.cwd()){let t=B(e,".tdk",_);if(!je(t))return!1;try{let s=JSON.parse(Oe(t,"utf-8"));return s.optional_infra?.verdaccio===!0||Object.values(s.phases??{}).some(n=>(n.enabledStacks??[]).includes("verdaccio"))}catch{return!1}}function ss(e){for(let t of[B(e,".npmrc"),B(e,R)])if(je(t))try{let s=Oe(t,"utf-8");if(/:4873\b/.test(s)||/verdaccio/i.test(s))return!0}catch{}return!1}function Ln(e=m()??process.cwd()){return Le(e)||ss(e)}function He(e=X,t=m()??process.cwd(),s=process.env.VERDACCIO_URL??process.env.NPM_REGISTRY_URL??On,n=!0){if(!n&&!ss(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(!Ln(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=Y(e,"docker",["ps","--format","{{.Names}}"],"docker ps --format '{{.Names}}'",{stdio:"pipe",encoding:"utf-8",timeout:z});r=/verdaccio/i.test(a)}catch{}let o=!1,i="";try{let a=process.platform==="win32"?Qt("curl.exe",["-fsS","-o","NUL","-w","%{http_code}","--max-time","2",s],{stdio:"pipe",encoding:"utf-8",timeout:Yt+1e3,windowsHide:!0}).trim():e(`curl -fsS -o /dev/null -w '%{http_code}' --max-time 2 ${es(s)}`,{stdio:"pipe",encoding:"utf-8",timeout:Yt+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 Ue(e=X,t=K(),s=An){let n=Ae(t),r="";try{r=Y(e,"docker",["ps","--format","{{.Names}}\\t{{.Ports}}"],"docker ps --format '{{.Names}}\\t{{.Ports}}'",{stdio:"pipe",encoding:"utf-8",timeout:z})}catch{return{name:"Ingress Ports",didPass:!0,isSkipped:!0,message:"Docker not available - skipped ingress port check"}}let o=In(r,s),i=Fn(o,n);if(i.length===0){let c=o.filter(d=>ts(d.name,n));return c.length>0?{name:"Ingress Ports",didPass:!0,message:`Ingress ports ${s.join("/")} held by this project's Traefik (${c.map(d=>d.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(c=>{let d=c.publishedPorts.join(", ");return`${c.name} (host ports ${d})`}).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 Hn(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 Be(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 ${g(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 ${g(e.length,"service")} responding on /health`};let n=s.map(o=>`${o.name} (${Hn(o)})
6
+ ${o.url}`).join(`
7
+ `),r=s.some(o=>o.status===404);return{name:"Service Health",didPass:!1,message:`${g(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 Ge(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 ${g(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:`${g(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 ns(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:`${g(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:`${g(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 We(e=X){let t="";try{t=Y(e,"tilt",["get","uiresources","-o","json"],"tilt get uiresources -o json",{stdio:"pipe",encoding:"utf-8",timeout:z})}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=Fe(t,Ie())}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=Bn(s.failures),o=n.slice(0,20),i=n.length-o.length,a=o.map(p=>({failure:p,why:Wn(p,e)})),c=a.map(({failure:p,why:L})=>`${p.name}: ${L}`).join(`
14
+ `),d=i>0?`
15
+ \u2026and ${g(i,"more failed resource")}`:"",l=s.pendingCount>0?`
16
+ ${g(s.pendingCount,"resource")} still pending/not started \u2014 often blocked by the failures above.`:"",u=s.deferredCount>0?`
17
+ ${g(s.deferredCount,"resource")} intentionally deferred (sablier.deferStart) \u2014 not started until first request, unrelated to the failures above.`:"",h=n.some(p=>/port is already allocated/i.test(p.error)),S=n.some(p=>Xt(p.error)||Xt(Me(p.error))),P=a.some(({why:p})=>/Kafka broker unreachable|kafka:9092/i.test(p)),k="Open the Tilt UI URL printed by flisk up (default port "+vt.tiltUi+" when TILT_PORT is unset), inspect the red resources, fix the listed errors, then `tilt trigger <resource>` or re-run `flisk up`.";return h?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.":S?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.":P&&(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 ${g(s.failures.length,"failed resource")}:
18
+ ${c}${d}${l}${u}`,fix:k}}var Un=/^(traefik|postgres|nats|infisical|verdaccio|proxy)([.-]|$)/i;function Zt(e){return Un.test(e)}function Bn(e){return[...e].sort((t,s)=>{let n=Zt(t.name)?0:1,r=Zt(s.name)?0:1;return n!==r?n-r:t.name.localeCompare(s.name)})}function Gn(e,t=X,s=K()){try{let n=Y(t,"docker",["ps","-a","--format","{{.Names}}"],"docker ps -a --format '{{.Names}}'",{stdio:"pipe",encoding:"utf-8",timeout:z}).split(`
19
+ `).map(d=>d.trim()).filter(Boolean),r=`-autogenerated-${e}-1`,o=n.find(d=>d===e)??n.find(d=>d.startsWith(`${s}-`)&&d.endsWith(r))??n.find(d=>d.endsWith(r))??n.find(d=>d.includes(e));if(!o)return null;let i=Y(t,"docker",["logs","--tail","120",o],`docker logs --tail 120 ${es(o)} 2>&1`,{stdio:"pipe",encoding:"utf-8",timeout:z});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 d=[...i.matchAll(/"path"\s*:\s*\[\s*"([^"]+)"\s*\]/g)].map(u=>u[1]),l=[...new Set(d)].slice(0,6);return l.length>0?`runtime crash: ZodError missing required config/env: ${l.join(", ")}`:"runtime crash: ZodError during config/env validation"}let c=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(c)return`runtime crash: ${c.replace(/\s+/g," ").trim().slice(0,180)}`}catch{return null}return null}function Wn(e,t=X){return e.error?Me(e.error):e.runtimeStatus==="error"?Gn(e.name,t)??"runtime error (container crashed or unhealthy \u2014 check Tilt/docker logs)":e.updateStatus||e.runtimeStatus||"unknown error"}var Vn=/\.(ts|tsx|mts|js|mjs|cjs)$/,qn=new Set(["node_modules","dist",D,"tests","__tests__"]);function rs(e){let t=[];for(let s of jn(e,{withFileTypes:!0}))s.isDirectory()?qn.has(s.name)||t.push(...rs(B(e,s.name))):Vn.test(s.name)&&!/\.(test|spec)\./.test(s.name)&&t.push(B(e,s.name));return t}function Jn(e){let t=e?.healthCheckPath||"/health";return{container:t,traefik:e?.traefik?.healthCheck||t}}function Kn(e){let t=[];for(let s of e){if(!I(s.config?.appType))continue;let n=B(s.path,"src");if(!je(n))continue;let r=rs(n);if(r.length===0)continue;let o=r.map(d=>Oe(d,"utf-8")),{container:i,traefik:a}=Jn(s.config),c=i===a?[{path:i,usedBy:"container and Traefik healthchecks"}]:[{path:i,usedBy:"container healthcheck"},{path:a,usedBy:"Traefik healthcheck"}];for(let{path:d,usedBy:l}of c){let u=["'",'"',"`"].map(h=>`${h}${d}${h}`);o.some(h=>u.some(S=>h.includes(S)))||t.push({name:s.name,healthPath:d,usedBy:l})}}return t}function os(e=m()??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=Kn(s);return n.length===0?{name:"Health Routes",didPass:!0,message:`All ${g(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 Xn=Yn(zn),Zn=1e4,Qn=5,is=10*6e4,er=3,tr=200,sr=async e=>{let{stdout:t,stderr:s}=await Xn("docker",e,{encoding:"utf-8",timeout:Zn,windowsHide:!0});return`${t}${s}`};function nr(e,t){let s=Ae(t).toLowerCase(),n=e.replace(/-/g,"_").toLowerCase();return n===s||n.startsWith(`${s}_`)}function rr(e,t=Date.now()){if(e.status==="restarting")return!0;if(e.restartCount<Qn)return!1;if(e.status==="running"){let n=Date.parse(e.startedAt);return Number.isNaN(n)||t-n<is}let s=Date.parse(e.finishedAt??"");return e.exitCode!==0&&!Number.isNaN(s)&&t-s<is}function or(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 ir(e){let t=[];for(let s of e.split(/\r?\n/)){let[n,r,o,i,a,c]=s.split(" ");!n||r===void 0||t.push({name:n.replace(/^\//,""),restartCount:Number(r)||0,status:o??"",startedAt:i??"",exitCode:Number(a)||0,finishedAt:c??""})}return t}async function as(e,t=[],s=sr,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,h])=>u&&h&&nr(h,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=ir(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=>rr(l,n));if(a.length===0)return{name:r,didPass:!0,message:"No project container is crash-looping"};let c=[],d=new Set;for(let l of a){let u="";try{u=await s(["logs","--tail",String(er),l.name])}catch{}let h=oe(u,t).split(/\r?\n/).map(P=>P.trim().slice(0,tr)).filter(Boolean),S=or(u,l);S&&d.add(S),c.push([`${l.name}: ${l.status}, restarted ${l.restartCount} times`,...h.map(P=>` | ${P}`)].join(`
22
+ `))}return{name:r,didPass:!1,message:`${a.length} container${a.length===1?" is":"s are"} crash-looping:
23
+ ${c.join(`
24
+ `)}`,fix:[...d,"Read the full log: docker logs <container>"].join("; ")}}import{execFile as yr}from"node:child_process";import{realpathSync as fs,statfsSync as br}from"node:fs";import{homedir as Sr}from"node:os";import{join as Pr}from"node:path";import{promisify as wr}from"node:util";import{statfsSync as ar}from"node:fs";import{homedir as cr}from"node:os";var ue="Disk Space",dr=1024**3,lr=2,Ve=10,cs=["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 ds(e=ar,t=cr()){let s;try{let r=e(t);s=Number(r.bavail)*Number(r.bsize)/dr}catch{return{name:ue,didPass:!0,isSkipped:!0,message:"Could not read free disk space"}}let n=`${s.toFixed(1)} GB free`;return s<lr?{name:ue,didPass:!1,message:`${n}: Docker cannot build or start containers`,fix:cs}:s<Ve?{name:ue,didPass:!1,isWarning:!0,message:`${n}: image builds may fail`,fix:cs}:{name:ue,didPass:!0,message:n}}var ur="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 ls(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:ur}}import{execFileSync as pr}from"node:child_process";var qe=(e,t)=>pr(e,t,{encoding:"utf-8",stdio:"pipe",windowsHide:!0}),us=["traefik-public","traefik-private","backend","database","infisical-network","verdaccio-network","proxy"];function Je(e){let t=e.replace(/-/g,"_");return us.map(s=>`${t}_${s}`)}function ps(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 Ke(e,t){for(let s of us)if(e.endsWith(`_${s}`)){let n=e.slice(0,-(s.length+1));if(t.has(n))return n}return null}function Yi(e,t=qe){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 Je(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 pe(e,t=process.platform,s=qe){if(t==="win32")return[];let n;try{n=s("ps",["-axo","pid=,command="])}catch{return[]}let r=[];for(let o of n.split(/\r?\n/)){let i=/^\s*(\d+)\s+(.*)$/.exec(o);if(!i)continue;let a=i[2]??"",c=(a.split(/\s+/)[0]??"").split("/").at(-1),d=` -f ${e}`,l=a.indexOf(d),u=a[l+d.length];c==="tilt"&&/^\S+\s+up\s/.test(a)&&l>0&&(u===void 0||u===" ")&&r.push(Number(i[1]))}return r}function Xi(e,t=process.platform,s=qe){let n=pe(e,t,s);for(let r of n)try{s("kill",["-TERM",String(r)])}catch{}return n}async function Zi(e,t=8e3,s=pe){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 fr}from"node:child_process";function ze(e){return new Promise(t=>{fr($("tilt")??"tilt",["get","uiresources","-o","json","--port",String(e)],{timeout:15e3,maxBuffer:16*1024*1024},(s,n)=>t(s?null:n))})}function mr(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 hr(e){return(JSON.parse(e).items??[]).filter(t=>t.status?.disableStatus?.state!=="Disabled").flatMap(t=>t.metadata?.name?[t.metadata.name]:[])}function gr(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 kr(e,t,s){let n=Fe(mr(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:hr(e)};if(s&&s.length>0){let{missing:o,disabled:i}=gr(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 na(e,t={}){let s=t.timeoutMs??Number(process.env.TDK_UP_READY_TIMEOUT_MS??9e5),n=t.intervalMs??2e3,r=t.fetchJson??ze,o=t.deferred??Ie(),i=Date.now()+s,a={ready:!1,failures:[],pending:0,timedOut:!1,enabled:[]};for(;;){let c=await r(e);if(c)try{let d=kr(c,o,t.expected);if(a=d.result,d.settled||a.failures.length>0&&t.isStalled?.(c))return a}catch{}if(Date.now()>=i)return{...a,ready:!1,timedOut:!0};await new Promise(d=>setTimeout(d,n))}}var fe=wr(yr),vr=15e3,xr=/^tdk_doctor_probe_(\d+)$/,$r=async e=>{let{stdout:t}=await fe("docker",e,{encoding:"utf-8",timeout:vr,windowsHide:!0});return t};function Ye(e){return String(e.stderr??e).trim().split(/\r?\n/)[0]??""}var Tr=120;function Er(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 Nr(e,t=ze,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 Dr(e){if(process.platform==="win32")return"unknown";try{let{stdout:t}=await fe("ps",["-p",String(e),"-o","etime="],{encoding:"utf-8",timeout:5e3}),s=Er(t);if(s===null||s<Tr)return"unknown";let{stdout:n}=await fe("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 Nr(r)?"healthy":"stale"}catch{return"unknown"}}function Rr(e=$r){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(Ye(s))}},freeDiskGib(){try{let t=br(Sr());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(Ye(s))}},async tiltStatus(t){return Dr(t)},stopProcess(t){process.kill(t,"SIGTERM")},isProcessAlive(t){try{return process.kill(t,0),!0}catch(s){return s.code==="EPERM"}}}}var ms=Rr();async function hs(e,t=ms,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<Ve){let{buildCache:l,danglingImages:u}=await t.reclaimable(),h=`${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:`${h}; ${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:`${h}; ${u} untagged image${u===1?"":"s"}`})}let c=new Set(e?Je(e):[]),d=ps(i.map(l=>l.name));for(let l of i){let u=xr.exec(l.name),h,S,P="unused network";if(u)h="probe",S="Orphaned probe networks";else if(c.has(l.name))h="project",S="Docker networks";else if(s.machine&&Ke(l.name,d))h="machine",S="Docker networks",P=`unused network of project "${Ke(l.name,d)}"`;else continue;let k={id:`remove-network:${l.name}`,check:S,scope:h,command:`docker network rm ${l.name}`,status:"planned",reason:P};l.containers>0?(k.status="skipped",k.reason=`${l.containers} container(s) still attached`):h==="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 gs(e,t,s=ms){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:Ye(i)})}}return n}function ks(e){return e.some(t=>t.status==="failed")}async function Cr(e){try{let{stdout:t}=await fe(e,["--version"],{encoding:"utf-8",timeout:5e3,windowsHide:!0});return t.trim().split(/\r?\n/)[0]||null}catch{return null}}async function _r(e=$t("flisk"),t=Cr){let s=new Set,n=[];for(let r of e){let o=r;try{o=fs(r)}catch{}s.has(o)||(s.add(o),n.push({path:r,version:await t(r)}))}return n}async function ys(e){let t=e??await _r();if(t.length<=1)return{name:"Flisk installs",didPass:!0,message:"One flisk install on PATH"};let s=t.map(r=>`${r.path} (${r.version??"version unknown"})`).join(", "),n=new Set(t.map(r=>r.version));return{name:"Flisk installs",didPass:!1,isWarning:!0,message:`${t.length} flisk installs on PATH${n.size>1?" with different versions":""}: ${s}`,fix:"Keep one: remove the others, or run flisk upgrade. The first on PATH is the one your shell runs; tools that launch /usr/local/bin/flisk directly may use another"}}function bs(e,t=pe){let s=new Set([e]);try{s.add(fs(e))}catch{}let n=new Set;for(let r of s)for(let o of t(Pr(r,".tdk",".tdk-out","Tiltfile")))n.add(o);return[...n]}var Xe=1;function jr(e,t=[]){return{schemaVersion:Xe,data:e,errors:t}}function Or(e){return e instanceof J?{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 ga(e){let t=Or(e);console.log(JSON.stringify(jr(null,[t.error]))),console.error(t.error.message),process.exit(t.exitCode)}async function Ps(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 Ss(e){let t=e.find(s=>s.name===x);return t?t.didPass:null}function M(e,t,s=[],n,r){return{schemaVersion:Xe,data:{ready:s.length===0&&e.every(o=>o.didPass||o.isSkipped||o.isWarning),inProject:t,checks:e,...r?{host:{...r,containerRuntimeReachable:Ss(e),canUp:r.canUp&&Ss(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 ws(e){return e.errors.length>0?2:e.data.ready?0:1}import{existsSync as Qe,readFileSync as vs}from"node:fs";import{dirname as Ar,join as Ze,normalize as Ir}from"node:path";function Fr(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 xs(e,t,s){return t==="ext://tdk-cli"?Ze(s,".tdk",".tdk-out","tdk-cli-ext","Tiltfile"):t.startsWith(".")||!t.includes("://")&&!t.startsWith("@")?Ir(Ze(Ar(e),t)):null}function Mr(e,t,s){let n=[],r=/^load\s*\(([\s\S]*?)\)/gm;for(let o of t.matchAll(r)){let c=(o[1]??"").match(/["']([^"']+)["']/)?.[1];if(!c)continue;let d=xs(e,c,s);d&&(Qe(d)||n.push(`${e}: ${c} -> ${d}`))}return n}function Lr(e,t,s){let n=[],r=/^load\s*\(([\s\S]*?)\)/gm;for(let o of t.matchAll(r)){let c=(o[1]??"").match(/["']([^"']+)["']/)?.[1];if(c){let d=xs(e,c,s);d&&n.push(d)}}return n}function Hr(e,t){let s=new Set,n=[e];for(;n.length>0;){let r=n.pop();if(!r||s.has(r)||!Qe(r))continue;s.add(r);let o=vs(r,"utf-8");for(let i of Lr(r,o,t))s.has(i)||n.push(i)}return Array.from(s).sort()}function $s(){let e=m()??process.cwd(),t=Ze(e,".tdk",".tdk-out","Tiltfile");if(!Qe(t))return{name:"Starlark Load Exports",didPass:!0,isSkipped:!0,message:"No generated Tiltfile to check"};let s=[],n=[],r=Hr(t,e);for(let i of r){let a=vs(i,"utf-8"),c=Fr(a);c.length>0&&s.push(`${i}: ${c.join(", ")}`);for(let d of Mr(i,a,e))n.push(d)}if(s.length===0&&n.length===0)return{name:"Starlark Load Exports",didPass:!0,message:`${g(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 zr,execSync as Yr}from"node:child_process";import{existsSync as tt,readdirSync as Is,readFileSync as Q}from"node:fs";import{basename as Xr,dirname as Zr,join as T,relative as Z}from"node:path";function Ta(e){return Ts(e,!1)}function Ea(e){return Ts(e,!0)}function Ts(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 Es={id:"bun",label:"Bun + Hono",installHint:"bun install"};var Ur="go run .",Ns={id:"go",label:"Go 1.23 (net/http)",devCommand:Ur,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 Br="node --watch src/index.js",Ds={id:"node",label:"Node.js 22",devCommand:Br,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 Gr="uvicorn main:app --app-dir src --host 0.0.0.0 --port ${PORT:-4000} --reload --reload-dir src",Rs={id:"python",label:"Python 3.12 + FastAPI",devCommand:Gr,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 Wr="cargo run",Cs={id:"rust",label:"Rust (axum)",devCommand:Wr,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 _s="bun",G={bun:Es,python:Rs,go:Ns,rust:Cs,node:Ds};function Vr(e){let t=(e??_s).trim().toLowerCase(),s=Object.hasOwn(G,t)?G[t]:void 0;if(!s){let n=Object.keys(G).join(", ");throw new J(`Unknown backend language "${e}". Supported languages: ${n}.`,[`Use one of: ${n}`,`Omit --language to use ${_s}`])}return s}function La(e,t){if(e!=="backend"){if(t!==void 0)throw new J("--language can only be used with --type backend.",["Add --type backend, or drop --language for this resource type"]);return}return Vr(t)}import{exec as qr,execFile as Jr}from"node:child_process";import{promisify as js}from"node:util";var Kr=js(qr),C=async(e,t)=>{if(process.platform==="win32"){let n=e.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g)??[],[r,...o]=n.map(c=>c.startsWith('"')||c.startsWith("'")?c.slice(1,-1):c);if(!r)throw new Error("Command is empty");let i=$(r)??r,{stdout:a}=await js(Jr)(i,o,{encoding:"utf-8",timeout:t,windowsHide:!0,shell:!1});return a}let{stdout:s}=await Kr(e,{encoding:"utf-8",timeout:t});return s};function Os(e){let t=e;return t?.code==="ETIMEDOUT"||t?.killed===!0}var he=1e4,Qr=/\.(?:[cm]?[jt]sx?|vue)$/,eo=/(?:\.test\.|\.spec\.|\/tests?\/|\/__tests__\/)/,to=7,so=new Set(["node_modules",D,"dist","tests","__tests__"]);function Fs(e){try{let t=JSON.parse(Q(T(e,".tdk",_),"utf-8"));return typeof t?.project?.name=="string"?t.project.name:void 0}catch{return}}function no(e){try{let t=JSON.parse(Q(e,"utf-8")).params;return t&&typeof t=="object"?t:{}}catch{return{}}}function et(e){try{let t=JSON.parse(Q(T(e,R),"utf-8"));return t&&typeof t=="object"?t:{}}catch{return{}}}function As(e){if(typeof e!="string")return;let t=e.match(/(?:^|[^0-9])(\d+)(?:\.|$)/);return t?Number(t[1]):void 0}function ro(e){let t=ke(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 oo(e){let t=T(e,D,"prisma.config.autogenerated.ts"),n=[T(e,"prisma.config.ts"),t].find(i=>tt(i));if(!n)return["missing prisma.config.ts or generated Prisma config"];let o=(ke(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 Ms(e=m()??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:`${g(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=et(o.path).dependencies,c={...et(o.path).devDependencies??{},...i??{}},d=As(c.prisma),l=As(c["@prisma/client"]);if(d===void 0||l===void 0?n.push(`${o.name}: prisma and @prisma/client are required`):(d!==l||d!==to)&&n.push(`${o.name}: prisma packages must both be major 7`),n.push(...ro(T(o.path,"prisma","schema.prisma")).map(h=>`${o.name}: ${h}`)),n.push(...oo(o.path).map(h=>`${o.name}: ${h}`)),(o.config?.appType??o.type)==="migrator")o.config?.dependsOn?.some(S=>S==="postgres"||S===Pt)||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 S=et(o.path).scripts;Object.entries(S??{}).some(([k,p])=>Js.has(k)&&typeof p=="string"&&/prisma\s+migrate/.test(p))&&n.push(`${o.name}: API start script must not run prisma migrate`);let P=T(o.path,o.config?.dockerfile??"Dockerfile");me(P,!0)&&n.push(`${o.name}: API image/startup must not run Prisma migrations`)}}return s.length>0&&!Re(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:`${g(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 Ls(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 io(e){let t=e.config?.language;return typeof t=="string"&&Object.hasOwn(G,t)&&G[t].createFiles!==void 0}function ao(e){return(e.config?.appType??e.type)===re}function Hs(e=m()??process.cwd()){let t=b(e).filter(s=>!ao(s)&&!io(s)&&!tt(T(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:`${g(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 ge(e=m()??process.cwd(),t=b(e)){let s=new Map;for(let o of t){let i=s.get(o.name)??[];i.push(Z(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:`${g(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 co(e){let t=e.config?.appType;return I(t)?!0:t===re&&e.config?.exposeViaProxy!==!1}function Us(e=m()??process.cwd()){let t=new Map;for(let r of b(e)){let o=r.config?.port;if(typeof o!="number"||!co(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:`${g(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 lo=/https?:\/\/([a-z][a-z0-9-]*):(\d+)/g;function Bs(e=m()??process.cwd()){let t=b(e),s=Ls(t),n=new Map([...s].map(([o,i])=>[i,o])),r=[];for(let o of t)for(let[i,a]of Object.entries(no(o.configPath)))for(let[,c,d]of String(a).matchAll(lo)){let l=Number(d),u=s.get(c);u!==void 0&&u!==l?r.push(`${o.name} param ${i}: ${c}:${l}, but ${c} listens on ${u}`):(c==="localhost"||c==="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:`${g(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 st(e){let t=[],s;try{s=Is(e,{withFileTypes:!0})}catch{return t}for(let n of s){let r=T(e,n.name);n.isDirectory()?so.has(n.name)||t.push(...st(r)):Qr.test(n.name)&&!eo.test(r)&&t.push(r)}return t}var uo=/(?:localhost|127\.0\.0\.1):(\d{2,5})\b/g,Gs=/^\s*(?:\/\/|\/\*|\*|<!--|#)/;function Ws(e=m()??process.cwd()){let t=new Map;for(let n of b(e)){let r=n.config;if(!(I(r?.appType)||r?.appType===re&&r.exposeViaProxy!==!1))continue;let i=Zr(n.path),a=r?.stack??Xr(i),c=`${i}\0${a}`,d=t.get(c)??{stack:a,resources:[]};d.resources.push(n),t.set(c,d)}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 c=new Map;for(let d of r){let l=d.config?.traefik?.[a];l&&c.set(l,[...c.get(l)??[],d.name])}for(let[d,l]of c)l.length>1&&s.push(`stack "${n}": ${l.sort().join(" and ")} both set traefik.${a} "${d}", 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 Vs(e=m()??process.cwd()){let t=b(e),s=new Map([...Ls(t)].map(([o,i])=>[i,o])),n=[];for(let o of t.filter(i=>i.config?.appType==="frontend"))for(let i of st(T(o.path,"src")))Q(i,"utf-8").split(`
390
+ `).forEach((a,c)=>{if(!Gs.test(a))for(let[,d]of a.matchAll(uo)){let l=s.get(Number(d));l&&n.push(`${Z(e,i)}:${c+1} calls localhost:${d} (${l})`)}});if(n.length===0)return{name:"Frontend backend URLs",didPass:!0,message:"No frontend calls a backend through a localhost port"};let r=Fs(e)??"<project>";return{name:"Frontend backend URLs",didPass:!1,message:`${g(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 qs=/\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/,Js=new Set(["start","dev","serve","prestart","predev","preserve"]),po=/\.(?:sh|bash)$/,fo=/^\s*(?:CMD|ENTRYPOINT)\b/i;function ke(e){try{return Q(e,"utf-8")}catch{return}}function mo(e){let t=ke(T(e,R));if(t===void 0)return[];let s={};try{s=JSON.parse(t)?.scripts??{}}catch{return[]}return Object.entries(s).filter(([n,r])=>Js.has(n)&&typeof r=="string"&&qs.test(r)).map(([n])=>`package.json "${n}" script`)}function me(e,t){let s=ke(e);return s===void 0?!1:s.split(`
393
+ `).some(n=>qs.test(n.replace(/["'`,[\]]+/g," "))&&!Gs.test(n)&&(!t||fo.test(n)))}function Ks(e=m()??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=T(r,s.config?.dockerfile??"Dockerfile");me(o,!0)&&t.push(`${s.name}: ${Z(e,o)} CMD or ENTRYPOINT`);let i=[];try{i=Is(r,{withFileTypes:!0})}catch{}for(let a of i){let c=T(r,a.name);a.isFile()&&po.test(a.name)&&me(c,!1)&&t.push(`${s.name}: ${Z(e,c)}`)}for(let a of st(T(r,"src")))me(a,!1)&&t.push(`${s.name}: ${Z(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:`${g(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 ye(e=m()??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(tt(T(e,"services","platform","messaging",wt)))return{name:"NATS broker",didPass:!0,message:`${g(t.length,"resource")} enable nats and services/platform/messaging/docker-compose.yml is present`};let s=(Fs(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 zs(e=m()??process.cwd()){let t=Re(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:c})=>`"${c}" (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:`${g(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 ho(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 Ys(e=m()??process.cwd(),t=Yr){let s;try{s=process.platform==="win32"?zr("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:he,windowsHide:!0}):t("ps -Ao pid=,command=",{encoding:"utf-8",timeout:he})}catch{return{name:"Tilt processes",didPass:!0,isSkipped:!0,message:"Could not list processes"}}let n=ho(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 Xs(e=C){let t=`tdk_doctor_probe_${process.pid}`;try{await e(`docker network create ${t}`,he)}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}`,he)}catch{}return{name:"Docker networks",didPass:!0,message:"Docker can create networks"}}import{relative as go}from"node:path";function be(e,t){return go(e,t.configPath)||t.configPath}function Zs(e){let t=e.config?.dependsOn;return t===void 0?[]:Array.isArray(t)&&t.every(s=>typeof s=="string")?t:null}function ko(e){let t=new Set(e.map(a=>a.name)),s=new Map(e.map(a=>[a.name,(Zs(a)??[]).filter(c=>t.has(c))])),n=new Map,r=new Map,o=[],i=a=>{r.set(a,"visiting"),o.push(a);for(let c of s.get(a)??[])if(r.get(c)==="visiting"){let d=o.slice(o.indexOf(c)),l=d.indexOf([...d].sort()[0]??c),u=[...d.slice(l),...d.slice(0,l)];n.set(u.join(">"),[...u,u[0]??c])}else r.has(c)||i(c);o.pop(),r.set(a,"done")};for(let a of[...s.keys()].sort())r.has(a)||i(a);return[...n.values()]}function nt(e=m()??process.cwd(),t=b(e)){let s=t.flatMap(n=>Zs(n)===null?[`${be(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:`${g(s.length,"invalid dependsOn","invalid dependsOn")}:
397
+ ${s.join(`
398
+ `)}`,fix:'Write "dependsOn" as an array of service names, for example ["postgres", "api"]'}}function rt(e=m()??process.cwd(),t=b(e)){let s=new Map(t.map(o=>[o.name,o])),n=ko(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?be(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"}:
399
+ ${r.join(`
400
+ `)}`,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 ot(e=m()??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?[]:[`${be(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:`${g(s.length,"invalid port")}:
401
+ ${s.join(`
402
+ `)}`,fix:'Set "port" to the port the service listens on, an integer from 1 to 65535'}}function it(e=m()??process.cwd(),t=!1,s=b(e)){let n=[],r=[];for(let i of s){let a=i.config?.schemaVersion;if(a===De)continue;let c=be(e,i);a===void 0?n.push(`${c} schemaVersion: missing`):r.push(`${c} schemaVersion ${JSON.stringify(a)}: this flisk supports ${De}`)}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:`${g(n.length+r.length,"service.json file")} without a supported schemaVersion:
403
+ ${[...n,...r].join(`
404
+ `)}`,fix:o.join(". ")}}function lc(e,t){let s=it(e,!1,t);s.didPass||(console.warn(y.yellow(`\u26A0 ${s.message}`)),s.fix&&console.warn(y.gray(` ${s.fix}`)))}function uc(e,t={},s=process.exit){let n=t.resources??b(e),r=[ge(e,n),nt(e,n),rt(e,n),ot(e,n)].filter(i=>!i.didPass);if(r.length===0)return;let o=r.map(i=>`${i.message}${i.fix?`
405
+ Fix: ${i.fix}`:""}`).join(`
406
+ `);t.onInvalid?.(o);for(let i of r)console.error(y.red(`\u2717 ${i.message}`)),i.fix&&console.error(y.gray(` Fix: ${i.fix}`));s(1)}import{readFileSync as yo}from"node:fs";import{join as bo}from"node:path";function Qs(e){let t=e.trim().match(/(\d+)\.(\d+)(?:\.(\d+))?/);return t?[Number(t[1]),Number(t[2]),Number(t[3]??0)]:null}function So(e){try{return JSON.parse(yo(bo(e,".tdk",_),"utf-8"))?.minTdkVersion}catch{return}}function en(e,t){let s=So(e);if(s===void 0)return{status:"none"};let n=typeof s=="string"?Qs(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=Qs(t),o=r!==null&&(()=>{for(let[a,c]of n.entries()){let d=r[a]??0;if(d!==c)return d>c}return!0})(),i=n.join(".");return o?{status:"ok",required:i}:{status:"too-old",required:i,message:`flisk ${t} is older than the ${i} this project requires (minTdkVersion)`,fix:"Run: flisk upgrade"}}var A=1e4,O={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"},sn="WSL2 detected. Use Docker Desktop WSL integration. Guide: docs/wsl2.md",nn="Native Windows landscape boot is unsupported. Use WSL2 Ubuntu with Docker Desktop integration. Guide: docs/wsl2.md",at=[0,25,0],H=[1,2,0];function Se(e,t){let s=ft(e);return s?mt(s,t):!1}function xo(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:`${sn} Project is on the WSL filesystem.`};let r=`${sn} 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 $o(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 To(e=process.env,t=!1){let s=(e.TDK_BIND_ADDRESS??"").trim();return $o(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 an(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 Eo(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 pt={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"},rn=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(pt)]);function No(e){return!!(e.requiresContainerRuntime||e.checkName&&rn.has(e.checkName)||e.name&&rn.has(e.name))}function j(e,t){let s=()=>t();return s.requiresContainerRuntime=!0,s.checkName=e,s}async function Do(e,t={}){let s=[],n=!!t.containerRuntimeFailed;for(let r of e){if(n&&No(r)){let i=r.checkName??(r.name&&pt[r.name]?pt[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===x&&!o.didPass&&(n=!0),!t.all&&!o.didPass&&!o.isSkipped&&!o.isWarning)break}return s}function Ro(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 gt(e){return Os(e)}function Co(e,t,s,n,r){return async(o=C)=>{try{return await o(t,A),{name:e,didPass:!0,message:s}}catch(i){return gt(i)?{name:e,didPass:!1,message:`${e} did not respond within ${A/1e3}s`,fix:r}:{name:e,didPass:!1,message:n,fix:r}}}}async function ct(e){try{return await C(e,A),!0}catch{return!1}}async function kt(){if(process.platform==="win32")try{return await C("docker ps",A),{name:x,didPass:!0,message:"Docker Desktop Linux container engine is running"}}catch{return{name:x,didPass:!1,message:"Docker is not running",fix:O.dockerDaemonDown}}let e=!!$("docker");try{return await C("docker ps",A),{name:x,didPass:!0,message:"Docker daemon is running"}}catch(s){if(gt(s))return{name:x,didPass:!1,message:"Docker daemon is not responding",fix:O.dockerDaemonDown}}let t=ls(await ct("pgrep -f com.docker.backend"));return t||(await ct("colima status")?{name:x,didPass:!0,message:"Colima (Docker runtime) is running"}:$("colima")?{name:x,didPass:!1,message:"Colima is installed but not running",fix:O.dockerDaemonDown}:await ct("podman ps")?{name:x,didPass:!0,message:"Podman is running"}:e?{name:x,didPass:!1,message:"Docker daemon is not running",fix:O.dockerDaemonDown}:{name:x,didPass:!1,message:"Docker is not running",fix:O.dockerMissing})}var ee=Co("Docker Compose","docker compose version","Docker Compose plugin available","Docker Compose plugin not found","Install Docker Compose: https://docs.docker.com/compose/install/");ee.requiresContainerRuntime=!0;ee.checkName="Docker Compose";var _o=[25,0,0],jo=[2,20,2];function ft(e){let t=e.trim().match(/(\d+)\.(\d+)(?:\.(\d+))?/);return t?[Number(t[1]),Number(t[2]),Number(t[3]??0)]:null}function mt(e,t){for(let[s,n]of t.entries()){let r=e[s]??0;if(r!==n)return r>n}return!0}async function te(e=C){let t=async a=>String(await e(a,A)).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=ft(s),o=ft(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 mt(r,_o)||i.push(`Docker Engine ${s} (need 25.0+)`),mt(o,jo)||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):
407
+ ${i.join(`
408
+ `)}`,fix:"Update Docker Desktop, or on Linux update docker-ce and the docker-compose-plugin package"}}te.requiresContainerRuntime=!0;te.checkName="Docker Versions";async function yt(e=C){let t;try{t=String(await e("tilt version",A)).trim()}catch{return{name:"Tilt CLI",didPass:!1,message:"Tilt CLI not found",fix:O.tiltMissing}}return Se(t,at)?{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${at.join(".")} floor`,fix:`Install Tilt v${at.join(".")} or newer: https://docs.tilt.dev/install.html`}}async function bt(e=C){let t;try{t=String(await e("docker info --format '{{.OSType}}'",A)).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"}}bt.requiresContainerRuntime=!0;bt.checkName="Docker OS";async function Oo(e=C){let t=m();if(!t)return{name:"Bun",didPass:!0,isSkipped:!0,message:"Not in a project - skipping Bun check"};if(!de(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",A)).trim();return Se(s,H)?{name:"Bun",didPass:!0,message:`Bun ${s} is available`}:{name:"Bun",didPass:!1,message:`Bun ${s||"version unknown"} is below the required ${H.join(".")} floor`,fix:`Install Bun ${H.join(".")} or newer: https://bun.sh/install`}}catch{return{name:"Bun",didPass:!1,message:"Bun is not available",fix:O.bunMissing}}}function Ao(){let e=m()??process.cwd(),t=Tt(e);if(t.missing.length>0)return{name:"Environment Variables",didPass:!1,message:`Missing required env variables: ${t.missing.join(", ")}`,fix:E(w(e,".env"))?`Edit .env and set these values:
409
+ ${t.missing.map(n=>`${n}=<value>`).join(`
410
+ `)}`:"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 Io(){let e=m()??process.cwd(),t=w(e,".tdk",".tdk-out"),s=$e.filter(n=>!E(w(t,n)));return s.length===0?{name:"Master Configs",didPass:!0,message:`${$e.join(", ")} found`}:{name:"Master Configs",didPass:!1,message:`Master configs missing: ${s.join(", ")}`,fix:"Run: flisk project"}}function Fo(e=xt()){let t=m();if(!t)return{name:"Flisk version",didPass:!0,isSkipped:!0,message:"Not in a project - skipping Flisk version check"};let s=en(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 Mo(){let e=m()??process.cwd(),t=_e(e),s=b(e).filter(r=>!le(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=>lt(ut(e,r.path))).join(", ");return{name:"Resource Discovery",didPass:!1,message:`${g(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 Lo=["install-deps.sh","bun-hoisted-symlink-fix.sh","prisma-bun-client-link-fix.sh","prisma-normalize-client.sh","infisical-entrypoint.sh"],Ho=/shared-platform-engineering\/docker-templates\/([\w.-]+)/g;function Uo(e){let t=new Set;for(let s of b(e)){let n=w(s.path,D);if(E(n)){for(let r of wo(n))if(!(!r.startsWith("Dockerfile")||r.endsWith(".dockerignore")))for(let o of W(w(n,r),"utf-8").matchAll(Ho))t.add(o[1])}}return[...t]}function Bo(){let e=m()??process.cwd(),t=[];E(w(e,R))||t.push(`${R} (workspace root manifest)`);let s=w(e,"shared-platform-engineering","docker-templates"),n=[];try{n=Uo(e)}catch{}for(let r of new Set([...Lo,...n]))E(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:
411
+ ${t.join(`
412
+ `)}`,fix:"Run `flisk project --yes` (or `flisk config regenerate`) with an updated Flisk. `flisk up` also refreshes these assets before starting Tilt."}}function Go(){let e=m()??process.cwd(),t=b(e),s=[];for(let n of t){let r=w(n.path,R);if(!E(r))continue;let o=n.config?.appType??"backend",i=Te[o]??Te.backend,a;try{a=JSON.parse(W(r,"utf-8")).scripts??{}}catch{s.push(`${n.name} (package.json is invalid JSON)`);continue}let c=i.filter(d=>!a[d]);c.length>0&&s.push(`${n.name}: missing "${c.join('", "')}"`)}return s.length===0?{name:"Startup Scripts",didPass:!0,message:"All services have required package.json scripts"}:{name:"Startup Scripts",didPass:!1,message:`Services missing required package.json scripts:
413
+ ${s.join(`
414
+ `)}`,fix:`Add the missing scripts to each service's package.json, e.g.:
415
+ "dev": "bun run src/index.ts",
416
+ "build": "tsc",
417
+ "start": "bun run dist/index.js"`}}function cn(e){if(e.startsWith("@"))return[e.split("/").slice(0,2).join("/")];let t=e.split("/")[0]??e;return[`@types/${t}`,t]}function dn(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(dn(e,r[1],s+1))return!0;return!1}function on(e){let t=cn(e);return e.includes("/")||e.startsWith("@")?t[t.length-1]:t[0]}var Wo={"@types/bun":"^1.4.2","@types/node":"^20.0.0"};function Vo(e,t){return(t.includes("bun")||e.has("@types/bun"))&&!e.has("@types/node")}function qo(){let e=m()??process.cwd(),t=b(e),s=[],n=new Set;for(let o of t){let i=w(o.path,R),a=w(o.path,D,"tsconfig.docker.autogenerated.json");if(!E(i)||!E(a))continue;let l=ht(a)?.compilerOptions?.types;if(!Array.isArray(l))continue;let u=ht(i),h=u?.scripts??{};if(!dn(h,"build"))continue;let S=new Set([...Object.keys(u?.devDependencies??{}),...Object.keys(u?.dependencies??{})]),P=l.filter(k=>typeof k=="string").filter(k=>!cn(k).some(p=>S.has(p)));for(let k of P)n.add(on(k));if(P.length>0){let k=P.map(p=>`"${p}" (needs ${on(p)})`).join(", ");s.push(`${o.name}: "types" lists ${k}`)}Vo(S,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=Wo[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:
418
+ ${s.join(`
419
+ `)}`,fix:`Add to each service's package.json devDependencies: ${r.join(", ")}`}}function ht(e){try{return JSON.parse(W(e,"utf-8"))}catch{return null}}function Jo(e){let s=ht(e)?.compilerOptions;return s?.allowSyntheticDefaultImports===!0||s?.esModuleInterop===!0}function Ko(){let e=m()??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){E(w(n.path,"public"))||s.push(`${n.name}: no public/ folder, but the Docker build copies it. Create it: mkdir -p ${lt(ut(e,w(n.path,"public")))} && touch ${lt(ut(e,w(n.path,"public",".gitkeep")))}`);let r=w(n.path,D,"Dockerfile.app.autogenerated"),o=w(n.path,D,"tsconfig.docker.autogenerated.json");if(E(r)){let i=W(r,"utf-8"),a=/\bEXPOSE\s+80\b/.test(i),c=n.config?.stack,d=c?w(e,"services",c,D,"docker-compose.app.autogenerated.yml"):"";if(a&&d&&E(d)){let l=W(d,"utf-8"),u=n.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),h=new RegExp(`traefik\\.http\\.services\\.${u}\\.loadbalancer\\.server\\.port=(\\d+)`),P=l.match(h)?.[1];P&&P!=="80"&&s.push(`${n.name}: nginx runtime exposes 80, but generated Traefik routes to ${P}`)}}if(E(o)&&!Jo(o)){let i=w(n.path,"src","main.tsx");if(E(i)){let a=W(i,"utf-8"),c=[/import\s+\w+\s+from\s+["']react["']/,/import\s+\w+\s+from\s+["']react-dom\/client["']/].filter(d=>d.test(a)).map(d=>d.source.includes("react-dom")?"react-dom/client":"react");c.length>0&&s.push(`${n.name}: Docker tsconfig does not allow synthetic default imports, but src/main.tsx default-imports ${c.join(" and ")}`)}}}return s.length===0?{name:"Frontend Docker Preflight",didPass:!0,message:`${g(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:
420
+ ${s.join(`
421
+ `)}`,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 zo=90,Yo=80;function Xo(e){return e.split(`
422
+ `).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 Zo=Object.assign(function(){let t;try{t=Po($("docker")??"docker",["stats","--no-stream","--format","{{.Name}},{{.MemPerc}},{{.CPUPerc}}"],{stdio:"pipe",encoding:"utf-8",timeout:A,windowsHide:process.platform==="win32"})}catch(o){return{name:"Container Resource Health",didPass:!0,isSkipped:!0,message:gt(o)?"Docker not responding - skipped container resource check":"Docker not running - skipped container resource check"}}let s=Xo(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>=zo&&o.cpuPct>=Yo);if(n.length===0)return{name:"Container Resource Health",didPass:!0,message:`${g(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(`
423
+ `);return{name:"Container Resource Health",didPass:!1,message:`${g(n.length,"container")} pinned near its memory limit while burning CPU -- likely stuck in a boot-time retry/fetch loop, not a normal crash:
424
+ ${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"}),Qo=5e3;async function ei(e,t){let s=m()??process.cwd(),n=Ne(b(s),t);return n.length===0?{name:"Service Health",didPass:!0,isSkipped:!0,message:"No routable services to ping"}:Be(await ie(n,e))}async function ti(e,t){let s=m()??process.cwd(),n=b(s),r=Ct(Rt(n,t),{timeoutSeconds:Math.ceil(e/1e3)});return r.length===0?Ge([]):(await ie(Ne(n,t),e)).some(i=>i.status!==void 0)?Ge(await jt(r,_t(s))):{name:"Service Smoke",didPass:!0,isSkipped:!0,message:"No services responded - skipped smoke checks"}}async function si(e,t){let s=m()??process.cwd(),n=b(s),r=Dt(n,t);return r.length===0?{name:"Advertised Endpoints",didPass:!0,isSkipped:!0,message:"No routable services to check"}:ns(await ie(r,e))}function ni(e,t){if(e.length===0){console.log(`${y.green("\u2713")} Nothing to repair
425
+ `);return}for(let s of e){let n=s.status==="planned"?`${y.cyan("would run")}`:s.status==="applied"?y.green("ran"):s.status==="failed"?y.red("failed"):y.gray("skipped"),r=s.status==="planned"?"":` (${s.reason})`;console.log(`${n}: ${s.command}${r}`)}t&&console.log(y.gray(`
426
+ Dry run: nothing was changed.`)),console.log("")}function dt(e){for(let t of an(e))!t.didPass&&!t.isSkipped&&!t.isWarning?(console.log(`${y.red("\u2717")} ${t.message}`),t.fix&&console.log(`${y.blue("\u2139")} Fix: ${t.fix}`)):t.isWarning?(console.log(`${y.yellow("\u26A0")} ${y.yellow(t.message)}`),t.fix&&console.log(`${y.blue("\u2139")} Fix: ${t.fix}`)):t.isSkipped?(console.log(`${y.gray("\u25CB")} ${y.gray(t.message)}`),t.fix&&console.log(`${y.blue("\u2139")} ${t.fix}`)):console.log(`${y.green("\u2713")} ${t.message}`)}function ri(e,t,s,n={},r){let o=r??[...e,...t];n.all?(console.log(y.bold("Machine")),dt(e),console.log(`
427
+ ${y.bold("Project")}`),s?t.length>0&&dt(t):console.log(`${y.gray("\u25CB")} ${y.gray("Not in a Flisk project, so project checks were skipped")}`),console.log(""),console.log(Ro(o))):(dt(o),console.log(""),o.every(a=>a.didPass||a.isSkipped||a.isWarning)&&!s&&(console.log(`${y.gray("\u25CB")} ${y.gray("Not in a Flisk project, so project checks were skipped")}`),console.log("")))}var oi=new vo("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),oi.opts().json&&console.log(JSON.stringify(M([],!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(Qo)).action(async e=>{let t=Number(e.pingTimeout);if(!/^\d+$/.test(e.pingTimeout)||!Number.isSafeInteger(t)||t<=0){let f="--ping-timeout must be a positive integer number of milliseconds";e.json&&console.log(JSON.stringify(M([],!1,[{code:"USAGE",message:f}]))),console.error(f),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 f=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(M([],!1,[{code:"USAGE",message:f}]))),console.error(f),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=Ut();if(process.platform==="win32"){if(e.json){let f=null;try{f=await At()}catch{}console.log(JSON.stringify(M([{name:"Native Windows support",didPass:!1,message:nn,fix:"Use WSL2 Ubuntu with Docker Desktop integration. Guide: docs/wsl2.md"}],!!m(),[],f,{...r,canUp:!1})))}console.error(nn),process.exit(1);return}if(r.kind==="webcontainer"){let f=M([{name:"Host",didPass:!1,message:Ce,fix:`Use a machine with Docker. Guide: ${ce}`}],!!m(),[],void 0,r);e.json&&console.log(JSON.stringify(f)),console.error(Ce),process.exit(1);return}e.json||(console.log(`
428
+ ${y.bold("\u{1F50D} Flisk Doctor")}
429
+ `),console.log(`Checking environment...
430
+ `));let o=m(),i;if(e.fix){try{let f;if(o)try{f=Mt(o).project.name}catch{}let v=o?bs(o):[],we=await hs(f,void 0,{tiltPids:v,machine:e.scope==="machine"});i=await gs(we,{dryRun:e.dryRun,confirm:e.yes||!e.json&&process.stdin.isTTY?async N=>e.yes||await Lt({message:`Run \`${N.command}\` (${N.check}, ${N.reason})?`}):void 0})}catch(f){i=[{id:"plan-fixes",check:"Docker networks",scope:"project",command:"docker network ls",status:"failed",reason:`could not list Docker networks: ${(f instanceof Error?f.message:String(f)).split(/\r?\n/)[0]}`}]}e.json||ni(i,e.dryRun)}let a,c;try{a=await ae(o??process.cwd())}catch(f){a=null,c=f instanceof Error?f.message:String(f)}let d=[()=>a?{name:"Host Ports",didPass:!0,message:`HTTP ${a.ingressHttp}, HTTPS ${a.ingressHttps}, Postgres ${a.postgres}`}:{name:"Host Ports",didPass:!1,message:c??"Could not select host ports",fix:"Set TDK_HTTP_PORT, TDK_HTTPS_PORT, or TDK_POSTGRES_PORT to available host ports."},()=>a?Ue(tn,void 0,[a.ingressHttp,a.ingressHttps]):{name:"Ingress Ports",didPass:!1,message:"Ingress port plan is unavailable"},kt,()=>ds(),j("Docker OS",bt),yt,j("Docker Compose",ee),j("Docker Versions",te),Oo,()=>xo(m()??process.cwd(),e.strict),()=>To(process.env,e.strict),j("Docker Network Pool",()=>Xs()),()=>ys()],l=[()=>Fo(),Io,Bo,$s,Go,()=>os(),qo,Ko,Mo,()=>Hs(),()=>ge(),()=>nt(),()=>rt(),()=>ot(),()=>it(void 0,e.strict),()=>Us(),()=>Bs(),()=>Vs(),()=>Ws(),()=>ye(),()=>Ms(),()=>zs(),()=>Ks(),()=>Ys(),Ao,async()=>{let f=m()??process.cwd(),v=Le(f)?await Ft(f):!0;return He(tn,f,void 0,v)},j("Container Resource Health",Zo),j("Crash-looping containers",()=>{let f=m()??process.cwd(),v=[];try{v=Ee(f)}catch{return{name:"Crash-looping containers",didPass:!0,isSkipped:!0,message:"Could not read .env - skipped crash-loop check"}}return as(K(),v)}),j("Tilt Resources",We)];if(e.ping){let f=o?It(o,a?.ingressHttp):a?.ingressHttp;l.push(j("Service Health",()=>ei(t,f))),l.push(j("Service Smoke",()=>ti(t,f))),l.push(j("Advertised Endpoints",()=>si(t,f)))}let u=!!o,h=[],S=[],P,k=[];if(e.json||!e.all){let f=await Ps(d,u?l:[]);P=f.checks,k=f.errors}else{let f=async(N,wn=!1)=>{let vn=N.map(ne=>{let ve=async()=>{try{return await ne()}catch(xe){return k.push({code:"INTERNAL",message:xe instanceof Error?xe.message:String(xe)}),{name:ne.checkName??"Doctor check",didPass:!1,isSkipped:!1,message:"Check failed with an internal error"}}};return ve.requiresContainerRuntime=ne.requiresContainerRuntime,ve.checkName=ne.checkName,ve});return Do(vn,{all:!!e.all,containerRuntimeFailed:wn})};h=await f(d);let v=h.some(N=>!N.didPass&&!N.isSkipped&&!N.isWarning),we=h.some(N=>N.name===x&&!N.didPass);u&&(e.all||!v)&&(S=await f(l,we)),P=[...h,...S]}if(Bt(r.kind))for(let f of P)f.name===x&&!f.didPass&&(f.fix=Ht);let p=M(an(P),u,k,a,r);i&&(p.data.actions=i),i&&ks(i)&&(p.data.ready=!1);let U=ws(p),q=p.data.ready;if(e.json){let f;try{f=Ee(m()??process.cwd())}catch(v){if(!(v instanceof Et))throw v;console.log(JSON.stringify(M([],u,[...k,{code:"ENV_UNREADABLE",message:v.message}]))),console.error(v.message),process.exit(1)}console.log(JSON.stringify(Nt(p,f)));for(let v of k)console.error(oe(v.message,f));U!==0&&process.exit(U);return}for(let f of k)console.error(`${y.red("\u2717")} Doctor check failed: ${f.message}`);ri(h,S,u,e,P);let St=Eo(u,q);console.log(`${q?y.green(y.bold("\u2713")):y.red(y.bold("\u2717"))} ${St}`),U!==0&&process.exit(U)});function ln(e){return Se(e,H)}var se=`${H[0]}.${H[1]}+`;import{execFileSync as un}from"node:child_process";import{accessSync as pn,constants as fn,readdirSync as ii}from"node:fs";import{delimiter as ai,join as V}from"node:path";var F="flisk",mn="@flisk-sh/flisk",ci="https://github.com/flisk-sh/flisk",hn="@tdk-landscape/tdk-cli-core";function gn(e=F,t=process.env){let s=t.PATH??t.Path??"";for(let n of s.split(ai)){if(!n)continue;let r=[V(n,e),V(n,`${e}.cmd`),V(n,`${e}.exe`)];for(let o of r)try{return pn(o,fn.X_OK),!0}catch{}}return!1}function di(e=process.env){let t=e.HOME??e.USERPROFILE??"";if(!t)return"flisk-workspace";let s=V(t,"Documents");try{return pn(s,fn.F_OK),V(s,"flisk")}catch{return V(t,"flisk")}}function li(e){try{return ii(e).every(t=>t.startsWith("."))}catch{return!0}}function kn(e=process.env,t=process.cwd()){if(!gn(F,e))return`The \`${F}\` command is not on PATH (this run is not a global install). Install it with \`npm install -g ${mn}\`, then run \`${F} project --yes\`. If npm reports EEXIST for \`flisk\`, the old package still owns that command: run \`npm uninstall -g ${hn}\` first. The current release is published from ${ci}.`;if(li(t))return`Next: ${F} project --yes`;let s=di(e);return`Next: mkdir -p ${s} && cd ${s} && ${F} project --yes
431
+ (${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 sd(e=process.env){if(gn(F,e))return"present";let t=e.npm_execpath?.includes("bun")?"bun":"npm",s=t==="bun"?"bun remove -g":"npm uninstall -g";try{un(s,[hn],{stdio:"ignore",timeout:12e4})}catch{}try{return un(t,["install","-g",mn],{stdio:"inherit",timeout:3e5}),"installed"}catch{return"failed"}}var fi=["docker","compose","tilt"],Sn=["node","bun","ports"],Pn=["node",...fi,"bun","ports"];function mi(e,t){return{id:e,ok:t.didPass||!!t.isSkipped,message:t.message,fix:t.fix}}function bn(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 Pe(e,t,s){try{return mi(e,await t())}catch{return{id:e,ok:!1,message:s}}}function hi(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 gi(e){try{return b(e).some(t=>t.config?.featuresEnabled?.includes("prisma")??!1)}catch{return!1}}async function ki(e={}){let t=e.cwd??process.cwd(),s=e.scope??"runtime",n=m(t),r=!!n,o=[],i=process.versions.node;o.push({id:"node",ok:!bn(i),message:i,fix:bn(i)?`Install Node.js 22.12+ (current: ${i}). https://nodejs.org`:void 0}),s==="runtime"&&(o.push(await Pe("docker",kt,"Docker daemon is not running")),o.push(await Pe("compose",async()=>{let[p,L]=await Promise.all([ee(),te()]);return p.didPass?hi(L):p},"Docker Engine or Compose version check failed")),o.push(await Pe("tilt",yt,"Tilt CLI not found")));let a=n?de(b(n)):!0,c=!1,d=a?$("bun"):void 0;if(d)try{let p=yn(d,["--version"],{encoding:"utf-8",timeout:3e3}).trim();c=ln(p)}catch{}o.push(a?{id:"bun",ok:c,message:c?`Bun ${se} is available on PATH`:`Bun ${se} not found on PATH`,fix:c?void 0:"curl -fsSL https://bun.sh/install | bash"}:{id:"bun",ok:!0,message:"Bun not needed: no generated JS services"});try{let p=await ae(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 Pe("nats",()=>ye(n),"NATS broker check failed");if(p.ok||o.push(p),gi(n)){let L=!1;try{let U=JSON.parse(ui(pi(n,".tdk",_),"utf-8")),q=String(U?.project?.name??"").replace(/-/g,"_");q&&(L=yn($("docker")??"docker",["ps","--filter",`label=com.docker.compose.project=${q}`,"--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"?Sn:Pn,h=l.some(p=>u.includes(p.id)),S=l.some(p=>p.id==="bun"),P=l.length?h?s==="scaffold"?S?`Project setup blocked. Bun ${se} must be installed on PATH.
432
+ Fix the machine checks below.`:"Project setup blocked. Fix the machine checks below.":S?`Cold start blocked. Bun ${se} must be installed on PATH.
433
+ 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.
434
+ ${kn()}`;return{ok:l.length===0,inProject:r,items:l,header:P,footer:k}}function yi(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(`
435
+ `)}async function kd(e={}){let t=e.scope??"runtime",s=await ki({scope:t}),n=t==="scaffold"?Sn:Pn;s.items.some(o=>n.includes(o.id))&&(console.error(yi(s)),process.exit(1))}function yd(e=$){return{hasDockerCli:!!e("docker"),hasTiltCli:!!e("tilt")}}function bd(e){let t=[];return e.hasDockerCli||t.push(`Docker is not installed. ${O.dockerMissing}`),e.hasTiltCli||t.push(`Tilt is not installed. ${O.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{jr as a,Or as b,ga as c,Ta as d,Ea as e,G as f,Vr as g,La as h,Ms as i,ho as j,Ce as k,Ht as l,Ut as m,Bt as n,_e as o,le as p,Ti as q,Jt as r,zt as s,Ie as t,Fe as u,Me as v,Yi as w,Xi as x,Zi as y,ze as z,mr as A,kr as B,na as C,lc as D,uc as E,en as F,oi as G,hn as H,sd as I,fi as J,Sn as K,Pn as L,bn as M,hi as N,ki as O,yi as P,kd as Q,yd as R,bd as S};