@glassly/miniapp-cli 0.1.0-beta.3

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/src/dev.ts ADDED
@@ -0,0 +1,348 @@
1
+ import os from 'os';
2
+ import { readFileSync, existsSync, statSync, unlinkSync } from 'fs';
3
+ import { join, resolve } from 'path';
4
+ import { printQR, writeQRPng, type QRSize } from './qr.js';
5
+ import { validateManifest } from './manifest.js';
6
+ import { startDevSidecar } from './dev-server.js';
7
+ import { getLanIp, getMdnsHostname } from './lan.js';
8
+
9
+ const DEFAULT_DEV_PORT = 3000;
10
+ const DEV_PORT_SCAN_LIMIT = 50;
11
+ /** How often to re-check Wi-Fi / LAN IP while `glassly dev` is running. */
12
+ const LAN_IP_POLL_MS = 2_000;
13
+
14
+ export interface DevAttestationInput {
15
+ packageName: string;
16
+ devServerUrl: string;
17
+ }
18
+
19
+ export interface DevOptions {
20
+ cwd?: string;
21
+ qrOutput?: string;
22
+ /** Terminal QR size (--qr/-q small|medium|large). Defaults to medium. */
23
+ qrSize?: QRSize;
24
+ signDevAttestation?: (
25
+ input: DevAttestationInput,
26
+ ) => string | Promise<string | null | undefined> | null | undefined;
27
+ }
28
+
29
+ function contentTypeFor(path: string): string {
30
+ if (path.endsWith('.json')) return 'application/json; charset=utf-8';
31
+ if (path.endsWith('.html')) return 'text/html; charset=utf-8';
32
+ if (path.endsWith('.js') || path.endsWith('.mjs')) return 'application/javascript; charset=utf-8';
33
+ if (path.endsWith('.css')) return 'text/css; charset=utf-8';
34
+ if (path.endsWith('.png')) return 'image/png';
35
+ if (path.endsWith('.jpg') || path.endsWith('.jpeg')) return 'image/jpeg';
36
+ if (path.endsWith('.svg')) return 'image/svg+xml';
37
+ if (path.endsWith('.map')) return 'application/json; charset=utf-8';
38
+ return 'application/octet-stream';
39
+ }
40
+
41
+ function canListenOnPort(port: number): boolean {
42
+ try {
43
+ const server = Bun.serve({
44
+ hostname: '0.0.0.0',
45
+ port,
46
+ fetch: () => new Response(),
47
+ });
48
+ server.stop(true);
49
+ return true;
50
+ } catch {
51
+ return false;
52
+ }
53
+ }
54
+
55
+ function pickDevPort(start: number): number {
56
+ for (let i = 0; i < DEV_PORT_SCAN_LIMIT; i++) {
57
+ const port = start + i;
58
+ if (canListenOnPort(port) && canListenOnPort(port + 1)) {
59
+ return port;
60
+ }
61
+ }
62
+
63
+ const end = start + DEV_PORT_SCAN_LIMIT - 1;
64
+ console.error(
65
+ `Error: no free adjacent dev port pair found between base ports ${start} and ${end}. ` +
66
+ '`glassly dev` needs one port for static files and the next port for live reload.',
67
+ );
68
+ process.exit(1);
69
+ }
70
+
71
+ /**
72
+ * Run the project's build script. Two-layer projects ship a `build.ts` at
73
+ * the project root that emits `dist/background/index.js` + `dist/ui/*`.
74
+ * The sidecar's `bundle.zip` endpoint reads from disk, so the build must
75
+ * finish before the phone fetches.
76
+ */
77
+ async function runBuild(cwd: string): Promise<void> {
78
+ const buildScript = resolve(cwd, 'build.ts');
79
+ if (!existsSync(buildScript)) {
80
+ throw new Error(
81
+ 'build.ts not found at project root. Two-layer miniapps emit ' +
82
+ '`dist/background/index.js` + `dist/ui/index.html` via a build.ts ' +
83
+ 'script — see miniapps/example-miniapp/build.ts for the canonical shape.',
84
+ );
85
+ }
86
+ const proc = Bun.spawn(['bun', 'run', 'build.ts'], {
87
+ cwd,
88
+ stdout: 'inherit',
89
+ stderr: 'inherit',
90
+ });
91
+ const code = await proc.exited;
92
+ if (code !== 0) {
93
+ throw new Error(`build.ts exited with code ${code}`);
94
+ }
95
+ }
96
+
97
+ export async function dev(options: DevOptions = {}): Promise<void> {
98
+ const cwd = resolve(options.cwd ?? process.cwd());
99
+ const manifestPath = resolve(cwd, 'miniapp.json');
100
+ if (!existsSync(manifestPath)) {
101
+ console.error('Error: miniapp.json not found in current directory');
102
+ process.exit(1);
103
+ }
104
+
105
+ let manifest: Record<string, unknown>;
106
+ try {
107
+ manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));
108
+ } catch {
109
+ console.error('Error: miniapp.json is not valid JSON');
110
+ process.exit(1);
111
+ }
112
+
113
+ // Validate the manifest before launching. Dev miniapps are served
114
+ // directly (not packed), so without this check a typo in permissions or
115
+ // hardwareRequirements wouldn't surface until the miniapp tried to
116
+ // subscribe on the phone — and the developer would have no idea why.
117
+ const { valid, errors } = validateManifest(manifest);
118
+ if (!valid) {
119
+ console.error('miniapp.json validation failed:');
120
+ for (const err of errors) {
121
+ console.error(` - ${err}`);
122
+ }
123
+ process.exit(1);
124
+ }
125
+
126
+ const entry = manifest.entry as { background?: string; ui?: string } | undefined;
127
+ if (!entry || typeof entry.background !== 'string') {
128
+ console.error(
129
+ 'Error: miniapp.json is missing `entry.background`. Two-layer miniapps ' +
130
+ 'must declare `entry.background` (and optionally `entry.ui`) — see ' +
131
+ 'sdk/docs/two-layer.md.',
132
+ );
133
+ process.exit(1);
134
+ }
135
+
136
+ const name: string = (manifest.name as string) ?? 'unnamed';
137
+ const packageName: string = (manifest.packageName as string) ?? 'unknown';
138
+ const requestedPort: number = (manifest.port as number) ?? DEFAULT_DEV_PORT;
139
+ const port = pickDevPort(requestedPort);
140
+
141
+ console.log(`Starting dev server for ${name} (${packageName}) on port ${port}...`);
142
+ if (port !== requestedPort) {
143
+ console.log(`Port ${requestedPort} was unavailable; using ${port} instead.`);
144
+ }
145
+
146
+ // Initial build before serving — a fresh `bun run dev` should always
147
+ // start from a clean, current `dist/`.
148
+ try {
149
+ await runBuild(cwd);
150
+ } catch (err) {
151
+ console.error('Initial build failed:', (err as Error).message);
152
+ process.exit(1);
153
+ }
154
+
155
+ // Static HTTP server on `port` serving the project root. The phone hits
156
+ // `${devUrl}/miniapp.json` (reachability + manifest) and `${devUrl}/icon.png`
157
+ // (icon preview) before falling through to the sidecar's `bundle.zip`
158
+ // for the actual install. Range requests aren't supported — files are
159
+ // small and short-lived.
160
+ const userServer = Bun.serve({
161
+ hostname: '0.0.0.0',
162
+ port,
163
+ fetch(req) {
164
+ const url = new URL(req.url);
165
+ // Strip leading slash and prevent ../ traversal. Path joining
166
+ // against cwd already canonicalises, but we double-check by
167
+ // refusing absolute paths and any segment starting with `..`.
168
+ const rel = decodeURIComponent(url.pathname).replace(/^\/+/, '');
169
+ if (rel.split('/').some((seg) => seg === '..')) {
170
+ return new Response('forbidden', { status: 403 });
171
+ }
172
+ const abs = rel === '' ? join(cwd, 'miniapp.json') : join(cwd, rel);
173
+ try {
174
+ const stat = statSync(abs);
175
+ if (stat.isDirectory()) {
176
+ // Index of a directory isn't useful for the phone — refuse.
177
+ return new Response('not found', { status: 404 });
178
+ }
179
+ const buf = readFileSync(abs);
180
+ return new Response(buf, {
181
+ headers: {
182
+ 'content-type': contentTypeFor(abs),
183
+ 'cache-control': 'no-store',
184
+ },
185
+ });
186
+ } catch {
187
+ return new Response('not found', { status: 404 });
188
+ }
189
+ },
190
+ });
191
+
192
+ let lanIp = getLanIp();
193
+ if (!lanIp) {
194
+ console.error('Warning: Could not detect LAN IP address');
195
+ userServer.stop(true);
196
+ process.exit(1);
197
+ }
198
+
199
+ // Sidecar on userPort + 1 — hosts the `__host_dev` WebSocket the
200
+ // phone uses for live reload + console-log forwarding. The
201
+ // `onBeforeBroadcast` hook rebuilds `dist/` before the phone is
202
+ // notified, so the next `bundle.zip` fetch ships current code.
203
+ // Failure here is non-fatal; the miniapp still runs without live reload.
204
+ let sidecarPort: number | null = null;
205
+ let sidecar: ReturnType<typeof startDevSidecar> | null = null;
206
+ try {
207
+ sidecar = startDevSidecar({
208
+ port: port + 1,
209
+ watchDir: cwd,
210
+ onBeforeBroadcast: async () => {
211
+ try {
212
+ await runBuild(cwd);
213
+ } catch (err) {
214
+ console.error('Rebuild failed:', (err as Error).message);
215
+ }
216
+ },
217
+ });
218
+ sidecarPort = sidecar.port;
219
+ } catch (err) {
220
+ console.warn(
221
+ `Warning: dev sidecar failed to start on port ${port + 1} (${(err as Error).message}). ` +
222
+ `Live reload + console bridge will be disabled.`,
223
+ );
224
+ }
225
+
226
+ const mdnsHost = getMdnsHostname();
227
+
228
+ const buildDevUrl = async (ip: string): Promise<string> => {
229
+ const devServerUrl = `http://${ip}:${port}`;
230
+ const base = `miniapp://dev?url=${encodeURIComponent(devServerUrl)}&name=${encodeURIComponent(name)}&package=${encodeURIComponent(packageName)}`;
231
+ const withDevPort = sidecarPort ? `${base}&dev=${sidecarPort}` : base;
232
+ // mDNS hint lets the phone retry via ComputerName.local when the raw IP
233
+ // goes stale after a Wi-Fi/DHCP change — same QR, new address under the hood.
234
+ const withMdns = mdnsHost ? `${withDevPort}&mdns=${encodeURIComponent(mdnsHost)}` : withDevPort;
235
+ if (!options.signDevAttestation) return withMdns;
236
+
237
+ try {
238
+ const attestation = await options.signDevAttestation({ packageName, devServerUrl });
239
+ if (!attestation) return withMdns;
240
+ return `${withMdns}&attestation=${encodeURIComponent(attestation)}`;
241
+ } catch (error) {
242
+ console.warn(`Warning: could not sign dev URL (${(error as Error).message}). Miniapp auto-auth will be unavailable.`);
243
+ return withMdns;
244
+ }
245
+ };
246
+
247
+ const printBanner = (): void => {
248
+ console.log('\n╔══════════════════════════════════════════════════════════════╗');
249
+ console.log('║ To test your miniapp on glasses: ║');
250
+ console.log('║ ║');
251
+ console.log('║ 1. Open the Glassly App on your phone ║');
252
+ console.log('║ 2. Settings → Developer settings ║');
253
+ console.log('║ 3. Under "Mini App Development", tap ║');
254
+ console.log('║ "Scan Mini App QR Code" and scan the QR below ║');
255
+ console.log('║ ║');
256
+ console.log('║ Your phone must be on the same Wi-Fi as this computer. ║');
257
+ console.log('║ ║');
258
+ console.log('║ Dev mode is live and temporary: ║');
259
+ console.log('║ • Keep this process and computer running. ║');
260
+ console.log('║ • Each package gets its own dev entry, so you can scan ║');
261
+ console.log('║ and test multiple dev miniapps side by side. ║');
262
+ console.log('║ • The Glassly App caches each miniapp name and icon. ║');
263
+ console.log('║ ║');
264
+ console.log('║ For a persistent install, run: bun run release ║');
265
+ console.log('╚══════════════════════════════════════════════════════════════╝\n');
266
+ };
267
+
268
+ const defaultQrPath = join(os.tmpdir(), `glassly-dev-qr-${packageName}-${port}.png`);
269
+ const qrOutputPath = resolve(options.qrOutput ?? defaultQrPath);
270
+ const cleanupQrOnExit = !options.qrOutput;
271
+
272
+ const emitQR = async (url: string): Promise<void> => {
273
+ await printQR(url, {size: options.qrSize});
274
+ const wrote = await writeQRPng(url, qrOutputPath);
275
+ console.log(`\n${url}`);
276
+ if (wrote) {
277
+ console.log(`PNG QR: ${qrOutputPath}\n`);
278
+ } else {
279
+ console.log(`PNG QR: (not written — see warning above)\n`);
280
+ }
281
+ };
282
+
283
+ printBanner();
284
+ if (mdnsHost) {
285
+ console.log(`mDNS: ${mdnsHost} (phone can keep using this name across Wi-Fi IP changes)\n`);
286
+ }
287
+ const devUrl = await buildDevUrl(lanIp);
288
+ await emitQR(devUrl);
289
+
290
+ // Monitor for LAN IP changes (e.g., Wi-Fi switch / DHCP renew).
291
+ // Re-score interfaces — a VPN coming up must not steal the QR off Wi-Fi,
292
+ // and a Wi-Fi roam must mint a new QR within a couple seconds.
293
+ let ipCheckInFlight = false;
294
+ const ipCheckInterval = setInterval(() => {
295
+ if (ipCheckInFlight) return;
296
+ const newIp = getLanIp();
297
+ if (!newIp || newIp === lanIp) return;
298
+ ipCheckInFlight = true;
299
+ void (async () => {
300
+ try {
301
+ console.log(`\n📶 LAN IP changed: ${lanIp} → ${newIp}`);
302
+ console.log('Rebuilding so baked-in LAN URLs (e.g. signing endpoints) stay current…');
303
+ try {
304
+ await runBuild(cwd);
305
+ } catch (err) {
306
+ // Leave lanIp on the previous value so the next poll retries this IP.
307
+ // Committing early would leave dist/ stale while skipping further rebuilds.
308
+ console.error('Rebuild after LAN IP change failed:', (err as Error).message);
309
+ return;
310
+ }
311
+ const previous = lanIp;
312
+ lanIp = newIp;
313
+ console.log(`LAN IP committed: ${previous} → ${newIp}`);
314
+ console.log('New QR (re-scan if the Glassly App still has the old IP):');
315
+ printBanner();
316
+ if (mdnsHost) {
317
+ console.log(`mDNS: ${mdnsHost}\n`);
318
+ }
319
+ const newDevUrl = await buildDevUrl(newIp);
320
+ await emitQR(newDevUrl);
321
+ } finally {
322
+ ipCheckInFlight = false;
323
+ }
324
+ })();
325
+ }, LAN_IP_POLL_MS);
326
+
327
+ const shutdown = () => {
328
+ clearInterval(ipCheckInterval);
329
+ // Only remove the auto temp path — keep an explicit --qr-output artifact.
330
+ if (cleanupQrOnExit) {
331
+ try {
332
+ unlinkSync(qrOutputPath);
333
+ } catch {
334
+ // best-effort cleanup of temp PNG
335
+ }
336
+ }
337
+ sidecar?.stop();
338
+ userServer.stop(true);
339
+ process.exit(0);
340
+ };
341
+ process.on('SIGINT', shutdown);
342
+ process.on('SIGTERM', shutdown);
343
+
344
+ // Keep the process alive — the static server + sidecar hold the loop.
345
+ // Block on a never-resolving promise so the foreground stays on the
346
+ // dev process until SIGINT/SIGTERM fires.
347
+ await new Promise<void>(() => {});
348
+ }
@@ -0,0 +1,163 @@
1
+ // `glassly hardware <action>` subcommand handlers. Mirrors permission.ts.
2
+
3
+ import * as p from "@clack/prompts"
4
+ import {ALLOWED_HARDWARE_LEVELS, ALLOWED_HARDWARE_TYPES} from "./manifest.js"
5
+ import {
6
+ addHardware,
7
+ listHardware,
8
+ MutateError,
9
+ removeHardware,
10
+ type Manifest,
11
+ } from "./manifest-mutate.js"
12
+ import {formatLoadError, formatWriteError, loadManifest, writeManifest} from "./manifest-format.js"
13
+ import {hardwareDescription} from "./permission-hints.js"
14
+
15
+ function loadOrExit(): {path: string; manifest: Manifest} {
16
+ const r = loadManifest(process.cwd())
17
+ if (!r.ok) {
18
+ console.error(formatLoadError(r.error))
19
+ process.exit(1)
20
+ }
21
+ return {path: r.value.path, manifest: r.value.manifest}
22
+ }
23
+
24
+ function persistOrExit(path: string, manifest: Manifest): void {
25
+ const w = writeManifest(path, manifest)
26
+ if (!w.ok) {
27
+ console.error(formatWriteError(w.error))
28
+ process.exit(1)
29
+ }
30
+ }
31
+
32
+ function printHardware(manifest: Manifest): void {
33
+ const hw = listHardware(manifest)
34
+ if (hw.length === 0) {
35
+ console.log("Hardware requirements: none declared.")
36
+ return
37
+ }
38
+ console.log(`Hardware requirements (${hw.length}):`)
39
+ for (const h of hw) {
40
+ const desc = h.description ? ` — ${h.description}` : ""
41
+ console.log(` • ${h.type} (${h.level})${desc}`)
42
+ }
43
+ }
44
+
45
+ export async function listHardwareCmd(): Promise<void> {
46
+ const {manifest} = loadOrExit()
47
+ printHardware(manifest)
48
+ }
49
+
50
+ export async function addHardwareCmd(typeArg?: string, levelArg?: string): Promise<void> {
51
+ const {path, manifest} = loadOrExit()
52
+ let type = typeArg
53
+ let level = levelArg
54
+ let description: string | undefined
55
+
56
+ if (!type) {
57
+ p.intro("Add a hardware requirement")
58
+ const declared = new Set(listHardware(manifest).map((h) => h.type))
59
+ const available = ALLOWED_HARDWARE_TYPES.filter((h) => !declared.has(h))
60
+ if (available.length === 0) {
61
+ p.note("All hardware types are already declared. Nothing to add.", "Hardware")
62
+ p.outro("Done")
63
+ return
64
+ }
65
+ const pickedType = await p.select({
66
+ message: "Which hardware?",
67
+ options: available.map((h) => ({value: h, label: h, hint: hardwareDescription(h)})),
68
+ })
69
+ if (p.isCancel(pickedType)) {
70
+ p.cancel("Cancelled.")
71
+ return
72
+ }
73
+ type = pickedType as string
74
+
75
+ if (!level) {
76
+ const pickedLevel = await p.select({
77
+ message: "Required or optional?",
78
+ options: ALLOWED_HARDWARE_LEVELS.map((l) => ({
79
+ value: l,
80
+ label: l,
81
+ hint:
82
+ l === "REQUIRED"
83
+ ? "Glasses without this hardware can't run the app"
84
+ : "Glasses without this hardware still run the app (degraded)",
85
+ })),
86
+ })
87
+ if (p.isCancel(pickedLevel)) {
88
+ p.cancel("Cancelled.")
89
+ return
90
+ }
91
+ level = pickedLevel as string
92
+ }
93
+
94
+ const desc = await p.text({
95
+ message: "Optional description (how the miniapp uses this hardware):",
96
+ placeholder: "(skip)",
97
+ })
98
+ if (p.isCancel(desc)) {
99
+ p.cancel("Cancelled.")
100
+ return
101
+ }
102
+ if (typeof desc === "string" && desc.trim()) description = desc.trim()
103
+ }
104
+
105
+ if (!level) {
106
+ console.error(`Missing level. Usage: glassly hardware add ${type} <REQUIRED|OPTIONAL>`)
107
+ process.exit(1)
108
+ }
109
+
110
+ let updated: Manifest
111
+ try {
112
+ updated = addHardware(manifest, type!, level!, description !== undefined ? {description} : undefined)
113
+ } catch (e) {
114
+ if (e instanceof MutateError) {
115
+ console.error(e.message)
116
+ process.exit(1)
117
+ }
118
+ throw e
119
+ }
120
+
121
+ persistOrExit(path, updated)
122
+ printHardware(updated)
123
+ if (typeArg === undefined) {
124
+ p.outro("Saved miniapp.json ✨")
125
+ }
126
+ }
127
+
128
+ export async function removeHardwareCmd(typeArg?: string): Promise<void> {
129
+ const {path, manifest} = loadOrExit()
130
+ let type = typeArg
131
+
132
+ if (!type) {
133
+ const declared = listHardware(manifest)
134
+ if (declared.length === 0) {
135
+ console.log("No hardware requirements declared. Nothing to remove.")
136
+ return
137
+ }
138
+ p.intro("Remove a hardware requirement")
139
+ const picked = await p.select({
140
+ message: "Which hardware to remove?",
141
+ options: declared.map((h) => ({value: h.type, label: `${h.type} (${h.level})`})),
142
+ })
143
+ if (p.isCancel(picked)) {
144
+ p.cancel("Cancelled.")
145
+ return
146
+ }
147
+ type = picked as string
148
+ }
149
+
150
+ let updated: Manifest
151
+ try {
152
+ updated = removeHardware(manifest, type!)
153
+ } catch (e) {
154
+ if (e instanceof MutateError) {
155
+ console.error(e.message)
156
+ process.exit(1)
157
+ }
158
+ throw e
159
+ }
160
+
161
+ persistOrExit(path, updated)
162
+ printHardware(updated)
163
+ }
@@ -0,0 +1,84 @@
1
+ /// <reference types="bun-types" />
2
+
3
+ import {describe, expect, test} from "bun:test"
4
+ import {getMdnsHostname, pickLanIp, scoreLanIface, type LanIface} from "./lan.js"
5
+ import os from "os"
6
+
7
+ function iface(partial: Partial<LanIface> & Pick<LanIface, "name" | "address">): LanIface {
8
+ return {
9
+ family: "IPv4",
10
+ internal: false,
11
+ netmask: "255.255.255.0",
12
+ mac: "aa:bb:cc:dd:ee:ff",
13
+ ...partial,
14
+ }
15
+ }
16
+
17
+ describe("scoreLanIface", () => {
18
+ test("rejects internal, link-local, and tunnel names", () => {
19
+ expect(scoreLanIface(iface({name: "lo0", address: "127.0.0.1", internal: true}))).toBeLessThan(0)
20
+ expect(scoreLanIface(iface({name: "en0", address: "169.254.1.2"}))).toBeLessThan(0)
21
+ expect(scoreLanIface(iface({name: "utun0", address: "10.137.68.90", netmask: "255.0.0.0", mac: "00:00:00:00:00:00"}))).toBeLessThan(
22
+ 0,
23
+ )
24
+ expect(scoreLanIface(iface({name: "tailscale0", address: "100.64.1.2"}))).toBeLessThan(0)
25
+ })
26
+
27
+ test("prefers en0 Wi-Fi over a leftover /8 tunnel-shaped address", () => {
28
+ const wifi = scoreLanIface(iface({name: "en0", address: "192.168.50.252"}))
29
+ const tunnel = scoreLanIface(
30
+ iface({name: "en5", address: "10.0.0.2", netmask: "255.0.0.0", mac: "00:00:00:00:00:00"}),
31
+ )
32
+ expect(wifi).toBeGreaterThan(0)
33
+ expect(wifi).toBeGreaterThan(tunnel)
34
+ })
35
+ })
36
+
37
+ describe("pickLanIp", () => {
38
+ test("picks Wi-Fi when a VPN utun is also present", () => {
39
+ const ip = pickLanIp({
40
+ lo0: [iface({name: "lo0", address: "127.0.0.1", internal: true})],
41
+ en0: [iface({name: "en0", address: "192.168.50.252"})],
42
+ utun0: [iface({name: "utun0", address: "10.137.68.90", netmask: "255.0.0.0", mac: "00:00:00:00:00:00"})],
43
+ })
44
+ expect(ip).toBe("192.168.50.252")
45
+ })
46
+
47
+ test("prefers 192.168 Wi-Fi over a first-listed 10.x tunnel-like iface", () => {
48
+ // Object key order would have returned 10.x first with the old naive picker.
49
+ const ip = pickLanIp({
50
+ utun2: [iface({name: "utun2", address: "10.1.2.3", netmask: "255.0.0.0", mac: "00:00:00:00:00:00"})],
51
+ en0: [iface({name: "en0", address: "192.168.3.162"})],
52
+ })
53
+ expect(ip).toBe("192.168.3.162")
54
+ })
55
+
56
+ test("returns null when only loopback exists", () => {
57
+ expect(
58
+ pickLanIp({
59
+ lo0: [iface({name: "lo0", address: "127.0.0.1", internal: true})],
60
+ }),
61
+ ).toBeNull()
62
+ })
63
+ })
64
+
65
+ describe("getMdnsHostname first label", () => {
66
+ test("strips DNS suffixes before appending .local", () => {
67
+ const original = os.hostname
68
+ ;(os as {hostname: () => string}).hostname = () => "mba.corp.example.com"
69
+ try {
70
+ expect(getMdnsHostname()).toBe("mba.local")
71
+ } finally {
72
+ ;(os as {hostname: typeof original}).hostname = original
73
+ }
74
+ })
75
+ })
76
+
77
+ describe("scoreLanIface Linux predictable names", () => {
78
+ test("ranks wlp*/enp* as real adapters", () => {
79
+ const wifi = scoreLanIface(iface({name: "wlp3s0", address: "192.168.1.40"}))
80
+ const eth = scoreLanIface(iface({name: "enp0s3", address: "192.168.1.41"}))
81
+ expect(wifi).toBeGreaterThan(50)
82
+ expect(eth).toBeGreaterThan(50)
83
+ })
84
+ })