-
Notifications
You must be signed in to change notification settings - Fork 289
Add command side event infrastructure #8403
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
70 changes: 70 additions & 0 deletions
70
packages/cli-kit/src/private/node/command-event-context.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 {commandEventSchema, 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(commandEventSchema.parse(event)) | ||
| if (isUnitTest()) collectLog('info', message) | ||
| outputWhereAppropriate('info', consoleWarn, message) | ||
| } |
114 changes: 114 additions & 0 deletions
114
packages/cli-kit/src/public/common/command-events.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| 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', | ||
| operation: 'upload', | ||
| status: 'updated', | ||
| 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() | ||
| }) | ||
|
|
||
| test('accepts non-fatal error diagnostics', () => { | ||
| const event = { | ||
| type: 'diagnostic', | ||
| timestamp: '2026-08-26T12:00:00.000Z', | ||
| level: 'error', | ||
| message: 'One item could not be uploaded', | ||
| } | ||
|
|
||
| expect(commandEventSchema.parse(event)).toEqual(event) | ||
| }) | ||
|
|
||
| test.each(['started', 'updated', 'completed'])('accepts %s progress without a message', (status) => { | ||
| const event = {type: 'progress', timestamp: '2026-08-26T12:00:00.000Z', operation: 'upload', status} | ||
|
|
||
| expect(commandEventSchema.parse(event)).toEqual(event) | ||
| }) | ||
|
|
||
| test.each([{operation: 'upload'}, {status: 'started'}, {operation: 'upload', status: 'unknown'}])( | ||
| 'rejects incomplete or invalid progress metadata: %j', | ||
| (metadata) => { | ||
| expect(() => | ||
| commandEventSchema.parse({type: 'progress', timestamp: '2026-08-26T12:00:00.000Z', ...metadata}), | ||
| ).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 | undefined)[] = [] | ||
| const channel = createCommandEventChannel({ | ||
| sink: (event) => receivedMessages.push(event.message), | ||
| }) | ||
|
|
||
| channel.emit({type: 'progress', operation: 'upload', status: 'updated', message: 'First'}) | ||
| channel.emit({type: 'progress', operation: 'upload', status: 'updated', 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', operation: 'upload', status: 'updated', message: 'Uploading files'}, | ||
| {alreadyRendered: true}, | ||
| ) | ||
|
|
||
| expect(sink).toHaveBeenCalledWith( | ||
| { | ||
| type: 'progress', | ||
| operation: 'upload', | ||
| status: 'updated', | ||
| timestamp: '2026-08-26T12:00:00.000Z', | ||
| message: 'Uploading files', | ||
| }, | ||
| {alreadyRendered: true}, | ||
| ) | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| 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', 'error']), | ||
| 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}), | ||
| status: z.enum(['started', 'updated', 'completed']), | ||
| operation: z.string(), | ||
| message: z.string().optional(), | ||
| current: z.number().nonnegative().optional(), | ||
| total: z.number().nonnegative().optional(), | ||
|
dmerand marked this conversation as resolved.
|
||
| }) | ||
| .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. | ||
| * Adapters validate events at their output boundary; the channel preserves domain-specific event fields. | ||
| * | ||
| * @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) { | ||
| // TypeScript cannot reconstruct the generic event from its distributive Omit. | ||
| const timestampedEvent = {...event, timestamp: clock().toISOString()} as unknown as TEvent | ||
| if (emissionOptions === undefined) { | ||
| sink(timestampedEvent) | ||
| } else { | ||
| sink(timestampedEvent, emissionOptions) | ||
| } | ||
| }, | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This pattern is unusual for our codebase. We have other patterns for lazy-creating globals; usually we do it in a function so loading a file has no side effects; this also has the benefit of keeping types simple because the function can more easily guarantee a return type.