Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

refactor(cli): delete the central CLIAnyResponse union (structural jsonOut) (#4432)

Joey0b4a276180cc
diff --git a/.changeset/cli-drop-cliany-union.md b/.changeset/cli-drop-cliany-union.md
new file mode 100644
index 0000000000..745f0125ad
--- /dev/null
+++ b/.changeset/cli-drop-cliany-union.md
@@ -0,0 +1,36 @@
+---
+'@astryxdesign/cli': minor
+---
+
+[breaking] cli/json: remove the central `CLIAnyResponse`, `CLIResponseType`, and `CLIResponseDataMap` types. `jsonOut` is now a structural serializer and `parseResponse` / `assertResponse` return the structural `CLIResponse` (`{type, data, meta?}`) instead of the discriminated union, so `result.data` is `unknown` until you narrow it yourself.
+
+Runtime output is unchanged (every `--json` envelope is byte-identical). This only affects consumers importing those types or relying on `parseResponse` / `assertResponse` to auto-narrow `.data`.
+
+To keep discriminated-union narrowing, rebuild it from the individual per-command response types, which are still exported from `@astryxdesign/cli/json`:
+
+```typescript
+import type {
+ ComponentDetailResponse,
+ ComponentListResponse,
+ DocsListResponse,
+ // ...import the responses you consume
+} from '@astryxdesign/cli/json';
+
+// Reconstruct the union you care about (replaces CLIAnyResponse):
+type MyResponse =
+ ComponentDetailResponse | ComponentListResponse | DocsListResponse;
+
+// Narrow parseResponse output by casting to your union:
+const raw = parseResponse(stdout);
+if (!isError(raw)) {
+ const r = raw as MyResponse;
+ if (r.type === 'component.detail') r.data.name; // ✅ narrowed
+}
+
+// Or wrap assertResponse for narrowing at the call site:
+function assertTyped<T extends MyResponse['type']>(raw: unknown, type: T) {
+ return assertResponse(raw, type) as Extract<MyResponse, {type: T}>;
+}
+```
+
+@josephfarina
diff --git a/packages/cli/CONTRIBUTING.md b/packages/cli/CONTRIBUTING.md
index 351390363d..7f7e717d0b 100644
--- a/packages/cli/CONTRIBUTING.md
+++ b/packages/cli/CONTRIBUTING.md
@@ -54,7 +54,7 @@ packages/cli/
schemas/ # zod/JSON schemas
types/ # hand-written .d.ts (see Roadmap: migrating to generated)
api.d.ts # API function signatures + AstryxError
- base.d.ts # CLIError, CLIResult<T>, CLIAnyResponse, CLIResponseType
+ base.d.ts # CLIError, CLIResult<T>, CLIResponse (structural — no central union)
component.d.ts # ComponentListResponse, ComponentDetailResponse, ...
build.d.ts # BuildKitResponse, BuildHelpResponse
swizzle.d.ts # SwizzleListResponse, SwizzleCopyResponse
@@ -168,14 +168,9 @@ Add to `types/index.d.ts`:
export * from './my-command';
```
-Add to `CLIAnyResponse` in `types/base.d.ts`:
-
-```typescript
-export type CLIAnyResponse =
- | ...existing types...
- | MyCommandListResponse
- | MyCommandDetailResponse;
-```
+That's the only type wiring — there is **no central response union** to register
+in. Each response `type` is guaranteed by its own command function's `@returns`
+(the source of truth); consumers import the per-command type directly.
### 5. That's it
@@ -225,15 +220,14 @@ packages/cli/templates/{name}/
1. Add the option to the API function in `api/{command}/{command}.mjs`
2. Pass it through from the CLI handler in `cli/commands/{command}.mjs`
3. Update the types in `types/api.d.ts` (add to the options interface)
-4. If it produces a new response type, also update `types/{command}.d.ts` and `types/base.d.ts`
+4. If it produces a new response type, add its interface to `types/{command}.d.ts` and reference it from the function's `@returns` (no central union to update)
### Adding a new response type (e.g. `component.detail.variants`)
1. Add the logic in `api/{command}/{command}.mjs` — return `{type: 'component.detail.variants', data: ...}`
2. Add a TypeScript interface in `types/{command}.d.ts`
-3. Add it to `CLIAnyResponse` in `types/base.d.ts`
-4. Add it to the result union in `types/api.d.ts`
-5. The parity test will auto-detect the new type and verify API=CLI
+3. Reference it from the function's `@returns` (and the result union in `types/api.d.ts`) — there is no central `CLIAnyResponse` to update
+4. The parity test will auto-detect the new type and verify API=CLI
### Renaming or removing a response type
@@ -367,7 +361,7 @@ Remaining commands, in order (largest / highest-risk deliberately taken one at a
core into `api/init` so the non-interactive path is scriptable.
4. **`blog --json`**: `blog` emits `blog.list` / `blog.detail` today but has **no
`blog.d.ts`** — enabling/locking its `--json` surface must _also_ add the response
- types and register them in `CLIAnyResponse`. Small, low-risk, pure win.
+ types (at the function's `@returns` / `types/blog.d.ts`). Small, low-risk, pure win.
5. **Data-command audit** (`component`, `docs`, `hook`, `template`): confirm no residual
business logic remains CLI-side after the reorg. Mostly already thin.
diff --git a/packages/cli/README.md b/packages/cli/README.md
index 2e6fa0e059..de8dd6c395 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -307,25 +307,56 @@ The CLI command handlers are thin wrappers around these functions: they parse ar
If you're spawning the CLI as a subprocess rather than importing the API directly:
```typescript
-import {parseResponse, isError, assertResponse} from '@astryxdesign/cli/json';
-import type {ComponentDetailResponse, CLIResult} from '@astryxdesign/cli/json';
+import {parseResponse, isError} from '@astryxdesign/cli/json';
+import type {
+ ComponentDetailResponse,
+ ComponentListResponse,
+ DocsListResponse,
+ // ...import the response types for the commands you consume
+} from '@astryxdesign/cli/json';
+
+// parseResponse returns the structural { type, data, meta? } envelope; `data`
+// is `unknown` until you narrow it. Reconstruct the union you care about from
+// the per-command response types, then narrow on `type`:
+type MyResponse =
+ ComponentDetailResponse | ComponentListResponse | DocsListResponse;
const result = parseResponse(stdout);
if (isError(result)) {
console.error(result.error);
} else {
- switch (result.type) {
+ const r = result as MyResponse;
+ switch (r.type) {
case 'component.detail':
- result.data.name; // TypeScript: ComponentDoc
+ r.data.name; // narrowed to ComponentDoc
break;
}
}
+```
+
+Prefer narrowing at the call site? Wrap `assertResponse` (which throws on
+error/mismatch) with your reconstructed union:
+
+```typescript
+import {assertResponse} from '@astryxdesign/cli/json';
+import type {ComponentDetailResponse} from '@astryxdesign/cli/json';
-// Or assert directly (throws on error/mismatch):
-const detail = assertResponse(stdout, 'component.detail');
-detail.data.name; // already narrowed
+type MyResponse = ComponentDetailResponse; /* | ...others */
+
+function assertTyped<T extends MyResponse['type']>(raw: unknown, type: T) {
+ return assertResponse(raw, type) as Extract<MyResponse, {type: T}>;
+}
+
+const detail = assertTyped(stdout, 'component.detail');
+detail.data.name; // narrowed
```
+> **Migration (removed in the structural-`jsonOut` release):** the central
+> `CLIAnyResponse`, `CLIResponseType`, and `CLIResponseDataMap` exports were
+> removed. `parseResponse` / `assertResponse` no longer auto-narrow `.data`.
+> Rebuild the union from the individual `*Response` types as shown above — they
+> are all still exported from `@astryxdesign/cli/json`.
+
### Type discriminators
Every response has a `type` string that uniquely identifies it:
diff --git a/packages/cli/cli/commands/build-theme.mjs b/packages/cli/cli/commands/build-theme.mjs
index 78f4ecd915..0a6673493d 100644
--- a/packages/cli/cli/commands/build-theme.mjs
+++ b/packages/cli/cli/commands/build-theme.mjs
@@ -1118,18 +1118,21 @@ export function registerTheme(program) {
}
if (json) {
- return jsonOut('theme.build', {
- name: themeDef.name,
- tokenCount,
- componentCount,
- sizeKB: parseFloat(size),
- outputs: {
- css: path.relative(process.cwd(), outPath),
- js: path.relative(process.cwd(), jsPath),
- dts: path.relative(process.cwd(), dtsPath),
- ...(variantDecl && variantDtsPath ? {variantsDts: path.relative(process.cwd(), variantDtsPath)} : {}),
+ return jsonOut({
+ type: 'theme.build',
+ data: {
+ name: themeDef.name,
+ tokenCount,
+ componentCount,
+ sizeKB: parseFloat(size),
+ outputs: {
+ css: path.relative(process.cwd(), outPath),
+ js: path.relative(process.cwd(), jsPath),
+ dts: path.relative(process.cwd(), dtsPath),
+ ...(variantDecl && variantDtsPath ? {variantsDts: path.relative(process.cwd(), variantDtsPath)} : {}),
+ },
+ warnings: warningMessages,
},
- warnings: warningMessages,
});
}
@@ -1186,9 +1189,7 @@ Or with a <link> tag:
return;
}
- // theme.list is not registered in CLIResponseType (base.d.ts, owned by the
- // coordinator) — cast the discriminant until it is added there.
- if (json) return jsonOut(/** @type {any} */ (result.type), result.data);
+ if (json) return jsonOut(result);
const themes = result.data;
if (themes.length === 0) {
@@ -1233,9 +1234,7 @@ Or with a <link> tag:
return;
}
- // theme.list/theme.add are not registered in CLIResponseType (base.d.ts,
- // owned by the coordinator) — cast the discriminant until they are added.
- if (json) return jsonOut(/** @type {any} */ (result.type), result.data);
+ if (json) return jsonOut(result);
if (result.type === 'theme.list') {
const themes = result.data;
diff --git a/packages/cli/cli/commands/build.mjs b/packages/cli/cli/commands/build.mjs
index 99d4d9c13e..afe44c48ff 100644
--- a/packages/cli/cli/commands/build.mjs
+++ b/packages/cli/cli/commands/build.mjs
@@ -68,7 +68,7 @@ export function registerBuild(program) {
// No query → the playbook. Still routed through the API for the envelope.
if (!query || !String(query).trim()) {
const result = await buildApi(undefined, {cwd: process.cwd()});
- if (json) return jsonOut(result.type, result.data);
+ if (json) return jsonOut(result);
printPlaybook(run);
return;
}
@@ -96,7 +96,7 @@ export function registerBuild(program) {
return;
}
- if (json) return jsonOut(result.type, result.data);
+ if (json) return jsonOut(result);
const {query: q, hasResults, directMatch, pages, blocks, domain, frame, foundation} =
result.data;
diff --git a/packages/cli/cli/commands/component/index.mjs b/packages/cli/cli/commands/component/index.mjs
index 361b8ddeb1..768b007c70 100644
--- a/packages/cli/cli/commands/component/index.mjs
+++ b/packages/cli/cli/commands/component/index.mjs
@@ -108,7 +108,7 @@ export function registerComponent(program) {
return;
}
- if (json) return jsonOut(result.type, result.data);
+ if (json) return jsonOut(result);
// ── Text output ────────────────────────────────────────────
// The api layer already resolved against core (result exists), so core is
diff --git a/packages/cli/cli/commands/discover.mjs b/packages/cli/cli/commands/discover.mjs
index f6b303f5c0..ce8bd00804 100644
--- a/packages/cli/cli/commands/discover.mjs
+++ b/packages/cli/cli/commands/discover.mjs
@@ -49,7 +49,7 @@ export function registerDiscover(program) {
// Forward optional meta (e.g. configured flag for discover.list) as a
// sibling of data via jsonOut, so the envelope still carries
// apiVersion and goes through the single sanctioned emit path.
- return jsonOut(result.type, result.data, 'meta' in result ? result.meta : undefined);
+ return jsonOut(result);
}
switch (result.type) {
diff --git a/packages/cli/cli/commands/docs.mjs b/packages/cli/cli/commands/docs.mjs
index 18ad64b566..b8be68e627 100644
--- a/packages/cli/cli/commands/docs.mjs
+++ b/packages/cli/cli/commands/docs.mjs
@@ -154,7 +154,7 @@ export function registerDocs(program) {
return;
}
- if (json) return jsonOut(result.type, result.data);
+ if (json) return jsonOut(result);
switch (result.type) {
case 'docs.list': {
diff --git a/packages/cli/cli/commands/doctor.mjs b/packages/cli/cli/commands/doctor.mjs
index 7ce6bdf265..8c5cc7de1e 100644
--- a/packages/cli/cli/commands/doctor.mjs
+++ b/packages/cli/cli/commands/doctor.mjs
@@ -72,7 +72,7 @@ export function registerDoctor(program) {
const hasFailure = report.summary.fail > 0;
if (json) {
- jsonOut('doctor', report);
+ jsonOut({type: 'doctor', data: report});
} else {
printHuman(report);
}
diff --git a/packages/cli/cli/commands/hook/index.mjs b/packages/cli/cli/commands/hook/index.mjs
index 4e2f57920d..b039dc49d7 100644
--- a/packages/cli/cli/commands/hook/index.mjs
+++ b/packages/cli/cli/commands/hook/index.mjs
@@ -80,7 +80,7 @@ export function registerHook(program) {
return;
}
- if (json) return jsonOut(result.type, result.data);
+ if (json) return jsonOut(result);
// ── Text output ────────────────────────────────────────────
switch (result.type) {
diff --git a/packages/cli/cli/commands/layout.mjs b/packages/cli/cli/commands/layout.mjs
index 1efcfae2e7..f9b023dccd 100644
--- a/packages/cli/cli/commands/layout.mjs
+++ b/packages/cli/cli/commands/layout.mjs
@@ -96,7 +96,7 @@ export function registerLayout(program) {
cliError(err.message, {suggestions: err.suggestions || [], code: err.code});
return;
}
- if (json) return jsonOut(result.type, result.data);
+ if (json) return jsonOut(result);
for (const warning of result.data.warnings) humanLog(`⚠ ${warning}`);
if (result.data.written) {
@@ -137,7 +137,7 @@ export function registerLayout(program) {
cliError(err.message, {suggestions: err.suggestions || [], code: err.code});
return;
}
- if (json) return jsonOut(result.type, result.data);
+ if (json) return jsonOut(result);
const {valid, form, errors, warnings, compact, outline} = result.data;
if (!valid) {
@@ -173,7 +173,7 @@ export function registerLayout(program) {
cliError(err.message, {suggestions: err.suggestions || [], code: err.code});
return;
}
- if (json) return jsonOut(result.type, result.data);
+ if (json) return jsonOut(result);
humanLog(result.data.text);
});
}
diff --git a/packages/cli/cli/commands/search.mjs b/packages/cli/cli/commands/search.mjs
index 07f917c60c..a1090c337b 100644
--- a/packages/cli/cli/commands/search.mjs
+++ b/packages/cli/cli/commands/search.mjs
@@ -67,7 +67,7 @@ export function registerSearch(program) {
return;
}
- if (json) return jsonOut(result.type, result.data);
+ if (json) return jsonOut(result);
// ── Text output ──────────────────────────────────────────────
const run = getCliInvocation();
diff --git a/packages/cli/cli/commands/swizzle.mjs b/packages/cli/cli/commands/swizzle.mjs
index 492886a154..de11802d10 100644
--- a/packages/cli/cli/commands/swizzle.mjs
+++ b/packages/cli/cli/commands/swizzle.mjs
@@ -46,7 +46,7 @@ export function registerSwizzle(program) {
return;
}
- if (json) return jsonOut(result.type, result.data);
+ if (json) return jsonOut(result);
if (result.type === 'swizzle.list') {
const components = result.data;
diff --git a/packages/cli/cli/commands/template.mjs b/packages/cli/cli/commands/template.mjs
index 0d15267969..9faa49ffb4 100644
--- a/packages/cli/cli/commands/template.mjs
+++ b/packages/cli/cli/commands/template.mjs
@@ -119,7 +119,7 @@ export function registerTemplate(program) {
return;
}
- if (json) return jsonOut(result.type, result.data);
+ if (json) return jsonOut(result);
switch (result.type) {
case 'template.list': {
diff --git a/packages/cli/cli/commands/upgrade.mjs b/packages/cli/cli/commands/upgrade.mjs
index 029ef57423..4640071f7a 100644
--- a/packages/cli/cli/commands/upgrade.mjs
+++ b/packages/cli/cli/commands/upgrade.mjs
@@ -61,7 +61,7 @@ export function registerUpgrade(program) {
throw e;
}
- if (json) jsonOut(result.type, result.data);
+ if (json) jsonOut(result);
},
);
}
diff --git a/packages/cli/cli/commands/validate-integration.mjs b/packages/cli/cli/commands/validate-integration.mjs
index 617e5d2d28..2d64f60a9c 100644
--- a/packages/cli/cli/commands/validate-integration.mjs
+++ b/packages/cli/cli/commands/validate-integration.mjs
@@ -74,7 +74,7 @@ export function registerValidateIntegration(program) {
const result = await validateIntegration(pkg);
if (json) {
- jsonOut(result.type, result.data);
+ jsonOut(result);
} else if (result.data.name === null) {
// No-arg + no local manifest: guidance, not an error.
humanLog(NO_MANIFEST_GUIDANCE);
diff --git a/packages/cli/lib/json-contract.test.mjs b/packages/cli/lib/json-contract.test.mjs
index 28190e0c44..9dccde9bb0 100644
--- a/packages/cli/lib/json-contract.test.mjs
+++ b/packages/cli/lib/json-contract.test.mjs
@@ -51,7 +51,7 @@ describe('json envelope shape', () => {
});
it('jsonOut stamps apiVersion + type + data', () => {
- jsonOut('docs.list', [{name: 'Button'}]);
+ jsonOut({type: 'docs.list', data: [{name: 'Button'}]});
const env = JSON.parse(logs[0]);
expect(env.apiVersion).toBe(API_VERSION);
expect(env.type).toBe('docs.list');
@@ -60,7 +60,7 @@ describe('json envelope shape', () => {
});
it('jsonOut attaches optional meta as a sibling of data', () => {
- jsonOut('discover.list', [], {configured: false});
+ jsonOut({type: 'discover.list', data: [], meta: {configured: false}});
const env = JSON.parse(logs[0]);
expect(env.meta).toEqual({configured: false});
expect(env.data).toEqual([]);
diff --git a/packages/cli/lib/json.mjs b/packages/cli/lib/json.mjs
index a1f5acc04c..f5d04be04c 100644
--- a/packages/cli/lib/json.mjs
+++ b/packages/cli/lib/json.mjs
@@ -19,7 +19,7 @@
* 4. Uncaught throws in --json mode become a JSON error envelope, never a
* raw stack trace (see toErrorEnvelope / the bin error boundary).
*
- * Commands call jsonOut(type, data) for success and jsonError(msg) for
+ * Commands call jsonOut({type, data}) for success and jsonError(msg) for
* errors. Consumer-facing utilities (parseResponse, isError, assertResponse)
* live in parse.mjs and are exported via @astryxdesign/cli/json.
*/
@@ -83,21 +83,21 @@ export function humanWarn(...args) {
}
/**
- * Output a typed JSON response envelope and mark as handled.
- * Type safety enforced via declaration in types/base.d.ts —
- * data must match the declared shape for the given type discriminator.
- * @template {import('../types/base').CLIResponseType} T
- * @param {T} type
- * @param {import('../types/base').CLIResponseDataMap[T]} data
- * @param {Record<string, unknown>} [meta] - Optional sidecar metadata (e.g.
- * {configured: false}). Emitted as a sibling of data, never merged into it.
+ * Output a JSON response envelope and mark it handled.
+ *
+ * Structural serializer: pass a command/API result straight through as
+ * `{type, data, meta?}`. There is no central response union — the correctness
+ * of the `type` discriminator is guaranteed at each API function's `@returns`
+ * (that's the fractal source-of-truth point), not by a map in this file.
+ *
+ * @param {{type: string, data: unknown, meta?: Record<string, unknown>}} response
* @returns {void}
*/
-export function jsonOut(type, data, meta) {
+export function jsonOut(response) {
process.__xdsJsonHandled = true;
/** @type {any} */
- const envelope = {apiVersion: API_VERSION, type, data};
- if (meta !== undefined) envelope.meta = meta;
+ const envelope = {apiVersion: API_VERSION, type: response.type, data: response.data};
+ if (response.meta !== undefined) envelope.meta = response.meta;
console.log(JSON.stringify(envelope, null, 2));
}
diff --git a/packages/cli/types/base.d.ts b/packages/cli/types/base.d.ts
index 37d8f0cff8..1e55959dfe 100644
--- a/packages/cli/types/base.d.ts
+++ b/packages/cli/types/base.d.ts
@@ -3,67 +3,14 @@
/**
* Shared types for the Astryx CLI JSON API.
*
- * CLIError and CLIUnsupportedError are the two error shapes.
- * CLIAnyResponse is the union of all success response types.
- * CLIResult<T> wraps any response with possible errors.
+ * `CLIError` and `CLIUnsupportedError` are the two error shapes. Success
+ * responses are the structural `{ type, data, meta? }` envelope (`CLIResponse`)
+ * — there is NO central union of every response. Each command's precise
+ * response type is the source of truth at its own function; import the
+ * per-command type, or use `ReturnType<typeof fn>`, when you need it.
*/
-import type {
- ComponentListResponse,
- ComponentBriefResponse,
- ComponentFullResponse,
- ComponentDetailResponse,
- ComponentDetailPropsResponse,
- ComponentDetailSourceResponse,
- ComponentDetailShowcaseResponse,
- ComponentDetailBlocksResponse,
-} from './component';
-import type {
- DiscoverListResponse,
- DiscoverDetailResponse,
- DiscoverDetailDocResponse,
- DiscoverSearchResponse,
-} from './discover';
-import type {
- DocsListResponse,
- DocsDetailResponse,
- DocsDetailSectionResponse,
-} from './docs';
-import type {
- TemplateListResponse,
- TemplateShowResponse,
- TemplateSkeletonResponse,
- TemplateCopyResponse,
-} from './template';
-import type {
- HookListResponse,
- HookBriefResponse,
- HookFullResponse,
- HookDetailResponse,
- HookDetailParamsResponse,
-} from './hook';
-import type {SwizzleListResponse, SwizzleCopyResponse} from './swizzle';
-import type {
- ThemeBuildResponse,
- ThemeListResponse,
- ThemeAddResponse,
-} from './theme';
-import type {
- UpgradeListResponse,
- UpgradeRunResponse,
- UpgradeStatusResponse,
-} from './upgrade';
-import type {SearchResponse} from './search';
-import type {
- LayoutExpandResponse,
- LayoutCheckResponse,
- LayoutGrammarResponse,
-} from './layout';
-import type {BuildHelpResponse, BuildKitResponse} from './build';
import type {ErrorCode} from './error-codes';
-import type {ManifestResponse} from './manifest';
-import type {DoctorResponse} from './doctor';
-import type {ValidateIntegrationResponse} from './validate-integration';
/**
* A "did you mean…" suggestion attached to an error. `reason` is optional:
@@ -93,72 +40,28 @@ export interface CLIUnsupportedError {
code: ErrorCode;
}
-/** Wrap any response type to include possible error shapes. */
-export type CLIResult<T> = T | CLIError | CLIUnsupportedError;
-
-/** Union of all possible success response types. */
-export type CLIAnyResponse =
- | ComponentListResponse
- | ComponentBriefResponse
- | ComponentFullResponse
- | ComponentDetailResponse
- | ComponentDetailPropsResponse
- | ComponentDetailSourceResponse
- | ComponentDetailShowcaseResponse
- | ComponentDetailBlocksResponse
- | DiscoverListResponse
- | DiscoverDetailResponse
- | DiscoverDetailDocResponse
- | DiscoverSearchResponse
- | DocsListResponse
- | DocsDetailResponse
- | DocsDetailSectionResponse
- | TemplateListResponse
- | TemplateShowResponse
- | TemplateSkeletonResponse
- | TemplateCopyResponse
- | HookListResponse
- | HookBriefResponse
- | HookFullResponse
- | HookDetailResponse
- | HookDetailParamsResponse
- | SwizzleListResponse
- | SwizzleCopyResponse
- | ThemeBuildResponse
- | ThemeListResponse
- | ThemeAddResponse
- | UpgradeListResponse
- | UpgradeRunResponse
- | UpgradeStatusResponse
- | SearchResponse
- | LayoutExpandResponse
- | LayoutCheckResponse
- | LayoutGrammarResponse
- | BuildHelpResponse
- | BuildKitResponse
- | ManifestResponse
- | DoctorResponse
- | ValidateIntegrationResponse;
-
-/** Union of all type discriminator string literals. */
-export type CLIResponseType = CLIAnyResponse['type'];
-
/**
- * Map from type discriminator to the data shape for that response.
- * Used by jsonOut to enforce type-safe data payloads.
+ * A success response envelope: a `type` discriminator, its `data` payload, and
+ * an optional `meta` sidecar (emitted as a sibling of `data`, never merged in).
+ *
+ * Structural by design — there is no central union of every response `type`.
+ * A specific command narrows `data` via its own return type.
*/
-export type CLIResponseDataMap = {
- [R in CLIAnyResponse as R['type']]: R['data'];
-};
+export interface CLIResponse {
+ type: string;
+ data: unknown;
+ meta?: Record<string, unknown>;
+}
+
+/** Wrap any response type to include possible error shapes. */
+export type CLIResult<T> = T | CLIError | CLIUnsupportedError;
/**
- * Output a typed JSON response envelope. The data parameter is
- * constrained to match the declared shape for the given type discriminator.
+ * Output a JSON response envelope. Structural serializer — the correctness of
+ * the `type` discriminator is guaranteed at each API function's return type,
+ * not by a central map here.
*/
-export function jsonOut<T extends CLIResponseType>(
- type: T,
- data: CLIResponseDataMap[T],
-): void;
+export function jsonOut(response: CLIResponse): void;
/**
* Output a structured JSON error and exit.
@@ -169,21 +72,25 @@ export function jsonError(
code?: ErrorCode,
): never;
-/** Parse raw CLI output (string or object) into typed result. */
+/** Parse raw CLI output (string or object) into a typed result. */
export function parseResponse(
raw: unknown,
-): CLIAnyResponse | CLIError | CLIUnsupportedError;
+): CLIResponse | CLIError | CLIUnsupportedError;
/** Type guard: returns true if result is an error. */
export function isError(
result: unknown,
): result is CLIError | CLIUnsupportedError;
-/** Assert a specific response type. Throws on error or type mismatch. */
-export function assertResponse<T extends CLIResponseType>(
+/**
+ * Assert a specific response type. Throws on error or type mismatch. Narrows
+ * the returned `type` to the expected literal; `data` stays `unknown` — import
+ * the per-command response type when you need a precise payload.
+ */
+export function assertResponse<T extends string>(
raw: unknown,
type: T,
-): Extract<CLIAnyResponse, {type: T}>;
+): CLIResponse & {type: T};
declare global {
namespace NodeJS {