@elumixor/devkit 0.10.2 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -6
- package/package.json +5 -2
- package/src/ansi.ts +25 -0
- package/src/bin/devkit.ts +4 -2
- package/src/bin/free-port.ts +2 -1
- package/src/config.ts +1 -1
- package/src/deploy-targets/tauri-macos.ts +0 -8
- package/src/dev/board.tsx +328 -0
- package/src/dev/lines.ts +30 -0
- package/src/dev/plain.ts +31 -0
- package/src/dev/processes.ts +85 -0
- package/src/dev/service.ts +143 -0
- package/src/dev/supervisor.ts +157 -0
- package/src/dev.ts +43 -79
- package/src/free-port.ts +17 -22
- package/src/graph.ts +4 -21
- package/src/run-target.ts +1 -1
- package/src/wait-port.ts +16 -7
package/README.md
CHANGED
|
@@ -65,10 +65,28 @@ steps it runs before.
|
|
|
65
65
|
|
|
66
66
|
## Dev
|
|
67
67
|
|
|
68
|
-
`devkit dev` frees the ports
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
68
|
+
`devkit dev` frees the ports and runs everything side by side. A platform is either one process or a
|
|
69
|
+
`processes` map — a web platform is a client and an API, and neither is worth naming as a platform of
|
|
70
|
+
its own.
|
|
71
|
+
|
|
72
|
+
On a terminal it draws a board: every process's URL and state (starting, ready in 1.2s, crashed) pinned
|
|
73
|
+
at the top, the merged log below.
|
|
74
|
+
|
|
75
|
+
```
|
|
76
|
+
devkit dev · budget logs in .devkit/dev
|
|
77
|
+
● 1 web:backend http://localhost:3107 ready in 2.4s
|
|
78
|
+
● 2 web:frontend http://localhost:8087 ready in 2.1s
|
|
79
|
+
── all ─────────────────────────────────────────────────────────────────────────────
|
|
80
|
+
web:frontend │ VITE v8.3.0 ready in 1055 ms
|
|
81
|
+
web:backend │ [nitro] ✔ Nitro Server built in 521ms
|
|
82
|
+
1-2 focus a all o open r restart c clear ↑↓ PgUp PgDn scroll q quit
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
A crashed process stays on the board until you restart it with `r`; the rest keep running. Anywhere
|
|
86
|
+
else (an agent's shell, CI, a pipe, or `--plain`) it prints prefixed lines instead: the URLs first,
|
|
87
|
+
then a `devkit` line for every ready, crash and exit, and one `all ready:` line listing every URL.
|
|
88
|
+
Either way, each process's full output is in `.devkit/dev/<name>.log`. With `--open`, every `open`
|
|
89
|
+
process's URL opens once its port answers.
|
|
72
90
|
|
|
73
91
|
| field | meaning |
|
|
74
92
|
| ----------- | ----------------------------------------------------------------------------- |
|
|
@@ -78,9 +96,9 @@ a platform of its own.
|
|
|
78
96
|
| `script` | script to run in the workspace (default `dev`) |
|
|
79
97
|
| `command` | raw shell command, overrides the above (e.g. `vite dev`) |
|
|
80
98
|
| `type` | a built-in dev target — see below |
|
|
81
|
-
| `port` | freed on start
|
|
99
|
+
| `port` | freed on start, shown on the board, and polled to tell when it is ready |
|
|
82
100
|
| `needs` | platforms that must be running too |
|
|
83
|
-
| `color` |
|
|
101
|
+
| `color` | label colour; one is picked for you otherwise |
|
|
84
102
|
| `open` | with `--open`, open this process's URL when its port comes up |
|
|
85
103
|
|
|
86
104
|
### Built-in dev targets
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@elumixor/devkit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.0",
|
|
4
4
|
"description": "Dev orchestrator for bun monorepos — free ports, run apps side-by-side, open the browser when ready",
|
|
5
5
|
"author": "elumixor",
|
|
6
6
|
"license": "ISC",
|
|
@@ -26,11 +26,14 @@
|
|
|
26
26
|
"release:major": "npm version major -m \"Release v%s\" && git push --follow-tags"
|
|
27
27
|
},
|
|
28
28
|
"dependencies": {
|
|
29
|
-
"
|
|
29
|
+
"ink": "7.1.1",
|
|
30
|
+
"react": "19.2.8",
|
|
31
|
+
"wrap-ansi": "10.0.2"
|
|
30
32
|
},
|
|
31
33
|
"devDependencies": {
|
|
32
34
|
"@biomejs/biome": "^2.4.8",
|
|
33
35
|
"@types/bun": "latest",
|
|
36
|
+
"@types/react": "19.2.18",
|
|
34
37
|
"typescript": "^5"
|
|
35
38
|
}
|
|
36
39
|
}
|
package/src/ansi.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/** Terminal colour helpers shared by the build board and the plain dev log. */
|
|
2
|
+
|
|
3
|
+
export const PALETTE: readonly string[] = ["magenta", "cyan", "yellow", "green", "blue", "red"];
|
|
4
|
+
|
|
5
|
+
const COLORS: Record<string, string> = {
|
|
6
|
+
black: "30",
|
|
7
|
+
red: "31",
|
|
8
|
+
green: "32",
|
|
9
|
+
yellow: "33",
|
|
10
|
+
blue: "34",
|
|
11
|
+
magenta: "35",
|
|
12
|
+
cyan: "36",
|
|
13
|
+
white: "37",
|
|
14
|
+
gray: "90",
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export const paint = (text: string, color: string) => `\x1b[${COLORS[color] ?? "37"}m${text}\x1b[0m`;
|
|
18
|
+
export const dim = (text: string) => `\x1b[2m${text}\x1b[0m`;
|
|
19
|
+
export const bold = (text: string) => `\x1b[1m${text}\x1b[0m`;
|
|
20
|
+
|
|
21
|
+
// Colour codes take no space on screen, so anything that lays text out has to measure what a reader would see.
|
|
22
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: an escape sequence is the thing being matched
|
|
23
|
+
export const SGR = /\x1b\[[0-9;]*m/g;
|
|
24
|
+
export const stripColor = (text: string) => text.replace(SGR, "");
|
|
25
|
+
export const visibleLength = (text: string) => stripColor(text).length;
|
package/src/bin/devkit.ts
CHANGED
|
@@ -16,6 +16,7 @@ import { runVersion } from "../version.ts";
|
|
|
16
16
|
const { values, positionals } = parseArgs({
|
|
17
17
|
options: {
|
|
18
18
|
open: { type: "boolean", default: false },
|
|
19
|
+
plain: { type: "boolean", default: false },
|
|
19
20
|
real: { type: "boolean", default: false },
|
|
20
21
|
device: { type: "string" },
|
|
21
22
|
dry: { type: "boolean", default: false },
|
|
@@ -47,6 +48,7 @@ const usage = `usage: devkit dev [platforms...] run the dev processes
|
|
|
47
48
|
typically web, mac, iphone, iwatch. Naming one also runs the platforms it declares in "needs".
|
|
48
49
|
|
|
49
50
|
--open open each dev process's URL in the browser once its port is live
|
|
51
|
+
--plain dev: print prefixed lines instead of the live board (automatic when not a terminal)
|
|
50
52
|
--dry print what would run without running it
|
|
51
53
|
--verbose stream every line instead of drawing the live board (build, deploy)
|
|
52
54
|
--real run a simulator against the real API instead of sample data
|
|
@@ -75,7 +77,7 @@ function chdirTo(dir?: string) {
|
|
|
75
77
|
try {
|
|
76
78
|
switch (command) {
|
|
77
79
|
case "dev": {
|
|
78
|
-
await runDev(platforms, { open: values.open, dry: values.dry });
|
|
80
|
+
await runDev(platforms, { open: values.open, dry: values.dry, plain: values.plain });
|
|
79
81
|
break;
|
|
80
82
|
}
|
|
81
83
|
case "build": {
|
|
@@ -87,7 +89,7 @@ try {
|
|
|
87
89
|
break;
|
|
88
90
|
}
|
|
89
91
|
// Internal: how a `type`d step actually runs — spawned as its own process by the graph (or by
|
|
90
|
-
//
|
|
92
|
+
// the dev supervisor) so it gets that step's own line on the board and its own log file.
|
|
91
93
|
case "_run": {
|
|
92
94
|
const [phase, name] = rest;
|
|
93
95
|
if (!isPhase(phase) || !name) throw new Error("usage: devkit _run <phase> <platform>");
|
package/src/bin/free-port.ts
CHANGED
package/src/config.ts
CHANGED
|
@@ -34,7 +34,7 @@ export interface DevProcess extends Step {
|
|
|
34
34
|
cwd?: string;
|
|
35
35
|
/** Script to run in the workspace (default `dev`). */
|
|
36
36
|
script?: string;
|
|
37
|
-
/** Port to free on start
|
|
37
|
+
/** Port to free on start, show on the board, and poll for readiness. */
|
|
38
38
|
port?: number;
|
|
39
39
|
/** With `--open`, open this process's URL once its port is live. */
|
|
40
40
|
open?: boolean;
|
|
@@ -11,8 +11,6 @@ export interface TauriMacosTargetOptions {
|
|
|
11
11
|
stageDir?: string;
|
|
12
12
|
/** Reinstall to `/Applications/<name>.app` after building, if it's already there (default true). */
|
|
13
13
|
installIfPresent?: boolean;
|
|
14
|
-
/** Open the reinstalled app once it's in place, so the deploy ends on the new build running (default true). */
|
|
15
|
-
relaunch?: boolean;
|
|
16
14
|
/** App Store Connect key env vars, for notarization (defaults match the iOS release). */
|
|
17
15
|
keyIdEnv?: string;
|
|
18
16
|
issuerIdEnv?: string;
|
|
@@ -100,12 +98,6 @@ export async function deployTauriMacos(options: TauriMacosTargetOptions = {}) {
|
|
|
100
98
|
await $`cp -R ${appBundle} ${installed}`;
|
|
101
99
|
await $`xattr -cr ${installed}`.nothrow().quiet();
|
|
102
100
|
console.log(`Reinstalled ${installed}`);
|
|
103
|
-
// The old copy was quit to make room; leaving the new one closed reads as "nothing happened",
|
|
104
|
-
// and the DMG gets dragged into /Applications by hand over a build that is already there.
|
|
105
|
-
if (options.relaunch ?? true) {
|
|
106
|
-
await $`open ${installed}`.nothrow();
|
|
107
|
-
console.log(`Opened ${installed}`);
|
|
108
|
-
}
|
|
109
101
|
}
|
|
110
102
|
|
|
111
103
|
/** Sends the disk image to Apple and staples their answer into it, so it opens offline too. */
|
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
/** @jsxImportSource react */
|
|
2
|
+
import { relative } from "node:path";
|
|
3
|
+
import { Box, render, Text, useApp, useInput, useStdout } from "ink";
|
|
4
|
+
import { useEffect, useMemo, useState, useSyncExternalStore } from "react";
|
|
5
|
+
import wrapAnsi from "wrap-ansi";
|
|
6
|
+
import type { Service, ServiceState } from "./service.ts";
|
|
7
|
+
import { DEVKIT, type LogEntry, type Supervisor } from "./supervisor.ts";
|
|
8
|
+
|
|
9
|
+
const SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|
|
10
|
+
const FRAME_MS = 80;
|
|
11
|
+
/** Lines can arrive by the thousand during a compile; the board redraws at most this often. */
|
|
12
|
+
const REDRAW_MS = 50;
|
|
13
|
+
/** Title, separator and key hints around the log. */
|
|
14
|
+
const CHROME_ROWS = 3;
|
|
15
|
+
/** Ink falls back to clearing the whole screen once a frame fills it, which flickers. */
|
|
16
|
+
const SPARE_ROWS = 1;
|
|
17
|
+
const MIN_LOG_WIDTH = 20;
|
|
18
|
+
|
|
19
|
+
const MARK: Record<ServiceState, { glyph: string; color: string }> = {
|
|
20
|
+
starting: { glyph: "", color: "yellow" },
|
|
21
|
+
ready: { glyph: "●", color: "green" },
|
|
22
|
+
running: { glyph: "●", color: "green" },
|
|
23
|
+
stopping: { glyph: "", color: "gray" },
|
|
24
|
+
stopped: { glyph: "○", color: "gray" },
|
|
25
|
+
exited: { glyph: "○", color: "gray" },
|
|
26
|
+
crashed: { glyph: "✗", color: "red" },
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The interactive dev screen: every service's URL and state pinned at the top, the merged log
|
|
31
|
+
* below. Runs in the alternate screen, like `less`, and gives the terminal back on quit.
|
|
32
|
+
*/
|
|
33
|
+
export async function runBoard(supervisor: Supervisor, title: string) {
|
|
34
|
+
const app = render(<Board supervisor={supervisor} title={title} />, {
|
|
35
|
+
alternateScreen: true,
|
|
36
|
+
exitOnCtrlC: false,
|
|
37
|
+
});
|
|
38
|
+
await app.waitUntilExit();
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function Board({ supervisor, title }: { readonly supervisor: Supervisor; readonly title: string }) {
|
|
42
|
+
const { exit } = useApp();
|
|
43
|
+
const { cols, rows } = useTerminalSize();
|
|
44
|
+
useThrottledVersion(supervisor);
|
|
45
|
+
const frame = useFrame(supervisor.services.some((s) => s.state === "starting" || s.state === "stopping"));
|
|
46
|
+
|
|
47
|
+
const [focus, setFocus] = useState<number | null>(null);
|
|
48
|
+
/** `seq` the view ends before while scrolled back; `null` follows the newest line. */
|
|
49
|
+
const [end, setEnd] = useState<number | null>(null);
|
|
50
|
+
const [quitting, setQuitting] = useState(false);
|
|
51
|
+
|
|
52
|
+
const services = supervisor.services;
|
|
53
|
+
const logRows = Math.max(1, rows - CHROME_ROWS - SPARE_ROWS - services.length);
|
|
54
|
+
const labelWidth = Math.max("devkit".length, ...services.map((s) => s.spec.label.length));
|
|
55
|
+
const textWidth = Math.max(MIN_LOG_WIDTH, cols - labelWidth - 3);
|
|
56
|
+
|
|
57
|
+
const shown = supervisor.entries.filter(
|
|
58
|
+
(entry) => focus == null || entry.source === focus || entry.source === DEVKIT,
|
|
59
|
+
);
|
|
60
|
+
const endIndex = end == null ? shown.length : countBefore(shown, end);
|
|
61
|
+
const who = (source: number) =>
|
|
62
|
+
source === DEVKIT
|
|
63
|
+
? { label: "devkit", color: "gray" }
|
|
64
|
+
: { label: services[source]?.spec.label ?? "", color: services[source]?.spec.color ?? "white" };
|
|
65
|
+
const lines = tail(shown, endIndex, logRows, textWidth, who);
|
|
66
|
+
const newer = shown.length - endIndex;
|
|
67
|
+
|
|
68
|
+
const scroll = (by: number) => {
|
|
69
|
+
const next = Math.min(shown.length, Math.max(firstFullScreen(shown, logRows, textWidth), endIndex + by));
|
|
70
|
+
setEnd(next >= shown.length ? null : (shown[next]?.seq ?? null));
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
const quit = () => {
|
|
74
|
+
if (quitting) return;
|
|
75
|
+
setQuitting(true);
|
|
76
|
+
void supervisor.stop().then(() => exit());
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
useInput((input, key) => {
|
|
80
|
+
if (input === "q" || (key.ctrl && input === "c")) return quit();
|
|
81
|
+
// Before Escape: Ink flags `escape` on every escape sequence, arrows and paging included.
|
|
82
|
+
if (key.upArrow || input === "k") return scroll(-1);
|
|
83
|
+
if (key.downArrow || input === "j") return scroll(1);
|
|
84
|
+
if (key.pageUp) return scroll(-(logRows - 1));
|
|
85
|
+
if (key.pageDown) return scroll(logRows - 1);
|
|
86
|
+
const digit = Number(input);
|
|
87
|
+
if (Number.isInteger(digit) && digit >= 1 && digit <= services.length) {
|
|
88
|
+
setFocus(focus === digit - 1 ? null : digit - 1);
|
|
89
|
+
return setEnd(null);
|
|
90
|
+
}
|
|
91
|
+
if (input === "a" || input === "0" || key.escape) {
|
|
92
|
+
setFocus(null);
|
|
93
|
+
return setEnd(null);
|
|
94
|
+
}
|
|
95
|
+
if (input === "o") return void supervisor.openService(openTarget(services, focus));
|
|
96
|
+
if (input === "r") return void supervisor.restart(focus ?? undefined);
|
|
97
|
+
if (input === "c") {
|
|
98
|
+
supervisor.clear();
|
|
99
|
+
return setEnd(null);
|
|
100
|
+
}
|
|
101
|
+
if (key.end || input === "G" || input === "f") setEnd(null);
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
return (
|
|
105
|
+
<Box flexDirection="column" width={cols} height={rows - SPARE_ROWS}>
|
|
106
|
+
<Box justifyContent="space-between">
|
|
107
|
+
<Text>
|
|
108
|
+
<Text bold> devkit dev</Text>
|
|
109
|
+
<Text dimColor> · {title}</Text>
|
|
110
|
+
{quitting && <Text color="yellow"> · stopping…</Text>}
|
|
111
|
+
</Text>
|
|
112
|
+
<Text dimColor>logs in {relative(process.cwd(), supervisor.logDir)} </Text>
|
|
113
|
+
</Box>
|
|
114
|
+
{services.map((service, i) => (
|
|
115
|
+
<ServiceRow
|
|
116
|
+
key={service.spec.label}
|
|
117
|
+
service={service}
|
|
118
|
+
index={i}
|
|
119
|
+
focused={focus === i}
|
|
120
|
+
labelWidth={labelWidth}
|
|
121
|
+
frame={frame}
|
|
122
|
+
/>
|
|
123
|
+
))}
|
|
124
|
+
<Text dimColor wrap="truncate-end">
|
|
125
|
+
{`── ${focus == null ? "all" : services[focus]?.spec.label} `.padEnd(cols, "─")}
|
|
126
|
+
</Text>
|
|
127
|
+
<Box flexDirection="column" height={logRows} overflow="hidden">
|
|
128
|
+
{lines.map((line) => (
|
|
129
|
+
<Box key={line.key}>
|
|
130
|
+
<Text color={line.color}>{(line.first ? line.label : "").padEnd(labelWidth)}</Text>
|
|
131
|
+
<Text dimColor> │ </Text>
|
|
132
|
+
<Text wrap="truncate-end">{line.text}</Text>
|
|
133
|
+
</Box>
|
|
134
|
+
))}
|
|
135
|
+
</Box>
|
|
136
|
+
<Footer count={services.length} newer={end == null ? 0 : newer} />
|
|
137
|
+
</Box>
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function ServiceRow({
|
|
142
|
+
service,
|
|
143
|
+
index,
|
|
144
|
+
focused,
|
|
145
|
+
labelWidth,
|
|
146
|
+
frame,
|
|
147
|
+
}: {
|
|
148
|
+
readonly service: Service;
|
|
149
|
+
readonly index: number;
|
|
150
|
+
readonly focused: boolean;
|
|
151
|
+
readonly labelWidth: number;
|
|
152
|
+
readonly frame: number;
|
|
153
|
+
}) {
|
|
154
|
+
const mark = MARK[service.state];
|
|
155
|
+
return (
|
|
156
|
+
<Text wrap="truncate-end">
|
|
157
|
+
{" "}
|
|
158
|
+
<Text color={mark.color}>{mark.glyph || SPINNER[frame % SPINNER.length]}</Text>
|
|
159
|
+
<Text dimColor> {index + 1} </Text>
|
|
160
|
+
<Text color={service.spec.color} bold={focused} inverse={focused}>
|
|
161
|
+
{service.spec.label.padEnd(labelWidth)}
|
|
162
|
+
</Text>
|
|
163
|
+
{" "}
|
|
164
|
+
<Text bold>{(service.url ?? "").padEnd(24)}</Text>
|
|
165
|
+
<StateText service={service} />
|
|
166
|
+
</Text>
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function StateText({ service }: { readonly service: Service }) {
|
|
171
|
+
const since = seconds(Date.now() - service.startedAt);
|
|
172
|
+
switch (service.state) {
|
|
173
|
+
case "starting":
|
|
174
|
+
return <Text color="yellow">starting {since}</Text>;
|
|
175
|
+
case "ready":
|
|
176
|
+
return (
|
|
177
|
+
<Text color="green">
|
|
178
|
+
ready<Text dimColor> in {seconds(service.readyMs ?? 0)}</Text>
|
|
179
|
+
</Text>
|
|
180
|
+
);
|
|
181
|
+
case "running":
|
|
182
|
+
return <Text color="green">running</Text>;
|
|
183
|
+
case "stopping":
|
|
184
|
+
return <Text dimColor>stopping…</Text>;
|
|
185
|
+
case "stopped":
|
|
186
|
+
return <Text dimColor>stopped · r to start</Text>;
|
|
187
|
+
case "exited":
|
|
188
|
+
return <Text dimColor>exited · r to start</Text>;
|
|
189
|
+
case "crashed":
|
|
190
|
+
return (
|
|
191
|
+
<Text color="red">
|
|
192
|
+
crashed{service.code != null ? ` (exit ${service.code})` : ""}
|
|
193
|
+
<Text dimColor> · r to restart</Text>
|
|
194
|
+
</Text>
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function Footer({ count, newer }: { readonly count: number; readonly newer: number }) {
|
|
200
|
+
const keys = [
|
|
201
|
+
[count > 1 ? `1-${count}` : "1", "focus"],
|
|
202
|
+
["a", "all"],
|
|
203
|
+
["o", "open"],
|
|
204
|
+
["r", "restart"],
|
|
205
|
+
["c", "clear"],
|
|
206
|
+
["↑↓ PgUp PgDn", "scroll"],
|
|
207
|
+
["q", "quit"],
|
|
208
|
+
];
|
|
209
|
+
return (
|
|
210
|
+
<Text wrap="truncate-end">
|
|
211
|
+
{" "}
|
|
212
|
+
{newer > 0 && <Text color="yellow">paused · {newer} newer · f to follow </Text>}
|
|
213
|
+
{keys.map(([key, label]) => (
|
|
214
|
+
<Text key={label}>
|
|
215
|
+
<Text bold>{key}</Text>
|
|
216
|
+
<Text dimColor> {label} </Text>
|
|
217
|
+
</Text>
|
|
218
|
+
))}
|
|
219
|
+
</Text>
|
|
220
|
+
);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
interface LogLine {
|
|
224
|
+
readonly key: string;
|
|
225
|
+
readonly label: string;
|
|
226
|
+
readonly color: string;
|
|
227
|
+
readonly text: string;
|
|
228
|
+
/** Only an entry's first wrapped row carries its label. */
|
|
229
|
+
readonly first: boolean;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** The last `count` screen rows of `entries[0, endIndex)`, wrapped to `width`. */
|
|
233
|
+
function tail(
|
|
234
|
+
entries: readonly LogEntry[],
|
|
235
|
+
endIndex: number,
|
|
236
|
+
count: number,
|
|
237
|
+
width: number,
|
|
238
|
+
who: (source: number) => { label: string; color: string },
|
|
239
|
+
): LogLine[] {
|
|
240
|
+
const out: LogLine[] = [];
|
|
241
|
+
for (let i = endIndex - 1; i >= 0 && out.length < count; i--) {
|
|
242
|
+
const entry = entries[i] as LogEntry;
|
|
243
|
+
const rows = wrapAnsi(entry.text, width, { hard: true, trim: false }).split("\n");
|
|
244
|
+
for (let row = rows.length - 1; row >= 0 && out.length < count; row--)
|
|
245
|
+
out.push({ key: `${entry.seq}:${row}`, text: rows[row] ?? "", first: row === 0, ...who(entry.source) });
|
|
246
|
+
}
|
|
247
|
+
return out.reverse();
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const heightOf = (entry: LogEntry, width: number) =>
|
|
251
|
+
wrapAnsi(entry.text, width, { hard: true, trim: false }).split("\n").length;
|
|
252
|
+
|
|
253
|
+
/** The fewest leading entries that fill the log — scrolling back further would only show blank rows. */
|
|
254
|
+
function firstFullScreen(entries: readonly LogEntry[], rows: number, width: number) {
|
|
255
|
+
let filled = 0;
|
|
256
|
+
for (let i = 0; i < entries.length; i++) {
|
|
257
|
+
filled += heightOf(entries[i] as LogEntry, width);
|
|
258
|
+
if (filled >= rows) return i + 1;
|
|
259
|
+
}
|
|
260
|
+
return entries.length;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** How many entries come before `seq` — entries are in `seq` order. */
|
|
264
|
+
function countBefore(entries: readonly LogEntry[], seq: number) {
|
|
265
|
+
let low = 0;
|
|
266
|
+
let high = entries.length;
|
|
267
|
+
while (low < high) {
|
|
268
|
+
const mid = (low + high) >> 1;
|
|
269
|
+
if ((entries[mid] as LogEntry).seq < seq) low = mid + 1;
|
|
270
|
+
else high = mid;
|
|
271
|
+
}
|
|
272
|
+
return low;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** The focused service, else the one marked `open`, else the first with a URL. */
|
|
276
|
+
function openTarget(services: readonly Service[], focus: number | null) {
|
|
277
|
+
if (focus != null) return focus;
|
|
278
|
+
const marked = services.findIndex((service) => service.url && service.spec.open);
|
|
279
|
+
return marked >= 0 ? marked : services.findIndex((service) => service.url);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function useThrottledVersion(supervisor: Supervisor) {
|
|
283
|
+
const subscribe = useMemo(
|
|
284
|
+
() => (notify: () => void) => {
|
|
285
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
286
|
+
const unsubscribe = supervisor.subscribe(() => {
|
|
287
|
+
timer ??= setTimeout(() => {
|
|
288
|
+
timer = undefined;
|
|
289
|
+
notify();
|
|
290
|
+
}, REDRAW_MS);
|
|
291
|
+
});
|
|
292
|
+
return () => {
|
|
293
|
+
unsubscribe();
|
|
294
|
+
clearTimeout(timer);
|
|
295
|
+
};
|
|
296
|
+
},
|
|
297
|
+
[supervisor],
|
|
298
|
+
);
|
|
299
|
+
return useSyncExternalStore(subscribe, () => supervisor.version);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** Ticks while something is in motion, for spinners and the "starting 3s" clock. */
|
|
303
|
+
function useFrame(active: boolean) {
|
|
304
|
+
const [frame, setFrame] = useState(0);
|
|
305
|
+
useEffect(() => {
|
|
306
|
+
if (!active) return;
|
|
307
|
+
const timer = setInterval(() => setFrame((n) => n + 1), FRAME_MS);
|
|
308
|
+
return () => clearInterval(timer);
|
|
309
|
+
}, [active]);
|
|
310
|
+
return frame;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
function useTerminalSize() {
|
|
314
|
+
const { stdout } = useStdout();
|
|
315
|
+
// A pty with no window size reports 0 — fall back to something drawable rather than nothing.
|
|
316
|
+
const read = () => ({ cols: stdout.columns || 100, rows: stdout.rows || 30 });
|
|
317
|
+
const [size, setSize] = useState(read);
|
|
318
|
+
useEffect(() => {
|
|
319
|
+
const onResize = () => setSize(read());
|
|
320
|
+
stdout.on("resize", onResize);
|
|
321
|
+
return () => {
|
|
322
|
+
stdout.off("resize", onResize);
|
|
323
|
+
};
|
|
324
|
+
});
|
|
325
|
+
return size;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
const seconds = (ms: number) => `${(ms / 1000).toFixed(ms < 10_000 ? 1 : 0)}s`;
|
package/src/dev/lines.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { Readable } from "node:stream";
|
|
2
|
+
|
|
3
|
+
// Cursor moves, screen clears and window titles would tear the board apart; colours are kept.
|
|
4
|
+
const CONTROL =
|
|
5
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: escape sequences are the thing being matched
|
|
6
|
+
/\x1b\[[0-9;?]*[A-Za-ln-z]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[=>()][0-9A-Za-z]?|[\x00-\x08\x0b-\x1a\x7f]/g;
|
|
7
|
+
const TAB = " ";
|
|
8
|
+
|
|
9
|
+
/** One printed line as a reader saw it: a `\r` redraw keeps only what was drawn last. */
|
|
10
|
+
export function cleanLine(raw: string): string {
|
|
11
|
+
const line = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
|
|
12
|
+
return line
|
|
13
|
+
.slice(line.lastIndexOf("\r") + 1)
|
|
14
|
+
.replace(CONTROL, "")
|
|
15
|
+
.replaceAll("\t", TAB);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Calls `onLine` for every complete line the stream prints, and for the unterminated rest at its end. */
|
|
19
|
+
export function eachLine(stream: Readable, onLine: (line: string) => void) {
|
|
20
|
+
let rest = "";
|
|
21
|
+
stream.setEncoding("utf8");
|
|
22
|
+
stream.on("data", (chunk: string) => {
|
|
23
|
+
const parts = (rest + chunk).split("\n");
|
|
24
|
+
rest = parts.pop() ?? "";
|
|
25
|
+
for (const part of parts) onLine(part);
|
|
26
|
+
});
|
|
27
|
+
stream.on("end", () => {
|
|
28
|
+
if (rest) onLine(rest);
|
|
29
|
+
});
|
|
30
|
+
}
|
package/src/dev/plain.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { relative } from "node:path";
|
|
2
|
+
import { paint, stripColor } from "../ansi.ts";
|
|
3
|
+
import { DEVKIT, type Supervisor } from "./supervisor.ts";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Prefixed line-by-line output for anything that is not a person at a terminal — an agent's shell,
|
|
7
|
+
* CI, a pipe. URLs come first, every state change is its own `devkit` line, and once every server
|
|
8
|
+
* answers one line lists them all, so a reader that only greps still finds where things are.
|
|
9
|
+
*/
|
|
10
|
+
export function printPlain(supervisor: Supervisor, color: boolean) {
|
|
11
|
+
const { services } = supervisor;
|
|
12
|
+
const width = Math.max("devkit".length, ...services.map((service) => service.spec.label.length));
|
|
13
|
+
const tag = (source: number) => {
|
|
14
|
+
const label = (source === DEVKIT ? "devkit" : (services[source]?.spec.label ?? "")).padEnd(width);
|
|
15
|
+
return color ? paint(label, source === DEVKIT ? "gray" : (services[source]?.spec.color ?? "white")) : label;
|
|
16
|
+
};
|
|
17
|
+
const say = (text: string) => console.log(`${tag(DEVKIT)} │ ${text}`);
|
|
18
|
+
|
|
19
|
+
say(`dev · logs in ${relative(process.cwd(), supervisor.logDir)}`);
|
|
20
|
+
for (const service of services) if (service.url) say(` ${service.spec.label.padEnd(width)} ${service.url}`);
|
|
21
|
+
|
|
22
|
+
supervisor.onEntry((entry) => console.log(`${tag(entry.source)} │ ${color ? entry.text : stripColor(entry.text)}`));
|
|
23
|
+
|
|
24
|
+
const servers = services.filter((service) => service.url);
|
|
25
|
+
let announced = false;
|
|
26
|
+
supervisor.subscribe(() => {
|
|
27
|
+
if (announced || !servers.length || servers.some((service) => service.state !== "ready")) return;
|
|
28
|
+
announced = true;
|
|
29
|
+
say(`all ready: ${servers.map((service) => `${service.spec.label} ${service.url}`).join(" · ")}`);
|
|
30
|
+
});
|
|
31
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { Glob } from "bun";
|
|
4
|
+
import { PALETTE } from "../ansi.ts";
|
|
5
|
+
import type { DevPlatform, DevProcess, Named } from "../config.ts";
|
|
6
|
+
|
|
7
|
+
/** One line of the dev board: a name, a shell command, and whatever its header row needs. */
|
|
8
|
+
export interface ServiceSpec {
|
|
9
|
+
/** What this line is called on screen. */
|
|
10
|
+
readonly label: string;
|
|
11
|
+
readonly command: string;
|
|
12
|
+
readonly color: string;
|
|
13
|
+
readonly port?: number;
|
|
14
|
+
/** With `--open`, open this URL once the port answers. */
|
|
15
|
+
readonly open: boolean;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Flatten a platform into the processes it runs — a web platform is a client and an API. */
|
|
19
|
+
function processesOf(platform: Named<DevPlatform>): (DevProcess & { label: string; platform: string })[] {
|
|
20
|
+
const group = platform.processes;
|
|
21
|
+
if (!group) return [{ ...platform, label: platform.name, platform: platform.name }];
|
|
22
|
+
if (platform.type) throw new Error(`"devkit.dev.${platform.name}" has both a "type" and "processes"`);
|
|
23
|
+
|
|
24
|
+
const keys = Object.keys(group);
|
|
25
|
+
if (!keys.length) throw new Error(`"devkit.dev.${platform.name}.processes" is empty`);
|
|
26
|
+
return keys.map((key) => {
|
|
27
|
+
const process = group[key] as DevProcess;
|
|
28
|
+
return {
|
|
29
|
+
...process,
|
|
30
|
+
// The workspace a bare process runs in is named by its key, not by the platform's.
|
|
31
|
+
filter: process.filter ?? key,
|
|
32
|
+
// A platform that runs one process is that process; several need telling apart.
|
|
33
|
+
label: keys.length === 1 ? platform.name : `${platform.name}:${key}`,
|
|
34
|
+
platform: platform.name,
|
|
35
|
+
};
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Workspace package name to its directory, from the root `package.json` `workspaces` globs. */
|
|
40
|
+
function workspaceDirs(): Map<string, string> {
|
|
41
|
+
const root = JSON.parse(readFileSync("package.json", "utf8")) as {
|
|
42
|
+
workspaces?: string[] | { packages?: string[] };
|
|
43
|
+
};
|
|
44
|
+
const patterns = Array.isArray(root.workspaces) ? root.workspaces : (root.workspaces?.packages ?? []);
|
|
45
|
+
const dirs = new Map<string, string>();
|
|
46
|
+
for (const pattern of patterns)
|
|
47
|
+
for (const manifest of new Glob(join(pattern, "package.json")).scanSync({ onlyFiles: true })) {
|
|
48
|
+
const { name } = JSON.parse(readFileSync(manifest, "utf8")) as { name?: string };
|
|
49
|
+
if (name) dirs.set(name, dirname(manifest));
|
|
50
|
+
}
|
|
51
|
+
return dirs;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Turn a process entry into the shell command that runs it. */
|
|
55
|
+
function commandFor(
|
|
56
|
+
process: DevProcess & { label: string; platform: string },
|
|
57
|
+
workspaces: Map<string, string>,
|
|
58
|
+
): string {
|
|
59
|
+
// A raw command still honours `cwd` — `bunx tauri dev` means the app's directory, not the root.
|
|
60
|
+
if (process.command)
|
|
61
|
+
return process.cwd ? `sh -c ${JSON.stringify(`cd ${process.cwd} && ${process.command}`)}` : process.command;
|
|
62
|
+
// A built-in dev target runs through `devkit _run dev`, which looks its options back up from
|
|
63
|
+
// this same config — the same trick the build and deploy graphs use.
|
|
64
|
+
if (process.type) return `devkit _run dev ${JSON.stringify(process.platform)}`;
|
|
65
|
+
const script = process.script ?? "dev";
|
|
66
|
+
// `bun --filter` would prefix every line with the package name and add its own exit banner, so a
|
|
67
|
+
// filter naming one workspace runs straight in that workspace's directory instead.
|
|
68
|
+
const filter = process.filter ?? process.label;
|
|
69
|
+
const cwd = process.cwd ?? workspaces.get(filter);
|
|
70
|
+
if (cwd) return `bun run --cwd ${cwd} ${script}`;
|
|
71
|
+
return `bun --filter ${filter} ${script}`;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function servicesOf(platforms: Named<DevPlatform>[]): ServiceSpec[] {
|
|
75
|
+
const workspaces = workspaceDirs();
|
|
76
|
+
return platforms.flatMap(processesOf).map((process, i) => ({
|
|
77
|
+
label: process.label,
|
|
78
|
+
command: commandFor(process, workspaces),
|
|
79
|
+
color: process.color ?? (PALETTE[i % PALETTE.length] as string),
|
|
80
|
+
port: process.port,
|
|
81
|
+
open: Boolean(process.open),
|
|
82
|
+
}));
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export const urlOf = (spec: ServiceSpec) => (spec.port != null ? `http://localhost:${spec.port}` : undefined);
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { type ChildProcess, spawn } from "node:child_process";
|
|
2
|
+
import { freePort } from "../free-port.ts";
|
|
3
|
+
import { probePort } from "../wait-port.ts";
|
|
4
|
+
import { eachLine } from "./lines.ts";
|
|
5
|
+
import { type ServiceSpec, urlOf } from "./processes.ts";
|
|
6
|
+
|
|
7
|
+
export type ServiceState = "starting" | "ready" | "running" | "stopping" | "stopped" | "exited" | "crashed";
|
|
8
|
+
|
|
9
|
+
const PROBE_INTERVAL_MS = 400;
|
|
10
|
+
/** `bun run` reports being stopped as an error, which it isn't when devkit asked for it. */
|
|
11
|
+
const STOPPED_BY_US = /terminated by signal SIG(TERM|INT|KILL)/;
|
|
12
|
+
const KILL_GRACE_MS = 3_000;
|
|
13
|
+
|
|
14
|
+
/** What a service reports back to whoever supervises it. */
|
|
15
|
+
export interface ServiceHooks {
|
|
16
|
+
readonly line: (text: string) => void;
|
|
17
|
+
/** A line about the service from devkit itself — readiness, exits, restarts. */
|
|
18
|
+
readonly note: (text: string) => void;
|
|
19
|
+
readonly changed: () => void;
|
|
20
|
+
readonly ready: () => void;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** One dev process: spawns it in its own process group, watches its port, and stops the whole group. */
|
|
24
|
+
export class Service {
|
|
25
|
+
readonly spec: ServiceSpec;
|
|
26
|
+
readonly url: string | undefined;
|
|
27
|
+
readonly #hooks: ServiceHooks;
|
|
28
|
+
readonly #env: NodeJS.ProcessEnv;
|
|
29
|
+
#state: ServiceState = "stopped";
|
|
30
|
+
#code: number | null = null;
|
|
31
|
+
#startedAt = 0;
|
|
32
|
+
#readyMs: number | null = null;
|
|
33
|
+
#child: ChildProcess | undefined;
|
|
34
|
+
#closed: Promise<void> = Promise.resolve();
|
|
35
|
+
#run = 0;
|
|
36
|
+
|
|
37
|
+
constructor(spec: ServiceSpec, env: NodeJS.ProcessEnv, hooks: ServiceHooks) {
|
|
38
|
+
this.spec = spec;
|
|
39
|
+
this.url = urlOf(spec);
|
|
40
|
+
this.#env = env;
|
|
41
|
+
this.#hooks = hooks;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
get state(): ServiceState {
|
|
45
|
+
return this.#state;
|
|
46
|
+
}
|
|
47
|
+
get code(): number | null {
|
|
48
|
+
return this.#code;
|
|
49
|
+
}
|
|
50
|
+
get startedAt(): number {
|
|
51
|
+
return this.#startedAt;
|
|
52
|
+
}
|
|
53
|
+
get readyMs(): number | null {
|
|
54
|
+
return this.#readyMs;
|
|
55
|
+
}
|
|
56
|
+
get alive(): boolean {
|
|
57
|
+
return this.#state === "starting" || this.#state === "ready" || this.#state === "running";
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
start() {
|
|
61
|
+
const run = ++this.#run;
|
|
62
|
+
this.#state = this.spec.port != null ? "starting" : "running";
|
|
63
|
+
this.#code = null;
|
|
64
|
+
this.#readyMs = null;
|
|
65
|
+
this.#startedAt = Date.now();
|
|
66
|
+
|
|
67
|
+
// Its own process group, so stopping it also stops whatever `bun run` or `sh -c` started under it.
|
|
68
|
+
const child = spawn(this.spec.command, {
|
|
69
|
+
shell: true,
|
|
70
|
+
detached: true,
|
|
71
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
72
|
+
env: this.#env,
|
|
73
|
+
});
|
|
74
|
+
this.#child = child;
|
|
75
|
+
const line = (text: string) => {
|
|
76
|
+
if (!(this.#state === "stopping" && STOPPED_BY_US.test(text))) this.#hooks.line(text);
|
|
77
|
+
};
|
|
78
|
+
eachLine(child.stdout, line);
|
|
79
|
+
eachLine(child.stderr, line);
|
|
80
|
+
child.on("error", (error) => this.#hooks.note(`could not start: ${error.message}`));
|
|
81
|
+
this.#closed = new Promise((done) => {
|
|
82
|
+
child.on("close", (code, signal) => {
|
|
83
|
+
if (run === this.#run) this.#ended(code, signal);
|
|
84
|
+
done();
|
|
85
|
+
});
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
if (this.spec.port != null) void this.#watchPort(run, this.spec.port);
|
|
89
|
+
this.#hooks.changed();
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async stop() {
|
|
93
|
+
if (!this.#child || !this.alive) return;
|
|
94
|
+
this.#state = "stopping";
|
|
95
|
+
this.#hooks.changed();
|
|
96
|
+
this.#signal("SIGTERM");
|
|
97
|
+
const force = setTimeout(() => this.#signal("SIGKILL"), KILL_GRACE_MS);
|
|
98
|
+
await this.#closed;
|
|
99
|
+
clearTimeout(force);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async restart() {
|
|
103
|
+
this.#hooks.note("restarting");
|
|
104
|
+
await this.stop();
|
|
105
|
+
// A server that forked a worker can leave it holding the port after its parent is gone.
|
|
106
|
+
if (this.spec.port != null) await freePort(this.spec.port);
|
|
107
|
+
this.start();
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
#ended(code: number | null, signal: NodeJS.Signals | null) {
|
|
111
|
+
const wasStopping = this.#state === "stopping";
|
|
112
|
+
this.#code = code;
|
|
113
|
+
this.#state = wasStopping ? "stopped" : code === 0 ? "exited" : "crashed";
|
|
114
|
+
if (!wasStopping) this.#hooks.note(code === 0 ? "exited" : `crashed (${signal ?? `exit ${code}`})`);
|
|
115
|
+
this.#hooks.changed();
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async #watchPort(run: number, port: number) {
|
|
119
|
+
while (run === this.#run && this.#state === "starting") {
|
|
120
|
+
if (await probePort(port)) {
|
|
121
|
+
if (run !== this.#run || this.#state !== "starting") return;
|
|
122
|
+
this.#state = "ready";
|
|
123
|
+
this.#readyMs = Date.now() - this.#startedAt;
|
|
124
|
+
this.#hooks.note(`ready at ${this.url} in ${(this.#readyMs / 1000).toFixed(1)}s`);
|
|
125
|
+
this.#hooks.changed();
|
|
126
|
+
this.#hooks.ready();
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
await new Promise((resolve) => setTimeout(resolve, PROBE_INTERVAL_MS));
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
#signal(signal: NodeJS.Signals) {
|
|
134
|
+
const pid = this.#child?.pid;
|
|
135
|
+
if (pid == null) return;
|
|
136
|
+
try {
|
|
137
|
+
process.kill(-pid, signal);
|
|
138
|
+
} catch (error) {
|
|
139
|
+
// The group is already gone: exactly what stopping it wanted.
|
|
140
|
+
if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { createWriteStream, mkdirSync, type WriteStream } from "node:fs";
|
|
2
|
+
import { resolve } from "node:path";
|
|
3
|
+
import { stripColor } from "../ansi.ts";
|
|
4
|
+
import { freePort } from "../free-port.ts";
|
|
5
|
+
import { openUrl } from "../wait-port.ts";
|
|
6
|
+
import { cleanLine } from "./lines.ts";
|
|
7
|
+
import type { ServiceSpec } from "./processes.ts";
|
|
8
|
+
import { Service } from "./service.ts";
|
|
9
|
+
|
|
10
|
+
/** Lines kept in memory for the board; the log files keep everything. */
|
|
11
|
+
const MAX_ENTRIES = 10_000;
|
|
12
|
+
const TRIM_BATCH = 1_000;
|
|
13
|
+
/** `source` of devkit's own lines. */
|
|
14
|
+
export const DEVKIT = -1;
|
|
15
|
+
|
|
16
|
+
export interface LogEntry {
|
|
17
|
+
/** Position in the whole run, so a paused view stays where it is while lines arrive and fall off. */
|
|
18
|
+
readonly seq: number;
|
|
19
|
+
/** Index into `services`, or `DEVKIT`. */
|
|
20
|
+
readonly source: number;
|
|
21
|
+
readonly text: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface SupervisorOptions {
|
|
25
|
+
/** Ask children for colour — they print to a pipe, so they would otherwise drop it. */
|
|
26
|
+
readonly color: boolean;
|
|
27
|
+
/** Open each `open` service's URL the first time its port answers. */
|
|
28
|
+
readonly open: boolean;
|
|
29
|
+
readonly logDir: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Runs every dev service side by side and keeps their output.
|
|
34
|
+
*
|
|
35
|
+
* Nothing here draws: the board and the plain printer both read the same entries and states, and
|
|
36
|
+
* every line also goes to `<logDir>/<label>.log` so an agent can tail a run it cannot see.
|
|
37
|
+
*/
|
|
38
|
+
export class Supervisor {
|
|
39
|
+
readonly services: readonly Service[];
|
|
40
|
+
readonly logDir: string;
|
|
41
|
+
readonly #files: readonly WriteStream[];
|
|
42
|
+
readonly #open: boolean;
|
|
43
|
+
readonly #entryListeners = new Set<(entry: LogEntry) => void>();
|
|
44
|
+
readonly #changeListeners = new Set<() => void>();
|
|
45
|
+
#entries: LogEntry[] = [];
|
|
46
|
+
#seq = 0;
|
|
47
|
+
#version = 0;
|
|
48
|
+
#opened = new Set<number>();
|
|
49
|
+
|
|
50
|
+
constructor(specs: readonly ServiceSpec[], options: SupervisorOptions) {
|
|
51
|
+
this.logDir = options.logDir;
|
|
52
|
+
this.#open = options.open;
|
|
53
|
+
mkdirSync(options.logDir, { recursive: true });
|
|
54
|
+
this.#files = specs.map((spec) =>
|
|
55
|
+
createWriteStream(resolve(options.logDir, `${spec.label.replaceAll(/[^\w.-]/g, "-")}.log`)),
|
|
56
|
+
);
|
|
57
|
+
const env = { ...process.env, ...(options.color ? { FORCE_COLOR: "1" } : {}) };
|
|
58
|
+
this.services = specs.map(
|
|
59
|
+
(spec, i) =>
|
|
60
|
+
new Service(spec, env, {
|
|
61
|
+
line: (raw) => this.#push(i, cleanLine(raw)),
|
|
62
|
+
note: (text) => {
|
|
63
|
+
this.#files[i]?.write(`[devkit] ${text}\n`);
|
|
64
|
+
this.#push(DEVKIT, `${spec.label} ${text}`);
|
|
65
|
+
},
|
|
66
|
+
changed: () => this.#changed(),
|
|
67
|
+
ready: () => this.#ready(i),
|
|
68
|
+
}),
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
get entries(): readonly LogEntry[] {
|
|
73
|
+
return this.#entries;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Bumped on every new line or state change — what the board re-renders on. */
|
|
77
|
+
get version(): number {
|
|
78
|
+
return this.#version;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
get allEnded(): boolean {
|
|
82
|
+
return this.services.every((service) => !service.alive && service.state !== "stopping");
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Arrow so it can be handed to `useSyncExternalStore` unbound. */
|
|
86
|
+
readonly subscribe = (listener: () => void) => {
|
|
87
|
+
this.#changeListeners.add(listener);
|
|
88
|
+
return () => {
|
|
89
|
+
this.#changeListeners.delete(listener);
|
|
90
|
+
};
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
onEntry(listener: (entry: LogEntry) => void) {
|
|
94
|
+
this.#entryListeners.add(listener);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async start() {
|
|
98
|
+
await Promise.all(
|
|
99
|
+
this.services.map(async ({ spec }) => {
|
|
100
|
+
if (spec.port == null) return;
|
|
101
|
+
const killed = await freePort(spec.port);
|
|
102
|
+
if (killed.length) this.say(`freed port ${spec.port} (killed ${killed.join(", ")})`);
|
|
103
|
+
}),
|
|
104
|
+
);
|
|
105
|
+
for (const service of this.services) service.start();
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Restart one service, or all of them. */
|
|
109
|
+
async restart(index?: number) {
|
|
110
|
+
const targets = index == null ? this.services : this.services.slice(index, index + 1);
|
|
111
|
+
await Promise.all(targets.map((service) => service.restart()));
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async stop() {
|
|
115
|
+
await Promise.all(this.services.map((service) => service.stop()));
|
|
116
|
+
await Promise.all(this.#files.map((file) => new Promise((done) => file.end(done))));
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
clear() {
|
|
120
|
+
this.#entries = [];
|
|
121
|
+
this.#changed();
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
say(text: string) {
|
|
125
|
+
this.#push(DEVKIT, text);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
async openService(index: number) {
|
|
129
|
+
const url = this.services[index]?.url;
|
|
130
|
+
if (!url) return;
|
|
131
|
+
await openUrl(url).then(
|
|
132
|
+
() => this.say(`opened ${url}`),
|
|
133
|
+
(error: Error) => this.say(`could not open ${url}: ${error.message}`),
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
#push(source: number, text: string) {
|
|
138
|
+
if (!stripColor(text).trim()) return;
|
|
139
|
+
const entry = { seq: this.#seq++, source, text };
|
|
140
|
+
this.#entries.push(entry);
|
|
141
|
+
if (this.#entries.length > MAX_ENTRIES + TRIM_BATCH) this.#entries = this.#entries.slice(-MAX_ENTRIES);
|
|
142
|
+
if (source !== DEVKIT) this.#files[source]?.write(`${stripColor(text)}\n`);
|
|
143
|
+
for (const listener of this.#entryListeners) listener(entry);
|
|
144
|
+
this.#changed();
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
#ready(index: number) {
|
|
148
|
+
if (!this.#open || !this.services[index]?.spec.open || this.#opened.has(index)) return;
|
|
149
|
+
this.#opened.add(index);
|
|
150
|
+
void this.openService(index);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
#changed() {
|
|
154
|
+
this.#version++;
|
|
155
|
+
for (const listener of this.#changeListeners) listener();
|
|
156
|
+
}
|
|
157
|
+
}
|
package/src/dev.ts
CHANGED
|
@@ -1,50 +1,17 @@
|
|
|
1
|
-
import
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
1
|
+
import { basename, resolve } from "node:path";
|
|
2
|
+
import { loadConfig, withNeeds } from "./config.ts";
|
|
3
|
+
import { printPlain } from "./dev/plain.ts";
|
|
4
|
+
import { servicesOf } from "./dev/processes.ts";
|
|
5
|
+
import { Supervisor } from "./dev/supervisor.ts";
|
|
5
6
|
|
|
6
|
-
const
|
|
7
|
+
const LOG_DIR = ".devkit/dev";
|
|
8
|
+
const STOP_SIGNALS = { SIGINT: 130, SIGTERM: 143, SIGHUP: 129 } as const;
|
|
7
9
|
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
platform: string;
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
/** Flatten a platform into the processes it runs — a web platform is a client and an API. */
|
|
17
|
-
function processesOf(platform: Named<DevPlatform>): Process[] {
|
|
18
|
-
const group = platform.processes;
|
|
19
|
-
if (!group) return [{ ...platform, label: platform.name, platform: platform.name }];
|
|
20
|
-
if (platform.type) throw new Error(`"devkit.dev.${platform.name}" has both a "type" and "processes"`);
|
|
21
|
-
|
|
22
|
-
const keys = Object.keys(group);
|
|
23
|
-
if (!keys.length) throw new Error(`"devkit.dev.${platform.name}.processes" is empty`);
|
|
24
|
-
return keys.map((key) => {
|
|
25
|
-
const process = group[key] as DevProcess;
|
|
26
|
-
return {
|
|
27
|
-
...process,
|
|
28
|
-
// The workspace a bare process runs in is named by its key, not by the platform's.
|
|
29
|
-
filter: process.filter ?? key,
|
|
30
|
-
// A platform that runs one process is that process; several need telling apart.
|
|
31
|
-
label: keys.length === 1 ? platform.name : `${platform.name}:${key}`,
|
|
32
|
-
platform: platform.name,
|
|
33
|
-
};
|
|
34
|
-
});
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
/** Turn a process entry into the shell command that runs it. */
|
|
38
|
-
function commandFor(process: Process): string {
|
|
39
|
-
// A raw command still honours `cwd` — `bunx tauri dev` means the app's directory, not the root.
|
|
40
|
-
if (process.command)
|
|
41
|
-
return process.cwd ? `sh -c ${JSON.stringify(`cd ${process.cwd} && ${process.command}`)}` : process.command;
|
|
42
|
-
// A built-in dev target runs through `devkit _run dev`, which looks its options back up from
|
|
43
|
-
// this same config — the same trick the build and deploy graphs use.
|
|
44
|
-
if (process.type) return `devkit _run dev ${JSON.stringify(process.platform)}`;
|
|
45
|
-
const script = process.script ?? "dev";
|
|
46
|
-
if (process.cwd) return `bun run --cwd ${process.cwd} ${script}`;
|
|
47
|
-
return `bun --filter ${process.filter ?? process.label} ${script}`;
|
|
10
|
+
export interface DevFlags {
|
|
11
|
+
open?: boolean;
|
|
12
|
+
dry?: boolean;
|
|
13
|
+
/** Line-by-line output even on a terminal. */
|
|
14
|
+
plain?: boolean;
|
|
48
15
|
}
|
|
49
16
|
|
|
50
17
|
/**
|
|
@@ -52,9 +19,10 @@ function commandFor(process: Process): string {
|
|
|
52
19
|
*
|
|
53
20
|
* `devkit dev` runs every platform; `devkit dev:mac` runs the Mac shell and, because it declares
|
|
54
21
|
* `needs`, the web stack it points at — a native shell with no dev server behind it is a window
|
|
55
|
-
* onto nothing.
|
|
22
|
+
* onto nothing. A person at a terminal gets the board (URLs and states pinned above the log);
|
|
23
|
+
* anything else — an agent's shell, CI, a pipe — gets plain prefixed lines.
|
|
56
24
|
*/
|
|
57
|
-
export async function runDev(only: string[], flags:
|
|
25
|
+
export async function runDev(only: string[], flags: DevFlags = {}): Promise<void> {
|
|
58
26
|
const { dev } = loadConfig();
|
|
59
27
|
if (!dev.length) throw new Error('No "devkit.dev" platforms to run');
|
|
60
28
|
|
|
@@ -63,47 +31,43 @@ export async function runDev(only: string[], flags: { open?: boolean; dry?: bool
|
|
|
63
31
|
if (missing.length) throw new Error(`${platform.name} needs unknown platform: ${missing.join(", ")}`);
|
|
64
32
|
}
|
|
65
33
|
|
|
66
|
-
const
|
|
67
|
-
const withPort = processes.filter((process) => process.port != null);
|
|
34
|
+
const specs = servicesOf(withNeeds(dev, only));
|
|
68
35
|
|
|
69
36
|
if (flags.dry) {
|
|
70
37
|
console.log("devkit dev (dry run):");
|
|
71
|
-
for (const
|
|
72
|
-
const url =
|
|
73
|
-
console.log(` [${
|
|
38
|
+
for (const spec of specs) {
|
|
39
|
+
const url = spec.port != null ? ` → http://localhost:${spec.port}${spec.open ? " (open)" : ""}` : "";
|
|
40
|
+
console.log(` [${spec.label}] ${spec.command}${url}`);
|
|
74
41
|
}
|
|
75
42
|
return;
|
|
76
43
|
}
|
|
77
44
|
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
}
|
|
45
|
+
const interactive = !flags.plain && Boolean(process.stdout.isTTY && process.stdin.isTTY) && !process.env.CI;
|
|
46
|
+
const supervisor = new Supervisor(specs, {
|
|
47
|
+
color: Boolean(process.stdout.isTTY),
|
|
48
|
+
open: Boolean(flags.open),
|
|
49
|
+
logDir: resolve(process.cwd(), LOG_DIR),
|
|
50
|
+
});
|
|
85
51
|
|
|
86
|
-
const
|
|
87
|
-
|
|
88
|
-
command: commandFor(process),
|
|
89
|
-
name: process.label,
|
|
90
|
-
prefixColor: process.color ?? PALETTE[i % PALETTE.length],
|
|
91
|
-
})),
|
|
92
|
-
{ prefix: "name", killOthersOn: ["failure", "success"] },
|
|
93
|
-
);
|
|
52
|
+
for (const [signal, code] of Object.entries(STOP_SIGNALS))
|
|
53
|
+
process.once(signal, () => void supervisor.stop().then(() => process.exit(code)));
|
|
94
54
|
|
|
95
|
-
if (
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
55
|
+
if (interactive) {
|
|
56
|
+
const { runBoard } = await import("./dev/board.tsx");
|
|
57
|
+
const board = runBoard(supervisor, basename(process.cwd()));
|
|
58
|
+
await supervisor.start();
|
|
59
|
+
await board;
|
|
60
|
+
console.log(`devkit dev stopped · logs in ${LOG_DIR}`);
|
|
61
|
+
return;
|
|
102
62
|
}
|
|
103
63
|
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
64
|
+
printPlain(supervisor, Boolean(process.stdout.isTTY));
|
|
65
|
+
await supervisor.start();
|
|
66
|
+
await new Promise<void>((done) => {
|
|
67
|
+
supervisor.subscribe(() => {
|
|
68
|
+
if (supervisor.allEnded) done();
|
|
69
|
+
});
|
|
70
|
+
});
|
|
71
|
+
await supervisor.stop();
|
|
72
|
+
if (supervisor.services.some((service) => service.state === "crashed")) process.exitCode = 1;
|
|
109
73
|
}
|
package/src/free-port.ts
CHANGED
|
@@ -3,27 +3,22 @@ import { promisify } from "node:util";
|
|
|
3
3
|
|
|
4
4
|
const execAsync = promisify(exec);
|
|
5
5
|
|
|
6
|
-
/** Kill whatever is listening on `port` so a dev server can always bind it. */
|
|
7
|
-
export async function freePort(port: number | string): Promise<
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
const pids = [
|
|
11
|
-
...new Set(
|
|
12
|
-
stdout
|
|
13
|
-
.split("\n")
|
|
14
|
-
.slice(1)
|
|
15
|
-
.map((line) => line.trim().split(/\s+/)[1])
|
|
16
|
-
.filter(Boolean),
|
|
17
|
-
),
|
|
18
|
-
];
|
|
19
|
-
if (pids.length > 0) {
|
|
20
|
-
await execAsync(`kill -9 ${pids.join(" ")}`);
|
|
21
|
-
console.log(`✓ Freed port ${port} (killed ${pids.join(", ")})`);
|
|
22
|
-
} else {
|
|
23
|
-
console.log(`✓ Port ${port} already free`);
|
|
24
|
-
}
|
|
25
|
-
} catch {
|
|
6
|
+
/** Kill whatever is listening on `port` so a dev server can always bind it. Returns the killed pids. */
|
|
7
|
+
export async function freePort(port: number | string): Promise<string[]> {
|
|
8
|
+
const listening = await execAsync(`lsof -nP -iTCP:${port} -sTCP:LISTEN`).then(
|
|
9
|
+
({ stdout }) => stdout,
|
|
26
10
|
// lsof exits 1 when nothing is listening
|
|
27
|
-
|
|
28
|
-
|
|
11
|
+
() => "",
|
|
12
|
+
);
|
|
13
|
+
const pids = [
|
|
14
|
+
...new Set(
|
|
15
|
+
listening
|
|
16
|
+
.split("\n")
|
|
17
|
+
.slice(1)
|
|
18
|
+
.map((line) => line.trim().split(/\s+/)[1])
|
|
19
|
+
.filter((pid): pid is string => Boolean(pid)),
|
|
20
|
+
),
|
|
21
|
+
];
|
|
22
|
+
if (pids.length > 0) await execAsync(`kill -9 ${pids.join(" ")}`);
|
|
23
|
+
return pids;
|
|
29
24
|
}
|
package/src/graph.ts
CHANGED
|
@@ -2,28 +2,13 @@ import { spawn } from "node:child_process";
|
|
|
2
2
|
import { mkdirSync, writeFileSync } from "node:fs";
|
|
3
3
|
import { resolve } from "node:path";
|
|
4
4
|
import { $ } from "bun";
|
|
5
|
+
import { bold, dim, PALETTE, paint, visibleLength } from "./ansi.ts";
|
|
5
6
|
import { type GenerateConfig, type Named, type Phase, type Step, withNeeds } from "./config.ts";
|
|
6
7
|
|
|
7
|
-
const PALETTE: readonly string[] = ["magenta", "cyan", "yellow", "green", "blue", "red"];
|
|
8
|
-
const COLORS: Record<string, string> = {
|
|
9
|
-
black: "30",
|
|
10
|
-
red: "31",
|
|
11
|
-
green: "32",
|
|
12
|
-
yellow: "33",
|
|
13
|
-
blue: "34",
|
|
14
|
-
magenta: "35",
|
|
15
|
-
cyan: "36",
|
|
16
|
-
white: "37",
|
|
17
|
-
gray: "90",
|
|
18
|
-
};
|
|
19
8
|
const SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|
|
20
9
|
const FRAME_MS = 80;
|
|
21
10
|
const TAIL_ON_FAILURE = 25;
|
|
22
11
|
|
|
23
|
-
const paint = (text: string, color: string) => `\x1b[${COLORS[color] ?? "37"}m${text}\x1b[0m`;
|
|
24
|
-
const dim = (text: string) => `\x1b[2m${text}\x1b[0m`;
|
|
25
|
-
const bold = (text: string) => `\x1b[1m${text}\x1b[0m`;
|
|
26
|
-
|
|
27
12
|
type Status = "waiting" | "running" | "done" | "failed" | "skipped";
|
|
28
13
|
|
|
29
14
|
/** One step's progress, and everything the board needs to draw its line. */
|
|
@@ -222,7 +207,9 @@ function report(phase: Phase, jobs: Job[], total: number) {
|
|
|
222
207
|
skipped ? dim(`${skipped} skipped`) : "",
|
|
223
208
|
dim(duration(total)),
|
|
224
209
|
].filter(Boolean);
|
|
225
|
-
console.log(
|
|
210
|
+
console.log(
|
|
211
|
+
`\n${bold(`${done}/${jobs.length} ${phase === "build" ? "built" : "deployed"}`)} · ${parts.join(" · ")}\n`,
|
|
212
|
+
);
|
|
226
213
|
}
|
|
227
214
|
|
|
228
215
|
function printPlan(phase: Phase, jobs: Job[], generate: GenerateConfig | undefined) {
|
|
@@ -251,8 +238,4 @@ function duration(ms: number) {
|
|
|
251
238
|
return seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m${String(seconds % 60).padStart(2, "0")}s`;
|
|
252
239
|
}
|
|
253
240
|
|
|
254
|
-
// Colour codes take no space on screen, so the board has to measure what a reader would see.
|
|
255
|
-
// biome-ignore lint/suspicious/noControlCharactersInRegex: an escape sequence is the thing being matched
|
|
256
|
-
const ANSI = /\x1b\[[0-9;]*m/g;
|
|
257
|
-
const visibleLength = (text: string) => text.replace(ANSI, "").length;
|
|
258
241
|
const clip = (text: string, room: number) => (text.length <= room ? text : `${text.slice(0, room - 1)}…`);
|
package/src/run-target.ts
CHANGED
|
@@ -46,7 +46,7 @@ const TARGETS: Record<Phase, Record<string, Target>> = {
|
|
|
46
46
|
/**
|
|
47
47
|
* Runs one built-in target, looked back up by phase and platform name.
|
|
48
48
|
*
|
|
49
|
-
* A typed step has no shell command of its own, so the graph (and
|
|
49
|
+
* A typed step has no shell command of its own, so the graph (and the dev supervisor) spawns
|
|
50
50
|
* `devkit _run <phase> <platform>` and this reads the same config back — which keeps every step a
|
|
51
51
|
* process of its own, with its own log file and its own line on the board.
|
|
52
52
|
*/
|
package/src/wait-port.ts
CHANGED
|
@@ -2,21 +2,30 @@ import { exec } from "node:child_process";
|
|
|
2
2
|
import { promisify } from "node:util";
|
|
3
3
|
|
|
4
4
|
const execAsync = promisify(exec);
|
|
5
|
+
const PROBE_TIMEOUT_MS = 2_000;
|
|
6
|
+
|
|
7
|
+
/** Whether something on this local port answers HTTP without a server error. */
|
|
8
|
+
export async function probePort(port: number | string): Promise<boolean> {
|
|
9
|
+
try {
|
|
10
|
+
const res = await fetch(`http://localhost:${port}`, {
|
|
11
|
+
redirect: "manual",
|
|
12
|
+
signal: AbortSignal.timeout(PROBE_TIMEOUT_MS),
|
|
13
|
+
});
|
|
14
|
+
return res.status < 500;
|
|
15
|
+
} catch {
|
|
16
|
+
// not listening yet, or still compiling the first response
|
|
17
|
+
return false;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
5
20
|
|
|
6
21
|
/** Poll a local port until it accepts HTTP connections (or the timeout elapses). */
|
|
7
22
|
export async function waitForPort(
|
|
8
23
|
port: number | string,
|
|
9
24
|
{ timeoutMs = 60_000, intervalMs = 400 }: { timeoutMs?: number; intervalMs?: number } = {},
|
|
10
25
|
): Promise<boolean> {
|
|
11
|
-
const url = `http://localhost:${port}`;
|
|
12
26
|
const deadline = Date.now() + timeoutMs;
|
|
13
27
|
while (Date.now() < deadline) {
|
|
14
|
-
|
|
15
|
-
const res = await fetch(url);
|
|
16
|
-
if (res.status < 500) return true;
|
|
17
|
-
} catch {
|
|
18
|
-
// server not up yet
|
|
19
|
-
}
|
|
28
|
+
if (await probePort(port)) return true;
|
|
20
29
|
await new Promise((resolve) => setTimeout(resolve, intervalMs));
|
|
21
30
|
}
|
|
22
31
|
return false;
|