@open-mercato/starter 0.10.1-develop.7983.1.fd91207efe → 0.10.1-develop.7990.1.82d0a183c5

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.
@@ -0,0 +1,201 @@
1
+ // Compact setup output, using the same keyboard and compact log hints as dev.
2
+ // Keep this build-free: setup runs before the workspace dependencies exist.
3
+ import { StringDecoder } from 'node:string_decoder'
4
+ import { format } from 'node:util'
5
+ import fs from 'node:fs'
6
+ import path from 'node:path'
7
+
8
+ const MAX_LINES = 200
9
+ const MAX_LINE_LENGTH = 4096
10
+
11
+ export function createSetupLogs({
12
+ input = process.stdin,
13
+ output = process.stdout,
14
+ env = process.env,
15
+ verbose = false,
16
+ nonInteractive = false,
17
+ repoRoot = null,
18
+ name = 'setup',
19
+ onInterrupt = () => process.kill(process.pid, 'SIGINT'),
20
+ } = {}) {
21
+ const interactive = Boolean(input.isTTY && output.isTTY
22
+ && env.CI !== 'true' && env.TERM !== 'dumb' && env.MERCATO_DEV_OUTPUT !== 'verbose'
23
+ && !verbose && !nonInteractive)
24
+ const colored = interactive && !env.NO_COLOR
25
+ let active = false
26
+ let started = false
27
+ let fileInitialized = false
28
+ let logFile = null
29
+ let fileFailed = false
30
+ let activity = null
31
+ let visible = !interactive
32
+ let previousRaw = false
33
+ let previousFlowing = false
34
+ let lines = []
35
+ let partial = ''
36
+ let visiblePartial = false
37
+ let rawLineStart = true
38
+ const decoder = new StringDecoder('utf8')
39
+
40
+ const write = (value) => output.write(value)
41
+ const tint = (code, value) => colored ? `\u001b[${code}m${value}\u001b[0m` : value
42
+
43
+
44
+ function writeRaw(text) {
45
+ let formatted = ''
46
+ for (const part of text.split(/(\r\n|\r|\n)/)) {
47
+ if (part === '\n' || part === '\r' || part === '\r\n') { formatted += part; rawLineStart = true }
48
+ else if (part) { formatted += (rawLineStart ? ' ' : '') + part; rawLineStart = false }
49
+ }
50
+ write(formatted)
51
+ }
52
+
53
+ function reportFileFailure() {
54
+ if (fileFailed) return
55
+ fileFailed = true
56
+ activity?.pause()
57
+ write(' ⚠️ Could not save setup logs; terminal output is still available.\n')
58
+ if (active && !visible) activity?.resume()
59
+ }
60
+
61
+ function initializeFile() {
62
+ if (fileInitialized) return
63
+ fileInitialized = true
64
+ if (!repoRoot || ['0', 'false'].includes(env.OM_DEV_LOG_TEE)) return
65
+ try {
66
+ const directory = env.OM_DEV_LOG_DIR?.trim()
67
+ ? path.resolve(repoRoot, env.OM_DEV_LOG_DIR.trim())
68
+ : path.join(repoRoot, '.mercato', 'logs')
69
+ const defaultId = `${new Date().toISOString().toLowerCase().replace(/[:.]/g, '-')}-pid${process.pid}`
70
+ // Run IDs are filenames, never paths, including when supplied by a shell.
71
+ const safe = (value) => String(value).replace(/[^A-Za-z0-9._-]/g, '-').slice(0, 160)
72
+ const runId = safe(env.OM_DEV_RUN_ID?.trim() || defaultId)
73
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 })
74
+ const target = path.join(directory, `${runId}-${safe(name)}-raw.log`)
75
+ fs.appendFileSync(target, '', { mode: 0o600 })
76
+ logFile = target
77
+ } catch {
78
+ reportFileFailure()
79
+ }
80
+ }
81
+
82
+ function show(reason = 'Raw logs shown') {
83
+ if (!interactive || visible) return
84
+ activity?.pause()
85
+ visible = true
86
+ write(` 📖 ${reason} · press [d] to hide\n`)
87
+ rawLineStart = true
88
+ if (lines.length === 0 && !partial) {
89
+ write(' 📭 No buffered logs yet\n')
90
+ return
91
+ }
92
+ if (lines.length > 0) writeRaw(`${lines.join('\n')}\n`)
93
+ if (partial) writeRaw(partial)
94
+ visiblePartial = partial.length > 0
95
+ // Displayed output remains in terminal scrollback and in the full log
96
+ // file. Replay only new output collected while the panel was hidden.
97
+ lines = []
98
+ partial = ''
99
+ }
100
+
101
+ function onData(chunk) {
102
+ for (const key of String(chunk)) {
103
+ if (key === '\u0003') {
104
+ suspend()
105
+ onInterrupt()
106
+ return
107
+ }
108
+ if (key.toLowerCase() !== 'd') continue
109
+ if (visible) {
110
+ visible = false
111
+ if (visiblePartial) write('\n')
112
+ visiblePartial = false
113
+ rawLineStart = true
114
+ activity?.resume()
115
+ } else show()
116
+ }
117
+ }
118
+
119
+ function resume() {
120
+ if (!interactive || active) return
121
+ previousRaw = Boolean(input.isRaw)
122
+ previousFlowing = input.readableFlowing === true
123
+ input.setRawMode?.(true)
124
+ input.on('data', onData)
125
+ input.resume()
126
+ active = true
127
+ }
128
+
129
+ function suspend() {
130
+ activity?.pause()
131
+ if (!active) return
132
+ input.removeListener('data', onData)
133
+ input.setRawMode?.(previousRaw)
134
+ if (!previousFlowing) input.pause()
135
+ active = false
136
+ }
137
+
138
+ function persist(chunk) {
139
+ initializeFile()
140
+ if (logFile && !fileFailed) {
141
+ try {
142
+ // Synchronous appends avoid losing the last output when setup hands
143
+ // over to dev or a failing command exits immediately.
144
+ fs.appendFileSync(logFile, chunk)
145
+ } catch {
146
+ reportFileFailure()
147
+ }
148
+ }
149
+ }
150
+
151
+ function raw(chunk, displayChunk = chunk) {
152
+ persist(chunk)
153
+ if (!interactive) {
154
+ write(chunk)
155
+ return
156
+ }
157
+ const text = typeof displayChunk === 'string' ? displayChunk : decoder.write(displayChunk)
158
+ if (visible) {
159
+ if (text) { writeRaw(text); visiblePartial = !text.endsWith('\n') }
160
+ return
161
+ }
162
+ // Bound both completed lines and partial progress output. A process can
163
+ // emit megabytes without a newline; it must not grow the buffer forever.
164
+ const entries = `${partial}${text}`.split('\n')
165
+ partial = entries.pop().slice(-MAX_LINE_LENGTH)
166
+ if (entries.length > 0) {
167
+ lines = lines.concat(entries.slice(-MAX_LINES).map((line) => line.slice(-MAX_LINE_LENGTH))).slice(-MAX_LINES)
168
+ }
169
+ }
170
+
171
+ return {
172
+ interactive,
173
+ setActivity(next) {
174
+ activity?.stop()
175
+ activity = next
176
+ if (visible) activity?.pause()
177
+ else activity?.resume()
178
+ },
179
+ resumeActivity() { if (!visible && active) activity?.resume() },
180
+ get logFile() { return logFile },
181
+ start() {
182
+ if (started) return
183
+ started = true
184
+ initializeFile()
185
+ if (logFile && !fileFailed) write(` 📝 Verbose logs ${logFile}\n`)
186
+ if (interactive) write(`${tint('2', ' 📋 Press [d] to show or hide raw logs')}\n`)
187
+ process.once('exit', suspend)
188
+ resume()
189
+ },
190
+ stop() { activity?.stop(); activity = null; suspend(); process.removeListener('exit', suspend); started = false },
191
+ suspend,
192
+ resume,
193
+ raw,
194
+ show,
195
+ log(...args) {
196
+ const text = format(...args)
197
+ raw(`${text}\n`, `${text.replace(/^ {1,3}/gm, '')}\n`)
198
+ },
199
+ record(...args) { persist(`${format(...args)}\n`) },
200
+ }
201
+ }
package/src/steps.mjs CHANGED
@@ -3,7 +3,7 @@ import crypto from 'node:crypto'
3
3
  import fs from 'node:fs'
