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
2 changes: 1 addition & 1 deletion apps/cli/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ rather than deleting it; `db remote commit` is the reference:
`withJsonErrorHandling`. Provide only `commandRuntimeLayer` and `telemetryStateLayer`.
- Keep the old flag and argument config so existing invocations reach the removal error, not a
parse error, and register the command with `Command.unlisted`.
- Delete the handler, its tests, and its docs pages, and drop it from `DOCS_EXCLUDED`.
- Delete the handler, its tests, and its docs pages, and remove its `withDeprecated` annotation.
- `SIDE_EFFECTS.md` documents exit 1, the removal message and suggestion, and the post-run
`telemetry.json` read and write under `SUPABASE_HOME`.
- Test every tombstone through the real parser with and without its old flags, asserting the
Expand Down
5 changes: 4 additions & 1 deletion apps/cli/scripts/docs-spec-validation.unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { expect, it } from "@effect/vitest";
import { Effect } from "effect";
import { Command } from "effect/cli";
import { stringify } from "yaml";
import { withDeprecated } from "../src/command-internal/command-access-policy.ts";
import { validateDocsSpec } from "./docs-spec-validation.ts";

const root = Command.make("supabase").pipe(
Expand Down Expand Up @@ -57,7 +58,9 @@ const inspectRoot = Command.make("supabase").pipe(
Command.withSubcommands([
Command.make("inspect").pipe(
Command.withSubcommands([
Command.make("db").pipe(Command.withSubcommands([Command.make("cache-hit")])),
Command.make("db").pipe(
Command.withSubcommands([Command.make("cache-hit").pipe(withDeprecated)]),
),
]),
),
]),
Expand Down
5 changes: 3 additions & 2 deletions apps/cli/src/cli/complete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { GlobalFlag } from "effect/cli";
import type { Command, Param, Primitive } from "effect/cli";
import type { PlatformError } from "effect/PlatformError";
import process from "node:process";
import { deprecatedShortDescription } from "../command-internal/command-access-policy.ts";
import { outputFormatsForCommand } from "../command-internal/output-formats.ts";
import { unwrapParam } from "../command-internal/param-introspection.ts";
import { REMOTE_FLAG_NAME } from "../command-internal/target/remote-vocabulary.ts";
Expand Down Expand Up @@ -842,7 +843,7 @@ function helpArgumentCandidates(
const visibleSubcommands = flattenSubcommands(resolved).filter((sub) => !sub.unlisted);
const candidates: Array<CompletionCandidate> = visibleSubcommands.map((sub) => ({
name: sub.name,
description: sub.shortDescription ?? sub.description,
description: deprecatedShortDescription(sub) ?? sub.shortDescription ?? sub.description,
}));
// `help` is included when nothing after it resolved, since it's one of root's own subcommands.
if (matchedPath.length === 0) {
Expand Down Expand Up @@ -973,7 +974,7 @@ export function classifyCompletion(input: ClassifyCompletionInput): CompletionRe
directive = CompletionDirective.NoFileComp;
const subcommandCandidates: Array<CompletionCandidate> = visibleSubcommands.map((sub) => ({
name: sub.name,
description: sub.shortDescription ?? sub.description,
description: deprecatedShortDescription(sub) ?? sub.shortDescription ?? sub.description,
}));
// `help` isn't a real command node in this tree; synthesize it as a candidate, but
// only at root, not recursively on descendants.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import { BunServices } from "@effect/platform-bun";
import { describe, expect, it } from "@effect/vitest";
import { Console, Effect, Layer, Schema } from "effect";
import { CliOutput, Command, Flag } from "effect/cli";

import { fakeConsole } from "../../tests/helpers/mocks.ts";
import { respondToComplete } from "../cli/complete.ts";
import { jsonCliOutputFormatter } from "../shared/output/json-formatter.ts";
import { docsCommandTree } from "../docs/docs-spec.ts";
import { textCliOutputFormatter } from "../shared/output/text-formatter.ts";
import { defineExperimentalAccess, withDeprecated } from "./command-access-policy.ts";

describe("command access policy", () => {
it.effect(
"retains check arguments, typed failure and success for optional experimental access",
() =>
Effect.gen(function* () {
const access = defineExperimentalAccess({
experimental: "optional",
check: (enabled: boolean) =>
enabled ? Effect.succeed("allowed") : Effect.fail("disabled"),
});
let executed = false;
const command = Command.make("preview", { enabled: Flag.Boolean("enabled") }).pipe(
Command.withHandler((flags) =>
Effect.gen(function* () {
const result = yield* access.check(flags.enabled);
executed = result === "allowed";
}),
),
access.annotate,
);
const layer = Layer.mergeAll(BunServices.layer, CliOutput.layer(textCliOutputFormatter()));
expect(
yield* Command.runWith(command, { version: "0" })(["--enabled=false"]).pipe(
Effect.flip,
Effect.provide(layer),
),
).toBe("disabled");
expect(executed).toBe(false);
yield* Command.runWith(command, { version: "0" })(["--enabled"]).pipe(
Effect.provide(layer),
);
expect(executed).toBe(true);
}),
);

it.effect("keeps a deprecated command runnable and visible in help but not the docs tree", () =>
Effect.gen(function* () {
let executed = false;
const leaf = Command.make("old").pipe(
Command.withDescription("Use the replacement instead."),
withDeprecated,
Command.withShortDescription("Show old data"),
Command.withHandler(() =>
Effect.sync(() => {
executed = true;
}),
),
);
const other = Command.make("other").pipe(
Command.withShortDescription("Other data"),
withDeprecated,
);
const fallback = Command.make("fallback").pipe(
withDeprecated,
Command.withDescription("First line\nMore detail"),
);
const root = Command.make("supabase").pipe(Command.withSubcommands([leaf, other, fallback]));
const context = { rootCommand: root, args: ["--help"] };
const { console, calls } = fakeConsole();
const formatterLayer = (formatter: CliOutput.Formatter) =>
Layer.mergeAll(
BunServices.layer,
CliOutput.layer(formatter),
Layer.succeed(Console.Console, console),
);
const layer = formatterLayer(textCliOutputFormatter(context));
yield* Command.runWith(root, { version: "0" })(["--help"]).pipe(Effect.provide(layer));
expect(calls.join("\n")).toContain("Show old data (deprecated)");
expect(calls.join("\n")).toContain("Other data (deprecated)");
const rows = [
{
name: "old",
description: "Use the replacement instead.",
shortDescription: "Show old data (deprecated)",
},
{ name: "other", description: "", shortDescription: "Other data (deprecated)" },
{
name: "fallback",
description: "First line\nMore detail",
shortDescription: "First line (deprecated)",
},
];
calls.length = 0;
yield* Command.runWith(root, { version: "0" })(["--help"]).pipe(
Effect.provide(formatterLayer(jsonCliOutputFormatter(context))),
);
const json = yield* Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown))(
calls.join("\n").replace(/^log:/, ""),
);
expect(json).toHaveProperty("doc.subcommands.0.commands", rows);
for (const prefix of [["__complete"], ["__complete", "help"]]) {
const result = respondToComplete(root, [...prefix, ""]);
for (const row of rows)
expect(result?.candidates).toContainEqual({
name: row.name,
description: row.shortDescription,
});
}
expect(executed).toBe(false);
expect(docsCommandTree(root).has("supabase-old")).toBe(false);
calls.length = 0;
yield* Command.runWith(root, { version: "0" })(["old", "--help"]).pipe(Effect.provide(layer));
expect(calls.join("\n")).toContain("Use the replacement instead.");
expect(calls.join("\n")).not.toContain("(deprecated)");
calls.length = 0;
yield* Command.runWith(root, { version: "0" })(["old"]).pipe(Effect.provide(layer));
expect(executed).toBe(true);
expect(calls).toEqual([]);
}),
);
});
36 changes: 36 additions & 0 deletions apps/cli/src/command-internal/command-access-policy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { Context, Option } from "effect";
import { Command } from "effect/cli";

/** Documentation requirement paired with the check that enforces experimental access. */
export class ExperimentalAccessAnnotation extends Context.Service<
ExperimentalAccessAnnotation,
"required" | "optional"
>()("supabase/ExperimentalAccessAnnotation") {}

export const defineExperimentalAccess = <Check>(policy: {
readonly experimental: "required" | "optional";
readonly check: Check;
}) => ({
check: policy.check,
annotate: Command.annotate(ExperimentalAccessAnnotation, policy.experimental),
});

export const readExperimentalAccess = (command: Command.Command.Any) =>
Context.getOption(command.annotations, ExperimentalAccessAnnotation);

/** Marks commands that remain in help but are excluded from the published reference. */
export class DeprecatedCommandAnnotation extends Context.Service<
DeprecatedCommandAnnotation,
true
>()("supabase/DeprecatedCommandAnnotation") {}

export const withDeprecated = Command.annotate(DeprecatedCommandAnnotation, true);

export const isDeprecated = (command: Command.Command.Any): boolean =>
Option.isSome(Context.getOption(command.annotations, DeprecatedCommandAnnotation));

export function deprecatedShortDescription(command: Command.Command.Any): string | undefined {
if (!isDeprecated(command)) return undefined;
const base = command.shortDescription ?? command.description?.split("\n")[0] ?? "";
return `${base} (deprecated)`;
}
13 changes: 10 additions & 3 deletions apps/cli/src/command-internal/experimental-gate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
ErrorActionabilityId,
} from "../shared/telemetry/error-actionability.ts";
import { resolveExperimental } from "./global-flags.ts";
import { defineExperimentalAccess } from "./command-access-policy.ts";

/**
* Gates access to experimental commands and their children. Must run before any
Expand All @@ -28,7 +29,13 @@ export class ExperimentalRequiredError extends Data.TaggedError("ExperimentalReq
}

/** Fails with {@link ExperimentalRequiredError} unless experimental is enabled. */
export const requireExperimental = Effect.gen(function* () {
if (yield* resolveExperimental) return;
return yield* new ExperimentalRequiredError();
export const requiredExperimentalAccess = defineExperimentalAccess({
experimental: "required",
check: Effect.gen(function* () {
if (yield* resolveExperimental) return;
return yield* new ExperimentalRequiredError();
}),
});

/** Flag-conditional experimental check, without command-level documentation metadata. */
export const requireExperimental = requiredExperimentalAccess.check;
120 changes: 120 additions & 0 deletions apps/cli/src/command-internal/experimental-pairing.unit.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import { expect, it } from "@effect/vitest";
import { Effect } from "effect";
import { fileURLToPath } from "node:url";
import * as ts from "typescript/unstable/ast";
import { API, type Checker, SymbolFlags } from "typescript/unstable/async";

function* nodes(root: ts.Node): Generator<ts.Node> {
yield root;
const children: ts.Node[] = [];
root.forEachChild((child) => {
children.push(child);
});
for (const child of children) yield* nodes(child);
}

const declaration = Effect.fnUntraced(function* (checker: Checker, ref: ts.Node) {
const symbol = yield* Effect.promise(() => checker.getSymbolAtLocation(ref));
if (!symbol) return undefined;
const target =
symbol.flags & SymbolFlags.Alias
? yield* Effect.promise(() => checker.getAliasedSymbol(symbol))
: symbol;
const handle = target.valueDeclaration;
return handle && (yield* Effect.promise(() => handle.resolve()));
});

const policy = Effect.fnUntraced(function* (checker: Checker, member: ts.PropertyAccessExpression) {
const decl = yield* declaration(checker, member.expression);
if (
decl &&
ts.isVariableDeclaration(decl) &&
decl.initializer &&
ts.isCallExpression(decl.initializer) &&
decl.initializer.expression.getText() === "defineExperimentalAccess"
) {
return `${decl.getSourceFile().fileName.split("/src/").pop()}:${decl.name.getText()}`;
}
return undefined;
});

function checksIn(
handler: ts.Node,
checker: Checker,
checks: Set<string>,
followHandler: boolean,
): Effect.Effect<void> {
return Effect.gen(function* () {
for (const node of nodes(handler)) {
if (ts.isYieldExpression(node) && node.asteriskToken && node.expression) {
const member = ts.isCallExpression(node.expression)
? node.expression.expression
: node.expression;
if (ts.isPropertyAccessExpression(member) && member.name.getText() === "check") {
const key = yield* policy(checker, member);
if (key) checks.add(key);
}
}
if (followHandler && ts.isCallExpression(node) && ts.isIdentifier(node.expression)) {
const decl = yield* declaration(checker, node.expression);
if (decl?.getSourceFile().fileName.endsWith(".handler.ts"))
yield* checksIn(decl, checker, checks, false);
}
}
});
}

it.effect(
"pairs each command's experimental annotations with checks in its own handler",
Effect.fn("ExperimentalAccess.inspectPairing")(function* () {
const config = fileURLToPath(new URL("../../tsconfig.json", import.meta.url));
const api = yield* Effect.acquireRelease(
Effect.sync(() => new API()),
(api) => Effect.promise(() => api.close()),
);
const snapshot = yield* Effect.promise(() => api.updateSnapshot({ openProjects: [config] }));
const project = snapshot.getProject(config)!;
const files = project.rootFiles.filter((file) => file.endsWith(".command.ts"));
expect(files.length).toBeGreaterThan(0);
const failures: string[] = [];
const recognizedPolicies = new Set<string>();
for (const file of files) {
const source = (yield* Effect.promise(() => project.program.getSourceFile(file)))!;
for (const pipe of nodes(source)) {
if (
!ts.isCallExpression(pipe) ||
!ts.isPropertyAccessExpression(pipe.expression) ||
pipe.expression.name.getText() !== "pipe"
)
continue;
const annotated = new Set<string>();
const checked = new Set<string>();
for (const arg of pipe.arguments) {
if (ts.isPropertyAccessExpression(arg) && arg.name.getText() === "annotate") {
const key = yield* policy(project.checker, arg);
if (key) annotated.add(key);
}
if (
ts.isCallExpression(arg) &&
arg.expression.getText() === "Command.withHandler" &&
arg.arguments[0]
) {
yield* checksIn(arg.arguments[0], project.checker, checked, true);
}
}
for (const key of new Set([...annotated, ...checked])) {
recognizedPolicies.add(key);
if (annotated.has(key) !== checked.has(key))
failures.push(
`${file}: missing ${annotated.has(key) ? "check" : "annotation"} for ${key}`,
);
}
}
}
expect(failures).toEqual([]);
expect(
recognizedPolicies.size,
"Recognized experimental policies in the command scan",
).toBeGreaterThan(0);
}),
);
26 changes: 15 additions & 11 deletions apps/cli/src/commands/db/schema/declarative/declarative.gate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { Effect } from "effect";
import { aqua, bold } from "../../../../command-internal/colors.ts";
import { configSetting } from "../../../../command-internal/config-advice.ts";
import { DeclarativeNotEnabledError } from "./declarative.errors.ts";
import { defineExperimentalAccess } from "../../../../command-internal/command-access-policy.ts";

/**
* Whether the declarative (pg-delta) code paths are enabled: the gate is open when either the
Expand All @@ -29,15 +30,18 @@ export function pgDeltaSuggestion(configPath: string, configFormat: ConfigFormat
* handler's own mutually-exclusive-flags check — a closed gate wins over a flag conflict, not
* the other way around.
*/
export const requirePgDelta = Effect.fnUntraced(function* (opts: {
readonly experimental: boolean;
readonly pgDeltaEnabled: boolean;
readonly configPath: string;
readonly configFormat?: ConfigFormat;
}) {
if (isPgDeltaEnabled(opts.experimental, opts.pgDeltaEnabled)) return;
return yield* new DeclarativeNotEnabledError({
message: "declarative commands require --experimental flag or pg-delta enabled in config",
suggestion: pgDeltaSuggestion(opts.configPath, opts.configFormat),
});
export const pgDeltaAccess = defineExperimentalAccess({
experimental: "optional",
check: Effect.fnUntraced(function* (opts: {
readonly experimental: boolean;
readonly pgDeltaEnabled: boolean;
readonly configPath: string;
readonly configFormat?: ConfigFormat;
}) {
if (isPgDeltaEnabled(opts.experimental, opts.pgDeltaEnabled)) return;
return yield* new DeclarativeNotEnabledError({
message: "declarative commands require --experimental flag or pg-delta enabled in config",
suggestion: pgDeltaSuggestion(opts.configPath, opts.configFormat),
});
}),
});
Loading
Loading