@akanjs/cli 3.1.1-rc.17 → 3.1.1-rc.19

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 (78) hide show
  1. package/.build-stamp +1 -1
  2. package/CodeAgent-rsebcq9c.js +9 -0
  3. package/{CodeTui-0626gxqd.js → CodeTui-mpybfknz.js} +1 -1
  4. package/TunnelShare-da9qj2mh.js +14 -0
  5. package/{agent.command-hpza0pg9.js → agent.command-xc1mf4yz.js} +13 -13
  6. package/akanCode.js +7 -5
  7. package/{application.command-3a7q1hs2.js → application.command-frkm7n6t.js} +43 -11
  8. package/{applicationBuildRunner-s7yt71j4.js → applicationBuildRunner-r9nvz9ms.js} +5 -5
  9. package/buildBatch.proc.js +5 -5
  10. package/{cloud.command-4vg0pcea.js → cloud.command-gakbzmdj.js} +16 -15
  11. package/cloud.script-1krw7gjb.js +26 -0
  12. package/{code.command-fbntb67p.js → code.command-pvfczhpy.js} +6 -6
  13. package/commandManifest.json +1 -1
  14. package/{context.command-31rm54v0.js → context.command-cp6fstk3.js} +16 -16
  15. package/context.runner-hwq8pwrg.js +26 -0
  16. package/{devTui-q7k7bakd.js → devTui-evr3b35y.js} +1 -1
  17. package/{guideline.command-cv3by2ng.js → guideline.command-761yyxqb.js} +2 -2
  18. package/guidelines/conventions/core.md +4 -2
  19. package/incrementalBuilder.proc.js +3 -3
  20. package/{index-zre4m2ce.js → index-1qmfdbjf.js} +4 -4
  21. package/{index-rvynj5gz.js → index-3e0c4d9d.js} +1 -1
  22. package/{index-922k2zwq.js → index-40qsd2tg.js} +3 -3
  23. package/{index-js1gj6f6.js → index-4412550g.js} +8 -8
  24. package/{index-x5ecanqh.js → index-6c5h9egr.js} +2 -2
  25. package/{index-tdv66eah.js → index-6h6x9e1n.js} +4 -4
  26. package/{index-7zeb5r1p.js → index-6yvp6qcb.js} +9 -9
  27. package/{index-mt0wa941.js → index-88aq81dz.js} +3 -3
  28. package/index-9bv479q5.js +1 -0
  29. package/{index-1dhf8ymv.js → index-9h8a7w1c.js} +3 -3
  30. package/{index-3gccwenr.js → index-9jyxbbnh.js} +1 -1
  31. package/{index-0ht91675.js → index-9z3xf23k.js} +35 -177
  32. package/{index-9ndw5d8j.js → index-a675rkqs.js} +7 -7
  33. package/{index-wfczhj1z.js → index-a9sjjv6x.js} +1 -1
  34. package/{index-05nxx4m5.js → index-acta9x3j.js} +2 -2
  35. package/{index-12kzwak1.js → index-b2p3qq5f.js} +2 -2
  36. package/{index-f5adsa58.js → index-b3br6jhe.js} +4 -4
  37. package/{index-57q1ayd2.js → index-cb58gjk2.js} +79 -11
  38. package/{index-0zyatd10.js → index-d1c677h0.js} +2 -2
  39. package/{index-hm7x0c11.js → index-d2x0mxsa.js} +4 -4
  40. package/{index-mwj9q2ya.js → index-fjxwyj3f.js} +1 -1
  41. package/{index-3txrjt6n.js → index-gftc47rk.js} +2 -2
  42. package/{index-8s8b4eba.js → index-mgdzy0cz.js} +64 -4
  43. package/{index-0zwznvv1.js → index-nrstta07.js} +1 -1
  44. package/{index-64g9fsjy.js → index-nt5c22sg.js} +9 -1
  45. package/{index-5n5hds19.js → index-t8jp2d3r.js} +1016 -658
  46. package/index-tenw3mah.js +225 -0
  47. package/{index-6269mf2s.js → index-tnhh146g.js} +8 -8
  48. package/{index-kjrvwzav.js → index-tpv8j9kq.js} +3 -3
  49. package/{index-5kh9scvs.js → index-trz8jyh1.js} +3 -73
  50. package/{index-m6r88hhr.js → index-v8w6kjx4.js} +2 -2
  51. package/{index-et6ce601.js → index-vp77rhem.js} +1 -1
  52. package/{index-w134p86k.js → index-zb0807wt.js} +1 -1
  53. package/{index-hvv5rnaq.js → index-zvhy8nch.js} +2 -2
  54. package/index.js +23 -23
  55. package/{library.command-sh70fyvy.js → library.command-stwr5zyk.js} +3 -3
  56. package/{localRegistry.command-2nbyy84d.js → localRegistry.command-t42y3tn6.js} +15 -14
  57. package/{module.command-n0bmtzwy.js → module.command-q2tv04e1.js} +5 -5
  58. package/{package.command-7h9r51bz.js → package.command-zra0r49p.js} +3 -3
  59. package/package.json +2 -2
  60. package/{page.command-vjtpfbb1.js → page.command-s7trjw69.js} +3 -3
  61. package/{pipeline.command-c93se3ar.js → pipeline.command-7p7tagtq.js} +2 -2
  62. package/{primitive.command-a3075qp2.js → primitive.command-6snsrb00.js} +6 -6
  63. package/{projectTypecheck-sf9xwaga.js → projectTypecheck-0g5azdzh.js} +1 -1
  64. package/{quality.command-dw1y9hmy.js → quality.command-n5kk1z6x.js} +3 -3
  65. package/{repair.command-tg57d8yt.js → repair.command-qngfxjd6.js} +5 -5
  66. package/{routeSourceValidator-6jd0q6r6.js → routeSourceValidator-4h947v7c.js} +13 -3
  67. package/{scalar.command-cwzge353.js → scalar.command-s28v00sy.js} +4 -4
  68. package/skills/akan-debug/SKILL.md +37 -3
  69. package/{subspace.command-3h03c7kc.js → subspace.command-8atqm584.js} +8 -8
  70. package/{tunnel.command-czaz6ys4.js → tunnel.command-kvwnw6n8.js} +7 -7
  71. package/{verify.command-nzwhtz71.js → verify.command-5fpqe0xp.js} +13 -13
  72. package/{workflow.command-srhky88x.js → workflow.command-0y3gez01.js} +10 -10
  73. package/{workspace.command-9stchcd2.js → workspace.command-fg6m6bjz.js} +29 -28
  74. package/CodeAgent-fbcq8vks.js +0 -9
  75. package/TunnelShare-2p24xxza.js +0 -14
  76. package/cloud.script-nkmeyhet.js +0 -25
  77. package/context.runner-w01a32ph.js +0 -26
  78. package/index-7md2g9vw.js +0 -6
@@ -4,29 +4,33 @@ import {
4
4
  } from "./index-p6x5b7hr.js";
5
5
  import {
6
6
  script,
7
+ ExitCodeError,
7
8
  markCliErrorPrinted,
8
9
  assertPromptable
9
- } from "./index-3gccwenr.js";
10
+ } from "./index-9jyxbbnh.js";
10
11
  import {
11
12
  AppExecutor,
12
13
  LibExecutor,
13
14
  PkgExecutor
14
- } from "./index-64g9fsjy.js";
15
+ } from "./index-nt5c22sg.js";
15
16
  import {
16
17
  DesktopServerStage
17
- } from "./index-w134p86k.js";
18
+ } from "./index-zb0807wt.js";
18
19
  import {
19
20
  LibraryScript
20
- } from "./index-hvv5rnaq.js";
21
+ } from "./index-zvhy8nch.js";
21
22
  import {
22
- ApplicationRunner
23
- } from "./index-57q1ayd2.js";
23
+ ApplicationRunner,
24
+ VerifyScope
25
+ } from "./index-cb58gjk2.js";
24
26
  import {
27
+ PreviewChrome2,
28
+ PreviewView2,
25
29
  stripAnsi
26
- } from "./index-7md2g9vw.js";
30
+ } from "./index-tenw3mah.js";
27
31
  import {
28
32
  formatSlicePlan
29
- } from "./index-mwj9q2ya.js";
33
+ } from "./index-fjxwyj3f.js";
30
34
  import {
31
35
  openBrowser
32
36
  } from "./index-9dp031by.js";
