@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.
- package/README.md +248 -0
- package/package.json +49 -0
- package/schema/miniapp.schema.json +269 -0
- package/src/api.ts +10 -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/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 +376 -0
- package/src/manifest.ts +412 -0
- package/src/pack.ts +131 -0
- package/src/permission-hints.ts +40 -0
- package/src/permission.ts +142 -0
- package/src/qr.test.ts +81 -0
- package/src/qr.ts +119 -0
- package/src/regenerate-schema.ts +6 -0
- package/src/release.ts +265 -0
- package/src/schema.test.ts +64 -0
- package/src/schema.ts +258 -0
package/src/lan.ts
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* LAN address selection for miniapp QR codes / release install URLs.
|
|
3
|
+
*
|
|
4
|
+
* Naive "first non-internal IPv4" picks VPN/tunnel interfaces (utun, tun,
|
|
5
|
+
* Tailscale, etc.) on many developer machines, which phones on Wi-Fi cannot
|
|
6
|
+
* reach. Score candidates and prefer real Wi-Fi / Ethernet instead.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import os from "os"
|
|
10
|
+
|
|
11
|
+
export interface LanIface {
|
|
12
|
+
name: string
|
|
13
|
+
address: string
|
|
14
|
+
internal: boolean
|
|
15
|
+
family: string | number
|
|
16
|
+
/** Present on normal broadcast LANs; often missing on point-to-point tunnels. */
|
|
17
|
+
netmask?: string
|
|
18
|
+
cidr?: string | null
|
|
19
|
+
mac?: string
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Interface-name prefixes that are almost never the Wi-Fi the phone shares. */
|
|
23
|
+
const SKIP_NAME_PREFIXES = [
|
|
24
|
+
"utun",
|
|
25
|
+
"awdl",
|
|
26
|
+
"llw",
|
|
27
|
+
"bridge",
|
|
28
|
+
"docker",
|
|
29
|
+
"veth",
|
|
30
|
+
"vmnet",
|
|
31
|
+
"tun",
|
|
32
|
+
"tap",
|
|
33
|
+
"zt",
|
|
34
|
+
"tailscale",
|
|
35
|
+
"ipsec",
|
|
36
|
+
"ppp",
|
|
37
|
+
"ap",
|
|
38
|
+
"phy",
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
/** Prefer these when present (macOS Wi-Fi is usually en0). */
|
|
42
|
+
const PREFERRED_NAMES = new Set(["en0", "en1", "eth0", "eth1", "wlan0", "wlan1", "wlp0s20f3"])
|
|
43
|
+
|
|
44
|
+
function isIpv4(family: string | number): boolean {
|
|
45
|
+
return family === "IPv4" || family === 4
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function isLinkLocal(address: string): boolean {
|
|
49
|
+
return address.startsWith("169.254.")
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function isPrivateLan(address: string): boolean {
|
|
53
|
+
if (address.startsWith("192.168.")) return true
|
|
54
|
+
if (address.startsWith("10.")) return true
|
|
55
|
+
return /^172\.(1[6-9]|2\d|3[0-1])\./.test(address)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function shouldSkipName(name: string): boolean {
|
|
59
|
+
const lower = name.toLowerCase()
|
|
60
|
+
return SKIP_NAME_PREFIXES.some((prefix) => lower === prefix || lower.startsWith(`${prefix}`))
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Rough "how /8-like is this mask?" — tunnel VPNs often advertise 255.0.0.0
|
|
65
|
+
* while home/office Wi-Fi is /24. Smaller host-count (tighter mask) scores higher.
|
|
66
|
+
*/
|
|
67
|
+
function netmaskSpecificity(netmask: string | undefined): number {
|
|
68
|
+
if (!netmask) return 0
|
|
69
|
+
const parts = netmask.split(".").map((p) => Number(p))
|
|
70
|
+
if (parts.length !== 4 || parts.some((n) => !Number.isFinite(n) || n < 0 || n > 255)) return 0
|
|
71
|
+
// Count set bits.
|
|
72
|
+
let bits = 0
|
|
73
|
+
for (const octet of parts) {
|
|
74
|
+
let v = octet
|
|
75
|
+
while (v) {
|
|
76
|
+
bits += v & 1
|
|
77
|
+
v >>= 1
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return bits
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Score a candidate; higher wins. Negative = reject. */
|
|
84
|
+
export function scoreLanIface(iface: LanIface): number {
|
|
85
|
+
if (!isIpv4(iface.family) || iface.internal) return -1
|
|
86
|
+
if (isLinkLocal(iface.address)) return -1
|
|
87
|
+
if (shouldSkipName(iface.name)) return -1
|
|
88
|
+
// Zero MAC is typical of virtual/tunnel adapters on macOS.
|
|
89
|
+
if (iface.mac === "00:00:00:00:00:00" && !PREFERRED_NAMES.has(iface.name)) return -1
|
|
90
|
+
|
|
91
|
+
let score = 0
|
|
92
|
+
if (isPrivateLan(iface.address)) score += 50
|
|
93
|
+
else score += 5 // public / unusual — last resort
|
|
94
|
+
|
|
95
|
+
if (PREFERRED_NAMES.has(iface.name)) score += 40
|
|
96
|
+
else if (
|
|
97
|
+
/^en\d+$/i.test(iface.name) ||
|
|
98
|
+
/^eth\d+$/i.test(iface.name) ||
|
|
99
|
+
/^wlan\d+$/i.test(iface.name) ||
|
|
100
|
+
// Predictable NetworkManager names on modern Linux (wlp3s0, enp0s3, …).
|
|
101
|
+
/^wlp\w+/i.test(iface.name) ||
|
|
102
|
+
/^enp\w+/i.test(iface.name)
|
|
103
|
+
) {
|
|
104
|
+
score += 25
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const specificity = netmaskSpecificity(iface.netmask)
|
|
108
|
+
// Prefer /16–/24 style LANs over /8 tunnels that slipped past the name filter.
|
|
109
|
+
if (specificity >= 16 && specificity <= 24) score += 20
|
|
110
|
+
else if (specificity > 24) score += 10
|
|
111
|
+
else if (specificity > 0 && specificity < 16) score -= 20
|
|
112
|
+
|
|
113
|
+
// 192.168/16 is the common home/office Wi-Fi shape.
|
|
114
|
+
if (iface.address.startsWith("192.168.")) score += 10
|
|
115
|
+
|
|
116
|
+
return score
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Pick the best LAN IPv4 for phone reachability from a NetworkInterfaces-like map.
|
|
121
|
+
* Exposed for unit tests; production code uses {@link getLanIp}.
|
|
122
|
+
*/
|
|
123
|
+
export function pickLanIp(interfaces: NodeJS.Dict<LanIface[] | undefined>): string | null {
|
|
124
|
+
let best: {address: string; score: number} | null = null
|
|
125
|
+
for (const [name, list] of Object.entries(interfaces)) {
|
|
126
|
+
for (const raw of list ?? []) {
|
|
127
|
+
const iface: LanIface = {...raw, name}
|
|
128
|
+
const score = scoreLanIface(iface)
|
|
129
|
+
if (score < 0) continue
|
|
130
|
+
if (!best || score > best.score) {
|
|
131
|
+
best = {address: iface.address, score}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return best?.address ?? null
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Current machine's best phone-reachable LAN IPv4, or null if none. */
|
|
139
|
+
export function getLanIp(): string | null {
|
|
140
|
+
return pickLanIp(os.networkInterfaces() as NodeJS.Dict<LanIface[] | undefined>)
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Bonjour / mDNS host for this machine (`ComputerName.local`), when usable.
|
|
145
|
+
* Survives Wi-Fi IP changes better than a raw IPv4 — phones that resolve
|
|
146
|
+
* `.local` can keep the same QR/dev URL across DHCP renewals.
|
|
147
|
+
*/
|
|
148
|
+
export function getMdnsHostname(): string | null {
|
|
149
|
+
const host = String(os.hostname() || "").trim()
|
|
150
|
+
if (!host) return null
|
|
151
|
+
// Bonjour advertises the first DNS label as `Label.local`. Machines whose
|
|
152
|
+
// hostname includes a corporate DNS suffix (e.g. `mba.corp.example.com`)
|
|
153
|
+
// must not become `mba.corp.example.com.local`.
|
|
154
|
+
const base = host.replace(/\.local$/i, "").split(".")[0] ?? ""
|
|
155
|
+
if (!base || base.toLowerCase() === "localhost") return null
|
|
156
|
+
// Reject names that would make a broken URL host.
|
|
157
|
+
if (!/^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/.test(base)) {
|
|
158
|
+
return null
|
|
159
|
+
}
|
|
160
|
+
return `${base}.local`
|
|
161
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// File I/O for miniapp.json. Atomic writes, line/column-precise parse errors.
|
|
2
|
+
|
|
3
|
+
import {existsSync, readFileSync, renameSync, writeFileSync, unlinkSync} from "fs"
|
|
4
|
+
import {resolve} from "path"
|
|
5
|
+
import type {Manifest} from "./manifest-mutate.js"
|
|
6
|
+
|
|
7
|
+
export type ManifestLoadError =
|
|
8
|
+
| {code: "not_found"; path: string}
|
|
9
|
+
| {code: "parse_error"; path: string; line: number; column: number; message: string}
|
|
10
|
+
| {code: "not_object"; path: string}
|
|
11
|
+
|
|
12
|
+
export type ManifestWriteError = {code: "write_failed"; path: string; cause: string}
|
|
13
|
+
|
|
14
|
+
export interface LoadedManifest {
|
|
15
|
+
path: string
|
|
16
|
+
raw: string
|
|
17
|
+
manifest: Manifest
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Load `miniapp.json` from `cwd`. Returns either the parsed manifest or a
|
|
22
|
+
* structured error describing what went wrong, including line/column for
|
|
23
|
+
* parse errors so the CLI can show the developer where to look.
|
|
24
|
+
*/
|
|
25
|
+
export function loadManifest(cwd: string): {ok: true; value: LoadedManifest} | {ok: false; error: ManifestLoadError} {
|
|
26
|
+
const path = resolve(cwd, "miniapp.json")
|
|
27
|
+
if (!existsSync(path)) {
|
|
28
|
+
return {ok: false, error: {code: "not_found", path}}
|
|
29
|
+
}
|
|
30
|
+
let raw: string
|
|
31
|
+
try {
|
|
32
|
+
raw = readFileSync(path, "utf8")
|
|
33
|
+
} catch (e) {
|
|
34
|
+
return {ok: false, error: {code: "parse_error", path, line: 0, column: 0, message: String(e)}}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
let parsed: unknown
|
|
38
|
+
try {
|
|
39
|
+
parsed = JSON.parse(raw)
|
|
40
|
+
} catch (e) {
|
|
41
|
+
const {line, column} = locateJsonParseError(raw, e as Error)
|
|
42
|
+
return {ok: false, error: {code: "parse_error", path, line, column, message: (e as Error).message}}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
46
|
+
return {ok: false, error: {code: "not_object", path}}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
return {ok: true, value: {path, raw, manifest: parsed as Manifest}}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Atomic write of `miniapp.json`. Writes to `<path>.tmp`, then renames in
|
|
54
|
+
* place. 2-space indentation matches the rest of the codebase. Pure JSON
|
|
55
|
+
* (no comments preserved — miniapp.json isn't JSONC).
|
|
56
|
+
*/
|
|
57
|
+
export function writeManifest(path: string, manifest: Manifest): {ok: true} | {ok: false; error: ManifestWriteError} {
|
|
58
|
+
const tmp = `${path}.tmp`
|
|
59
|
+
try {
|
|
60
|
+
writeFileSync(tmp, JSON.stringify(manifest, null, 2) + "\n", "utf8")
|
|
61
|
+
renameSync(tmp, path)
|
|
62
|
+
return {ok: true}
|
|
63
|
+
} catch (e) {
|
|
64
|
+
try {
|
|
65
|
+
// Best-effort cleanup of the partial tmp file.
|
|
66
|
+
if (existsSync(tmp)) unlinkSync(tmp)
|
|
67
|
+
} catch {
|
|
68
|
+
/* ignore */
|
|
69
|
+
}
|
|
70
|
+
return {ok: false, error: {code: "write_failed", path, cause: String(e)}}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Bun and V8 surface JSON parse errors with messages like
|
|
76
|
+
* "JSON Parse error: Unexpected token at line 4, column 12"
|
|
77
|
+
* "Unexpected token } in JSON at position 87"
|
|
78
|
+
* We extract the position and convert to (line, column) for friendlier output.
|
|
79
|
+
*/
|
|
80
|
+
function locateJsonParseError(raw: string, err: Error): {line: number; column: number} {
|
|
81
|
+
const msg = err.message
|
|
82
|
+
// Try Bun's "at line X, column Y" first (already 1-indexed).
|
|
83
|
+
const directMatch = msg.match(/at line (\d+), column (\d+)/i)
|
|
84
|
+
if (directMatch) {
|
|
85
|
+
return {line: parseInt(directMatch[1], 10), column: parseInt(directMatch[2], 10)}
|
|
86
|
+
}
|
|
87
|
+
// Fallback: V8-style "at position N".
|
|
88
|
+
const posMatch = msg.match(/position (\d+)/i)
|
|
89
|
+
if (posMatch) {
|
|
90
|
+
const pos = parseInt(posMatch[1], 10)
|
|
91
|
+
let line = 1
|
|
92
|
+
let column = 1
|
|
93
|
+
for (let i = 0; i < pos && i < raw.length; i++) {
|
|
94
|
+
if (raw[i] === "\n") {
|
|
95
|
+
line++
|
|
96
|
+
column = 1
|
|
97
|
+
} else {
|
|
98
|
+
column++
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return {line, column}
|
|
102
|
+
}
|
|
103
|
+
return {line: 0, column: 0}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function formatLoadError(error: ManifestLoadError): string {
|
|
107
|
+
switch (error.code) {
|
|
108
|
+
case "not_found":
|
|
109
|
+
return `No miniapp.json found in this directory.\n Expected: ${error.path}`
|
|
110
|
+
case "parse_error": {
|
|
111
|
+
const loc = error.line > 0 ? ` at line ${error.line}, column ${error.column}` : ""
|
|
112
|
+
return `miniapp.json is not valid JSON${loc}.\n ${error.path}\n ${error.message}`
|
|
113
|
+
}
|
|
114
|
+
case "not_object":
|
|
115
|
+
return `miniapp.json must be a JSON object (got an array or primitive).\n ${error.path}`
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function formatWriteError(error: ManifestWriteError): string {
|
|
120
|
+
return `Failed to write miniapp.json:\n ${error.path}\n ${error.cause}`
|
|
121
|
+
}
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import {describe, expect, test} from "bun:test"
|
|
2
|
+
import {
|
|
3
|
+
addHardware,
|
|
4
|
+
addPermission,
|
|
5
|
+
closestAllowedValue,
|
|
6
|
+
listHardware,
|
|
7
|
+
listPermissions,
|
|
8
|
+
Manifest,
|
|
9
|
+
MutateError,
|
|
10
|
+
removeHardware,
|
|
11
|
+
removePermission,
|
|
12
|
+
} from "./manifest-mutate.js"
|
|
13
|
+
import {ALLOWED_HARDWARE_TYPES, ALLOWED_PERMISSIONS} from "./manifest.js"
|
|
14
|
+
|
|
15
|
+
const baseManifest = (): Manifest => ({
|
|
16
|
+
packageName: "com.test.app",
|
|
17
|
+
version: "1.0.0",
|
|
18
|
+
name: "Test",
|
|
19
|
+
hardwareRequirements: [],
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
describe("addPermission", () => {
|
|
23
|
+
test("adds a valid permission", () => {
|
|
24
|
+
const m = addPermission(baseManifest(), "MICROPHONE")
|
|
25
|
+
expect(listPermissions(m)).toEqual([{type: "MICROPHONE"}])
|
|
26
|
+
})
|
|
27
|
+
|
|
28
|
+
test("normalizes case", () => {
|
|
29
|
+
const m = addPermission(baseManifest(), "microphone")
|
|
30
|
+
expect(listPermissions(m)).toEqual([{type: "MICROPHONE"}])
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
test("includes optional description and required", () => {
|
|
34
|
+
const m = addPermission(baseManifest(), "MICROPHONE", {description: "for transcription", required: false})
|
|
35
|
+
expect(listPermissions(m)[0]).toEqual({type: "MICROPHONE", description: "for transcription", required: false})
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
test("rejects unknown type with closest-match suggestion", () => {
|
|
39
|
+
let err: MutateError | null = null
|
|
40
|
+
try {
|
|
41
|
+
addPermission(baseManifest(), "MICRPHONE")
|
|
42
|
+
} catch (e) {
|
|
43
|
+
err = e as MutateError
|
|
44
|
+
}
|
|
45
|
+
expect(err).not.toBeNull()
|
|
46
|
+
expect(err!.info.code).toBe("unknown_type")
|
|
47
|
+
expect(err!.info.closestMatch).toBe("MICROPHONE")
|
|
48
|
+
expect(err!.message).toContain('Did you mean "MICROPHONE"?')
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
test("rejects gibberish without suggestion", () => {
|
|
52
|
+
let err: MutateError | null = null
|
|
53
|
+
try {
|
|
54
|
+
addPermission(baseManifest(), "QQQQQQQQ")
|
|
55
|
+
} catch (e) {
|
|
56
|
+
err = e as MutateError
|
|
57
|
+
}
|
|
58
|
+
expect(err).not.toBeNull()
|
|
59
|
+
expect(err!.info.code).toBe("unknown_type")
|
|
60
|
+
expect(err!.info.closestMatch).toBeUndefined()
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
test("rejects duplicates", () => {
|
|
64
|
+
const m = addPermission(baseManifest(), "MICROPHONE")
|
|
65
|
+
let err: MutateError | null = null
|
|
66
|
+
try {
|
|
67
|
+
addPermission(m, "MICROPHONE")
|
|
68
|
+
} catch (e) {
|
|
69
|
+
err = e as MutateError
|
|
70
|
+
}
|
|
71
|
+
expect(err).not.toBeNull()
|
|
72
|
+
expect(err!.info.code).toBe("duplicate")
|
|
73
|
+
})
|
|
74
|
+
|
|
75
|
+
test("does not mutate input manifest", () => {
|
|
76
|
+
const m = baseManifest()
|
|
77
|
+
addPermission(m, "MICROPHONE")
|
|
78
|
+
expect(m.permissions ?? []).toEqual([])
|
|
79
|
+
})
|
|
80
|
+
})
|
|
81
|
+
|
|
82
|
+
describe("removePermission", () => {
|
|
83
|
+
test("removes a present permission", () => {
|
|
84
|
+
let m = addPermission(baseManifest(), "MICROPHONE")
|
|
85
|
+
m = addPermission(m, "CAMERA")
|
|
86
|
+
m = removePermission(m, "MICROPHONE")
|
|
87
|
+
expect(listPermissions(m)).toEqual([{type: "CAMERA"}])
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
test("rejects missing permission", () => {
|
|
91
|
+
let err: MutateError | null = null
|
|
92
|
+
try {
|
|
93
|
+
removePermission(baseManifest(), "MICROPHONE")
|
|
94
|
+
} catch (e) {
|
|
95
|
+
err = e as MutateError
|
|
96
|
+
}
|
|
97
|
+
expect(err).not.toBeNull()
|
|
98
|
+
expect(err!.info.code).toBe("not_present")
|
|
99
|
+
})
|
|
100
|
+
|
|
101
|
+
test("rejects unknown type", () => {
|
|
102
|
+
let err: MutateError | null = null
|
|
103
|
+
try {
|
|
104
|
+
removePermission(baseManifest(), "BOGUS")
|
|
105
|
+
} catch (e) {
|
|
106
|
+
err = e as MutateError
|
|
107
|
+
}
|
|
108
|
+
expect(err).not.toBeNull()
|
|
109
|
+
expect(err!.info.code).toBe("unknown_type")
|
|
110
|
+
})
|
|
111
|
+
})
|
|
112
|
+
|
|
113
|
+
describe("addHardware", () => {
|
|
114
|
+
test("adds a valid hardware requirement", () => {
|
|
115
|
+
const m = addHardware(baseManifest(), "DISPLAY", "REQUIRED")
|
|
116
|
+
expect(listHardware(m)).toEqual([{type: "DISPLAY", level: "REQUIRED"}])
|
|
117
|
+
})
|
|
118
|
+
|
|
119
|
+
test("rejects unknown level with suggestion", () => {
|
|
120
|
+
let err: MutateError | null = null
|
|
121
|
+
try {
|
|
122
|
+
addHardware(baseManifest(), "DISPLAY", "REQURED")
|
|
123
|
+
} catch (e) {
|
|
124
|
+
err = e as MutateError
|
|
125
|
+
}
|
|
126
|
+
expect(err).not.toBeNull()
|
|
127
|
+
expect(err!.info.code).toBe("invalid_level")
|
|
128
|
+
expect(err!.info.closestMatch).toBe("REQUIRED")
|
|
129
|
+
})
|
|
130
|
+
|
|
131
|
+
test("rejects unknown type", () => {
|
|
132
|
+
let err: MutateError | null = null
|
|
133
|
+
try {
|
|
134
|
+
addHardware(baseManifest(), "BLUETOOTH", "REQUIRED")
|
|
135
|
+
} catch (e) {
|
|
136
|
+
err = e as MutateError
|
|
137
|
+
}
|
|
138
|
+
expect(err).not.toBeNull()
|
|
139
|
+
expect(err!.info.code).toBe("unknown_type")
|
|
140
|
+
})
|
|
141
|
+
|
|
142
|
+
test("rejects duplicates", () => {
|
|
143
|
+
const m = addHardware(baseManifest(), "DISPLAY", "REQUIRED")
|
|
144
|
+
let err: MutateError | null = null
|
|
145
|
+
try {
|
|
146
|
+
addHardware(m, "DISPLAY", "OPTIONAL")
|
|
147
|
+
} catch (e) {
|
|
148
|
+
err = e as MutateError
|
|
149
|
+
}
|
|
150
|
+
expect(err).not.toBeNull()
|
|
151
|
+
expect(err!.info.code).toBe("duplicate")
|
|
152
|
+
})
|
|
153
|
+
})
|
|
154
|
+
|
|
155
|
+
describe("removeHardware", () => {
|
|
156
|
+
test("removes a present hardware requirement", () => {
|
|
157
|
+
let m = addHardware(baseManifest(), "DISPLAY", "REQUIRED")
|
|
158
|
+
m = addHardware(m, "CAMERA", "OPTIONAL")
|
|
159
|
+
m = removeHardware(m, "DISPLAY")
|
|
160
|
+
expect(listHardware(m)).toEqual([{type: "CAMERA", level: "OPTIONAL"}])
|
|
161
|
+
})
|
|
162
|
+
|
|
163
|
+
test("rejects missing hardware", () => {
|
|
164
|
+
let err: MutateError | null = null
|
|
165
|
+
try {
|
|
166
|
+
removeHardware(baseManifest(), "DISPLAY")
|
|
167
|
+
} catch (e) {
|
|
168
|
+
err = e as MutateError
|
|
169
|
+
}
|
|
170
|
+
expect(err).not.toBeNull()
|
|
171
|
+
expect(err!.info.code).toBe("not_present")
|
|
172
|
+
})
|
|
173
|
+
})
|
|
174
|
+
|
|
175
|
+
describe("closestAllowedValue", () => {
|
|
176
|
+
test("matches obvious typo", () => {
|
|
177
|
+
expect(closestAllowedValue("MICRPHONE", ALLOWED_PERMISSIONS)).toBe("MICROPHONE")
|
|
178
|
+
})
|
|
179
|
+
|
|
180
|
+
test("returns null for distant input", () => {
|
|
181
|
+
expect(closestAllowedValue("QQQQQQQQ", ALLOWED_PERMISSIONS)).toBe(null)
|
|
182
|
+
})
|
|
183
|
+
|
|
184
|
+
test("matches case-insensitive", () => {
|
|
185
|
+
expect(closestAllowedValue("microphone", ALLOWED_PERMISSIONS)).toBe("MICROPHONE")
|
|
186
|
+
})
|
|
187
|
+
|
|
188
|
+
test("works for hardware types too", () => {
|
|
189
|
+
expect(closestAllowedValue("CAMRA", ALLOWED_HARDWARE_TYPES)).toBe("CAMERA")
|
|
190
|
+
})
|
|
191
|
+
})
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
// Pure manifest mutation helpers. No I/O. Returns new manifest objects.
|
|
2
|
+
//
|
|
3
|
+
// Used by the object-verb subcommands (`permission add`, `hardware add`, etc.)
|
|
4
|
+
// and the interactive `glassly manifest` wizard. Both surfaces share
|
|
5
|
+
// these primitives so behavior is identical.
|
|
6
|
+
|
|
7
|
+
import {
|
|
8
|
+
ALLOWED_HARDWARE_LEVELS,
|
|
9
|
+
ALLOWED_HARDWARE_TYPES,
|
|
10
|
+
ALLOWED_PERMISSIONS,
|
|
11
|
+
AllowedHardwareLevel,
|
|
12
|
+
AllowedHardwareType,
|
|
13
|
+
AllowedPermission,
|
|
14
|
+
ManifestHardwareRequirement,
|
|
15
|
+
ManifestPermission,
|
|
16
|
+
MiniappManifestV1,
|
|
17
|
+
} from "./manifest.js"
|
|
18
|
+
|
|
19
|
+
export type Manifest = MiniappManifestV1 & Record<string, unknown>
|
|
20
|
+
|
|
21
|
+
export interface ManifestMutateError {
|
|
22
|
+
code:
|
|
23
|
+
| "unknown_type"
|
|
24
|
+
| "duplicate"
|
|
25
|
+
| "invalid_level"
|
|
26
|
+
| "not_present"
|
|
27
|
+
message: string
|
|
28
|
+
/** For `unknown_type`: the closest allowed value by Levenshtein distance, if any. */
|
|
29
|
+
closestMatch?: string
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export class MutateError extends Error {
|
|
33
|
+
readonly info: ManifestMutateError
|
|
34
|
+
constructor(info: ManifestMutateError) {
|
|
35
|
+
super(info.message)
|
|
36
|
+
this.name = "MutateError"
|
|
37
|
+
this.info = info
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// ---------------------------------------------------------------------------
|
|
42
|
+
// Permissions
|
|
43
|
+
// ---------------------------------------------------------------------------
|
|
44
|
+
|
|
45
|
+
export function listPermissions(m: Manifest): ManifestPermission[] {
|
|
46
|
+
return [...(m.permissions ?? [])]
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function addPermission(
|
|
50
|
+
m: Manifest,
|
|
51
|
+
type: string,
|
|
52
|
+
opts?: {description?: string; required?: boolean},
|
|
53
|
+
): Manifest {
|
|
54
|
+
const validated = validatePermissionType(type)
|
|
55
|
+
const existing = m.permissions ?? []
|
|
56
|
+
if (existing.some((p) => p.type === validated)) {
|
|
57
|
+
throw new MutateError({
|
|
58
|
+
code: "duplicate",
|
|
59
|
+
message: `${validated} is already declared. Use 'glassly permission remove ${validated}' first if you want to update its description / required flag.`,
|
|
60
|
+
})
|
|
61
|
+
}
|
|
62
|
+
const entry: ManifestPermission = {type: validated}
|
|
63
|
+
if (opts?.description !== undefined) entry.description = opts.description
|
|
64
|
+
if (opts?.required !== undefined) entry.required = opts.required
|
|
65
|
+
return {...m, permissions: [...existing, entry]}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function removePermission(m: Manifest, type: string): Manifest {
|
|
69
|
+
const validated = validatePermissionType(type)
|
|
70
|
+
const existing = m.permissions ?? []
|
|
71
|
+
if (!existing.some((p) => p.type === validated)) {
|
|
72
|
+
throw new MutateError({
|
|
73
|
+
code: "not_present",
|
|
74
|
+
message: `${validated} is not declared. Currently declared: ${existing.map((p) => p.type).join(", ") || "(none)"}.`,
|
|
75
|
+
})
|
|
76
|
+
}
|
|
77
|
+
return {...m, permissions: existing.filter((p) => p.type !== validated)}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// ---------------------------------------------------------------------------
|
|
81
|
+
// Hardware
|
|
82
|
+
// ---------------------------------------------------------------------------
|
|
83
|
+
|
|
84
|
+
export function listHardware(m: Manifest): ManifestHardwareRequirement[] {
|
|
85
|
+
return [...(m.hardwareRequirements ?? [])]
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function addHardware(
|
|
89
|
+
m: Manifest,
|
|
90
|
+
type: string,
|
|
91
|
+
level: string,
|
|
92
|
+
opts?: {description?: string},
|
|
93
|
+
): Manifest {
|
|
94
|
+
const validatedType = validateHardwareType(type)
|
|
95
|
+
const validatedLevel = validateHardwareLevel(level)
|
|
96
|
+
const existing = m.hardwareRequirements ?? []
|
|
97
|
+
if (existing.some((h) => h.type === validatedType)) {
|
|
98
|
+
throw new MutateError({
|
|
99
|
+
code: "duplicate",
|
|
100
|
+
message: `${validatedType} hardware requirement already declared. Use 'glassly hardware remove ${validatedType}' first if you want to update its level / description.`,
|
|
101
|
+
})
|
|
102
|
+
}
|
|
103
|
+
const entry: ManifestHardwareRequirement = {type: validatedType, level: validatedLevel}
|
|
104
|
+
if (opts?.description !== undefined) entry.description = opts.description
|
|
105
|
+
return {...m, hardwareRequirements: [...existing, entry]}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function removeHardware(m: Manifest, type: string): Manifest {
|
|
109
|
+
const validatedType = validateHardwareType(type)
|
|
110
|
+
const existing = m.hardwareRequirements ?? []
|
|
111
|
+
if (!existing.some((h) => h.type === validatedType)) {
|
|
112
|
+
throw new MutateError({
|
|
113
|
+
code: "not_present",
|
|
114
|
+
message: `${validatedType} hardware requirement is not declared. Currently declared: ${existing.map((h) => h.type).join(", ") || "(none)"}.`,
|
|
115
|
+
})
|
|
116
|
+
}
|
|
117
|
+
return {...m, hardwareRequirements: existing.filter((h) => h.type !== validatedType)}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// ---------------------------------------------------------------------------
|
|
121
|
+
// Validators (with Levenshtein closest-match suggestions)
|
|
122
|
+
// ---------------------------------------------------------------------------
|
|
123
|
+
|
|
124
|
+
function validatePermissionType(input: string): AllowedPermission {
|
|
125
|
+
const normalized = input.toUpperCase()
|
|
126
|
+
if ((ALLOWED_PERMISSIONS as readonly string[]).includes(normalized)) {
|
|
127
|
+
return normalized as AllowedPermission
|
|
128
|
+
}
|
|
129
|
+
const closest = closestAllowedValue(normalized, ALLOWED_PERMISSIONS)
|
|
130
|
+
throw new MutateError({
|
|
131
|
+
code: "unknown_type",
|
|
132
|
+
message:
|
|
133
|
+
`Unknown permission "${input}".` +
|
|
134
|
+
(closest ? ` Did you mean "${closest}"?` : "") +
|
|
135
|
+
` Allowed: ${ALLOWED_PERMISSIONS.join(", ")}.`,
|
|
136
|
+
...(closest ? {closestMatch: closest} : {}),
|
|
137
|
+
})
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function validateHardwareType(input: string): AllowedHardwareType {
|
|
141
|
+
const normalized = input.toUpperCase()
|
|
142
|
+
if ((ALLOWED_HARDWARE_TYPES as readonly string[]).includes(normalized)) {
|
|
143
|
+
return normalized as AllowedHardwareType
|
|
144
|
+
}
|
|
145
|
+
const closest = closestAllowedValue(normalized, ALLOWED_HARDWARE_TYPES)
|
|
146
|
+
throw new MutateError({
|
|
147
|
+
code: "unknown_type",
|
|
148
|
+
message:
|
|
149
|
+
`Unknown hardware type "${input}".` +
|
|
150
|
+
(closest ? ` Did you mean "${closest}"?` : "") +
|
|
151
|
+
` Allowed: ${ALLOWED_HARDWARE_TYPES.join(", ")}.`,
|
|
152
|
+
...(closest ? {closestMatch: closest} : {}),
|
|
153
|
+
})
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function validateHardwareLevel(input: string): AllowedHardwareLevel {
|
|
157
|
+
const normalized = input.toUpperCase()
|
|
158
|
+
if ((ALLOWED_HARDWARE_LEVELS as readonly string[]).includes(normalized)) {
|
|
159
|
+
return normalized as AllowedHardwareLevel
|
|
160
|
+
}
|
|
161
|
+
const closest = closestAllowedValue(normalized, ALLOWED_HARDWARE_LEVELS)
|
|
162
|
+
throw new MutateError({
|
|
163
|
+
code: "invalid_level",
|
|
164
|
+
message:
|
|
165
|
+
`Invalid hardware level "${input}".` +
|
|
166
|
+
(closest ? ` Did you mean "${closest}"?` : "") +
|
|
167
|
+
` Allowed: ${ALLOWED_HARDWARE_LEVELS.join(", ")}.`,
|
|
168
|
+
...(closest ? {closestMatch: closest} : {}),
|
|
169
|
+
})
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Return the closest allowed value to `input` by Levenshtein distance. Threshold
|
|
174
|
+
* of 2 — anything further is too distant to be helpful.
|
|
175
|
+
*/
|
|
176
|
+
export function closestAllowedValue<T extends string>(
|
|
177
|
+
input: string,
|
|
178
|
+
allowed: readonly T[],
|
|
179
|
+
): T | null {
|
|
180
|
+
const upper = input.toUpperCase()
|
|
181
|
+
let best: T | null = null
|
|
182
|
+
let bestDist = Infinity
|
|
183
|
+
for (const candidate of allowed) {
|
|
184
|
+
const d = levenshtein(upper, candidate)
|
|
185
|
+
if (d < bestDist) {
|
|
186
|
+
bestDist = d
|
|
187
|
+
best = candidate
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
return bestDist <= 2 ? best : null
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function levenshtein(a: string, b: string): number {
|
|
194
|
+
if (a === b) return 0
|
|
195
|
+
if (!a.length) return b.length
|
|
196
|
+
if (!b.length) return a.length
|
|
197
|
+
|
|
198
|
+
const prev = new Array<number>(b.length + 1)
|
|
199
|
+
for (let j = 0; j <= b.length; j++) prev[j] = j
|
|
200
|
+
|
|
201
|
+
for (let i = 1; i <= a.length; i++) {
|
|
202
|
+
let curr = i
|
|
203
|
+
for (let j = 1; j <= b.length; j++) {
|
|
204
|
+
const cost = a[i - 1] === b[j - 1] ? 0 : 1
|
|
205
|
+
const next = Math.min(curr + 1, prev[j] + 1, prev[j - 1] + cost)
|
|
206
|
+
prev[j - 1] = curr
|
|
207
|
+
curr = next
|
|
208
|
+
}
|
|
209
|
+
prev[b.length] = curr
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
return prev[b.length]
|
|
213
|
+
}
|