Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions packages/cli-kit/src/private/node/command-event-context.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import {
createCommandEventChannel,
type CommandEvent,
type CommandEventChannel,
type CommandEventChannelOptions,
type CommandEventEmissionOptions,
type CommandEventInput,
} from '../../public/common/command-events.js'
import {AsyncLocalStorage} from 'node:async_hooks'

export type CommandEventOutputMode = 'text' | 'json'

interface CommandEventContext {
channel: CommandEventChannel
outputMode: CommandEventOutputMode
}

interface RunWithCommandEventsOptions extends CommandEventChannelOptions<CommandEvent> {
outputMode?: CommandEventOutputMode
}

const commandEventStorageKey = Symbol.for('@shopify/cli-kit/command-event-storage')
const existingCommandEventStorage = Reflect.get(globalThis, commandEventStorageKey) as
| AsyncLocalStorage<CommandEventContext>
| undefined
const commandEventStorage = existingCommandEventStorage ?? new AsyncLocalStorage<CommandEventContext>()

if (!existingCommandEventStorage) {
// cli-kit can be loaded both externally and inside the bundled CLI. Both copies must observe
// the same command execution context so output helpers consistently emit JSON events.
Reflect.set(globalThis, commandEventStorageKey, commandEventStorage)
}

/**
* Runs a command execution with an event channel available to all nested asynchronous work.
*
* @param options - The event sink, clock, and output mode used by the channel.
* @param execute - The command execution to run with the channel.
* @returns The result of the command execution.
*/
export function runWithCommandEvents<TResult>(options: RunWithCommandEventsOptions, execute: () => TResult): TResult {
return commandEventStorage.run(
{
channel: createCommandEventChannel(options),
outputMode: options.outputMode ?? 'text',
},
execute,
)
}

/**
* Emits an event for the current command execution.
*
* Events emitted outside a command execution are ignored.
*
* @param event - The event to emit before its timestamp is added.
* @param options - Presentation details that are not included in the event.
*/
export function emitCommandEvent(event: CommandEventInput, options?: CommandEventEmissionOptions): void {
commandEventStorage.getStore()?.channel.emit(event, options)
}

/**
* Returns how command events are presented for the current execution.
*
* @returns The current event output mode, or undefined outside a command event context.
*/
export function commandEventOutputMode(): CommandEventOutputMode | undefined {
return commandEventStorage.getStore()?.outputMode
}
15 changes: 15 additions & 0 deletions packages/cli-kit/src/private/node/command-event-output.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import {consoleWarn} from './output.js'
import {isUnitTest} from '../../public/node/context/local.js'
import {collectLog, outputWhereAppropriate} from '../../public/node/output.js'
import type {CommandEvent} from '../../public/common/command-events.js'

/**
* Writes a command event as JSON without routing it back through the command event context.
*
* @param event - The event to write.
*/
export function outputCommandEventAsJson(event: CommandEvent): void {
const message = JSON.stringify(event)
if (isUnitTest()) collectLog('info', message)
outputWhereAppropriate('info', consoleWarn, message)
}
81 changes: 81 additions & 0 deletions packages/cli-kit/src/public/common/command-events.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import {createCommandEventChannel, commandEventSchema, type CommandEvent} from './command-events.js'
import {describe, expect, test, vi} from 'vitest'

describe('commandEventSchema', () => {
test.each<CommandEvent>([
{
type: 'diagnostic',
timestamp: '2026-08-26T12:00:00.000Z',
level: 'warning',
message: 'Using a fallback',
code: 'fallback',
},
{
type: 'progress',
timestamp: '2026-08-26T12:00:01.000Z',
message: 'Uploading files',
current: 2,
total: 10,
},
])('accepts a $type event', (event) => {
expect(commandEventSchema.parse(event)).toEqual(event)
})

test('rejects an event without a timestamp', () => {
expect(() => commandEventSchema.parse({type: 'diagnostic', level: 'info', message: 'Missing timestamp'})).toThrow()
})
})