@@ -35,752 +39,1097 @@ import {
35
39
  import { confirm } from "@inquirer/prompts";
36
40
  import { Logger as Logger3, toError } from "akanjs/common";
37
41
 
38
- // pkgs/@akanjs/cli/application/hostProcessProbe.ts
39
- import { readdirSync, readFileSync, readlinkSync } from "fs";
42
+ // pkgs/@akanjs/cli/application/appPreview.ts
43
+ import { closeSync, openSync, realpathSync } from "fs";
44
+ import { mkdir as mkdir2 } from "fs/promises";
45
+ import path2 from "path";
46
+ import { parseRouteModuleKey } from "akanjs/common";
40
47
 
41
- class HostProcessProbe {
42
- static timeoutMs = 3000;
43
- static win32TimeoutMs = 20000;
44
- static #procTcpListen = "0A";
45
- static #win32ProcessQuery = "[Console]::OutputEncoding=[Text.Encoding]::UTF8; Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,CommandLine,CreationDate | ConvertTo-Json -Compress";
46
- platform;
47
- #win32Table = null;
48
- constructor(platform = process.platform) {
49
- this.platform = platform;
50
- }
51
- async listenersOn(port) {
52
- if (this.platform === "win32")
53
- return HostProcessProbe.parseNetstat(await HostProcessProbe.run(["netstat", "-ano"]), port);
54
- if (this.platform === "linux")
55
- return HostProcessProbe.#procListenersOn(port);
56
- const output = await HostProcessProbe.run(["lsof", "-ti", `tcp:${port}`, "-sTCP:LISTEN"]);
57
- return [
58
- ...new Set(output.split(`
59
- `).map((line) => Number(line.trim())).filter((pid) => Number.isInteger(pid) && pid > 0))
60
- ];
48
+ // pkgs/@akanjs/cli/application/devBootConcurrency.ts
49
+ import os from "os";
50
+ import { MemoryLimit } from "akanjs/server/memoryLimit";
51
+
52
+ class DevBootConcurrency {
53
+ static perAppBytes = 1800 * 1024 * 1024;
54
+ static memoryShare = 0.5;
55
+ static coresPerApp = 4;
56
+ static budget() {
57
+ const hostBytes = os.totalmem();
58
+ const declaredBytes = MemoryLimit.parseBytesEnv("AKAN_MEMORY_LIMIT") ?? MemoryLimit.readCgroupBytes();
59
+ return { memoryBytes: Math.min(hostBytes, declaredBytes ?? hostBytes), cores: os.availableParallelism() };
61
60
  }
62
- async parentOf(pid) {
63
- if (this.platform === "win32") {
64
- const child = await this.#win32Process(pid);
65
- const parent = child ? await this.#win32Process(child.ppid) : null;
66
- return child && parent ? HostProcessProbe.parentPidOf(child, parent) : null;
67
- }
68
- if (this.platform === "linux") {
69
- const stat = HostProcessProbe.#readProc(pid, "stat");
70
- return stat === null ? null : HostProcessProbe.parseProcStatPpid(stat);
61
+ static resolve(appCount, requested, budget = DevBootConcurrency.budget()) {
62
+ const apps = Math.max(1, Math.trunc(appCount));
63
+ if (requested !== null && Number.isFinite(requested)) {
64
+ const asked = Math.max(1, Math.trunc(requested));
65
+ return { concurrency: Math.min(apps, asked), reason: `--concurrency ${asked}` };
71
66
  }
72
- const parsed = Number((await HostProcessProbe.run(["ps", "-p", String(pid), "-o", "ppid="])).trim());
73
- return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
67
+ const byMemory = Math.floor(budget.memoryBytes * DevBootConcurrency.memoryShare / DevBootConcurrency.perAppBytes);
68
+ const byCores = Math.floor(budget.cores / DevBootConcurrency.coresPerApp);
69
+ return {
70
+ concurrency: Math.max(1, Math.min(apps, byMemory, byCores)),
71
+ reason: `${budget.cores} cores, ${DevBootConcurrency.#formatBytes(budget.memoryBytes)} memory`
72
+ };
74
73
  }
75
- async commandOf(pid) {
76
- if (this.platform === "win32")
77
- return (await this.#win32Process(pid))?.command ?? null;
78
- if (this.platform === "linux") {
79
- const cmdline = HostProcessProbe.#readProc(pid, "cmdline");
80
- return cmdline?.split("\x00").filter(Boolean).join(" ") || null;
81
- }
82
- return (await HostProcessProbe.run(["ps", "-ww", "-p", String(pid), "-o", "command="])).trim() || null;
74
+ static describe(appCount, plan) {
75
+ if (plan.concurrency >= appCount)
76
+ return `booting all ${appCount} apps at once (${plan.reason})`;
77
+ return `booting ${plan.concurrency} of ${appCount} apps at a time (${plan.reason}) \u2014 --concurrency raises it`;
83
78
  }
84
- static parentPidOf(child, parent) {
85
- if (child.ppid !== parent.pid)
86
- return null;
87
- if (parent.startedAt !== null && child.startedAt !== null && parent.startedAt > child.startedAt)
88
- return null;
89
- return parent.pid;
79
+ static #formatBytes(bytes) {
80
+ const gigabytes = bytes / 1024 ** 3;
81
+ return gigabytes >= 10 ? `${Math.round(gigabytes)}GB` : `${gigabytes.toFixed(1)}GB`;
90
82
  }
91
- static parseNetstat(output, port) {
92
- const pids = new Set;
93
- for (const line of output.split(/\r?\n/)) {
94
- const fields = line.trim().split(/\s+/);
95
- if (fields[0] !== "TCP" || fields.length < 5)
96
- continue;
97
- const [, local, remote] = fields;
98
- if (!local?.endsWith(`:${port}`) || !remote?.endsWith(":0"))
99
- continue;
100
- const pid = Number(fields.at(-1));
101
- if (Number.isInteger(pid) && pid > 0)
102
- pids.add(pid);
103
- }
104
- return [...pids];
83
+ }
84
+
85
+ // pkgs/@akanjs/cli/application/devSessionLog.ts
86
+ import { mkdir, rename } from "fs/promises";
87
+ import path from "path";
88
+ import dayjs from "dayjs";
89
+
90
+ class DevSessionLog {
91
+ static fileName = "dev.log";
92
+ static previousFileName = "dev.prev.log";
93
+ static flushMs = 200;
94
+ static bufferBytes = 64 * 1024;
95
+ #workspaceRoot;
96
+ #appNames;
97
+ #now;
98
+ #writers = new Map;
99
+ #partial = new Map;
100
+ #lastState = new Map;
101
+ #flushTimer = null;
102
+ constructor({ workspaceRoot, apps, now = () => new Date }) {
103
+ this.#workspaceRoot = workspaceRoot;
104
+ this.#appNames = [...apps];
105
+ this.#now = now;
105
106
  }
106
- static parseProcNetTcp(text, port) {
107
- const inodes = [];
108
- for (const line of text.split(`
109
- `).slice(1)) {
110
- const fields = line.trim().split(/\s+/);
111
- const [, local, , state, , , , , , inode] = fields;
112
- if (!local || !inode || state !== HostProcessProbe.#procTcpListen || inode === "0")
113
- continue;
114
- if (Number.parseInt(local.slice(local.lastIndexOf(":") + 1), 16) === port)
115
- inodes.push(inode);
116
- }
117
- return inodes;
107
+ get appNames() {
108
+ return [...this.#appNames];
118
109
  }
119
- static parseProcStatPpid(stat) {
120
- const ppid = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
121
- return Number.isInteger(ppid) && ppid > 0 ? ppid : null;
110
+ pathOf(app) {
111
+ return path.join(this.#runtimeDirOf(app), DevSessionLog.fileName);
122
112
  }
123
- static parseWin32Processes(json) {
124
- const table = new Map;
125
- let parsed;
126
- try {
127
- parsed = JSON.parse(json.trim() || "[]");
128
- } catch {
129
- return table;
130
- }
131
- const rows = Array.isArray(parsed) ? parsed : [parsed];
132
- for (const row of rows) {
133
- if (typeof row?.ProcessId !== "number")
134
- continue;
135
- table.set(row.ProcessId, {
136
- pid: row.ProcessId,
137
- ppid: row.ParentProcessId ?? 0,
138
- command: row.CommandLine?.trim() || null,
139
- startedAt: HostProcessProbe.#parseCimDate(row.CreationDate)
140
- });
141
- }
142
- return table;
113
+ previousPathOf(app) {
114
+ return path.join(this.#runtimeDirOf(app), DevSessionLog.previousFileName);
143
115
  }
144
- static async run(command, timeoutMs = HostProcessProbe.timeoutMs) {
145
- let proc;
146
- try {
147
- proc = Bun.spawn(command, { stdio: ["ignore", "pipe", "ignore"], windowsHide: true });
148
- } catch {
149
- return "";
150
- }
151
- const timer = setTimeout(() => proc.kill("SIGKILL"), timeoutMs);
152
- try {
153
- return await new Response(proc.stdout).text();
154
- } catch {
155
- return "";
156
- } finally {
157
- clearTimeout(timer);
116
+ relativePathOf(app) {
117
+ return path.relative(this.#workspaceRoot, this.pathOf(app));
118
+ }
119
+ async open() {
120
+ const stamp = dayjs(this.#now()).format("YYYY-MM-DD HH:mm:ss");
121
+ for (const app of this.#appNames) {
122
+ const file = this.pathOf(app);
123
+ await mkdir(path.dirname(file), { recursive: true });
124
+ await rename(file, this.previousPathOf(app)).catch(() => {
125
+ return;
126
+ });
127
+ this.#writers.set(app, Bun.file(file).writer({ highWaterMark: DevSessionLog.bufferBytes }));
128
+ this.#writeLine(app, `\u2500\u2500 akan start \xB7 ${app} \xB7 ${stamp} \u2500\u2500`);
158
129
  }
159
130
  }
160
- async#win32Process(pid) {
161
- this.#win32Table ??= await HostProcessProbe.#queryWin32Processes();
162
- if (!this.#win32Table.has(pid))
163
- this.#win32Table = await HostProcessProbe.#queryWin32Processes();
164
- return this.#win32Table.get(pid) ?? null;
131
+ write(app, kind, chunk) {
132
+ const key = `${app}:${kind}`;
133
+ const parts = `${this.#partial.get(key) ?? ""}${chunk}`.split(`
134
+ `);
135
+ this.#partial.set(key, parts.pop() ?? "");
136
+ for (const line of parts)
137
+ this.#writeLine(app, stripAnsi(line));
165
138
  }
166
- static async#queryWin32Processes() {
167
- const output = await HostProcessProbe.run(["powershell", "-NoProfile", "-NonInteractive", "-Command", HostProcessProbe.#win32ProcessQuery], HostProcessProbe.win32TimeoutMs);
168
- return HostProcessProbe.parseWin32Processes(output);
139
+ note(text) {
140
+ for (const app of this.#appNames)
141
+ this.#writeLine(app, `[akan] ${text}`);
169
142
  }
170
- static #parseCimDate(value) {
171
- if (!value)
172
- return null;
173
- const legacy = /\/Date\((\d+)/.exec(value)?.[1];
174
- const ms = legacy ? Number(legacy) : Date.parse(value);
175
- return Number.isFinite(ms) ? ms : null;
143
+ status(statuses) {
144
+ for (const status of statuses) {
145
+ if (this.#lastState.get(status.name) === status.state)
146
+ continue;
147
+ this.#lastState.set(status.name, status.state);
148
+ const detail = status.detail ? ` (${status.detail})` : "";
149
+ const where = status.state === "ready" ? ` \u2014 ${status.url}` : "";
150
+ this.#writeLine(status.name, `[akan] ${status.name} ${status.state}${detail}${where}`);
151
+ }
176
152
  }
177
- static #procListenersOn(port) {
178
- const inodes = new Set(["tcp", "tcp6"].flatMap((table) => HostProcessProbe.parseProcNetTcp(HostProcessProbe.#readProc("net", table) ?? "", port)));
179
- if (!inodes.size)
180
- return [];
181
- const pids = [];
182
- for (const entry of HostProcessProbe.#listDir("/proc")) {
183
- if (!/^\d+$/.test(entry))
153
+ async close() {
154
+ for (const [key, remainder] of this.#partial) {
155
+ if (!remainder)
184
156
  continue;
185
- const holds = HostProcessProbe.#listDir(`/proc/${entry}/fd`).some((fd) => {
186
- const link = HostProcessProbe.#orElse(() => readlinkSync(`/proc/${entry}/fd/${fd}`), "");
187
- const inode = /^socket:\[(\d+)\]$/.exec(link)?.[1];
188
- return !!inode && inodes.has(inode);
189
- });
190
- if (holds)
191
- pids.push(Number(entry));
157
+ this.#writeLine(key.slice(0, key.lastIndexOf(":")), stripAnsi(remainder));
192
158
  }
193
- return pids;
159
+ this.#partial.clear();
160
+ if (this.#flushTimer)
161
+ clearTimeout(this.#flushTimer);
162
+ this.#flushTimer = null;
163
+ await Promise.all([...this.#writers.values()].map(async (writer) => await writer.end()));
164
+ this.#writers.clear();
194
165
  }
195
- static #readProc(pid, file) {
196
- return HostProcessProbe.#orElse(() => readFileSync(`/proc/${pid}/${file}`, "utf8"), null);
166
+ #runtimeDirOf(app) {
167
+ return path.join(this.#workspaceRoot, "local", "apps", app, "runtime");
197
168
  }
198
- static #listDir(dir) {
199
- return HostProcessProbe.#orElse(() => readdirSync(dir), []);
169
+ #writeLine(app, text) {
170
+ const writer = this.#writers.get(app);
171
+ if (!writer)
172
+ return;
173
+ writer.write(`${text}
174
+ `);
175
+ this.#scheduleFlush();
200
176
  }
201
- static #orElse(read, fallback) {
202
- try {
203
- return read();
204
- } catch {
205
- return fallback;
206
- }
177
+ #scheduleFlush() {
178
+ if (this.#flushTimer)
179
+ return;
180
+ this.#flushTimer = setTimeout(() => {
181
+ this.#flushTimer = null;
182
+ for (const writer of this.#writers.values())
183
+ writer.flush();
184
+ }, DevSessionLog.flushMs);
207
185
  }
208
186
  }
209
187
 
210
- // pkgs/@akanjs/cli/application/devPortReclaimer.ts
211
- class DevPortReclaimer {
212
- static releaseTimeoutMs = 8000;
213
- static maxAncestorDepth = 8;
214
- static #releasePollMs = 100;
215
- static wsPortOffset = 1e4;
216
- static portsFor(ports) {
217
- return [...new Set(ports.flatMap((port) => [port, port + DevPortReclaimer.wsPortOffset]))].sort((left, right) => left - right);
188
+ // pkgs/@akanjs/cli/application/devSupervisor.ts
189
+ class DevSupervisor {
190
+ static resolveDevUi(plain, {
191
+ isTty = !!process.stdout.isTTY,
192
+ columns = process.stdout.columns ?? 0
193
+ } = {}) {
194
+ if (plain)
195
+ return { mode: "stream", downgraded: false };
196
+ if (!isTty || columns <= 0)
197
+ return { mode: "stream", downgraded: true };
198
+ return { mode: "tui", downgraded: false };
218
199
  }
219
- static isAkanCommand(command) {
220
- const normalized = command.replaceAll("\\", "/");
221
- return /(^|\/)akan(\.exe)?"?(\s|$)/.test(normalized) || normalized.includes("@akanjs/cli") || normalized.includes("akanjs/server") || /\bapps\/[^/\s]+\/main\.ts\b/.test(normalized) || normalized.includes("incrementalBuilder.proc") || normalized.includes("rscWorker");
200
+ static supervisedEnvKey = "AKAN_DEV_SUPERVISED";
201
+ static childHooks() {
202
+ if (process.env[DevSupervisor.supervisedEnvKey] !== "1" || !process.send)
203
+ return {};
204
+ const send = process.send.bind(process);
205
+ return {
206
+ stdio: "pipe",
207
+ onDevEvent: (event) => {
208
+ try {
209
+ send(event);
210
+ } catch {}
211
+ }
212
+ };
222
213
  }
223
- #probe;
224
- constructor(probe = new HostProcessProbe) {
225
- this.#probe = probe;
214
+ static bootTimeoutMs = 180000;
215
+ static shutdownGraceMs = 12000;
216
+ #options;
217
+ #children = new Map;
218
+ #sessionLog;
219
+ #view = null;
220
+ #stopping = false;
221
+ constructor(options) {
222
+ this.#options = options;
223
+ this.#sessionLog = new DevSessionLog({
224
+ workspaceRoot: options.apps[0]?.workspace.workspaceRoot ?? process.cwd(),
225
+ apps: options.apps.map((app) => app.name)
226
+ });
226
227
  }
227
- async reclaim(ports) {
228
- const killed = [];
229
- const foreign = [];
230
- const seen = new Set;
231
- for (const port of DevPortReclaimer.portsFor(ports)) {
232
- for (const holder of await this.holdersOf(port)) {
233
- if (seen.has(holder.pid))
234
- continue;
235
- seen.add(holder.pid);
236
- if (!holder.akan) {
237
- foreign.push(holder);
238
- continue;
239
- }
240
- if (await this.#terminate(holder.pid))
241
- killed.push(holder);
242
- else
243
- foreign.push(holder);
244
- }
245
- }
246
- return { killed, foreign };
228
+ get statuses() {
229
+ return [...this.#children.values()].map((child) => child.status);
247
230
  }
248
- async holdersOf(port) {
249
- const holders = [];
250
- for (const listenerPid of await this.#probe.listenersOn(port)) {
251
- if (listenerPid === process.pid || listenerPid === process.ppid)
252
- continue;
253
- const command = await this.#probe.commandOf(listenerPid);
254
- if (!command)
255
- continue;
256
- if (!DevPortReclaimer.isAkanCommand(command)) {
257
- holders.push({ pid: listenerPid, command, port, listenerPid, akan: false });
258
- continue;
259
- }
260
- const root = await this.#akanRootOf(listenerPid, command);
261
- holders.push({ pid: root.pid, command: root.command, port, listenerPid, akan: true });
262
- }
263
- return holders;
231
+ get sessionLog() {
232
+ return this.#sessionLog;
264
233
  }
265
- async#akanRootOf(pid, command) {
266
- let root = { pid, command };
267
- for (let depth = 0;depth < DevPortReclaimer.maxAncestorDepth; depth += 1) {
268
- const parentPid = await this.#probe.parentOf(root.pid);
269
- if (parentPid === null || parentPid <= 1 || parentPid === process.pid || parentPid === process.ppid)
270
- break;
271
- const parentCommand = await this.#probe.commandOf(parentPid);
272
- if (!parentCommand || !DevPortReclaimer.isAkanCommand(parentCommand))
273
- break;
274
- root = { pid: parentPid, command: parentCommand };
275
- }
276
- return root;
234
+ async run(view) {
235
+ this.#view = view;
236
+ await this.#sessionLog.open();
237
+ const ports = await this.#assignPorts();
238
+ for (const app of this.#options.apps)
239
+ this.#children.set(app.name, this.#makeChild(app, ports.get(app.name) ?? 0));
240
+ this.#publishStatus();
241
+ const logPaths = this.#sessionLog.appNames.map((name) => this.#sessionLog.relativePathOf(name));
242
+ this.#note(`session log: ${logPaths.join(" \xB7 ")}`, "info");
243
+ const stopped = this.#installSignalHandlers();
244
+ this.#bootInOrder();
245
+ await Promise.race([view.waitForExit(), stopped]);
246
+ await this.stop();
247
+ view.close?.();
248
+ await this.#sessionLog.close();
277
249
  }
278
- async#terminate(pid) {
279
- if (this.#probe.platform === "win32") {
280
- await HostProcessProbe.run(["taskkill", "/PID", String(pid), "/T", "/F"]);
281
- return await this.#released(pid);
250
+ async#assignPorts() {
251
+ const taken = new Set;
252
+ const ports = new Map;
253
+ for (const app of this.#options.apps) {
254
+ let port = await app.getDevPort();
255
+ while (taken.has(port))
256
+ port += 1;
257
+ taken.add(port);
258
+ ports.set(app.name, port);
282
259
  }
283
- if (!this.#signal(pid, "SIGTERM"))
284
- return !this.#alive(pid);
285
- if (await this.#released(pid))
286
- return true;
287
- this.#signal(pid, "SIGKILL");
288
- await Bun.sleep(DevPortReclaimer.#releasePollMs);
289
- return !this.#alive(pid);
260
+ return ports;
290
261
  }
291
- async#released(pid) {
292
- const deadline = Date.now() + DevPortReclaimer.releaseTimeoutMs;
293
- while (Date.now() < deadline) {
294
- if (!this.#alive(pid))
295
- return true;
296
- await Bun.sleep(DevPortReclaimer.#releasePollMs);
262
+ #makeChild(app, port) {
263
+ const { promise: booted, resolve: markBooted } = Promise.withResolvers();
264
+ return {
265
+ status: {
266
+ app,
267
+ name: app.name,
268
+ port,
269
+ url: `http://localhost:${port}`,
270
+ shareUrl: this.#options.shares?.get(app.name) ?? null,
271
+ state: "starting",
272
+ detail: "queued",
273
+ exitCode: null
274
+ },
275
+ proc: null,
276
+ booted,
277
+ markBooted,
278
+ opened: false
279
+ };
280
+ }
281
+ async#bootInOrder() {
282
+ const queue = [...this.#children.values()];
283
+ const plan = DevBootConcurrency.resolve(queue.length, this.#options.concurrency ?? null);
284
+ const concurrency = plan.concurrency;
285
+ if (queue.length > 1)
286
+ this.#note(DevBootConcurrency.describe(queue.length, plan), "info");
287
+ const waves = [];
288
+ for (let idx = 0;idx < queue.length; idx += concurrency)
289
+ waves.push(queue.slice(idx, idx + concurrency));
290
+ for (const wave of waves) {
291
+ if (this.#stopping)
292
+ return;
293
+ for (const child of wave)
294
+ this.#spawnChild(child);
295
+ this.#publishStatus();
296
+ await Promise.all(wave.map(async (child) => await this.#waitForBoot(child)));
297
297
  }
298
- return false;
299
298
  }
300
- #signal(pid, signal) {
299
+ async#waitForBoot(child) {
300
+ if (await DevSupervisor.timesOut(child.booted, DevSupervisor.bootTimeoutMs))
301
+ this.#note(`${child.status.name} has not finished booting after ${Math.round(DevSupervisor.bootTimeoutMs / 1000)}s; starting the next app anyway`, "warn");
302
+ }
303
+ static async timesOut(work, ms) {
304
+ let timer;
305
+ const expired = new Promise((resolve) => {
306
+ timer = setTimeout(() => resolve(true), ms);
307
+ });
301
308
  try {
302
- process.kill(pid, signal);
303
- return true;
304
- } catch {
305
- return false;
309
+ return await Promise.race([work.then(() => false), expired]);
310
+ } finally {
311
+ clearTimeout(timer);
306
312
  }
307
313
  }
308
- #alive(pid) {
309
- try {
310
- process.kill(pid, 0);
311
- return true;
312
- } catch (error) {
313
- return error.code === "EPERM";
314
+ static childArgs(name, { write = true } = {}) {
315
+ return [
316
+ "start",
317
+ name,
318
+ "--plain",
319
+ "--dbup",
320
+ "false",
321
+ "--write",
322
+ String(write)
323
+ ];
324
+ }
325
+ #spawnChild(child) {
326
+ const { app, name, port } = child.status;
327
+ const args = DevSupervisor.childArgs(name, { write: this.#options.write ?? true });
328
+ const proc = Bun.spawn([process.execPath, Bun.main, ...args], {
329
+ cwd: app.workspace.workspaceRoot,
330
+ env: {
331
+ ...process.env,
332
+ [DevSupervisor.supervisedEnvKey]: "1",
333
+ AKAN_PUBLIC_APP_NAME: name,
334
+ AKAN_DEV_PORT: String(port)
335
+ },
336
+ stdio: ["ignore", "pipe", "pipe"],
337
+ ipc: (message) => {
338
+ if (!message || typeof message !== "object")
339
+ return;
340
+ if ("booted" in message)
341
+ child.markBooted();
342
+ else if (typeof message.state === "string")
343
+ this.#applyChildEvent(child, message);
344
+ },
345
+ serialization: "advanced",
346
+ onExit: (_proc, exitCode, signalCode) => {
347
+ child.proc = null;
348
+ child.status.exitCode = exitCode;
349
+ if (this.#stopping)
350
+ return;
351
+ child.status.state = "stopped";
352
+ child.status.detail = signalCode ? `killed by ${signalCode}` : `exited with ${exitCode}`;
353
+ child.markBooted();
354
+ this.#publishStatus();
355
+ }
356
+ });
357
+ child.proc = proc;
358
+ child.status.state = "starting";
359
+ child.status.detail = `pid ${proc.pid}`;
360
+ this.#drain(proc.stdout, name, "stdout");
361
+ this.#drain(proc.stderr, name, "stderr");
362
+ }
363
+ #applyChildEvent(child, event) {
364
+ child.status.state = event.state;
365
+ child.status.detail = event.detail ?? "";
366
+ if (event.state === "ready") {
367
+ if (this.#options.open && !child.opened) {
368
+ child.opened = true;
369
+ openBrowser(child.status.url);
370
+ }
314
371
  }
372
+ if (event.state === "failed")
373
+ child.markBooted();
374
+ this.#publishStatus();
315
375
  }
316
- }
317
-
318
- // pkgs/@akanjs/cli/application/devStreamView.ts
319
- import { Logger } from "akanjs/common";
320
- import chalk from "chalk";
321
- var appColors = ["cyan", "magenta", "yellow", "green", "blue", "red"];
322
-
323
- class DevStreamView {
324
- #logger = new Logger("akan start");
325
- #partial = new Map;
326
- #lastState = new Map;
327
- #color = new Map;
328
- #width = 0;
329
- constructor(appNames) {
330
- this.#width = appNames.reduce((max, name) => Math.max(max, name.length), 0);
331
- appNames.forEach((name, idx) => {
332
- this.#color.set(name, appColors[idx % appColors.length] ?? "cyan");
376
+ async#drain(stream, name, kind) {
377
+ const decoder = new TextDecoder;
378
+ try {
379
+ for await (const chunk of stream) {
380
+ const text = decoder.decode(chunk, { stream: true });
381
+ if (!text)
382
+ continue;
383
+ this.#view?.onOutput(name, kind, text);
384
+ this.#sessionLog.write(name, kind, text);
385
+ }
386
+ } catch {}
387
+ }
388
+ #publishStatus() {
389
+ this.#view?.onStatus(this.statuses);
390
+ this.#sessionLog.status(this.statuses);
391
+ }
392
+ #note(text, level) {
393
+ this.#view?.onNote(text, level);
394
+ this.#sessionLog.note(text);
395
+ }
396
+ #installSignalHandlers() {
397
+ return new Promise((resolve) => {
398
+ let asked = false;
399
+ const onSignal = () => {
400
+ if (asked) {
401
+ this.#note("abandoning the wait; children may be left running", "warn");
402
+ process.exit(130);
403
+ }
404
+ asked = true;
405
+ resolve();
406
+ };
407
+ process.on("SIGINT", onSignal);
408
+ process.on("SIGTERM", onSignal);
333
409
  });
334
410
  }
335
- onOutput = (app, kind, text) => {
336
- const key = `${app}:${kind}`;
337
- const pending = `${this.#partial.get(key) ?? ""}${text}`;
338
- const lines = pending.split(`
339
- `);
340
- this.#partial.set(key, lines.pop() ?? "");
341
- if (lines.length === 0)
411
+ async restart(name) {
412
+ const child = this.#children.get(name);
413
+ if (!child || this.#stopping)
342
414
  return;
343
- const prefixed = lines.map((line) => `${this.#prefix(app)}${line}`).join(`
344
- `);
345
- (kind === "stderr" ? process.stderr : process.stdout).write(`${prefixed}
346
- `);
347
- };
348
- onStatus = (statuses) => {
349
- for (const status of statuses) {
350
- if (this.#lastState.get(status.name) === status.state)
351
- continue;
352
- this.#lastState.set(status.name, status.state);
353
- const detail = status.detail ? ` (${status.detail})` : "";
354
- const where = status.state === "ready" ? ` \u2014 ${status.url}` : "";
355
- const line = `${status.name} ${status.state}${detail}${where}`;
356
- if (status.state === "failed")
357
- this.#logger.error(line);
358
- else if (status.state === "stopped")
359
- this.#logger.warn(line);
360
- else
361
- this.#logger.info(line);
415
+ const running = child.proc;
416
+ if (running) {
417
+ running.kill("SIGTERM");
418
+ await running.exited;
362
419
  }
363
- };
364
- onNote = (text, level) => {
365
- if (level === "warn")
366
- this.#logger.warn(text);
367
- else
368
- this.#logger.info(text);
369
- };
370
- waitForExit = () => new Promise(() => {
371
- return;
372
- });
373
- close = () => {
374
- for (const [key, remainder] of this.#partial) {
375
- if (!remainder)
420
+ child.status.state = "starting";
421
+ child.status.detail = "restarting";
422
+ child.status.exitCode = null;
423
+ this.#publishStatus();
424
+ this.#spawnChild(child);
425
+ this.#publishStatus();
426
+ }
427
+ async stop() {
428
+ if (this.#stopping)
429
+ return;
430
+ this.#stopping = true;
431
+ const running = [...this.#children.values()].filter((child) => Boolean(child.proc));
432
+ for (const child of running)
433
+ child.proc.kill("SIGTERM");
434
+ const exited = Promise.all(running.map(async (child) => await child.proc.exited));
435
+ if (!await DevSupervisor.timesOut(exited, DevSupervisor.shutdownGraceMs))
436
+ return;
437
+ for (const child of running) {
438
+ if (child.proc.killed)
376
439
  continue;
377
- const app = key.slice(0, key.lastIndexOf(":"));
378
- process.stdout.write(`${this.#prefix(app)}${remainder}
379
- `);
440
+ this.#note(`${child.status.name} did not exit in time; killing it`, "warn");
441
+ child.proc.kill("SIGKILL");
380
442
  }
381
- this.#partial.clear();
382
- };
383
- #prefix(app) {
384
- const color = this.#color.get(app) ?? "cyan";
385
- return `${chalk[color](app.padEnd(this.#width))} ${chalk.dim("\u2502")} `;
386
443
  }
387
444
  }
388
445
 
389
- // pkgs/@akanjs/cli/application/devBootConcurrency.ts
390
- import os from "os";
391
- import { MemoryLimit } from "akanjs/server/memoryLimit";
446
+ // pkgs/@akanjs/cli/application/hostProcessProbe.ts
447
+ import { readdirSync, readFileSync, readlinkSync } from "fs";
392
448
 
393
- class DevBootConcurrency {
394
- static perAppBytes = 1800 * 1024 * 1024;
395
- static memoryShare = 0.5;
396
- static coresPerApp = 4;
397
- static budget() {
398
- const hostBytes = os.totalmem();
399
- const declaredBytes = MemoryLimit.parseBytesEnv("AKAN_MEMORY_LIMIT") ?? MemoryLimit.readCgroupBytes();
400
- return { memoryBytes: Math.min(hostBytes, declaredBytes ?? hostBytes), cores: os.availableParallelism() };
401
- }
402
- static resolve(appCount, requested, budget = DevBootConcurrency.budget()) {
403
- const apps = Math.max(1, Math.trunc(appCount));
404
- if (requested !== null && Number.isFinite(requested)) {
405
- const asked = Math.max(1, Math.trunc(requested));
406
- return { concurrency: Math.min(apps, asked), reason: `--concurrency ${asked}` };
407
- }
408
- const byMemory = Math.floor(budget.memoryBytes * DevBootConcurrency.memoryShare / DevBootConcurrency.perAppBytes);
409
- const byCores = Math.floor(budget.cores / DevBootConcurrency.coresPerApp);
410
- return {
411
- concurrency: Math.max(1, Math.min(apps, byMemory, byCores)),
412
- reason: `${budget.cores} cores, ${DevBootConcurrency.#formatBytes(budget.memoryBytes)} memory`
413
- };
449
+ class HostProcessProbe {
450
+ static timeoutMs = 3000;
451
+ static win32TimeoutMs = 20000;
452
+ static #procTcpListen = "0A";
453
+ static #win32ProcessQuery = "[Console]::OutputEncoding=[Text.Encoding]::UTF8; Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,CommandLine,CreationDate | ConvertTo-Json -Compress";
454
+ platform;
455
+ #win32Table = null;
456
+ constructor(platform = process.platform) {
457
+ this.platform = platform;
414
458
  }
415
- static describe(appCount, plan) {
416
- if (plan.concurrency >= appCount)
417
- return `booting all ${appCount} apps at once (${plan.reason})`;
418
- return `booting ${plan.concurrency} of ${appCount} apps at a time (${plan.reason}) \u2014 --concurrency raises it`;
459
+ async listenersOn(port) {
460
+ if (this.platform === "win32")
461
+ return HostProcessProbe.parseNetstat(await HostProcessProbe.run(["netstat", "-ano"]), port);
462
+ if (this.platform === "linux")
463
+ return HostProcessProbe.#procListenersOn(port);
464
+ const output = await HostProcessProbe.run(["lsof", "-ti", `tcp:${port}`, "-sTCP:LISTEN"]);
465
+ return [
466
+ ...new Set(output.split(`
467
+ `).map((line) => Number(line.trim())).filter((pid) => Number.isInteger(pid) && pid > 0))
468
+ ];
419
469
  }
420
- static #formatBytes(bytes) {
421
- const gigabytes = bytes / 1024 ** 3;
422
- return gigabytes >= 10 ? `${Math.round(gigabytes)}GB` : `${gigabytes.toFixed(1)}GB`;
470
+ async parentOf(pid) {
471
+ if (this.platform === "win32") {
472
+ const child = await this.#win32Process(pid);
473
+ const parent = child ? await this.#win32Process(child.ppid) : null;
474
+ return child && parent ? HostProcessProbe.parentPidOf(child, parent) : null;
475
+ }
476
+ if (this.platform === "linux") {
477
+ const stat = HostProcessProbe.#readProc(pid, "stat");
478
+ return stat === null ? null : HostProcessProbe.parseProcStatPpid(stat);
479
+ }
480
+ const parsed = Number((await HostProcessProbe.run(["ps", "-p", String(pid), "-o", "ppid="])).trim());
481
+ return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
423
482
  }
424
- }
425
-
426
- // pkgs/@akanjs/cli/application/devSessionLog.ts
427
- import { mkdir, rename } from "fs/promises";
428
- import path from "path";
429
- import dayjs from "dayjs";
430
-
431
- class DevSessionLog {
432
- static fileName = "dev.log";
433
- static previousFileName = "dev.prev.log";
434
- static flushMs = 200;
435
- static bufferBytes = 64 * 1024;
436
- #workspaceRoot;
437
- #appNames;
438
- #now;
439
- #writers = new Map;
440
- #partial = new Map;
441
- #lastState = new Map;
442
- #flushTimer = null;
443
- constructor({ workspaceRoot, apps, now = () => new Date }) {
444
- this.#workspaceRoot = workspaceRoot;
445
- this.#appNames = [...apps];
446
- this.#now = now;
483
+ async commandOf(pid) {
484
+ if (this.platform === "win32")
485
+ return (await this.#win32Process(pid))?.command ?? null;
486
+ if (this.platform === "linux") {
487
+ const cmdline = HostProcessProbe.#readProc(pid, "cmdline");
488
+ return cmdline?.split("\x00").filter(Boolean).join(" ") || null;
489
+ }
490
+ return (await HostProcessProbe.run(["ps", "-ww", "-p", String(pid), "-o", "command="])).trim() || null;
447
491
  }
448
- get appNames() {
449
- return [...this.#appNames];
492
+ static parentPidOf(child, parent) {
493
+ if (child.ppid !== parent.pid)
494
+ return null;
495
+ if (parent.startedAt !== null && child.startedAt !== null && parent.startedAt > child.startedAt)
496
+ return null;
497
+ return parent.pid;
450
498
  }
451
- pathOf(app) {
452
- return path.join(this.#runtimeDirOf(app), DevSessionLog.fileName);
499
+ static parseNetstat(output, port) {
500
+ const pids = new Set;
501
+ for (const line of output.split(/\r?\n/)) {
502
+ const fields = line.trim().split(/\s+/);
503
+ if (fields[0] !== "TCP" || fields.length < 5)
504
+ continue;
505
+ const [, local, remote] = fields;
506
+ if (!local?.endsWith(`:${port}`) || !remote?.endsWith(":0"))
507
+ continue;
508
+ const pid = Number(fields.at(-1));
509
+ if (Number.isInteger(pid) && pid > 0)
510
+ pids.add(pid);
511
+ }
512
+ return [...pids];
453
513
  }
454
- previousPathOf(app) {
455
- return path.join(this.#runtimeDirOf(app), DevSessionLog.previousFileName);
514
+ static parseProcNetTcp(text, port) {
515
+ const inodes = [];
516
+ for (const line of text.split(`
517
+ `).slice(1)) {
518
+ const fields = line.trim().split(/\s+/);
519
+ const [, local, , state, , , , , , inode] = fields;
520
+ if (!local || !inode || state !== HostProcessProbe.#procTcpListen || inode === "0")
521
+ continue;
522
+ if (Number.parseInt(local.slice(local.lastIndexOf(":") + 1), 16) === port)
523
+ inodes.push(inode);
524
+ }
525
+ return inodes;
456
526
  }
457
- relativePathOf(app) {
458
- return path.relative(this.#workspaceRoot, this.pathOf(app));
527
+ static parseProcStatPpid(stat) {
528
+ const ppid = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
529
+ return Number.isInteger(ppid) && ppid > 0 ? ppid : null;
459
530
  }
460
- async open() {
461
- const stamp = dayjs(this.#now()).format("YYYY-MM-DD HH:mm:ss");
462
- for (const app of this.#appNames) {
463
- const file = this.pathOf(app);
464
- await mkdir(path.dirname(file), { recursive: true });
465
- await rename(file, this.previousPathOf(app)).catch(() => {
466
- return;
531
+ static parseWin32Processes(json) {
532
+ const table = new Map;
533
+ let parsed;
534
+ try {
535
+ parsed = JSON.parse(json.trim() || "[]");
536
+ } catch {
537
+ return table;
538
+ }
539
+ const rows = Array.isArray(parsed) ? parsed : [parsed];
540
+ for (const row of rows) {
541
+ if (typeof row?.ProcessId !== "number")
542
+ continue;
543
+ table.set(row.ProcessId, {
544
+ pid: row.ProcessId,
545
+ ppid: row.ParentProcessId ?? 0,
546
+ command: row.CommandLine?.trim() || null,
547
+ startedAt: HostProcessProbe.#parseCimDate(row.CreationDate)
467
548
  });
468
- this.#writers.set(app, Bun.file(file).writer({ highWaterMark: DevSessionLog.bufferBytes }));
469
- this.#writeLine(app, `\u2500\u2500 akan start \xB7 ${app} \xB7 ${stamp} \u2500\u2500`);
470
549
  }
550
+ return table;
471
551
  }
472
- write(app, kind, chunk) {
473
- const key = `${app}:${kind}`;
474
- const parts = `${this.#partial.get(key) ?? ""}${chunk}`.split(`
475
- `);
476
- this.#partial.set(key, parts.pop() ?? "");
477
- for (const line of parts)
478
- this.#writeLine(app, stripAnsi(line));
552
+ static async run(command, timeoutMs = HostProcessProbe.timeoutMs) {
553
+ let proc;
554
+ try {
555
+ proc = Bun.spawn(command, { stdio: ["ignore", "pipe", "ignore"], windowsHide: true });
556
+ } catch {
557
+ return "";
558
+ }
559
+ const timer = setTimeout(() => proc.kill("SIGKILL"), timeoutMs);
560
+ try {
561
+ return await new Response(proc.stdout).text();
562
+ } catch {
563
+ return "";
564
+ } finally {
565
+ clearTimeout(timer);
566
+ }
567
+ }
568
+ async#win32Process(pid) {
569
+ this.#win32Table ??= await HostProcessProbe.#queryWin32Processes();
570
+ if (!this.#win32Table.has(pid))
571
+ this.#win32Table = await HostProcessProbe.#queryWin32Processes();
572
+ return this.#win32Table.get(pid) ?? null;
479
573
  }
480
- note(text) {
481
- for (const app of this.#appNames)
482
- this.#writeLine(app, `[akan] ${text}`);
574
+ static async#queryWin32Processes() {
575
+ const output = await HostProcessProbe.run(["powershell", "-NoProfile", "-NonInteractive", "-Command", HostProcessProbe.#win32ProcessQuery], HostProcessProbe.win32TimeoutMs);
576
+ return HostProcessProbe.parseWin32Processes(output);
483
577
  }
484
- status(statuses) {
485
- for (const status of statuses) {
486
- if (this.#lastState.get(status.name) === status.state)
487
- continue;
488
- this.#lastState.set(status.name, status.state);
489
- const detail = status.detail ? ` (${status.detail})` : "";
490
- const where = status.state === "ready" ? ` \u2014 ${status.url}` : "";
491
- this.#writeLine(status.name, `[akan] ${status.name} ${status.state}${detail}${where}`);
492
- }
578
+ static #parseCimDate(value) {
579
+ if (!value)
580
+ return null;
581
+ const legacy = /\/Date\((\d+)/.exec(value)?.[1];
582
+ const ms = legacy ? Number(legacy) : Date.parse(value);
583
+ return Number.isFinite(ms) ? ms : null;
493
584
  }
494
- async close() {
495
- for (const [key, remainder] of this.#partial) {
496
- if (!remainder)
585
+ static #procListenersOn(port) {
586
+ const inodes = new Set(["tcp", "tcp6"].flatMap((table) => HostProcessProbe.parseProcNetTcp(HostProcessProbe.#readProc("net", table) ?? "", port)));
587
+ if (!inodes.size)
588
+ return [];
589
+ const pids = [];
590
+ for (const entry of HostProcessProbe.#listDir("/proc")) {
591
+ if (!/^\d+$/.test(entry))
497
592
  continue;
498
- this.#writeLine(key.slice(0, key.lastIndexOf(":")), stripAnsi(remainder));
593
+ const holds = HostProcessProbe.#listDir(`/proc/${entry}/fd`).some((fd) => {
594
+ const link = HostProcessProbe.#orElse(() => readlinkSync(`/proc/${entry}/fd/${fd}`), "");
595
+ const inode = /^socket:\[(\d+)\]$/.exec(link)?.[1];
596
+ return !!inode && inodes.has(inode);
597
+ });
598
+ if (holds)
599
+ pids.push(Number(entry));
499
600
  }
500
- this.#partial.clear();
501
- if (this.#flushTimer)
502
- clearTimeout(this.#flushTimer);
503
- this.#flushTimer = null;
504
- await Promise.all([...this.#writers.values()].map(async (writer) => await writer.end()));
505
- this.#writers.clear();
601
+ return pids;
506
602
  }
507
- #runtimeDirOf(app) {
508
- return path.join(this.#workspaceRoot, "local", "apps", app, "runtime");
603
+ static #readProc(pid, file) {
604
+ return HostProcessProbe.#orElse(() => readFileSync(`/proc/${pid}/${file}`, "utf8"), null);
509
605
  }
510
- #writeLine(app, text) {
511
- const writer = this.#writers.get(app);
512
- if (!writer)
513
- return;
514
- writer.write(`${text}
515
- `);
516
- this.#scheduleFlush();
606
+ static #listDir(dir) {
607
+ return HostProcessProbe.#orElse(() => readdirSync(dir), []);
517
608
  }
518
- #scheduleFlush() {
519
- if (this.#flushTimer)
520
- return;
521
- this.#flushTimer = setTimeout(() => {
522
- this.#flushTimer = null;
523
- for (const writer of this.#writers.values())
524
- writer.flush();
525
- }, DevSessionLog.flushMs);
609
+ static #orElse(read, fallback) {
610
+ try {
611
+ return read();
612
+ } catch {
613
+ return fallback;
614
+ }
526
615
  }
527
616
  }
528
617
 
529
- // pkgs/@akanjs/cli/application/devSupervisor.ts
530
- class DevSupervisor {
531
- static resolveDevUi(plain, {
532
- isTty = !!process.stdout.isTTY,
533
- columns = process.stdout.columns ?? 0
534
- } = {}) {
535
- if (plain)
536
- return { mode: "stream", downgraded: false };
537
- if (!isTty || columns <= 0)
538
- return { mode: "stream", downgraded: true };
539
- return { mode: "tui", downgraded: false };
618
+ // pkgs/@akanjs/cli/application/appPreview.ts
619
+ class AppPreview {
620
+ static mobileViewport = { width: 390, height: 844 };
621
+ static desktopViewport = { width: 1280, height: 800 };
622
+ static csrTarget = "preview";
623
+ static settleMs = 1000;
624
+ static logGraceMs = 300;
625
+ static stopGraceMs = 15000;
626
+ static async run(app, options = {}) {
627
+ const engine = options.engine ?? PreviewChrome2.backend;
628
+ const unavailable = PreviewView2.unavailableReason(engine);
629
+ if (unavailable)
630
+ throw new Error(unavailable);
631
+ const { i18n } = await app.getConfig();
632
+ const changed = options.changed ? await AppPreview.#changedPages(app) : { paths: [], skipped: [] };
633
+ if (options.changed && !changed.paths.length && !options.paths?.length)
634
+ throw new Error(`No page to open: ${changed.skipped.join("; ")}. Pass a concrete path, e.g. \`akan preview ${app.name} /memo/1\`.`);
635
+ const paths = AppPreview.pagePaths([...options.paths ?? [], ...changed.paths], i18n, { csr: !!options.csr });
636
+ const port = await app.getDevPort();
637
+ const origin = `http://localhost:${port}`;
638
+ const root = app.workspace.workspaceRoot;
639
+ const previewDir = path2.join(ApplicationRunner.runtimeDirOf(app), "preview");
640
+ const started = await ApplicationRunner.answers(origin, app.name, root) ? null : await AppPreview.#startServer(app, port, previewDir);
641
+ const viewport = options.desktop ? AppPreview.desktopViewport : AppPreview.mobileViewport;
642
+ const report = {
643
+ app: app.name,
644
+ origin,
645
+ engine,
646
+ viewport,
647
+ server: started ? options.keep ? "kept" : "started" : "running",
648
+ serverPid: started?.proc.pid ?? null,
649
+ serverLog: started ? path2.relative(root, started.logPath) : null,
650
+ logsRead: false,
651
+ skipped: changed.skipped,
652
+ pages: []
653
+ };
654
+ try {
655
+ if (started)
656
+ await AppPreview.#waitBooted(started);
657
+ const records = [];
658
+ const tail = await AppPreview.#tail(app, records);
659
+ report.logsRead = !!tail;
660
+ try {
661
+ for (const pagePath of paths) {
662
+ const mark = records.length;
663
+ const page = await AppPreview.#probe(origin, pagePath, {
664
+ engine,
665
+ viewport,
666
+ screenshot: options.screenshot ? path2.join(previewDir, AppPreview.screenshotName(pagePath)) : null,
667
+ timeoutMs: options.timeoutMs ?? 60000
668
+ });
669
+ if (tail)
670
+ await Bun.sleep(AppPreview.logGraceMs);
671
+ AppPreview.attribute(page, records.slice(mark));
672
+ if (page.screenshot)
673
+ page.screenshot = path2.relative(root, page.screenshot);
674
+ report.pages.push(page);
675
+ }
676
+ } finally {
677
+ tail?.close();
678
+ }
679
+ return report;
680
+ } finally {
681
+ if (started && !options.keep)
682
+ await AppPreview.#stopServer(started.proc);
683
+ else
684
+ started?.proc.unref();
685
+ }
540
686
  }
541
- static supervisedEnvKey = "AKAN_DEV_SUPERVISED";
542
- static childHooks() {
543
- if (process.env[DevSupervisor.supervisedEnvKey] !== "1" || !process.send)
544
- return {};
545
- const send = process.send.bind(process);
546
- return {
547
- stdio: "pipe",
548
- onDevEvent: (event) => {
549
- try {
550
- send(event);
551
- } catch {}
687
+ static pagePaths(paths, i18n, { csr }) {
688
+ const pages = (paths.length ? paths : ["/"]).map((raw) => {
689
+ const url = new URL(/^https?:\/\//.test(raw) ? raw : `http://localhost${raw.startsWith("/") ? "" : "/"}${raw}`);
690
+ const [first] = url.pathname.split("/").filter(Boolean);
691
+ if (!first || !i18n.locales.includes(first))
692
+ url.pathname = `/${i18n.defaultLocale}${url.pathname === "/" ? "/" : url.pathname}`;
693
+ if (csr) {
694
+ url.searchParams.set("csr", "true");
695
+ url.searchParams.set("akanMobileTarget", AppPreview.csrTarget);
696
+ }
697
+ return `${url.pathname}${url.search}`;
698
+ });
699
+ return [...new Set(pages)];
700
+ }
701
+ static changedPageLimit = 8;
702
+ static changedPages(sources, changedFiles) {
703
+ const realOf = (file) => {
704
+ try {
705
+ return realpathSync(file);
706
+ } catch {
707
+ return file;
552
708
  }
553
709
  };
710
+ const changed = new Set([...changedFiles].map(realOf));
711
+ const routes = sources.map((source) => ({
712
+ route: parseRouteModuleKey(source.key),
713
+ touched: changed.has(realOf(source.absPath))
714
+ }));
715
+ const layouts = routes.filter(({ route, touched }) => touched && route.kind === "layout").map(({ route }) => route.routeSegments.join("/"));
716
+ const reached = [];
717
+ const skipped = [];
718
+ let anyRoute = layouts.length > 0;
719
+ for (const { route, touched } of routes) {
720
+ if (route.kind !== "page")
721
+ continue;
722
+ anyRoute ||= touched;
723
+ const segments = route.routeSegments;
724
+ const reach = route.leaf === "_index" ? segments.length : segments.length - 1;
725
+ const wrapped = layouts.some((layout) => Array.from({ length: reach + 1 }, (_, idx) => segments.slice(0, idx).join("/")).includes(layout));
726
+ if (!touched && !wrapped)
727
+ continue;
728
+ const urlPath = route.pattern.replace(/^\/:lang/, "") || "/";
729
+ if (urlPath.includes("/:"))
730
+ skipped.push(`${urlPath} needs a concrete path`);
731
+ else
732
+ reached.push(urlPath);
733
+ }
734
+ if (!anyRoute)
735
+ return { paths: ["/"], skipped };
736
+ const paths = reached.sort((a, b) => a.localeCompare(b)).slice(0, AppPreview.changedPageLimit);
737
+ if (reached.length > paths.length)
738
+ skipped.push(`${reached.length - paths.length} more page(s) under a changed layout`);
739
+ return { paths, skipped };
740
+ }
741
+ static screenshotName(pagePath) {
742
+ const url = new URL(pagePath, "http://localhost");
743
+ const slug = url.pathname.split("/").filter(Boolean).join("-").replace(/[^\w-]/g, "_") || "index";
744
+ return `${slug}${url.searchParams.get("csr") === "true" ? ".csr" : ""}.png`;
745
+ }
746
+ static attribute(page, records) {
747
+ const pathname = new URL(page.finalUrl).pathname;
748
+ for (const record of records) {
749
+ if (record.name === "ClientReport") {
750
+ const href = typeof record.attrs?.href === "string" ? record.attrs.href : null;
751
+ if (href && new URL(href, page.finalUrl).pathname !== pathname)
752
+ continue;
753
+ page.clientReports.push(record.message);
754
+ } else
755
+ page.serverErrors.push(AppPreview.#firstLines(`[${record.name}] ${record.message}`));
756
+ }
757
+ page.failed ||= page.clientReports.length > 0 || page.serverErrors.length > 0;
758
+ }
759
+ static render(report) {
760
+ const server = {
761
+ running: "already running",
762
+ started: `started for this preview and stopped; its log: ${report.serverLog}`,
763
+ kept: `started for this preview and left running (pid ${report.serverPid}; stop it with \`${AppPreview.stopArgvOf(report.serverPid ?? 0).join(" ")}\`); its log: ${report.serverLog}`
764
+ }[report.server];
765
+ const lines = [
766
+ `${report.origin}: ${report.app} dev server, ${server}`,
767
+ `${report.engine}, ${report.viewport.width}x${report.viewport.height}`
768
+ ];
769
+ if (!report.logsRead)
770
+ lines.push("The app's log socket did not answer, so client and server errors are not shown.");
771
+ for (const reason of report.skipped)
772
+ lines.push(`Not opened: ${reason}.`);
773
+ lines.push("");
774
+ for (const page of report.pages) {
775
+ const verdict = page.failed ? "FAIL" : page.domFindings.length || page.consoleWarnings.length ? "warn" : "ok";
776
+ const landed = new URL(page.finalUrl).pathname;
777
+ const moved = landed !== new URL(page.url).pathname ? ` -> ${landed}` : "";
778
+ const status = page.status === null ? "---" : String(page.status);
779
+ lines.push(`${verdict.padEnd(4)} ${page.path}${moved} ${status} "${page.title}" ${(page.ms / 1000).toFixed(1)}s`);
780
+ const items = [
781
+ ["error", page.error ? [page.error] : []],
782
+ ["page", page.pageErrors],
783
+ ["client", page.clientReports],
784
+ ["server", page.serverErrors],
785
+ ["console", [...page.consoleErrors, ...page.consoleWarnings]],
786
+ ["dom", page.domFindings],
787
+ [
788
+ "text",
789
+ page.text ? [JSON.stringify(page.text.length > 160 ? `${page.text.slice(0, 160)}...` : page.text)] : []
790
+ ],
791
+ ["screenshot", page.screenshot ? [page.screenshot] : []]
792
+ ];
793
+ for (const [label, entries] of items)
794
+ for (const entry of entries)
795
+ lines.push(` ${label}: ${entry.split(`
796
+ `).join(`
797
+ `)}`);
798
+ }
799
+ const failed = report.pages.filter((page) => page.failed).length;
800
+ lines.push("", failed ? `${failed} of ${report.pages.length} page(s) failed.` : `${report.pages.length} page(s) rendered.`);
801
+ return lines.join(`
802
+ `);
554
803
  }
555
- static bootTimeoutMs = 180000;
556
- static shutdownGraceMs = 12000;
557
- #options;
558
- #children = new Map;
559
- #sessionLog;
560
- #view = null;
561
- #stopping = false;
562
- constructor(options) {
563
- this.#options = options;
564
- this.#sessionLog = new DevSessionLog({
565
- workspaceRoot: options.apps[0]?.workspace.workspaceRoot ?? process.cwd(),
566
- apps: options.apps.map((app) => app.name)
804
+ static async#probe(origin, pagePath, {
805
+ engine,
806
+ viewport,
807
+ screenshot,
808
+ timeoutMs
809
+ }) {
810
+ const url = new URL(pagePath, origin).toString();
811
+ const at = Date.now();
812
+ const page = {
813
+ path: pagePath,
814
+ url,
815
+ finalUrl: url,
816
+ status: null,
817
+ title: "",
818
+ text: "",
819
+ ms: 0,
820
+ failed: true,
821
+ error: null,
822
+ pageErrors: [],
823
+ clientReports: [],
824
+ serverErrors: [],
825
+ consoleErrors: [],
826
+ consoleWarnings: [],
827
+ domFindings: [],
828
+ screenshot: null
829
+ };
830
+ try {
831
+ const probe = await PreviewView2.probe(url, {
832
+ engine,
833
+ ...viewport,
834
+ screenshot: !!screenshot,
835
+ timeoutMs,
836
+ settleMs: AppPreview.settleMs
837
+ });
838
+ Object.assign(page, {
839
+ finalUrl: probe.finalUrl,
840
+ status: probe.status,
841
+ title: probe.title,
842
+ text: probe.text,
843
+ pageErrors: probe.pageErrors,
844
+ consoleErrors: probe.consoleErrors,
845
+ consoleWarnings: probe.consoleWarnings,
846
+ domFindings: probe.domFindings
847
+ });
848
+ if (screenshot && probe.screenshot) {
849
+ await mkdir2(path2.dirname(screenshot), { recursive: true });
850
+ await Bun.write(screenshot, Buffer.from(probe.screenshot, "base64"));
851
+ page.screenshot = screenshot;
852
+ }
853
+ page.failed = page.status !== null && page.status >= 400 || page.pageErrors.length > 0 || page.consoleErrors.length > 0;
854
+ } catch (error) {
855
+ page.error = error instanceof Error ? error.message : String(error);
856
+ }
857
+ page.ms = Date.now() - at;
858
+ return page;
859
+ }
860
+ static async#changedPages(app) {
861
+ const root = app.workspace.workspaceRoot;
862
+ const changes = await VerifyScope.changesIn(root) ?? [];
863
+ const files = changes.filter((change) => !change.code.includes("D")).map((change) => path2.join(root, change.file));
864
+ return AppPreview.changedPages(await app.getRouteSources(), files);
865
+ }
866
+ static async#tail(app, records) {
867
+ const { LogTailClient } = await import("akanjs/server/logging/logTailClient");
868
+ const socketPath = LogTailClient.socketPath(ApplicationRunner.runtimeDirOf(app));
869
+ try {
870
+ const client = await LogTailClient.connect(socketPath, { onRecord: (entry) => void records.push(entry.record) });
871
+ await client.subscribe({ level: "error" });
872
+ return client;
873
+ } catch {
874
+ return null;
875
+ }
876
+ }
877
+ static async#startServer(app, port, previewDir) {
878
+ await mkdir2(previewDir, { recursive: true });
879
+ const logPath = path2.join(previewDir, "server.log");
880
+ const { promise: settled, resolve: settle } = Promise.withResolvers();
881
+ const fd = openSync(logPath, "w");
882
+ try {
883
+ const proc = Bun.spawn([process.execPath, Bun.main, "start", app.name, "--plain"], {
884
+ cwd: app.workspace.workspaceRoot,
885
+ env: { ...process.env, AKAN_DEV_PORT: String(port), [DevSupervisor.supervisedEnvKey]: "1" },
886
+ stdio: ["ignore", fd, fd],
887
+ detached: true,
888
+ ipc: (message) => {
889
+ if (!message || typeof message !== "object")
890
+ return;
891
+ if ("booted" in message)
892
+ settle({ state: "booted" });
893
+ else if (message.state === "failed")
894
+ settle({ state: "failed", ...message.detail ? { detail: message.detail } : {} });
895
+ },
896
+ serialization: "advanced",
897
+ onExit: (_proc, exitCode) => settle({ state: "exited", detail: `exit code ${exitCode}` })
898
+ });
899
+ return { proc, logPath, settled };
900
+ } finally {
901
+ closeSync(fd);
902
+ }
903
+ }
904
+ static async#waitBooted({ settled, logPath }) {
905
+ const { state, detail } = await AppPreview.#raceTimer(settled, DevSupervisor.bootTimeoutMs, {
906
+ state: "timeout",
907
+ detail: undefined
567
908
  });
909
+ if (state === "booted")
910
+ return;
911
+ const what = {
912
+ failed: "failed to boot",
913
+ exited: "exited before it booted",
914
+ timeout: `did not boot within ${DevSupervisor.bootTimeoutMs / 1000}s`
915
+ }[state];
916
+ throw new Error(`The dev server this preview started ${what}${detail ? ` (${detail})` : ""}; see ${logPath}`);
917
+ }
918
+ static stopArgvOf(pid, platform = process.platform) {
919
+ return platform === "win32" ? ["taskkill", "/PID", String(pid), "/T", "/F"] : ["kill", "-INT", `-${pid}`];
920
+ }
921
+ static async#stopServer(proc) {
922
+ if (proc.exitCode !== null)
923
+ return;
924
+ if (process.platform === "win32") {
925
+ await HostProcessProbe.run(AppPreview.stopArgvOf(proc.pid));
926
+ await AppPreview.#raceTimer(proc.exited, AppPreview.stopGraceMs, null);
927
+ return;
928
+ }
929
+ const signal = (name) => {
930
+ try {
931
+ process.kill(-proc.pid, name);
932
+ } catch {}
933
+ };
934
+ signal("SIGINT");
935
+ const exited = await AppPreview.#raceTimer(proc.exited.then(() => true), AppPreview.stopGraceMs, false);
936
+ if (!exited)
937
+ signal("SIGKILL");
568
938
  }
569
- get statuses() {
570
- return [...this.#children.values()].map((child) => child.status);
939
+ static async#raceTimer(work, ms, fallback) {
940
+ let timer;
941
+ const expired = new Promise((resolve) => {
942
+ timer = setTimeout(() => resolve(fallback), ms);
943
+ });
944
+ try {
945
+ return await Promise.race([work, expired]);
946
+ } finally {
947
+ clearTimeout(timer);
948
+ }
571
949
  }
572
- get sessionLog() {
573
- return this.#sessionLog;
950
+ static #firstLines(text, count = 6) {
951
+ return text.split(`
952
+ `).slice(0, count).join(`
953
+ `).slice(0, 2000);
574
954
  }
575
- async run(view) {
576
- this.#view = view;
577
- await this.#sessionLog.open();
578
- const ports = await this.#assignPorts();
579
- for (const app of this.#options.apps)
580
- this.#children.set(app.name, this.#makeChild(app, ports.get(app.name) ?? 0));
581
- this.#publishStatus();
582
- const logPaths = this.#sessionLog.appNames.map((name) => this.#sessionLog.relativePathOf(name));
583
- this.#note(`session log: ${logPaths.join(" \xB7 ")}`, "info");
584
- const stopped = this.#installSignalHandlers();
585
- this.#bootInOrder();
586
- await Promise.race([view.waitForExit(), stopped]);
587
- await this.stop();
588
- view.close?.();
589
- await this.#sessionLog.close();
955
+ }
956
+
957
+ // pkgs/@akanjs/cli/application/devPortReclaimer.ts
958
+ class DevPortReclaimer {
959
+ static releaseTimeoutMs = 8000;
960
+ static maxAncestorDepth = 8;
961
+ static #releasePollMs = 100;
962
+ static wsPortOffset = 1e4;
963
+ static portsFor(ports) {
964
+ return [...new Set(ports.flatMap((port) => [port, port + DevPortReclaimer.wsPortOffset]))].sort((left, right) => left - right);
590
965
  }
591
- async#assignPorts() {
592
- const taken = new Set;
593
- const ports = new Map;
594
- for (const app of this.#options.apps) {
595
- let port = await app.getDevPort();
596
- while (taken.has(port))
597
- port += 1;
598
- taken.add(port);
599
- ports.set(app.name, port);
600
- }
601
- return ports;
966
+ static isAkanCommand(command) {
967
+ const normalized = command.replaceAll("\\", "/");
968
+ return /(^|\/)akan(\.exe)?"?(\s|$)/.test(normalized) || normalized.includes("@akanjs/cli") || normalized.includes("akanjs/server") || /\bapps\/[^/\s]+\/main\.ts\b/.test(normalized) || normalized.includes("incrementalBuilder.proc") || normalized.includes("rscWorker");
602
969
  }
603
- #makeChild(app, port) {
604
- const { promise: booted, resolve: markBooted } = Promise.withResolvers();
605
- return {
606
- status: {
607
- app,
608
- name: app.name,
609
- port,
610
- url: `http://localhost:${port}`,
611
- shareUrl: this.#options.shares?.get(app.name) ?? null,
612
- state: "starting",
613
- detail: "queued",
614
- exitCode: null
615
- },
616
- proc: null,
617
- booted,
618
- markBooted,
619
- opened: false
620
- };
970
+ #probe;
971
+ constructor(probe = new HostProcessProbe) {
972
+ this.#probe = probe;
621
973
  }
622
- async#bootInOrder() {
623
- const queue = [...this.#children.values()];
624
- const plan = DevBootConcurrency.resolve(queue.length, this.#options.concurrency ?? null);
625
- const concurrency = plan.concurrency;
626
- if (queue.length > 1)
627
- this.#note(DevBootConcurrency.describe(queue.length, plan), "info");
628
- const waves = [];
629
- for (let idx = 0;idx < queue.length; idx += concurrency)
630
- waves.push(queue.slice(idx, idx + concurrency));
631
- for (const wave of waves) {
632
- if (this.#stopping)
633
- return;
634
- for (const child of wave)
635
- this.#spawnChild(child);
636
- this.#publishStatus();
637
- await Promise.all(wave.map(async (child) => await this.#waitForBoot(child)));
974
+ async reclaim(ports) {
975
+ const killed = [];
976
+ const foreign = [];
977
+ const seen = new Set;
978
+ for (const port of DevPortReclaimer.portsFor(ports)) {
979
+ for (const holder of await this.holdersOf(port)) {
980
+ if (seen.has(holder.pid))
981
+ continue;
982
+ seen.add(holder.pid);
983
+ if (!holder.akan) {
984
+ foreign.push(holder);
985
+ continue;
986
+ }
987
+ if (await this.#terminate(holder.pid))
988
+ killed.push(holder);
989
+ else
990
+ foreign.push(holder);
991
+ }
638
992
  }
993
+ return { killed, foreign };
639
994
  }
640
- async#waitForBoot(child) {
641
- if (await DevSupervisor.timesOut(child.booted, DevSupervisor.bootTimeoutMs))
642
- this.#note(`${child.status.name} has not finished booting after ${Math.round(DevSupervisor.bootTimeoutMs / 1000)}s; starting the next app anyway`, "warn");
643
- }
644
- static async timesOut(work, ms) {
645
- let timer;
646
- const expired = new Promise((resolve) => {
647
- timer = setTimeout(() => resolve(true), ms);
648
- });
649
- try {
650
- return await Promise.race([work.then(() => false), expired]);
651
- } finally {
652
- clearTimeout(timer);
995
+ async holdersOf(port) {
996
+ const holders = [];
997
+ for (const listenerPid of await this.#probe.listenersOn(port)) {
998
+ if (listenerPid === process.pid || listenerPid === process.ppid)
999
+ continue;
1000
+ const command = await this.#probe.commandOf(listenerPid);
1001
+ if (!command)
1002
+ continue;
1003
+ if (!DevPortReclaimer.isAkanCommand(command)) {
1004
+ holders.push({ pid: listenerPid, command, port, listenerPid, akan: false });
1005
+ continue;
1006
+ }
1007
+ const root = await this.#akanRootOf(listenerPid, command);
1008
+ holders.push({ pid: root.pid, command: root.command, port, listenerPid, akan: true });
653
1009
  }
1010
+ return holders;
654
1011
  }
655
- static childArgs(name, { write = true } = {}) {
656
- return [
657
- "start",
658
- name,
659
- "--plain",
660
- "--dbup",
661
- "false",
662
- "--write",
663
- String(write)
664
- ];
1012
+ async#akanRootOf(pid, command) {
1013
+ let root = { pid, command };
1014
+ for (let depth = 0;depth < DevPortReclaimer.maxAncestorDepth; depth += 1) {
1015
+ const parentPid = await this.#probe.parentOf(root.pid);
1016
+ if (parentPid === null || parentPid <= 1 || parentPid === process.pid || parentPid === process.ppid)
1017
+ break;
1018
+ const parentCommand = await this.#probe.commandOf(parentPid);
1019
+ if (!parentCommand || !DevPortReclaimer.isAkanCommand(parentCommand))
1020
+ break;
1021
+ root = { pid: parentPid, command: parentCommand };
1022
+ }
1023
+ return root;
665
1024
  }
666
- #spawnChild(child) {
667
- const { app, name, port } = child.status;
668
- const args = DevSupervisor.childArgs(name, { write: this.#options.write ?? true });
669
- const proc = Bun.spawn([process.execPath, Bun.main, ...args], {
670
- cwd: app.workspace.workspaceRoot,
671
- env: {
672
- ...process.env,
673
- [DevSupervisor.supervisedEnvKey]: "1",
674
- AKAN_PUBLIC_APP_NAME: name,
675
- AKAN_DEV_PORT: String(port)
676
- },
677
- stdio: ["ignore", "pipe", "pipe"],
678
- ipc: (message) => {
679
- if (!message || typeof message !== "object")
680
- return;
681
- if ("booted" in message)
682
- child.markBooted();
683
- else if (typeof message.state === "string")
684
- this.#applyChildEvent(child, message);
685
- },
686
- serialization: "advanced",
687
- onExit: (_proc, exitCode, signalCode) => {
688
- child.proc = null;
689
- child.status.exitCode = exitCode;
690
- if (this.#stopping)
691
- return;
692
- child.status.state = "stopped";
693
- child.status.detail = signalCode ? `killed by ${signalCode}` : `exited with ${exitCode}`;
694
- child.markBooted();
695
- this.#publishStatus();
696
- }
697
- });
698
- child.proc = proc;
699
- child.status.state = "starting";
700
- child.status.detail = `pid ${proc.pid}`;
701
- this.#drain(proc.stdout, name, "stdout");
702
- this.#drain(proc.stderr, name, "stderr");
1025
+ async#terminate(pid) {
1026
+ if (this.#probe.platform === "win32") {
1027
+ await HostProcessProbe.run(["taskkill", "/PID", String(pid), "/T", "/F"]);
1028
+ return await this.#released(pid);
1029
+ }
1030
+ if (!this.#signal(pid, "SIGTERM"))
1031
+ return !this.#alive(pid);
1032
+ if (await this.#released(pid))
1033
+ return true;
1034
+ this.#signal(pid, "SIGKILL");
1035
+ await Bun.sleep(DevPortReclaimer.#releasePollMs);
1036
+ return !this.#alive(pid);
703
1037
  }
704
- #applyChildEvent(child, event) {
705
- child.status.state = event.state;
706
- child.status.detail = event.detail ?? "";
707
- if (event.state === "ready") {
708
- if (this.#options.open && !child.opened) {
709
- child.opened = true;
710
- openBrowser(child.status.url);
711
- }
1038
+ async#released(pid) {
1039
+ const deadline = Date.now() + DevPortReclaimer.releaseTimeoutMs;
1040
+ while (Date.now() < deadline) {
1041
+ if (!this.#alive(pid))
1042
+ return true;
1043
+ await Bun.sleep(DevPortReclaimer.#releasePollMs);
712
1044
  }
713
- if (event.state === "failed")
714
- child.markBooted();
715
- this.#publishStatus();
1045
+ return false;
716
1046
  }
717
- async#drain(stream, name, kind) {
718
- const decoder = new TextDecoder;
1047
+ #signal(pid, signal) {
719
1048
  try {
720
- for await (const chunk of stream) {
721
- const text = decoder.decode(chunk, { stream: true });
722
- if (!text)
723
- continue;
724
- this.#view?.onOutput(name, kind, text);
725
- this.#sessionLog.write(name, kind, text);
726
- }
727
- } catch {}
728
- }
729
- #publishStatus() {
730
- this.#view?.onStatus(this.statuses);
731
- this.#sessionLog.status(this.statuses);
1049
+ process.kill(pid, signal);
1050
+ return true;
1051
+ } catch {
1052
+ return false;
1053
+ }
732
1054
  }
733
- #note(text, level) {
734
- this.#view?.onNote(text, level);
735
- this.#sessionLog.note(text);
1055
+ #alive(pid) {
1056
+ try {
1057
+ process.kill(pid, 0);
1058
+ return true;
1059
+ } catch (error) {
1060
+ return error.code === "EPERM";
1061
+ }
736
1062
  }
737
- #installSignalHandlers() {
738
- return new Promise((resolve) => {
739
- let asked = false;
740
- const onSignal = () => {
741
- if (asked) {
742
- this.#note("abandoning the wait; children may be left running", "warn");
743
- process.exit(130);
744
- }
745
- asked = true;
746
- resolve();
747
- };
748
- process.on("SIGINT", onSignal);
749
- process.on("SIGTERM", onSignal);
1063
+ }
1064
+
1065
+ // pkgs/@akanjs/cli/application/devStreamView.ts
1066
+ import { Logger } from "akanjs/common";
1067
+ import chalk from "chalk";
1068
+ var appColors = ["cyan", "magenta", "yellow", "green", "blue", "red"];
1069
+
1070
+ class DevStreamView {
1071
+ #logger = new Logger("akan start");
1072
+ #partial = new Map;
1073
+ #lastState = new Map;
1074
+ #color = new Map;
1075
+ #width = 0;
1076
+ constructor(appNames) {
1077
+ this.#width = appNames.reduce((max, name) => Math.max(max, name.length), 0);
1078
+ appNames.forEach((name, idx) => {
1079
+ this.#color.set(name, appColors[idx % appColors.length] ?? "cyan");
750
1080
  });
751
1081
  }
752
- async restart(name) {
753
- const child = this.#children.get(name);
754
- if (!child || this.#stopping)
1082
+ onOutput = (app, kind, text) => {
1083
+ const key = `${app}:${kind}`;
1084
+ const pending = `${this.#partial.get(key) ?? ""}${text}`;
1085
+ const lines = pending.split(`
1086
+ `);
1087
+ this.#partial.set(key, lines.pop() ?? "");
1088
+ if (lines.length === 0)
755
1089
  return;
756
- const running = child.proc;
757
- if (running) {
758
- running.kill("SIGTERM");
759
- await running.exited;
1090
+ const prefixed = lines.map((line) => `${this.#prefix(app)}${line}`).join(`
1091
+ `);
1092
+ (kind === "stderr" ? process.stderr : process.stdout).write(`${prefixed}
1093
+ `);
1094
+ };
1095
+ onStatus = (statuses) => {
1096
+ for (const status of statuses) {
1097
+ if (this.#lastState.get(status.name) === status.state)
1098
+ continue;
1099
+ this.#lastState.set(status.name, status.state);
1100
+ const detail = status.detail ? ` (${status.detail})` : "";
1101
+ const where = status.state === "ready" ? ` \u2014 ${status.url}` : "";
1102
+ const line = `${status.name} ${status.state}${detail}${where}`;
1103
+ if (status.state === "failed")
1104
+ this.#logger.error(line);
1105
+ else if (status.state === "stopped")
1106
+ this.#logger.warn(line);
1107
+ else
1108
+ this.#logger.info(line);
760
1109
  }
761
- child.status.state = "starting";
762
- child.status.detail = "restarting";
763
- child.status.exitCode = null;
764
- this.#publishStatus();
765
- this.#spawnChild(child);
766
- this.#publishStatus();
767
- }
768
- async stop() {
769
- if (this.#stopping)
770
- return;
771
- this.#stopping = true;
772
- const running = [...this.#children.values()].filter((child) => Boolean(child.proc));
773
- for (const child of running)
774
- child.proc.kill("SIGTERM");
775
- const exited = Promise.all(running.map(async (child) => await child.proc.exited));
776
- if (!await DevSupervisor.timesOut(exited, DevSupervisor.shutdownGraceMs))
777
- return;
778
- for (const child of running) {
779
- if (child.proc.killed)
1110
+ };
1111
+ onNote = (text, level) => {
1112
+ if (level === "warn")
1113
+ this.#logger.warn(text);
1114
+ else
1115
+ this.#logger.info(text);
1116
+ };
1117
+ waitForExit = () => new Promise(() => {
1118
+ return;
1119
+ });
1120
+ close = () => {
1121
+ for (const [key, remainder] of this.#partial) {
1122
+ if (!remainder)
780
1123
  continue;
781
- this.#note(`${child.status.name} did not exit in time; killing it`, "warn");
782
- child.proc.kill("SIGKILL");
1124
+ const app = key.slice(0, key.lastIndexOf(":"));
1125
+ process.stdout.write(`${this.#prefix(app)}${remainder}
1126
+ `);
783
1127
  }
1128
+ this.#partial.clear();
1129
+ };
1130
+ #prefix(app) {
1131
+ const color = this.#color.get(app) ?? "cyan";
1132
+ return `${chalk[color](app.padEnd(this.#width))} ${chalk.dim("\u2502")} `;
784
1133
  }
785
1134
  }
786
1135
 
@@ -919,6 +1268,15 @@ class ApplicationScript extends script("application", [ApplicationRunner, Librar
919
1268
  async logs(app, options) {
920
1269
  await this.applicationRunner.runLogs(app, options);
921
1270
  }
1271
+ async preview(app, { format = "text", ...options }) {
1272
+ const report = await AppPreview.run(app, options);
1273
+ Logger3.rawLog(format === "json" ? JSON.stringify(report, null, 2) : AppPreview.render(report));
1274
+ if (!report.pages.some((page) => page.failed))
1275
+ return;
1276
+ const failure = new ExitCodeError("preview found broken pages", 1);
1277
+ markCliErrorPrinted(failure);
1278
+ throw failure;
1279
+ }
922
1280
  async build(app, {
923
1281
  write = true,
924
1282
  fast = false,
@@ -1054,7 +1412,7 @@ class ApplicationScript extends script("application", [ApplicationRunner, Librar
1054
1412
  throw new Error("No app selected to start");
1055
1413
  const startedDatabase = dbup ? await this.#prepareSharedDatabase(apps) : false;
1056
1414
  const supervisor = new DevSupervisor({ apps, mode, concurrency, open, write, shares });
1057
- const view = mode === "tui" ? new (await import("./devTui-q7k7bakd.js")).DevTui(supervisor) : new DevStreamView(apps.map((app) => app.name));
1415
+ const view = mode === "tui" ? new (await import("./devTui-evr3b35y.js")).DevTui(supervisor) : new DevStreamView(apps.map((app) => app.name));
1058
1416
  await supervisor.run(view);
1059
1417
  if (startedDatabase)
1060
1418
  await this.#stopDatabase(workspace);
@@ -1218,7 +1576,7 @@ class ApplicationScript extends script("application", [ApplicationRunner, Librar
1218
1576
  await Promise.all(shares.map(async (share) => await share.close()));
1219
1577
  }, "Abandoning the tunnel release; the shares expire on their own.");
1220
1578
  await Promise.all(apps.map(async (app) => {
1221
- const { TunnelShare } = await import("./TunnelShare-2p24xxza.js");
1579
+ const { TunnelShare } = await import("./TunnelShare-da9qj2mh.js");
1222
1580
  const share = await TunnelShare.open(app, { workspace: app.workspace });
1223
1581
  shares.push(share);
1224
1582
  urls.set(app.name, share.url);