diff --git a/.changeset/app-logs-historical.md b/.changeset/app-logs-historical.md deleted file mode 100644 index 6acb6c32f52..00000000000 --- a/.changeset/app-logs-historical.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -'@shopify/app': minor -'@shopify/cli': minor ---- - -Add `shopify app logs` to list historical app logs by type, filter, and time window. diff --git a/docs-shopify.dev/generated/generated_docs_data_v2.json b/docs-shopify.dev/generated/generated_docs_data_v2.json index 5df900a6f2b..a0b7db01c51 100644 --- a/docs-shopify.dev/generated/generated_docs_data_v2.json +++ b/docs-shopify.dev/generated/generated_docs_data_v2.json @@ -3191,260 +3191,6 @@ "value": "export interface appinit {\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 Client ID of your app. Use this to automatically link your new project to an existing app. In non-interactive environments, provide this flag or both --name and --organization-id.\n * @environment SHOPIFY_FLAG_CLIENT_ID\n */\n '--client-id '?: string\n\n /**\n * Which flavor of the given template to use. Required in non-interactive environments when the selected template offers multiple flavors.\n * @environment SHOPIFY_FLAG_TEMPLATE_FLAVOR\n */\n '--flavor '?: 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 name for the new app. When provided, skips the app selection prompt and creates a new app with this name. Required in non-interactive environments unless --client-id is provided.\n * @environment SHOPIFY_FLAG_NAME\n */\n '-n, --name '?: string\n\n /**\n * Disable color output.\n * @environment SHOPIFY_FLAG_NO_COLOR\n */\n '--no-color'?: ''\n\n /**\n * Disable interactive prompts and browser authentication.\n * @environment SHOPIFY_FLAG_NO_INPUT\n */\n '--no-input'?: ''\n\n /**\n * The organization ID. Your organization ID can be found in your Dev Dashboard URL: https://dev.shopify.com/dashboard/. Required in non-interactive environments unless --client-id is provided.\n * @environment SHOPIFY_FLAG_ORGANIZATION_ID\n */\n '--organization-id '?: string\n\n /**\n * \n * @environment SHOPIFY_FLAG_PACKAGE_MANAGER\n */\n '-d, --package-manager '?: string\n\n /**\n * \n * @environment SHOPIFY_FLAG_PATH\n */\n '-p, --path '?: string\n\n /**\n * The app template. Accepts one of the following:\n - \n - Any GitHub repo with optional branch and subpath, e.g., https://github.com/Shopify//[subpath]#[branch]. Required if non interactive.\n * @environment SHOPIFY_FLAG_TEMPLATE\n */\n '--template '?: string\n\n /**\n * Increase the verbosity of the output. May include sensitive data.\n * @environment SHOPIFY_FLAG_VERBOSE\n */\n '--verbose'?: ''\n}" } }, - "applogs": { - "docs-shopify.dev/commands/interfaces/app-logs.interface.ts": { - "filePath": "docs-shopify.dev/commands/interfaces/app-logs.interface.ts", - "name": "applogs", - "description": "The following flags are available for the `app logs` command:", - "isPublicDocs": true, - "members": [ - { - "filePath": "docs-shopify.dev/commands/interfaces/app-logs.interface.ts", - "syntaxKind": "PropertySignature", - "name": "--auth-alias ", - "value": "string", - "description": "Alias of the Shopify account to use for authentication.", - "isOptional": true, - "environmentValue": "SHOPIFY_FLAG_AUTH_ALIAS" - }, - { - "filePath": "docs-shopify.dev/commands/interfaces/app-logs.interface.ts", - "syntaxKind": "PropertySignature", - "name": "--client-id ", - "value": "string", - "description": "The Client ID of your app.", - "isOptional": true, - "environmentValue": "SHOPIFY_FLAG_CLIENT_ID" - }, - { - "filePath": "docs-shopify.dev/commands/interfaces/app-logs.interface.ts", - "syntaxKind": "PropertySignature", - "name": "--event-handle ", - "value": "string", - "description": "Exact app event or app billing event handle; excludes other record types.", - "isOptional": true, - "environmentValue": "SHOPIFY_FLAG_EVENT_HANDLE" - }, - { - "filePath": "docs-shopify.dev/commands/interfaces/app-logs.interface.ts", - "syntaxKind": "PropertySignature", - "name": "--function-handle ", - "value": "string", - "description": "Exact Function extension handle; excludes non-Function records.", - "isOptional": true, - "environmentValue": "SHOPIFY_FLAG_FUNCTION_HANDLE" - }, - { - "filePath": "docs-shopify.dev/commands/interfaces/app-logs.interface.ts", - "syntaxKind": "PropertySignature", - "name": "--json-schema", - "value": "''", - "description": "Print the command's JSON schemas.", - "isOptional": true, - "environmentValue": "SHOPIFY_FLAG_JSON_SCHEMA" - }, - { - "filePath": "docs-shopify.dev/commands/interfaces/app-logs.interface.ts", - "syntaxKind": "PropertySignature", - "name": "--limit ", - "value": "string", - "description": "Maximum number of records to return, from 1 through 1000.", - "isOptional": true, - "environmentValue": "SHOPIFY_FLAG_LIMIT" - }, - { - "filePath": "docs-shopify.dev/commands/interfaces/app-logs.interface.ts", - "syntaxKind": "PropertySignature", - "name": "--method ", - "value": "string", - "description": "Exact REST HTTP method; excludes non-REST records.", - "isOptional": true, - "environmentValue": "SHOPIFY_FLAG_METHOD" - }, - { - "filePath": "docs-shopify.dev/commands/interfaces/app-logs.interface.ts", - "syntaxKind": "PropertySignature", - "name": "--no-color", - "value": "''", - "description": "Disable color output.", - "isOptional": true, - "environmentValue": "SHOPIFY_FLAG_NO_COLOR" - }, - { - "filePath": "docs-shopify.dev/commands/interfaces/app-logs.interface.ts", - "syntaxKind": "PropertySignature", - "name": "--no-input", - "value": "''", - "description": "Disable interactive prompts and browser authentication.", - "isOptional": true, - "environmentValue": "SHOPIFY_FLAG_NO_INPUT" - }, - { - "filePath": "docs-shopify.dev/commands/interfaces/app-logs.interface.ts", - "syntaxKind": "PropertySignature", - "name": "--operation-name ", - "value": "string", - "description": "Exact GraphQL operation name; excludes non-GraphQL records.", - "isOptional": true, - "environmentValue": "SHOPIFY_FLAG_OPERATION_NAME" - }, - { - "filePath": "docs-shopify.dev/commands/interfaces/app-logs.interface.ts", - "syntaxKind": "PropertySignature", - "name": "--operation-type ", - "value": "string", - "description": "Exact GraphQL operation type; excludes non-GraphQL records.", - "isOptional": true, - "environmentValue": "SHOPIFY_FLAG_OPERATION_TYPE" - }, - { - "filePath": "docs-shopify.dev/commands/interfaces/app-logs.interface.ts", - "syntaxKind": "PropertySignature", - "name": "--order ", - "value": "string", - "description": "Sort direction: asc (oldest first, default with --sort) or desc (newest first).", - "isOptional": true, - "environmentValue": "SHOPIFY_FLAG_ORDER" - }, - { - "filePath": "docs-shopify.dev/commands/interfaces/app-logs.interface.ts", - "syntaxKind": "PropertySignature", - "name": "--path ", - "value": "string", - "description": "The path to your app directory.", - "isOptional": true, - "environmentValue": "SHOPIFY_FLAG_PATH" - }, - { - "filePath": "docs-shopify.dev/commands/interfaces/app-logs.interface.ts", - "syntaxKind": "PropertySignature", - "name": "--request-id ", - "value": "string", - "description": "Exact GraphQL or REST request ID; excludes other record types.", - "isOptional": true, - "environmentValue": "SHOPIFY_FLAG_REQUEST_ID" - }, - { - "filePath": "docs-shopify.dev/commands/interfaces/app-logs.interface.ts", - "syntaxKind": "PropertySignature", - "name": "--request-path ", - "value": "string", - "description": "Exact REST request path; excludes non-REST records.", - "isOptional": true, - "environmentValue": "SHOPIFY_FLAG_REQUEST_PATH" - }, - { - "filePath": "docs-shopify.dev/commands/interfaces/app-logs.interface.ts", - "syntaxKind": "PropertySignature", - "name": "--since ", - "value": "string", - "description": "Inclusive start: positive duration (s/m/h/d) or whole-second RFC 3339 timestamp.", - "isOptional": true, - "environmentValue": "SHOPIFY_FLAG_SINCE" - }, - { - "filePath": "docs-shopify.dev/commands/interfaces/app-logs.interface.ts", - "syntaxKind": "PropertySignature", - "name": "--sort ", - "value": "string", - "description": "Select the oldest/newest matches using server-side sorting. Omit for faster, less-throttled retrieval.", - "isOptional": true, - "environmentValue": "SHOPIFY_FLAG_SORT" - }, - { - "filePath": "docs-shopify.dev/commands/interfaces/app-logs.interface.ts", - "syntaxKind": "PropertySignature", - "name": "--status ", - "value": "string", - "description": "Recorded result status; not inferred from HTTP codes or response bodies.", - "isOptional": true, - "environmentValue": "SHOPIFY_FLAG_STATUS" - }, - { - "filePath": "docs-shopify.dev/commands/interfaces/app-logs.interface.ts", - "syntaxKind": "PropertySignature", - "name": "--status-code ", - "value": "string", - "description": "Exact webhook or REST HTTP status code (100–599); no status classes.", - "isOptional": true, - "environmentValue": "SHOPIFY_FLAG_STATUS_CODE" - }, - { - "filePath": "docs-shopify.dev/commands/interfaces/app-logs.interface.ts", - "syntaxKind": "PropertySignature", - "name": "--target ", - "value": "string", - "description": "Exact Function execution, Sidekick event, or UI extension target; excludes other record types.", - "isOptional": true, - "environmentValue": "SHOPIFY_FLAG_TARGET" - }, - { - "filePath": "docs-shopify.dev/commands/interfaces/app-logs.interface.ts", - "syntaxKind": "PropertySignature", - "name": "--topic ", - "value": "string", - "description": "Exact webhook topic; excludes non-webhook records.", - "isOptional": true, - "environmentValue": "SHOPIFY_FLAG_TOPIC" - }, - { - "filePath": "docs-shopify.dev/commands/interfaces/app-logs.interface.ts", - "syntaxKind": "PropertySignature", - "name": "--type ", - "value": "string", - "description": "Log type; repeat to select multiple. Defaults to all supported types.", - "isOptional": true, - "environmentValue": "SHOPIFY_FLAG_TYPE" - }, - { - "filePath": "docs-shopify.dev/commands/interfaces/app-logs.interface.ts", - "syntaxKind": "PropertySignature", - "name": "--until ", - "value": "string", - "description": "Exclusive whole-second RFC 3339 end; defaults to the current time.", - "isOptional": true, - "environmentValue": "SHOPIFY_FLAG_UNTIL" - }, - { - "filePath": "docs-shopify.dev/commands/interfaces/app-logs.interface.ts", - "syntaxKind": "PropertySignature", - "name": "--verbose", - "value": "''", - "description": "Increase the verbosity of the output. May include sensitive data.", - "isOptional": true, - "environmentValue": "SHOPIFY_FLAG_VERBOSE" - }, - { - "filePath": "docs-shopify.dev/commands/interfaces/app-logs.interface.ts", - "syntaxKind": "PropertySignature", - "name": "-c, --config ", - "value": "string", - "description": "The name of the app configuration.", - "isOptional": true, - "environmentValue": "SHOPIFY_FLAG_APP_CONFIG" - }, - { - "filePath": "docs-shopify.dev/commands/interfaces/app-logs.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/app-logs.interface.ts", - "syntaxKind": "PropertySignature", - "name": "-s, --store ", - "value": "string", - "description": "Exact store handle or myshopify.com domain/URL.", - "isOptional": true, - "environmentValue": "SHOPIFY_FLAG_STORE" - } - ], - "value": "export interface applogs {\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 Client ID of your app.\n * @environment SHOPIFY_FLAG_CLIENT_ID\n */\n '--client-id '?: string\n\n /**\n * The name of the app configuration.\n * @environment SHOPIFY_FLAG_APP_CONFIG\n */\n '-c, --config '?: string\n\n /**\n * Exact app event or app billing event handle; excludes other record types.\n * @environment SHOPIFY_FLAG_EVENT_HANDLE\n */\n '--event-handle '?: string\n\n /**\n * Exact Function extension handle; excludes non-Function records.\n * @environment SHOPIFY_FLAG_FUNCTION_HANDLE\n */\n '--function-handle '?: 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 * Maximum number of records to return, from 1 through 1000.\n * @environment SHOPIFY_FLAG_LIMIT\n */\n '--limit '?: string\n\n /**\n * Exact REST HTTP method; excludes non-REST records.\n * @environment SHOPIFY_FLAG_METHOD\n */\n '--method '?: string\n\n /**\n * Disable color output.\n * @environment SHOPIFY_FLAG_NO_COLOR\n */\n '--no-color'?: ''\n\n /**\n * Disable interactive prompts and browser authentication.\n * @environment SHOPIFY_FLAG_NO_INPUT\n */\n '--no-input'?: ''\n\n /**\n * Exact GraphQL operation name; excludes non-GraphQL records.\n * @environment SHOPIFY_FLAG_OPERATION_NAME\n */\n '--operation-name '?: string\n\n /**\n * Exact GraphQL operation type; excludes non-GraphQL records.\n * @environment SHOPIFY_FLAG_OPERATION_TYPE\n */\n '--operation-type '?: string\n\n /**\n * Sort direction: asc (oldest first, default with --sort) or desc (newest first).\n * @environment SHOPIFY_FLAG_ORDER\n */\n '--order '?: string\n\n /**\n * The path to your app directory.\n * @environment SHOPIFY_FLAG_PATH\n */\n '--path '?: string\n\n /**\n * Exact GraphQL or REST request ID; excludes other record types.\n * @environment SHOPIFY_FLAG_REQUEST_ID\n */\n '--request-id '?: string\n\n /**\n * Exact REST request path; excludes non-REST records.\n * @environment SHOPIFY_FLAG_REQUEST_PATH\n */\n '--request-path '?: string\n\n /**\n * Inclusive start: positive duration (s/m/h/d) or whole-second RFC 3339 timestamp.\n * @environment SHOPIFY_FLAG_SINCE\n */\n '--since '?: string\n\n /**\n * Select the oldest/newest matches using server-side sorting. Omit for faster, less-throttled retrieval.\n * @environment SHOPIFY_FLAG_SORT\n */\n '--sort '?: string\n\n /**\n * Recorded result status; not inferred from HTTP codes or response bodies.\n * @environment SHOPIFY_FLAG_STATUS\n */\n '--status '?: string\n\n /**\n * Exact webhook or REST HTTP status code (100–599); no status classes.\n * @environment SHOPIFY_FLAG_STATUS_CODE\n */\n '--status-code '?: string\n\n /**\n * Exact store handle or myshopify.com domain/URL.\n * @environment SHOPIFY_FLAG_STORE\n */\n '-s, --store '?: string\n\n /**\n * Exact Function execution, Sidekick event, or UI extension target; excludes other record types.\n * @environment SHOPIFY_FLAG_TARGET\n */\n '--target '?: string\n\n /**\n * Exact webhook topic; excludes non-webhook records.\n * @environment SHOPIFY_FLAG_TOPIC\n */\n '--topic '?: string\n\n /**\n * Log type; repeat to select multiple. Defaults to all supported types.\n * @environment SHOPIFY_FLAG_TYPE\n */\n '--type '?: string\n\n /**\n * Exclusive whole-second RFC 3339 end; defaults to the current time.\n * @environment SHOPIFY_FLAG_UNTIL\n */\n '--until '?: string\n\n /**\n * Increase the verbosity of the output. May include sensitive data.\n * @environment SHOPIFY_FLAG_VERBOSE\n */\n '--verbose'?: ''\n}" - } - }, "apprelease": { "docs-shopify.dev/commands/interfaces/app-release.interface.ts": { "filePath": "docs-shopify.dev/commands/interfaces/app-release.interface.ts", diff --git a/docs/cli/json-output.md b/docs/cli/json-output.md index 82e43b7cd54..a7fade70ca1 100644 --- a/docs/cli/json-output.md +++ b/docs/cli/json-output.md @@ -9,7 +9,8 @@ Finite commands expose their successful result as typed data independently from domain package owns this contract; CLI Kit only provides the shared schema and help infrastructure. All visible commands must include `jsonFlag` and expose a `jsonOutputSchema`. The repository lint check enforces -both and does not accept path exceptions. Hidden commands are outside the rule's scope. +both and does not accept path exceptions. Hidden commands, including removed command stubs such as `app logs`, +are outside the rule's scope. ## Choose the public shape @@ -84,7 +85,7 @@ envelope. Keep domain details under `details`, and add stable error codes when c retain `details.errors`, `details.extensions`, and partial `details.data` when available. Do not print a result followed by a second fatal document. -Exception: `shopify app logs` omits partial `details.data` on GraphQL failures so failed queries never return +Exception: `shopify app logs-next` omits partial `details.data` on GraphQL failures so failed queries never return log results. Fatal errors and diagnostic events may include a nonempty string `code` when a stable code is known. Omit unknown diff --git a/packages/app/src/cli/commands/app/logs-next.test.ts b/packages/app/src/cli/commands/app/logs-next.test.ts new file mode 100644 index 00000000000..2a1a9eb2e1d --- /dev/null +++ b/packages/app/src/cli/commands/app/logs-next.test.ts @@ -0,0 +1,772 @@ +import Logs from './logs-next.js' +import {retrieveLogs} from '../../services/historical-logs/service.js' +import {prepareLogInput} from '../../services/historical-logs/input.js' +import {logsOutput, type LogsResult} from '../../services/historical-logs/types.js' +import {Config} from '@oclif/core' +import {afterEach, beforeEach, expect, test, vi} from 'vitest' +import {mockAndCaptureOutput, withCapturedStandardStreams} from '@shopify/cli-kit/node/testing/output' + +vi.mock('../../services/historical-logs/service.js', async (importOriginal) => ({ + ...(await importOriginal()), + retrieveLogs: vi.fn(), +})) + +const originalColumns = Object.getOwnPropertyDescriptor(process.stdout, 'columns') + +beforeEach(() => Object.defineProperty(process.stdout, 'columns', {value: 240, configurable: true})) + +afterEach(() => { + vi.unstubAllEnvs() + mockAndCaptureOutput().clear() + if (originalColumns) Object.defineProperty(process.stdout, 'columns', originalColumns) + else Reflect.deleteProperty(process.stdout, 'columns') +}) + +function result(): LogsResult { + return { + logs: [ + { + id: 'gid://shopify/AppLogRecord/example', + timestamp: '2026-10-06T13:30:00.123456789Z', + type: 'WEBHOOK', + resultStatus: 'FAILURE', + shopMyshopifyDomain: 'example.myshopify.com', + topic: 'orders/create', + extra: {nested: true}, + }, + ], + ordering: 'subset-timestamp-asc' as const, + limitations: [], + } +} + +test('remains hidden while historical logs are experimental', () => { + expect(Logs.hidden).toBe(true) +}) + +test('parses space/equals forms and forwards effective defaults', async () => { + vi.mocked(retrieveLogs).mockResolvedValue(result()) + await new Logs( + ['--client-id=explicit-app', '--type', 'webhook', '--topic=orders/create', '-s', 'example'], + await Config.load(), + ).run() + expect(retrieveLogs).toHaveBeenCalledWith( + expect.objectContaining({ + 'client-id': 'explicit-app', + type: ['webhook'], + topic: 'orders/create', + store: 'example', + since: '1h', + limit: 20, + }), + ) + expect(mockAndCaptureOutput().output()).toContain('Used fast retrieval: returned records shown oldest first') + expect(vi.mocked(retrieveLogs).mock.calls[0]![0].sort).toBeUndefined() + expect(vi.mocked(retrieveLogs).mock.calls[0]![0].order).toBeUndefined() +}) + +test('connects existing webhook and GraphQL filter flags to their exact API filters together', async () => { + vi.mocked(retrieveLogs).mockResolvedValue(result()) + + await new Logs( + [ + '--store', + 'example', + '--status', + 'failure', + '--topic', + 'orders/create', + '--status-code', + '500', + '--operation-type', + 'QUERY', + '--operation-name', + 'MyQuery', + '--request-id', + 'request-123', + ], + await Config.load(), + ).run() + + const flags = vi.mocked(retrieveLogs).mock.calls[0]![0] + expect(prepareLogInput(flags).filters).toEqual([ + {field: 'SHOP_MYSHOPIFY_DOMAIN', operator: 'EQUALS', value: 'example.myshopify.com'}, + {field: 'RESULT_STATUS', operator: 'EQUALS', value: 'FAILURE'}, + {field: 'TOPIC', operator: 'EQUALS', value: 'orders/create'}, + {field: 'STATUS_CODE', operator: 'EQUALS', value: '500'}, + {field: 'OPERATION_TYPE', operator: 'EQUALS', value: 'QUERY'}, + {field: 'OPERATION_NAME', operator: 'EQUALS', value: 'MyQuery'}, + {field: 'REQUEST_ID', operator: 'EQUALS', value: 'request-123'}, + ]) +}) + +test.each([ + {argv: []}, + {argv: ['--type=function', '--function-handle=discount', '--target', 'cart.lines.discounts.generate.run']}, +])('parses Function filters from environment variables with flag precedence for $argv', async ({argv}) => { + vi.stubEnv('SHOPIFY_FLAG_TYPE', 'function') + vi.stubEnv('SHOPIFY_FLAG_FUNCTION_HANDLE', 'environment-handle') + vi.stubEnv('SHOPIFY_FLAG_TARGET', 'environment-target') + vi.mocked(retrieveLogs).mockResolvedValue(result()) + + await new Logs(argv, await Config.load()).run() + + const input = prepareLogInput(vi.mocked(retrieveLogs).mock.calls[0]![0]) + expect(input.types).toEqual([{name: 'function', backend: 'FUNCTION_RUN'}]) + expect(input.filters).toEqual([ + {field: 'FUNCTION_HANDLE', operator: 'EQUALS', value: argv.length ? 'discount' : 'environment-handle'}, + { + field: 'TARGET', + operator: 'EQUALS', + value: argv.length ? 'cart.lines.discounts.generate.run' : 'environment-target', + }, + ]) +}) + +test.each([ + {argv: []}, + {argv: ['--type=app-event', '--event-handle=onboarding_completed']}, + {argv: ['--type', 'app-event', '--event-handle', 'onboarding_completed']}, +])('parses app event filters from environment variables with flag precedence for $argv', async ({argv}) => { + vi.stubEnv('SHOPIFY_FLAG_TYPE', 'app-event') + vi.stubEnv('SHOPIFY_FLAG_EVENT_HANDLE', 'environment-handle') + vi.mocked(retrieveLogs).mockResolvedValue(result()) + + await new Logs(argv, await Config.load()).run() + + const input = prepareLogInput(vi.mocked(retrieveLogs).mock.calls[0]![0]) + expect(input.types).toEqual([{name: 'app-event', backend: 'APP_EVENT'}]) + expect(input.filters).toEqual([ + {field: 'EVENT_HANDLE', operator: 'EQUALS', value: argv.length ? 'onboarding_completed' : 'environment-handle'}, + ]) +}) + +test('parses app billing events with shared event handle, store, and status filters', async () => { + vi.mocked(retrieveLogs).mockResolvedValue(result()) + + await new Logs( + ['--type', 'app-billing-event', '--event-handle=sms_sent', '--store', 'example', '--status=failure'], + await Config.load(), + ).run() + + const input = prepareLogInput(vi.mocked(retrieveLogs).mock.calls[0]![0]) + expect(input.types).toEqual([{name: 'app-billing-event', backend: 'APP_BILLING_EVENT'}]) + expect(input.filters).toEqual([ + {field: 'SHOP_MYSHOPIFY_DOMAIN', operator: 'EQUALS', value: 'example.myshopify.com'}, + {field: 'RESULT_STATUS', operator: 'EQUALS', value: 'FAILURE'}, + {field: 'EVENT_HANDLE', operator: 'EQUALS', value: 'sms_sent'}, + ]) +}) + +test.each([ + {argv: []}, + {argv: ['--type=rest', '--method=GET', '--request-path=/admin/api/products.json']}, + {argv: ['--type', 'rest', '--method', 'GET', '--request-path', '/admin/api/products.json']}, +])('parses REST filters from environment variables with flag precedence for $argv', async ({argv}) => { + vi.stubEnv('SHOPIFY_FLAG_TYPE', 'rest') + vi.stubEnv('SHOPIFY_FLAG_METHOD', 'POST') + vi.stubEnv('SHOPIFY_FLAG_REQUEST_PATH', '/environment-path') + vi.mocked(retrieveLogs).mockResolvedValue(result()) + + await new Logs(argv, await Config.load()).run() + + const input = prepareLogInput(vi.mocked(retrieveLogs).mock.calls[0]![0]) + expect(input.types).toEqual([{name: 'rest', backend: 'REST_REQUEST'}]) + expect(input.filters).toEqual([ + {field: 'METHOD', operator: 'EQUALS', value: argv.length ? 'GET' : 'POST'}, + {field: 'REQUEST_PATH', operator: 'EQUALS', value: argv.length ? '/admin/api/products.json' : '/environment-path'}, + ]) +}) + +test('parses Sidekick events with shared target, store, and status filters', async () => { + vi.mocked(retrieveLogs).mockResolvedValue(result()) + + await new Logs( + ['--type', 'sidekick', '--target=extensions/security_scan', '--store', 'example', '--status=failure'], + await Config.load(), + ).run() + + const input = prepareLogInput(vi.mocked(retrieveLogs).mock.calls[0]![0]) + expect(input.types).toEqual([{name: 'sidekick', backend: 'SIDEKICK_EVENT'}]) + expect(input.filters).toEqual([ + {field: 'SHOP_MYSHOPIFY_DOMAIN', operator: 'EQUALS', value: 'example.myshopify.com'}, + {field: 'RESULT_STATUS', operator: 'EQUALS', value: 'FAILURE'}, + {field: 'TARGET', operator: 'EQUALS', value: 'extensions/security_scan'}, + ]) +}) + +test('parses UI extension errors with shared target, store, and status filters', async () => { + vi.mocked(retrieveLogs).mockResolvedValue(result()) + + await new Logs( + ['--type', 'ui-extension', '--target=purchase.checkout.block.render', '--store', 'example', '--status=failure'], + await Config.load(), + ).run() + + const input = prepareLogInput(vi.mocked(retrieveLogs).mock.calls[0]![0]) + expect(input.types).toEqual([{name: 'ui-extension', backend: 'UI_EXTENSION'}]) + expect(input.filters).toEqual([ + {field: 'SHOP_MYSHOPIFY_DOMAIN', operator: 'EQUALS', value: 'example.myshopify.com'}, + {field: 'RESULT_STATUS', operator: 'EQUALS', value: 'FAILURE'}, + {field: 'TARGET', operator: 'EQUALS', value: 'purchase.checkout.block.render'}, + ]) +}) + +test('accepts the maximum limit through parsing and input validation', async () => { + vi.mocked(retrieveLogs).mockResolvedValue(result()) + + await new Logs(['--limit', '1000'], await Config.load()).run() + + const flags = vi.mocked(retrieveLogs).mock.calls[0]![0] + expect(prepareLogInput(flags).limit).toBe(1000) +}) + +test('omitted type and repeated type flags are passed to the service without inventing filter OR', async () => { + vi.mocked(retrieveLogs).mockResolvedValue(result()) + await new Logs(['--client-id', 'explicit-app'], await Config.load()).run() + expect(vi.mocked(retrieveLogs).mock.calls[0]?.[0].type).toBeUndefined() + await new Logs( + [ + '--type', + 'webhook', + '--type', + 'graphql', + '--type', + 'function', + '--type', + 'app-event', + '--type', + 'app-billing-event', + '--type', + 'rest', + '--type', + 'sidekick', + '--type', + 'ui-extension', + '--request-id', + 'request-123', + ], + await Config.load(), + ).run() + expect(retrieveLogs).toHaveBeenLastCalledWith( + expect.objectContaining({ + type: ['webhook', 'graphql', 'function', 'app-event', 'app-billing-event', 'rest', 'sidekick', 'ui-extension'], + 'request-id': 'request-123', + }), + ) +}) + +test.each([ + {argv: [], backend: 'WEBHOOK'}, + {argv: ['--type', 'graphql'], backend: 'GRAPHQL_REQUEST'}, +])('resolves the environment log type with command-line precedence for $argv', async ({argv, backend}) => { + vi.stubEnv('SHOPIFY_FLAG_TYPE', 'webhook') + vi.mocked(retrieveLogs).mockResolvedValue(result()) + + await new Logs(argv, await Config.load()).run() + + const flags = vi.mocked(retrieveLogs).mock.calls[0]![0] + expect(prepareLogInput(flags).types).toEqual([expect.objectContaining({backend})]) +}) + +test.each([ + {argv: ['--sort', 'timestamp'], order: undefined}, + {argv: ['--sort=timestamp', '--order=asc'], order: 'asc'}, + {argv: ['--sort', 'timestamp', '--order', 'desc'], order: 'desc'}, +])('parses explicit sorting flags $argv', async ({argv, order}) => { + vi.mocked(retrieveLogs).mockResolvedValue(result()) + + await new Logs(argv, await Config.load()).run() + + const flags = vi.mocked(retrieveLogs).mock.calls[0]![0] + expect(flags.sort).toBe('timestamp') + expect(flags.order).toBe(order) +}) + +test('accepts sorting from environment variables and requires the sort key', async () => { + vi.stubEnv('SHOPIFY_FLAG_SORT', 'timestamp') + vi.stubEnv('SHOPIFY_FLAG_ORDER', 'desc') + vi.mocked(retrieveLogs).mockResolvedValue(result()) + + await new Logs([], await Config.load()).run() + + expect(retrieveLogs).toHaveBeenCalledWith(expect.objectContaining({sort: 'timestamp', order: 'desc'})) + vi.stubEnv('SHOPIFY_FLAG_SORT', undefined) + vi.mocked(retrieveLogs).mockClear() + await expect(new Logs([], await Config.load()).run()).rejects.toThrow() + expect(retrieveLogs).not.toHaveBeenCalled() +}) + +test.each([ + ['--client-id', 'one', '--client-id=two'], + ['--status', 'success', '--status=failure'], + ['--store', 'one', '--store=two'], + ['--topic', 'orders/create', '--topic=orders/delete'], + ['--operation-name', 'one', '--operation-name=two'], + ['--function-handle', 'one', '--function-handle=two'], + ['--target', 'one', '--target=two'], + ['--event-handle', 'one', '--event-handle=two'], + ['--method', 'GET', '--method=POST'], + ['--request-path', '/one', '--request-path=/two'], + ['--since', '1h', '--since=2h'], + ['--limit', '10', '--limit=20'], + ['--until', '2026-10-06T13:00:00Z', '--until=2026-10-06T14:00:00Z'], + ['--sort', 'timestamp', '--sort=timestamp'], + ['--sort', 'timestamp', '--order', 'asc', '--order=desc'], +])('rejects repeated singular flags %j before authentication', async (...argv) => { + await expect(new Logs(['--type', 'webhook', ...argv], await Config.load()).run()).rejects.toThrow( + 'can only be specified once', + ) + expect(retrieveLogs).not.toHaveBeenCalled() +}) + +test.each([ + ['--type', 'unsupported'], + ['--sort', 'id'], + ['--sort', 'timestamp', '--order', 'ascending'], + ['--order', 'asc'], + ['--order', 'desc'], + ['--type', 'webhook', '--offset', '10'], + ['--type', 'graphql', '--client-ip', '123'], + ['--type', 'graphql', '--user-agent', 'test'], + ['--type', 'webhook', '--query', '{ app }'], +])('rejects missing or unsupported flags %j', async (...argv) => { + await expect(new Logs(argv, await Config.load()).run()).rejects.toThrow() + expect(retrieveLogs).not.toHaveBeenCalled() +}) + +test.each([ + {argv: ['--json'], json: true, noInput: false}, + {argv: ['--no-input'], json: false, noInput: true}, + {argv: ['--json', '--no-input'], json: true, noInput: true}, +])('keeps JSON and no-input independent ($argv)', async ({argv, json, noInput}) => { + vi.mocked(retrieveLogs).mockResolvedValue(result()) + await new Logs(['--type', 'webhook', ...argv], await Config.load()).run() + expect(vi.mocked(retrieveLogs).mock.calls[0]![0]['no-input'] ?? false).toBe(noInput) + expect(mockAndCaptureOutput().output().startsWith('{')).toBe(json) + if (json) expect(JSON.parse(mockAndCaptureOutput().output())).toEqual(result()) +}) + +test('JSON writes one complete object without query or pagination metadata or terminal text', async () => { + vi.mocked(retrieveLogs).mockResolvedValue(result()) + await withCapturedStandardStreams(async ({stdout, stderr}) => { + await new Logs(['--type', 'webhook', '--json', '--no-input'], await Config.load()).run() + expect(JSON.parse(stdout())).toEqual(result()) + expect(JSON.parse(stdout())).not.toHaveProperty('query') + expect(JSON.parse(stdout())).not.toHaveProperty('pageInfo') + expect(stderr()).toBe('') + }) +}) + +test('webhook-only human output omits the inapplicable API column', async () => { + vi.mocked(retrieveLogs).mockResolvedValue(result()) + await withCapturedStandardStreams(async ({stdout, stderr}) => { + await new Logs(['--type', 'webhook'], await Config.load()).run() + expect(stdout()).toBe('') + const lines = stderr().trim().split('\n') + expect(lines[1]!.trim().split(/ {2,}/)).toEqual(['Timestamp', 'Type', 'Result', 'Store', 'Details']) + expect(lines[3]!.trim().split(/ {2,}/)).toEqual([ + '2026-10-06T13:30:00.123456789Z', + 'WEBHOOK', + 'FAILURE', + 'example.myshopify.com', + 'orders/create', + ]) + }) +}) + +test.each([ + ['timestamp-asc', 'Oldest first'], + ['timestamp-desc', 'Newest first'], +] as const)('renders %s without result disclaimers in table and JSON output', async (ordering, label) => { + const data = { + ...result(), + ordering, + limitations: [], + } + vi.mocked(retrieveLogs).mockResolvedValue(data) + + await withCapturedStandardStreams(async ({stdout, stderr}) => { + await new Logs([], await Config.load()).run() + expect(stdout()).toBe('') + expect(stderr().split('\n')[0]).toBe(`${label} by timestamp.`) + expect(stderr()).not.toContain('Additional records may match your search.') + expect(stderr()).not.toContain('Used fast retrieval') + expect(stderr()).toContain('orders/create') + }) + await withCapturedStandardStreams(async ({stdout, stderr}) => { + await new Logs(['--json'], await Config.load()).run() + expect(JSON.parse(stdout())).toEqual(data) + expect(stderr()).toBe('') + }) +}) + +test.each(['ADMIN', undefined])('GraphQL-only human output keeps the API column for %s', async (api) => { + const data = result() + data.logs = [{...data.logs[0]!, type: 'GRAPHQL_REQUEST', topic: undefined, operationName: 'MyQuery', api}] + vi.mocked(retrieveLogs).mockResolvedValue(data) + await withCapturedStandardStreams(async ({stderr}) => { + await new Logs(['--type', 'graphql'], await Config.load()).run() + const lines = stderr().trim().split('\n') + expect(lines[1]!.trim().split(/ {2,}/).at(-1)).toBe('API') + expect(lines[3]!.trim().split(/ {2,}/).slice(-2)).toEqual(['MyQuery', api ?? 'unknown']) + }) +}) + +test.each([ + {functionHandle: 'discount', target: 'cart.lines.discounts.generate.run', details: 'discount', status: 'FAILURE'}, + {functionHandle: null, target: 'cart.lines.discounts.generate.run', details: 'cart.lines.discounts.generate.run'}, + {target: 'cart.lines.discounts.generate.run', details: 'cart.lines.discounts.generate.run', status: null}, + {functionHandle: null, target: null, details: 'unknown'}, + { + functionHandle: `discount\n${'a'.repeat(100)}`, + details: `discount\\u000a${'a'.repeat(85)}…`, + status: 'SUCCESS', + }, +])( + 'Function human output shows $details with the recorded result', + async ({functionHandle, target, details, status}) => { + const data = result() + data.logs = [{...data.logs[0]!, type: 'FUNCTION_RUN', functionHandle, target, resultStatus: status}] + vi.mocked(retrieveLogs).mockResolvedValue(data) + + await withCapturedStandardStreams(async ({stderr}) => { + await new Logs(['--type', 'function'], await Config.load()).run() + const lines = stderr().trim().split('\n') + expect(lines[1]!.trim().split(/ {2,}/)).toEqual(['Timestamp', 'Type', 'Result', 'Store', 'Details']) + expect(lines[3]!.trim().split(/ {2,}/)).toEqual([ + data.logs[0]!.timestamp, + 'FUNCTION_RUN', + status ?? 'unknown', + 'example.myshopify.com', + details, + ]) + }) + }, +) + +test.each([ + {eventHandle: 'onboarding_completed', details: 'onboarding_completed'}, + {eventHandle: null, details: 'unknown'}, + {eventHandle: undefined, details: 'unknown'}, + {eventHandle: `event\n${'a'.repeat(100)}`, details: `event\\u000a${'a'.repeat(88)}…`}, +])('app event human output shows $details and no result status', async ({eventHandle, details}) => { + const data = result() + data.logs = [{timestamp: data.logs[0]!.timestamp, type: 'APP_EVENT', shopMyshopifyDomain: null, eventHandle}] + vi.mocked(retrieveLogs).mockResolvedValue(data) + + await withCapturedStandardStreams(async ({stdout, stderr}) => { + await new Logs(['--type', 'app-event'], await Config.load()).run() + expect(stdout()).toBe('') + const lines = stderr().trim().split('\n') + expect(lines[1]!.trim().split(/ {2,}/)).toEqual(['Timestamp', 'Type', 'Result', 'Store', 'Details']) + expect(lines[3]!.trim().split(/ {2,}/)).toEqual([data.logs[0]!.timestamp, 'APP_EVENT', '—', 'unknown', details]) + }) +}) + +test.each([ + {eventHandle: 'sms_sent', details: 'sms_sent', status: 'FAILURE'}, + {eventHandle: null, details: 'unknown', status: null}, + {eventHandle: undefined, details: 'unknown', status: undefined}, + {eventHandle: `event\n${'a'.repeat(100)}`, details: `event\\u000a${'a'.repeat(88)}…`, status: 'SUCCESS'}, +])('app billing event human output shows $details with the recorded result', async ({eventHandle, details, status}) => { + const data = result() + data.logs = [{...data.logs[0]!, type: 'APP_BILLING_EVENT', eventHandle, resultStatus: status}] + vi.mocked(retrieveLogs).mockResolvedValue(data) + + await withCapturedStandardStreams(async ({stdout, stderr}) => { + await new Logs(['--type', 'app-billing-event'], await Config.load()).run() + expect(stdout()).toBe('') + const lines = stderr().trim().split('\n') + expect(lines[1]!.trim().split(/ {2,}/)).toEqual(['Timestamp', 'Type', 'Result', 'Store', 'Details']) + expect(lines[3]!.trim().split(/ {2,}/)).toEqual([ + data.logs[0]!.timestamp, + 'APP_BILLING_EVENT', + status ?? 'unknown', + 'example.myshopify.com', + details, + ]) + }) +}) + +test.each([ + {method: 'GET', requestPath: '/products.json', details: 'GET /products.json', status: 'FAILURE'}, + {method: 'GET', requestPath: null, details: 'GET', status: null}, + {method: undefined, requestPath: '/products.json', details: '/products.json'}, + {method: null, requestPath: null, details: 'unknown'}, + {method: undefined, requestPath: undefined, details: 'unknown'}, + {method: '', requestPath: '', details: 'unknown'}, + {method: '', requestPath: '/products.json', details: '/products.json'}, + {method: 'GET', requestPath: '', details: 'GET'}, + {method: 42, requestPath: false, details: 'unknown'}, + {method: 'GET', requestPath: `/\n${'a'.repeat(100)}`, details: `GET /\\u000a${'a'.repeat(88)}…`, status: 'SUCCESS'}, +])('REST human output shows $details with the recorded result', async ({method, requestPath, details, status}) => { + const data = result() + data.logs = [{...data.logs[0]!, type: 'REST_REQUEST', method, requestPath, resultStatus: status, statusCode: 200}] + vi.mocked(retrieveLogs).mockResolvedValue(data) + + await withCapturedStandardStreams(async ({stdout, stderr}) => { + await new Logs(['--type', 'rest'], await Config.load()).run() + expect(stdout()).toBe('') + const lines = stderr().trim().split('\n') + expect(lines[1]!.trim().split(/ {2,}/)).toEqual(['Timestamp', 'Type', 'Result', 'Store', 'Details']) + expect(lines[3]!.trim().split(/ {2,}/)).toEqual([ + data.logs[0]!.timestamp, + 'REST_REQUEST', + status ?? 'unknown', + 'example.myshopify.com', + details, + ]) + }) +}) + +test.each([ + {target: 'extensions/security_scan', details: 'extensions/security_scan', status: 'FAILURE'}, + {target: null, details: 'unknown', status: null}, + {target: undefined, details: 'unknown', status: undefined}, + {target: `extensions/\n${'a'.repeat(100)}`, details: `extensions/\\u000a${'a'.repeat(82)}…`, status: 'SUCCESS'}, +])('Sidekick human output shows $details with the recorded result', async ({target, details, status}) => { + const data = result() + data.logs = [ + {...data.logs[0]!, type: 'SIDEKICK_EVENT', target, resultStatus: status, errorMessage: 'not-in-human-summary'}, + ] + vi.mocked(retrieveLogs).mockResolvedValue(data) + + await withCapturedStandardStreams(async ({stdout, stderr}) => { + await new Logs(['--type', 'sidekick'], await Config.load()).run() + expect(stdout()).toBe('') + const lines = stderr().trim().split('\n') + expect(lines[1]!.trim().split(/ {2,}/)).toEqual(['Timestamp', 'Type', 'Result', 'Store', 'Details']) + expect(lines[3]!.trim().split(/ {2,}/)).toEqual([ + data.logs[0]!.timestamp, + 'SIDEKICK_EVENT', + status ?? 'unknown', + 'example.myshopify.com', + details, + ]) + expect(stderr()).not.toContain('not-in-human-summary') + }) +}) + +test.each([ + {target: 'purchase.checkout.block.render', details: 'purchase.checkout.block.render', status: 'FAILURE'}, + {target: null, details: 'unknown', status: null}, + {target: undefined, details: 'unknown', status: undefined}, + {target: `extensions/\n${'a'.repeat(100)}`, details: `extensions/\\u000a${'a'.repeat(82)}…`, status: 'SUCCESS'}, +])('UI extension error human output shows $details with the recorded result', async ({target, details, status}) => { + const data = result() + data.logs = [ + {...data.logs[0]!, type: 'UI_EXTENSION', target, resultStatus: status, errorMessage: 'not-in-human-summary'}, + ] + vi.mocked(retrieveLogs).mockResolvedValue(data) + + await withCapturedStandardStreams(async ({stdout, stderr}) => { + await new Logs(['--type', 'ui-extension'], await Config.load()).run() + expect(stdout()).toBe('') + const lines = stderr().trim().split('\n') + expect(lines[1]!.trim().split(/ {2,}/)).toEqual(['Timestamp', 'Type', 'Result', 'Store', 'Details']) + expect(lines[3]!.trim().split(/ {2,}/)).toEqual([ + data.logs[0]!.timestamp, + 'UI_EXTENSION', + status ?? 'unknown', + 'example.myshopify.com', + details, + ]) + expect(stderr()).not.toContain('not-in-human-summary') + }) +}) + +test('human output aligns headers with mixed log rows between the warning and JSON hint', async () => { + const data = result() + data.logs.push({ + id: 'gid://shopify/AppLogRecord/another', + timestamp: '2026-10-06T13:31:00Z', + type: 'GRAPHQL_REQUEST', + resultStatus: 'SUCCESS', + shopMyshopifyDomain: 'longer-example.myshopify.com', + operationName: 'QueryWithALongerOperationName', + api: 'STOREFRONT', + }) + data.logs.push({ + timestamp: '2026-10-06T13:32:00Z', + type: 'FUNCTION_RUN', + resultStatus: 'FAILURE', + shopMyshopifyDomain: 'example.myshopify.com', + functionHandle: 'discount', + target: 'cart.lines.discounts.generate.run', + }) + data.logs.push({ + timestamp: '2026-10-06T13:33:00Z', + type: 'APP_EVENT', + shopMyshopifyDomain: 'example.myshopify.com', + eventHandle: 'onboarding_completed', + }) + data.logs.push({ + timestamp: '2026-10-06T13:34:00Z', + type: 'APP_BILLING_EVENT', + resultStatus: 'SUCCESS', + shopMyshopifyDomain: 'example.myshopify.com', + eventHandle: 'sms_sent', + }) + data.logs.push({ + timestamp: '2026-10-06T13:35:00Z', + type: 'REST_REQUEST', + resultStatus: 'FAILURE', + shopMyshopifyDomain: 'example.myshopify.com', + method: 'GET', + requestPath: '/products.json', + }) + data.logs.push({ + timestamp: '2026-10-06T13:36:00Z', + type: 'SIDEKICK_EVENT', + resultStatus: 'SUCCESS', + shopMyshopifyDomain: 'example.myshopify.com', + target: 'extensions/security_scan', + }) + data.logs.push({ + timestamp: '2026-10-06T13:37:00Z', + type: 'UI_EXTENSION', + resultStatus: 'SUCCESS', + shopMyshopifyDomain: 'example.myshopify.com', + target: 'purchase.checkout.block.render', + }) + vi.mocked(retrieveLogs).mockResolvedValue(data) + await withCapturedStandardStreams(async ({stdout, stderr}) => { + await new Logs([], await Config.load()).run() + expect(stdout()).toBe('') + const lines = stderr().trim().split('\n') + expect(lines[0]).toBe('Used fast retrieval: returned records shown oldest first.') + expect(lines.at(-1)).toBe('Use --json for full records.') + expect(lines).toHaveLength(13) + expect(lines.at(-2)).toBe('Returned all 8 matching records available at query time.') + const headers = ['Timestamp', 'Type', 'Result', 'Store', 'Details', 'API'] + expect(lines[1]!.trim().split(/ {2,}/)).toEqual(headers) + for (const [index, record] of data.logs.entries()) { + const values = [ + record.timestamp, + record.type, + record.resultStatus ?? '—', + record.shopMyshopifyDomain, + record.topic ?? + record.operationName ?? + record.functionHandle ?? + record.eventHandle ?? + record.target ?? + `${record.method} ${record.requestPath}`, + record.api ?? '—', + ] + const row = lines[index + 3]! + expect(row.trim().split(/ {2,}/)).toEqual(values) + for (const [column, header] of headers.entries()) { + const start = lines[1]!.indexOf(header) + expect(row.slice(start, start + String(values[column]).length)).toBe(String(values[column])) + } + } + }) +}) + +test('empty human output confirms no matches without a table or footer', async () => { + vi.mocked(retrieveLogs).mockResolvedValue({...result(), logs: []}) + await withCapturedStandardStreams(async ({stdout, stderr}) => { + await new Logs(['--type', 'webhook'], await Config.load()).run() + expect(stdout()).toBe('') + expect(stderr().trim().split('\n')).toEqual(['No matching records available at query time.']) + }) +}) + +test.each(['subset-timestamp-asc', 'timestamp-asc', 'timestamp-desc'] as const)( + 'human output confirms a below-limit result for %s', + async (ordering) => { + vi.mocked(retrieveLogs).mockResolvedValue({...result(), ordering}) + + await withCapturedStandardStreams(async ({stderr}) => { + await new Logs(['--limit', '2'], await Config.load()).run() + + expect(stderr()).toContain('Returned all 1 matching record available at query time.') + expect(stderr()).not.toContain('additional records may match') + expect(stderr()).not.toContain('not necessarily') + }) + }, +) + +test.each(['subset-timestamp-asc', 'timestamp-asc', 'timestamp-desc'] as const)( + 'human output warns at the requested limit for %s without asserting completeness', + async (ordering) => { + const data = {...result(), ordering, limitations: ['Reached the limit of 1 record; additional records may match.']} + vi.mocked(retrieveLogs).mockResolvedValue(data) + + await withCapturedStandardStreams(async ({stderr}) => { + await new Logs(['--limit', '1'], await Config.load()).run() + + expect(stderr()).toContain('Reached the limit of 1 record; additional records may match.') + expect(stderr()).not.toContain('Returned all') + }) + }, +) + +test('human output marks abbreviated cells and does not print body data', async () => { + const data = result() + data.logs[0]!.topic = `orders/${'a'.repeat(150)}` + data.logs[0]!.requestBody = 'not-in-human-summary' + vi.mocked(retrieveLogs).mockResolvedValue(data) + await withCapturedStandardStreams(async ({stdout, stderr}) => { + await new Logs(['--type', 'webhook'], await Config.load()).run() + expect(stdout()).toBe('') + expect(stderr()).toContain(`orders/${'a'.repeat(92)}…`) + expect(stderr()).toContain('Use --json for full records.') + expect(stderr()).not.toContain('not-in-human-summary') + }) + expect(JSON.parse(logsOutput.encode(data)).logs).toEqual(data.logs) +}) + +test.each([ + {topic: `${'a'.repeat(98)}😀z`, displayed: `${'a'.repeat(98)}…`}, + {topic: `${'a'.repeat(98)}\nz`, displayed: `${'a'.repeat(98)}…`}, + {topic: `${'a'.repeat(93)}\nzz`, displayed: `${'a'.repeat(93)}\\u000a…`}, + {topic: `${'a'.repeat(98)}😀`, displayed: `${'a'.repeat(98)}😀`}, +])('human output keeps Unicode and control escapes intact when abbreviating $topic', async ({topic, displayed}) => { + const data = result() + data.logs[0]!.topic = topic + vi.mocked(retrieveLogs).mockResolvedValue(data) + + await withCapturedStandardStreams(async ({stderr}) => { + await new Logs(['--type', 'webhook'], await Config.load()).run() + + expect(stderr().trim().split('\n')[3]!.trim().split(/ {2,}/).at(-1)).toBe(displayed) + }) + expect(JSON.parse(logsOutput.encode(data)).logs[0].topic).toBe(topic) +}) + +test('escapes terminal control characters in human output without changing JSON', async () => { + const data = result() + data.logs[0]!.topic = 'orders/\u001b[31mred\u001b[0m\nnext\u202eline' + vi.mocked(retrieveLogs).mockResolvedValue(data) + await withCapturedStandardStreams(async ({stderr}) => { + await new Logs(['--type', 'webhook'], await Config.load()).run() + expect(stderr()).toContain('orders/red\\u000anext\\u202eline') + expect(stderr()).not.toContain('\u001b[31m') + }) + expect(JSON.parse(logsOutput.encode(data)).logs).toEqual(data.logs) +}) + +test('help states the backend time-window limits', () => { + expect(Logs.description).toContain('Maximum: 1-day window within the last 7 days, 1000 records.') +}) + +test('publishes a strict envelope and an extensible native record schema', () => { + expect(Logs.jsonOutputSchema).toBe(logsOutput) + expect(Logs.descriptionForHelp()).toContain('HistoricalAppLogs') + expect(Logs.description).toContain('HistoricalAppLogs') + expect(() => logsOutput.validate({...result(), accidental: true})).toThrow() + expect(() => logsOutput.validate({...result(), query: {clientId: 'test-app'}})).toThrow() + expect(JSON.parse(logsOutput.encode(result())).logs[0].extra).toEqual({nested: true}) + expect(logsOutput.jsonSchema).toHaveProperty('properties.logs') + expect(logsOutput.jsonSchema).toHaveProperty('properties.ordering.enum', [ + 'subset-timestamp-asc', + 'timestamp-asc', + 'timestamp-desc', + ]) + expect(logsOutput.jsonSchema).not.toHaveProperty('properties.query') + expect(logsOutput.jsonSchema).not.toHaveProperty('properties.pageInfo') + expect(() => logsOutput.validate({...result(), pageInfo: {limit: 20}})).toThrow() +}) diff --git a/packages/app/src/cli/commands/app/logs-next.ts b/packages/app/src/cli/commands/app/logs-next.ts new file mode 100644 index 00000000000..a1f2d48e5df --- /dev/null +++ b/packages/app/src/cli/commands/app/logs-next.ts @@ -0,0 +1,38 @@ +import {historicalLogFlags} from '../../services/historical-logs/flags.js' +import {retrieveLogs} from '../../services/historical-logs/service.js' +import {renderHistoricalLogs} from '../../services/historical-logs/presenter.js' +import {logsOutput} from '../../services/historical-logs/types.js' +import BaseCommand from '@shopify/cli-kit/node/base-command' +import {authAliasFlag, globalFlags, jsonFlag} from '@shopify/cli-kit/node/cli' + +export default class Logs extends BaseCommand { + static hidden = true + static baseFlags = {...BaseCommand.baseFlags, ...authAliasFlag} + static summary = 'Lists historical app logs.' + static descriptionWithMarkdown = `Returns a list of historical app logs and exits. Defaults to all supported log types. Use --type to select a type; repeat it to select multiple. + +Fast retrieval is the default: leave out --sort. Prefer this mode with a narrow time window and selective filters to consume less throttle capacity. The CLI orders the returned records oldest first, but when the limit is reached they aren't necessarily the oldest or newest matches. + +Use server-side sorting only when selecting the oldest or newest matching records matters: --sort timestamp selects oldest first; add --order desc for newest first. This sorts before the result limit and is subject to API query limits. + +When fewer than --limit records are returned, all matching records available at query time were returned. Sorting isn't needed to establish completeness. + +Different filters combine with AND; each accepts one exact value. Type-specific filters exclude records without that field; combining --topic and --operation-name returns no records. + +Defaults: preceding hour, 20 records. Maximum: 1-day window within the last 7 days, 1000 records. Time inputs accept whole seconds only. + +--json preserves native record JSON in logs[], including fractional timestamps, diagnostic fields, bodies, and producer truncation flags.` + static jsonOutputSchema = logsOutput + static description = this.descriptionForHelp() + static flags = {...globalFlags, ...jsonFlag, ...historicalLogFlags} + static examples = [ + '<%= config.bin %> <%= command.id %> --client-id APP_CLIENT_ID --type webhook --topic orders/create --status failure --since 30m', + '<%= config.bin %> <%= command.id %> --type graphql --operation-name MyQuery --json --no-input', + '<%= config.bin %> <%= command.id %> --since 1h --sort timestamp --order desc', + ] + + async run(): Promise { + const {flags} = await this.parse(Logs) + renderHistoricalLogs(await retrieveLogs(flags), flags.json, flags.limit) + } +} diff --git a/packages/app/src/cli/commands/app/logs.test.ts b/packages/app/src/cli/commands/app/logs.test.ts index 9ca2ba4f611..fbdd314238d 100644 --- a/packages/app/src/cli/commands/app/logs.test.ts +++ b/packages/app/src/cli/commands/app/logs.test.ts @@ -1,789 +1,75 @@ import Logs from './logs.js' -import {commonLogFilters, logFilters, logTypes} from '../../services/historical-logs/catalog.js' -import {historicalLogFlags} from '../../services/historical-logs/flags.js' -import {retrieveLogs} from '../../services/historical-logs/service.js' -import {prepareLogInput} from '../../services/historical-logs/input.js' -import {logsOutput, type LogsResult} from '../../services/historical-logs/types.js' import {Config} from '@oclif/core' -import {afterEach, beforeEach, expect, test, vi} from 'vitest' -import {mockAndCaptureOutput, withCapturedStandardStreams} from '@shopify/cli-kit/node/testing/output' +import {reportAnalyticsEvent} from '@shopify/cli-kit/node/analytics' +import {unstyled} from '@shopify/cli-kit/node/output' +import {withCapturedStandardStreams} from '@shopify/cli-kit/node/testing/output' +import {afterEach, describe, expect, test, vi} from 'vitest' +import {fileURLToPath} from 'node:url' -vi.mock('../../services/historical-logs/service.js', async (importOriginal) => ({ - ...(await importOriginal()), - retrieveLogs: vi.fn(), -})) +vi.mock('@shopify/cli-kit/node/analytics') -const originalColumns = Object.getOwnPropertyDescriptor(process.stdout, 'columns') - -beforeEach(() => Object.defineProperty(process.stdout, 'columns', {value: 240, configurable: true})) +const removalMessage = + '`shopify app logs` and `shopify app logs sources` were removed in Shopify CLI 5.0. ' + + 'To see Function logs, run `shopify app dev`.' +const originalExitCode = process.exitCode afterEach(() => { + process.exitCode = originalExitCode vi.unstubAllEnvs() - mockAndCaptureOutput().clear() - if (originalColumns) Object.defineProperty(process.stdout, 'columns', originalColumns) - else Reflect.deleteProperty(process.stdout, 'columns') -}) - -function result(): LogsResult { - return { - logs: [ - { - id: 'gid://shopify/AppLogRecord/example', - timestamp: '2026-10-06T13:30:00.123456789Z', - type: 'WEBHOOK', - resultStatus: 'FAILURE', - shopMyshopifyDomain: 'example.myshopify.com', - topic: 'orders/create', - extra: {nested: true}, - }, - ], - ordering: 'subset-timestamp-asc' as const, - limitations: [], - } -} - -test('help lists every log type with its filters, and every filter applies to a type', () => { - const typedFilters = new Set([...commonLogFilters, ...logTypes.flatMap(({filters}) => filters)]) - - expect(logFilters.map(({flag}) => flag).filter((flag) => !typedFilters.has(flag))).toEqual([]) - expect( - Object.entries(historicalLogFlags) - .filter(([, flag]) => flag.helpGroup === 'FILTER') - .map(([name]) => name), - ).toEqual(logFilters.map(({flag}) => flag)) - expect(Logs.description).toContain('Every type also accepts --store.') - expect(Logs.description).toContain( - '- app-event: Events the app sent with the App Events API. Filters: --event-handle.', - ) - expect(Logs.description).toContain( - '- function: Shopify Function runs. Filters: --status, --function-handle, --target.', - ) - for (const {name} of logTypes) expect(Logs.description).toContain(`- ${name}: `) }) -test('help states the backend time-window limits', () => { - expect(Logs.description).toContain('Maximum: 1-day window within the last 7 days, 1000 records.') -}) - -test('parses space/equals forms and forwards effective defaults', async () => { - vi.mocked(retrieveLogs).mockResolvedValue(result()) - await new Logs( - ['--client-id=explicit-app', '--type', 'webhook', '--topic=orders/create', '-s', 'example'], - await Config.load(), - ).run() - expect(retrieveLogs).toHaveBeenCalledWith( - expect.objectContaining({ - 'client-id': 'explicit-app', - type: ['webhook'], - topic: 'orders/create', - store: 'example', - since: '1h', - limit: 20, - }), - ) - expect(mockAndCaptureOutput().output()).toContain('Used fast retrieval: returned records shown oldest first') - expect(vi.mocked(retrieveLogs).mock.calls[0]![0].sort).toBeUndefined() - expect(vi.mocked(retrieveLogs).mock.calls[0]![0].order).toBeUndefined() -}) - -test('connects existing webhook and GraphQL filter flags to their exact API filters together', async () => { - vi.mocked(retrieveLogs).mockResolvedValue(result()) - - await new Logs( +describe('removed app logs command', () => { + test.each( [ - '--store', - 'example', - '--status', - 'failure', - '--topic', - 'orders/create', - '--status-code', - '500', - '--operation-type', - 'QUERY', - '--operation-name', - 'MyQuery', - '--request-id', - 'request-123', - ], - await Config.load(), - ).run() - - const flags = vi.mocked(retrieveLogs).mock.calls[0]![0] - expect(prepareLogInput(flags).filters).toEqual([ - {field: 'SHOP_MYSHOPIFY_DOMAIN', operator: 'EQUALS', value: 'example.myshopify.com'}, - {field: 'RESULT_STATUS', operator: 'EQUALS', value: 'FAILURE'}, - {field: 'TOPIC', operator: 'EQUALS', value: 'orders/create'}, - {field: 'STATUS_CODE', operator: 'EQUALS', value: '500'}, - {field: 'OPERATION_TYPE', operator: 'EQUALS', value: 'QUERY'}, - {field: 'OPERATION_NAME', operator: 'EQUALS', value: 'MyQuery'}, - {field: 'REQUEST_ID', operator: 'EQUALS', value: 'request-123'}, - ]) -}) - -test.each([ - {argv: []}, - {argv: ['--type=function', '--function-handle=discount', '--target', 'cart.lines.discounts.generate.run']}, -])('parses Function filters from environment variables with flag precedence for $argv', async ({argv}) => { - vi.stubEnv('SHOPIFY_FLAG_TYPE', 'function') - vi.stubEnv('SHOPIFY_FLAG_FUNCTION_HANDLE', 'environment-handle') - vi.stubEnv('SHOPIFY_FLAG_TARGET', 'environment-target') - vi.mocked(retrieveLogs).mockResolvedValue(result()) - - await new Logs(argv, await Config.load()).run() - - const input = prepareLogInput(vi.mocked(retrieveLogs).mock.calls[0]![0]) - expect(input.types).toEqual([{name: 'function', backend: 'FUNCTION_RUN'}]) - expect(input.filters).toEqual([ - {field: 'FUNCTION_HANDLE', operator: 'EQUALS', value: argv.length ? 'discount' : 'environment-handle'}, - { - field: 'TARGET', - operator: 'EQUALS', - value: argv.length ? 'cart.lines.discounts.generate.run' : 'environment-target', - }, - ]) -}) - -test.each([ - {argv: []}, - {argv: ['--type=app-event', '--event-handle=onboarding_completed']}, - {argv: ['--type', 'app-event', '--event-handle', 'onboarding_completed']}, -])('parses app event filters from environment variables with flag precedence for $argv', async ({argv}) => { - vi.stubEnv('SHOPIFY_FLAG_TYPE', 'app-event') - vi.stubEnv('SHOPIFY_FLAG_EVENT_HANDLE', 'environment-handle') - vi.mocked(retrieveLogs).mockResolvedValue(result()) - - await new Logs(argv, await Config.load()).run() - - const input = prepareLogInput(vi.mocked(retrieveLogs).mock.calls[0]![0]) - expect(input.types).toEqual([{name: 'app-event', backend: 'APP_EVENT'}]) - expect(input.filters).toEqual([ - {field: 'EVENT_HANDLE', operator: 'EQUALS', value: argv.length ? 'onboarding_completed' : 'environment-handle'}, - ]) -}) - -test('parses app billing events with shared event handle, store, and status filters', async () => { - vi.mocked(retrieveLogs).mockResolvedValue(result()) - - await new Logs( - ['--type', 'app-billing-event', '--event-handle=sms_sent', '--store', 'example', '--status=failure'], - await Config.load(), - ).run() - - const input = prepareLogInput(vi.mocked(retrieveLogs).mock.calls[0]![0]) - expect(input.types).toEqual([{name: 'app-billing-event', backend: 'APP_BILLING_EVENT'}]) - expect(input.filters).toEqual([ - {field: 'SHOP_MYSHOPIFY_DOMAIN', operator: 'EQUALS', value: 'example.myshopify.com'}, - {field: 'RESULT_STATUS', operator: 'EQUALS', value: 'FAILURE'}, - {field: 'EVENT_HANDLE', operator: 'EQUALS', value: 'sms_sent'}, - ]) -}) - -test.each([ - {argv: []}, - {argv: ['--type=rest', '--method=GET', '--request-path=/admin/api/products.json']}, - {argv: ['--type', 'rest', '--method', 'GET', '--request-path', '/admin/api/products.json']}, -])('parses REST filters from environment variables with flag precedence for $argv', async ({argv}) => { - vi.stubEnv('SHOPIFY_FLAG_TYPE', 'rest') - vi.stubEnv('SHOPIFY_FLAG_METHOD', 'POST') - vi.stubEnv('SHOPIFY_FLAG_REQUEST_PATH', '/environment-path') - vi.mocked(retrieveLogs).mockResolvedValue(result()) - - await new Logs(argv, await Config.load()).run() - - const input = prepareLogInput(vi.mocked(retrieveLogs).mock.calls[0]![0]) - expect(input.types).toEqual([{name: 'rest', backend: 'REST_REQUEST'}]) - expect(input.filters).toEqual([ - {field: 'METHOD', operator: 'EQUALS', value: argv.length ? 'GET' : 'POST'}, - {field: 'REQUEST_PATH', operator: 'EQUALS', value: argv.length ? '/admin/api/products.json' : '/environment-path'}, - ]) -}) - -test('parses Sidekick events with shared target, store, and status filters', async () => { - vi.mocked(retrieveLogs).mockResolvedValue(result()) - - await new Logs( - ['--type', 'sidekick', '--target=extensions/security_scan', '--store', 'example', '--status=failure'], - await Config.load(), - ).run() - - const input = prepareLogInput(vi.mocked(retrieveLogs).mock.calls[0]![0]) - expect(input.types).toEqual([{name: 'sidekick', backend: 'SIDEKICK_EVENT'}]) - expect(input.filters).toEqual([ - {field: 'SHOP_MYSHOPIFY_DOMAIN', operator: 'EQUALS', value: 'example.myshopify.com'}, - {field: 'RESULT_STATUS', operator: 'EQUALS', value: 'FAILURE'}, - {field: 'TARGET', operator: 'EQUALS', value: 'extensions/security_scan'}, - ]) -}) - -test('parses UI extension errors with shared target, store, and status filters', async () => { - vi.mocked(retrieveLogs).mockResolvedValue(result()) - - await new Logs( - ['--type', 'ui-extension', '--target=purchase.checkout.block.render', '--store', 'example', '--status=failure'], - await Config.load(), - ).run() - - const input = prepareLogInput(vi.mocked(retrieveLogs).mock.calls[0]![0]) - expect(input.types).toEqual([{name: 'ui-extension', backend: 'UI_EXTENSION'}]) - expect(input.filters).toEqual([ - {field: 'SHOP_MYSHOPIFY_DOMAIN', operator: 'EQUALS', value: 'example.myshopify.com'}, - {field: 'RESULT_STATUS', operator: 'EQUALS', value: 'FAILURE'}, - {field: 'TARGET', operator: 'EQUALS', value: 'purchase.checkout.block.render'}, - ]) -}) - -test('accepts the maximum limit through parsing and input validation', async () => { - vi.mocked(retrieveLogs).mockResolvedValue(result()) - - await new Logs(['--limit', '1000'], await Config.load()).run() - - const flags = vi.mocked(retrieveLogs).mock.calls[0]![0] - expect(prepareLogInput(flags).limit).toBe(1000) -}) - -test('omitted type and repeated type flags are passed to the service without inventing filter OR', async () => { - vi.mocked(retrieveLogs).mockResolvedValue(result()) - await new Logs(['--client-id', 'explicit-app'], await Config.load()).run() - expect(vi.mocked(retrieveLogs).mock.calls[0]?.[0].type).toBeUndefined() - await new Logs( - [ - '--type', - 'webhook', - '--type', - 'graphql', - '--type', - 'function', - '--type', - 'app-event', - '--type', - 'app-billing-event', - '--type', - 'rest', - '--type', - 'sidekick', - '--type', - 'ui-extension', - '--request-id', - 'request-123', - ], - await Config.load(), - ).run() - expect(retrieveLogs).toHaveBeenLastCalledWith( - expect.objectContaining({ - type: ['webhook', 'graphql', 'function', 'app-event', 'app-billing-event', 'rest', 'sidekick', 'ui-extension'], - 'request-id': 'request-123', - }), - ) -}) - -test.each([ - {argv: [], backend: 'WEBHOOK'}, - {argv: ['--type', 'graphql'], backend: 'GRAPHQL_REQUEST'}, -])('resolves the environment log type with command-line precedence for $argv', async ({argv, backend}) => { - vi.stubEnv('SHOPIFY_FLAG_TYPE', 'webhook') - vi.mocked(retrieveLogs).mockResolvedValue(result()) - - await new Logs(argv, await Config.load()).run() - - const flags = vi.mocked(retrieveLogs).mock.calls[0]![0] - expect(prepareLogInput(flags).types).toEqual([expect.objectContaining({backend})]) -}) - -test.each([ - {argv: ['--sort', 'timestamp'], order: undefined}, - {argv: ['--sort=timestamp', '--order=asc'], order: 'asc'}, - {argv: ['--sort', 'timestamp', '--order', 'desc'], order: 'desc'}, -])('parses explicit sorting flags $argv', async ({argv, order}) => { - vi.mocked(retrieveLogs).mockResolvedValue(result()) - - await new Logs(argv, await Config.load()).run() - - const flags = vi.mocked(retrieveLogs).mock.calls[0]![0] - expect(flags.sort).toBe('timestamp') - expect(flags.order).toBe(order) -}) - -test('accepts sorting from environment variables and requires the sort key', async () => { - vi.stubEnv('SHOPIFY_FLAG_SORT', 'timestamp') - vi.stubEnv('SHOPIFY_FLAG_ORDER', 'desc') - vi.mocked(retrieveLogs).mockResolvedValue(result()) - - await new Logs([], await Config.load()).run() - - expect(retrieveLogs).toHaveBeenCalledWith(expect.objectContaining({sort: 'timestamp', order: 'desc'})) - vi.stubEnv('SHOPIFY_FLAG_SORT', undefined) - vi.mocked(retrieveLogs).mockClear() - await expect(new Logs([], await Config.load()).run()).rejects.toThrow() - expect(retrieveLogs).not.toHaveBeenCalled() -}) - -test.each([ - ['--client-id', 'one', '--client-id=two'], - ['--status', 'success', '--status=failure'], - ['--store', 'one', '--store=two'], - ['--topic', 'orders/create', '--topic=orders/delete'], - ['--operation-name', 'one', '--operation-name=two'], - ['--function-handle', 'one', '--function-handle=two'], - ['--target', 'one', '--target=two'], - ['--event-handle', 'one', '--event-handle=two'], - ['--method', 'GET', '--method=POST'], - ['--request-path', '/one', '--request-path=/two'], - ['--since', '1h', '--since=2h'], - ['--limit', '10', '--limit=20'], - ['--until', '2026-10-06T13:00:00Z', '--until=2026-10-06T14:00:00Z'], - ['--sort', 'timestamp', '--sort=timestamp'], - ['--sort', 'timestamp', '--order', 'asc', '--order=desc'], -])('rejects repeated singular flags %j before authentication', async (...argv) => { - await expect(new Logs(['--type', 'webhook', ...argv], await Config.load()).run()).rejects.toThrow( - 'can only be specified once', - ) - expect(retrieveLogs).not.toHaveBeenCalled() -}) - -test.each([ - ['--type', 'unsupported'], - ['--sort', 'id'], - ['--sort', 'timestamp', '--order', 'ascending'], - ['--order', 'asc'], - ['--order', 'desc'], - ['--type', 'webhook', '--offset', '10'], - ['--type', 'graphql', '--client-ip', '123'], - ['--type', 'graphql', '--user-agent', 'test'], - ['--type', 'webhook', '--query', '{ app }'], -])('rejects missing or unsupported flags %j', async (...argv) => { - await expect(new Logs(argv, await Config.load()).run()).rejects.toThrow() - expect(retrieveLogs).not.toHaveBeenCalled() -}) - -test.each([ - {argv: ['--json'], json: true, noInput: false}, - {argv: ['--no-input'], json: false, noInput: true}, - {argv: ['--json', '--no-input'], json: true, noInput: true}, -])('keeps JSON and no-input independent ($argv)', async ({argv, json, noInput}) => { - vi.mocked(retrieveLogs).mockResolvedValue(result()) - await new Logs(['--type', 'webhook', ...argv], await Config.load()).run() - expect(vi.mocked(retrieveLogs).mock.calls[0]![0]['no-input'] ?? false).toBe(noInput) - expect(mockAndCaptureOutput().output().startsWith('{')).toBe(json) - if (json) expect(JSON.parse(mockAndCaptureOutput().output())).toEqual(result()) -}) - -test('JSON writes one complete object without query or pagination metadata or terminal text', async () => { - vi.mocked(retrieveLogs).mockResolvedValue(result()) - await withCapturedStandardStreams(async ({stdout, stderr}) => { - await new Logs(['--type', 'webhook', '--json', '--no-input'], await Config.load()).run() - expect(JSON.parse(stdout())).toEqual(result()) - expect(JSON.parse(stdout())).not.toHaveProperty('query') - expect(JSON.parse(stdout())).not.toHaveProperty('pageInfo') - expect(stderr()).toBe('') - }) -}) - -test('webhook-only human output omits the inapplicable API column', async () => { - vi.mocked(retrieveLogs).mockResolvedValue(result()) - await withCapturedStandardStreams(async ({stdout, stderr}) => { - await new Logs(['--type', 'webhook'], await Config.load()).run() - expect(stdout()).toBe('') - const lines = stderr().trim().split('\n') - expect(lines[1]!.trim().split(/ {2,}/)).toEqual(['Timestamp', 'Type', 'Result', 'Store', 'Details']) - expect(lines[3]!.trim().split(/ {2,}/)).toEqual([ - '2026-10-06T13:30:00.123456789Z', - 'WEBHOOK', - 'FAILURE', - 'example.myshopify.com', - 'orders/create', - ]) - }) -}) - -test.each([ - ['timestamp-asc', 'Oldest first'], - ['timestamp-desc', 'Newest first'], -] as const)('renders %s without result disclaimers in table and JSON output', async (ordering, label) => { - const data = { - ...result(), - ordering, - limitations: [], - } - vi.mocked(retrieveLogs).mockResolvedValue(data) - - await withCapturedStandardStreams(async ({stdout, stderr}) => { - await new Logs([], await Config.load()).run() - expect(stdout()).toBe('') - expect(stderr().split('\n')[0]).toBe(`${label} by timestamp.`) - expect(stderr()).not.toContain('Additional records may match your search.') - expect(stderr()).not.toContain('Used fast retrieval') - expect(stderr()).toContain('orders/create') - }) - await withCapturedStandardStreams(async ({stdout, stderr}) => { - await new Logs(['--json'], await Config.load()).run() - expect(JSON.parse(stdout())).toEqual(data) - expect(stderr()).toBe('') - }) -}) - -test.each(['ADMIN', undefined])('GraphQL-only human output keeps the API column for %s', async (api) => { - const data = result() - data.logs = [{...data.logs[0]!, type: 'GRAPHQL_REQUEST', topic: undefined, operationName: 'MyQuery', api}] - vi.mocked(retrieveLogs).mockResolvedValue(data) - await withCapturedStandardStreams(async ({stderr}) => { - await new Logs(['--type', 'graphql'], await Config.load()).run() - const lines = stderr().trim().split('\n') - expect(lines[1]!.trim().split(/ {2,}/).at(-1)).toBe('API') - expect(lines[3]!.trim().split(/ {2,}/).slice(-2)).toEqual(['MyQuery', api ?? 'unknown']) - }) -}) - -test.each([ - {functionHandle: 'discount', target: 'cart.lines.discounts.generate.run', details: 'discount', status: 'FAILURE'}, - {functionHandle: null, target: 'cart.lines.discounts.generate.run', details: 'cart.lines.discounts.generate.run'}, - {target: 'cart.lines.discounts.generate.run', details: 'cart.lines.discounts.generate.run', status: null}, - {functionHandle: null, target: null, details: 'unknown'}, - { - functionHandle: `discount\n${'a'.repeat(100)}`, - details: `discount\\u000a${'a'.repeat(85)}…`, - status: 'SUCCESS', - }, -])( - 'Function human output shows $details with the recorded result', - async ({functionHandle, target, details, status}) => { - const data = result() - data.logs = [{...data.logs[0]!, type: 'FUNCTION_RUN', functionHandle, target, resultStatus: status}] - vi.mocked(retrieveLogs).mockResolvedValue(data) - - await withCapturedStandardStreams(async ({stderr}) => { - await new Logs(['--type', 'function'], await Config.load()).run() - const lines = stderr().trim().split('\n') - expect(lines[1]!.trim().split(/ {2,}/)).toEqual(['Timestamp', 'Type', 'Result', 'Store', 'Details']) - expect(lines[3]!.trim().split(/ {2,}/)).toEqual([ - data.logs[0]!.timestamp, - 'FUNCTION_RUN', - status ?? 'unknown', - 'example.myshopify.com', - details, - ]) + [], + ['--store', 'example.myshopify.com', '--status', 'failure'], + ['-s', 'first.myshopify.com', '-s', 'second.myshopify.com', '--source', 'extensions.discount'], + ['--path', '/missing/app', '--config', 'missing', '--client-id', 'missing', '--reset'], + ['sources'], + ['sources', '--path', '/missing/app'], + ].map((argv) => ({argv})), + )('returns migration guidance without loading an app for $argv', async ({argv}) => { + await withCapturedStandardStreams(async ({stdout, stderr}) => { + await runLogs(argv) + expect(stdout()).toBe('') + expect( + unstyled(stderr()) + .replace(/[│╭╮╰╯─]/g, ' ') + .replace(/\s+/g, ' '), + ).toContain(removalMessage) + expect(reportAnalyticsEvent).toHaveBeenCalledWith(expect.objectContaining({exitMode: 'expected_error'})) }) - }, -) - -test.each([ - {eventHandle: 'onboarding_completed', details: 'onboarding_completed'}, - {eventHandle: null, details: 'unknown'}, - {eventHandle: undefined, details: 'unknown'}, - {eventHandle: `event\n${'a'.repeat(100)}`, details: `event\\u000a${'a'.repeat(88)}…`}, -])('app event human output shows $details and no result status', async ({eventHandle, details}) => { - const data = result() - data.logs = [{timestamp: data.logs[0]!.timestamp, type: 'APP_EVENT', shopMyshopifyDomain: null, eventHandle}] - vi.mocked(retrieveLogs).mockResolvedValue(data) - - await withCapturedStandardStreams(async ({stdout, stderr}) => { - await new Logs(['--type', 'app-event'], await Config.load()).run() - expect(stdout()).toBe('') - const lines = stderr().trim().split('\n') - expect(lines[1]!.trim().split(/ {2,}/)).toEqual(['Timestamp', 'Type', 'Result', 'Store', 'Details']) - expect(lines[3]!.trim().split(/ {2,}/)).toEqual([data.logs[0]!.timestamp, 'APP_EVENT', '—', 'unknown', details]) - }) -}) - -test.each([ - {eventHandle: 'sms_sent', details: 'sms_sent', status: 'FAILURE'}, - {eventHandle: null, details: 'unknown', status: null}, - {eventHandle: undefined, details: 'unknown', status: undefined}, - {eventHandle: `event\n${'a'.repeat(100)}`, details: `event\\u000a${'a'.repeat(88)}…`, status: 'SUCCESS'}, -])('app billing event human output shows $details with the recorded result', async ({eventHandle, details, status}) => { - const data = result() - data.logs = [{...data.logs[0]!, type: 'APP_BILLING_EVENT', eventHandle, resultStatus: status}] - vi.mocked(retrieveLogs).mockResolvedValue(data) - - await withCapturedStandardStreams(async ({stdout, stderr}) => { - await new Logs(['--type', 'app-billing-event'], await Config.load()).run() - expect(stdout()).toBe('') - const lines = stderr().trim().split('\n') - expect(lines[1]!.trim().split(/ {2,}/)).toEqual(['Timestamp', 'Type', 'Result', 'Store', 'Details']) - expect(lines[3]!.trim().split(/ {2,}/)).toEqual([ - data.logs[0]!.timestamp, - 'APP_BILLING_EVENT', - status ?? 'unknown', - 'example.myshopify.com', - details, - ]) - }) -}) - -test.each([ - {method: 'GET', requestPath: '/products.json', details: 'GET /products.json', status: 'FAILURE'}, - {method: 'GET', requestPath: null, details: 'GET', status: null}, - {method: undefined, requestPath: '/products.json', details: '/products.json'}, - {method: null, requestPath: null, details: 'unknown'}, - {method: undefined, requestPath: undefined, details: 'unknown'}, - {method: '', requestPath: '', details: 'unknown'}, - {method: '', requestPath: '/products.json', details: '/products.json'}, - {method: 'GET', requestPath: '', details: 'GET'}, - {method: 42, requestPath: false, details: 'unknown'}, - {method: 'GET', requestPath: `/\n${'a'.repeat(100)}`, details: `GET /\\u000a${'a'.repeat(88)}…`, status: 'SUCCESS'}, -])('REST human output shows $details with the recorded result', async ({method, requestPath, details, status}) => { - const data = result() - data.logs = [{...data.logs[0]!, type: 'REST_REQUEST', method, requestPath, resultStatus: status, statusCode: 200}] - vi.mocked(retrieveLogs).mockResolvedValue(data) - - await withCapturedStandardStreams(async ({stdout, stderr}) => { - await new Logs(['--type', 'rest'], await Config.load()).run() - expect(stdout()).toBe('') - const lines = stderr().trim().split('\n') - expect(lines[1]!.trim().split(/ {2,}/)).toEqual(['Timestamp', 'Type', 'Result', 'Store', 'Details']) - expect(lines[3]!.trim().split(/ {2,}/)).toEqual([ - data.logs[0]!.timestamp, - 'REST_REQUEST', - status ?? 'unknown', - 'example.myshopify.com', - details, - ]) - }) -}) - -test.each([ - {target: 'extensions/security_scan', details: 'extensions/security_scan', status: 'FAILURE'}, - {target: null, details: 'unknown', status: null}, - {target: undefined, details: 'unknown', status: undefined}, - {target: `extensions/\n${'a'.repeat(100)}`, details: `extensions/\\u000a${'a'.repeat(82)}…`, status: 'SUCCESS'}, -])('Sidekick human output shows $details with the recorded result', async ({target, details, status}) => { - const data = result() - data.logs = [ - {...data.logs[0]!, type: 'SIDEKICK_EVENT', target, resultStatus: status, errorMessage: 'not-in-human-summary'}, - ] - vi.mocked(retrieveLogs).mockResolvedValue(data) - - await withCapturedStandardStreams(async ({stdout, stderr}) => { - await new Logs(['--type', 'sidekick'], await Config.load()).run() - expect(stdout()).toBe('') - const lines = stderr().trim().split('\n') - expect(lines[1]!.trim().split(/ {2,}/)).toEqual(['Timestamp', 'Type', 'Result', 'Store', 'Details']) - expect(lines[3]!.trim().split(/ {2,}/)).toEqual([ - data.logs[0]!.timestamp, - 'SIDEKICK_EVENT', - status ?? 'unknown', - 'example.myshopify.com', - details, - ]) - expect(stderr()).not.toContain('not-in-human-summary') - }) -}) - -test.each([ - {target: 'purchase.checkout.block.render', details: 'purchase.checkout.block.render', status: 'FAILURE'}, - {target: null, details: 'unknown', status: null}, - {target: undefined, details: 'unknown', status: undefined}, - {target: `extensions/\n${'a'.repeat(100)}`, details: `extensions/\\u000a${'a'.repeat(82)}…`, status: 'SUCCESS'}, -])('UI extension error human output shows $details with the recorded result', async ({target, details, status}) => { - const data = result() - data.logs = [ - {...data.logs[0]!, type: 'UI_EXTENSION', target, resultStatus: status, errorMessage: 'not-in-human-summary'}, - ] - vi.mocked(retrieveLogs).mockResolvedValue(data) - - await withCapturedStandardStreams(async ({stdout, stderr}) => { - await new Logs(['--type', 'ui-extension'], await Config.load()).run() - expect(stdout()).toBe('') - const lines = stderr().trim().split('\n') - expect(lines[1]!.trim().split(/ {2,}/)).toEqual(['Timestamp', 'Type', 'Result', 'Store', 'Details']) - expect(lines[3]!.trim().split(/ {2,}/)).toEqual([ - data.logs[0]!.timestamp, - 'UI_EXTENSION', - status ?? 'unknown', - 'example.myshopify.com', - details, - ]) - expect(stderr()).not.toContain('not-in-human-summary') - }) -}) - -test('human output aligns headers with mixed log rows between the warning and JSON hint', async () => { - const data = result() - data.logs.push({ - id: 'gid://shopify/AppLogRecord/another', - timestamp: '2026-10-06T13:31:00Z', - type: 'GRAPHQL_REQUEST', - resultStatus: 'SUCCESS', - shopMyshopifyDomain: 'longer-example.myshopify.com', - operationName: 'QueryWithALongerOperationName', - api: 'STOREFRONT', - }) - data.logs.push({ - timestamp: '2026-10-06T13:32:00Z', - type: 'FUNCTION_RUN', - resultStatus: 'FAILURE', - shopMyshopifyDomain: 'example.myshopify.com', - functionHandle: 'discount', - target: 'cart.lines.discounts.generate.run', - }) - data.logs.push({ - timestamp: '2026-10-06T13:33:00Z', - type: 'APP_EVENT', - shopMyshopifyDomain: 'example.myshopify.com', - eventHandle: 'onboarding_completed', - }) - data.logs.push({ - timestamp: '2026-10-06T13:34:00Z', - type: 'APP_BILLING_EVENT', - resultStatus: 'SUCCESS', - shopMyshopifyDomain: 'example.myshopify.com', - eventHandle: 'sms_sent', - }) - data.logs.push({ - timestamp: '2026-10-06T13:35:00Z', - type: 'REST_REQUEST', - resultStatus: 'FAILURE', - shopMyshopifyDomain: 'example.myshopify.com', - method: 'GET', - requestPath: '/products.json', - }) - data.logs.push({ - timestamp: '2026-10-06T13:36:00Z', - type: 'SIDEKICK_EVENT', - resultStatus: 'SUCCESS', - shopMyshopifyDomain: 'example.myshopify.com', - target: 'extensions/security_scan', }) - data.logs.push({ - timestamp: '2026-10-06T13:37:00Z', - type: 'UI_EXTENSION', - resultStatus: 'SUCCESS', - shopMyshopifyDomain: 'example.myshopify.com', - target: 'purchase.checkout.block.render', - }) - vi.mocked(retrieveLogs).mockResolvedValue(data) - await withCapturedStandardStreams(async ({stdout, stderr}) => { - await new Logs([], await Config.load()).run() - expect(stdout()).toBe('') - const lines = stderr().trim().split('\n') - expect(lines[0]).toBe('Used fast retrieval: returned records shown oldest first.') - expect(lines.at(-1)).toBe('Use --json for full records.') - expect(lines).toHaveLength(13) - expect(lines.at(-2)).toBe('Returned all 8 matching records available at query time.') - const headers = ['Timestamp', 'Type', 'Result', 'Store', 'Details', 'API'] - expect(lines[1]!.trim().split(/ {2,}/)).toEqual(headers) - for (const [index, record] of data.logs.entries()) { - const values = [ - record.timestamp, - record.type, - record.resultStatus ?? '—', - record.shopMyshopifyDomain, - record.topic ?? - record.operationName ?? - record.functionHandle ?? - record.eventHandle ?? - record.target ?? - `${record.method} ${record.requestPath}`, - record.api ?? '—', - ] - const row = lines[index + 3]! - expect(row.trim().split(/ {2,}/)).toEqual(values) - for (const [column, header] of headers.entries()) { - const start = lines[1]!.indexOf(header) - expect(row.slice(start, start + String(values[column]).length)).toBe(String(values[column])) - } - } - }) -}) - -test('empty human output confirms no matches without a table or footer', async () => { - vi.mocked(retrieveLogs).mockResolvedValue({...result(), logs: []}) - await withCapturedStandardStreams(async ({stdout, stderr}) => { - await new Logs(['--type', 'webhook'], await Config.load()).run() - expect(stdout()).toBe('') - expect(stderr().trim().split('\n')).toEqual(['No matching records available at query time.']) - }) -}) - -test.each(['subset-timestamp-asc', 'timestamp-asc', 'timestamp-desc'] as const)( - 'human output confirms a below-limit result for %s', - async (ordering) => { - vi.mocked(retrieveLogs).mockResolvedValue({...result(), ordering}) - - await withCapturedStandardStreams(async ({stderr}) => { - await new Logs(['--limit', '2'], await Config.load()).run() - expect(stderr()).toContain('Returned all 1 matching record available at query time.') - expect(stderr()).not.toContain('additional records may match') - expect(stderr()).not.toContain('not necessarily') - }) - }, -) - -test.each(['subset-timestamp-asc', 'timestamp-asc', 'timestamp-desc'] as const)( - 'human output warns at the requested limit for %s without asserting completeness', - async (ordering) => { - const data = {...result(), ordering, limitations: ['Reached the limit of 1 record; additional records may match.']} - vi.mocked(retrieveLogs).mockResolvedValue(data) - - await withCapturedStandardStreams(async ({stderr}) => { - await new Logs(['--limit', '1'], await Config.load()).run() + test.each([[], ['sources'], ['--store', 'example.myshopify.com', '--status', 'failure']].map((argv) => ({argv})))( + 'writes one JSON error document for $argv', + async ({argv}) => { + await withCapturedStandardStreams(async ({stdout, stderr}) => { + await runLogs([...argv, '--json']) + expect(JSON.parse(stdout())).toMatchObject({error: {type: 'abort', message: removalMessage}}) + expect(stderr()).toBe('') + }) + }, + ) - expect(stderr()).toContain('Reached the limit of 1 record; additional records may match.') - expect(stderr()).not.toContain('Returned all') + test('honors JSON output selected through the environment', async () => { + vi.stubEnv('SHOPIFY_FLAG_JSON', '1') + await withCapturedStandardStreams(async ({stdout, stderr}) => { + await runLogs([]) + expect(JSON.parse(stdout())).toMatchObject({error: {type: 'abort', message: removalMessage}}) + expect(stderr()).toBe('') }) - }, -) - -test('human output marks abbreviated cells and does not print body data', async () => { - const data = result() - data.logs[0]!.topic = `orders/${'a'.repeat(150)}` - data.logs[0]!.requestBody = 'not-in-human-summary' - vi.mocked(retrieveLogs).mockResolvedValue(data) - await withCapturedStandardStreams(async ({stdout, stderr}) => { - await new Logs(['--type', 'webhook'], await Config.load()).run() - expect(stdout()).toBe('') - expect(stderr()).toContain(`orders/${'a'.repeat(92)}…`) - expect(stderr()).toContain('Use --json for full records.') - expect(stderr()).not.toContain('not-in-human-summary') }) - expect(JSON.parse(logsOutput.encode(data)).logs).toEqual(data.logs) }) -test.each([ - {topic: `${'a'.repeat(98)}😀z`, displayed: `${'a'.repeat(98)}…`}, - {topic: `${'a'.repeat(98)}\nz`, displayed: `${'a'.repeat(98)}…`}, - {topic: `${'a'.repeat(93)}\nzz`, displayed: `${'a'.repeat(93)}\\u000a…`}, - {topic: `${'a'.repeat(98)}😀`, displayed: `${'a'.repeat(98)}😀`}, -])('human output keeps Unicode and control escapes intact when abbreviating $topic', async ({topic, displayed}) => { - const data = result() - data.logs[0]!.topic = topic - vi.mocked(retrieveLogs).mockResolvedValue(data) - - await withCapturedStandardStreams(async ({stderr}) => { - await new Logs(['--type', 'webhook'], await Config.load()).run() - - expect(stderr().trim().split('\n')[3]!.trim().split(/ {2,}/).at(-1)).toBe(displayed) - }) - expect(JSON.parse(logsOutput.encode(data)).logs[0].topic).toBe(topic) -}) - -test('escapes terminal control characters in human output without changing JSON', async () => { - const data = result() - data.logs[0]!.topic = 'orders/\u001b[31mred\u001b[0m\nnext\u202eline' - vi.mocked(retrieveLogs).mockResolvedValue(data) - await withCapturedStandardStreams(async ({stderr}) => { - await new Logs(['--type', 'webhook'], await Config.load()).run() - expect(stderr()).toContain('orders/red\\u000anext\\u202eline') - expect(stderr()).not.toContain('\u001b[31m') - }) - expect(JSON.parse(logsOutput.encode(data)).logs).toEqual(data.logs) -}) - -test('publishes a strict envelope and an extensible native record schema', () => { - expect(Logs.jsonOutputSchema).toBe(logsOutput) - expect(Logs.descriptionForHelp()).toContain('HistoricalAppLogs') - expect(Logs.description).toContain('HistoricalAppLogs') - expect(() => logsOutput.validate({...result(), accidental: true})).toThrow() - expect(() => logsOutput.validate({...result(), query: {clientId: 'test-app'}})).toThrow() - expect(JSON.parse(logsOutput.encode(result())).logs[0].extra).toEqual({nested: true}) - expect(logsOutput.jsonSchema).toHaveProperty('properties.logs') - expect(logsOutput.jsonSchema).toHaveProperty('properties.ordering.enum', [ - 'subset-timestamp-asc', - 'timestamp-asc', - 'timestamp-desc', - ]) - expect(logsOutput.jsonSchema).not.toHaveProperty('properties.query') - expect(logsOutput.jsonSchema).not.toHaveProperty('properties.pageInfo') - expect(() => logsOutput.validate({...result(), pageInfo: {limit: 20}})).toThrow() -}) +async function runLogs(argv: string[]) { + const config = await Config.load({root: fileURLToPath(new URL('../../../../', import.meta.url))}) + config.plugins.delete('@shopify/app') + const exit = vi.spyOn(process, 'exit').mockReturnValue(undefined as never) + try { + await Logs.run(argv, config) + expect(exit).toHaveBeenCalledExactlyOnceWith(1) + } finally { + exit.mockRestore() + } +} diff --git a/packages/app/src/cli/commands/app/logs.ts b/packages/app/src/cli/commands/app/logs.ts index 7a7158e3641..d5c4000dd49 100644 --- a/packages/app/src/cli/commands/app/logs.ts +++ b/packages/app/src/cli/commands/app/logs.ts @@ -1,41 +1,21 @@ -import {logTypesHelp} from '../../services/historical-logs/catalog.js' -import {historicalLogFlags} from '../../services/historical-logs/flags.js' -import {retrieveLogs} from '../../services/historical-logs/service.js' -import {renderHistoricalLogs} from '../../services/historical-logs/presenter.js' -import {logsOutput} from '../../services/historical-logs/types.js' -import BaseCommand from '@shopify/cli-kit/node/base-command' -import {authAliasFlag, globalFlags, jsonFlag} from '@shopify/cli-kit/node/cli' +import Command from '@shopify/cli-kit/node/base-command' +import {globalFlags, jsonFlag} from '@shopify/cli-kit/node/cli' +import {AbortError} from '@shopify/cli-kit/node/error' -export default class Logs extends BaseCommand { - static baseFlags = {...BaseCommand.baseFlags, ...authAliasFlag} - static summary = 'Lists historical app logs.' - static descriptionWithMarkdown = `Returns a list of historical app logs and exits. Defaults to all supported log types. Use --type to select a type; repeat it to select multiple. +export default class Logs extends Command { + static hidden = true -Fast retrieval is the default: leave out --sort. Prefer this mode with a narrow time window and selective filters to consume less throttle capacity. The CLI orders the returned records oldest first, but when the limit is reached they aren't necessarily the oldest or newest matches. + static strict = false -Use server-side sorting only when selecting the oldest or newest matching records matters: --sort timestamp selects oldest first; add --order desc for newest first. This sorts before the result limit and is subject to API query limits. + static summary = 'App logs were removed in Shopify CLI 5.0.' -When fewer than --limit records are returned, all matching records available at query time were returned. Sorting isn't needed to establish completeness. - -Different filters combine with AND; each accepts one exact value. Type-specific filters exclude records without that field; combining --topic and --operation-name returns no records. - -${logTypesHelp()} - -Defaults: preceding hour, 20 records. Maximum: 1-day window within the last 7 days, 1000 records. Time inputs accept whole seconds only. - ---json preserves native record JSON in logs[], including fractional timestamps, diagnostic fields, bodies, and producer truncation flags.` - - static jsonOutputSchema = logsOutput - static description = this.descriptionForHelp() - static flags = {...globalFlags, ...jsonFlag, ...historicalLogFlags} - static examples = [ - '<%= config.bin %> <%= command.id %> --client-id APP_CLIENT_ID --type webhook --topic orders/create --status failure --since 30m', - '<%= config.bin %> <%= command.id %> --type graphql --operation-name MyQuery --json --no-input', - '<%= config.bin %> <%= command.id %> --since 1h --sort timestamp --order desc', - ] + static flags = {...globalFlags, ...jsonFlag} async run(): Promise { - const {flags} = await this.parse(Logs) - renderHistoricalLogs(await retrieveLogs(flags), flags.json, flags.limit) + // Skip parsing so legacy flags and the removed sources subcommand receive the migration guidance. + throw new AbortError( + '`shopify app logs` and `shopify app logs sources` were removed in Shopify CLI 5.0. ' + + 'To see Function logs, run `shopify app dev`.', + ) } } diff --git a/packages/app/src/cli/index.ts b/packages/app/src/cli/index.ts index 049e3cb7177..4e7546edcbf 100644 --- a/packages/app/src/cli/index.ts +++ b/packages/app/src/cli/index.ts @@ -13,6 +13,7 @@ import SecurityInstructions from './commands/app/security/instructions.js' import SecurityRecord from './commands/app/security/record.js' import SecurityReview from './commands/app/security/review.js' import Logs from './commands/app/logs.js' +import LogsNext from './commands/app/logs-next.js' import EnvPull from './commands/app/env/pull.js' import EnvShow from './commands/app/env/show.js' import BulkExecute from './commands/app/bulk/execute.js' @@ -66,6 +67,7 @@ export const commands: {[key: string]: typeof AppLinkedCommand | typeof AppUnlin 'app:security:record': SecurityRecord, 'app:security:review': SecurityReview, 'app:logs': Logs, + 'app:logs-next': LogsNext, 'app:import:channel-config': ImportChannelConfig, 'app:import:custom-data-definitions': ImportCustomDataDefinitions, 'app:import:dashboard-extensions': ImportDashboardExtensions, diff --git a/packages/app/src/cli/services/historical-logs/catalog.ts b/packages/app/src/cli/services/historical-logs/catalog.ts index 14347df453b..efe5ef9fef1 100644 --- a/packages/app/src/cli/services/historical-logs/catalog.ts +++ b/packages/app/src/cli/services/historical-logs/catalog.ts @@ -1,5 +1,16 @@ import {AbortError} from '@shopify/cli-kit/node/error' +const logTypes = [ + {name: 'webhook', backend: 'WEBHOOK'}, + {name: 'graphql', backend: 'GRAPHQL_REQUEST'}, + {name: 'function', backend: 'FUNCTION_RUN'}, + {name: 'app-event', backend: 'APP_EVENT'}, + {name: 'app-billing-event', backend: 'APP_BILLING_EVENT'}, + {name: 'rest', backend: 'REST_REQUEST'}, + {name: 'sidekick', backend: 'SIDEKICK_EVENT'}, + {name: 'ui-extension', backend: 'UI_EXTENSION'}, +] as const + export const logFilters = [ {flag: 'store', field: 'SHOP_MYSHOPIFY_DOMAIN'}, {flag: 'status', field: 'RESULT_STATUS'}, @@ -15,69 +26,6 @@ export const logFilters = [ {flag: 'request-path', field: 'REQUEST_PATH'}, ] as const -type LogFilterFlag = (typeof logFilters)[number]['flag'] - -// Filters that every log type records. Each type lists the other filters that apply to it. -export const commonLogFilters = ['store'] as const satisfies ReadonlyArray - -// App events record no result status, so --status applies to every other type. -export const logTypes = [ - { - name: 'webhook', - backend: 'WEBHOOK', - description: 'Webhook deliveries.', - filters: ['status', 'topic', 'status-code'], - }, - { - name: 'graphql', - backend: 'GRAPHQL_REQUEST', - description: 'GraphQL API requests.', - filters: ['status', 'operation-type', 'operation-name', 'request-id'], - }, - { - name: 'function', - backend: 'FUNCTION_RUN', - description: 'Shopify Function runs.', - filters: ['status', 'function-handle', 'target'], - }, - { - name: 'app-event', - backend: 'APP_EVENT', - description: 'Events the app sent with the App Events API.', - filters: ['event-handle'], - }, - { - name: 'app-billing-event', - backend: 'APP_BILLING_EVENT', - description: 'Billing outcomes of app events.', - filters: ['status', 'event-handle'], - }, - { - name: 'rest', - backend: 'REST_REQUEST', - description: 'REST API requests.', - filters: ['status', 'status-code', 'request-id', 'method', 'request-path'], - }, - {name: 'sidekick', backend: 'SIDEKICK_EVENT', description: 'Sidekick events.', filters: ['status', 'target']}, - {name: 'ui-extension', backend: 'UI_EXTENSION', description: 'UI extension errors.', filters: ['status', 'target']}, -] as const satisfies ReadonlyArray<{ - name: string - backend: string - description: string - filters: ReadonlyArray -}> - -export const logTypeNames = logTypes.map(({name}) => name) - -export function logTypesHelp(): string { - const rows = logTypes.map( - ({name, description, filters}) => - `- ${name}: ${description} Filters: ${filters.map((flag) => `--${flag}`).join(', ')}.`, - ) - const common = commonLogFilters.map((flag) => `--${flag}`).join(', ') - return [`Log types and the filters that apply to each. Every type also accepts ${common}.`, '', ...rows].join('\n') -} - export const queryLimits = { defaultLimit: 20, defaultSince: '1h', @@ -99,11 +47,12 @@ function selectedLogType(value?: string) { if (!type) throw logError( 'invalid-argument', - `Supported log types are ${new Intl.ListFormat('en', {type: 'conjunction'}).format(logTypeNames)}.`, + 'Supported log types are webhook, graphql, function, app-event, app-billing-event, rest, sidekick, and ui-extension.', ) - return {name: type.name, backend: type.backend} + return type } -export function selectedLogTypes(values: string | string[] = logTypeNames) { +export function selectedLogTypes(values?: string | string[]) { + if (values === undefined) return [...logTypes] return [...new Set(typeof values === 'string' ? [values] : values)].map(selectedLogType) } diff --git a/packages/app/src/cli/services/historical-logs/flags.ts b/packages/app/src/cli/services/historical-logs/flags.ts index 5907e0d323b..34e9a871e9a 100644 --- a/packages/app/src/cli/services/historical-logs/flags.ts +++ b/packages/app/src/cli/services/historical-logs/flags.ts @@ -1,4 +1,3 @@ -import {logTypeNames} from './catalog.js' import {appFlags} from '../../flags.js' import {Flags} from '@oclif/core' @@ -8,103 +7,85 @@ export const historicalLogFlags = { 'client-id': appFlags['client-id'], type: Flags.string({ description: 'Log type; repeat to select multiple. Defaults to all supported types.', - options: logTypeNames, + options: ['webhook', 'graphql', 'function', 'app-event', 'app-billing-event', 'rest', 'sidekick', 'ui-extension'], multiple: true, multipleNonGreedy: true, - helpGroup: 'QUERY', env: 'SHOPIFY_FLAG_TYPE', }), store: Flags.string({ description: 'Exact store handle or myshopify.com domain/URL.', char: 's', - helpGroup: 'FILTER', env: 'SHOPIFY_FLAG_STORE', }), status: Flags.string({ description: 'Recorded result status; not inferred from HTTP codes or response bodies.', options: ['success', 'failure'], - helpGroup: 'FILTER', env: 'SHOPIFY_FLAG_STATUS', }), topic: Flags.string({ description: 'Exact webhook topic; excludes non-webhook records.', - helpGroup: 'FILTER', env: 'SHOPIFY_FLAG_TOPIC', }), 'status-code': Flags.string({ description: 'Exact webhook or REST HTTP status code (100–599); no status classes.', - helpGroup: 'FILTER', env: 'SHOPIFY_FLAG_STATUS_CODE', }), 'operation-type': Flags.string({ description: 'Exact GraphQL operation type; excludes non-GraphQL records.', - helpGroup: 'FILTER', env: 'SHOPIFY_FLAG_OPERATION_TYPE', }), 'operation-name': Flags.string({ description: 'Exact GraphQL operation name; excludes non-GraphQL records.', - helpGroup: 'FILTER', env: 'SHOPIFY_FLAG_OPERATION_NAME', }), 'request-id': Flags.string({ description: 'Exact GraphQL or REST request ID; excludes other record types.', - helpGroup: 'FILTER', env: 'SHOPIFY_FLAG_REQUEST_ID', }), 'function-handle': Flags.string({ description: 'Exact Function extension handle; excludes non-Function records.', - helpGroup: 'FILTER', env: 'SHOPIFY_FLAG_FUNCTION_HANDLE', }), target: Flags.string({ description: 'Exact Function execution, Sidekick event, or UI extension target; excludes other record types.', - helpGroup: 'FILTER', env: 'SHOPIFY_FLAG_TARGET', }), 'event-handle': Flags.string({ description: 'Exact app event or app billing event handle; excludes other record types.', - helpGroup: 'FILTER', env: 'SHOPIFY_FLAG_EVENT_HANDLE', }), method: Flags.string({ description: 'Exact REST HTTP method; excludes non-REST records.', - helpGroup: 'FILTER', env: 'SHOPIFY_FLAG_METHOD', }), 'request-path': Flags.string({ description: 'Exact REST request path; excludes non-REST records.', - helpGroup: 'FILTER', env: 'SHOPIFY_FLAG_REQUEST_PATH', }), since: Flags.string({ description: 'Inclusive start: positive duration (s/m/h/d) or whole-second RFC 3339 timestamp.', default: '1h', - helpGroup: 'QUERY', env: 'SHOPIFY_FLAG_SINCE', }), until: Flags.string({ description: 'Exclusive whole-second RFC 3339 end; defaults to the current time.', - helpGroup: 'QUERY', env: 'SHOPIFY_FLAG_UNTIL', }), limit: Flags.integer({ description: 'Maximum number of records to return, from 1 through 1000.', default: 20, - helpGroup: 'QUERY', env: 'SHOPIFY_FLAG_LIMIT', }), sort: Flags.string({ description: 'Select the oldest/newest matches using server-side sorting. Omit for faster, less-throttled retrieval.', options: ['timestamp'], - helpGroup: 'QUERY', env: 'SHOPIFY_FLAG_SORT', }), order: Flags.string({ description: 'Sort direction: asc (oldest first, default with --sort) or desc (newest first).', options: ['asc', 'desc'], dependsOn: ['sort'], - helpGroup: 'QUERY', env: 'SHOPIFY_FLAG_ORDER', }), } diff --git a/packages/cli/README.md b/packages/cli/README.md index 3c4c81c6e1a..505f812e6c3 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -26,7 +26,6 @@ * [`shopify app import dashboard-extensions`](#shopify-app-import-dashboard-extensions) * [`shopify app info`](#shopify-app-info) * [`shopify app init`](#shopify-app-init) -* [`shopify app logs`](#shopify-app-logs) * [`shopify app release --version `](#shopify-app-release---version-version) * [`shopify app security check`](#shopify-app-security-check) * [`shopify app security clean`](#shopify-app-security-clean) @@ -5624,256 +5623,6 @@ EXAMPLES $ shopify app init --client-id 123 --template none ``` -## `shopify app logs` - -Lists historical app logs. - -``` -USAGE - $ shopify app logs [--auth-alias ] [--client-id | -c ] [--event-handle ] - [--function-handle ] [-j] [--json-schema] [--limit ] [--method ] [--no-color] [--no-input] - [--operation-name ] [--operation-type ] [--order asc|desc --sort timestamp] [--path ] - [--request-id ] [--request-path ] [--since ] [--status success|failure] [--status-code ] - [-s ] [--target ] [--topic ] [--type - webhook|graphql|function|app-event|app-billing-event|rest|sidekick|ui-extension...] [--until ] [--verbose] - -FLAGS - -c, --config= - The name of the app configuration. - [env: SHOPIFY_FLAG_APP_CONFIG] - - -j, --json - Output the result as JSON. Automatically disables color output. - [env: SHOPIFY_FLAG_JSON] - - --auth-alias= - Alias of the Shopify account to use for authentication. - [env: SHOPIFY_FLAG_AUTH_ALIAS] - - --client-id= - The Client ID of your app. - [env: SHOPIFY_FLAG_CLIENT_ID] - - --json-schema - Print the command's JSON schemas. - [env: SHOPIFY_FLAG_JSON_SCHEMA] - - --no-color - Disable color output. - [env: SHOPIFY_FLAG_NO_COLOR] - - --no-input - Disable interactive prompts and browser authentication. - [env: SHOPIFY_FLAG_NO_INPUT] - - --path= - The path to your app directory. - [env: SHOPIFY_FLAG_PATH] - - --verbose - Increase the verbosity of the output. May include sensitive data. - [env: SHOPIFY_FLAG_VERBOSE] - -FILTER FLAGS - -s, --store= - Exact store handle or myshopify.com domain/URL. - [env: SHOPIFY_FLAG_STORE] - - --event-handle= - Exact app event or app billing event handle; excludes other record types. - [env: SHOPIFY_FLAG_EVENT_HANDLE] - - --function-handle= - Exact Function extension handle; excludes non-Function records. - [env: SHOPIFY_FLAG_FUNCTION_HANDLE] - - --method= - Exact REST HTTP method; excludes non-REST records. - [env: SHOPIFY_FLAG_METHOD] - - --operation-name= - Exact GraphQL operation name; excludes non-GraphQL records. - [env: SHOPIFY_FLAG_OPERATION_NAME] - - --operation-type= - Exact GraphQL operation type; excludes non-GraphQL records. - [env: SHOPIFY_FLAG_OPERATION_TYPE] - - --request-id= - Exact GraphQL or REST request ID; excludes other record types. - [env: SHOPIFY_FLAG_REQUEST_ID] - - --request-path= - Exact REST request path; excludes non-REST records. - [env: SHOPIFY_FLAG_REQUEST_PATH] - - --status=