describe('createCommandEventChannel', () => {
test('adds the timestamp when the event is emitted and delivers synchronously', () => {
const calls: string[] = []
const sink = vi.fn((event: CommandEvent) => calls.push(event.timestamp))
const channel = createCommandEventChannel({
sink,
clock: () => new Date('2026-08-26T12:00:00.000Z'),
})

calls.push('before')
channel.emit({type: 'diagnostic', level: 'debug', message: 'Resolving store'})
calls.push('after')

expect(calls).toEqual(['before', '2026-08-26T12:00:00.000Z', 'after'])
expect(sink).toHaveBeenCalledWith({
type: 'diagnostic',
timestamp: '2026-08-26T12:00:00.000Z',
level: 'debug',
message: 'Resolving store',
})
})

test('preserves event order', () => {
const receivedMessages: string[] = []
const channel = createCommandEventChannel({
sink: (event) => receivedMessages.push(event.message),
})

channel.emit({type: 'progress', message: 'First'})
channel.emit({type: 'progress', message: 'Second'})

expect(receivedMessages).toEqual(['First', 'Second'])
})

test('delivers presentation details without adding them to the event', () => {
const sink = vi.fn()
const channel = createCommandEventChannel({
sink,
clock: () => new Date('2026-08-26T12:00:00.000Z'),
})

channel.emit({type: 'progress', message: 'Uploading files'}, {alreadyRendered: true})

expect(sink).toHaveBeenCalledWith(
{
type: 'progress',
timestamp: '2026-08-26T12:00:00.000Z',
message: 'Uploading files',
},
{alreadyRendered: true},
)
})
})
93 changes: 93 additions & 0 deletions packages/cli-kit/src/public/common/command-events.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import {z} from 'zod'

/** Schema for a diagnostic emitted while a command executes. */
export const commandDiagnosticEventSchema = z
.object({
type: z.literal('diagnostic'),
timestamp: z.string().datetime({offset: true}),
level: z.enum(['debug', 'info', 'warning']),
message: z.string(),
code: z.string().optional(),
})
.strict()

/** Schema for a progress update emitted while a command executes. */
export const commandProgressEventSchema = z
.object({
type: z.literal('progress'),
timestamp: z.string().datetime({offset: true}),
message: z.string(),
current: z.number().nonnegative().optional(),
total: z.number().nonnegative().optional(),
})
.strict()

/** Schema for side events emitted while a command executes. */
export const commandEventSchema = z.discriminatedUnion('type', [
commandDiagnosticEventSchema,
commandProgressEventSchema,
])

/** A diagnostic emitted while a command executes. */
export type CommandDiagnosticEvent = z.infer<typeof commandDiagnosticEventSchema>

/** A progress update emitted while a command executes. */
export type CommandProgressEvent = z.infer<typeof commandProgressEventSchema>

/** A side event emitted while a command executes. */
export type CommandEvent = z.infer<typeof commandEventSchema>

/** An event before its emission timestamp is added. */
export type CommandEventInput<TEvent extends CommandEvent = CommandEvent> = TEvent extends unknown
? Omit<TEvent, 'timestamp'>
: never

/** Presentation details that are not included in the emitted event. */
export interface CommandEventEmissionOptions {
/** The event is already visible in the command's text UI. */
alreadyRendered?: boolean
}

/** Receives one timestamped event from a command execution. */
export type CommandEventSink<TEvent extends CommandEvent = CommandEvent> = (
event: TEvent,
options?: CommandEventEmissionOptions,
) => void

/** Emits timestamped side events from one command execution. */
export interface CommandEventChannel<TEvent extends CommandEvent = CommandEvent> {
emit: (event: CommandEventInput<TEvent>, options?: CommandEventEmissionOptions) => void
}

/** Supplies the current time when an event is emitted. */
export type CommandEventClock = () => Date

/** Options for a command event channel. */
export interface CommandEventChannelOptions<TEvent extends CommandEvent> {
sink?: CommandEventSink<TEvent>
clock?: CommandEventClock
}

