@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/src/release.ts ADDED
@@ -0,0 +1,263 @@
1
+ /**
2
+ * `glassly-miniapp 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 = '/__glassly_release/health'
37
+ const MANIFEST_PATH = '/miniapp.json'
38
+ const ICON_PATH = '/icon.png'
39
+ const BUNDLE_PATH = '/bundle.zip'
40
+
41
+ interface ReleaseOptions {
42
+ noCache?: boolean
43
+ /** Terminal QR size (--qr/-q small|medium|large). Defaults to medium. */
44
+ qrSize?: QRSize
45
+ qrOutput?: string
46
+ }
47
+
48
+ export async function release(opts: ReleaseOptions = {}): Promise<void> {
49
+ const cwd = process.cwd()
50
+
51
+ // ---- 1. Validate manifest + read identity ---------------------------
52
+ const manifestPath = resolve(cwd, 'miniapp.json')
53
+ if (!existsSync(manifestPath)) {
54
+ console.error('Error: miniapp.json not found in current directory')
55
+ process.exit(1)
56
+ }
57
+ let manifest: Record<string, unknown>
58
+ try {
59
+ manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'))
60
+ } catch {
61
+ console.error('Error: miniapp.json is not valid JSON')
62
+ process.exit(1)
63
+ }
64
+ const validation = validateManifest(manifest)
65
+ if (!validation.valid) {
66
+ console.error('miniapp.json validation failed:')
67
+ for (const err of validation.errors) console.error(` - ${err}`)
68
+ process.exit(1)
69
+ }
70
+
71
+ const packageName = manifest.packageName as string
72
+ const version = manifest.version as string
73
+ const name = (manifest.name as string) ?? packageName
74
+
75
+ // ---- 2. Build (or skip via cache) -----------------------------------
76
+ const cacheDir = resolve(cwd, 'build')
77
+ const cachedZipName = `${packageName}-${version}.zip`
78
+ const cachedZipPath = join(cacheDir, cachedZipName)
79
+
80
+ const cacheValid = !opts.noCache && isCacheFresh(cachedZipPath, cwd)
81
+ if (cacheValid) {
82
+ console.log(`✓ Using cached build (${cachedZipName})`)
83
+ } else {
84
+ await buildProduction(cwd)
85
+
86
+ // Pack into build/<pkg>-<v>.zip
87
+ const packStart = Date.now()
88
+ const zipPath = await pack({outDir: 'build', silent: true})
89
+ const sizeKb = Math.round(statSync(zipPath).size / 1024)
90
+ console.log(`✓ Packed ${packageName}@${version} (${sizeKb} KB) in ${((Date.now() - packStart) / 1000).toFixed(1)}s`)
91
+ }
92
+
93
+ // ---- 3. Find a free port and load the bundle into memory ------------
94
+ const zipBuffer = readFileSync(cachedZipPath)
95
+ const iconPath = resolve(cwd, 'icon.png')
96
+ const iconBuffer = existsSync(iconPath) ? readFileSync(iconPath) : null
97
+ const manifestBuffer = readFileSync(manifestPath)
98
+
99
+ const port = await pickPort(DEFAULT_PORT_START, PORT_SCAN_LIMIT)
100
+ const lanIp = getLanIp()
101
+ if (!lanIp) {
102
+ console.error('Error: could not detect LAN IP. Connect to a Wi-Fi network and re-run.')
103
+ process.exit(1)
104
+ }
105
+
106
+ const baseUrl = `http://${lanIp}:${port}`
107
+
108
+ let installCount = 0
109
+
110
+ // ---- 4. Serve --------------------------------------------------------
111
+ const server = Bun.serve({
112
+ hostname: '0.0.0.0',
113
+ port,
114
+ fetch(req) {
115
+ const url = new URL(req.url)
116
+ if (url.pathname === HEALTH_PATH) {
117
+ return new Response(JSON.stringify({ok: true}), {
118
+ headers: {'content-type': 'application/json'},
119
+ })
120
+ }
121
+ if (url.pathname === MANIFEST_PATH) {
122
+ return new Response(manifestBuffer, {
123
+ headers: {'content-type': 'application/json'},
124
+ })
125
+ }
126
+ if (url.pathname === ICON_PATH) {
127
+ if (!iconBuffer) return new Response('Not found', {status: 404})
128
+ return new Response(iconBuffer, {
129
+ headers: {'content-type': 'image/png'},
130
+ })
131
+ }
132
+ if (url.pathname === BUNDLE_PATH) {
133
+ installCount += 1
134
+ const remote = req.headers.get('x-forwarded-for') ?? 'unknown'
135
+ console.log(`✓ Install #${installCount} — ${name}@${version} → ${remote}`)
136
+ return new Response(zipBuffer, {
137
+ headers: {
138
+ 'content-type': 'application/zip',
139
+ 'content-length': String(zipBuffer.length),
140
+ },
141
+ })
142
+ }
143
+ return new Response('Not found', {status: 404})
144
+ },
145
+ })
146
+
147
+ // ---- 5. QR + banner --------------------------------------------------
148
+ const qrUrl = `miniapp://release?url=${encodeURIComponent(baseUrl)}&package=${encodeURIComponent(packageName)}&version=${encodeURIComponent(version)}&name=${encodeURIComponent(name)}`
149
+
150
+ console.log('\n╔══════════════════════════════════════════════════════════════╗')
151
+ console.log('║ Install your mini app on a phone: ║')
152
+ console.log('║ ║')
153
+ console.log('║ 1. Open the Glassly app ║')
154
+ console.log('║ 2. Settings → Developer settings ║')
155
+ console.log('║ 3. Under "Mini App Development", tap ║')
156
+ console.log('║ "Scan Mini App QR Code" and scan the QR below ║')
157
+ console.log('║ ║')
158
+ console.log('║ Phone must be on the same Wi-Fi as this computer. ║')
159
+ console.log('║ This server stays up — install on multiple phones, then ║')
160
+ console.log('║ Ctrl+C to stop. ║')
161
+ console.log('╚══════════════════════════════════════════════════════════════╝\n')
162
+
163
+ const defaultQrPath = join(os.tmpdir(), `glassly-release-qr-${packageName}.png`)
164
+ const qrOutputPath = resolve(opts.qrOutput ?? defaultQrPath)
165
+ const cleanupQrOnExit = !opts.qrOutput
166
+
167
+ await printQR(qrUrl, {size: opts.qrSize})
168
+ const wrotePng = await writeQRPng(qrUrl, qrOutputPath)
169
+ console.log(`\n${qrUrl}`)
170
+ if (wrotePng) {
171
+ console.log(`PNG QR: ${qrOutputPath}\n`)
172
+ } else {
173
+ console.log(`PNG QR: (not written — see warning above)\n`)
174
+ }
175
+ console.log(`Serving on ${baseUrl}`)
176
+
177
+ // ---- 6. Wait for SIGINT / SIGTERM -----------------------------------
178
+ await new Promise<void>((resolvePromise) => {
179
+ const shutdown = () => {
180
+ console.log('\nShutting down...')
181
+ // Only remove the auto temp path — keep an explicit --qr-output artifact.
182
+ if (cleanupQrOnExit) {
183
+ try {
184
+ unlinkSync(qrOutputPath)
185
+ } catch {
186
+ // best-effort cleanup of temp PNG
187
+ }
188
+ }
189
+ server.stop()
190
+ resolvePromise()
191
+ }
192
+ process.on('SIGINT', shutdown)
193
+ process.on('SIGTERM', shutdown)
194
+ })
195
+ }
196
+
197
+ // ---------------------------------------------------------------------------
198
+ // Helpers
199
+ // ---------------------------------------------------------------------------
200
+
201
+ async function pickPort(start: number, limit: number): Promise<number> {
202
+ for (let i = 0; i < limit; i++) {
203
+ const port = start + i
204
+ try {
205
+ const server = Bun.serve({port, hostname: '127.0.0.1', fetch: () => new Response()})
206
+ server.stop()
207
+ return port
208
+ } catch {
209
+ continue
210
+ }
211
+ }
212
+ console.error(`Error: no free port found between ${start} and ${start + limit - 1}`)
213
+ process.exit(1)
214
+ }
215
+
216
+ /**
217
+ * Cache is fresh if the zip exists and is newer than every source file in
218
+ * the project (excluding node_modules / dist / build / .git).
219
+ */
220
+ function isCacheFresh(zipPath: string, cwd: string): boolean {
221
+ if (!existsSync(zipPath)) return false
222
+ const zipMtime = statSync(zipPath).mtimeMs
223
+ return walkAllNewerThan(cwd, zipMtime, ['node_modules', 'dist', 'build', '.git']) === false
224
+ }
225
+
226
+ /**
227
+ * Returns true if any file under `dir` (recursively) has mtime > `threshold`.
228
+ * Skips directories whose name matches `excludeNames`. Bounded to keep
229
+ * cache-check fast on large monorepos.
230
+ */
231
+ function walkAllNewerThan(dir: string, threshold: number, excludeNames: string[]): boolean {
232
+ const MAX_FILES = 1000
233
+ let scanned = 0
234
+ const queue: string[] = [dir]
235
+ while (queue.length > 0) {
236
+ const cur = queue.shift()!
237
+ let entries: string[]
238
+ try {
239
+ entries = readdirSync(cur)
240
+ } catch {
241
+ continue
242
+ }
243
+ for (const entry of entries) {
244
+ if (excludeNames.includes(entry)) continue
245
+ if (entry.startsWith('.') && entry !== '.') continue
246
+ const abs = join(cur, entry)
247
+ let st
248
+ try {
249
+ st = statSync(abs)
250
+ } catch {
251
+ continue
252
+ }
253
+ if (st.isDirectory()) {
254
+ queue.push(abs)
255
+ } else if (st.isFile()) {
256
+ if (st.mtimeMs > threshold) return true
257
+ scanned += 1
258
+ if (scanned >= MAX_FILES) return true // err on rebuild for large trees
259
+ }
260
+ }
261
+ }
262
+ return false
263
+ }
@@ -0,0 +1,54 @@
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('top-level allows extras for forward-compat', () => {
41
+ const schema = generateSchema() as any;
42
+ expect(schema.additionalProperties).toBe(true);
43
+ });
44
+
45
+ test('packageName has reverse-DNS pattern', () => {
46
+ const schema = generateSchema() as any;
47
+ expect(schema.properties.packageName.pattern).toBeDefined();
48
+ const re = new RegExp(schema.properties.packageName.pattern);
49
+ expect(re.test('com.glassly.example')).toBe(true);
50
+ expect(re.test('com.glassly.example.app')).toBe(true);
51
+ expect(re.test('justone')).toBe(false);
52
+ expect(re.test('a.b.c.d')).toBe(true);
53
+ });
54
+ });
package/src/schema.ts ADDED
@@ -0,0 +1,231 @@
1
+ // JSON Schema generator for miniapp.json.
2
+ //
3
+ // The schema is built from the same constants the validator uses (ALLOWED_PERMISSIONS,
4
+ // ALLOWED_HARDWARE_TYPES, ALLOWED_HARDWARE_LEVELS) so the two never drift.
5
+ //
6
+ // Surface:
7
+ // - generateSchema(): returns the JSON Schema object
8
+ // - glassly-miniapp schema print : prints the schema to stdout
9
+ //
10
+ // Authors point their IDE at the schema via $schema in miniapp.json:
11
+ // "$schema": "./node_modules/@glassly/miniapp-cli/schema/miniapp.schema.json"
12
+ //
13
+ // The scaffolder injects this $schema line so new projects get autocomplete on
14
+ // day one without anyone having to know it exists.
15
+
16
+ import {writeFileSync, mkdirSync} from 'fs';
17
+ import {dirname, resolve} from 'path';
18
+ import {fileURLToPath} from 'url';
19
+ import {
20
+ ALLOWED_PERMISSIONS,
21
+ ALLOWED_HARDWARE_TYPES,
22
+ ALLOWED_HARDWARE_LEVELS,
23
+ ALLOWED_ACTION_PARAM_TYPES,
24
+ } from './manifest.js';
25
+
26
+ const SCHEMA_ID = 'https://schemas.glassly.com/miniapp/v1.json';
27
+
28
+ export function generateSchema(): Record<string, unknown> {
29
+ return {
30
+ $schema: 'http://json-schema.org/draft-07/schema#',
31
+ $id: SCHEMA_ID,
32
+ title: 'Glassly miniapp manifest',
33
+ description: 'Manifest schema for a Glassly miniapp (miniapp.json)',
34
+ type: 'object',
35
+ required: ['packageName', 'version', 'name', 'hardwareRequirements'],
36
+ additionalProperties: true,
37
+ properties: {
38
+ $schema: {type: 'string'},
39
+ packageName: {
40
+ type: 'string',
41
+ pattern: '^[a-zA-Z][a-zA-Z0-9_]*(\\.[a-zA-Z][a-zA-Z0-9_]*)+$',
42
+ description: 'Reverse-DNS app identifier (e.g. com.example.app)',
43
+ },
44
+ version: {
45
+ type: 'string',
46
+ description: 'Semver version string (e.g. 1.0.0)',
47
+ },
48
+ name: {
49
+ type: 'string',
50
+ description: 'Human-readable app name',
51
+ },
52
+ description: {
53
+ type: 'string',
54
+ description: 'Short description shown in the store / dev tools',
55
+ },
56
+ icon: {
57
+ type: 'string',
58
+ description: 'Path or URL to the app icon (e.g. icon.png)',
59
+ },
60
+ port: {
61
+ type: 'integer',
62
+ minimum: 1,
63
+ maximum: 65535,
64
+ description: 'Port the dev server listens on (default 3000)',
65
+ },
66
+ sdkVersion: {
67
+ type: 'string',
68
+ description: 'Semver of the @glassly/miniapp SDK this bundle targets. Host refuses to spawn a miniapp whose sdkVersion is incompatible with the runtime it ships.',
69
+ },
70
+ minHostVersion: {
71
+ type: 'string',
72
+ description: 'Semver of the lowest Glassly Manager host version that can run this bundle. The host re-validates this on every install and after host upgrades; bundles that no longer meet the bar are disabled (not deleted) with a clear UI.',
73
+ },
74
+ entry: {
75
+ type: 'object',
76
+ description: 'Two-layer bundle entry points. Background is the always-running JSContext entry; UI is the on-demand WebView entry.',
77
+ additionalProperties: false,
78
+ required: ['background'],
79
+ properties: {
80
+ background: {
81
+ type: 'string',
82
+ description: 'Path to the background bundle, relative to the bundle root (e.g. background/index.js). Required for V2+ two-layer bundles.',
83
+ },
84
+ ui: {
85
+ type: 'string',
86
+ description: "Path to the UI bundle entry HTML, relative to the bundle root (e.g. ui/index.html). Optional -- pure-background miniapps don't need a WebView.",
87
+ },
88
+ },
89
+ },
90
+ type: {
91
+ type: 'string',
92
+ enum: ['standard', 'background'],
93
+ description: "Miniapp type. 'standard' includes a UI WebView; 'background' is JSContext-only. Defaults to 'standard'.",
94
+ },
95
+ permissions: {
96
+ type: 'array',
97
+ description: 'Phone permissions the miniapp needs to declare',
98
+ items: {
99
+ type: 'object',
100
+ required: ['type'],
101
+ additionalProperties: false,
102
+ properties: {
103
+ type: {
104
+ type: 'string',
105
+ enum: [...ALLOWED_PERMISSIONS],
106
+ description: 'Permission type',
107
+ },
108
+ required: {
109
+ type: 'boolean',
110
+ description: 'If false, the permission is optional. Defaults to required at runtime.',
111
+ },
112
+ description: {
113
+ type: 'string',
114
+ description: "User-facing reason this permission is needed (shown in OS prompts)",
115
+ },
116
+ },
117
+ },
118
+ },
119
+ hardwareRequirements: {
120
+ type: 'array',
121
+ description: 'Glasses hardware capabilities the miniapp needs',
122
+ items: {
123
+ type: 'object',
124
+ required: ['type', 'level'],
125
+ additionalProperties: false,
126
+ properties: {
127
+ type: {
128
+ type: 'string',
129
+ enum: [...ALLOWED_HARDWARE_TYPES],
130
+ description: 'Hardware capability type',
131
+ },
132
+ level: {
133
+ type: 'string',
134
+ enum: [...ALLOWED_HARDWARE_LEVELS],
135
+ description: 'REQUIRED hides the app on glasses without it; OPTIONAL still lets it run',
136
+ },
137
+ description: {
138
+ type: 'string',
139
+ description: 'How the miniapp uses this hardware',
140
+ },
141
+ },
142
+ },
143
+ },
144
+ actions: {
145
+ type: 'array',
146
+ description: 'Actions other miniapps can discover and invoke via session.actions. Maps 1:1 onto MCP tools.',
147
+ items: {
148
+ type: 'object',
149
+ required: ['id', 'description'],
150
+ additionalProperties: false,
151
+ properties: {
152
+ id: {
153
+ type: 'string',
154
+ pattern: '^[a-z][a-z0-9_]*$',
155
+ maxLength: 64,
156
+ description: 'Unique-within-app action id (lowercase, starts with a letter).',
157
+ },
158
+ description: {
159
+ type: 'string',
160
+ description: 'AI-facing contract -- say when to use the action.',
161
+ },
162
+ visibility: {
163
+ type: 'string',
164
+ enum: ['public', 'system'],
165
+ description:
166
+ 'Who may invoke this action: "public" (default -- any installed miniapp) or "system" (system miniapps such as the AI assistant only).',
167
+ },
168
+ parameters: {
169
+ type: 'object',
170
+ description: 'JSON-Schema input descriptor (the MCP inputSchema subset).',
171
+ properties: {
172
+ type: {const: 'object'},
173
+ properties: {
174
+ type: 'object',
175
+ additionalProperties: {
176
+ type: 'object',
177
+ properties: {
178
+ type: {type: 'string', enum: [...ALLOWED_ACTION_PARAM_TYPES]},
179
+ description: {type: 'string'},
180
+ enum: {type: 'array'},
181
+ items: {
182
+ type: 'object',
183
+ properties: {
184
+ type: {type: 'string', enum: ['string', 'number', 'boolean']},
185
+ },
186
+ },
187
+ },
188
+ },
189
+ },
190
+ required: {type: 'array', items: {type: 'string'}},
191
+ },
192
+ },
193
+ outputSchema: {
194
+ type: 'object',
195
+ description: 'JSON-Schema descriptor for the structured action result (MCP outputSchema).',
196
+ },
197
+ },
198
+ },
199
+ },
200
+ },
201
+ };
202
+ }
203
+
204
+ /** Returns the schema as a pretty-printed JSON string. */
205
+ export function generateSchemaString(): string {
206
+ return JSON.stringify(generateSchema(), null, 2) + '\n';
207
+ }
208
+
209
+ /** Write the schema to disk. Used at build time to produce `schema/miniapp.schema.json`. */
210
+ export function writeSchemaFile(absPath: string): void {
211
+ mkdirSync(dirname(absPath), {recursive: true});
212
+ writeFileSync(absPath, generateSchemaString(), 'utf8');
213
+ }
214
+
215
+ /** CLI entry: `glassly-miniapp schema print` writes JSON to stdout. */
216
+ export function schemaPrint(): void {
217
+ process.stdout.write(generateSchemaString());
218
+ }
219
+
220
+ /**
221
+ * CLI entry: regenerate the on-disk schema file. Run from the CLI package's
222
+ * own scripts (e.g. as a build step) so the published file stays in sync.
223
+ */
224
+ export function regenerateSchemaFile(): void {
225
+ // Resolve relative to this file: sdk/miniapp-cli/src/schema.ts -> ../schema/miniapp.schema.json
226
+ const here = fileURLToPath(import.meta.url);
227
+ const target = resolve(here, '..', '..', 'schema', 'miniapp.schema.json');
228
+ writeSchemaFile(target);
229
+ process.stdout.write(`Wrote ${target}\n`);
230
+ }
231
+