Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .oxlintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@
"sentry-cli/no-examples-in-full-description": "error",
"sentry-cli/no-regex-markdown-parsing": "error",
"sentry-cli/json-transform-uses-fields": "error",
"sentry-cli/no-runtime-output-schema-imports": "error",
"no-restricted-imports": [
"error",
{
Expand Down
31 changes: 24 additions & 7 deletions packages/cli/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -239,29 +239,46 @@ Lint enforcement: `stderr.write()` is banned in command files (GritQL rule). Use

`output.schema` drives `--fields` completion, the JSON field table in `--help`, and the skill references. Nothing validates output against it, so declare each field once and derive the TypeScript type from the schema; the compiler then keeps the two in sync ([#1824](https://github.com/getsentry/toolkit/issues/1824)).

The schemas live in `src/output-schemas/<area>.ts` (one module per top-level command), which only the build loads ([#1914](https://github.com/getsentry/toolkit/issues/1914)). `script/generate-output-schemas.ts` (part of `generate:docs`) reads each exported `…Schema` and writes its field list and `--fields` paths to the gitignored `src/generated/output-schemas/<area>.ts`, under the same export name. A command imports that data as its `output.schema`, so a run loads only its own route's field lists, and none of the schemas:

- Import the schema data from `src/generated/output-schemas/`, and everything else from `src/output-schemas/` with `import type` only. Lint (`sentry-cli/no-runtime-output-schema-imports`) rejects a value import, or `import { type X }`, which `verbatimModuleSyntax` keeps as a runtime import.
- Export the type the command needs next to its schema (`export type ReleaseDeleteOutput = InferOutput<typeof ReleaseDeleteOutputSchema>`), or `import type` the schema and write `typeof`.
- A schema that also validates an API response at runtime (`SentryLogSchema`, `TransactionListItemSchema`, `ConversationListItemSchema`, `DashboardRevisionSchema`) stays where it is and is re-exported from its area's module.
- `src/output-schemas/` must not import `src/generated/output-schemas/`: the generator loads the former to write the latter.

- **API fields** keep their `@sentry/api` type and come from the generated `@sentry/api/valibot` schema (`vXxxResponse.entries`, wrapped in `pipe(field, description(…))` when it needs a description).
- **Fields the CLI adds** (target context such as `org`/`orgSlug`, flags such as `dryRun`/`deleted`, computed values such as `url`, `trace`, `period`) are written once as a valibot `object` of output fields. Spread its `entries` into the schema, and get the type with `InferOutput<typeof Fields>`, or `WithOutputFields<ApiType, typeof Fields>` (`src/types/output.ts`) when the fields sit on (or override) an API object.
- **Fields the CLI adds** (target context such as `org`/`orgSlug`, flags such as `dryRun`/`deleted`, computed values such as `url`, `trace`, `period`) are written once as a valibot `object` of output fields. Spread its `entries` into the schema, and get the type with `InferOutput<typeof Fields>`, or `WithOutputFields<ApiType, typeof Fields>` (`src/output-schemas/output.ts`) when the fields sit on (or override) an API object.
- Type the `human` formatter's parameter (and `jsonTransform`'s, when set) with the derived type. `buildCommand`, `buildListCommand`, and `buildDeleteCommand` infer the output type from `output` and check every `CommandOutput` that `func` yields against it. Annotate a yield (`new CommandOutput<Output>(…)`) only when it builds a discriminated-union literal (`kind: "endpoints"`) that would otherwise widen to `string`.
- Without `jsonTransform`, the data (each item, for array data) must also satisfy `output.schema`: a field the schema documents but the command doesn't produce, or documents with another type, is a compile error. Keep the data typed: an API response typed `Record<string, unknown>` can't satisfy a schema built from `@sentry/api/valibot`, so type it with its `@sentry/api` response type.
- With `jsonTransform`, the schema describes the transform's item: each item of a `{ data: [...] }` envelope or an array, otherwise the result itself. Every field the schema documents must exist on that item with a matching type; optionality isn't compared, since `--fields` makes items `Partial`. So the transform must return a typed result, not `unknown` or `Record<string, unknown>`: return `ListJson<Item>` from `jsonTransformListResult`, type a hand-built envelope as `ListEnvelope<Item>` (`lib/org-list.ts`), and let a single object's type come from its spread with `filterFieldsIfSet`. The error names the mismatched fields under `~outputMismatch`.
- An `OrgListConfig` checks its entity against `schema` when you pass the schema's type: `OrgListConfig<SentryTeam, TeamWithOrg, typeof SentryTeamSchema>`. Don't annotate an output config as `OutputConfig<T>` or check it with `satisfies OutputConfig<T>`: that erases the schema's type, and the check passes without comparing anything.
- Reuse the shared fields: `DryRunOutputField`, `orgListItemSchema`/`WithOrg` (`lib/org-list.ts`) for org-scoped lists, `opaque<T>()` for a field the docs leave opaque but the code types (a full event payload).
- An `OrgListConfig` takes the item's schema data (`orgListItemSchema(Entity)`, exported from the area's module) and checks its entity against it when you pass its type: `OrgListConfig<SentryTeam, TeamWithOrg, typeof TeamListItemSchema>`. Don't annotate an output config as `OutputConfig<T>` or check it with `satisfies OutputConfig<T>`: that erases the schema's type, and the check passes without comparing anything.
- Reuse the shared fields: `DryRunOutputField` and `opaque<T>()` (`src/output-schemas/output.ts`; `opaque` is for a field the docs leave opaque but the code types, such as a full event payload), and `orgListItemSchema` (`src/output-schemas/org-list.ts`) with `WithOrg` (`lib/org-list.ts`) for org-scoped lists.
- Data only the human formatter needs (pre-rendered lines, a resolved target) stays out of the schema; keep it outside the derived type or strip it with `jsonExclude`.

```typescript
const DeployOutputFields = object({
// src/output-schemas/release.ts
export const ReleaseDeployOutputFields = object({
dryRun: DryRunOutputField,
version: optional(pipe(string(), description("Release version (--dry-run)"))),
});
type DeployOutput = WithOutputFields<SentryDeploy, typeof DeployOutputFields>;
export const ReleaseDeployOutputSchema = looseObject({
...SentryDeploySchema.entries,
...ReleaseDeployOutputFields.entries,
});

// src/commands/release/deploy.ts
import { ReleaseDeployOutputSchema } from "../../generated/output-schemas/release.js";
import type { ReleaseDeployOutputFields } from "../../output-schemas/release.js";

type DeployOutput = WithOutputFields<SentryDeploy, typeof ReleaseDeployOutputFields>;

output: {
human: (deploy: DeployOutput) => …,
schema: looseObject({ ...SentryDeploySchema.entries, ...DeployOutputFields.entries }),
schema: ReleaseDeployOutputSchema,
},
```

Reference: `src/commands/release/deploy.ts`, `src/commands/alert/output-schemas.ts`, `ReplayViewOutputFields` in `src/types/replay.ts`.
Reference: `src/commands/release/deploy.ts`, `src/output-schemas/alert.ts`, `ReplayViewOutputFields` in `src/output-schemas/replay.ts`.

### Route Maps (Stricli)

Expand Down
30 changes: 30 additions & 0 deletions packages/cli/lint-rules/cli-oxlint-plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -731,6 +731,36 @@ const rules = {
}
: {},
),
"no-runtime-output-schema-imports": rule(
"src/output-schemas/ is build-only: use `import type` from it, and import the field data from src/generated/output-schemas/.",
(_context, file, report) => {
if (!file.includes("/src/") || file.includes("/src/output-schemas/"))
return {};
const buildOnly = (source) =>
typeof source === "string" &&
/(?:^|\/)output-schemas\//.test(source) &&
!/(?:^|\/)generated\/output-schemas\//.test(source);
// Only `import type` / `export type` is erased whole. Under
// `verbatimModuleSyntax`, `import { type X }` still loads the module.
return {
ImportDeclaration(node) {
if (buildOnly(node.source.value) && node.importKind !== "type")
report(node);
},
ExportNamedDeclaration(node) {
if (buildOnly(node.source?.value) && node.exportKind !== "type")
report(node);
},
ExportAllDeclaration(node) {
if (buildOnly(node.source.value) && node.exportKind !== "type")
report(node);
},
ImportExpression(node) {
if (buildOnly(node.source.value)) report(node);
},
};
},
),
"no-skipped-tests": rule(
"Do not leave disabled tests in the suite.",
(_context, file, report) =>
Expand Down
3 changes: 2 additions & 1 deletion packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,9 @@
"generate:sdk": "pnpm tsx script/generate-sdk.ts",
"generate:skill": "pnpm tsx script/generate-skill.ts",
"generate:banner": "pnpm tsx script/generate-banner-image.ts",
"generate:docs": "node script/ensure-generated.mjs schema && pnpm run generate:grammar && pnpm run generate:command-api && pnpm run generate:banner && pnpm run generate:completions && pnpm run generate:top-level-routes && pnpm run generate:command-docs && pnpm run generate:docs-sections && pnpm run generate:skill",
"generate:docs": "node script/ensure-generated.mjs schema && pnpm run generate:grammar && pnpm run generate:output-schemas && pnpm run generate:command-api && pnpm run generate:banner && pnpm run generate:completions && pnpm run generate:top-level-routes && pnpm run generate:command-docs && pnpm run generate:docs-sections && pnpm run generate:skill",
"generate:grammar": "node ../../scripts/generate-parsers.mjs .",
"generate:output-schemas": "pnpm tsx script/generate-output-schemas.ts",
"generate:completions": "pnpm tsx script/generate-completion-targets.ts",
"generate:top-level-routes": "pnpm tsx script/generate-top-level-routes.ts",
"generate:docs-sections": "pnpm tsx script/generate-docs-sections.ts",
Expand Down
1 change: 1 addition & 0 deletions packages/cli/script/ensure-generated.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ const GRAMMAR_OUTPUTS = [
];
/** Produced by `generate:docs`; imported at runtime by `src/`. */
const DOCS_OUTPUTS = [
"src/generated/output-schemas",
"src/generated/command-api.json",
"src/generated/skill-content.ts",
"src/generated/completion-targets.json",
Expand Down
102 changes: 102 additions & 0 deletions packages/cli/script/generate-output-schemas.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
#!/usr/bin/env tsx
/**
* Generate Output Schema Fields
*
* Command output schemas (`src/output-schemas/`) are valibot schemas the CLI
* only needs for their field list: `--help`, `sentry help <cmd>`, `--fields`
* parsing and completion, the skill references, and the SDK's return types.
* Reading that list out of a schema needs the schema, valibot, and
* everything the schema spreads in from `@sentry/api/valibot`, so this
* script reads it at build time instead. It loads each module in
* `src/output-schemas/`, and for each exported valibot schema whose name
* ends in `Schema` writes its fields and field paths
* ({@link OutputSchemaFields}) to `src/generated/output-schemas/`, in a
* module of the same name and under the same export name. Commands import
* those, so a run loads the field data of its own route's commands and no
* schema.
*
* `src/output-schemas/` must not import from `src/generated/output-schemas/`:
* this script loads it to write that directory.
*
* The output is gitignored and regenerated by `generate:docs`, which runs as
* part of `dev`, `build`, `bundle`, `typecheck`, and `test`.
*
* Usage: tsx script/generate-output-schemas.ts
* Output: src/generated/output-schemas/*.ts
*/

import { mkdir, readdir, rm, writeFile } from "node:fs/promises";
import { basename, resolve } from "node:path";
import { pathToFileURL } from "node:url";
import type { GenericSchema } from "valibot";
import type { OutputSchemaFields } from "../src/lib/formatters/output.js";
import {
extractSchemaFieldPaths,
extractSchemaFields,
} from "./lib/output-schema-fields.js";

const SOURCE_DIR = "src/output-schemas";
const OUTPUT_DIR = "src/generated/output-schemas";

/** Whether `value` is a valibot schema (not an action or a plain value). */
function isSchema(value: unknown): value is GenericSchema {
return (
typeof value === "object" &&
value !== null &&
(value as { kind?: unknown }).kind === "schema"
);
}

/** The generated module for one `src/output-schemas/` module. */
function renderModule(
name: string,
schemas: [string, GenericSchema][],
): string {
const source = `../../output-schemas/${name}.js`;
const lines = [
`// Generated by script/generate-output-schemas.ts from ${SOURCE_DIR}/${name}.ts.`,
"// Do not edit; change the schemas there instead.",
"",
'import type { OutputSchemaFields } from "../../lib/formatters/output.js";',
"import type {",
...schemas.map(([exportName]) => ` ${exportName} as ${exportName}Source,`),
`} from ${JSON.stringify(source)};`,
];
for (const [exportName, schema] of schemas) {
const fields: OutputSchemaFields = {
fields: extractSchemaFields(schema),
paths: extractSchemaFieldPaths(schema),
};
lines.push(
"",
`export const ${exportName}: OutputSchemaFields<typeof ${exportName}Source> = ${JSON.stringify(fields)};`,
);
}
return `${lines.join("\n")}\n`;
}

const files = (await readdir(SOURCE_DIR))
.filter((file) => file.endsWith(".ts"))
.sort();

await rm(OUTPUT_DIR, { recursive: true, force: true });
await mkdir(OUTPUT_DIR, { recursive: true });

let count = 0;
for (const file of files) {
const name = basename(file, ".ts");
const exports: Record<string, unknown> = await import(
pathToFileURL(resolve(SOURCE_DIR, file)).href
);
const schemas = Object.entries(exports).filter(
(entry): entry is [string, GenericSchema] =>
entry[0].endsWith("Schema") && isSchema(entry[1]),
);
if (schemas.length === 0) {
continue;
}
count += schemas.length;
await writeFile(`${OUTPUT_DIR}/${name}.ts`, renderModule(name, schemas));
}

console.log(`Generated ${OUTPUT_DIR}/ (${count} output schemas)`);
20 changes: 8 additions & 12 deletions packages/cli/script/generate-sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
import { writeFile } from "node:fs/promises";
import ts from "typescript";
import { routes } from "../src/app.js";
import { extractSchemaFields } from "../src/lib/formatters/output.js";
import type { SchemaFieldInfo } from "../src/lib/formatters/output.js";
import {
type Command,
type FlagDef,
Expand Down Expand Up @@ -238,7 +238,7 @@ function derivePositional(command: Command): PositionalInfo {
}

// ---------------------------------------------------------------------------
// Return Type Generation from __jsonSchema
// Return Type Generation from __jsonFields
// ---------------------------------------------------------------------------

/** Map a single schema field type name to a TypeScript type node. */
Expand Down Expand Up @@ -306,20 +306,16 @@ function propertySignature(
}

/**
* Build the result type from a command's __jsonSchema.
* Returns null if no schema is attached.
* Build the result type from a command's __jsonFields.
* Returns null if no output schema is attached.
*/
function buildReturnType(
command: Command,
typeName: string,
): ts.TypeAliasDeclaration | null {
const schema = (command as any).__jsonSchema;
if (!schema) {
return null;
}

const fields = extractSchemaFields(schema);
if (fields.length === 0) {
const fields: readonly SchemaFieldInfo[] | undefined = (command as any)
.__jsonFields;
if (!fields?.length) {
return null;
}

Expand Down Expand Up @@ -801,7 +797,7 @@ const sdkType = exportedObjectType(SDK_TYPE_NAME, [

/** Sections shared verbatim by the implementation file and the published declarations. */
const sharedTypes = [
"// --- Return types (derived from __jsonSchema) ---",
"// --- Return types (derived from __jsonFields) ---",
"",
returnTypes.length > 0
? printNodes(returnTypes)
Expand Down
Loading
Loading