/**
* Creates a synchronous, execution-scoped channel for command side events.
*
* @param options - The event sink and clock used by the channel.
* @returns A channel that adds an ISO timestamp before synchronously delivering each event.
*/
export function createCommandEventChannel<TEvent extends CommandEvent = CommandEvent>(
options: CommandEventChannelOptions<TEvent> = {},
): CommandEventChannel<TEvent> {
const sink = options.sink ?? (() => {})
const clock = options.clock ?? (() => new Date())

return {
emit(event, emissionOptions) {
const timestampedEvent = {...event, timestamp: clock().toISOString()} as TEvent
if (emissionOptions === undefined) {
sink(timestampedEvent)
} else {
sink(timestampedEvent, emissionOptions)
}
},
}
}
70 changes: 69 additions & 1 deletion packages/cli-kit/src/public/node/base-command.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import Command from './base-command.js'
import {Environments} from './environments.js'
import {encodeToml as encodeTOML} from './toml/codec.js'
import {globalFlags, requiredIfNonInteractive} from './cli.js'
import {globalFlags, jsonFlag, requiredIfNonInteractive} from './cli.js'
import {emitCommandEvent} from './command-events.js'
import {inTemporaryDirectory, mkdir, writeFile} from './fs.js'
import {joinPath, resolvePath, cwd} from './path.js'
import {mockAndCaptureOutput} from './testing/output.js'
Expand All @@ -25,6 +26,7 @@ beforeEach(() => {
afterEach(() => {
Object.defineProperty(process.stdin, 'isTTY', {value: originalStdinIsTTY, configurable: true, writable: true})
Object.defineProperty(process.stdout, 'isTTY', {value: originalStdoutIsTTY, configurable: true, writable: true})
mockAndCaptureOutput().clear()
})

let testResult: Record<string, unknown> = {}
Expand Down Expand Up @@ -149,6 +151,26 @@ class MockCommandWithoutEnvironmentFlag extends Command {
}
}

class MockCommandWithEvents extends Command {
static enableJsonFlag = true
static flags = {...jsonFlag}

async run(): Promise<void> {
await this.parse(MockCommandWithEvents)
emitCommandEvent({type: 'progress', message: 'Command event'})
}
}

class MockCommandWithAlreadyRenderedEvent extends Command {
static enableJsonFlag = true
static flags = {...jsonFlag}

async run(): Promise<void> {
await this.parse(MockCommandWithAlreadyRenderedEvent)
emitCommandEvent({type: 'progress', message: 'Displayed by task UI'}, {alreadyRendered: true})
}
}

const validEnvironment = {
someString: 'stringy',
someBoolean: true,
Expand Down Expand Up @@ -207,6 +229,52 @@ const allEnvironments: Environments = {
},
}

describe('command events', () => {
test('renders events for commands', async () => {
const outputMock = mockAndCaptureOutput()
outputMock.clear()

await MockCommandWithEvents.run([])

expect(outputMock.info()).toContain('Command event')
})

test('renders events as JSON for JSON commands', async () => {
const outputMock = mockAndCaptureOutput()
outputMock.clear()

await MockCommandWithEvents.run(['--json'])

expect(JSON.parse(outputMock.info())).toEqual({
type: 'progress',
timestamp: expect.any(String),
message: 'Command event',
})
})

test('does not duplicate events already displayed by the text UI', async () => {
const outputMock = mockAndCaptureOutput()
outputMock.clear()

await MockCommandWithAlreadyRenderedEvent.run([])

expect(outputMock.info()).toBe('')
})

test('renders UI-managed events as JSON without presentation details', async () => {
const outputMock = mockAndCaptureOutput()
outputMock.clear()

await MockCommandWithAlreadyRenderedEvent.run(['--json'])

expect(JSON.parse(outputMock.info())).toEqual({
type: 'progress',
timestamp: expect.any(String),
message: 'Displayed by task UI',
})
})
})

describe('applying environments', async () => {
const runTestInTmpDir = (testName: string, testFunc: (tmpDir: string) => Promise<void>) => {
test(testName, async () => {
Expand Down
5 changes: 5 additions & 0 deletions packages/cli-kit/src/public/node/base-command.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {isDevelopment} from './context/local.js'
import {addPublicMetadata} from './metadata.js'
import {AbortError} from './error.js'
import {runWithCommandEventsForCommand} from './command-events.js'
import {outputContent, outputResult, outputToken} from './output.js'
import {setCurrentSessionAlias} from './session.js'
import {terminalSupportsPrompting} from './system.js'
Expand Down Expand Up @@ -62,6 +63,10 @@ abstract class BaseCommand extends Command {
return Errors.handle(error)
}

protected async _run<T>(): Promise<T> {
return runWithCommandEventsForCommand(this.argv, () => super._run<T>())
}

protected async init(): Promise<unknown> {
this.exitWithTimestampWhenEnvVariablePresent()
setCurrentCommandId(this.id ?? '')
Expand Down
Loading
Loading