4
4
  import path from 'node:path'
5
5
 
6
- import { detectDocker, parseComposePsOutput, runCaptureSync, runCompose, runStreamingSync } from './compose.mjs'
6
+ import { detectDocker, parseComposePsOutput, runCaptureSync, runCompose, runStreaming } from './compose.mjs'
7
7
  import { captureInterceptionCas, findVendorCaBundles, harvestWindowsStoreCas, hostTrustEnv, probeTlsInterception, provisionDockerCerts, provisionRancherDesktopCa, summarizeProbeResults, writeCaBundle } from './certs.mjs'
8
8
  import { loadCompanyConfig, resolveCompanyCertBundles } from './company.mjs'
9
9
  import { CAPTURED_CA_BUNDLE, DEFAULT_OPENCODE_BASE_IMAGE, OPENCODE_SERVICE_IMAGE, STARTER_STATE_DIR, resolveStackPorts } from './constants.mjs'
@@ -13,7 +13,8 @@ import { addEnvValue, readEnvValue } from './env-file.mjs'
13
13
  import { describeInfraProblem, startInfra } from './infra.mjs'
14
14
  import { findUnhealthyServices } from './infra-preflight.mjs'
15
15
  import { ensureLlmProvider } from './providers.mjs'
16
- import { color, formatDuration, guideBox, statusLine, stepHeader } from './ui.mjs'
16
+ import { createSetupLogs } from './setup-logs.mjs'
17
+ import { color, createSpinner, formatDuration, guideBox, statusLine, stepHeader } from './ui.mjs'
17
18
 
