@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.
@@ -0,0 +1,142 @@
1
+ // `glassly permission <action>` subcommand handlers.
2
+ //
3
+ // Object-verb surface for the most common manifest edit. Both interactive
4
+ // (no type arg → clack prompts) and non-interactive (type arg given) flows.
5
+ // Shares mutation backend with the wizard via manifest-mutate.ts.
6
+
7
+ import * as p from "@clack/prompts"
8
+ import {ALLOWED_PERMISSIONS} from "./manifest.js"
9
+ import {
10
+ addPermission,
11
+ listPermissions,
12
+ MutateError,
13
+ removePermission,
14
+ type Manifest,
15
+ } from "./manifest-mutate.js"
16
+ import {formatLoadError, formatWriteError, loadManifest, writeManifest} from "./manifest-format.js"
17
+ import {permissionDescription} from "./permission-hints.js"
18
+
19
+ function loadOrExit(): {path: string; manifest: Manifest} {
20
+ const r = loadManifest(process.cwd())
21
+ if (!r.ok) {
22
+ console.error(formatLoadError(r.error))
23
+ process.exit(1)
24
+ }
25
+ return {path: r.value.path, manifest: r.value.manifest}
26
+ }
27
+
28
+ function persistOrExit(path: string, manifest: Manifest): void {
29
+ const w = writeManifest(path, manifest)
30
+ if (!w.ok) {
31
+ console.error(formatWriteError(w.error))
32
+ process.exit(1)
33
+ }
34
+ }
35
+
36
+ function printPermissions(manifest: Manifest): void {
37
+ const perms = listPermissions(manifest)
38
+ if (perms.length === 0) {
39
+ console.log("Permissions: none declared.")
40
+ return
41
+ }
42
+ console.log(`Permissions (${perms.length}):`)
43
+ for (const perm of perms) {
44
+ const desc = perm.description ? ` — ${perm.description}` : ""
45
+ const req = perm.required === false ? " [optional]" : ""
46
+ console.log(` • ${perm.type}${req}${desc}`)
47
+ }
48
+ }
49
+
50
+ export async function listPermissionsCmd(): Promise<void> {
51
+ const {manifest} = loadOrExit()
52
+ printPermissions(manifest)
53
+ }
54
+
55
+ export async function addPermissionCmd(typeArg?: string): Promise<void> {
56
+ const {path, manifest} = loadOrExit()
57
+ let type = typeArg
58
+ let description: string | undefined
59
+
60
+ if (!type) {
61
+ p.intro("Add a permission")
62
+ const declared = new Set(listPermissions(manifest).map((perm) => perm.type))
63
+ const available = ALLOWED_PERMISSIONS.filter((perm) => !declared.has(perm))
64
+ if (available.length === 0) {
65
+ p.note("All permissions are already declared. Nothing to add.", "Permissions")
66
+ p.outro("Done")
67
+ return
68
+ }
69
+ const picked = await p.select({
70
+ message: "Which permission?",
71
+ options: available.map((perm) => ({value: perm, label: perm, hint: permissionDescription(perm)})),
72
+ })
73
+ if (p.isCancel(picked)) {
74
+ p.cancel("Cancelled.")
75
+ return
76
+ }
77
+ type = picked as string
78
+ const desc = await p.text({
79
+ message: "Optional description (shown to the user when the OS prompts for permission):",
80
+ placeholder: "(skip)",
81
+ })
82
+ if (p.isCancel(desc)) {
83
+ p.cancel("Cancelled.")
84
+ return
85
+ }
86
+ if (typeof desc === "string" && desc.trim()) description = desc.trim()
87
+ }
88
+
89
+ let updated: Manifest
90
+ try {
91
+ updated = addPermission(manifest, type!, description !== undefined ? {description} : undefined)
92
+ } catch (e) {
93
+ if (e instanceof MutateError) {
94
+ console.error(e.message)
95
+ process.exit(1)
96
+ }
97
+ throw e
98
+ }
99
+
100
+ persistOrExit(path, updated)
101
+ printPermissions(updated)
102
+ if (typeArg === undefined) {
103
+ p.outro("Saved miniapp.json ✨")
104
+ }
105
+ }
106
+
107
+ export async function removePermissionCmd(typeArg?: string): Promise<void> {
108
+ const {path, manifest} = loadOrExit()
109
+ let type = typeArg
110
+
111
+ if (!type) {
112
+ const declared = listPermissions(manifest)
113
+ if (declared.length === 0) {
114
+ console.log("No permissions declared. Nothing to remove.")
115
+ return
116
+ }
117
+ p.intro("Remove a permission")
118
+ const picked = await p.select({
119
+ message: "Which permission to remove?",
120
+ options: declared.map((perm) => ({value: perm.type, label: perm.type})),
121
+ })
122
+ if (p.isCancel(picked)) {
123
+ p.cancel("Cancelled.")
124
+ return
125
+ }
126
+ type = picked as string
127
+ }
128
+
129
+ let updated: Manifest
130
+ try {
131
+ updated = removePermission(manifest, type!)
132
+ } catch (e) {
133
+ if (e instanceof MutateError) {
134
+ console.error(e.message)
135
+ process.exit(1)
136
+ }
137
+ throw e
138
+ }
139
+
140
+ persistOrExit(path, updated)
141
+ printPermissions(updated)
142
+ }
package/src/qr.test.ts ADDED
@@ -0,0 +1,81 @@
1
+ import {afterEach, describe, expect, test} from 'bun:test';
2
+ import {chmodSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync} from 'fs';
3
+ import {tmpdir} from 'os';
4
+ import {join} from 'path';
5
+ import {writeQRPng} from './qr.js';
6
+
7
+ const tempDirs: string[] = [];
8
+
9
+ function makeTempDir(): string {
10
+ const dir = mkdtempSync(join(tmpdir(), 'glassly-qr-test-'));
11
+ tempDirs.push(dir);
12
+ return dir;
13
+ }
14
+
15
+ afterEach(() => {
16
+ for (const dir of tempDirs.splice(0)) {
17
+ try {
18
+ chmodSync(dir, 0o700);
19
+ rmSync(dir, {recursive: true, force: true});
20
+ } catch {
21
+ // best-effort cleanup
22
+ }
23
+ }
24
+ });
25
+
26
+ describe('writeQRPng', () => {
27
+ test('creates a file with mode 0o600 and non-empty PNG content', async () => {
28
+ const dir = makeTempDir();
29
+ const outPath = join(dir, 'qr.png');
30
+ await writeQRPng('miniapp://dev?url=http%3A%2F%2F192.168.1.1%3A3000', outPath);
31
+
32
+ const st = statSync(outPath);
33
+ expect(st.size).toBeGreaterThan(0);
34
+ // Mask off higher mode bits so comparison is portable across platforms.
35
+ expect(st.mode & 0o777).toBe(0o600);
36
+
37
+ const header = readFileSync(outPath).subarray(0, 8);
38
+ // PNG magic number
39
+ expect([...header]).toEqual([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
40
+ });
41
+
42
+ test('overwrites the same path in place on a second call', async () => {
43
+ const dir = makeTempDir();
44
+ const outPath = join(dir, 'qr.png');
45
+ await writeQRPng('miniapp://dev?url=http%3A%2F%2F192.168.1.1%3A3000', outPath);
46
+ const first = readFileSync(outPath);
47
+
48
+ await writeQRPng('miniapp://dev?url=http%3A%2F%2F10.0.0.1%3A3000', outPath);
49
+ const second = readFileSync(outPath);
50
+
51
+ expect(Buffer.compare(first, second)).not.toBe(0);
52
+ expect(statSync(outPath).isFile()).toBe(true);
53
+ });
54
+
55
+ test('forces mode 0o600 even when overwriting a looser-mode file', async () => {
56
+ const dir = makeTempDir();
57
+ const outPath = join(dir, 'qr.png');
58
+ writeFileSync(outPath, 'placeholder', {mode: 0o644});
59
+ chmodSync(outPath, 0o644);
60
+ expect(statSync(outPath).mode & 0o777).toBe(0o644);
61
+
62
+ await writeQRPng('miniapp://dev?url=http%3A%2F%2F192.168.1.1%3A3000', outPath);
63
+ expect(statSync(outPath).mode & 0o777).toBe(0o600);
64
+ });
65
+
66
+ test('returns false when the output directory is unwritable', async () => {
67
+ const dir = makeTempDir();
68
+ const readonlyDir = join(dir, 'readonly');
69
+ // Create a directory entry that exists as a file, so writing qr.png under it fails.
70
+ writeFileSync(readonlyDir, 'not-a-directory');
71
+ const outPath = join(readonlyDir, 'qr.png');
72
+
73
+ await expect(writeQRPng('miniapp://dev?test=1', outPath)).resolves.toBe(false);
74
+ });
75
+
76
+ test('returns true on success', async () => {
77
+ const dir = makeTempDir();
78
+ const outPath = join(dir, 'ok.png');
79
+ await expect(writeQRPng('miniapp://dev?test=1', outPath)).resolves.toBe(true);
80
+ });
81
+ });
package/src/qr.ts ADDED
@@ -0,0 +1,119 @@
1
+ import {chmodSync, writeFileSync} from 'fs';
2
+ import QRCode from 'qrcode';
3
+
4
+ export type QRSize = 'small' | 'medium' | 'large';
5
+
6
+ const BG_WHITE = '\x1b[47m';
7
+ const FG_BLACK = '\x1b[30m';
8
+ const RESET = '\x1b[0m';
9
+
10
+ // Sextant block characters indexed by a 6-bit pattern: bit 0 = upper-left,
11
+ // 1 = upper-right, 2 = middle-left, 3 = middle-right, 4 = lower-left,
12
+ // 5 = lower-right. A set bit is a dark module drawn as black foreground on
13
+ // white background. Unicode's Symbols for Legacy Computing sextant range
14
+ // (U+1FB00–U+1FB3B) omits empty, the two half blocks, and full — those come
15
+ // from Block Elements.
16
+ const SEXTANTS: string[] = Array.from({length: 64}, (_, v) => {
17
+ if (v === 0) return ' ';
18
+ if (v === 0b010101) return '▌';
19
+ if (v === 0b101010) return '▐';
20
+ if (v === 0b111111) return '█';
21
+ return String.fromCodePoint(0x1fb00 + v - 1 - (v > 0b010101 ? 1 : 0) - (v > 0b101010 ? 1 : 0));
22
+ });
23
+
24
+ /**
25
+ * Render 2x3 modules per character using sextant blocks — half the width and
26
+ * two-thirds the height of the half-block renderer. In a typical 1:2 terminal
27
+ * cell the modules come out only ~1.33x taller than wide (quadrants would be
28
+ * 2x). Perfectly square at this width needs Unicode 16 octants (2x4), which
29
+ * few terminal fonts render yet. Sextants are the most sensitive mode to
30
+ * missing font support — if the QR shows boxes or gaps, use medium/large.
31
+ */
32
+ function renderSextant(url: string): string {
33
+ const qr = QRCode.create(url, {errorCorrectionLevel: 'L'});
34
+ const size = qr.modules.size;
35
+ const data = qr.modules.data;
36
+ const margin = 1;
37
+ const padded = size + margin * 2;
38
+
39
+ const dark = (x: number, y: number): number => {
40
+ const mx = x - margin;
41
+ const my = y - margin;
42
+ if (mx < 0 || my < 0 || mx >= size || my >= size) return 0;
43
+ return data[my * size + mx] ? 1 : 0;
44
+ };
45
+
46
+ let output = '';
47
+ for (let y = 0; y < padded; y += 3) {
48
+ output += BG_WHITE + FG_BLACK;
49
+ for (let x = 0; x < padded; x += 2) {
50
+ let bits = 0;
51
+ for (let dy = 0; dy < 3; dy++) {
52
+ bits |= dark(x, y + dy) << (dy * 2);
53
+ bits |= dark(x + 1, y + dy) << (dy * 2 + 1);
54
+ }
55
+ output += SEXTANTS[bits];
56
+ }
57
+ output += RESET + '\n';
58
+ }
59
+ return output;
60
+ }
61
+
62
+ /**
63
+ * Print a scannable QR to the terminal at one of three sizes (`--qr`/`-q`):
64
+ *
65
+ * - `small` — sextant blocks, 2x3 modules per character (~20 columns for a
66
+ * dev URL). Densest, and the most dependent on the terminal font drawing
67
+ * Legacy Computing sextant glyphs flush.
68
+ * - `medium` (default) — half-block renderer, 1x2 modules per character
69
+ * (~40 columns). A line-height far from 1.0 inserts gaps between rows and
70
+ * can make small/medium unscannable.
71
+ * - `large` — each module is two spaces with forced ANSI black/white
72
+ * backgrounds (~80 columns). Survives any font or line-height.
73
+ *
74
+ * The plain URL is always printed alongside the QR as a last resort.
75
+ */
76
+ export async function printQR(url: string, opts: {size?: QRSize} = {}): Promise<void> {
77
+ const size = opts.size ?? 'medium';
78
+ try {
79
+ const str = size === 'small'
80
+ ? renderSextant(url)
81
+ : await QRCode.toString(url, {
82
+ type: 'terminal',
83
+ small: size === 'medium',
84
+ errorCorrectionLevel: 'L',
85
+ margin: 1,
86
+ });
87
+ process.stdout.write('\n' + str);
88
+ } catch (error) {
89
+ console.error(`Could not render terminal QR code: ${(error as Error).message}`);
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Write a PNG QR to disk with mode 0o600.
95
+ *
96
+ * Dev/release URLs can carry a signed attestation query param; writing with
97
+ * restrictive permissions avoids a world-readable window on multi-user machines.
98
+ * Failures only warn — a broken PNG write must not take down the server.
99
+ *
100
+ * @returns true if the file was written successfully
101
+ */
102
+ export async function writeQRPng(url: string, outPath: string): Promise<boolean> {
103
+ try {
104
+ const buffer = await QRCode.toBuffer(url, {
105
+ type: 'png',
106
+ errorCorrectionLevel: 'M',
107
+ margin: 2,
108
+ scale: 8,
109
+ });
110
+ // mode on writeFileSync only applies to newly created files — always chmod
111
+ // after write so overwrites of a looser-mode temp path stay private.
112
+ writeFileSync(outPath, buffer, {mode: 0o600});
113
+ chmodSync(outPath, 0o600);
114
+ return true;
115
+ } catch (error) {
116
+ console.warn(`Could not write QR PNG to ${outPath}: ${(error as Error).message}`);
117
+ return false;
118
+ }
119
+ }
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env bun
2
+ // Package build step: rewrite schema/miniapp.schema.json from the in-source
3
+ // allowed-value lists. `glassly schema regenerate` runs the same function.
4
+ import { regenerateSchemaFile } from './schema.js';
5
+
6
+ regenerateSchemaFile();
package/src/release.ts ADDED
@@ -0,0 +1,265 @@
1
+ /**
2
+ * `glassly release` — build a release and install it on a phone.
3
+ *
4
+ * Flow:
5
+ * 1. Detect package manager, run `<pm> run build` so the user's bundler
6
+ * produces dist/.
7
+ * 2. Validate manifest + pack dist/ → build/<pkg>-<v>.zip (uses pack()).
8
+ * 3. Spin up a tiny HTTP server on the LAN that serves the zip and
9
+ * manifest at fixed paths.
10
+ * 4. Print a QR with `miniapp://release?url=<lan-base>&...`.
11
+ * 5. Stay up (default persistent) so multiple devices can install. Print a
12
+ * ✓ line whenever a phone successfully fetches /bundle.zip.
13
+ *
14
+ * Phone-side: scanner branches on `miniapp://release`, downloads the
15
+ * zip via composer.installMiniApp(<base>/bundle.zip). The miniapp lands in
16
+ * lmas/<pkg>/<manifestVersion>/ and behaves like any installed local
17
+ * miniapp — runs offline, persists across restarts, no laptop required.
18
+ *
19
+ * Why "release" and not "install": `install` collides with package
20
+ * managers (`bun run install` is reserved). Naming the action after what
21
+ * the user is producing — a release build for their phone — avoids the
22
+ * collision and matches Android's `installRelease` mental model.
23
+ */
24
+
25
+ import {readFileSync, existsSync, statSync, readdirSync, unlinkSync} from 'fs'
26
+ import os from 'os'
27
+ import {resolve, join} from 'path'
28
+ import {buildProduction} from './build.js'
29
+ import {pack} from './pack.js'
30
+ import {printQR, writeQRPng, type QRSize} from './qr.js'
31
+ import {getLanIp} from './lan.js'
32
+ import {validateManifest} from './manifest.js'
33
+
34
+ const DEFAULT_PORT_START = 6789
35
+ const PORT_SCAN_LIMIT = 10
36
+ const HEALTH_PATH = '/__host_release/health'
37
+ const MANIFEST_PATH = '/miniapp.json'
38
+ const ICON_PATH = '/icon.png'
39
+ const BUNDLE_PATH = '/bundle.zip'
40
+
41
+ export interface ReleaseOptions {
42
+ /** Miniapp project root. Defaults to the current working directory. */
43
+ cwd?: string
44
+ noCache?: boolean
45
+ /** Terminal QR size (--qr/-q small|medium|large). Defaults to medium. */
46
+ qrSize?: QRSize
47
+ qrOutput?: string
48
+ }
49
+
50
+ export async function release(opts: ReleaseOptions = {}): Promise<void> {
51
+ const cwd = resolve(opts.cwd ?? process.cwd())
52
+
53
+ // ---- 1. Validate manifest + read identity ---------------------------
54
+ const manifestPath = resolve(cwd, 'miniapp.json')
55
+ if (!existsSync(manifestPath)) {
56
+ console.error('Error: miniapp.json not found in current directory')
57
+ process.exit(1)
58
+ }
59
+ let manifest: Record<string, unknown>
60
+ try {
61
+ manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'))
62
+ } catch {
63
+ console.error('Error: miniapp.json is not valid JSON')
64
+ process.exit(1)
65
+ }
66
+ const validation = validateManifest(manifest)
67
+ if (!validation.valid) {
68
+ console.error('miniapp.json validation failed:')
69
+ for (const err of validation.errors) console.error(` - ${err}`)
70
+ process.exit(1)
71
+ }
72
+
73
+ const packageName = manifest.packageName as string
74
+ const version = manifest.version as string
75
+ const name = (manifest.name as string) ?? packageName
76
+
77
+ // ---- 2. Build (or skip via cache) -----------------------------------
78
+ const cacheDir = resolve(cwd, 'build')
79
+ const cachedZipName = `${packageName}-${version}.zip`
80
+ const cachedZipPath = join(cacheDir, cachedZipName)
81
+
82
+ const cacheValid = !opts.noCache && isCacheFresh(cachedZipPath, cwd)
83
+ if (cacheValid) {
84
+ console.log(`✓ Using cached build (${cachedZipName})`)
85
+ } else {
86
+ await buildProduction(cwd)
87
+
88
+ // Pack into build/<pkg>-<v>.zip
89
+ const packStart = Date.now()
90
+ const zipPath = await pack({outDir: 'build', silent: true})
91
+ const sizeKb = Math.round(statSync(zipPath).size / 1024)
92
+ console.log(`✓ Packed ${packageName}@${version} (${sizeKb} KB) in ${((Date.now() - packStart) / 1000).toFixed(1)}s`)
93
+ }
94
+
95
+ // ---- 3. Find a free port and load the bundle into memory ------------
96
+ const zipBuffer = readFileSync(cachedZipPath)
97
+ const iconPath = resolve(cwd, 'icon.png')
98
+ const iconBuffer = existsSync(iconPath) ? readFileSync(iconPath) : null
99
+ const manifestBuffer = readFileSync(manifestPath)
100
+
101
+ const port = await pickPort(DEFAULT_PORT_START, PORT_SCAN_LIMIT)
102
+ const lanIp = getLanIp()
103
+ if (!lanIp) {
104
+ console.error('Error: could not detect LAN IP. Connect to a Wi-Fi network and re-run.')
105
+ process.exit(1)
106
+ }
107
+
108
+ const baseUrl = `http://${lanIp}:${port}`
109
+
110
+ let installCount = 0
111
+
112
+ // ---- 4. Serve --------------------------------------------------------
113
+ const server = Bun.serve({
114
+ hostname: '0.0.0.0',
115
+ port,
116
+ fetch(req) {
117
+ const url = new URL(req.url)
118
+ if (url.pathname === HEALTH_PATH) {
119
+ return new Response(JSON.stringify({ok: true}), {
120
+ headers: {'content-type': 'application/json'},
121
+ })
122
+ }
123
+ if (url.pathname === MANIFEST_PATH) {
124
+ return new Response(manifestBuffer, {
125
+ headers: {'content-type': 'application/json'},
126
+ })
127
+ }
128
+ if (url.pathname === ICON_PATH) {
129
+ if (!iconBuffer) return new Response('Not found', {status: 404})
130
+ return new Response(iconBuffer, {
131
+ headers: {'content-type': 'image/png'},
132
+ })
133
+ }
134
+ if (url.pathname === BUNDLE_PATH) {
135
+ installCount += 1
136
+ const remote = req.headers.get('x-forwarded-for') ?? 'unknown'
137
+ console.log(`✓ Install #${installCount} — ${name}@${version} → ${remote}`)
138
+ return new Response(zipBuffer, {
139
+ headers: {
140
+ 'content-type': 'application/zip',
141
+ 'content-length': String(zipBuffer.length),
142
+ },
143
+ })
144
+ }
145
+ return new Response('Not found', {status: 404})
146
+ },
147
+ })
148
+
149
+ // ---- 5. QR + banner --------------------------------------------------
150
+ const qrUrl = `miniapp://release?url=${encodeURIComponent(baseUrl)}&package=${encodeURIComponent(packageName)}&version=${encodeURIComponent(version)}&name=${encodeURIComponent(name)}`
151
+
152
+ console.log('\n╔══════════════════════════════════════════════════════════════╗')
153
+ console.log('║ Install your mini app on a phone: ║')
154
+ console.log('║ ║')
155
+ console.log('║ 1. Open the Glassly app ║')
156
+ console.log('║ 2. Settings → Developer settings ║')
157
+ console.log('║ 3. Under "Mini App Development", tap ║')
158
+ console.log('║ "Scan Mini App QR Code" and scan the QR below ║')
159
+ console.log('║ ║')
160
+ console.log('║ Phone must be on the same Wi-Fi as this computer. ║')
161
+ console.log('║ This server stays up — install on multiple phones, then ║')
162
+ console.log('║ Ctrl+C to stop. ║')
163
+ console.log('╚══════════════════════════════════════════════════════════════╝\n')
164
+
165
+ const defaultQrPath = join(os.tmpdir(), `glassly-release-qr-${packageName}.png`)
166
+ const qrOutputPath = resolve(opts.qrOutput ?? defaultQrPath)
167
+ const cleanupQrOnExit = !opts.qrOutput
168
+
169
+ await printQR(qrUrl, {size: opts.qrSize})
170
+ const wrotePng = await writeQRPng(qrUrl, qrOutputPath)
171
+ console.log(`\n${qrUrl}`)
172
+ if (wrotePng) {
173
+ console.log(`PNG QR: ${qrOutputPath}\n`)
174
+ } else {
175
+ console.log(`PNG QR: (not written — see warning above)\n`)
176
+ }
177
+ console.log(`Serving on ${baseUrl}`)
178
+
179
+ // ---- 6. Wait for SIGINT / SIGTERM -----------------------------------
180
+ await new Promise<void>((resolvePromise) => {
181
+ const shutdown = () => {
182
+ console.log('\nShutting down...')
183
+ // Only remove the auto temp path — keep an explicit --qr-output artifact.
184
+ if (cleanupQrOnExit) {
185
+ try {
186
+ unlinkSync(qrOutputPath)
187
+ } catch {
188
+ // best-effort cleanup of temp PNG
189
+ }
190
+ }
191
+ server.stop()
192
+ resolvePromise()
193
+ }
194
+ process.on('SIGINT', shutdown)
195
+ process.on('SIGTERM', shutdown)
196
+ })
197
+ }
198
+
199
+ // ---------------------------------------------------------------------------
200
+ // Helpers
201
+ // ---------------------------------------------------------------------------
202
+
203
+ async function pickPort(start: number, limit: number): Promise<number> {
204
+ for (let i = 0; i < limit; i++) {
205
+ const port = start + i
206
+ try {
207
+ const server = Bun.serve({port, hostname: '127.0.0.1', fetch: () => new Response()})
208
+ server.stop()
209
+ return port
210
+ } catch {
211
+ continue
212
+ }
213
+ }
214
+ console.error(`Error: no free port found between ${start} and ${start + limit - 1}`)
215
+ process.exit(1)
216
+ }
217
+
218
+ /**
219
+ * Cache is fresh if the zip exists and is newer than every source file in
220
+ * the project (excluding node_modules / dist / build / .git).
221
+ */
222
+ function isCacheFresh(zipPath: string, cwd: string): boolean {
223
+ if (!existsSync(zipPath)) return false
224
+ const zipMtime = statSync(zipPath).mtimeMs
225
+ return walkAllNewerThan(cwd, zipMtime, ['node_modules', 'dist', 'build', '.git']) === false
226
+ }
227
+
228
+ /**
229
+ * Returns true if any file under `dir` (recursively) has mtime > `threshold`.
230
+ * Skips directories whose name matches `excludeNames`. Bounded to keep
231
+ * cache-check fast on large monorepos.
232
+ */
233
+ function walkAllNewerThan(dir: string, threshold: number, excludeNames: string[]): boolean {
234
+ const MAX_FILES = 1000
235
+ let scanned = 0
236
+ const queue: string[] = [dir]
237
+ while (queue.length > 0) {
238
+ const cur = queue.shift()!
239
+ let entries: string[]
240
+ try {
241
+ entries = readdirSync(cur)
242
+ } catch {
243
+ continue
244
+ }
245
+ for (const entry of entries) {
246
+ if (excludeNames.includes(entry)) continue
247
+ if (entry.startsWith('.') && entry !== '.') continue
248
+ const abs = join(cur, entry)
249
+ let st
250
+ try {
251
+ st = statSync(abs)
252
+ } catch {
253
+ continue
254
+ }
255
+ if (st.isDirectory()) {
256
+ queue.push(abs)
257
+ } else if (st.isFile()) {
258
+ if (st.mtimeMs > threshold) return true
259
+ scanned += 1
260
+ if (scanned >= MAX_FILES) return true // err on rebuild for large trees
261
+ }
262
+ }
263
+ }
264
+ return false
265
+ }
@@ -0,0 +1,64 @@
1
+ import {expect, test, describe} from 'bun:test';
2
+ import {generateSchema} from './schema.js';
3
+ import {ALLOWED_PERMISSIONS, ALLOWED_HARDWARE_TYPES, ALLOWED_HARDWARE_LEVELS} from './manifest.js';
4
+
5
+ describe('generateSchema', () => {
6
+ test('declares the required top-level fields', () => {
7
+ const schema = generateSchema() as Record<string, unknown>;
8
+ expect(schema.type).toBe('object');
9
+ expect(schema.required).toEqual(['packageName', 'version', 'name', 'hardwareRequirements']);
10
+ });
11
+
12
+ test('permission enum mirrors ALLOWED_PERMISSIONS exactly', () => {
13
+ const schema = generateSchema() as any;
14
+ const enumValues = schema.properties.permissions.items.properties.type.enum;
15
+ expect(enumValues).toEqual([...ALLOWED_PERMISSIONS]);
16
+ });
17
+
18
+ test('hardware enum mirrors ALLOWED_HARDWARE_TYPES exactly', () => {
19
+ const schema = generateSchema() as any;
20
+ const enumValues = schema.properties.hardwareRequirements.items.properties.type.enum;
21
+ expect(enumValues).toEqual([...ALLOWED_HARDWARE_TYPES]);
22
+ });
23
+
24
+ test('hardware level enum mirrors ALLOWED_HARDWARE_LEVELS exactly', () => {
25
+ const schema = generateSchema() as any;
26
+ const enumValues = schema.properties.hardwareRequirements.items.properties.level.enum;
27
+ expect(enumValues).toEqual([...ALLOWED_HARDWARE_LEVELS]);
28
+ });
29
+
30
+ test('permission item disallows extra properties (catches typos)', () => {
31
+ const schema = generateSchema() as any;
32
+ expect(schema.properties.permissions.items.additionalProperties).toBe(false);
33
+ });
34
+
35
+ test('actions expose MCP outputSchema metadata', () => {
36
+ const schema = generateSchema() as any;
37
+ expect(schema.properties.actions.items.properties.outputSchema.type).toBe('object');
38
+ });
39
+
40
+ test('store fields carry the validator limits', () => {
41
+ const schema = generateSchema() as any;
42
+ expect(schema.properties.tagline.maxLength).toBe(80);
43
+ expect(schema.properties.tags.maxItems).toBe(5);
44
+ const re = new RegExp(schema.properties.tags.items.pattern);
45
+ expect(re.test('productivity')).toBe(true);
46
+ expect(re.test('home-automation')).toBe(true);
47
+ expect(re.test('Productivity')).toBe(false);
48
+ });
49
+
50
+ test('top-level allows extras for forward-compat', () => {
51
+ const schema = generateSchema() as any;
52
+ expect(schema.additionalProperties).toBe(true);
53
+ });
54
+
55
+ test('packageName has reverse-DNS pattern', () => {
56
+ const schema = generateSchema() as any;
57
+ expect(schema.properties.packageName.pattern).toBeDefined();
58
+ const re = new RegExp(schema.properties.packageName.pattern);
59
+ expect(re.test('com.glassly.example')).toBe(true);
60
+ expect(re.test('com.glassly.example.app')).toBe(true);
61
+ expect(re.test('justone')).toBe(false);
62
+ expect(re.test('a.b.c.d')).toBe(true);
63
+ });
64
+ });