Repository navigation
Add typed JSON output to app function typegen #8892
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
gonzaloriestra
merged 5 commits into
gonzalo/function-schema-json
from
gonzalo/function-typegen-json
Oct 16, 2026
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
e784c25
Add typed JSON output to app function typegen
gonzaloriestra 2a79a32
Refresh Function typegen docs and native path expectations
gonzaloriestra a6f00e2
Add one changeset for the Function JSON commands
gonzaloriestra 31c08a3
Inline Function identity in the typegen result
gonzaloriestra 7d1a5bc
Select JSON typegen events from parsed flags
gonzaloriestra File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| '@shopify/cli': minor | ||
| --- | ||
|
|
||
| Add typed JSON output to `app function` commands |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
145 changes: 145 additions & 0 deletions
145
packages/app/src/cli/commands/app/function/typegen.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,145 @@ | ||
| import FunctionTypegen from './typegen.js' | ||
| import {chooseFunction} from '../../../services/function/common.js' | ||
| import {localAppContext} from '../../../services/app-context.js' | ||
| import {testApp, testFunctionExtension, testProject} from '../../../models/app/app.test-data.js' | ||
| import {functionTypegenJsonOutputSchema} from '../../../services/function/typegen/types.js' | ||
| import {Config} from '@oclif/core' | ||
| import {afterEach, expect, test, vi} from 'vitest' | ||
| import {inTemporaryDirectory, readFile, writeFile} from '@shopify/cli-kit/node/fs' | ||
| import {joinPath} from '@shopify/cli-kit/node/path' | ||
| import {withCapturedStandardStreams} from '@shopify/cli-kit/node/testing/output' | ||
| import {runWithCommandEventsForCommand} from '@shopify/cli-kit/node/command-events' | ||
| import {ExternalError, AbortError, handler} from '@shopify/cli-kit/node/error' | ||
| import {exec} from '@shopify/cli-kit/node/system' | ||
| import {packageManagerBinaryCommandForDirectory} from '@shopify/cli-kit/node/node-package-manager' | ||
| import {unstyled} from '@shopify/cli-kit/node/output' | ||
|
|
||
| // eslint-disable-next-line no-restricted-imports | ||
| import {resolve} from 'node:path' | ||
|
|
||
| vi.mock('../../../services/app-context.js') | ||
| vi.mock('@shopify/cli-kit/node/system', async (importOriginal) => ({ | ||
| ...(await importOriginal<typeof import('@shopify/cli-kit/node/system')>()), | ||
| exec: vi.fn(), | ||
| })) | ||
| vi.mock('@shopify/cli-kit/node/node-package-manager', async (importOriginal) => ({ | ||
| ...(await importOriginal<typeof import('@shopify/cli-kit/node/node-package-manager')>()), | ||
| packageManagerBinaryCommandForDirectory: vi.fn(), | ||
| })) | ||
| vi.mock('../../../services/function/common.js', async (importOriginal) => ({ | ||
| ...(await importOriginal<typeof import('../../../services/function/common.js')>()), | ||
| chooseFunction: vi.fn(), | ||
| })) | ||
| afterEach(() => vi.unstubAllEnvs()) | ||
|
|
||
| async function command(argv: string[], directory: string, custom = false) { | ||
| const app = testApp({directory}) | ||
| const extension = await testFunctionExtension({dir: directory, entryPath: 'src/index.js'}) | ||
| if (custom) extension.configuration.build!.typegen_command = 'custom-codegen --target test' | ||
| vi.mocked(localAppContext).mockResolvedValue({app, project: testProject(), activeConfig: {} as never}) | ||
| vi.mocked(chooseFunction).mockResolvedValue(extension) | ||
| vi.mocked(packageManagerBinaryCommandForDirectory).mockResolvedValue({ | ||
| command: 'codegen', | ||
| args: ['--config', 'package.json'], | ||
| }) | ||
| return {instance: new FunctionTypegen(argv, await Config.load()), extension, app} | ||
| } | ||
|
|
||
| test.each([ | ||
| {custom: true, argv: ['--json', '--no-input']}, | ||
| {custom: true, argv: ['--json']}, | ||
| {custom: false, argv: ['--json', '--no-input']}, | ||
| {custom: false, argv: ['--json']}, | ||
| {custom: true, argv: ['-jcstaging']}, | ||
| {custom: false, argv: ['-jcstaging']}, | ||
| {custom: true, argv: ['-j']}, | ||
| {custom: false, argv: ['-j']}, | ||
| ])('emits one result and codegen side events: %j', async ({custom, argv}) => { | ||
| await inTemporaryDirectory(async (directory) => { | ||
| const {instance, extension, app} = await command(argv, directory, custom) | ||
| vi.mocked(exec).mockImplementation(async (_command, _args, options) => { | ||
| if (options?.stdout && options.stdout !== 'inherit') options.stdout.write('Generating types\n') | ||
| if (options?.stderr && options.stderr !== 'inherit') options.stderr.write('Codegen warning\n') | ||
| await writeFile(joinPath(directory, 'generated.ts'), 'export type Input = {}\n') | ||
| }) | ||
| await withCapturedStandardStreams(async ({stdout, stderr}) => { | ||
| await expect(runWithCommandEventsForCommand(argv, () => instance.run())).resolves.toEqual({app}) | ||
| expect(JSON.parse(stdout())).toEqual({ | ||
| status: 'success', | ||
| function: {handle: extension.configuration.handle ?? null, name: extension.name, directory: resolve(directory)}, | ||
| }) | ||
| const events = stderr() | ||
| .trim() | ||
| .split('\n') | ||
| .map((line) => JSON.parse(line)) | ||
| expect(events).toContainEqual( | ||
| expect.objectContaining({type: 'diagnostic', message: expect.stringContaining('Codegen warning')}), | ||
| ) | ||
| if (custom) | ||
| expect(events).toContainEqual( | ||
| expect.objectContaining({type: 'diagnostic', message: expect.stringContaining('Generating types')}), | ||
| ) | ||
| expect(stderr()).not.toContain('GraphQL types generated successfully.') | ||
| }) | ||
| await expect(readFile(joinPath(directory, 'generated.ts'))).resolves.toBe('export type Input = {}\n') | ||
| expect(exec).toHaveBeenCalledWith( | ||
| custom ? 'custom-codegen' : 'codegen', | ||
| custom ? ['--target', 'test'] : ['--config', 'package.json'], | ||
| expect.objectContaining({cwd: directory}), | ||
| ) | ||
| }) | ||
| }) | ||
|
|
||
| test.each([[], ['--no-input']])('keeps custom codegen text output and the success banner: %j', async (...argv) => { | ||
| await inTemporaryDirectory(async (directory) => { | ||
| const {instance} = await command(argv, directory, true) | ||
| vi.mocked(exec).mockImplementation(async (_command, _args, options) => { | ||
| if (options?.stdout && options.stdout !== 'inherit') options.stdout.write('Native codegen output\n') | ||
| }) | ||
| await withCapturedStandardStreams(async ({stdout, stderr}) => { | ||
| await instance.run() | ||
| expect(stdout()).toBe('Native codegen output\n') | ||
| expect(unstyled(stderr())).toContain('GraphQL types generated successfully.') | ||
| }) | ||
| }) | ||
| }) | ||
|
|
||
| test('emits one fatal document when the custom generator fails', async () => { | ||
| vi.stubEnv('SHOPIFY_FLAG_JSON', '1') | ||
| await inTemporaryDirectory(async (directory) => { | ||
| const {instance} = await command(['--json'], directory, true) | ||
| vi.mocked(exec).mockRejectedValue(new ExternalError('Generator failed', 'custom-codegen', [])) | ||
| await withCapturedStandardStreams(async ({stdout}) => { | ||
| await runWithCommandEventsForCommand(instance.argv, async () => { | ||
| try { | ||
| await instance.run() | ||
| expect.unreachable('Expected typegen to fail') | ||
| } catch (error) { | ||
| if (!(error instanceof ExternalError)) throw error | ||
| await handler(error) | ||
| } | ||
| }) | ||
| expect(JSON.parse(stdout())).toMatchObject({error: {type: 'external', message: 'Generator failed'}}) | ||
| expect(stdout()).not.toContain('"status":"success"') | ||
| }) | ||
| }) | ||
| }) | ||
|
|
||
| test('keeps the missing custom generator error for non-JavaScript functions', async () => { | ||
| await inTemporaryDirectory(async (directory) => { | ||
| const {instance, extension} = await command(['--json'], directory) | ||
| extension.entrySourceFilePath = 'src/main.rs' | ||
| await withCapturedStandardStreams(async ({stdout}) => { | ||
| await expect(runWithCommandEventsForCommand(instance.argv, () => instance.run())).rejects.toThrow(AbortError) | ||
| expect(stdout()).toBe('') | ||
| }) | ||
| expect(exec).not.toHaveBeenCalled() | ||
| }) | ||
| }) | ||
|
|
||
| test('exposes the result schema and retains inherited flags', () => { | ||
| expect(FunctionTypegen.flags.json).toBeDefined() | ||
| expect(FunctionTypegen.flags['no-input']).toBeDefined() | ||
| expect(FunctionTypegen.jsonOutputSchema).toBe(functionTypegenJsonOutputSchema) | ||
| expect(FunctionTypegen.descriptionForHelp()).toContain('FunctionTypegenResult') | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| import {generateFunctionTypes} from './typegen.js' | ||
| import {buildGraphqlTypes} from './build.js' | ||
| import {testApp, testFunctionExtension} from '../../models/app/app.test-data.js' | ||
| import {expect, test, vi} from 'vitest' | ||
|
|
||
| // eslint-disable-next-line no-restricted-imports | ||
| import {resolve} from 'node:path' | ||
|
|
||
| vi.mock('./build.js') | ||
|
|
||
| test('returns a typed Function identity after generation', async () => { | ||
| const extension = await testFunctionExtension() | ||
| const options = {app: testApp(), stdout: process.stdout, stderr: process.stderr} | ||
| await expect(generateFunctionTypes(extension, options)).resolves.toEqual({ | ||
| status: 'success', | ||
| function: { | ||
| handle: extension.configuration.handle ?? null, | ||
| name: extension.name, | ||
| directory: resolve(extension.directory), | ||
| }, | ||
| }) | ||
| expect(buildGraphqlTypes).toHaveBeenCalledWith(extension, options) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| import {buildGraphqlTypes} from './build.js' | ||
| import {type FunctionTypegenResult} from './typegen/types.js' | ||
| import {type ExtensionBuildOptions} from '../build/extension.js' | ||
| import {ExtensionInstance} from '../../models/extensions/extension-instance.js' | ||
| import {FunctionConfigType} from '../../models/extensions/specifications/function.js' | ||
| // eslint-disable-next-line no-restricted-imports | ||
| import {resolve} from 'node:path' | ||
|
|
||
| export async function generateFunctionTypes( | ||
| extension: ExtensionInstance<FunctionConfigType>, | ||
| options: Pick<ExtensionBuildOptions, 'app' | 'stdout' | 'stderr' | 'signal'>, | ||
| ): Promise<FunctionTypegenResult> { | ||
| await buildGraphqlTypes(extension, options) | ||
| return { | ||
| status: 'success', | ||
| function: { | ||
| handle: extension.configuration.handle ?? null, | ||
| name: extension.name, | ||
| directory: resolve(extension.directory), | ||
| }, | ||
| } | ||
| } |
21 changes: 21 additions & 0 deletions
21
packages/app/src/cli/services/function/typegen/result.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| import {functionTypegenJsonOutputSchema} from './types.js' | ||
| import {expect, test} from 'vitest' | ||
|
|
||
| function fixture() { | ||
| return {status: 'success' as const, function: {handle: null, name: 'My Function', directory: '/function'}} | ||
| } | ||
|
|
||
| test.each([ | ||
| {field: 'directory', value: 'relative/path'}, | ||
| {field: 'handle', value: 123}, | ||
| {field: 'unexpected', value: true}, | ||
| ])('rejects invalid Function $field values', ({field, value}) => { | ||
| const result = fixture() | ||
| expect(() => | ||
| functionTypegenJsonOutputSchema.validate({...result, function: {...result.function, [field]: value}}), | ||
| ).toThrow() | ||
| }) | ||
|
|
||
| test('rejects unknown root fields', () => { | ||
| expect(() => functionTypegenJsonOutputSchema.validate({...fixture(), unexpected: true})).toThrow() | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| import {functionTypegenJsonOutputSchema, type FunctionTypegenResult} from './types.js' | ||
| import {outputResult} from '@shopify/cli-kit/node/output' | ||
| import {renderSuccess} from '@shopify/cli-kit/node/ui' | ||
|
|
||
| export function renderFunctionTypegenResult(result: FunctionTypegenResult, json: boolean): void { | ||
| if (json) outputResult(functionTypegenJsonOutputSchema.encode(result)) | ||
| else renderSuccess({headline: 'GraphQL types generated successfully.'}) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| import {functionIdentitySchema} from '../types.js' | ||
| import {defineJsonOutputSchema, type InferJsonOutputSchema} from '@shopify/cli-kit/node/json-output-schema' | ||
| import {zod} from '@shopify/cli-kit/node/schema' | ||
|
|
||
| export const functionTypegenJsonOutputSchema = defineJsonOutputSchema({ | ||
| name: 'FunctionTypegenResult', | ||
| schema: zod | ||
| .object({ | ||
| status: zod.literal('success'), | ||
| function: functionIdentitySchema, | ||
| }) | ||
| .strict(), | ||
| definitions: {Function: functionIdentitySchema}, | ||
| }) | ||
|
|
||
| export type FunctionTypegenResult = InferJsonOutputSchema<typeof functionTypegenJsonOutputSchema> |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.