File size: 22,756 Bytes
914f53d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 | import os from 'os';
import { readFileSync, existsSync, statSync, unlinkSync } from 'fs';
import { join, resolve } from 'path';
import { printQR, writeQRPng } from './qr.js';
import { warnIfPlaceholderIcon } from './icon.js';
import { validateManifest } from './manifest.js';
import { buildProjectSnapshot, startDevSidecar } from './dev-server.js';
import { getLanIp, getMdnsHostname } from './lan.js';
import { adbReverse, closeUsbTunnel, missingReversePorts, openUsbTunnel } from './adb.js';
const DEFAULT_DEV_PORT = 3000;
const DEV_PORT_SCAN_LIMIT = 50;
/** How often to re-check Wi-Fi / LAN IP while `mentra-miniapp dev` is running. */
const LAN_IP_POLL_MS = 2_000;
/**
* How often to confirm the `adb reverse` mappings are still live. Slower than
* the LAN poll because each check spawns an adb subprocess, and a dropped
* tunnel only matters on the phone's next fetch.
*/
const USB_TUNNEL_POLL_MS = 5_000;
/** Where `adb reverse` publishes the laptop from the phone's point of view. */
const USB_LOOPBACK_HOST = '127.0.0.1';
export interface DevOptions {
cwd?: string;
qrOutput?: string;
/**
* Reach the phone over USB via `adb reverse` instead of the LAN. The QR
* advertises loopback, so the phone does not need to share this computer's
* Wi-Fi. Android only.
*/
usb?: boolean;
/** Target a specific `adb` device serial. Only meaningful with `usb`. */
device?: string;
/**
* Watch source files and remount the phone WebView / respawn the
* background JSContext on save. Default true. `--no-hot-reload` sets
* this to false; the sidecar still forwards console logs.
*/
hotReload?: boolean;
}
/** Where the dev server serves the project's ZIP, relative to the miniapp URL. */
export const DEV_BUNDLE_PATH = 'bundle.zip';
/**
* The miniapp URL the QR encodes and `dev` prints: the dev server's root,
* which serves miniapp.json like any miniapp URL. A LAN address, or loopback
* over USB, so the Mentra App installs it as a local-network miniapp.
*/
export function buildDevUrl(host: string, port: number): string {
const urlHost = host.includes(':') && !host.startsWith('[') ? `[${host}]` : host;
return `http://${urlHost}:${port}/`;
}
/** What the served miniapp.json's `development` field tells the phone about the dev server. */
export interface DevelopmentInfo {
/** The sidecar's live-reload socket. Absent while the sidecar isn't running. */
reload?: string;
/** This computer's mDNS name, to reach it by when its LAN address changes. */
mdns?: string;
}
/**
* The miniapp.json the dev server serves: the ZIP's own, plus `bundle` naming
* the ZIP and its SHA-256, as any miniapp URL serves, and `development`, which
* the Mentra App reads only from a local-network URL.
*/
export function servedDevManifest(
manifest: Record<string, unknown>,
sha256: string,
development: DevelopmentInfo,
): Record<string, unknown> {
return { ...manifest, bundle: { url: DEV_BUNDLE_PATH, sha256 }, development };
}
export interface DevRequestHandlerOptions {
/** The project root the server serves. */
cwd: string;
/** The sidecar's port, read on each request: null while it isn't running. */
sidecarPort: () => number | null;
/** This computer's mDNS name, if it has one. */
mdnsHost: string | null;
/**
* Settles once no build is writing dist/, so a request never reads half a
* build, and miniapp.json and the ZIP it names come from the same one.
*/
idle?: () => Promise<void>;
}
const NO_STORE = 'no-store';
/**
* Runs builds one at a time, in the order they were asked for, so two
* triggers (a save and a LAN address change) never write dist/ at once.
* `idle` settles once every build asked for so far has finished, failed ones
* included.
*/
export function createBuildQueue(run: () => Promise<void>): { build: () => Promise<void>; idle: () => Promise<void> } {
let tail: Promise<void> = Promise.resolve();
return {
build() {
const next = tail.then(run);
tail = next.catch(() => {});
return next;
},
async idle() {
let current: Promise<void>;
do {
current = tail;
await current;
} while (current !== tail);
},
};
}
/**
* The static server's requests. `/miniapp.json` (and `/`) is the served
* manifest, `/bundle.zip` the ZIP it names; any other path is a project file,
* which live launches load `dist/` from.
*/
export function createDevRequestHandler(options: DevRequestHandlerOptions): (req: Request) => Promise<Response> {
return async (req) => {
await options.idle?.();
const url = new URL(req.url);
if (url.pathname === '/' || url.pathname === '/miniapp.json') {
const snapshot = await buildProjectSnapshot(options.cwd);
if (snapshot.manifest === null) return new Response('not found', { status: 404 });
let manifest: unknown;
try {
manifest = JSON.parse(snapshot.manifest);
} catch {
manifest = null;
}
if (typeof manifest !== 'object' || manifest === null || Array.isArray(manifest)) {
return new Response('miniapp.json is not a JSON object', { status: 500 });
}
const development: DevelopmentInfo = {};
const sidecarPort = options.sidecarPort();
// The host the phone reached this server by: the LAN address, loopback
// over USB, or the mDNS name. The sidecar is on the same machine.
if (sidecarPort) development.reload = `ws://${url.hostname}:${sidecarPort}/__mentra_dev`;
// Lets the phone retry via ComputerName.local when the raw IP goes stale
// after a Wi-Fi/DHCP change.
if (options.mdnsHost) development.mdns = options.mdnsHost;
const served = servedDevManifest(manifest as Record<string, unknown>, snapshot.sha256, development);
return new Response(`${JSON.stringify(served, null, 2)}\n`, {
headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': NO_STORE },
});
}
if (url.pathname === `/${DEV_BUNDLE_PATH}` || url.pathname === '/__mentra_dev/bundle.zip') {
const { zip } = await buildProjectSnapshot(options.cwd);
const body = zip.buffer.slice(zip.byteOffset, zip.byteOffset + zip.byteLength) as ArrayBuffer;
return new Response(body, {
headers: {
'content-type': 'application/zip',
'content-length': String(zip.byteLength),
'cache-control': NO_STORE,
},
});
}
// Strip leading slash and prevent ../ traversal. Path joining
// against cwd already canonicalises, but we double-check by
// refusing absolute paths and any segment starting with `..`.
const rel = decodeURIComponent(url.pathname).replace(/^\/+/, '');
if (rel.split('/').some((seg) => seg === '..')) {
return new Response('forbidden', { status: 403 });
}
const abs = join(options.cwd, rel);
try {
const stat = statSync(abs);
if (stat.isDirectory()) {
// Index of a directory isn't useful for the phone β refuse.
return new Response('not found', { status: 404 });
}
const buf = readFileSync(abs);
return new Response(buf, {
headers: {
'content-type': contentTypeFor(abs),
'cache-control': NO_STORE,
},
});
} catch {
return new Response('not found', { status: 404 });
}
};
}
function contentTypeFor(path: string): string {
if (path.endsWith('.json')) return 'application/json; charset=utf-8';
if (path.endsWith('.html')) return 'text/html; charset=utf-8';
if (path.endsWith('.js') || path.endsWith('.mjs')) return 'application/javascript; charset=utf-8';
if (path.endsWith('.css')) return 'text/css; charset=utf-8';
if (path.endsWith('.png')) return 'image/png';
if (path.endsWith('.jpg') || path.endsWith('.jpeg')) return 'image/jpeg';
if (path.endsWith('.svg')) return 'image/svg+xml';
if (path.endsWith('.map')) return 'application/json; charset=utf-8';
return 'application/octet-stream';
}
function canListenOnPort(port: number): boolean {
try {
const server = Bun.serve({
hostname: '0.0.0.0',
port,
fetch: () => new Response(),
});
server.stop(true);
return true;
} catch {
return false;
}
}
function pickDevPort(start: number): number {
for (let i = 0; i < DEV_PORT_SCAN_LIMIT; i++) {
const port = start + i;
if (canListenOnPort(port) && canListenOnPort(port + 1)) {
return port;
}
}
const end = start + DEV_PORT_SCAN_LIMIT - 1;
console.error(
`Error: no free adjacent dev port pair found between base ports ${start} and ${end}. ` +
'`mentra-miniapp dev` needs one port for static files and the next port for live reload.',
);
process.exit(1);
}
/**
* Run the project's build script. Two-layer projects ship a `build.ts` at
* the project root that emits `dist/background/index.js` + `dist/ui/*`.
* The sidecar's `bundle.zip` endpoint reads from disk, so the build must
* finish before the phone fetches.
*/
async function runBuild(cwd: string): Promise<void> {
const buildScript = resolve(cwd, 'build.ts');
if (!existsSync(buildScript)) {
throw new Error(
'build.ts not found at project root. Two-layer miniapps emit ' +
'`dist/background/index.js` + `dist/ui/index.html` via a build.ts ' +
'script β see examples/miniapp/build.ts for the canonical shape.',
);
}
const proc = Bun.spawn(['bun', 'run', 'build.ts'], {
cwd,
stdout: 'inherit',
stderr: 'inherit',
});
const code = await proc.exited;
if (code !== 0) {
throw new Error(`build.ts exited with code ${code}`);
}
}
export async function dev(options: DevOptions = {}): Promise<void> {
const cwd = resolve(options.cwd ?? process.cwd());
const manifestPath = resolve(cwd, 'miniapp.json');
if (!existsSync(manifestPath)) {
console.error('Error: miniapp.json not found in current directory');
process.exit(1);
}
let manifest: Record<string, unknown>;
try {
manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));
} catch {
console.error('Error: miniapp.json is not valid JSON');
process.exit(1);
}
// Validate the manifest before launching. Dev miniapps are served
// directly (not packed), so without this check a typo in permissions or
// hardwareRequirements wouldn't surface until the miniapp tried to
// subscribe on the phone β and the developer would have no idea why.
const { valid, errors } = validateManifest(manifest);
if (!valid) {
console.error('miniapp.json validation failed:');
for (const err of errors) {
console.error(` - ${err}`);
}
process.exit(1);
}
const entry = manifest.entry as { background?: string; ui?: string } | undefined;
if (!entry || typeof entry.background !== 'string') {
console.error(
'Error: miniapp.json is missing `entry.background`. Two-layer miniapps ' +
'must declare `entry.background` (and optionally `entry.ui`) β see ' +
'sdk/docs/two-layer.md.',
);
process.exit(1);
}
warnIfPlaceholderIcon(cwd);
const name: string = (manifest.name as string) ?? 'unnamed';
const packageName: string = (manifest.packageName as string) ?? 'unknown';
// MENTRA_MINIAPP_DEV_PORT: the port a runner serving several miniapps assigned
// (the Mentra App's scripts/dev-miniapps.mjs).
const requestedPort: number =
Number(process.env.MENTRA_MINIAPP_DEV_PORT) || ((manifest.port as number) ?? DEFAULT_DEV_PORT);
const port = pickDevPort(requestedPort);
console.log(`Starting dev server for ${name} (${packageName}) on port ${port}...`);
if (port !== requestedPort) {
console.log(`Port ${requestedPort} was unavailable; using ${port} instead.`);
}
// Every build goes through one queue, so the server can hold requests until
// no build is writing dist/.
const { build, idle } = createBuildQueue(() => runBuild(cwd));
// Initial build before serving β a fresh `bun run dev` should always
// start from a clean, current `dist/`.
try {
await build();
} catch (err) {
console.error('Initial build failed:', (err as Error).message);
process.exit(1);
}
const mdnsHost = getMdnsHostname();
let sidecarPort: number | null = null;
// Static HTTP server on `port` serving the project root: the miniapp URL.
// The phone fetches `miniapp.json`, then the `bundle.zip` it names, and
// live launches load `dist/` files from here. Range requests aren't
// supported β files are small and short-lived.
const userServer = Bun.serve({
hostname: '0.0.0.0',
port,
fetch: createDevRequestHandler({ cwd, sidecarPort: () => sidecarPort, mdnsHost, idle }),
});
// In USB mode the QR advertises loopback, so a missing LAN IP is the expected
// case (laptop off Wi-Fi entirely) rather than a fatal one. It's still kept
// when present, as the fallback if the ADB tunnel can't be established.
let lanIp = getLanIp();
if (!lanIp && !options.usb) {
console.error('Warning: Could not detect LAN IP address');
userServer.stop(true);
process.exit(1);
}
// Sidecar on userPort + 1 β hosts the `__mentra_dev` WebSocket the
// phone uses for live reload + console-log forwarding. The
// `onBeforeBroadcast` hook rebuilds `dist/` before the phone is
// notified, so the next `bundle.zip` fetch ships current code.
// Failure here is non-fatal; the miniapp still runs without live reload.
let sidecar: ReturnType<typeof startDevSidecar> | null = null;
try {
sidecar = startDevSidecar({
port: port + 1,
watchDir: cwd,
hotReload: options.hotReload !== false,
onBeforeBroadcast: async () => {
try {
await build();
} catch (err) {
console.error('Rebuild failed:', (err as Error).message);
}
},
});
sidecarPort = sidecar.port;
if (options.hotReload === false) {
console.log('Hot reload off. Restart without --no-hot-reload to remount the miniapp on save.');
}
} catch (err) {
console.warn(
`Warning: dev sidecar failed to start on port ${port + 1} (${(err as Error).message}). ` +
`Live reload + console bridge will be disabled.`,
);
}
// USB mode: publish this machine's ports on the phone's loopback so the QR
// can point at 127.0.0.1. Done after the sidecar starts so we only tunnel a
// port that something is actually listening on.
const usbPorts: number[] = options.usb ? (sidecarPort ? [port, sidecarPort] : [port]) : [];
let usbSerial: string | undefined;
let usbActive = false;
if (options.device && !options.usb) {
console.warn('Warning: --device applies only with --usb. Ignoring it; the QR will use the LAN address.');
}
if (options.usb) {
const tunnel = openUsbTunnel(usbPorts, { device: options.device });
if (tunnel.ok) {
usbActive = true;
usbSerial = tunnel.serial;
const portList = usbPorts.map((p) => `tcp:${p}`).join(', ');
console.log(`USB: adb reverse active on ${portList}${usbSerial ? ` (${usbSerial})` : ''}`);
if (!sidecarPort) {
console.warn('Warning: dev sidecar is down, so live reload is unavailable over USB too.');
}
} else {
console.error(`Error: --usb could not establish an ADB tunnel.\n ${tunnel.reason}`);
if (!lanIp) {
sidecar?.stop();
userServer.stop(true);
process.exit(1);
}
console.warn(`Falling back to the LAN address ${lanIp} β the phone must share this computer's Wi-Fi.`);
}
}
const printBanner = (): void => {
console.log('\nββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ');
console.log('β To test your miniapp on glasses: β');
console.log('β β');
console.log('β 1. Open the Mentra App on your phone β');
console.log('β 2. Settings β Miniapp Developer Settings β');
console.log('β 3. Tap "Scan Miniapp QR Code" and scan the QR below β');
console.log('β β');
if (usbActive) {
console.log('β Your phone is reached over USB (adb reverse), not Wi-Fi. β');
console.log('β Keep the cable plugged in. β');
} else {
console.log('β Your phone must be on the same Wi-Fi as this computer. β');
}
console.log('β β');
console.log('β Scan once. Every saved change rebuilds and reloads on the β');
console.log('β phone, with no rescan. Keep this process running. β');
console.log('β β');
console.log('β Each package gets its own dev entry, so several dev β');
console.log('β miniapps can run side by side. The home screen caches the β');
console.log('β name and icon; rescan to update them. β');
console.log('β β');
console.log('β For an install that runs without this computer: β');
console.log('β bun run release β');
console.log('ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n');
};
const defaultQrPath = join(os.tmpdir(), `mentra-dev-qr-${packageName}-${port}.png`);
const qrOutputPath = resolve(options.qrOutput ?? defaultQrPath);
const cleanupQrOnExit = !options.qrOutput;
const emitQR = async (url: string): Promise<void> => {
await printQR(url);
const wrote = await writeQRPng(url, qrOutputPath);
console.log(`\nMiniapp URL: ${url}`);
if (wrote) {
console.log(`PNG QR: ${qrOutputPath}\n`);
} else {
console.log(`PNG QR: (not written β see warning above)\n`);
}
};
printBanner();
if (mdnsHost) {
console.log(`mDNS: ${mdnsHost} (phone can keep using this name across Wi-Fi IP changes)\n`);
}
// Loopback when the USB tunnel is up, otherwise the LAN IP. `lanIp` is
// non-null here: the only path that leaves it null exits above unless the
// tunnel came up. The QR is the plain miniapp URL and carries no credential.
const devHost = usbActive ? USB_LOOPBACK_HOST : lanIp!;
await emitQR(buildDevUrl(devHost, port));
// Confirm the reverse mappings survive. They are dropped on unplug, on
// `adb kill-server`, and on device reboot, and nothing notifies us β the
// phone just silently stops reaching the laptop. Log the transitions only,
// so a long unplug doesn't spam a line every tick.
let usbTunnelHealthy = true;
const usbTunnelInterval = usbActive
? setInterval(() => {
const missing = missingReversePorts(usbPorts, { device: usbSerial });
if (missing.length === 0) {
if (!usbTunnelHealthy) {
usbTunnelHealthy = true;
console.log('USB: tunnel restored.');
}
return;
}
if (usbTunnelHealthy) {
usbTunnelHealthy = false;
const portList = missing.map((p) => `tcp:${p}`).join(', ');
console.warn(`USB: tunnel lost (${portList}) β device unplugged or adb restarted. Retryingβ¦`);
}
for (const p of missing) adbReverse(p, { device: usbSerial });
}, USB_TUNNEL_POLL_MS)
: null;
// Monitor for LAN IP changes (e.g., Wi-Fi switch / DHCP renew).
// Re-score interfaces β a VPN coming up must not steal the QR off Wi-Fi,
// and a Wi-Fi roam must mint a new QR within a couple seconds.
let ipCheckInFlight = false;
const checkLanIpChange = (): void => {
if (ipCheckInFlight) return;
const newIp = getLanIp();
if (!newIp || newIp === lanIp) return;
ipCheckInFlight = true;
void (async () => {
try {
console.log(`\nπΆ LAN IP changed: ${lanIp} β ${newIp}`);
console.log('Rebuilding so baked-in LAN URLs (e.g. signing endpoints) stay currentβ¦');
try {
await build();
} catch (err) {
// Leave lanIp on the previous value so the next poll retries this IP.
// Committing early would leave dist/ stale while skipping further rebuilds.
console.error('Rebuild after LAN IP change failed:', (err as Error).message);
return;
}
const previous = lanIp;
lanIp = newIp;
console.log(`LAN IP committed: ${previous} β ${newIp}`);
console.log('New QR (re-scan if the Mentra App still has the old IP):');
printBanner();
if (mdnsHost) {
console.log(`mDNS: ${mdnsHost}\n`);
}
await emitQR(buildDevUrl(newIp, port));
} finally {
ipCheckInFlight = false;
}
})();
};
// Skipped under USB: the QR host is a fixed loopback address, and there are
// no baked-in LAN URLs to keep current.
const ipCheckInterval = usbActive ? null : setInterval(checkLanIpChange, LAN_IP_POLL_MS);
const shutdown = () => {
if (ipCheckInterval) clearInterval(ipCheckInterval);
if (usbTunnelInterval) clearInterval(usbTunnelInterval);
if (usbActive) closeUsbTunnel(usbPorts, { device: usbSerial });
// Only remove the auto temp path β keep an explicit --qr-output artifact.
if (cleanupQrOnExit) {
try {
unlinkSync(qrOutputPath);
} catch {
// best-effort cleanup of temp PNG
}
}
sidecar?.stop();
userServer.stop(true);
process.exit(0);
};
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
// Keep the process alive β the static server + sidecar hold the loop.
// Block on a never-resolving promise so the foreground stays on the
// dev process until SIGINT/SIGTERM fires.
await new Promise<void>(() => {});
}
|