18
19
  // The idempotent convergence pipeline behind `up`. Every step follows the same
19
20
  // contract so re-running is always safe and always cheap when nothing changed:
@@ -251,9 +252,9 @@ export function yarnInvocation(ctx, args) {
251
252
  : { command: 'yarn', args }
252
253
  }
253
254
 
254
- function runYarn(ctx, args) {
255
+ async function runYarn(ctx, args) {
255
256
  const invocation = yarnInvocation(ctx, args)
256
- const status = (ctx.runStreamingImpl ?? runStreamingSync)(invocation.command, invocation.args, { cwd: ctx.repoRoot, env: ctx.env })
257
+ const status = await (ctx.runStreamingImpl ?? runStreaming)(invocation.command, invocation.args, { cwd: ctx.repoRoot, env: ctx.env, logs: ctx.logs })
257
258
  if (status !== 0) {
258
259
  throw new Error(`yarn ${args.join(' ')} failed (exit ${status}) — fix the error above and re-run; completed steps are skipped.`)
259
260
  }
@@ -281,9 +282,9 @@ export const prerequisitesStep = {
281
282
  // Node exists (we are running on it), so yarn is ours to install: enable
282
283
  // corepack and activate the exact version pinned in package.json.
283
284
  const spec = JSON.parse(fs.readFileSync(path.join(ctx.repoRoot, 'package.json'), 'utf8')).packageManager.split('+')[0]
284
- const enable = runStreamingSync('corepack', ['enable'], { cwd: ctx.repoRoot, env: ctx.env })
285
+ const enable = await runStreaming('corepack', ['enable'], { cwd: ctx.repoRoot, env: ctx.env, logs: ctx.logs })
285
286
  if (enable !== 0) ctx.log('⚠️ corepack enable failed (PATH not writable?) — falling back to running yarn through corepack.')
286
- const prepare = runStreamingSync('corepack', ['prepare', spec, '--activate'], { cwd: ctx.repoRoot, env: ctx.env })
287
+ const prepare = await runStreaming('corepack', ['prepare', spec, '--activate'], { cwd: ctx.repoRoot, env: ctx.env, logs: ctx.logs })
287
288
  if (prepare !== 0) {
288
289
  throw new Error(`corepack prepare ${spec} failed. Behind a corporate proxy? Set HTTPS_PROXY and re-run — the starter provisions the corporate CA automatically in the next step; if this step itself is blocked, set COREPACK_NPM_REGISTRY to your internal mirror (see starters/company/).`)
289
290
  }
@@ -419,7 +420,7 @@ export const envFilesStep = {
419
420
  return { ok: false, detail: 'converging (never overwrites existing values)' }
420
421
  },
421
422
  async apply(ctx) {
422
- ensureEnvFiles(ctx.repoRoot, { log: (line) => ctx.log(` ${line}`), warn: (line) => ctx.log(` ⚠️ ${line}`), extraDefaults: ctx.company.env })
423
+ ensureEnvFiles(ctx.repoRoot, { log: (line) => ctx.log(` ${String(line).trimStart()}`), warn: (line) => ctx.log(` ⚠️ ${line}`), extraDefaults: ctx.company.env })
423
424
  },
424
425
  }
425
426
 
@@ -438,7 +439,7 @@ export const workspaceInstallStep = {
438
439
  if (ctx.company.mirrors.npmRegistry) {
439
440
  ctx.env = { ...ctx.env, COREPACK_NPM_REGISTRY: ctx.company.mirrors.npmRegistry, YARN_NPM_REGISTRY_SERVER: ctx.company.mirrors.npmRegistry }
440
441
  }
441
- runYarn(ctx, ['install'])
442
+ await runYarn(ctx, ['install'])
442
443
  writeState(ctx.repoRoot, 'install.hash', ctx.installHash)
443
444
  ctx.installChanged = true
444
445
  },
@@ -466,14 +467,15 @@ export const workspaceBuildStep = {
466
467
  // Mirrors the root `yarn build`: core only compiles `generated/**` into
467
468
  // dist/generated when it exists, which on a fresh clone is after `generate`.
468
469
  const run = ctx.runYarnImpl ?? runYarn
469
- run(ctx, ['build:packages'])
470
- run(ctx, ['generate'])
471
- run(ctx, ['build:packages'])
470
+ await run(ctx, ['build:packages'])
471
+ await run(ctx, ['generate'])
472
+ await run(ctx, ['build:packages'])
472
473
  },
473
474
  }
474
475
 
475
476
  export const llmProviderStep = {
476
477
  id: 'llm-provider',
478
+ interactive: true,
477
479
  expectation: 'waits for your input on first run; have an API key ready',
478
480
  title: 'AI provider (LLM API key)',
479
481
  async apply(ctx) {
@@ -483,7 +485,7 @@ export const llmProviderStep = {
483
485
  }, {
484
486
  skipPrompt: ctx.flags.skipLlmPrompt,
485
487
  nonInteractive: ctx.flags.nonInteractive,
486
- log: (line) => ctx.log(` ${line}`),
488
+ log: (line) => ctx.log(` ${String(line).trimStart()}`),
487
489
  warn: (line) => ctx.log(` ⚠️ ${line}`),
488
490
  })
489
491
  if (outcome === 'failed') {
@@ -508,15 +510,15 @@ export function resolveOpencodeBaseImage(repoRoot, env = process.env) {
508
510
  // Desktop) and therefore survives corporate TLS interception that breaks
509
511
  // build-stage egress; the thin build itself only COPYs project files.
510
512
  // --rebuild forces the thin rebuild (e.g. after yarn generate in prod mode).
511
- export function ensureOpencodeImage(ctx) {
513
+ export async function ensureOpencodeImage(ctx) {
512
514
  const baseImage = resolveOpencodeBaseImage(ctx.repoRoot, ctx.env)
513
515
  const baseExists = spawnSync('docker', ['image', 'inspect', baseImage], { stdio: 'ignore' }).status === 0
514
516
  if (baseExists) {
515
517
  ctx.log(` opencode base image: ${baseImage} (already present)`)
516
518
  } else {
517
519
  ctx.log(` pulling OpenCode base image ${baseImage} ...`)
518
- const pull = spawnSync('docker', ['pull', baseImage], { stdio: 'inherit' })
519
- if (pull.status !== 0) {
520
+ const pull = await (ctx.runStreamingImpl ?? runStreaming)('docker', ['pull', baseImage], { cwd: ctx.repoRoot, env: ctx.env, logs: ctx.logs })
521
+ if (pull !== 0) {
520
522
  throw new Error(`Could not pull the OpenCode base image ${baseImage}. Behind a proxy that blocks registry-1.docker.io? Set OPENCODE_BASE_IMAGE in .env to your internal mirror (build/push runbook: docker/opencode/BASE_IMAGE.md), then re-run.`)
521
523
  }
522
524
  }
@@ -526,13 +528,13 @@ export function ensureOpencodeImage(ctx) {
526
528
  return
527
529
  }
528
530
  ctx.log(` building ${OPENCODE_SERVICE_IMAGE} from ${baseImage} (project files only — no network) ...`)
529
- const build = spawnSync('docker', [
531
+ const build = await (ctx.runStreamingImpl ?? runStreaming)('docker', [
530
532
  'build',
531
533
  '-t', OPENCODE_SERVICE_IMAGE,
532
534
  '--build-arg', `OPENCODE_BASE_IMAGE=${baseImage}`,
533
535
  path.join(ctx.repoRoot, 'docker', 'opencode'),
534
- ], { stdio: 'inherit', cwd: ctx.repoRoot })
535
- if (build.status !== 0) {
536
+ ], { cwd: ctx.repoRoot, env: ctx.env, logs: ctx.logs })
537
+ if (build !== 0) {
536
538
  throw new Error('Local build of the OpenCode service image failed — see the output above, then re-run.')
537
539
  }
538
540
  }
@@ -561,6 +563,8 @@ export const infraUpStep = {
561
563
  const prepareOpencodeImage = ctx.ensureOpencodeImageImpl ?? ensureOpencodeImage
562
564
  const outcome = await (ctx.startInfraImpl ?? startInfra)(ctx.repoRoot, {
563
565
  profiles: ctx.flags.profiles,
566
+ env: ctx.env,
567
+ logs: ctx.logs,
564
568
  log: ctx.log,
565
569
  beforeUp: () => prepareOpencodeImage(ctx),
566
570
  })
@@ -633,7 +637,7 @@ export const databaseStep = {
633
637
  'or start over with a fresh database (DELETES all local data): yarn om reset',
634
638
  ].join('\n'))
635
639
  }
636
- runYarn(ctx, ['db:migrate'])
640
+ await runYarn(ctx, ['db:migrate'])
637
641
  writeState(ctx.repoRoot, ctx.dbMigrationsMarker, ctx.migrationsFingerprint)
638
642
  const applied = readAppliedMigrationModules(ctx)
639
643
  if (applied && applied.size > 0) {
@@ -652,7 +656,7 @@ export const databaseStep = {
652
656
  // to run the destructive --reinstall. An emptied volume (dbReinitialize)
653
657
  // has no users, so it seeds either way; the flag is left off there.
654
658
  const initArgs = ctx.dbReinitialize ? ['initialize'] : ['initialize', '--', '--skip-if-initialized']
655
- runYarn({ ...ctx, env: { ...ctx.env, OM_INIT_DEV_AUTOSTART: '1' } }, initArgs)
659
+ await runYarn({ ...ctx, env: { ...ctx.env, OM_INIT_DEV_AUTOSTART: '1' } }, initArgs)
656
660
  }
657
661
  writeState(ctx.repoRoot, ctx.dbMarker, new Date().toISOString())
658
662
  }
@@ -767,31 +771,63 @@ export async function createStepContext(repoRoot, { mode = 'hybrid', flags = {},
767
771
  }
768
772
 
769
773
  export async function runSteps(steps, ctx) {
770
- const active = steps.filter((step) => !step.appliesTo || step.appliesTo(ctx))
771
- let index = 0
772
- for (const step of active) {
773
- index += 1
774
- stepHeader(index, active.length, step.title, step.expectation, { log: ctx.log })
775
- const startedAt = Date.now()
776
- try {
777
- const checked = step.check ? await step.check(ctx) : { ok: false, detail: '' }
778
- if (checked.ok) {
779
- statusLine('ok', `${checked.detail || 'already satisfied'} ${color.dim('(skipped — already done)')}`, { log: ctx.log })
780
- continue
774
+ const originalLog = ctx.log
775
+ const logs = ctx.logs ?? createSetupLogs({ repoRoot: ctx.repoRoot, ...ctx.flags })
776
+ // Step summaries stay visible; routine details and child output share the
777
+ // foldable buffer. Keep mutations to ctx (env, markers) on the real context.
778
+ let spinner = null
779
+ const log = (...args) => { spinner?.pause(); originalLog(...args); logs.record(...args) }
780
+ const stopSpinner = () => {
781
+ spinner?.stop()
782
+ spinner = null
783
+ logs.setActivity?.(null)
784
+ }
785
+ ctx.logs = logs
786
+ logs.start()
787
+ try {
788
+ const active = steps.filter((step) => !step.appliesTo || step.appliesTo(ctx))
789
+ let index = 0
790
+ for (const step of active) {
791
+ index += 1
792
+ stepHeader(index, active.length, step.title, step.expectation, { log })
793
+ const startedAt = Date.now()
794
+ if (step.interactive) logs.suspend()
795
+ else if (logs.interactive) {
796
+ spinner = (ctx.createSpinnerImpl ?? createSpinner)('⚙️ working…', { startPaused: true, frames: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'] })
797
+ logs.setActivity?.(spinner)
781
798
  }
782
- if (checked.detail) statusLine('info', checked.detail, { log: ctx.log })
783
- if (!step.apply) continue
784
- await step.apply(ctx)
785
- statusLine('ok', `done ${color.dim(`in ${formatDuration(Date.now() - startedAt)}`)}`, { log: ctx.log })
786
- } catch (error) {
787
- if (error instanceof StepBlocked) {
788
- statusLine('fail', 'blocked — this starter proposes, it does not install system components', { log: ctx.log })
789
- guideBox('What to do next', error.guide, { log: ctx.log })
790
- return { ok: false, blockedStep: step.id }
799
+ ctx.log = step.interactive ? log : (...args) => logs.log(...args)
800
+ try {
801
+ const checked = step.check ? await step.check(ctx) : { ok: false, detail: '' }
802
+ if (checked.ok) {
803
+ statusLine('ok', `${checked.detail || 'already satisfied'} ${color.dim('(skipped — already done)')}`, { log })
804
+ continue
805
+ }
806
+ if (checked.detail) statusLine('info', checked.detail, { log })
807
+ if (!step.apply) continue
808
+ logs.resumeActivity?.()
809
+ await step.apply(ctx)
810
+ statusLine('ok', `done ${color.dim(`in ${formatDuration(Date.now() - startedAt)}`)}`, { log })
811
+ } catch (error) {
812
+ stopSpinner()
813
+ logs.show(`Setup stopped at ${step.title}`)
814
+ if (error instanceof StepBlocked) {
815
+ statusLine('fail', 'blocked — this starter proposes, it does not install system components', { log })
816
+ guideBox('What to do next', error.guide, { log })
817
+ return { ok: false, blockedStep: step.id }
818
+ }
819
+ statusLine('fail', error instanceof Error ? error.message : String(error), { log })
820
+ return { ok: false, failedStep: step.id }
821
+ } finally {
822
+ stopSpinner()
823
+ ctx.log = originalLog
824
+ if (step.interactive) logs.resume()
791
825
  }
792
- statusLine('fail', error instanceof Error ? error.message : String(error), { log: ctx.log })
793
- return { ok: false, failedStep: step.id }
794
826
  }
827
+ return { ok: true }
828
+ } finally {
829
+ stopSpinner()
830
+ ctx.log = originalLog
831
+ logs.stop()
795
832
  }
796
- return { ok: true }
797
833
  }
package/src/ui.mjs CHANGED
@@ -51,15 +51,15 @@ export function printBanner(subtitle, { log = console.log } = {}) {
51
51
 
52
52
  export function stepHeader(index, total, title, expectation, { log = console.log } = {}) {
53
53
  log('')
54
- log(`${color.bold(color.blue(`── Step ${index}/${total}`))} ${color.bold(title)}`)
55
- if (expectation) log(color.dim(` Expected: ${expectation}`))
54
+ log(` ${color.bold(color.blue(`── Step ${index}/${total}`))} ${color.bold(title)}`)
55
+ if (expectation) log(` ${color.bold(color.yellow('Expected:'))} ${expectation}`)
56
56
  }
57
57
 
58
58
  export const icons = {
59
- ok: color.green('OK'),
60
- warn: color.yellow('!!'),
61
- fail: color.red('XX'),
62
- info: color.cyan('--'),
59
+ ok: color.green('✅'),
60
+ warn: color.yellow('⚠️'),
61
+ fail: color.red('❌'),
62
+ info: color.cyan('ℹ️'),
63
63
  }
64
64
 
65
65
  export function statusLine(kind, message, { log = console.log } = {}) {
@@ -80,37 +80,58 @@ const SPINNER_FRAMES = ['|', '/', '-', '\\']
80
80
 
81
81
  // Spinner for long waits that produce no streamed output. In non-TTY contexts
82
82
  // it prints the label once and then only meaningful updates via update().
83
- export function createSpinner(label) {
83
+ export function createSpinner(label, {
84
+ output = process.stdout,
85
+ env = process.env,
86
+ log = console.log,
87
+ frames = SPINNER_FRAMES,
88
+ startPaused = false,
89
+ now = Date.now,
90
+ setIntervalImpl = setInterval,
91
+ clearIntervalImpl = clearInterval,
92
+ } = {}) {
84
93
  let frame = 0
85
94
  let currentLabel = label
86
95
  let timer = null
87
- const startedAt = Date.now()
96
+ let stopped = false
97
+ let rendered = false
98
+ const startedAt = now()
99
+ const animated = Boolean(output.isTTY && env.CI !== 'true' && env.TERM !== 'dumb')
88
100
 
89
101
  const render = () => {
90
- const elapsed = Math.round((Date.now() - startedAt) / 1000)
91
- process.stdout.write(`\r ${color.cyan(SPINNER_FRAMES[frame % SPINNER_FRAMES.length])} ${currentLabel} ${color.dim(`(${elapsed}s)`)} `)
102
+ const elapsed = Math.round((now() - startedAt) / 1000)
103
+ output.write(`\r ${color.cyan(frames[frame % frames.length])} ${currentLabel} ${color.dim(`(${elapsed}s)`)} `)
92
104
  frame += 1
105
+ rendered = true
93
106
  }
94
107
 
95
- if (isTty) {
96
- timer = setInterval(render, 120)
108
+ const pause = () => {
109
+ if (timer !== null) clearIntervalImpl(timer)
110
+ timer = null
111
+ if (rendered) output.write('\r' + ' '.repeat(Math.max(1, Math.min(output.columns ?? 100, 100) - 1)) + '\r')
112
+ rendered = false
113
+ }
114
+ const resume = () => {
115
+ if (!animated || stopped || timer !== null) return
116
+ timer = setIntervalImpl(render, 120)
97
117
  render()
98
- } else {
99
- console.log(` ... ${label}`)
100
118
  }
101
119
 
120
+ if (animated) { if (!startPaused) resume() }
121
+ else log(` ... ${label}`)
122
+
102
123
  return {
124
+ pause,
125
+ resume,
103
126
  update(nextLabel) {
104
127
  if (nextLabel === currentLabel) return
105
128
  currentLabel = nextLabel
106
- if (!isTty) console.log(` ... ${nextLabel}`)
129
+ if (!animated) log(` ... ${nextLabel}`)
107
130
  },
108
131
  stop(kind = null, message = null) {
109
- if (timer) {
110
- clearInterval(timer)
111
- process.stdout.write('\r' + ' '.repeat(100) + '\r')
112
- }
113
- if (kind && message) statusLine(kind, message)
132
+ pause()
133
+ stopped = true
134
+ if (kind && message) statusLine(kind, message, { log })
114
135
  },
115
136
  }
116
137
  }