Skip to content
Open
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
54 changes: 54 additions & 0 deletions apps/cli/src/command-internal/flag-documentation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { Context, Option } from "effect";
import type { Param } from "effect/cli";
import type { UnwrappedParam } from "./param-introspection.ts";

export interface FlagDocumentationShape {
readonly defaultValue?: string;
readonly choices?: ReadonlyArray<string>;
readonly required?: boolean;
/** Website compatibility labels need not describe an actual runtime default. */
readonly helpDefault?: string | false;
}

export class FlagDocumentation extends Context.Service<FlagDocumentation, FlagDocumentationShape>()(
"supabase/FlagDocumentation",
) {}

export function flagDocumentation(
single: Param.Single<Param.ParamKind, unknown>,
): FlagDocumentationShape {
return Context.getOption(single.annotations, FlagDocumentation).pipe(
Option.getOrElse(() => ({})),
);
}

/** Only literal scalar and array defaults can be displayed without evaluating user code. */
function literalDefault(value: unknown): string | undefined {
if (typeof value === "string") return value;
if (typeof value === "boolean" || (typeof value === "number" && Number.isFinite(value))) {
return String(value);
}
if (Array.isArray(value)) {
const values: unknown[] = value;
if (
values.every(
(item) =>
typeof item === "string" ||
typeof item === "boolean" ||
(typeof item === "number" && Number.isFinite(item)),
)
) {
return JSON.stringify(values);
}
}
return undefined;
}

export function flagDefault(unwrapped: UnwrappedParam): string | undefined {
return (
flagDocumentation(unwrapped.single).defaultValue ??
Option.flatMap(unwrapped.defaultValue, (value) =>
Option.fromUndefinedOr(literalDefault(value)),
).pipe(Option.getOrUndefined)
);
}
11 changes: 9 additions & 2 deletions apps/cli/src/command-internal/global-flags.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { FlagDocumentation } from "./flag-documentation.ts";
import { Effect, Option } from "effect";
import { Flag, GlobalFlag } from "effect/cli";

Expand Down Expand Up @@ -32,14 +33,20 @@ export const OutputFlag = GlobalFlag.Setting("output")({
flag: Flag.Literals("output", GLOBAL_OUTPUT_FORMATS).pipe(
Flag.withAlias("o"),
Flag.withDescription("output format of status variables"),
Flag.annotate(FlagDocumentation, {
defaultValue: "pretty",
helpDefault: false, // Commands select their own format when --output is omitted.
choices: ["env", "pretty", "json", "toml", "yaml"],
}),
Flag.optional,
),
});

