diff --git a/docs-shopify.dev/generated/generated_docs_data_v2.json b/docs-shopify.dev/generated/generated_docs_data_v2.json index 7be513a2efc..2b142950461 100644 --- a/docs-shopify.dev/generated/generated_docs_data_v2.json +++ b/docs-shopify.dev/generated/generated_docs_data_v2.json @@ -9183,6 +9183,15 @@ "isOptional": true, "environmentValue": "SHOPIFY_FLAG_ENVIRONMENT" }, + { + "filePath": "docs-shopify.dev/commands/interfaces/theme-share.interface.ts", + "syntaxKind": "PropertySignature", + "name": "-j, --json", + "value": "''", + "description": "Output the result as JSON. Automatically disables color output.", + "isOptional": true, + "environmentValue": "SHOPIFY_FLAG_JSON" + }, { "filePath": "docs-shopify.dev/commands/interfaces/theme-share.interface.ts", "syntaxKind": "PropertySignature", @@ -9193,7 +9202,7 @@ "environmentValue": "SHOPIFY_FLAG_STORE" } ], - "value": "export interface themeshare {\n /**\n * Alias of the Shopify account to use for authentication.\n * @environment SHOPIFY_FLAG_AUTH_ALIAS\n */\n '--auth-alias '?: string\n\n /**\n * The environment to apply to the current command.\n * @environment SHOPIFY_FLAG_ENVIRONMENT\n */\n '-e, --environment '?: string\n\n /**\n * Print the command's JSON schemas.\n * @environment SHOPIFY_FLAG_JSON_SCHEMA\n */\n '--json-schema'?: ''\n\n /**\n * The listing preset to use for multi-preset themes. Applies preset files from listings/[preset-name] directory.\n * @environment SHOPIFY_FLAG_LISTING\n */\n '--listing '?: string\n\n /**\n * Disable color output.\n * @environment SHOPIFY_FLAG_NO_COLOR\n */\n '--no-color'?: ''\n\n /**\n * Password generated from the Theme Access app or an Admin API token.\n * @environment SHOPIFY_CLI_THEME_TOKEN\n */\n '--password '?: string\n\n /**\n * The path where you want to run the command. Defaults to the current working directory.\n * @environment SHOPIFY_FLAG_PATH\n */\n '--path '?: string\n\n /**\n * Store URL. It can be the store prefix (example) or the full myshopify.com URL (example.myshopify.com, https://example.myshopify.com).\n * @environment SHOPIFY_FLAG_STORE\n */\n '-s, --store '?: string\n\n /**\n * Increase the verbosity of the output. May include sensitive data.\n * @environment SHOPIFY_FLAG_VERBOSE\n */\n '--verbose'?: ''\n}" + "value": "export interface themeshare {\n /**\n * Alias of the Shopify account to use for authentication.\n * @environment SHOPIFY_FLAG_AUTH_ALIAS\n */\n '--auth-alias '?: string\n\n /**\n * The environment to apply to the current command.\n * @environment SHOPIFY_FLAG_ENVIRONMENT\n */\n '-e, --environment '?: string\n\n /**\n * Output the result as JSON. Automatically disables color output.\n * @environment SHOPIFY_FLAG_JSON\n */\n '-j, --json'?: ''\n\n /**\n * Print the command's JSON schemas.\n * @environment SHOPIFY_FLAG_JSON_SCHEMA\n */\n '--json-schema'?: ''\n\n /**\n * The listing preset to use for multi-preset themes. Applies preset files from listings/[preset-name] directory.\n * @environment SHOPIFY_FLAG_LISTING\n */\n '--listing '?: string\n\n /**\n * Disable color output.\n * @environment SHOPIFY_FLAG_NO_COLOR\n */\n '--no-color'?: ''\n\n /**\n * Password generated from the Theme Access app or an Admin API token.\n * @environment SHOPIFY_CLI_THEME_TOKEN\n */\n '--password '?: string\n\n /**\n * The path where you want to run the command. Defaults to the current working directory.\n * @environment SHOPIFY_FLAG_PATH\n */\n '--path '?: string\n\n /**\n * Store URL. It can be the store prefix (example) or the full myshopify.com URL (example.myshopify.com, https://example.myshopify.com).\n * @environment SHOPIFY_FLAG_STORE\n */\n '-s, --store '?: string\n\n /**\n * Increase the verbosity of the output. May include sensitive data.\n * @environment SHOPIFY_FLAG_VERBOSE\n */\n '--verbose'?: ''\n}" } }, "upgrade": { diff --git a/packages/cli/README.md b/packages/cli/README.md index d3437178576..b187342c879 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -9718,14 +9718,18 @@ Creates a shareable, unpublished, and new theme on your theme library with a ran ``` USAGE - $ shopify theme share [--auth-alias ] [-e ...] [--json-schema] [--listing ] [--no-color] - [--password ] [--path ] [-s ] [--verbose] + $ shopify theme share [--auth-alias ] [-e ...] [-j] [--json-schema] [--listing ] + [--no-color] [--password ] [--path ] [-s ] [--verbose] FLAGS -e, --environment=... The environment to apply to the current command. [env: SHOPIFY_FLAG_ENVIRONMENT] + -j, --json + Output the result as JSON. Automatically disables color output. + [env: SHOPIFY_FLAG_JSON] + -s, --store= Store URL. It can be the store prefix (example) or the full myshopify.com URL (example.myshopify.com, https://example.myshopify.com). @@ -9767,6 +9771,111 @@ DESCRIPTION This command returns a "preview link" (https://help.shopify.com/manual/online-store/themes/adding-themes#share-a-theme-preview-with-others) that you can share with others. + + Use `--json-schema` to print the result, error, and event schemas. + + Output from `--json` conforms to the `ThemeShareResult` schema. + + ```json + { + "anyOf": [ + { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "success", + "failed" + ] + }, + "environment": { + "type": "string" + }, + "theme": { + "$ref": "#/definitions/ThemePushTheme" + } + }, + "required": [ + "status", + "theme" + ], + "additionalProperties": false + }, + { + "type": "array", + "items": { + "type": "object", + "properties": { + "status": { + "$ref": "#/definitions/ThemeShareResult/anyOf/0/properties/status" + }, + "environment": { + "type": "string" + }, + "theme": { + "$ref": "#/definitions/ThemePushTheme" + } + }, + "required": [ + "status", + "environment", + "theme" + ], + "additionalProperties": false + } + } + ], + "title": "ThemeShareResult", + "definitions": { + "ThemePushTheme": { + "type": "object", + "properties": { + "id": { + "type": "number" + }, + "name": { + "type": "string" + }, + "role": { + "type": "string" + }, + "shop": { + "type": "string" + }, + "editor_url": { + "type": "string" + }, + "preview_url": { + "type": "string" + }, + "warning": { + "type": "string" + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "required": [ + "id", + "name", + "role", + "shop", + "editor_url", + "preview_url" + ], + "additionalProperties": false + } + }, + "$schema": "http://json-schema.org/draft-07/schema#" + } + ``` ``` ## `shopify upgrade` diff --git a/packages/cli/oclif.manifest.json b/packages/cli/oclif.manifest.json index 7028c16ee29..c7f9686e409 100644 --- a/packages/cli/oclif.manifest.json +++ b/packages/cli/oclif.manifest.json @@ -11710,7 +11710,7 @@ "args": { }, "customPluginName": "@shopify/theme", - "description": "Uploads your theme as a new, unpublished theme in your theme library. The theme is given a randomized name.\n\n This command returns a \"preview link\" (https://help.shopify.com/manual/online-store/themes/adding-themes#share-a-theme-preview-with-others) that you can share with others.", + "description": "Uploads your theme as a new, unpublished theme in your theme library. The theme is given a randomized name.\n\n This command returns a \"preview link\" (https://help.shopify.com/manual/online-store/themes/adding-themes#share-a-theme-preview-with-others) that you can share with others.\n\nUse `--json-schema` to print the result, error, and event schemas.\n\nOutput from `--json` conforms to the `ThemeShareResult` schema.\n\n```json\n{\n \"anyOf\": [\n {\n \"type\": \"object\",\n \"properties\": {\n \"status\": {\n \"type\": \"string\",\n \"enum\": [\n \"success\",\n \"failed\"\n ]\n },\n \"environment\": {\n \"type\": \"string\"\n },\n \"theme\": {\n \"$ref\": \"#/definitions/ThemePushTheme\"\n }\n },\n \"required\": [\n \"status\",\n \"theme\"\n ],\n \"additionalProperties\": false\n },\n {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"status\": {\n \"$ref\": \"#/definitions/ThemeShareResult/anyOf/0/properties/status\"\n },\n \"environment\": {\n \"type\": \"string\"\n },\n \"theme\": {\n \"$ref\": \"#/definitions/ThemePushTheme\"\n }\n },\n \"required\": [\n \"status\",\n \"environment\",\n \"theme\"\n ],\n \"additionalProperties\": false\n }\n }\n ],\n \"title\": \"ThemeShareResult\",\n \"definitions\": {\n \"ThemePushTheme\": {\n \"type\": \"object\",\n \"properties\": {\n \"id\": {\n \"type\": \"number\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"role\": {\n \"type\": \"string\"\n },\n \"shop\": {\n \"type\": \"string\"\n },\n \"editor_url\": {\n \"type\": \"string\"\n },\n \"preview_url\": {\n \"type\": \"string\"\n },\n \"warning\": {\n \"type\": \"string\"\n },\n \"errors\": {\n \"type\": \"object\",\n \"additionalProperties\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n }\n }\n },\n \"required\": [\n \"id\",\n \"name\",\n \"role\",\n \"shop\",\n \"editor_url\",\n \"preview_url\"\n ],\n \"additionalProperties\": false\n }\n },\n \"$schema\": \"http://json-schema.org/draft-07/schema#\"\n}\n```", "descriptionWithMarkdown": "Uploads your theme as a new, unpublished theme in your theme library. The theme is given a randomized name.\n\n This command returns a [preview link](https://help.shopify.com/manual/online-store/themes/adding-themes#share-a-theme-preview-with-others) that you can share with others.", "enableJsonFlag": false, "flags": { @@ -11740,6 +11740,15 @@ "name": "force", "type": "boolean" }, + "json": { + "allowNo": false, + "char": "j", + "description": "Output the result as JSON. Automatically disables color output.", + "env": "SHOPIFY_FLAG_JSON", + "hidden": false, + "name": "json", + "type": "boolean" + }, "json-schema": { "allowNo": false, "description": "Print the command's JSON schemas.", diff --git a/packages/eslint-plugin-cli/rules/json-output-command-exceptions.js b/packages/eslint-plugin-cli/rules/json-output-command-exceptions.js index 245175f2627..fb7a06d6430 100644 --- a/packages/eslint-plugin-cli/rules/json-output-command-exceptions.js +++ b/packages/eslint-plugin-cli/rules/json-output-command-exceptions.js @@ -49,7 +49,6 @@ const commandExceptions = [ 'packages/theme/src/cli/commands/theme/package.ts', 'packages/theme/src/cli/commands/theme/preview.ts', 'packages/theme/src/cli/commands/theme/profile.ts', - 'packages/theme/src/cli/commands/theme/share.ts', // Streaming commands without a single finite result. 'packages/app/src/cli/commands/app/dev.ts', diff --git a/packages/theme/src/cli/commands/theme/share.test.ts b/packages/theme/src/cli/commands/theme/share.test.ts new file mode 100644 index 00000000000..1526a9263ee --- /dev/null +++ b/packages/theme/src/cli/commands/theme/share.test.ts @@ -0,0 +1,119 @@ +import Share from './share.js' +import {executeThemePush} from '../../services/push.js' +import {themeShareJsonOutputSchema} from '../../services/share/types.js' +import {Config} from '@oclif/core' +import {getRandomName} from '@shopify/cli-kit/common/string' +import {mockAndCaptureOutput, withCapturedStandardStreams} from '@shopify/cli-kit/node/testing/output' +import {describe, expect, test, vi} from 'vitest' + +vi.mock('../../services/push.js') +vi.mock('@shopify/cli-kit/common/string', async (importOriginal) => ({ + ...(await importOriginal()), + getRandomName: vi.fn(), +})) + +const session = {storeFqdn: 'test.myshopify.com', token: 'token'} + +function result() { + return { + theme: { + id: 1, + name: 'Creative Theme', + role: 'unpublished', + shop: session.storeFqdn, + editor_url: 'editor', + preview_url: 'preview', + }, + published: false, + hasErrors: false, + errors: {}, + } +} + +describe('theme share', () => { + test('exposes JSON and schema flags and documents its own result', () => { + expect(Share.jsonOutputSchema).toBe(themeShareJsonOutputSchema) + expect(Share.description).toContain('ThemeShareResult') + expect(Share.flags.json).toBeDefined() + expect(Share.baseFlags).toHaveProperty('json-schema') + }) + + test('creates an unpublished theme with a random name and forwards the listing', async () => { + vi.mocked(getRandomName).mockReturnValue('Creative Theme') + vi.mocked(executeThemePush).mockResolvedValue(result()) + const command = new Share([], new Config({root: '.'})) + await withCapturedStandardStreams(async ({stdout, stderr}) => { + await command.command({json: true, path: '/theme', listing: 'preset'} as never, session, false) + + expect(getRandomName).toHaveBeenCalledWith('creative') + expect(executeThemePush).toHaveBeenCalledWith( + expect.objectContaining({unpublished: true, theme: 'Creative Theme', path: '/theme', listing: 'preset'}), + session, + false, + undefined, + ) + expect(stdout()).toBe(`${themeShareJsonOutputSchema.encode({status: 'success', theme: result().theme})}\n`) + expect(stderr()).toBe('') + }) + }) + + test('keeps upload errors and environment in JSON', async () => { + vi.mocked(executeThemePush).mockResolvedValue({ + ...result(), + environment: 'staging', + hasErrors: true, + errors: {'assets/theme.css': ['bad CSS']}, + }) + const command = new Share([], new Config({root: '.'})) + await withCapturedStandardStreams(async ({stdout}) => { + await command.command({json: true, environment: ['staging']} as never, session, false) + + expect(JSON.parse(stdout())).toEqual({ + status: 'failed', + environment: 'staging', + theme: { + ...result().theme, + warning: "[staging] The theme 'Creative Theme' was pushed with errors", + errors: {'assets/theme.css': ['bad CSS']}, + }, + }) + }) + }) + + test('preserves the push success banner in text mode', async () => { + vi.mocked(executeThemePush).mockResolvedValue(result()) + const output = mockAndCaptureOutput() + output.clear() + await new Share([], new Config({root: '.'})).command({} as never, session, false) + expect(output.info()).toContain("The theme 'Creative Theme' (#1) was pushed successfully.") + expect(output.info()).toContain('View your theme') + expect(output.info()).toContain('Customize your theme at the theme editor') + }) + + test('does not emit a result when cancelled', async () => { + vi.mocked(executeThemePush).mockResolvedValue(undefined) + await withCapturedStandardStreams(async ({stdout}) => { + await new Share([], new Config({root: '.'})).command({json: true} as never, session, false) + + expect(stdout()).toBe('') + }) + }) + + test('propagates theme creation failures through the shared error path', async () => { + const failure = new Error('theme creation failed') + vi.mocked(executeThemePush).mockRejectedValue(failure) + await withCapturedStandardStreams(async ({stdout}) => { + await expect(new Share([], new Config({root: '.'})).command({json: true} as never, session, false)).rejects.toBe( + failure, + ) + + expect(stdout()).toBe('') + }) + }) + + test.each([{id: '1'}, {role: null}, {errors: {file: 'invalid'}}])('rejects malformed theme data %j', (fields) => { + expect(() => + themeShareJsonOutputSchema.validate({status: 'success', theme: {...result().theme, ...fields}}), + ).toThrow() + }) +}) diff --git a/packages/theme/src/cli/commands/theme/share.ts b/packages/theme/src/cli/commands/theme/share.ts index 3700dfa313e..f97d99b4739 100644 --- a/packages/theme/src/cli/commands/theme/share.ts +++ b/packages/theme/src/cli/commands/theme/share.ts @@ -1,8 +1,10 @@ +import {themeShareJsonOutputSchema} from '../../services/share/types.js' +import {renderThemeShareResult, renderThemeShareEnvironmentResults} from '../../services/share/result.js' import {themeFlags} from '../../flags.js' import ThemeCommand from '../../utilities/theme-command.js' -import {push, PushFlags} from '../../services/push.js' +import {executeThemePush, PushFlags} from '../../services/push.js' import {Flags} from '@oclif/core' -import {globalFlags} from '@shopify/cli-kit/node/cli' +import {globalFlags, jsonFlag} from '@shopify/cli-kit/node/cli' import {getRandomName} from '@shopify/cli-kit/common/string' import {recordTiming} from '@shopify/cli-kit/node/analytics' import {InferredFlags} from '@oclif/core/interfaces' @@ -13,6 +15,10 @@ import {Writable} from 'stream' type ShareFlags = InferredFlags export default class Share extends ThemeCommand { + static get jsonOutputSchema() { + return themeShareJsonOutputSchema + } + static summary = 'Creates a shareable, unpublished, and new theme on your theme library with a randomized name.' static descriptionWithMarkdown = `Uploads your theme as a new, unpublished theme in your theme library. The theme is given a randomized name. @@ -23,6 +29,7 @@ export default class Share extends ThemeCommand { static flags = { ...globalFlags, + ...jsonFlag, ...themeFlags, force: Flags.boolean({ hidden: true, @@ -59,7 +66,17 @@ export default class Share extends ThemeCommand { } recordTiming('theme-command:share') - await push(pushFlags, adminSession, multiEnvironment, context) + const result = await executeThemePush(pushFlags, adminSession, multiEnvironment, context) + if (result && !(flags.json && multiEnvironment)) renderThemeShareResult(result, flags.json ? 'json' : 'text') recordTiming('theme-command:share') + return result + } + + protected collectsEnvironmentResults(flags: {json?: boolean}): boolean { + return Boolean(flags.json) + } + + protected renderEnvironmentResults(results: {environment: string; result: unknown}[]): void { + renderThemeShareEnvironmentResults(results) } } diff --git a/packages/theme/src/cli/commands/theme/transfer-environments.test.ts b/packages/theme/src/cli/commands/theme/transfer-environments.test.ts index 79319aa5e76..9de6239e692 100644 --- a/packages/theme/src/cli/commands/theme/transfer-environments.test.ts +++ b/packages/theme/src/cli/commands/theme/transfer-environments.test.ts @@ -1,8 +1,10 @@ import Push from './push.js' import Pull from './pull.js' +import Share from './share.js' import {executeThemePull} from '../../services/pull.js' import {executeThemePush} from '../../services/push.js' import {withCapturedStandardStreams} from '@shopify/cli-kit/node/testing/output' +import {addPublicMetadata} from '@shopify/cli-kit/node/metadata' import {loadEnvironment} from '@shopify/cli-kit/node/environments' import {ensureAuthenticatedThemes} from '@shopify/cli-kit/node/session' import {inTemporaryDirectory} from '@shopify/cli-kit/node/fs' @@ -24,9 +26,13 @@ class TestPull extends Pull { public parse = vi.fn() } -describe.each([TestPush, TestPull])('%s', (Command) => { +class TestShare extends Share { + public parse = vi.fn() +} + +describe.each([TestPush, TestPull, TestShare])('%s', (Command) => { // Exercise real environment orchestration, presenter, encoder and streams. - test.each(['none', 'partial', 'total'] as const)( + test.each(['none', 'partial', 'total', 'cancelled', 'analytics'] as const)( 'collects environment successes in requested order with %s failures', async (failures) => { await inTemporaryDirectory(async (path) => { @@ -41,12 +47,19 @@ describe.each([TestPush, TestPull])('%s', (Command) => { const secondStarted = new Promise((resolve) => { releaseFirst = resolve }) + vi.mocked(addPublicMetadata).mockImplementation(async (collect) => { + const metadata = await collect() + if (failures === 'analytics' && metadata?.store_domain === 'second.myshopify.com') { + throw new Error('analytics failed') + } + }) const executionOrder: string[] = [] const execute = async (flags: {environment?: string[]}, session?: {storeFqdn: string}) => { const environment = flags.environment![0]! if (environment === 'first') await secondStarted if (environment === 'second') releaseFirst() executionOrder.push(environment) + if (failures === 'cancelled' && environment === 'second') return undefined if (failures === 'total' || (failures === 'partial' && environment === 'second')) throw new Error('upload failed') return { @@ -89,7 +102,7 @@ describe.each([TestPush, TestPull])('%s', (Command) => { .map((line) => JSON.parse(line)) : [] expect(events.filter((event) => event.level === 'error')).toHaveLength( - {none: 0, partial: 1, total: 3}[failures], + {none: 0, partial: 1, total: 3, cancelled: 0, analytics: 1}[failures], ) }) }) @@ -108,6 +121,7 @@ describe.each([TestPush, TestPull])('%s', (Command) => { expect(JSON.parse(stdout())).toEqual([]) expect(executeThemePush).not.toHaveBeenCalled() + expect(executeThemePull).not.toHaveBeenCalled() expect( stderr() .trim() diff --git a/packages/theme/src/cli/services/share/result.ts b/packages/theme/src/cli/services/share/result.ts new file mode 100644 index 00000000000..af3788d6f17 --- /dev/null +++ b/packages/theme/src/cli/services/share/result.ts @@ -0,0 +1,21 @@ +import {themeShareJsonOutputSchema, type ThemeShareResult} from './types.js' +import {themePushJsonResult, renderThemePushResult} from '../push/result.js' +import {themePushResultSchema, type ThemePushResult} from '../push/types.js' +import {outputResult} from '@shopify/cli-kit/node/output' + +export function renderThemeShareResult(result: ThemePushResult, format: 'text' | 'json'): void { + if (format === 'json') { + outputResult(themeShareJsonOutputSchema.encode(themePushJsonResult(result))) + } else { + renderThemePushResult(result, 'text') + } +} + +export function renderThemeShareEnvironmentResults(results: {environment: string; result: unknown}[]): void { + const output: ThemeShareResult = results.flatMap(({environment, result}) => + result === undefined + ? [] + : [{...themePushJsonResult({...themePushResultSchema.parse(result), environment}), environment}], + ) + outputResult(themeShareJsonOutputSchema.encode(output)) +} diff --git a/packages/theme/src/cli/services/share/types.ts b/packages/theme/src/cli/services/share/types.ts new file mode 100644 index 00000000000..d568e983d17 --- /dev/null +++ b/packages/theme/src/cli/services/share/types.ts @@ -0,0 +1,10 @@ +import {themePushJsonOutputSchema} from '../push/types.js' +import {defineJsonOutputSchema, type InferJsonOutputSchema} from '@shopify/cli-kit/node/json-output-schema' + +export const themeShareJsonOutputSchema = defineJsonOutputSchema({ + name: 'ThemeShareResult', + schema: themePushJsonOutputSchema.schema, + definitions: themePushJsonOutputSchema.definitions, +}) + +export type ThemeShareResult = InferJsonOutputSchema