kamoji-dev 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +115 -2
- package/bin/kamoji.js +9 -0
- package/package.json +26 -4
- package/spec/VALIDATION.md +68 -0
- package/src/ble.js +215 -0
- package/src/check.js +276 -0
- package/src/cli.js +271 -0
- package/src/dev.js +314 -0
- package/src/keys.js +37 -0
- package/src/logfilter.js +56 -0
- package/src/protocol.js +574 -0
- package/src/serial.js +169 -0
- package/src/watch.js +106 -0
package/src/check.js
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
// Reading a mini app folder and checking it before it is sent: the rules and their ids are in
|
|
2
|
+
// spec/VALIDATION.md (shared with the Python worker/rig/kamoji_dev.py of kamoji-cms).
|
|
3
|
+
//
|
|
4
|
+
// Copied from kamoji-cms src/utils/appBundle.ts (APP_ID_RE, SEMVER_RE, APP_PERMISSIONS, APP_FEATURES,
|
|
5
|
+
// APP_PLATFORMS, BUNDLE_LIMITS, checkAppPath) because this package is published on its own: keep both
|
|
6
|
+
// in step when the store's rules change.
|
|
7
|
+
import fs from 'node:fs'
|
|
8
|
+
import path from 'node:path'
|
|
9
|
+
import { spawnSync } from 'node:child_process'
|
|
10
|
+
import { md5Hex } from './protocol.js'
|
|
11
|
+
|
|
12
|
+
export const APP_ID_RE = /^[a-z0-9][a-z0-9-]{1,39}$/
|
|
13
|
+
export const SEMVER_RE = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/
|
|
14
|
+
export const VERSION_RE = /^v?\d+(\.\d+){1,3}(-[0-9A-Za-z.-]+)?$/
|
|
15
|
+
export const APP_PERMISSIONS = [
|
|
16
|
+
'sensors.imu', 'sensors.light', 'sensors.mic', 'sensors.env', 'sensors.obd', 'events.drive', 'events.device',
|
|
17
|
+
'touch', 'net.http', 'net.mqtt', 'net.phone', 'phone.navigation', 'ble.gatt',
|
|
18
|
+
]
|
|
19
|
+
export const APP_FEATURES = ['gyro', 'temperature', 'light', 'microphone', 'fft', 'wifi', 'ble', 'gatt', 'mqtt', 'http', 'time', 'rgb_leds']
|
|
20
|
+
export const APP_PLATFORMS = ['android', 'ios']
|
|
21
|
+
export const PARAM_TYPES = ['number', 'bool', 'string', 'enum', 'color', 'secret']
|
|
22
|
+
export const WIDGET_TYPES = ['label', 'rect', 'circle', 'arc', 'bar', 'line', 'polyline', 'bitmap', 'chart', 'image']
|
|
23
|
+
export const ALIGNS = ['center', 'top_left', 'top_mid', 'top_right', 'left_mid', 'right_mid', 'bottom_left', 'bottom_mid', 'bottom_right']
|
|
24
|
+
export const LIMITS = { maxTotalBytes: 2 * 1024 * 1024, maxFiles: 64, maxPathBytes: 63, maxDepth: 3, maxManifestBytes: 16384 }
|
|
25
|
+
|
|
26
|
+
const SKIP_NAMES = new Set(['.DS_Store', 'Thumbs.db', '__MACOSX', 'node_modules', '4913'])
|
|
27
|
+
|
|
28
|
+
/** Files an editor or the OS leaves next to the real ones: never sent. */
|
|
29
|
+
export function isJunk(name) {
|
|
30
|
+
return (
|
|
31
|
+
name.startsWith('.') || SKIP_NAMES.has(name) || name.endsWith('~') || /\.(swp|swo|swx|tmp)$/i.test(name) ||
|
|
32
|
+
/^#.*#$/.test(name)
|
|
33
|
+
)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Same as the store's checkAppPath: an error message, or null. */
|
|
37
|
+
export function checkAppPath(p) {
|
|
38
|
+
if (!p) return 'empty path'
|
|
39
|
+
if (p.startsWith('/') || /^[a-zA-Z]:/.test(p)) return `absolute path not allowed: ${p}`
|
|
40
|
+
if (p.includes('\\')) return `backslash in path: ${p}`
|
|
41
|
+
if (/[\x00-\x1f\x7f]/.test(p)) return `control character in path: ${JSON.stringify(p)}`
|
|
42
|
+
const segments = p.split('/')
|
|
43
|
+
for (const s of segments) {
|
|
44
|
+
if (s === '') return `empty path segment: ${p}`
|
|
45
|
+
if (s === '..' || s === '.') return `relative segment not allowed: ${p}`
|
|
46
|
+
if (s.startsWith('.')) return `names starting with "." are not allowed: ${p}`
|
|
47
|
+
}
|
|
48
|
+
if (Buffer.byteLength(p, 'utf8') > LIMITS.maxPathBytes) return `path longer than ${LIMITS.maxPathBytes} bytes: ${p}`
|
|
49
|
+
if (segments.length > LIMITS.maxDepth) return `path deeper than ${LIMITS.maxDepth} levels: ${p}`
|
|
50
|
+
return null
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Every file of the folder that would be sent: [{path, data, md5}] sorted by path, plus what was skipped.
|
|
55
|
+
*/
|
|
56
|
+
export function readAppFolder(folder) {
|
|
57
|
+
const files = []
|
|
58
|
+
const skipped = []
|
|
59
|
+
const walk = (dir, rel) => {
|
|
60
|
+
for (const ent of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : 1))) {
|
|
61
|
+
const r = rel ? `${rel}/${ent.name}` : ent.name
|
|
62
|
+
if (isJunk(ent.name)) {
|
|
63
|
+
skipped.push(r)
|
|
64
|
+
continue
|
|
65
|
+
}
|
|
66
|
+
const full = path.join(dir, ent.name)
|
|
67
|
+
if (ent.isSymbolicLink()) skipped.push(r)
|
|
68
|
+
else if (ent.isDirectory()) walk(full, r)
|
|
69
|
+
else if (ent.isFile()) {
|
|
70
|
+
const data = fs.readFileSync(full)
|
|
71
|
+
files.push({ path: r, data, md5: md5Hex(data) })
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
walk(folder, '')
|
|
76
|
+
files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))
|
|
77
|
+
return { files, skipped }
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Version compare like the firmware checks: 0.3.10 > 0.3.9, a release after its -rc. */
|
|
81
|
+
export function compareVersions(a, b) {
|
|
82
|
+
const parse = (v) => {
|
|
83
|
+
const m = /^v?(\d+(?:\.\d+)*)(?:-(.*))?$/.exec(String(v ?? '').trim())
|
|
84
|
+
if (!m) return [[0, 0, 0, 0], '']
|
|
85
|
+
const nums = [...m[1].split('.').map(Number), 0, 0, 0, 0].slice(0, 4)
|
|
86
|
+
return [nums, m[2] ?? '~']
|
|
87
|
+
}
|
|
88
|
+
const [na, pa] = parse(a)
|
|
89
|
+
const [nb, pb] = parse(b)
|
|
90
|
+
for (let i = 0; i < 4; i++) if (na[i] !== nb[i]) return na[i] < nb[i] ? -1 : 1
|
|
91
|
+
return pa === pb ? 0 : pa < pb ? -1 : 1
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
let luacCache
|
|
95
|
+
/** The Lua compiler on this computer: { cmd, version: '5.4' | '5.5' | … } or null. */
|
|
96
|
+
export function findLuac() {
|
|
97
|
+
if (luacCache !== undefined) return luacCache
|
|
98
|
+
luacCache = null
|
|
99
|
+
for (const cmd of [process.env.KAMOJI_LUAC, 'luac5.4', 'luac54', 'luac'].filter(Boolean)) {
|
|
100
|
+
const r = spawnSync(cmd, ['-v'], { encoding: 'utf8' })
|
|
101
|
+
if (r.error) continue
|
|
102
|
+
const m = /Lua (\d+\.\d+)/.exec(`${r.stdout}${r.stderr}`)
|
|
103
|
+
luacCache = { cmd, version: m ? m[1] : '?' }
|
|
104
|
+
break
|
|
105
|
+
}
|
|
106
|
+
return luacCache
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function checkLua(file, add) {
|
|
110
|
+
const luac = findLuac()
|
|
111
|
+
if (!luac) return false
|
|
112
|
+
const r = spawnSync(luac.cmd, ['-p', '-'], { input: file.data, encoding: 'utf8' })
|
|
113
|
+
if (r.status !== 0) {
|
|
114
|
+
const msg = `${r.stderr || r.stdout}`.trim().split('\n')[0].replace(/^\S*luac\S*:\s*/, '').replace(/^(stdin|=stdin|-):/, `${file.path}:`)
|
|
115
|
+
if (luac.version === '5.4') add('error', 'lua-syntax', msg, file.path)
|
|
116
|
+
else add('warning', 'lua-other-version', `${msg} (checked with Lua ${luac.version}; Kamoji runs Lua 5.4: confirm on Kamoji)`, file.path)
|
|
117
|
+
}
|
|
118
|
+
return true
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function checkLayout(file, add) {
|
|
122
|
+
let layout
|
|
123
|
+
try {
|
|
124
|
+
layout = JSON.parse(file.data.toString('utf8').replace(/^/, ''))
|
|
125
|
+
} catch (e) {
|
|
126
|
+
add('error', 'layout-json', `not valid JSON: ${e.message}`, file.path)
|
|
127
|
+
return
|
|
128
|
+
}
|
|
129
|
+
let widgets
|
|
130
|
+
if (Array.isArray(layout)) widgets = layout
|
|
131
|
+
else if (layout && typeof layout === 'object' && Array.isArray(layout.widgets)) widgets = layout.widgets
|
|
132
|
+
else {
|
|
133
|
+
add('error', 'layout-shape', 'must be an array of widgets, or an object with a "widgets" array', file.path)
|
|
134
|
+
return
|
|
135
|
+
}
|
|
136
|
+
widgets.forEach((w, i) => {
|
|
137
|
+
const where = `${file.path} widget ${i + 1}`
|
|
138
|
+
if (!w || typeof w !== 'object' || Array.isArray(w)) {
|
|
139
|
+
add('warning', 'widget-type', 'not an object (skipped by Kamoji)', where)
|
|
140
|
+
return
|
|
141
|
+
}
|
|
142
|
+
if (!WIDGET_TYPES.includes(w.type))
|
|
143
|
+
add('warning', 'widget-type', `type ${JSON.stringify(w.type)} is not a widget Kamoji draws (${WIDGET_TYPES.join(', ')})`, where)
|
|
144
|
+
if (w.align !== undefined && !ALIGNS.includes(w.align)) add('warning', 'align', `align ${JSON.stringify(w.align)} is not one of ${ALIGNS.join(', ')}`, where)
|
|
145
|
+
for (const [k, v] of Object.entries(w)) {
|
|
146
|
+
if (typeof v === 'string' && v.split('{{').length - 1 > v.split('}}').length - 1)
|
|
147
|
+
add('warning', 'binding-braces', `"${k}" opens {{ without closing }}`, where)
|
|
148
|
+
}
|
|
149
|
+
})
|
|
150
|
+
if (!Array.isArray(layout) && layout.on !== undefined) {
|
|
151
|
+
if (!layout.on || typeof layout.on !== 'object' || Array.isArray(layout.on)) add('error', 'layout-on', '"on" must be an object', file.path)
|
|
152
|
+
else
|
|
153
|
+
for (const [k, v] of Object.entries(layout.on))
|
|
154
|
+
if (typeof v !== 'string') add('error', 'layout-on', `"on.${k}" must be a string of Lua statements`, file.path)
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function checkManifest(m, folderName, add) {
|
|
159
|
+
const where = 'manifest.json'
|
|
160
|
+
if (typeof m.id !== 'string' || !APP_ID_RE.test(m.id))
|
|
161
|
+
add('error', 'id', '"id": lowercase letters, digits and "-", starting with a letter or digit, 2 to 40 characters', where)
|
|
162
|
+
else if (folderName && m.id !== folderName)
|
|
163
|
+
add('warning', 'id-folder', `"id" is "${m.id}" but the folder is "${folderName}" (the store and Kamoji use the id as the folder name)`, where)
|
|
164
|
+
if (typeof m.version !== 'string' || !SEMVER_RE.test(m.version))
|
|
165
|
+
add('error', 'version', '"version" must be a version like 1.0.0 (the store needs it)', where)
|
|
166
|
+
if (m.api_version !== 1) add('error', 'api-version', '"api_version" must be 1', where)
|
|
167
|
+
const perms = m.permissions
|
|
168
|
+
if (perms !== undefined) {
|
|
169
|
+
if (!Array.isArray(perms)) add('error', 'permissions', '"permissions" must be an array', where)
|
|
170
|
+
else {
|
|
171
|
+
const unknown = perms.filter((p) => !APP_PERMISSIONS.includes(p))
|
|
172
|
+
if (unknown.length) add('error', 'permissions', `unknown permissions: ${unknown.join(', ')} (known: ${APP_PERMISSIONS.join(', ')})`, where)
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
if (m.features !== undefined) {
|
|
176
|
+
if (!Array.isArray(m.features)) add('error', 'features', '"features" must be an array', where)
|
|
177
|
+
else {
|
|
178
|
+
const unknown = m.features.filter((f) => !APP_FEATURES.includes(f))
|
|
179
|
+
if (unknown.length) add('error', 'features', `unknown features: ${unknown.join(', ')} (known: ${APP_FEATURES.join(', ')})`, where)
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
if (m.platforms !== undefined) {
|
|
183
|
+
if (!Array.isArray(m.platforms) || m.platforms.length === 0) add('error', 'platforms', '"platforms" must be a non-empty array', where)
|
|
184
|
+
else {
|
|
185
|
+
const unknown = m.platforms.filter((p) => !APP_PLATFORMS.includes(p))
|
|
186
|
+
if (unknown.length) add('error', 'platforms', `unknown platforms: ${unknown.join(', ')}`, where)
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
if (m.min_firmware !== undefined && (typeof m.min_firmware !== 'string' || !VERSION_RE.test(m.min_firmware)))
|
|
190
|
+
add('error', 'min-firmware', '"min_firmware" must be a version string like "0.3.0"', where)
|
|
191
|
+
const has = (p) => Array.isArray(perms) && perms.includes(p)
|
|
192
|
+
if (m.ble !== undefined && !has('ble.gatt')) add('error', 'ble-permission', '"ble" needs the "ble.gatt" permission (Kamoji refuses the install)', where)
|
|
193
|
+
if (m.http !== undefined && !has('net.http')) add('warning', 'http-permission', '"http" without the "net.http" permission: http is nil in Lua', where)
|
|
194
|
+
if ((m.ble !== undefined || m.http !== undefined) &&
|
|
195
|
+
(typeof m.min_firmware !== 'string' || compareVersions(m.min_firmware, '0.3.0') < 0))
|
|
196
|
+
add('warning', 'min-firmware-030', '"ble" and "http" need firmware 0.3.0: set "min_firmware": "0.3.0"', where)
|
|
197
|
+
if (m.params !== undefined) {
|
|
198
|
+
if (!Array.isArray(m.params)) add('error', 'params', '"params" must be an array', where)
|
|
199
|
+
else {
|
|
200
|
+
const seen = new Set()
|
|
201
|
+
m.params.forEach((p, i) => {
|
|
202
|
+
const at = `params[${i}]`
|
|
203
|
+
if (!p || typeof p !== 'object' || Array.isArray(p)) return add('error', 'params', `${at} must be an object`, where)
|
|
204
|
+
if (typeof p.key !== 'string' || !p.key) add('error', 'params', `${at} needs a "key"`, where)
|
|
205
|
+
else if (seen.has(p.key)) add('error', 'params', `${at}: key "${p.key}" is used twice`, where)
|
|
206
|
+
else seen.add(p.key)
|
|
207
|
+
const type = p.type ?? 'string'
|
|
208
|
+
if (!PARAM_TYPES.includes(type)) add('error', 'params', `${at}: type ${JSON.stringify(type)} is not one of ${PARAM_TYPES.join(', ')}`, where)
|
|
209
|
+
if (type === 'enum' && (!Array.isArray(p.options) || p.options.length === 0))
|
|
210
|
+
add('error', 'params', `${at}: an enum needs "options"`, where)
|
|
211
|
+
})
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Check a folder. Returns { problems:[{level,id,message,where}], errors, warnings, manifest, appId, files, skipped, bytes }.
|
|
218
|
+
* @param {{lua?: boolean}} [opts] lua: false skips the Lua compiler
|
|
219
|
+
*/
|
|
220
|
+
export function checkApp(folder, opts = {}) {
|
|
221
|
+
const problems = []
|
|
222
|
+
const add = (level, id, message, where) => problems.push({ level, id, message, where })
|
|
223
|
+
const folderName = path.basename(path.resolve(folder))
|
|
224
|
+
const { files, skipped } = readAppFolder(folder)
|
|
225
|
+
if (skipped.length) add('info', 'skipped', `not sent: ${skipped.join(', ')}`)
|
|
226
|
+
for (const f of files) {
|
|
227
|
+
const err = checkAppPath(f.path)
|
|
228
|
+
if (err) add('error', 'path', err, f.path)
|
|
229
|
+
}
|
|
230
|
+
if (files.length > LIMITS.maxFiles) add('error', 'too-many-files', `${files.length} files (at most ${LIMITS.maxFiles})`)
|
|
231
|
+
const bytes = files.reduce((n, f) => n + f.data.length, 0)
|
|
232
|
+
if (bytes > LIMITS.maxTotalBytes) add('error', 'too-large', `${Math.ceil(bytes / 1024)} KB (at most 2 MB)`)
|
|
233
|
+
|
|
234
|
+
let manifest = null
|
|
235
|
+
const mf = files.find((f) => f.path === 'manifest.json')
|
|
236
|
+
if (!mf) add('error', 'manifest-missing', 'no manifest.json at the root of the folder')
|
|
237
|
+
else if (mf.data.length > LIMITS.maxManifestBytes) add('error', 'manifest-size', `manifest.json is ${mf.data.length} bytes (at most 16 KB)`, 'manifest.json')
|
|
238
|
+
else {
|
|
239
|
+
try {
|
|
240
|
+
manifest = JSON.parse(mf.data.toString('utf8').replace(/^/, ''))
|
|
241
|
+
if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) {
|
|
242
|
+
manifest = null
|
|
243
|
+
add('error', 'manifest-json', 'manifest.json must be a JSON object', 'manifest.json')
|
|
244
|
+
}
|
|
245
|
+
} catch (e) {
|
|
246
|
+
add('error', 'manifest-json', `not valid JSON: ${e.message}`, 'manifest.json')
|
|
247
|
+
}
|
|
248
|
+
if (manifest) checkManifest(manifest, folderName, add)
|
|
249
|
+
}
|
|
250
|
+
const layout = files.find((f) => f.path === 'layout.json')
|
|
251
|
+
if (layout) checkLayout(layout, add)
|
|
252
|
+
if (opts.lua !== false) {
|
|
253
|
+
const luaFiles = files.filter((f) => f.path.endsWith('.lua'))
|
|
254
|
+
if (luaFiles.length) {
|
|
255
|
+
let ran = false
|
|
256
|
+
for (const f of luaFiles) ran = checkLua(f, add) || ran
|
|
257
|
+
if (!ran) add('info', 'lua-missing', 'no Lua compiler (luac5.4 / luac) found: Lua is checked by Kamoji only')
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
const appId = manifest && typeof manifest.id === 'string' && APP_ID_RE.test(manifest.id) ? manifest.id : null
|
|
261
|
+
return {
|
|
262
|
+
problems,
|
|
263
|
+
errors: problems.filter((p) => p.level === 'error'),
|
|
264
|
+
warnings: problems.filter((p) => p.level === 'warning'),
|
|
265
|
+
manifest,
|
|
266
|
+
appId,
|
|
267
|
+
files,
|
|
268
|
+
skipped,
|
|
269
|
+
bytes,
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** The md5 of the whole set (paths + contents): unchanged files are not sent again. */
|
|
274
|
+
export function bundleHash(files) {
|
|
275
|
+
return md5Hex(Buffer.from(files.map((f) => `${f.path}\0${f.md5}`).join('\n')))
|
|
276
|
+
}
|
package/src/cli.js
ADDED
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
// kamoji: develop Kamoji Mini Apps on your own Kamoji. See README.md.
|
|
2
|
+
import fs from 'node:fs'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
import readline from 'node:readline'
|
|
5
|
+
import { parseArgs } from 'node:util'
|
|
6
|
+
import { chooseKamoji, connect, loadNoble, poweredOn, scan } from './ble.js'
|
|
7
|
+
import { checkApp } from './check.js'
|
|
8
|
+
import { DevSession, kb, makeUi, printProblems } from './dev.js'
|
|
9
|
+
import { deleteKey, keyPath, loadOrCreateKey } from './keys.js'
|
|
10
|
+
import { KamojiError, Session } from './protocol.js'
|
|
11
|
+
import { SerialLog, findPorts } from './serial.js'
|
|
12
|
+
|
|
13
|
+
const VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version
|
|
14
|
+
|
|
15
|
+
export const HELP = `kamoji ${VERSION}: develop Kamoji Mini Apps on your own Kamoji
|
|
16
|
+
|
|
17
|
+
Usage:
|
|
18
|
+
kamoji dev <folder> check, install over Bluetooth and open the app, then again on every save
|
|
19
|
+
kamoji install <folder> check, install and open once
|
|
20
|
+
kamoji check <folder> only check the folder (manifest, layout, Lua) like the Mini Apps store
|
|
21
|
+
kamoji apps list the mini apps on Kamoji
|
|
22
|
+
kamoji shot save a screenshot of Kamoji's screen
|
|
23
|
+
kamoji logs show Kamoji's USB log (USB cable needed)
|
|
24
|
+
kamoji forget make Kamoji forget this computer, and delete its key
|
|
25
|
+
|
|
26
|
+
Options:
|
|
27
|
+
--device KMJ-XXXX which Kamoji (needed when several are near)
|
|
28
|
+
--port PATH USB serial port for the log (default: found by itself)
|
|
29
|
+
--ble Bluetooth only: no USB log even with a cable
|
|
30
|
+
--usb require the USB cable (log and screenshots over USB)
|
|
31
|
+
--out DIR where screenshots go (default: ./kamoji-shots)
|
|
32
|
+
--reboot restart Kamoji by itself when the app's Bluetooth services need it
|
|
33
|
+
--app ID (logs) filter the USB log to this app
|
|
34
|
+
--verbose every USB log line, and more detail
|
|
35
|
+
--no-lua don't run luac
|
|
36
|
+
--json (check) print the result as JSON
|
|
37
|
+
|
|
38
|
+
While "kamoji dev" runs: Enter = install again, o = open, s = screenshot, b = restart Kamoji, q = quit.
|
|
39
|
+
|
|
40
|
+
Before you start: disconnect the Kamoji app on your phone (Kamoji takes one Bluetooth connection at
|
|
41
|
+
a time). The first time, keep the computer right next to Kamoji: it then trusts this computer (key in
|
|
42
|
+
${keyPath('KMJ-XXXX').replace(/KMJ-XXXX\.key$/, '<board>.key')}).`
|
|
43
|
+
|
|
44
|
+
const OPTIONS = {
|
|
45
|
+
device: { type: 'string' },
|
|
46
|
+
port: { type: 'string' },
|
|
47
|
+
ble: { type: 'boolean' },
|
|
48
|
+
usb: { type: 'boolean' },
|
|
49
|
+
out: { type: 'string' },
|
|
50
|
+
reboot: { type: 'boolean' },
|
|
51
|
+
app: { type: 'string' },
|
|
52
|
+
verbose: { type: 'boolean', short: 'v' },
|
|
53
|
+
'no-lua': { type: 'boolean' },
|
|
54
|
+
json: { type: 'boolean' },
|
|
55
|
+
once: { type: 'boolean' },
|
|
56
|
+
help: { type: 'boolean', short: 'h' },
|
|
57
|
+
version: { type: 'boolean' },
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The Bluetooth connector used by DevSession. */
|
|
61
|
+
export function bleConnector(device, ui) {
|
|
62
|
+
return async ({ onDisconnect }) => {
|
|
63
|
+
const noble = await loadNoble()
|
|
64
|
+
await poweredOn(noble)
|
|
65
|
+
const seen = await scan(noble, { want: device, ms: device ? 30000 : 10000, ui })
|
|
66
|
+
const d = chooseKamoji(seen, device)
|
|
67
|
+
const link = await connect(d, { onDisconnect })
|
|
68
|
+
return { link, board: d.name ?? d.id, name: d.name, revision: d.revision, firmware: d.firmware }
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const keyStore = (board) => {
|
|
73
|
+
const k = loadOrCreateKey(board)
|
|
74
|
+
return { key: k.key, created: k.created }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The USB serial log, when there is (or must be) one. */
|
|
78
|
+
async function openSerial(a, ui, onLine) {
|
|
79
|
+
if (a.ble) return null
|
|
80
|
+
let port = a.port && a.port !== 'auto' ? a.port : null
|
|
81
|
+
try {
|
|
82
|
+
if (!port) {
|
|
83
|
+
const ports = await findPorts()
|
|
84
|
+
if (ports.length === 1) port = ports[0]
|
|
85
|
+
else if (ports.length > 1) {
|
|
86
|
+
const msg = `${ports.length} Espressif USB devices (${ports.join(', ')}): pass --port to pick one.`
|
|
87
|
+
if (a.usb) throw new KamojiError('usb', msg)
|
|
88
|
+
ui.warn(`${msg} No USB log for now.`)
|
|
89
|
+
return null
|
|
90
|
+
} else if (a.usb) throw new KamojiError('usb', 'No Kamoji on USB.', 'Plug it in with a USB-C data cable, or pass --port.')
|
|
91
|
+
else {
|
|
92
|
+
ui.info('No USB cable: no Kamoji log (plug it in for print() output, Lua errors and crashes).')
|
|
93
|
+
return null
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
const s = new SerialLog(port, { onLine })
|
|
97
|
+
await s.start()
|
|
98
|
+
ui.ok(`USB log from ${port}.`)
|
|
99
|
+
return s
|
|
100
|
+
} catch (e) {
|
|
101
|
+
if (a.usb || e instanceof KamojiError) throw e
|
|
102
|
+
ui.warn(`USB log unavailable (${e.message}).`)
|
|
103
|
+
return null
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export async function main(argv = process.argv.slice(2)) {
|
|
108
|
+
let parsed
|
|
109
|
+
try {
|
|
110
|
+
parsed = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true })
|
|
111
|
+
} catch (e) {
|
|
112
|
+
console.error(`${e.message}\n\n${HELP}`)
|
|
113
|
+
return 2
|
|
114
|
+
}
|
|
115
|
+
const a = parsed.values
|
|
116
|
+
const [cmd, folderArg] = parsed.positionals
|
|
117
|
+
if (a.version) {
|
|
118
|
+
console.log(VERSION)
|
|
119
|
+
return 0
|
|
120
|
+
}
|
|
121
|
+
if (a.help || !cmd || cmd === 'help') {
|
|
122
|
+
console.log(HELP)
|
|
123
|
+
return cmd || a.help ? 0 : 2
|
|
124
|
+
}
|
|
125
|
+
const ui = makeUi({ verbose: !!a.verbose })
|
|
126
|
+
const needsFolder = ['dev', 'install', 'check'].includes(cmd)
|
|
127
|
+
if (needsFolder && !folderArg) {
|
|
128
|
+
ui.error(`kamoji ${cmd} needs the mini app folder, e.g. kamoji ${cmd} ./my-app`)
|
|
129
|
+
return 2
|
|
130
|
+
}
|
|
131
|
+
const folder = folderArg ? path.resolve(folderArg) : null
|
|
132
|
+
if (folder && !fs.statSync(folder, { throwIfNoEntry: false })?.isDirectory()) {
|
|
133
|
+
ui.error(`${folderArg} is not a folder.`, 'Give the folder that holds manifest.json (unzip a .zip first).')
|
|
134
|
+
return 2
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (cmd === 'check') {
|
|
138
|
+
const r = checkApp(folder, { lua: !a['no-lua'] })
|
|
139
|
+
if (a.json) console.log(JSON.stringify({ app: r.appId, bytes: r.bytes, files: r.files.length, problems: r.problems }, null, 2))
|
|
140
|
+
else {
|
|
141
|
+
printProblems(ui, r)
|
|
142
|
+
if (!r.errors.length) ui.ok(`${r.appId}: ${r.files.length} file(s), ${kb(r.bytes)}, ${r.warnings.length ? `${r.warnings.length} warning(s)` : 'no problems'}.`)
|
|
143
|
+
else ui.error(`${r.errors.length} problem(s).`)
|
|
144
|
+
}
|
|
145
|
+
return r.errors.length ? 1 : 0
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
if (!['dev', 'install', 'apps', 'shot', 'logs', 'forget'].includes(cmd)) {
|
|
149
|
+
ui.error(`unknown command "${cmd}"`)
|
|
150
|
+
console.log(HELP)
|
|
151
|
+
return 2
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const dev = new DevSession({
|
|
155
|
+
folder,
|
|
156
|
+
ui,
|
|
157
|
+
connector: bleConnector(a.device, ui),
|
|
158
|
+
keys: keyStore,
|
|
159
|
+
reboot: !!a.reboot,
|
|
160
|
+
lua: !a['no-lua'],
|
|
161
|
+
})
|
|
162
|
+
const shotsDir = path.resolve(a.out ?? 'kamoji-shots')
|
|
163
|
+
let code = 0
|
|
164
|
+
const stop = async (c) => {
|
|
165
|
+
await dev.close().catch(() => undefined)
|
|
166
|
+
process.exit(c)
|
|
167
|
+
}
|
|
168
|
+
process.on('SIGINT', () => {
|
|
169
|
+
process.stdout.write('\n')
|
|
170
|
+
stop(130)
|
|
171
|
+
})
|
|
172
|
+
try {
|
|
173
|
+
if (cmd === 'logs') {
|
|
174
|
+
if (a.ble) throw new KamojiError('usb', 'kamoji logs reads the USB log: drop --ble.')
|
|
175
|
+
dev.appId = a.app ?? null
|
|
176
|
+
dev.serial = await openSerial({ ...a, usb: true }, ui, (l) => dev.logLine(l))
|
|
177
|
+
if (!dev.appId && !a.verbose) ui.info('Showing app lines, errors and crashes; add --verbose for every line, --app <id> to follow one app.')
|
|
178
|
+
await new Promise(() => undefined) // until Ctrl-C
|
|
179
|
+
}
|
|
180
|
+
if (cmd === 'apps') {
|
|
181
|
+
await dev.connect()
|
|
182
|
+
const list = dev.lastList
|
|
183
|
+
for (const app of list.apps)
|
|
184
|
+
ui.info(
|
|
185
|
+
`${app.ok ? `mode ${String(list.modes[app.id]).padEnd(3)}` : 'cannot run'} ${app.id} ${app.version} ${app.name}` +
|
|
186
|
+
`${app.bytes !== undefined ? ` ${kb(app.bytes)}` : ''}${app.reason ? ` (${app.reason})` : ''}`,
|
|
187
|
+
)
|
|
188
|
+
if (!list.apps.length) ui.info('No mini apps on this Kamoji.')
|
|
189
|
+
} else if (cmd === 'shot') {
|
|
190
|
+
dev.serial = await openSerial(a, ui, () => undefined)
|
|
191
|
+
await dev.screenshot(shotsDir)
|
|
192
|
+
} else if (cmd === 'forget') {
|
|
193
|
+
await dev.connect()
|
|
194
|
+
const { key } = loadOrCreateKey(dev.conn.board)
|
|
195
|
+
const left = await dev.session.forget(key)
|
|
196
|
+
deleteKey(dev.conn.board)
|
|
197
|
+
ui.ok(left >= 0 ? `Kamoji forgot this computer (${left} trusted device(s) left); key deleted.` : 'Kamoji did not know this key; key deleted.')
|
|
198
|
+
} else if (cmd === 'install' || (cmd === 'dev' && a.once)) {
|
|
199
|
+
dev.serial = await openSerial(a, ui, (l) => dev.logLine(l))
|
|
200
|
+
code = (await dev.deploy({ force: true })) ? 0 : 1
|
|
201
|
+
if (code === 0 && dev.serial) await new Promise((r) => setTimeout(r, 3000)) // the app's first log lines
|
|
202
|
+
} else if (cmd === 'dev') {
|
|
203
|
+
code = await watchLoop(dev, a, ui, folder, shotsDir)
|
|
204
|
+
}
|
|
205
|
+
} catch (e) {
|
|
206
|
+
if (e instanceof KamojiError) ui.error(e.message, e.hint)
|
|
207
|
+
else ui.error(e?.stack ?? String(e))
|
|
208
|
+
code = 1
|
|
209
|
+
}
|
|
210
|
+
await stop(code)
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
async function watchLoop(dev, a, ui, folder, shotsDir) {
|
|
214
|
+
const { Reloader, watchFolder } = await import('./watch.js')
|
|
215
|
+
dev.watching = true
|
|
216
|
+
dev.serial = await openSerial(a, ui, (l) => dev.logLine(l))
|
|
217
|
+
const reload = new Reloader(async () => {
|
|
218
|
+
try {
|
|
219
|
+
await dev.deploy()
|
|
220
|
+
} catch (e) {
|
|
221
|
+
if (e instanceof KamojiError) ui.error(e.message, e.hint)
|
|
222
|
+
else ui.error(e?.message ?? String(e))
|
|
223
|
+
}
|
|
224
|
+
})
|
|
225
|
+
await reload.fire()
|
|
226
|
+
watchFolder(folder, () => reload.trigger())
|
|
227
|
+
ui.info(`Watching ${folder}: save a file to reload. Enter = install again, o = open, s = screenshot, b = restart Kamoji, q = quit.`)
|
|
228
|
+
// Keys: single keypresses in a terminal (no Enter needed); one line per command when stdin is a pipe
|
|
229
|
+
// (KAMOJI_KEYS, scripts and tests). q / Ctrl-C always quit, even during an install.
|
|
230
|
+
let busy = Promise.resolve()
|
|
231
|
+
const quit = async () => {
|
|
232
|
+
ui.info('Bye.')
|
|
233
|
+
await Promise.race([dev.close().catch(() => undefined), new Promise((r) => setTimeout(r, 2000))])
|
|
234
|
+
if (process.stdin.isTTY) process.stdin.setRawMode(false)
|
|
235
|
+
process.exit(0)
|
|
236
|
+
}
|
|
237
|
+
const handle = (k) => {
|
|
238
|
+
if (k === 'q') return quit()
|
|
239
|
+
busy = busy.then(async () => {
|
|
240
|
+
try {
|
|
241
|
+
if (k === '' || k === 'r') {
|
|
242
|
+
dev.lastHash = null
|
|
243
|
+
await reload.fire()
|
|
244
|
+
} else if (k === 'o') {
|
|
245
|
+
await dev.connect()
|
|
246
|
+
await dev.open()
|
|
247
|
+
} else if (k === 's') await dev.screenshot(shotsDir)
|
|
248
|
+
else if (k === 'b') {
|
|
249
|
+
await dev.connect()
|
|
250
|
+
ui.info('Restarting Kamoji…')
|
|
251
|
+
await dev.restart()
|
|
252
|
+
} else ui.info('Enter = install again, o = open, s = screenshot, b = restart Kamoji, q = quit.')
|
|
253
|
+
} catch (e) {
|
|
254
|
+
ui.error(e?.message ?? String(e), e?.hint)
|
|
255
|
+
}
|
|
256
|
+
})
|
|
257
|
+
}
|
|
258
|
+
if (process.stdin.isTTY && !process.env.KAMOJI_KEYS) {
|
|
259
|
+
readline.emitKeypressEvents(process.stdin)
|
|
260
|
+
process.stdin.setRawMode(true)
|
|
261
|
+
process.stdin.on('keypress', (str, key) => {
|
|
262
|
+
if (key?.ctrl && (key.name === 'c' || key.name === 'd')) return void quit()
|
|
263
|
+
if (key?.name === 'return' || key?.name === 'enter') return void handle('')
|
|
264
|
+
if (typeof str === 'string' && str.length === 1) handle(str.toLowerCase())
|
|
265
|
+
})
|
|
266
|
+
} else if (process.env.KAMOJI_KEYS) {
|
|
267
|
+
const rl = readline.createInterface({ input: process.stdin })
|
|
268
|
+
rl.on('line', (line) => handle(line.trim().toLowerCase()))
|
|
269
|
+
}
|
|
270
|
+
return new Promise(() => undefined) // until q or Ctrl-C
|
|
271
|
+
}
|