/** The TS-only `--output-format` global, accepted on any subcommand. */
export const OutputFormatFlag = GlobalFlag.Setting("output-format")({
flag: Flag.Literals("output-format", ["text", "json", "stream-json"]).pipe(
Flag.withDescription("Output format: text (default), json, or stream-json (NDJSON)"),
Flag.withDescription("Output format: text, json, or stream-json (NDJSON)"),
Flag.annotate(FlagDocumentation, { defaultValue: "text" }),
Flag.optional,
),
});
Expand Down Expand Up @@ -109,7 +116,7 @@ export const CreateTicketFlag = GlobalFlag.Setting("create-ticket")({

export const AgentFlag = GlobalFlag.Setting("agent")({
flag: Flag.Literals("agent", ["auto", "yes", "no"] as const).pipe(
Flag.withDescription("Override agent detection: yes, no, or auto (default auto)"),
Flag.withDescription("Override agent detection: yes, no, or auto"),
Flag.withDefault("auto" as const),
),
});
Expand Down
19 changes: 17 additions & 2 deletions apps/cli/src/command-internal/param-introspection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,14 @@ function isWrappedParam(param: Param.Any): param is Param.Any & WrappedParam {
return "param" in param;
}

interface FallbackParam extends WrappedParam {
readonly fallback?: Param.Fallback;
}

function isFallbackParam(param: Param.Any & WrappedParam): param is Param.Any & FallbackParam {
return param._tag === "Transform" && "fallback" in param;
}

interface VariadicParam {
readonly min: Option.Option<number>;
}
Expand All @@ -34,6 +42,7 @@ export interface UnwrappedParam {
* this instead of `isVariadic` when determining whether a flag is required.
*/
readonly variadicMin: number;
readonly defaultValue: Option.Option<unknown>;
}

/**
Expand All @@ -46,10 +55,16 @@ export function unwrapParam(param: Param.Any): UnwrappedParam | undefined {
let isOptional = false;
let isVariadic = false;
let variadicMin = 0;
let defaultValue: Option.Option<unknown> = Option.none();

while (!Param.isSingle(current)) {
if (!isWrappedParam(current)) return undefined;
if (current._tag === "Optional") isOptional = true;
if (!isVariadic && current._tag === "Optional") isOptional = true;
if (!isVariadic && isFallbackParam(current) && current.fallback) {
isOptional = true;
defaultValue =
current.fallback._tag === "Default" ? Option.some(current.fallback.value) : Option.none();
}
if (current._tag === "Variadic") {
isVariadic = true;
if (isVariadicParam(current)) {
Expand All @@ -59,7 +74,7 @@ export function unwrapParam(param: Param.Any): UnwrappedParam | undefined {
current = current.param;
Comment thread
mdonnalley marked this conversation as resolved.
Resolved
}

return { single: current, isOptional, isVariadic, variadicMin };
return { single: current, isOptional, isVariadic, variadicMin, defaultValue };
}

/**
Expand Down
4 changes: 4 additions & 0 deletions apps/cli/src/commands/db/advisors/advisors.command.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { FlagDocumentation } from "../../../command-internal/flag-documentation.ts";
import { Command, Flag } from "effect/cli";
import type * as CliCommand from "effect/cli/Command";
import { withPermissions } from "../../../command-internal/command-permissions/command-permissions.annotation.ts";
Expand All @@ -22,14 +23,17 @@ const config = {
...targetFlags({ subject: "database", dbUrl: true }),
type: Flag.Literals("type", ["all", "security", "performance"] as const).pipe(
Flag.withDescription("Type of advisors to check: all, security, performance."),
Flag.annotate(FlagDocumentation, { defaultValue: "all" }),
Flag.optional,
),
level: Flag.Literals("level", ["info", "warn", "error"] as const).pipe(
Flag.withDescription("Minimum issue level to display: info, warn, error."),
Flag.annotate(FlagDocumentation, { defaultValue: "warn" }),
Flag.optional,
),
failOn: Flag.Literals("fail-on", ["none", "info", "warn", "error"] as const).pipe(
Flag.withDescription("Issue level to exit with non-zero status: none, info, warn, error."),
Flag.annotate(FlagDocumentation, { defaultValue: "none" }),
Flag.optional,
),
} as const;
Expand Down
3 changes: 3 additions & 0 deletions apps/cli/src/commands/db/lint/lint.command.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { FlagDocumentation } from "../../../command-internal/flag-documentation.ts";
import { Command, Flag } from "effect/cli";
import type * as CliCommand from "effect/cli/Command";
import { withPermissions } from "../../../command-internal/command-permissions/command-permissions.annotation.ts";
Expand Down Expand Up @@ -29,10 +30,12 @@ const config = {
),
level: Flag.Literals("level", ["warning", "error"] as const).pipe(
Flag.withDescription("Error level to emit."),
Flag.annotate(FlagDocumentation, { defaultValue: "warning" }),
Flag.optional,
),
failOn: Flag.Literals("fail-on", ["none", "warning", "error"] as const).pipe(
Flag.withDescription("Error level to exit with non-zero status."),
Flag.annotate(FlagDocumentation, { defaultValue: "none" }),
Flag.optional,
),
} as const;
Expand Down
2 changes: 2 additions & 0 deletions apps/cli/src/commands/db/pull/pull.command.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { FlagDocumentation } from "../../../command-internal/flag-documentation.ts";
import { Effect, Layer, Option } from "effect";
import { Argument, Command, Flag } from "effect/cli";
import type * as CliCommand from "effect/cli/Command";
Expand Down Expand Up @@ -44,6 +45,7 @@ const config = {
}),
diffEngine: Flag.Literals("diff-engine", ["migra", "pg-delta"] as const).pipe(
Flag.withDescription("Diff engine to use for migration-style db pull."),
Flag.annotate(FlagDocumentation, { defaultValue: "pg-delta" }),
Flag.optional,
),
strictCoverage: Flag.Boolean("strict-coverage").pipe(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { FlagDocumentation } from "../../../../../command-internal/flag-documentation.ts";
import { Effect } from "effect";
import { Command, Flag } from "effect/cli";
import type * as CliCommand from "effect/cli/Command";
Expand Down Expand Up @@ -30,6 +31,7 @@ const config = {
file: Flag.String("file").pipe(
Flag.withAlias("f"),
Flag.withDescription("Saves schema diff to a new migration file."),
Flag.annotate(FlagDocumentation, { defaultValue: "declarative_sync" }),
Flag.optional,
),
name: Flag.String("name").pipe(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ const config = {
(tail) => `Expected --tail to be 0 or more, got ${tail}`,
),
Flag.withDescription(
"Number of retained lines to print across the selected services (default 200); 0 prints none.",
"Number of retained lines to print across the selected services; 0 prints none.",
),
Flag.withDefault(200),
),
Expand Down
2 changes: 2 additions & 0 deletions apps/cli/src/commands/functions/deploy/deploy.command.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { FlagDocumentation } from "../../../command-internal/flag-documentation.ts";
import { Argument, Command, Flag } from "effect/cli";
import type * as CliCommand from "effect/cli/Command";
import { withPermissions } from "../../../command-internal/command-permissions/command-permissions.annotation.ts";
Expand Down Expand Up @@ -43,6 +44,7 @@ const config = {
(jobs) => `Expected --jobs to be non-negative, got ${jobs}`,
),
Flag.withDescription("Maximum number of parallel jobs."),
Flag.annotate(FlagDocumentation, { defaultValue: "1" }),
Flag.optional,
),
useDocker: Flag.Boolean("use-docker").pipe(
Expand Down
18 changes: 13 additions & 5 deletions apps/cli/src/commands/gen/bearer-jwt/bearer-jwt.command.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { FlagDocumentation } from "../../../command-internal/flag-documentation.ts";
import { Layer } from "effect";
import { Command, Flag } from "effect/cli";
import type * as CliCommand from "effect/cli/Command";
Expand All @@ -19,11 +20,17 @@ const config = {
// `--role` stays optional at parse time so a missing value is enforced in
// the handler instead, after telemetry is wired up — see
// `GenBearerJwtRoleRequiredError`.
role: Flag.String("role").pipe(Flag.withDescription("Postgres role to use."), Flag.optional),
// The displayed default is cosmetically "anonymous" but the real default
// stays "" — an omitted `--sub` never puts a `sub` claim in the token at
// all.
sub: Flag.String("sub").pipe(Flag.withDescription("User ID to impersonate."), Flag.optional),
role: Flag.String("role").pipe(
Flag.withDescription("Postgres role to use."),
Flag.annotate(FlagDocumentation, { required: true }),
Flag.optional,
),
// The website retains its compatibility label; an omitted --sub adds no claim.
sub: Flag.String("sub").pipe(
Flag.withDescription("User ID to impersonate."),
Flag.annotate(FlagDocumentation, { defaultValue: "anonymous", helpDefault: false }),
Flag.optional,
),
exp: Flag.String("exp").pipe(
Flag.withDescription("Expiry timestamp for this token."),
Flag.mapTryCatch(
Expand All @@ -35,6 +42,7 @@ const config = {
validFor: Flag.String("valid-for").pipe(
Flag.withDescription("Validity duration for this token."),
Flag.withDefault("30m"),
Flag.annotate(FlagDocumentation, { defaultValue: "30m0s" }),
Flag.mapTryCatch(
(value) => parseBearerJwtValidFor(value),
(err) => (err instanceof Error ? err.message : String(err)),
Expand Down
4 changes: 2 additions & 2 deletions apps/cli/src/commands/gen/types/types.command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ const config = {
...targetFlags({ subject: "database", dbUrl: true }),
projectId: deprecatedProjectIdFlag,
lang: Flag.Literals("lang", GEN_TYPES_LANGUAGES).pipe(
Flag.withDescription("Output language of the generated types. (default typescript)"),
Flag.withDescription("Output language of the generated types."),
Flag.withDefault("typescript"),
),
schema: Flag.String("schema").pipe(
Expand All @@ -64,7 +64,7 @@ const config = {
Flag.withDefault(false),
),
queryTimeout: Flag.String("query-timeout").pipe(
Flag.withDescription("Maximum timeout allowed for the database query. (default 15s)"),
Flag.withDescription("Maximum timeout allowed for the database query."),
Flag.withDefault("15s"),
),
} as const;
Expand Down
29 changes: 13 additions & 16 deletions apps/cli/src/commands/gen/types/types.languages.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { languages, type OptionSpec, type OptionValue, type OptionValues } from "@supabase/typegen";
import { Option } from "effect";
import { FlagDocumentation } from "../../../command-internal/flag-documentation.ts";
import { Flag } from "effect/cli";

/** A user-facing registry option as one CLI flag, merged across the languages that declare it. */
Expand Down Expand Up @@ -54,8 +55,7 @@ export const mergeUserOptions = (
};

const languageFlag = (spec: LanguageFlagSpec): Flag.Flag<GenTypesLanguageFlagValue> => {
const help =
spec.default === undefined ? spec.help : `${spec.help} (default ${String(spec.default)})`;
const { help } = spec;
switch (spec.kind) {
case "boolean":
return Flag.Boolean(spec.name).pipe(Flag.withDescription(help), Flag.optional);
Expand All @@ -81,7 +81,17 @@ export const languageFlagsFor = (
`@supabase/typegen declares language flags that collide with CLI flags: ${collisions.join(", ")}`,
);
}
return Object.fromEntries(specs.map((spec) => [spec.name, languageFlag(spec)]));
return Object.fromEntries(
specs.map((spec) => [
spec.name,
languageFlag(spec).pipe(
Flag.annotate(
FlagDocumentation,
spec.default === undefined ? {} : { defaultValue: String(spec.default) },
),
),
]),
);
};

/** The values the user set, keyed by option name; unset flags are absent. */
Expand All @@ -100,16 +110,6 @@ export const optionValuesFor = (
return values;
};

/** Documented defaults keyed the way `DOCS_DEFAULT_OVERRIDES` expects. */
export const flagDefaultsFor = (
specs: ReadonlyArray<LanguageFlagSpec>,
): Readonly<Record<string, string>> =>
Object.fromEntries(
specs.flatMap((spec) =>
spec.default === undefined ? [] : [[`supabase-gen-types ${spec.name}`, String(spec.default)]],
),
);

export const GEN_TYPES_LANGUAGES: ReadonlyArray<string> = languages.map(
(language) => language.name,
);
Expand All @@ -131,8 +131,5 @@ export const GEN_TYPES_LANGUAGE_VALUE_FLAG_NAMES: ReadonlyArray<string> =
export const genTypesLanguageFlags = (reservedFlagNames: Iterable<string>) =>
languageFlagsFor(GEN_TYPES_LANGUAGE_OPTIONS, reservedFlagNames);

export const genTypesLanguageFlagDefaults = (): Readonly<Record<string, string>> =>
flagDefaultsFor(GEN_TYPES_LANGUAGE_OPTIONS);

export const languageOptionValues = (flags: Readonly<Record<string, unknown>>): OptionValues =>
optionValuesFor(GEN_TYPES_LANGUAGE_OPTIONS, flags);
20 changes: 9 additions & 11 deletions apps/cli/src/commands/gen/types/types.languages.unit.test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
import { describe, expect, it } from "@effect/vitest";
import type { OptionSpec } from "@supabase/typegen";
import { Option } from "effect";
import {
flagDefaultsFor,
languageFlagsFor,
mergeUserOptions,
optionValuesFor,
} from "./types.languages.ts";
import { languageFlagsFor, mergeUserOptions, optionValuesFor } from "./types.languages.ts";
import { docsFlagDoc } from "../../../docs/docs-spec.ts";

const level = (choices: ReadonlyArray<string>, fallback: string): OptionSpec => ({
name: "level",
Expand Down Expand Up @@ -78,11 +74,13 @@ describe("optionValuesFor", () => {
});
});

describe("flagDefaultsFor", () => {
describe("language flag documentation", () => {
it("documents a default only when it is unambiguous", () => {
expect(flagDefaultsFor(mergeUserOptions([level(["a"], "a")]))).toEqual({
"supabase-gen-types level": "a",
});
expect(flagDefaultsFor(mergeUserOptions([level(["a"], "a"), level(["b"], "b")]))).toEqual({});
const documented = (specs: ReadonlyArray<OptionSpec>) =>
Object.values(languageFlagsFor(mergeUserOptions(specs), [])).map(
(flag) => docsFlagDoc(["supabase", "gen", "types"], flag)?.default_value,
);
expect(documented([level(["a"], "a")])).toEqual(["a"]);
expect(documented([level(["a"], "a"), level(["b"], "b")])).toEqual([""]);
});
});
5 changes: 5 additions & 0 deletions apps/cli/src/commands/login/login.command.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { FlagDocumentation } from "../../command-internal/flag-documentation.ts";
import { Command, Flag } from "effect/cli";
import type * as CliCommand from "effect/cli/Command";

Expand All @@ -17,6 +18,10 @@ const config = {
),
name: Flag.String("name").pipe(
Flag.withDescription("Name that will be used to store token in your settings."),
Flag.annotate(FlagDocumentation, {
defaultValue: "built-in token name generator",
helpDefault: "generated when omitted",
}),
Flag.optional,
),
noBrowser: Flag.Boolean("no-browser").pipe(
Expand Down
Loading
Loading