@crossberryweb/mozhi 3.7.1 → 3.10.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/lib/appman.js ADDED
@@ -0,0 +1,641 @@
1
+ 'use strict';
2
+ /*
3
+ * Mozhi app platform — `mz app new|check|build|install|list|open|home|uninstall`.
4
+ *
5
+ * An "app" is a Mozhi project (mozhi.toml + entry .mz) with an [app]
6
+ * identity section: reverse-DNS id, launcher icon, window kind. The
7
+ * lifecycle mirrors Android's:
8
+ *
9
+ * .mz sources -- mz app build --> <name>-<version>.pkg -- install --> ~/.mozhi/apps/<id>/
10
+ * launcher (mz app home) -- open --> full app window
11
+ *
12
+ * The .pkg is a plain zip (npm/lib/zip.js) containing mozhi.toml, the
13
+ * bundled entry (produced by `mozhi build`), views/, public/, the icon and
14
+ * a SHA-256 manifest. It is Mozhi's app format — not an Android APK.
15
+ *
16
+ * Honesty notes:
17
+ * - today the full window is a browser window (kind = "web"); the same
18
+ * .pkg format is what the future NoxOS v0.4 native launcher will
19
+ * install and open on-device;
20
+ * - nothing here pretends to be Android or to run on Android.
21
+ */
22
+
23
+ const fs = require('fs');
24
+ const os = require('os');
25
+ const path = require('path');
26
+ const net = require('net');
27
+ const crypto = require('crypto');
28
+ const { spawn, spawnSync } = require('child_process');
29
+ const zip = require('./zip');
30
+ const pkgman = require('./pkgman');
31
+
32
+ const APP_ORIGIN_FILE = '.mozhi-app.json';
33
+ const DEFAULT_PORT = 8431;
34
+
35
+ /* ------------------------------------------------------------------ */
36
+ /* manifest */
37
+ /* ------------------------------------------------------------------ */
38
+
39
+ /* Lenient app-manifest reader: any `key = value` line wins for its key
40
+ * regardless of section headers; values may be quoted or bare. Mirrors
41
+ * the spirit of pkgman.parseManifest but tolerates unquoted numbers
42
+ * (server.port must be a bare int for `mozhi dev`). */
43
+ function parseAppFields(text) {
44
+ const fields = {};
45
+ for (const rawLine of String(text).split(/\r?\n/)) {
46
+ let stripped = '';
47
+ let inQuote = false;
48
+ for (const ch of rawLine) {
49
+ if (ch === '"') inQuote = !inQuote;
50
+ if (ch === '#' && !inQuote) break;
51
+ stripped += ch;
52
+ }
53
+ const line = stripped.trim();
54
+ if (!line || line.startsWith('[')) continue;
55
+ const eq = line.indexOf('=');
56
+ if (eq < 1) continue;
57
+ const key = line.slice(0, eq).trim();
58
+ let value = line.slice(eq + 1).trim();
59
+ if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) {
60
+ value = value.slice(1, -1);
61
+ } else if (value.length >= 2 && value.startsWith("'") && value.endsWith("'")) {
62
+ value = value.slice(1, -1);
63
+ }
64
+ if (!(key in fields)) fields[key] = value;
65
+ }
66
+ return fields;
67
+ }
68
+
69
+ const ID_RE = /^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+$/;
70
+ const VERSION_RE = /^\d+\.\d+\.\d+$/;
71
+
72
+ function isPng(buf) {
73
+ return Buffer.isBuffer(buf) && buf.length > 8 &&
74
+ buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47;
75
+ }
76
+
77
+ function appsRoot(global_ = true) {
78
+ if (global_) return path.join(os.homedir(), '.mozhi', 'apps');
79
+ return path.join(process.cwd(), '.mozhi', 'apps');
80
+ }
81
+
82
+ function findManifestFile(dir) {
83
+ for (const m of pkgman.MANIFESTS) {
84
+ const p = path.join(dir, m);
85
+ if (fs.existsSync(p)) return p;
86
+ }
87
+ return null;
88
+ }
89
+
90
+ /* Load + validate an app directory. Throws with a clear message on any
91
+ * structural problem. Returns { dir, manifestFile, text, fields, entry,
92
+ * entryPath, iconRel, iconPath }. */
93
+ function loadAppDir(dir) {
94
+ const abs = path.resolve(dir);
95
+ const manifestFile = findManifestFile(abs);
96
+ if (!manifestFile) {
97
+ throw new Error('not an app directory (no ' + pkgman.MANIFESTS.join(' or ') + '): ' + abs);
98
+ }
99
+ const text = fs.readFileSync(manifestFile, 'utf8');
100
+ const fields = parseAppFields(text);
101
+
102
+ if (!fields.id) throw new Error(manifestFile + ': [app] section needs an `id` (reverse-DNS, e.g. in.crossberry.counter)');
103
+ if (!ID_RE.test(fields.id)) {
104
+ throw new Error(manifestFile + ': bad app id "' + fields.id + '" — want lowercase reverse-DNS like in.crossberry.counter');
105
+ }
106
+ if (!fields.name) throw new Error(manifestFile + ': [project] needs a `name`');
107
+ if (fields.version && !VERSION_RE.test(fields.version)) {
108
+ throw new Error(manifestFile + ': bad version "' + fields.version + '" — want x.y.z');
109
+ }
110
+ const entry = fields.entry || 'main.mz';
111
+ const entryPath = path.join(abs, entry);
112
+ if (!fs.existsSync(entryPath)) {
113
+ throw new Error(manifestFile + ': entry "' + entry + '" not found in ' + abs);
114
+ }
115
+ const iconRel = fields.icon || 'public/icon.png';
116
+ const iconPath = path.join(abs, iconRel);
117
+ if (!fs.existsSync(iconPath)) {
118
+ throw new Error(manifestFile + ': launcher icon "' + iconRel + '" not found in ' + abs);
119
+ }
120
+ if (!isPng(fs.readFileSync(iconPath))) {
121
+ throw new Error(manifestFile + ': launcher icon "' + iconRel + '" is not a PNG');
122
+ }
123
+ const kind = (fields.kind || 'web').toLowerCase();
124
+ if (!['web', 'terminal'].includes(kind)) {
125
+ throw new Error(manifestFile + ': [app] kind must be "web" or "terminal" (got "' + kind + '")');
126
+ }
127
+ const mode = (fields.window || 'full').toLowerCase();
128
+ if (!['full', 'windowed'].includes(mode)) {
129
+ throw new Error(manifestFile + ': [app] window must be "full" or "windowed" (got "' + mode + '")');
130
+ }
131
+ return {
132
+ dir: abs,
133
+ manifestFile: path.basename(manifestFile),
134
+ text,
135
+ fields,
136
+ entry,
137
+ entryPath,
138
+ iconRel,
139
+ iconPath,
140
+ kind,
141
+ mode,
142
+ label: fields.label || fields.name,
143
+ version: fields.version || '0.0.0',
144
+ port: parseInt(fields.port, 10) || DEFAULT_PORT,
145
+ };
146
+ }
147
+
148
+ /* Same validation over an in-memory file map (zip contents). */
149
+ function validateAppFiles(files) {
150
+ const prefix = pkgman.findManifestPrefix(files);
151
+ let text = null;
152
+ let manifestFile = null;
153
+ for (const m of pkgman.MANIFESTS) {
154
+ const f = files.get(prefix + m);
155
+ if (f !== undefined) { text = f.toString('utf8'); manifestFile = m; break; }
156
+ }
157
+ if (text === null) {
158
+ throw new Error('invalid .pkg: no ' + pkgman.MANIFESTS.join('/') + ' found');
159
+ }
160
+ const fields = parseAppFields(text);
161
+ if (!fields.id || !ID_RE.test(fields.id)) {
162
+ throw new Error('invalid .pkg: [app] id missing or not reverse-DNS');
163
+ }
164
+ if (!fields.name) throw new Error('invalid .pkg: [project] name missing');
165
+ const entry = fields.entry || 'main.mz';
166
+ if (!files.has(prefix + entry)) {
167
+ throw new Error('invalid .pkg: entry "' + entry + '" missing');
168
+ }
169
+ const iconRel = fields.icon || 'public/icon.png';
170
+ if (!isPng(files.get(prefix + iconRel))) {
171
+ throw new Error('invalid .pkg: launcher icon "' + iconRel + '" missing or not a PNG');
172
+ }
173
+ /* verify the SHA-256 manifest if present */
174
+ const manifestTxt = files.get(prefix + 'MANIFEST.txt');
175
+ if (manifestTxt !== undefined) {
176
+ for (const line of manifestTxt.toString('utf8').split('\n')) {
177
+ const m = /^([0-9a-f]{64}) (.+)$/.exec(line.trim());
178
+ if (!m) continue;
179
+ const member = files.get(prefix + m[2]);
180
+ if (!member) throw new Error('corrupt .pkg: MANIFEST lists missing file ' + m[2]);
181
+ if (sha256(member) !== m[1]) {
182
+ throw new Error('corrupt .pkg: checksum mismatch for ' + m[2]);
183
+ }
184
+ }
185
+ }
186
+ return { prefix, manifestFile, fields, entry, iconRel, label: fields.label || fields.name,
187
+ version: fields.version || '0.0.0', kind: (fields.kind || 'web').toLowerCase(),
188
+ mode: (fields.window || 'full').toLowerCase(), port: parseInt(fields.port, 10) || DEFAULT_PORT };
189
+ }
190
+
191
+ function sha256(buf) {
192
+ return crypto.createHash('sha256').update(buf).digest('hex');
193
+ }
194
+
195
+ /* ------------------------------------------------------------------ */
196
+ /* scaffold: mz app new */
197
+ /* ------------------------------------------------------------------ */
198
+
199
+ function fillTemplate(text, vars) {
200
+ return text
201
+ .replace(/{{name}}/g, vars.name)
202
+ .replace(/{{id}}/g, vars.id)
203
+ .replace(/{{label}}/g, vars.label)
204
+ .replace(/{{port}}/g, String(vars.port));
205
+ }
206
+
207
+ function scaffoldApp(name, dir, opts = {}) {
208
+ if (!/^[a-z][a-z0-9_-]*$/i.test(name)) {
209
+ throw new Error('invalid app name "' + name + '" — use letters, digits, - and _ (starting with a letter)');
210
+ }
211
+ const root = path.resolve(dir || name);
212
+ if (fs.existsSync(root)) {
213
+ throw new Error('target directory already exists: ' + root);
214
+ }
215
+ const vars = {
216
+ name,
217
+ id: opts.id || 'app.' + name.toLowerCase().replace(/[^a-z0-9_]/g, '_'),
218
+ label: opts.label || name.charAt(0).toUpperCase() + name.slice(1),
219
+ port: opts.port || DEFAULT_PORT,
220
+ };
221
+ if (!ID_RE.test(vars.id)) {
222
+ throw new Error('invalid app id "' + vars.id + '" — want lowercase reverse-DNS like in.crossberry.counter');
223
+ }
224
+
225
+ const templateDir = path.join(__dirname, 'app-template');
226
+ let count = 0;
227
+ const walk = (rel) => {
228
+ for (const item of fs.readdirSync(path.join(templateDir, rel), { withFileTypes: true })) {
229
+ const relPath = path.join(rel, item.name);
230
+ if (item.isDirectory()) {
231
+ fs.mkdirSync(path.join(root, relPath), { recursive: true });
232
+ walk(relPath);
233
+ continue;
234
+ }
235
+ const src = path.join(templateDir, relPath);
236
+ const dst = path.join(root, relPath);
237
+ if (item.name.endsWith('.png')) {
238
+ fs.copyFileSync(src, dst); // binary asset: copy as-is
239
+ } else {
240
+ fs.writeFileSync(dst, fillTemplate(fs.readFileSync(src, 'utf8'), vars));
241
+ }
242
+ count++;
243
+ }
244
+ };
245
+ fs.mkdirSync(root, { recursive: true });
246
+ walk('');
247
+ return { root, vars, files: count };
248
+ }
249
+
250
+ /* ------------------------------------------------------------------ */
251
+ /* build: mz app build -> dist/<name>-<version>.pkg */
252
+ /* ------------------------------------------------------------------ */
253
+
254
+ function findInterpreterBinary() {
255
+ if (process.env.MOZHI_BIN) return process.env.MOZHI_BIN;
256
+ const fromPath = spawnSync('sh', ['-c', 'command -v mozhi || command -v mz'], { encoding: 'utf8' });
257
+ if (fromPath.status === 0 && fromPath.stdout.trim()) return fromPath.stdout.trim();
258
+ const arch = process.arch === 'x64' ? 'x86_64' : process.arch;
259
+ const bundled = path.join(__dirname, '..', 'bin', 'mozhi-' + process.platform + '-' + arch);
260
+ if (fs.existsSync(bundled)) return bundled;
261
+ return null;
262
+ }
263
+
264
+ function collectStaticFiles(app, files, rel) {
265
+ const absDir = path.join(app.dir, rel);
266
+ if (!fs.existsSync(absDir)) return;
267
+ for (const item of fs.readdirSync(absDir, { withFileTypes: true })) {
268
+ const relPath = rel ? rel + '/' + item.name : item.name;
269
+ if (item.isDirectory()) {
270
+ collectStaticFiles(app, files, relPath);
271
+ } else {
272
+ files.set(relPath, fs.readFileSync(path.join(app.dir, relPath)));
273
+ }
274
+ }
275
+ }
276
+
277
+ /* Everything an installed app needs at runtime: the UI surfaces
278
+ * (views/, public/), app modules (src/, lib/) and the launcher icon. */
279
+ function collectAppFiles(app, files) {
280
+ for (const dir of ['views', 'public', 'src', 'lib']) {
281
+ collectStaticFiles(app, files, dir);
282
+ }
283
+ }
284
+
285
+ function buildApp(dir) {
286
+ const app = loadAppDir(dir);
287
+ const bin = findInterpreterBinary();
288
+ if (!bin) {
289
+ throw new Error('mozhi interpreter not found (set MOZHI_BIN or install @crossberryweb/mozhi) — `mz app build` verifies with `mozhi build`');
290
+ }
291
+ /* 1. verify the project via the interpreter's own build (parses the
292
+ * entry and resolves every import; also writes its own dist/ bundle
293
+ * which we intentionally do NOT ship — the .pkg keeps the original
294
+ * multi-file layout so module imports stay intact). */
295
+ const r = spawnSync(bin, ['build', '--release'], { cwd: app.dir, encoding: 'utf8' });
296
+ if (r.status !== 0) {
297
+ const detail = (r.stderr || r.stdout || '').trim();
298
+ throw new Error('app verification failed (mozhi build):\n' + detail);
299
+ }
300
+
301
+ /* 2. assemble the .pkg zip from the original sources */
302
+ const distDir = path.join(app.dir, 'dist');
303
+ fs.mkdirSync(distDir, { recursive: true });
304
+ const files = new Map();
305
+ files.set(app.manifestFile, fs.readFileSync(path.join(app.dir, app.manifestFile)));
306
+ files.set(app.entry, fs.readFileSync(app.entryPath));
307
+ collectAppFiles(app, files);
308
+ files.set(app.iconRel, fs.readFileSync(app.iconPath));
309
+
310
+ const lines = [
311
+ '# ' + app.label + ' ' + app.version + ' — Mozhi app package manifest',
312
+ '# id: ' + app.fields.id,
313
+ '# format: <sha256> <path>',
314
+ ];
315
+ for (const name of Array.from(files.keys()).sort()) {
316
+ lines.push(sha256(files.get(name)) + ' ' + name);
317
+ }
318
+ files.set('MANIFEST.txt', Buffer.from(lines.join('\n') + '\n'));
319
+
320
+ const outName = (app.fields.name || path.basename(app.dir)) + '-' + app.version + '.pkg';
321
+ const outPath = path.join(distDir, outName);
322
+ const buf = zip.writeZip(files);
323
+ fs.writeFileSync(outPath, buf);
324
+ return { out: outPath, name: (app.fields.name || path.basename(app.dir)), label: app.label, id: app.fields.id,
325
+ version: app.version, count: files.size, sha256: sha256(buf), bytes: buf.length };
326
+ }
327
+
328
+ /* ------------------------------------------------------------------ */
329
+ /* install / list / uninstall */
330
+ /* ------------------------------------------------------------------ */
331
+
332
+ function writeInstalled(files, prefix, meta, dest) {
333
+ fs.mkdirSync(dest, { recursive: true });
334
+ for (const [name, data] of files) {
335
+ if (!name.startsWith(prefix)) continue;
336
+ const rel = name.slice(prefix.length);
337
+ if (!rel) continue;
338
+ const dst = path.join(dest, rel);
339
+ fs.mkdirSync(path.dirname(dst), { recursive: true });
340
+ fs.writeFileSync(dst, data);
341
+ }
342
+ fs.writeFileSync(path.join(dest, APP_ORIGIN_FILE), JSON.stringify(meta, null, 2) + '\n');
343
+ }
344
+
345
+ function installApp(target, opts = {}) {
346
+ const dest_root = appsRoot(opts.local !== undefined ? !opts.local : true);
347
+ const abs = path.resolve(target);
348
+ let files, metaSource;
349
+ if (fs.existsSync(abs) && fs.statSync(abs).isDirectory()) {
350
+ /* install straight from an app directory (dev shortcut) */
351
+ const app = loadAppDir(abs);
352
+ files = new Map();
353
+ files.set(app.manifestFile, fs.readFileSync(path.join(app.dir, app.manifestFile)));
354
+ files.set(app.entry, fs.readFileSync(app.entryPath));
355
+ collectAppFiles(app, files);
356
+ files.set(app.iconRel, fs.readFileSync(app.iconPath));
357
+ const lines = ['# ' + app.label + ' ' + app.version + ' — Mozhi app package manifest', '# id: ' + app.fields.id, '# format: <sha256> <path>'];
358
+ for (const name of Array.from(files.keys()).sort()) lines.push(sha256(files.get(name)) + ' ' + name);
359
+ files.set('MANIFEST.txt', Buffer.from(lines.join('\n') + '\n'));
360
+ metaSource = 'directory ' + abs;
361
+ } else if (fs.existsSync(abs)) {
362
+ const raw = fs.readFileSync(abs);
363
+ let pkgFiles;
364
+ try {
365
+ pkgFiles = zip.readZip(raw);
366
+ } catch (e) {
367
+ throw new Error('not a readable .pkg zip: ' + abs + ' (' + e.message + ')');
368
+ }
369
+ /* normalize through validation (also handles a single top-level dir) */
370
+ const v = validateAppFiles(pkgFiles);
371
+ files = new Map();
372
+ for (const [name, data] of pkgFiles) files.set(name.startsWith(v.prefix) ? name.slice(v.prefix.length) : name, data);
373
+ metaSource = 'package ' + abs;
374
+ } else {
375
+ throw new Error('no such .pkg or app directory: ' + abs);
376
+ }
377
+
378
+ const v = validateAppFiles(new Map(Array.from(files).map(([k, val]) => [k, val])));
379
+ const dest = path.join(dest_root, v.fields.id);
380
+ const meta = {
381
+ id: v.fields.id,
382
+ label: v.label,
383
+ version: v.version,
384
+ kind: v.kind,
385
+ window: v.mode,
386
+ source: metaSource,
387
+ installedAt: new Date().toISOString(),
388
+ };
389
+ writeInstalled(files, '', meta, dest);
390
+ return { dest, meta, root: dest_root };
391
+ }
392
+
393
+ function readInstalledDir(dir) {
394
+ const mf = findManifestFile(dir);
395
+ if (!mf) return null;
396
+ const fields = parseAppFields(fs.readFileSync(mf, 'utf8'));
397
+ if (!fields.id) return null;
398
+ let meta = null;
399
+ const origin = path.join(dir, APP_ORIGIN_FILE);
400
+ if (fs.existsSync(origin)) {
401
+ try { meta = JSON.parse(fs.readFileSync(origin, 'utf8')); } catch { meta = null; }
402
+ }
403
+ return {
404
+ id: fields.id,
405
+ label: fields.label || fields.name,
406
+ version: fields.version || '0.0.0',
407
+ kind: (fields.kind || 'web').toLowerCase(),
408
+ window: (fields.window || 'full').toLowerCase(),
409
+ path: dir,
410
+ installedAt: meta ? meta.installedAt : null,
411
+ source: meta ? meta.source : null,
412
+ };
413
+ }
414
+
415
+ function listApps(opts = {}) {
416
+ const roots = [];
417
+ if (opts.local) {
418
+ roots.push(appsRoot(false));
419
+ } else {
420
+ roots.push(appsRoot(true));
421
+ roots.push(appsRoot(false));
422
+ }
423
+ const seen = new Set();
424
+ const rows = [];
425
+ for (const root of roots) {
426
+ if (!fs.existsSync(root)) continue;
427
+ for (const item of fs.readdirSync(root, { withFileTypes: true })) {
428
+ if (!item.isDirectory() || seen.has(item.name)) continue;
429
+ const info = readInstalledDir(path.join(root, item.name));
430
+ if (info) { seen.add(item.name); rows.push(info); }
431
+ }
432
+ }
433
+ rows.sort((a, b) => a.id.localeCompare(b.id));
434
+ return rows;
435
+ }
436
+
437
+ function resolveApp(idOrDir, opts = {}) {
438
+ const abs = path.resolve(idOrDir);
439
+ if (fs.existsSync(abs) && findManifestFile(abs)) {
440
+ return { appDir: abs, info: readInstalledDir(abs) };
441
+ }
442
+ for (const root of [appsRoot(true), appsRoot(false)]) {
443
+ const candidate = path.join(root, idOrDir);
444
+ if (fs.existsSync(candidate) && findManifestFile(candidate)) {
445
+ return { appDir: candidate, info: readInstalledDir(candidate) };
446
+ }
447
+ }
448
+ throw new Error('app not installed: ' + idOrDir + ' — install it first with `mz app install` (see `mz app list`)');
449
+ }
450
+
451
+ function uninstallApp(id, opts = {}) {
452
+ const root = opts.local ? appsRoot(false) : appsRoot(true);
453
+ const dest = path.join(root, id);
454
+ if (!fs.existsSync(dest)) {
455
+ throw new Error('not installed: ' + id + ' (looked in ' + root + ')');
456
+ }
457
+ if (!ID_RE.test(id)) throw new Error('refusing to remove: "' + id + '" is not a valid app id');
458
+ fs.rmSync(dest, { recursive: true, force: true });
459
+ return dest;
460
+ }
461
+
462
+ /* ------------------------------------------------------------------ */
463
+ /* open: launch the app in its full window */
464
+ /* ------------------------------------------------------------------ */
465
+
466
+ function waitPort(port, timeoutMs) {
467
+ const deadline = Date.now() + timeoutMs;
468
+ return new Promise((resolve, reject) => {
469
+ const attempt = () => {
470
+ const sock = net.connect({ port, host: '127.0.0.1' });
471
+ sock.once('connect', () => { sock.destroy(); resolve(true); });
472
+ sock.once('error', () => {
473
+ sock.destroy();
474
+ if (Date.now() > deadline) reject(new Error('app did not start listening on 127.0.0.1:' + port + ' within ' + (timeoutMs / 1000) + 's'));
475
+ else setTimeout(attempt, 250);
476
+ });
477
+ };
478
+ attempt();
479
+ });
480
+ }
481
+
482
+ function openBrowser(url) {
483
+ const plat = process.platform;
484
+ try {
485
+ if (plat === 'darwin') {
486
+ spawnSync('open', [url], { stdio: 'ignore' });
487
+ return true;
488
+ }
489
+ if (plat === 'win32') {
490
+ spawnSync('cmd', ['/c', 'start', '', url], { stdio: 'ignore' });
491
+ return true;
492
+ }
493
+ const r = spawnSync('xdg-open', [url], { stdio: 'ignore' });
494
+ return r.status === 0;
495
+ } catch {
496
+ return false;
497
+ }
498
+ }
499
+
500
+ /* Runs the app in the foreground. Resolves with the exit code when the
501
+ * app process exits. kind=web waits for the port, then opens the window. */
502
+ async function openApp(idOrDir, opts = {}) {
503
+ const { appDir, info } = resolveApp(idOrDir, opts);
504
+ const app = loadAppDir(appDir);
505
+ const bin = findInterpreterBinary();
506
+ if (!bin) {
507
+ throw new Error('mozhi interpreter not found (set MOZHI_BIN or install @crossberryweb/mozhi)');
508
+ }
509
+ const url = 'http://127.0.0.1:' + app.port + '/';
510
+ let child;
511
+ if (app.kind === 'web') {
512
+ child = spawn(bin, ['run', app.entry], { cwd: appDir, stdio: 'inherit' });
513
+ process.stdout.write('starting ' + app.label + ' (' + app.fields.id + ') ...\n');
514
+ try {
515
+ await waitPort(app.port, 15000);
516
+ } catch (e) {
517
+ child.kill('SIGTERM');
518
+ throw e;
519
+ }
520
+ if (opts.noOpen) {
521
+ process.stdout.write('app window ready (full): ' + url + '\n');
522
+ process.stdout.write('serving in the foreground — press Ctrl+C to stop\n');
523
+ } else {
524
+ const opened = openBrowser(url);
525
+ if (opened) {
526
+ process.stdout.write('opened full app window: ' + url + '\n');
527
+ } else {
528
+ process.stdout.write('could not open a browser automatically — full app window at: ' + url + '\n');
529
+ }
530
+ }
531
+ } else {
532
+ child = spawn(bin, ['run', app.entry], { cwd: appDir, stdio: 'inherit' });
533
+ }
534
+ return await new Promise((resolve) => {
535
+ child.on('exit', (code) => resolve(code === null ? 0 : code));
536
+ child.on('error', () => resolve(1));
537
+ });
538
+ }
539
+
540
+ /* ------------------------------------------------------------------ */
541
+ /* home: the launcher home screen */
542
+ /* ------------------------------------------------------------------ */
543
+
544
+ const HOME_COLORS = [45, 61, 90, 97, 130, 166, 202, 213]; // ANSI 256-color codes
545
+
546
+ function colorFor(id) {
547
+ let h = 0;
548
+ for (const ch of String(id)) h = (h * 31 + ch.charCodeAt(0)) >>> 0;
549
+ return HOME_COLORS[h % HOME_COLORS.length];
550
+ }
551
+
552
+ function monogram(label) {
553
+ const word = String(label || '?').trim();
554
+ return word.charAt(0).toUpperCase();
555
+ }
556
+
557
+ function homeScreen(rows) {
558
+ const out = [];
559
+ out.push('');
560
+ out.push(' Mozhi Home apps: ' + rows.length);
561
+ out.push(' ─────────────────────────────────────────────');
562
+ if (!rows.length) {
563
+ out.push(' no apps installed — create one with:');
564
+ out.push(' mz app new my-app');
565
+ out.push(' mz app install <my-app>.pkg (or an app directory)');
566
+ out.push('');
567
+ return out.join('\n');
568
+ }
569
+ const COLS = 3;
570
+ const W = 24;
571
+ for (let i = 0; i < rows.length; i += COLS) {
572
+ const chunk = rows.slice(i, i + COLS);
573
+ const cells = chunk.map((r, j) => {
574
+ const n = i + j + 1;
575
+ const c = colorFor(r.id);
576
+ return '\u001b[38;5;16m\u001b[48;5;' + c + 'm ' +
577
+ '\u001b[1m ' + monogram(r.label) + ' \u001b[22m' +
578
+ ' '.repeat(Math.max(0, W - 8)) + '\u001b[0m';
579
+ });
580
+ out.push(' ' + cells.map((s) => padEnd(s, W + 20)).join(''));
581
+ out.push(' ' + chunk.map((r, j) => padEnd(' ' + trunc(r.label, W - 4) + ' ', W)).join(''));
582
+ out.push(' ' + chunk.map((r) => padEnd(' v' + r.version + ' · ' + r.kind, W)).join(''));
583
+ out.push('');
584
+ }
585
+ out.push(' ─────────────────────────────────────────────');
586
+ rows.forEach((r, j) => {
587
+ out.push(' ' + (j + 1) + ') ' + padEnd(trunc(r.label, 22), 24) + padEnd(trunc(r.id, 34), 36) + r.path);
588
+ });
589
+ out.push('');
590
+ return out.join('\n');
591
+ }
592
+
593
+ function padEnd(s, n) {
594
+ s = String(s == null ? '' : s);
595
+ /* strip ANSI escapes for width purposes */
596
+ const plain = s.replace(/\u001b\[[0-9;]*m/g, '');
597
+ return plain.length >= n ? s : s + ' '.repeat(n - plain.length);
598
+ }
599
+
600
+ function trunc(s, n) {
601
+ s = String(s == null ? '' : s);
602
+ return s.length > n ? s.slice(0, n - 1) + '…' : s;
603
+ }
604
+
605
+ /* Interactive launcher: prints the home screen and, on a TTY, waits for
606
+ * a number to open that app in its full window. Returns exit code. */
607
+ async function home(opts = {}) {
608
+ const render = () => homeScreen(listApps(opts));
609
+ process.stdout.write(render());
610
+ if (opts.noPrompt || !process.stdin.isTTY) return 0;
611
+ const rows = () => listApps(opts);
612
+ while (true) {
613
+ const answer = await new Promise((resolve) => {
614
+ process.stdout.write('type a number to open the app in its full window · r refresh · q quit\n> ');
615
+ process.stdin.resume();
616
+ process.stdin.setEncoding('utf8');
617
+ process.stdin.once('data', (d) => {
618
+ process.stdin.pause();
619
+ resolve(String(d).trim());
620
+ });
621
+ });
622
+ if (answer === 'q' || answer === 'quit' || answer === '') return 0;
623
+ if (answer === 'r' || answer === 'refresh') { process.stdout.write(render()); continue; }
624
+ const n = parseInt(answer, 10);
625
+ const list = rows();
626
+ if (!n || n < 1 || n > list.length) {
627
+ process.stdout.write('no app number ' + answer + ' — try again\n');
628
+ continue;
629
+ }
630
+ const code = await openApp(list[n - 1].id, opts);
631
+ process.stdout.write('app closed (exit ' + code + ')\n');
632
+ process.stdout.write(render());
633
+ }
634
+ }
635
+
636
+ module.exports = {
637
+ appsRoot, parseAppFields, loadAppDir, validateAppFiles, scaffoldApp,
638
+ checkAppDir: loadAppDir, buildApp, installApp, listApps, resolveApp,
639
+ uninstallApp, openApp, home, homeScreen, findInterpreterBinary,
640
+ APP_ORIGIN_FILE, DEFAULT_PORT,
641
+ };