repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/ui/errors.ts

Raw
export type UiErrorCode =
	| "server_bind_failed"
	| "no_lan_address"
	| "auth_failed"
	| "runtime_not_active"
	| "runtime_already_active"
	| "session_seed_failed"
	| "open_failed"
	| "qr_failed";

export type UiError = Error & {
	code: UiErrorCode;
	action: string;
	retryable: boolean;
	cause?: unknown;
};

export function uiError(
	code: UiErrorCode,
	message: string,
	options: { action: string; retryable?: boolean; cause?: unknown },
): UiError {
	const error = new Error(message) as UiError;
	error.name = "UiError";
	error.code = code;
	error.action = options.action;
	error.retryable = options.retryable ?? false;
	error.cause = options.cause;
	return error;
}

export function humanError(error: UiError): string {
	return [
		`${error.code}: ${error.message}`,
		`Action: ${error.action}`,
		`Retryable: ${error.retryable ? "yes" : "no"}`,
	].join("\n");
}

export function errorMessage(error: unknown): string {
	return error instanceof Error ? error.message : String(error);
}

export function redactToken(value: string): string {
	return value.replace(/([?&]token=)[^&#\s]+/g, "$1<redacted>");
}