@geastack/cli 0.1.92 → 0.1.93

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geastack/cli",
3
- "version": "0.1.92",
3
+ "version": "0.1.93",
4
4
  "description": "Command-line front door for GeaStack apps, targets, and local toolchains.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -109,7 +109,10 @@ function macUsbCalloutPortsForSerial(serial, ioreg = runIoreg) {
109
109
  for (const line of output.split(/\r?\n/)) {
110
110
  const node = line.match(/^([\s|]*)[+\\-]*o\s+/)
111
111
  if (node) {
112
- const depth = (node[1].match(/\|/g) || []).length
112
+ // The column of `+-o` is the depth. Counting `|` is not: ioreg draws the
113
+ // last child's subtree with spaces, so a callout under a device's last
114
+ // interface would look shallower than the device holding its serial.
115
+ const depth = node[1].length
113
116
  while (stack.length > 0 && stack[stack.length - 1].depth >= depth) stack.pop()
114
117
  stack.push({ depth, serial: '' })
115
118
  continue
@@ -144,7 +147,10 @@ export function listMacUsbCalloutPorts(ioreg = runIoreg) {
144
147
  for (const line of output.split(/\r?\n/)) {
145
148
  const node = line.match(/^([\s|]*)[+\\-]*o\s+/)
146
149
  if (node) {
147
- const depth = (node[1].match(/\|/g) || []).length
150
+ // The column of `+-o` is the depth. Counting `|` is not: ioreg draws the
151
+ // last child's subtree with spaces, so a callout under a device's last
152
+ // interface would look shallower than the device holding its serial.
153
+ const depth = node[1].length
148
154
  while (stack.length > 0 && stack[stack.length - 1].depth >= depth) stack.pop()
149
155
  stack.push({ depth, serial: '', product: '' })
150
156
  continue
@@ -183,8 +189,18 @@ function resolveMacUsbSerialPort(serial, ioreg = runIoreg) {
183
189
  throw new Error(`Could not map USB serial ${serial} to a /dev/cu.* port. Check that the board is attached.`)
184
190
  }
185
191
 
186
- export function resolveUsbSerialPort({ serial }, { platform = process.platform, ioreg = runIoreg } = {}) {
192
+ export function resolveUsbSerialPort({ serial }, { platform = process.platform, ioreg = runIoreg, env = process.env } = {}) {
187
193
  if (!serial) throw new Error('A USB serial number is required to locate the board; /dev paths are not accepted.')
194
+ // GEA_SERIAL_DEVICES replaces OS enumeration everywhere (see detectSerialDevices);
195
+ // resolution honors it with the same exact-serial rule, so a declared device list
196
+ // can never map one board's serial onto another's port.
197
+ if (env.GEA_SERIAL_DEVICES) {
198
+ const needle = normalizedSerial(serial)
199
+ const matches = detectSerialDevices({ env }).filter((device) => device.serial && normalizedSerial(device.serial) === needle)
200
+ if (matches.length === 1) return matches[0].path
201
+ if (matches.length > 1) throw new Error([`USB serial ${serial} maps to multiple ports:`, ...matches.map((device) => ` ${device.path}`)].join('\n'))
202
+ throw new Error(`Could not map USB serial ${serial} to a port in GEA_SERIAL_DEVICES. Check that the board is attached.`)
203
+ }
188
204
  if (platform === 'linux') {
189
205
  const matches = linuxSerialByIdCandidates(serial)
190
206
  if (matches.length === 1) return realpathSync(matches[0])
@@ -225,7 +241,8 @@ export async function waitForSerialPort({
225
241
  pollSeconds = 1,
226
242
  log = (line) => process.stderr.write(`${line}\n`),
227
243
  resolver = resolveUsbSerialPort,
228
- portPresent = serialPortPresent
244
+ portPresent = serialPortPresent,
245
+ env = process.env
229
246
  } = {}) {
230
247
  const startedAt = Date.now()
231
248
  let nextLog = startedAt
@@ -234,14 +251,14 @@ export async function waitForSerialPort({
234
251
  if (portPresent(port)) {
235
252
  if (!serial) return port
236
253
  try {
237
- if (resolver({ serial }) === port) return port
254
+ if (resolver({ serial }, { env }) === port) return port
238
255
  } catch {
239
256
  // An explicit path does not override the registered board identity.
240
257
  }
241
258
  }
242
259
  } else if (serial) {
243
260
  try {
244
- const resolved = resolver({ serial })
261
+ const resolved = resolver({ serial }, { env })
245
262
  if (resolved && portPresent(resolved)) return resolved
246
263
  } catch {
247
264
  // not attached yet
@@ -161,7 +161,7 @@ export async function cleanCommand(ctx, parsed, rest, options) {
161
161
  async function flashEsp32(ctx, parsed, rest, options, selection, { monitor }) {
162
162
  const base = io(parsed, options)
163
163
  const env = createChildEnv(ctx, base.env)
164
- const idf = requireEspIdf(env, base.stdout)
164
+ const idf = requireEspIdf(env, base.stdout, selection)
165
165
  const flashEnv = idf.env
166
166
  const opts = flashOptions(flashEnv, { idf, selection, manualBoot: flag(parsed, 'manual-boot'), noReset: option(parsed, 'reset') === false, baud: option(parsed, 'flash-baud', '') })
167
167
  const common = { idf, selection, options: opts, port: selection.port, env: flashEnv, dryRun: base.dryRun, verbose: flag(parsed, 'verbose'), stdout: base.stdout, stderr: base.stderr }
@@ -36,7 +36,7 @@ export async function openDevice({ selection, transport, host = '', port = '', e
36
36
  if (!selection.usbSerial && !port) {
37
37
  fail(`Board '${selection.boardName || selection.target}' has no transports.usbSerial.serial; use --transport wifi or add the USB serial.`, ExitCode.usage)
38
38
  }
39
- const devicePath = await waitForSerialPort({ port, serial: selection.usbSerial, timeoutSeconds: waitSeconds, label: 'USB serial port', log: stderr })
39
+ const devicePath = await waitForSerialPort({ port, serial: selection.usbSerial, timeoutSeconds: waitSeconds, label: 'USB serial port', log: stderr, env })
40
40
  const serial = await SerialDevice.open({ path: devicePath, baudRate: serialBaudRate(selection, env), trace, stderr })
41
41
  return new UsbDevice(serial, { stderr })
42
42
  }
@@ -92,13 +92,47 @@ export class SerialDevice {
92
92
 
93
93
  async writeLine(line) {
94
94
  const data = `${line.replace(/[\r\n]+$/, '')}\n`
95
- await new Promise((resolve, reject) => this.port.write(data, (error) => (error ? reject(error) : resolve())))
96
- await new Promise((resolve) => this.port.drain(() => resolve()))
95
+ await this.writeRaw(data)
97
96
  }
98
97
 
99
98
  async writeRaw(data) {
100
- await new Promise((resolve, reject) => this.port.write(data, (error) => (error ? reject(error) : resolve())))
101
- await new Promise((resolve) => this.port.drain(() => resolve()))
99
+ if (this.error) throw this.error
100
+ if (this.closed) throw new Error(`serial device ${this.path} is closed`)
101
+ // A USB removal can leave write/drain callbacks permanently pending.
102
+ // Keep a referenced deadline and reject on lifecycle events so callers can
103
+ // still release remote resources when the physical transport disappears.
104
+ await new Promise((resolve, reject) => {
105
+ let settled = false
106
+ const finish = (error) => {
107
+ if (settled) return
108
+ settled = true
109
+ clearTimeout(timer)
110
+ this.port.removeListener('close', closed)
111
+ this.port.removeListener('error', failed)
112
+ if (error) reject(error)
113
+ else resolve()
114
+ }
115
+ const closed = () => finish(new Error(`serial device ${this.path} closed during write`))
116
+ const failed = (error) => finish(error)
117
+ const timer = setTimeout(() => finish(new Error(`serial write timed out for ${this.path}`)), 5000)
118
+ this.port.once('close', closed)
119
+ this.port.once('error', failed)
120
+ try {
121
+ this.port.write(data, (error) => {
122
+ if (settled) return
123
+ if (error) finish(error)
124
+ else {
125
+ try {
126
+ this.port.drain((error) => finish(error))
127
+ } catch (error) {
128
+ finish(error)
129
+ }
130
+ }
131
+ })
132
+ } catch (error) {
133
+ finish(error)
134
+ }
135
+ })
102
136
  }
103
137
 
104
138
  async readLine(timeoutMs) {
@@ -9,6 +9,7 @@ import { appCmakeMeta, appCmakeLdFragments, appTargetConfig, appTargetPaths } fr
9
9
  import { quietSteps, runQuiet } from '../run.mjs'
10
10
  import { resolveAppCapabilities, withRendererFeatureDefines } from './capabilities.mjs'
11
11
  import { activateEspIdf, idfPyCommand } from './idf-env.mjs'
12
+ import { espIdfVersionForTarget } from './idf-version.mjs'
12
13
  import { Sdkconfig, prepareBuildLocalSdkconfig } from './sdkconfig.mjs'
13
14
  import { writePartitionTable } from './partitions-from-manifest.mjs'
14
15
  import { listAppSources } from './source-set.mjs'
@@ -48,15 +49,19 @@ export function buildImages(buildDir) {
48
49
  }
49
50
  }
50
51
 
51
- export function requireEspIdf(env, log) {
52
+ export function requireEspIdf(env, log, selection = null) {
53
+ const defaultVersion = espIdfVersionForTarget(selection?.target)
52
54
  let idf
53
55
  try {
54
- idf = activateEspIdf({ env, log })
56
+ idf = activateEspIdf({ env, log, defaultVersion })
55
57
  } catch (error) {
56
58
  fail(error.message, ExitCode.missingDependency)
57
59
  }
58
60
  if (!idf) {
59
- fail('ESP-IDF was not found. Install it and set IDF_PATH (or place it under ~/esp or ~/esp32).', ExitCode.missingDependency)
61
+ fail(
62
+ `ESP-IDF ${defaultVersion} was not found${selection?.target ? ` for target '${selection.target}'` : ''}. Install it under ~/esp32/esp-idf-v${defaultVersion} and run its install.sh (install.bat on Windows), or set IDF_PATH to another installation.`,
63
+ ExitCode.missingDependency
64
+ )
60
65
  }
61
66
  return idf
62
67
  }
@@ -549,7 +554,7 @@ function runInTarget(command, args, { cwd, env, dryRun, verbose, label, logFile,
549
554
  // system's responsibility. This retains Ninja's sub-second no-op.
550
555
  export async function ensureConfigured({ idf, prepared, env, dryRun = false, verbose = false, stdout, stderr = console.error }) {
551
556
  const signatureFile = path.join(prepared.buildDir, '.gea-configure-args')
552
- const signature = [`-DSDKCONFIG=${prepared.sdkconfigFile}`, `-DSDKCONFIG_DEFAULTS=${prepared.defaultsArg || prepared.defaultsFile}`, ...prepared.idfArgs, ...(prepared.sourceSet || [])].join('\n') + '\n'
557
+ const signature = [`IDF_PATH=${idf.idfDir}`, `IDF_PYTHON_ENV_PATH=${idf.pythonEnv}`, `-DSDKCONFIG=${prepared.sdkconfigFile}`, `-DSDKCONFIG_DEFAULTS=${prepared.defaultsArg || prepared.defaultsFile}`, ...prepared.idfArgs, ...(prepared.sourceSet || [])].join('\n') + '\n'
553
558
  if (existsSync(path.join(prepared.buildDir, 'CMakeCache.txt')) && existsSync(signatureFile) && readFileSync(signatureFile, 'utf8') === signature) {
554
559
  return false
555
560
  }
@@ -623,7 +628,7 @@ export async function buildEsp32Firmware({ ctx, selection, app = null, env = ctx
623
628
  // dim line; the spinner labels name each phase.
624
629
  const quiet = quietSteps(env, verbose)
625
630
  const detail = quiet ? () => {} : stdout
626
- const idf = requireEspIdf(env, detail)
631
+ const idf = requireEspIdf(env, detail, selection)
627
632
  const prepared = prepareEsp32Build({ ctx, selection, app, env: idf.env, log: detail, bleOta, dryRun })
628
633
  prepared.targetDir = selection.targetDir
629
634
  if (quiet) hint(stdout, buildSummaryLine(idf, selection, prepared.capabilities))
@@ -70,7 +70,7 @@ export async function runEsptoolOverUsb({ idf, selection, options, args, port =
70
70
  }
71
71
  const flashPort = dryRun
72
72
  ? port || `<usb serial ${selection.usbSerial}>`
73
- : await waitForSerialPort({ port, serial: selection.usbSerial, timeoutSeconds: remaining, label: 'ESP32 USB flash port', log: stderr })
73
+ : await waitForSerialPort({ port, serial: selection.usbSerial, timeoutSeconds: remaining, label: 'ESP32 USB flash port', log: stderr, env })
74
74
  if (options.before === 'no-reset') {
75
75
  stdout('Manual boot mode: hold BOOT/IO0, reset or power-cycle the board, then keep BOOT held until esptool connects.')
76
76
  stdout('Manual boot mode: esptool will not toggle reset before connecting.')
@@ -43,13 +43,38 @@ function compareVersions(a, b) {
43
43
  return 0
44
44
  }
45
45
 
46
- // Where an ESP-IDF checkout may live. Explicit settings win; otherwise the
47
- // newest install under the conventional directories is used, because the
48
- // firmware tracks the current IDF major (older ones do not compile it).
49
- export function findEspIdf(env = process.env, home = os.homedir()) {
50
- const explicit = [env.IDF_PATH, envExportDir(env.GEA_EMBEDDED_IDF_EXPORT), envExportDir(env.ESP_IDF_EXPORT)]
46
+ // A checkout of an unreleased IDF line (master, a release candidate) is named
47
+ // for it: `esp-idf-v6.2-dev`, `esp-idf-v6.1-rc1`. Its version.cmake already
48
+ // reads like the release, so the name is the only thing that tells it apart.
49
+ function isPrereleaseIdf(dir) {
50
+ return /-(dev|rc\d*|beta\d*|master)$/i.test(path.basename(dir))
51
+ }
52
+
53
+ function meetsMinimum(dir, minimum) {
54
+ if (!minimum) return true
55
+ const want = minimum.split('.').map((part) => Number(part) || 0)
56
+ return compareVersions(versionKey(dir), [want[0] || 0, want[1] || 0, 0]) >= 0
57
+ }
58
+
59
+ function matchesDefaultVersion(dir, defaultVersion) {
60
+ if (!defaultVersion) return true
61
+ const version = espIdfVersion(dir)
62
+ if (defaultVersion.endsWith('-dev')) {
63
+ return version?.majorMinor === defaultVersion.slice(0, -4) && /-dev$/i.test(path.basename(dir))
64
+ }
65
+ return version?.full === defaultVersion && !isPrereleaseIdf(dir)
66
+ }
67
+
68
+ // Generic discovery honours explicit settings and otherwise prefers the
69
+ // newest stable installation. Callers can request a minimum version instead.
70
+ // Builds provide an exact defaultVersion for automatic discovery. IDF_PATH
71
+ // overrides that default; export-script hints must still match the target.
72
+ export function findEspIdf(env = process.env, home = os.homedir(), { minVersion = '', defaultVersion = '' } = {}) {
73
+ const accepts = (dir) => meetsMinimum(dir, minVersion) && matchesDefaultVersion(dir, defaultVersion)
74
+ if (isIdfDir(env.IDF_PATH) && meetsMinimum(env.IDF_PATH, minVersion)) return path.resolve(env.IDF_PATH)
75
+ const explicit = [envExportDir(env.GEA_EMBEDDED_IDF_EXPORT), envExportDir(env.ESP_IDF_EXPORT)]
51
76
  for (const candidate of explicit) {
52
- if (isIdfDir(candidate)) return path.resolve(candidate)
77
+ if (isIdfDir(candidate) && accepts(candidate)) return path.resolve(candidate)
53
78
  }
54
79
  const roots = [path.join(home, 'esp'), path.join(home, 'esp32'), home]
55
80
  const found = []
@@ -72,7 +97,9 @@ export function findEspIdf(env = process.env, home = os.homedir()) {
72
97
  }
73
98
  if (found.length === 0) return ''
74
99
  found.sort((a, b) => compareVersions(versionKey(b), versionKey(a)))
75
- return found[0]
100
+ if (defaultVersion) return found.find(accepts) || ''
101
+ if (minVersion) return found.find((dir) => meetsMinimum(dir, minVersion)) || ''
102
+ return found.find((dir) => !isPrereleaseIdf(dir)) || found[0]
76
103
  }
77
104
 
78
105
  function envExportDir(exportScript) {
@@ -92,9 +119,10 @@ export function idfVenvPython(pythonEnv) {
92
119
  }
93
120
 
94
121
  export function findIdfPythonEnv(idfDir, env = process.env, home = os.homedir()) {
95
- const explicit = env.IDF_PYTHON_ENV_PATH
96
- if (explicit && existsSync(idfVenvPython(explicit))) return explicit
97
122
  const version = espIdfVersion(idfDir)?.majorMinor
123
+ const explicit = env.IDF_PYTHON_ENV_PATH
124
+ const explicitVersion = explicit && path.basename(explicit).match(/^idf(\d+\.\d+)_py/)?.[1]
125
+ if (explicit && (!explicitVersion || explicitVersion === version) && existsSync(idfVenvPython(explicit))) return explicit
98
126
  if (!version) return ''
99
127
  const envRoot = path.join(env.IDF_TOOLS_PATH || path.join(home, '.espressif'), 'python_env')
100
128
  let entries = []
@@ -130,10 +158,15 @@ const activationCache = new Map()
130
158
  // The tool export is cached per installation; the caller's environment is
131
159
  // layered on fresh every time so per-invocation settings (jobs, variants,
132
160
  // flash baud) are never frozen into a cached activation.
133
- export function activateEspIdf({ env = process.env, home = os.homedir(), log = () => {} } = {}) {
134
- const idfDir = findEspIdf(env, home)
161
+ export function activateEspIdf({ env = process.env, home = env.HOME || env.USERPROFILE || os.homedir(), log = () => {}, minVersion = '', defaultVersion = '' } = {}) {
162
+ const idfDir = findEspIdf(env, home, { minVersion, defaultVersion })
135
163
  if (!idfDir) return null
136
- const pythonEnv = findIdfPythonEnv(idfDir, env, home)
164
+ // A venv exported by a different active checkout belongs to that checkout.
165
+ const activeIdf = env.IDF_PATH || envExportDir(env.GEA_EMBEDDED_IDF_EXPORT) || envExportDir(env.ESP_IDF_EXPORT)
166
+ const pythonEnvSettings = defaultVersion && activeIdf && path.resolve(activeIdf) !== idfDir
167
+ ? { ...env, IDF_PYTHON_ENV_PATH: '' }
168
+ : env
169
+ const pythonEnv = findIdfPythonEnv(idfDir, pythonEnvSettings, home)
137
170
  if (!pythonEnv) {
138
171
  const envRoot = path.join(env.IDF_TOOLS_PATH || path.join(home, '.espressif'), 'python_env')
139
172
  throw new Error(
@@ -149,7 +182,7 @@ export function activateEspIdf({ env = process.env, home = os.homedir(), log = (
149
182
  exported = parseKeyValueExport(
150
183
  execFileSync(python, [idfToolsPy, 'export', '--format', 'key-value'], {
151
184
  encoding: 'utf8',
152
- env: { ...env, IDF_PATH: idfDir },
185
+ env: { ...env, IDF_PATH: idfDir, IDF_PYTHON_ENV_PATH: pythonEnv },
153
186
  stdio: ['ignore', 'pipe', 'ignore']
154
187
  })
155
188
  )
@@ -157,8 +190,8 @@ export function activateEspIdf({ env = process.env, home = os.homedir(), log = (
157
190
  throw new Error(`ESP-IDF tool export failed for ${idfDir}: ${error.message}`)
158
191
  }
159
192
  activationCache.set(cacheKey, exported)
160
- log(`Using ESP-IDF ${espIdfVersion(idfDir)?.full || ''} at ${idfDir} (python env ${pythonEnv})`)
161
193
  }
194
+ log(`Using ESP-IDF ${espIdfVersion(idfDir)?.full || ''} at ${idfDir} (python env ${pythonEnv})`)
162
195
  const callerPath = envPath(env)
163
196
  const exportedPath = (exported.PATH || '').replace(/\$PATH|%PATH%/g, callerPath)
164
197
  return {
@@ -15,6 +15,11 @@ const VERSION_IN_TEXT = /v?(\d+)\.(\d+)\.(\d+)/i
15
15
  // Bump this alongside board-script updates.
16
16
  export const DEFAULT_ESP_IDF_VERSION = 'v6.0.2'
17
17
 
18
+ // Automatic build selection is target-specific; IDF_PATH can override it.
19
+ export function espIdfVersionForTarget(target) {
20
+ return target === 'esp32-s31-espressif-mosaico' ? '6.2-dev' : DEFAULT_ESP_IDF_VERSION.slice(1)
21
+ }
22
+
18
23
  const GITHUB_LATEST_RELEASE_URL = 'https://api.github.com/repos/espressif/esp-idf/releases/latest'
19
24
 
20
25
  // Parses a strict `vX.Y.Z` release tag. Returns null for anything else,