import * as Cause from "effect/Cause";
import * as CliError from "effect/cli/CliError";
import * as Console from "effect/Console";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Runtime from "effect/Runtime";
import * as Schema from "effect/Schema";
import { isUserFacing, UserFacingError } from "../../UserFacingError.ts";
import { colorsEnabled, terminalStyle, unicodeEnabled } from "../../Util/Terminal.ts";
import { glyphsFor, theme } from "../../Util/Theme.ts";
const isTerminalCancelled = Schema.is(
Schema.Struct({ _tag: Schema.Literals(["TerminalCancelled"]) }),
);
const isAuthErrorLike = Schema.is(
Schema.Struct({
_tag: Schema.Literals(["AuthError"]),
cause: Schema.optional(Schema.Unknown),
}),
);
export const isPromptCancellation = (error: unknown): boolean => {
for (let current = error, depth = 0; current != null && depth < 16; depth++) {
if (isTerminalCancelled(current)) return true;
if (!isAuthErrorLike(current)) return false;
current = current.cause;
}
return false;
};
export const EXIT_CANCELLED = 130;
export const setExitCode = (code: number) =>
Effect.sync(() => {
process.exitCode = code;
});
export const exitDeclined = setExitCode(1);
let interruptMessagesSuppressed = false;
export const suppressInterruptMessages = Effect.sync(() => {
interruptMessagesSuppressed = true;
});
const SHUTDOWN_FEEDBACK_DELAY_MS = 500;
/**
* Keep quick shutdowns quiet, but acknowledge cleanup that takes long enough
* to be noticeable. The Effect runtime continues to own signal handling and
* teardown; this listener only writes delayed feedback.
*/
export const installShutdownFeedback = Effect.sync(() => {
let scheduled = false;
const onSignal = () => {
if (scheduled || interruptMessagesSuppressed) return;
scheduled = true;
const timer = setTimeout(() => {
process.stderr.write(`\n${terminalStyle({ stream: process.stderr }).dim("Shutting down")}\n`);
}, SHUTDOWN_FEEDBACK_DELAY_MS);
timer.unref();
};
process.on("SIGINT", onSignal);
process.on("SIGTERM", onSignal);
});
export const handleCancellation = (self: Effect.Effect) =>
self.pipe(
Effect.catchCause((cause) => {
const cancelled = cause.reasons.some((reason) => {
if (Cause.isFailReason(reason)) return isPromptCancellation(reason.error);
if (Cause.isDieReason(reason)) return isPromptCancellation(reason.defect);
return false;
});
return cancelled
? Console.log(`\n${terminalStyle().dim("Cancelled.")}`).pipe(
Effect.andThen(setExitCode(EXIT_CANCELLED)),
)
: (Effect.failCause(cause) as Effect.Effect);
}),
Effect.onInterrupt(() =>
interruptMessagesSuppressed
? Effect.void
: Console.log(`\n${terminalStyle().dim("Exited.")}`),
),
);
class ReportedCliError {
readonly [Runtime.errorReported] = false;
constructor(readonly cause: unknown) {}
}
// `ConfigError` is effect's own class and cannot carry the `UserFacingError`
// marker. Everything else is matched by the marker alone — new user-facing
// errors opt in by assigning the symbol, not by growing this list.
const isUnmarkedUserFacingError = Schema.is(
Schema.Struct({
_tag: Schema.Literals(["ConfigError"]),
message: Schema.String,
}),
);
const isUserFacingError = (error: unknown): error is { readonly message: string } =>
isUserFacing(error) || isUnmarkedUserFacingError(error);
export class UserInputError extends Data.TaggedError("UserInputError")<{
readonly message: string;
}> {
readonly [UserFacingError] = true;
}
export const handleUserErrors = (self: Effect.Effect) =>
self.pipe(
Effect.catchCause((cause) => {
for (const reason of cause.reasons) {
const error = Cause.isFailReason(reason)
? reason.error
: Cause.isDieReason(reason)
? reason.defect
: undefined;
if (isUserFacingError(error)) {
const glyphs = glyphsFor(unicodeEnabled());
return Console.error(
`${colorsEnabled(process.stderr) ? terminalStyle({ stream: process.stderr }).hex(theme.color.danger)(`${glyphs.error} error:`) : "error:"} ${error.message}`,
).pipe(Effect.flatMap(() => Effect.fail(new ReportedCliError(cause)))) as Effect.Effect<
never,
E | ReportedCliError,
never
>;
}
}
return Effect.failCause(cause) as Effect.Effect;
}),
);
export const handleCliErrors = (self: Effect.Effect) =>
self.pipe(handleCancellation, handleUserErrors);
export const failWithHelp = (commandPath: ReadonlyArray) =>
setExitCode(1).pipe(
Effect.andThen(
Effect.fail(CliError.ShowHelp.make({ commandPath: [...commandPath], errors: [] })),
),
);