@rootnative/loupe 0.0.0-alpha.0 → 0.0.0-alpha.2

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/CHANGELOG.md ADDED
@@ -0,0 +1,45 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@rootnative/loupe` are in this file. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). Versions follow modified semver: a breaking change bumps the middle digit (`0.1.0`), and fixes and additions bump the last digit (`0.0.2`).
4
+
5
+ ## [Unreleased]
6
+
7
+ ## [0.0.0-alpha.2] - 2026-11-25
8
+
9
+ The Expo helpers: loupe warms, opens, and restarts your app in Expo Go, and switches it to RTL and back.
10
+
11
+ ### Added
12
+
13
+ - **`expo-warm`**: it asks Metro (`npx expo start`) for the manifest of your app and its launch bundle, as Expo Go does on its first open. Then the first open doesn't wait for a cold bundle. It gives the SDK version and the folder of the app, and the time, the size, and the SHA-256 of the bundle: after an edit, the same hash means that Metro didn't see the edit. It asks Metro on 127.0.0.1 only.
14
+ - **`expo-open`**: it opens your app in Expo Go at a route, through `adb reverse` of the port of Metro. It warms the bundle first, closes Expo Go's onboarding sheet and developer menu, opens the link again when Expo Go loses it, and waits until the app shows: on the route when your app has the probe. With no probe, it waits until the screen has text, a label or a touch and keeps still, then reads it once more, so a loading screen or a sheet that comes a moment later isn't taken for your app. It warns when Expo Go isn't for the SDK of your app, and with no Expo Go it says how to install it. When Expo Go's screen never keeps still for uiautomator (an animation that never stops, or a long one), it gives `not_idle` with what to do.
15
+ - **`expo-reload`**: it stops Expo Go and opens your app again, so its JavaScript starts again in a new process. It opens the route that the probe shows before the stop, or the route that you give, else the root. It warms the bundle first, so it stops nothing when Metro doesn't run. After the stop, it waits until the process of Expo Go is gone, then opens the link. It warns when Android didn't start Expo Go cold.
16
+ - **`expo-rtl`**: `expo-rtl on` writes `supportsRTL` and `forcesRTL` in the `extra` of your app.json, and opens your app again in RTL, as `expo-reload` does. It keeps app.json as it was in `.expo/loupe-rtl.json`, and `expo-rtl off` puts it back byte for byte. It finds app.json through the manifest of Metro, waits until the manifest has the change, and waits until the probe shows the direction. When the manifest doesn't get the change (an `app.config.js` that replaces `extra`), it puts app.json back and says why. A project with no app.json gets `unsupported`, with the two lines to add.
17
+ - **`direction` and `reopens`** in the output of `expo-open`, `expo-reload` and `expo-rtl`: the layout direction that the probe shows, and what loupe saw before each time that it opened the link again.
18
+ - **`sweep --reload-every <n>`**: it stops the app before each n-th link that the sweep opens, over all the variants, and the link starts it again, so stacked screens don't slow the app down. In Expo Go, loupe then waits until the app shows the route of the link, as `expo-open` does. It needs `--app`. Each screen in the report has `reloaded`.
19
+ - **`sweep --direction ltr,rtl`**: in Expo Go, it checks each screen in each layout direction. loupe sets each direction once, before its variants, in your app.json, as `expo-rtl` does, opens the app again, and waits until the probe shows that direction. At the end it puts app.json back byte for byte and opens the app again in its direction. Each variant has `direction`, and its name ends with it: `portrait-light-rtl`. `--port` gives the port of Metro.
20
+ - **The error code `no_server`**: nothing answers on the port of Metro, or the server there isn't Metro.
21
+
22
+ ### Fixed
23
+
24
+ - `scroll-to` and `sweep --scroll` leave out Expo Go's own overlay when they compare what a scroll view shows. A fresh Expo Go shows a "Tools" label for a few seconds. loupe took the change of that label for a change of the list: `sweep --scroll` warned that the list didn't show its top again, and a scroll that didn't move could count as one.
25
+ - `dismiss` sends Back or Escape only when the input focus is on the layer that it closes. On a busy device, Android moves the input focus a moment after the window focus. A Back right after the notification shade closed could reach the shade, and the share sheet under it stayed open. When the input focus doesn't arrive within the limit, `dismiss` gives `timeout` and sends no key.
26
+
27
+ ## [0.0.0-alpha.1] - 2026-11-24
28
+
29
+ loupe drives an Android emulator or device, measures each screen of your app in dp, and gives your agent "pass" or "fail" with the numbers. It works on Android 11 (API level 30) and later.
30
+
31
+ ### Added
32
+
33
+ - **The CLI**, `loupe`. It prints JSON through a pipe and text in a terminal. Exit codes: 0 passed, 1 failed, 2 a wrong command or flag, 130 cancelled.
34
+ - **The MCP server**, `loupe mcp`. Each command is a tool, with the schemas of its input and its output. A sweep sends its progress, and a cancelled call stops at a safe point. `screenshot` and `sweep` also give their images in the result.
35
+ - **The skill**, `skills/loupe/SKILL.md`: the workflow, the rules, and what to do for each error. It tells your agent to ask you before it starts an emulator or opens an app. The MCP server serves it too.
36
+ - **`check`**, with five rules: `inset`, `overflow`, `centred`, `touch-target`, and `mirrored`. Each finding gives the element and its numbers in dp.
37
+ - **`sweep`**: it checks each link in each orientation and theme, and with `scroll` once more after a scroll down. It writes `report.json`, a screenshot of each screen, and a contact sheet of each variant. Then it puts the orientation and the theme back.
38
+ - **Reads:** `screenshot` (upright, with a crop and a scale), `ui` (the accessibility tree, with frames in dp), `insets` (the system bars, the cutout, and the safe area), `measure` (the colour runs along a row or a column, and where an element sits), and `wait`.
39
+ - **Touches:** `tap`, `double-tap`, `hold`, `swipe`, `drag`, `pinch`, `type`, `key`, and `scroll-to`. `tap`, `double-tap`, `hold`, and `pinch` aim at a point in dp, or at an element by its text, label, or id. Each touch but `scroll-to` can then wait for a text or a still screen.
40
+ - **The device:** `devices`, `open-url`, `rotate`, `theme`, `background`, `foreground`, and `dismiss`. `dismiss` closes a system sheet, a dialog, the keyboard, or an overlay of your app.
41
+ - **The probe:** when your app renders `<LoupeProbe />` from `@rootnative/loupe-probe`, `insets` and the rules use the app's own safe area.
42
+
43
+ [unreleased]: https://github.com/rootnative/loupe/compare/loupe@0.0.0-alpha.2...HEAD
44
+ [0.0.0-alpha.2]: https://github.com/rootnative/loupe/releases/tag/loupe@0.0.0-alpha.2
45
+ [0.0.0-alpha.1]: https://github.com/rootnative/loupe/releases/tag/loupe@0.0.0-alpha.1
package/README.md CHANGED
@@ -1,8 +1,191 @@
1
1
  # @rootnative/loupe
2
2
 
3
- loupe by Root Native: layout checks for iOS and Android, built for AI agents.
3
+ Layout checks for iOS and Android, built for AI agents.
4
4
 
5
- This version, `0.0.0-alpha.0`, is empty. It has no code. Use a later
6
- version.
5
+ loupe drives an emulator or a device, opens each screen of your app, and
6
+ gives your agent exact numbers: element frames, safe areas, cutouts, and
7
+ edges, in dp. Your agent can then say "pass" or "fail" with evidence, not
8
+ with a guess from a screenshot.
7
9
 
8
- Source and docs: https://github.com/rootnative/loupe
10
+ > loupe is in alpha, and it drives Android only for now. A new version can
11
+ > change the commands, their options, and their JSON.
12
+
13
+ ## What you need
14
+
15
+ - Node.js 20.19 or later.
16
+ - `adb` from the Android SDK platform tools, on your `PATH` or in
17
+ `$ANDROID_HOME/platform-tools`.
18
+ - An emulator or a device with Android 11 (API level 30) or later.
19
+
20
+ ## Use it with an agent
21
+
22
+ ### The MCP server
23
+
24
+ `loupe mcp` serves each loupe command as an MCP tool, over stdin and stdout.
25
+
26
+ In Claude Code:
27
+
28
+ ```sh
29
+ claude mcp add loupe -- npx -y @rootnative/loupe mcp
30
+ ```
31
+
32
+ In VS Code, add it to `.vscode/mcp.json`:
33
+
34
+ ```json
35
+ {
36
+ "servers": {
37
+ "loupe": {
38
+ "type": "stdio",
39
+ "command": "npx",
40
+ "args": ["-y", "@rootnative/loupe", "mcp"]
41
+ }
42
+ }
43
+ }
44
+ ```
45
+
46
+ In another MCP client:
47
+
48
+ ```json
49
+ {
50
+ "mcpServers": {
51
+ "loupe": {
52
+ "command": "npx",
53
+ "args": ["-y", "@rootnative/loupe", "mcp"]
54
+ }
55
+ }
56
+ }
57
+ ```
58
+
59
+ When adb isn't on your `PATH`, set `ANDROID_HOME` in the server's `env`.
60
+ With more than one device, set `ANDROID_SERIAL`, or let the agent give
61
+ `device` in each call.
62
+
63
+ The server runs one call at a time, because two touches at the same time
64
+ lose events. A sweep sends its progress, and a cancelled call stops at a
65
+ safe point. `screenshot` and `sweep` also give their images in the result.
66
+
67
+ ### The skill
68
+
69
+ `skills/loupe/SKILL.md` tells your agent how to use loupe: the workflow, the
70
+ rules, and what to do for each error. It also tells the agent to ask you
71
+ before it starts an emulator or opens an app.
72
+
73
+ A client with the MCP skills extension gets the skill from the server. For
74
+ another agent, copy the skill into the agent's skills folder. For Claude
75
+ Code:
76
+
77
+ ```sh
78
+ npm install --save-dev @rootnative/loupe
79
+ cp -R node_modules/@rootnative/loupe/skills/loupe .claude/skills/
80
+ ```
81
+
82
+ ## Use it from the command line
83
+
84
+ ```sh
85
+ npx @rootnative/loupe devices
86
+ npx @rootnative/loupe open-url "exp://127.0.0.1:8081/--/settings" --app host.exp.exponent --wait-still
87
+ npx @rootnative/loupe check --app host.exp.exponent
88
+ npx @rootnative/loupe rotate landscape-left
89
+ npx @rootnative/loupe check --app host.exp.exponent
90
+ ```
91
+
92
+ Run `loupe --help` for the commands, and `loupe <command> --help` for the
93
+ options of one command.
94
+
95
+ To check many screens in one call:
96
+
97
+ ```sh
98
+ npx @rootnative/loupe sweep \
99
+ --url "exp://127.0.0.1:8081/--/settings" \
100
+ --url "exp://127.0.0.1:8081/--/profile" \
101
+ --orientation portrait,landscape-left \
102
+ --theme light,dark \
103
+ --app host.exp.exponent
104
+ ```
105
+
106
+ A sweep writes `loupe-sweep/report.json`, a screenshot of each screen, and a
107
+ contact sheet of each variant. A red frame on the contact sheet marks a
108
+ screen that failed. At the end, loupe puts the orientation and the theme
109
+ back. For a long list, `--reload-every 10` stops the app before each 10th
110
+ link, so stacked screens don't slow it down. In Expo Go,
111
+ `--direction ltr,rtl` checks each screen in both layout directions: loupe
112
+ sets each one in `app.json`, as `expo-rtl` does, and puts the file back at
113
+ the end.
114
+
115
+ ## The output
116
+
117
+ - Each position and size is in dp, from the top-left corner of the current
118
+ orientation. Each reading gives `scale`, the pixels in one dp.
119
+ - Through a pipe, each command prints JSON: `{ "ok": true, "command": …,
120
+ "data": … }`, or `"ok": false` with `"error": { "code": …, "message": …
121
+ }`. In a terminal, it prints text. `--json` and `--no-json` choose.
122
+ - Exit codes: 0 passed, 1 failed (also a check that ran and found a
123
+ defect), 2 a wrong command or option, 130 cancelled.
124
+
125
+ ## The rules
126
+
127
+ `check` and `sweep` run these rules:
128
+
129
+ | Rule | Fails when |
130
+ | --- | --- |
131
+ | `inset` | An element with text, a label, or a touch sits under a system bar or the cutout, or outside the safe area. |
132
+ | `overflow` | An element at a screen edge is shorter than the elements like it in its row or column: the edge cuts it. |
133
+ | `centred` | A text with an element on each side is more than 4 dp from the centre of its container. |
134
+ | `touch-target` | An element that you can press is smaller than 48 × 48 dp. From 40 dp, loupe gives a warning: a `hitSlop` can make it whole. |
135
+ | `mirrored` | In RTL, an element sits where LTR puts it. Save the other direction with `ui --out <file>`, then run `check --mirror-of <file>`. |
136
+
137
+ Each finding gives the element and its numbers in dp.
138
+
139
+ ## The commands
140
+
141
+ | Command | What it does |
142
+ | --- | --- |
143
+ | `devices` | List the Android emulators and devices, and the AVDs that don't run. |
144
+ | `open-url` | Open a link (a deep link or a web page), and wait until it opens. |
145
+ | `check` | Check the screen for layout defects with the rules above. |
146
+ | `sweep` | Open each link in each orientation and theme, check each screen, and write a report, the screenshots, and a contact sheet of each variant. |
147
+ | `screenshot` | Save the screen as a PNG file, upright in each orientation. |
148
+ | `ui` | Read the accessibility tree of the screen, with frames in dp. |
149
+ | `insets` | Read the safe-area insets and the cutout of the current orientation. |
150
+ | `measure` | Measure the colour runs along a row or a column, or where an element sits on the screen and in the safe area. |
151
+ | `wait` | Wait until the screen keeps still, or until an element is on the screen. |
152
+ | `rotate` | Turn the screen, and wait until it has turned. |
153
+ | `theme` | Set the system theme to light or dark, and wait until the app shows it. With no theme, read it. |
154
+ | `tap` | Tap one point, or the element with a text, label, or id. |
155
+ | `double-tap` | Tap one point or element twice. |
156
+ | `hold` | Touch one point or element and hold it: a long press. |
157
+ | `swipe` | Move one touch in a straight line from one point to another. |
158
+ | `drag` | Touch, hold, move, hold, and lift, with a screenshot while the touch is down. |
159
+ | `pinch` | Pinch or spread two fingers around a point or an element, and turn them. On an emulator only. |
160
+ | `scroll-to` | Scroll until the element with a text, label, or id is in view, and give its frame. |
161
+ | `type` | Type text into the field that has the focus. |
162
+ | `key` | Press one key, for example `back`, `home`, or `enter`. |
163
+ | `dismiss` | Close the top layer over the app: the keyboard, a dialog, a menu or a sheet of the app, a system sheet, or the notification shade. |
164
+ | `background` | Send the app in front to the background. With `--for`, bring it back after that time. |
165
+ | `foreground` | Bring an app back to the front, as a person does from Recents. |
166
+ | `expo-open` | Open the app in Expo Go at a route, close Expo Go's onboarding sheet and developer menu, and wait until the app shows. |
167
+ | `expo-reload` | Stop Expo Go and open the app again, so its JavaScript starts again. Keep the route when the app has the probe. |
168
+ | `expo-rtl` | Turn RTL on or off in the app.json of the app, and open the app again in that direction. `off` puts app.json back as it was. |
169
+ | `expo-warm` | Ask Metro (`npx expo start`) for the app and its bundle, so that the first open in Expo Go is fast. Give the SHA-256 of the bundle. |
170
+ | `version` | Print the loupe version and the host it runs on. |
171
+
172
+ ## The probe
173
+
174
+ With [`@rootnative/loupe-probe`](https://github.com/rootnative/loupe/tree/main/packages/probe#readme)
175
+ in your app, `insets` and the rules use the app's own safe area. Without it,
176
+ loupe takes the safe area from Android.
177
+
178
+ ## Privacy
179
+
180
+ - On a real phone, give `--app`. loupe then reads the screen only while that
181
+ app is in front, so it never shows another app to your agent.
182
+ - loupe makes no call over the network. It talks to the device through adb,
183
+ and the Expo commands talk to Metro on this machine (127.0.0.1) only.
184
+ - `expo-rtl` and `sweep --direction` are the only commands that write in
185
+ your project: they edit `app.json`, keep the file as it was in
186
+ `.expo/loupe-rtl.json`, and put it back (`expo-rtl off`, or the end of
187
+ the sweep).
188
+
189
+ ## License
190
+
191
+ MIT
package/dist/bin.js ADDED
@@ -0,0 +1,315 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ LoupeError,
4
+ createContext,
5
+ inputJsonSchema,
6
+ registry,
7
+ runCommand,
8
+ version
9
+ } from "./chunk-HWVQXYQ3.js";
10
+
11
+ // src/cli/flags.ts
12
+ import { parseArgs } from "util";
13
+ var RESERVED = /* @__PURE__ */ new Set(["help", "json"]);
14
+ function kebab(key) {
15
+ return key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
16
+ }
17
+ function kindOf(node) {
18
+ switch (node?.type) {
19
+ case "string":
20
+ return "string";
21
+ case "number":
22
+ case "integer":
23
+ return "number";
24
+ case "boolean":
25
+ return "boolean";
26
+ default:
27
+ return void 0;
28
+ }
29
+ }
30
+ function flagsOf(command) {
31
+ const schema = inputJsonSchema(command);
32
+ const required = new Set(schema.required);
33
+ const positionals = new Set(command.positionals);
34
+ const flags = Object.entries(schema.properties ?? {}).map(
35
+ ([key, node]) => {
36
+ const name = kebab(key);
37
+ const multiple = node.type === "array";
38
+ const leaf = multiple ? node.items : node;
39
+ const kind = kindOf(leaf);
40
+ const positional = positionals.has(key);
41
+ if (RESERVED.has(name)) {
42
+ throw new Error(
43
+ `${command.name}: the field "${key}" has the name of a CLI flag.`
44
+ );
45
+ }
46
+ if (!kind) {
47
+ throw new Error(
48
+ `${command.name}: the field "${key}" must be a string, a number, a boolean, or a list of these.`
49
+ );
50
+ }
51
+ if (positional && (multiple || kind === "boolean")) {
52
+ throw new Error(
53
+ `${command.name}: the positional field "${key}" must be one string or one number.`
54
+ );
55
+ }
56
+ return {
57
+ key,
58
+ name,
59
+ kind,
60
+ multiple,
61
+ required: required.has(key),
62
+ positional,
63
+ description: typeof node.description === "string" ? node.description : void 0,
64
+ choices: Array.isArray(leaf?.enum) ? leaf.enum.map(String) : void 0,
65
+ defaultValue: node.default
66
+ };
67
+ }
68
+ );
69
+ for (const key of positionals) {
70
+ if (!flags.some((flag) => flag.key === key)) {
71
+ throw new Error(
72
+ `${command.name}: the positional "${key}" is not an input field.`
73
+ );
74
+ }
75
+ }
76
+ return flags;
77
+ }
78
+ function convert(flag, raw) {
79
+ if (flag.kind !== "number" || typeof raw !== "string") return raw;
80
+ const value = raw.trim() === "" ? Number.NaN : Number(raw);
81
+ return Number.isNaN(value) ? raw : value;
82
+ }
83
+ function parseCommandArgs(command, args) {
84
+ const flags = flagsOf(command);
85
+ let parsed;
86
+ try {
87
+ parsed = parseArgs({
88
+ args: [...args],
89
+ options: {
90
+ help: { type: "boolean", short: "h" },
91
+ ...Object.fromEntries(
92
+ flags.map((flag) => [
93
+ flag.name,
94
+ {
95
+ type: flag.kind === "boolean" ? "boolean" : "string",
96
+ multiple: flag.multiple
97
+ }
98
+ ])
99
+ )
100
+ },
101
+ allowPositionals: true,
102
+ allowNegative: true,
103
+ strict: true
104
+ });
105
+ } catch (error) {
106
+ throw new LoupeError(
107
+ "invalid_input",
108
+ error instanceof Error ? error.message : String(error)
109
+ );
110
+ }
111
+ const values = parsed.values;
112
+ const input = {};
113
+ for (const flag of flags) {
114
+ const raw = values[flag.name];
115
+ if (raw === void 0) continue;
116
+ input[flag.key] = Array.isArray(raw) ? raw.map((item) => convert(flag, item)) : convert(flag, raw);
117
+ }
118
+ const order = command.positionals ?? [];
119
+ if (parsed.positionals.length > order.length) {
120
+ const extra = parsed.positionals[order.length];
121
+ throw new LoupeError(
122
+ "invalid_input",
123
+ `"${extra}" is one argument too many for ${command.name}.`
124
+ );
125
+ }
126
+ parsed.positionals.forEach((raw, index) => {
127
+ const flag = flags.find((item) => item.key === order[index]);
128
+ if (!flag) return;
129
+ if (flag.key in input) {
130
+ throw new LoupeError(
131
+ "invalid_input",
132
+ `${flag.key} has two values: one by position and one from --${flag.name}.`
133
+ );
134
+ }
135
+ input[flag.key] = convert(flag, raw);
136
+ });
137
+ return { help: parsed.values.help === true, input };
138
+ }
139
+
140
+ // src/cli/help.ts
141
+ function columns(rows) {
142
+ const width = Math.max(0, ...rows.map(([left]) => left.length));
143
+ return rows.map(([left, right]) => ` ${left.padEnd(width)} ${right}`.trimEnd()).join("\n");
144
+ }
145
+ var SHARED_OPTIONS = [
146
+ ["--json", "Print JSON. The default when the output is not a terminal"],
147
+ ["--no-json", "Print text for a person"],
148
+ ["-h, --help", "Print this help"]
149
+ ];
150
+ function globalHelp(registry2) {
151
+ const commands = columns(
152
+ registry2.list().map((command) => [command.name, command.summary])
153
+ );
154
+ return `Usage: loupe <command> [options]
155
+ loupe mcp
156
+
157
+ Commands:
158
+ ${commands}
159
+
160
+ Options:
161
+ ${columns([...SHARED_OPTIONS, ["-v, --version", "Print the version"]])}
162
+
163
+ Run "loupe <command> --help" for the options of one command.
164
+ Run "loupe mcp" to serve each command as an MCP tool, over stdin and stdout.`;
165
+ }
166
+ function mcpHelp() {
167
+ return `Usage: loupe mcp
168
+
169
+ Serve each loupe command as an MCP tool, over stdin and stdout. An MCP client starts this server. For example, its config runs "npx -y @rootnative/loupe mcp".
170
+
171
+ Options:
172
+ ${columns([["-h, --help", "Print this help"]])}`;
173
+ }
174
+ function flagLeft(flag) {
175
+ if (flag.kind === "boolean") return `--${flag.name}`;
176
+ const value = flag.choices ? flag.choices.join("|") : `<${flag.kind}>`;
177
+ return `--${flag.name} ${value}`;
178
+ }
179
+ function flagRight(flag) {
180
+ const notes = [];
181
+ if (flag.required) notes.push("required");
182
+ if (flag.multiple) notes.push("can repeat");
183
+ if (flag.defaultValue !== void 0 && !(Array.isArray(flag.defaultValue) && flag.defaultValue.length === 0)) {
184
+ notes.push(`default: ${JSON.stringify(flag.defaultValue)}`);
185
+ }
186
+ const note = notes.length > 0 ? `(${notes.join(", ")})` : "";
187
+ return [flag.description, note].filter(Boolean).join(" ");
188
+ }
189
+ function commandHelp(command) {
190
+ const flags = flagsOf(command);
191
+ const positionals = (command.positionals ?? []).map((key) => flags.find((flag) => flag.key === key)).filter((flag) => flag !== void 0).map((flag) => flag.required ? `<${flag.name}>` : `[${flag.name}]`);
192
+ const usage = ["loupe", command.name, ...positionals, "[options]"].join(" ");
193
+ const options = columns([
194
+ ...flags.map((flag) => [flagLeft(flag), flagRight(flag)]),
195
+ ...SHARED_OPTIONS
196
+ ]);
197
+ return `Usage: ${usage}
198
+
199
+ ${command.summary}
200
+
201
+ Options:
202
+ ${options}`;
203
+ }
204
+
205
+ // src/cli/run.ts
206
+ var defaultIO = {
207
+ out: (text) => process.stdout.write(`${text}
208
+ `),
209
+ err: (text) => process.stderr.write(`${text}
210
+ `),
211
+ isTTY: process.stdout.isTTY === true,
212
+ // `once`: a second Ctrl-C finds no listener, and Node quits at once.
213
+ onInterrupt: (listener) => {
214
+ process.once("SIGINT", listener);
215
+ return () => process.off("SIGINT", listener);
216
+ }
217
+ };
218
+ var EXIT_OK = 0;
219
+ var EXIT_FAILED = 1;
220
+ var EXIT_USAGE = 2;
221
+ var EXIT_CANCELLED = 130;
222
+ var JSON_FLAGS = /* @__PURE__ */ new Set(["--json", "--no-json"]);
223
+ async function mcp(args, io, registry2, context) {
224
+ if (args.some((arg) => arg === "--help" || arg === "-h")) {
225
+ io.out(mcpHelp());
226
+ return EXIT_OK;
227
+ }
228
+ if (args.length > 0) {
229
+ io.err(`loupe mcp: "${args[0]}" is not an option of mcp.`);
230
+ io.err('Run "loupe mcp --help" for its use.');
231
+ return EXIT_USAGE;
232
+ }
233
+ const { serveMcp } = await import("./server-567FSCAH.js");
234
+ await serveMcp({
235
+ registry: registry2,
236
+ context,
237
+ onerror: (error) => io.err(`loupe mcp: ${error.message}`)
238
+ });
239
+ return EXIT_OK;
240
+ }
241
+ function exitCodeOf(result) {
242
+ if (result.ok) return EXIT_OK;
243
+ const { code } = result.error;
244
+ if (code === "cancelled") return EXIT_CANCELLED;
245
+ return code === "unknown_command" || code === "invalid_input" ? EXIT_USAGE : EXIT_FAILED;
246
+ }
247
+ async function run(argv, io = defaultIO, registry2 = registry, context = createContext()) {
248
+ const jsonFlag = argv.findLast((arg) => JSON_FLAGS.has(arg));
249
+ const json = jsonFlag ? jsonFlag === "--json" : !io.isTTY;
250
+ const [first, ...rest] = argv.filter((arg) => !JSON_FLAGS.has(arg));
251
+ if (first === void 0 || first === "--help" || first === "-h") {
252
+ io.out(globalHelp(registry2));
253
+ return EXIT_OK;
254
+ }
255
+ if (first === "--version" || first === "-v") {
256
+ io.out(version);
257
+ return EXIT_OK;
258
+ }
259
+ if (first === "mcp") return mcp(rest, io, registry2, context);
260
+ const report = (result) => {
261
+ const definition = registry2.get(result.command);
262
+ if (json) {
263
+ io.out(JSON.stringify(result));
264
+ } else if (result.ok) {
265
+ const format = definition?.format;
266
+ io.out(format?.(result.data) ?? JSON.stringify(result.data, null, 2));
267
+ } else {
268
+ io.err(`loupe ${result.command}: ${result.error.message}`);
269
+ if (exitCodeOf(result) === EXIT_USAGE) {
270
+ io.err('Run "loupe --help" for the commands and their options.');
271
+ }
272
+ }
273
+ if (result.ok && definition?.passed?.(result.data) === false) {
274
+ return EXIT_FAILED;
275
+ }
276
+ return exitCodeOf(result);
277
+ };
278
+ const command = registry2.get(first);
279
+ if (!command) return report(await runCommand(registry2, first, {}));
280
+ let parsed;
281
+ try {
282
+ parsed = parseCommandArgs(command, rest);
283
+ } catch (error) {
284
+ if (!(error instanceof LoupeError)) throw error;
285
+ return report({
286
+ ok: false,
287
+ command: command.name,
288
+ error: { code: error.code, message: error.message }
289
+ });
290
+ }
291
+ if (parsed.help) {
292
+ io.out(commandHelp(command));
293
+ return EXIT_OK;
294
+ }
295
+ const controller = new AbortController();
296
+ const stopListening = io.onInterrupt?.(() => {
297
+ io.err(
298
+ `loupe ${command.name}: stopping at the next safe point. Press Ctrl-C again to quit now.`
299
+ );
300
+ controller.abort();
301
+ });
302
+ try {
303
+ return report(
304
+ await runCommand(registry2, command.name, parsed.input, {
305
+ ...context,
306
+ signal: controller.signal
307
+ })
308
+ );
309
+ } finally {
310
+ stopListening?.();
311
+ }
312
+ }
313
+
314
+ // src/bin.ts
315
+ process.exitCode = await run(process.argv.slice(2));