@glassly/miniapp-cli 0.1.0-dev.1
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/README.md +221 -0
- package/package.json +52 -0
- package/schema/miniapp.schema.json +245 -0
- package/src/api.ts +4 -0
- package/src/build-helpers.test.ts +104 -0
- package/src/build-helpers.ts +357 -0
- package/src/build.ts +67 -0
- package/src/dev-server.test.ts +138 -0
- package/src/dev-server.ts +454 -0
- package/src/dev.ts +348 -0
- package/src/hardware.ts +163 -0
- package/src/index.ts +127 -0
- package/src/lan.test.ts +84 -0
- package/src/lan.ts +161 -0
- package/src/manifest-format.ts +121 -0
- package/src/manifest-mutate.test.ts +191 -0
- package/src/manifest-mutate.ts +213 -0
- package/src/manifest-wizard.ts +218 -0
- package/src/manifest.test.ts +322 -0
- package/src/manifest.ts +340 -0
- package/src/pack.ts +137 -0
- package/src/permission-hints.ts +36 -0
- package/src/permission.ts +142 -0
- package/src/qr.test.ts +81 -0
- package/src/qr.ts +119 -0
- package/src/release.ts +263 -0
- package/src/schema.test.ts +54 -0
- package/src/schema.ts +231 -0
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-miniapp 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-miniapp 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 sdk/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 `__glassly_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
|
+
}
|
package/src/hardware.ts
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
// `glassly-miniapp 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-miniapp 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
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
|
|
3
|
+
import { dev } from './dev.js';
|
|
4
|
+
import { release } from './release.js';
|
|
5
|
+
import { pack } from './pack.js';
|
|
6
|
+
import { schemaPrint, regenerateSchemaFile } from './schema.js';
|
|
7
|
+
import { addPermissionCmd, listPermissionsCmd, removePermissionCmd } from './permission.js';
|
|
8
|
+
import { addHardwareCmd, listHardwareCmd, removeHardwareCmd } from './hardware.js';
|
|
9
|
+
import { runManifestWizard } from './manifest-wizard.js';
|
|
10
|
+
import type { QRSize } from './qr.js';
|
|
11
|
+
|
|
12
|
+
const subcommand = process.argv[2];
|
|
13
|
+
const subcommandArg = process.argv[3];
|
|
14
|
+
|
|
15
|
+
const QR_SIZES: Record<string, QRSize> = {
|
|
16
|
+
sm: 'small',
|
|
17
|
+
small: 'small',
|
|
18
|
+
md: 'medium',
|
|
19
|
+
medium: 'medium',
|
|
20
|
+
lg: 'large',
|
|
21
|
+
large: 'large',
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
function parseQrSize(): QRSize {
|
|
25
|
+
let raw: string | undefined;
|
|
26
|
+
for (let i = 0; i < process.argv.length; i++) {
|
|
27
|
+
const arg = process.argv[i];
|
|
28
|
+
if (arg === '--qr' || arg === '-q') raw = process.argv[i + 1];
|
|
29
|
+
else if (arg.startsWith('--qr=')) raw = arg.slice('--qr='.length);
|
|
30
|
+
}
|
|
31
|
+
if (raw === undefined) return 'medium';
|
|
32
|
+
const size = QR_SIZES[raw.toLowerCase()];
|
|
33
|
+
if (!size) {
|
|
34
|
+
console.error(`Invalid --qr size "${raw}" (expected small|medium|large or sm|md|lg)`);
|
|
35
|
+
process.exit(1);
|
|
36
|
+
}
|
|
37
|
+
return size;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function printUsage(): void {
|
|
41
|
+
console.log('Usage: glassly-miniapp <command>\n');
|
|
42
|
+
console.log('Commands:');
|
|
43
|
+
console.log(' dev Start dev server with hot reload and QR code (--qr/-q sm|md|lg, default md)');
|
|
44
|
+
console.log(' Options: --qr-output <path> write PNG QR to path');
|
|
45
|
+
console.log(' release Build, pack, and serve a QR to install on a phone (--qr/-q sm|md|lg, default md)');
|
|
46
|
+
console.log(' Options: --no-cache --qr-output <path>');
|
|
47
|
+
console.log(' pack Production-build and package miniapp into build/<pkg>-<version>.zip (--no-build to skip build)');
|
|
48
|
+
console.log(' manifest Edit miniapp.json interactively');
|
|
49
|
+
console.log(' permission list List declared permissions');
|
|
50
|
+
console.log(' permission add [TYPE] Add a permission (interactive without TYPE)');
|
|
51
|
+
console.log(' permission remove [TYPE] Remove a declared permission');
|
|
52
|
+
console.log(' hardware list List declared hardware requirements');
|
|
53
|
+
console.log(' hardware add [TYPE] [LEVEL] Add a hardware requirement');
|
|
54
|
+
console.log(' hardware remove [TYPE] Remove a declared hardware requirement');
|
|
55
|
+
console.log(' schema print Print the miniapp.json JSON Schema to stdout');
|
|
56
|
+
console.log(' schema regenerate Regenerate the published schema file (CLI internal)');
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function flagValue(flag: string): string | undefined {
|
|
60
|
+
const idx = process.argv.indexOf(flag);
|
|
61
|
+
if (idx === -1) return undefined;
|
|
62
|
+
const value = process.argv[idx + 1];
|
|
63
|
+
if (!value || value.startsWith('-')) {
|
|
64
|
+
console.error(`Error: ${flag} requires a path argument`);
|
|
65
|
+
process.exit(1);
|
|
66
|
+
}
|
|
67
|
+
return value;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
switch (subcommand) {
|
|
71
|
+
case 'dev':
|
|
72
|
+
await dev({qrSize: parseQrSize(), qrOutput: flagValue('--qr-output')});
|
|
73
|
+
break;
|
|
74
|
+
case 'release':
|
|
75
|
+
await release({
|
|
76
|
+
noCache: process.argv.includes('--no-cache'),
|
|
77
|
+
qrSize: parseQrSize(),
|
|
78
|
+
qrOutput: flagValue('--qr-output'),
|
|
79
|
+
});
|
|
80
|
+
break;
|
|
81
|
+
case 'pack':
|
|
82
|
+
// Build with NODE_ENV=production before zipping, so `pack` never ships
|
|
83
|
+
// a stale dev-mode dist/ left behind by `dev`. `--no-build` zips dist/
|
|
84
|
+
// as-is for callers that manage the build themselves.
|
|
85
|
+
await pack({build: !process.argv.includes('--no-build')});
|
|
86
|
+
break;
|
|
87
|
+
case 'manifest':
|
|
88
|
+
await runManifestWizard();
|
|
89
|
+
break;
|
|
90
|
+
case 'permission':
|
|
91
|
+
if (subcommandArg === 'list') {
|
|
92
|
+
await listPermissionsCmd();
|
|
93
|
+
} else if (subcommandArg === 'add') {
|
|
94
|
+
await addPermissionCmd(process.argv[4]);
|
|
95
|
+
} else if (subcommandArg === 'remove') {
|
|
96
|
+
await removePermissionCmd(process.argv[4]);
|
|
97
|
+
} else {
|
|
98
|
+
console.error('Usage: glassly-miniapp permission <list|add|remove> [TYPE]');
|
|
99
|
+
process.exit(1);
|
|
100
|
+
}
|
|
101
|
+
break;
|
|
102
|
+
case 'hardware':
|
|
103
|
+
if (subcommandArg === 'list') {
|
|
104
|
+
await listHardwareCmd();
|
|
105
|
+
} else if (subcommandArg === 'add') {
|
|
106
|
+
await addHardwareCmd(process.argv[4], process.argv[5]);
|
|
107
|
+
} else if (subcommandArg === 'remove') {
|
|
108
|
+
await removeHardwareCmd(process.argv[4]);
|
|
109
|
+
} else {
|
|
110
|
+
console.error('Usage: glassly-miniapp hardware <list|add|remove> [TYPE] [LEVEL]');
|
|
111
|
+
process.exit(1);
|
|
112
|
+
}
|
|
113
|
+
break;
|
|
114
|
+
case 'schema':
|
|
115
|
+
if (subcommandArg === 'print') {
|
|
116
|
+
schemaPrint();
|
|
117
|
+
} else if (subcommandArg === 'regenerate') {
|
|
118
|
+
regenerateSchemaFile();
|
|
119
|
+
} else {
|
|
120
|
+
console.error('Usage: glassly-miniapp schema <print|regenerate>');
|
|
121
|
+
process.exit(1);
|
|
122
|
+
}
|
|
123
|
+
break;
|
|
124
|
+
default:
|
|
125
|
+
printUsage();
|
|
126
|
+
process.exit(subcommand ? 1 : 0);
|
|
127
|
+
}
|