feat: unify onboarding + config schema
This commit is contained in:
84
src/wizard/clack-prompter.ts
Normal file
84
src/wizard/clack-prompter.ts
Normal file
@@ -0,0 +1,84 @@
|
||||
import {
|
||||
cancel,
|
||||
confirm,
|
||||
intro,
|
||||
isCancel,
|
||||
multiselect,
|
||||
note,
|
||||
type Option,
|
||||
outro,
|
||||
select,
|
||||
spinner,
|
||||
text,
|
||||
} from "@clack/prompts";
|
||||
|
||||
import type { WizardProgress, WizardPrompter } from "./prompts.js";
|
||||
import { WizardCancelledError } from "./prompts.js";
|
||||
|
||||
function guardCancel<T>(value: T | symbol): T {
|
||||
if (isCancel(value)) {
|
||||
cancel("Setup cancelled.");
|
||||
throw new WizardCancelledError();
|
||||
}
|
||||
return value as T;
|
||||
}
|
||||
|
||||
export function createClackPrompter(): WizardPrompter {
|
||||
return {
|
||||
intro: async (title) => {
|
||||
intro(title);
|
||||
},
|
||||
outro: async (message) => {
|
||||
outro(message);
|
||||
},
|
||||
note: async (message, title) => {
|
||||
note(message, title);
|
||||
},
|
||||
select: async (params) =>
|
||||
guardCancel(
|
||||
await select({
|
||||
message: params.message,
|
||||
options: params.options.map((opt) => {
|
||||
const base = { value: opt.value, label: opt.label };
|
||||
return opt.hint === undefined ? base : { ...base, hint: opt.hint };
|
||||
}) as Option<(typeof params.options)[number]["value"]>[],
|
||||
initialValue: params.initialValue,
|
||||
}),
|
||||
),
|
||||
multiselect: async (params) =>
|
||||
guardCancel(
|
||||
await multiselect({
|
||||
message: params.message,
|
||||
options: params.options.map((opt) => {
|
||||
const base = { value: opt.value, label: opt.label };
|
||||
return opt.hint === undefined ? base : { ...base, hint: opt.hint };
|
||||
}) as Option<(typeof params.options)[number]["value"]>[],
|
||||
initialValues: params.initialValues,
|
||||
}),
|
||||
),
|
||||
text: async (params) =>
|
||||
guardCancel(
|
||||
await text({
|
||||
message: params.message,
|
||||
initialValue: params.initialValue,
|
||||
placeholder: params.placeholder,
|
||||
validate: params.validate,
|
||||
}),
|
||||
),
|
||||
confirm: async (params) =>
|
||||
guardCancel(
|
||||
await confirm({
|
||||
message: params.message,
|
||||
initialValue: params.initialValue,
|
||||
}),
|
||||
),
|
||||
progress: (label: string): WizardProgress => {
|
||||
const spin = spinner();
|
||||
spin.start(label);
|
||||
return {
|
||||
update: (message) => spin.message(message),
|
||||
stop: (message) => spin.stop(message),
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
535
src/wizard/onboarding.ts
Normal file
535
src/wizard/onboarding.ts
Normal file
@@ -0,0 +1,535 @@
|
||||
import path from "node:path";
|
||||
|
||||
import { loginAnthropic, type OAuthCredentials } from "@mariozechner/pi-ai";
|
||||
import {
|
||||
isRemoteEnvironment,
|
||||
loginAntigravityVpsAware,
|
||||
} from "../commands/antigravity-oauth.js";
|
||||
import { healthCommand } from "../commands/health.js";
|
||||
import {
|
||||
applyMinimaxConfig,
|
||||
setAnthropicApiKey,
|
||||
writeOAuthCredentials,
|
||||
} from "../commands/onboard-auth.js";
|
||||
import {
|
||||
applyWizardMetadata,
|
||||
DEFAULT_WORKSPACE,
|
||||
ensureWorkspaceAndSessions,
|
||||
handleReset,
|
||||
openUrl,
|
||||
printWizardHeader,
|
||||
probeGatewayReachable,
|
||||
randomToken,
|
||||
resolveControlUiLinks,
|
||||
summarizeExistingConfig,
|
||||
} from "../commands/onboard-helpers.js";
|
||||
import { setupProviders } from "../commands/onboard-providers.js";
|
||||
import { promptRemoteGatewayConfig } from "../commands/onboard-remote.js";
|
||||
import { setupSkills } from "../commands/onboard-skills.js";
|
||||
import type {
|
||||
AuthChoice,
|
||||
GatewayAuthChoice,
|
||||
OnboardMode,
|
||||
OnboardOptions,
|
||||
ResetScope,
|
||||
} from "../commands/onboard-types.js";
|
||||
import type { ClawdisConfig } from "../config/config.js";
|
||||
import {
|
||||
CONFIG_PATH_CLAWDIS,
|
||||
readConfigFileSnapshot,
|
||||
resolveGatewayPort,
|
||||
writeConfigFile,
|
||||
} from "../config/config.js";
|
||||
import { GATEWAY_LAUNCH_AGENT_LABEL } from "../daemon/constants.js";
|
||||
import { resolveGatewayProgramArguments } from "../daemon/program-args.js";
|
||||
import { resolveGatewayService } from "../daemon/service.js";
|
||||
import type { RuntimeEnv } from "../runtime.js";
|
||||
import { defaultRuntime } from "../runtime.js";
|
||||
import { resolveUserPath, sleep } from "../utils.js";
|
||||
import type { WizardPrompter } from "./prompts.js";
|
||||
|
||||
export async function runOnboardingWizard(
|
||||
opts: OnboardOptions,
|
||||
runtime: RuntimeEnv = defaultRuntime,
|
||||
prompter: WizardPrompter,
|
||||
) {
|
||||
printWizardHeader(runtime);
|
||||
await prompter.intro("Clawdis onboarding");
|
||||
|
||||
const snapshot = await readConfigFileSnapshot();
|
||||
let baseConfig: ClawdisConfig = snapshot.valid ? snapshot.config : {};
|
||||
|
||||
if (snapshot.exists) {
|
||||
const title = snapshot.valid
|
||||
? "Existing config detected"
|
||||
: "Invalid config";
|
||||
await prompter.note(summarizeExistingConfig(baseConfig), title);
|
||||
if (!snapshot.valid && snapshot.issues.length > 0) {
|
||||
await prompter.note(
|
||||
snapshot.issues
|
||||
.map((iss) => `- ${iss.path}: ${iss.message}`)
|
||||
.join("\n"),
|
||||
"Config issues",
|
||||
);
|
||||
}
|
||||
|
||||
const action = (await prompter.select({
|
||||
message: "Config handling",
|
||||
options: [
|
||||
{ value: "keep", label: "Use existing values" },
|
||||
{ value: "modify", label: "Update values" },
|
||||
{ value: "reset", label: "Reset" },
|
||||
],
|
||||
})) as "keep" | "modify" | "reset";
|
||||
|
||||
if (action === "reset") {
|
||||
const workspaceDefault = baseConfig.agent?.workspace ?? DEFAULT_WORKSPACE;
|
||||
const resetScope = (await prompter.select({
|
||||
message: "Reset scope",
|
||||
options: [
|
||||
{ value: "config", label: "Config only" },
|
||||
{
|
||||
value: "config+creds+sessions",
|
||||
label: "Config + creds + sessions",
|
||||
},
|
||||
{
|
||||
value: "full",
|
||||
label: "Full reset (config + creds + sessions + workspace)",
|
||||
},
|
||||
],
|
||||
})) as ResetScope;
|
||||
await handleReset(resetScope, resolveUserPath(workspaceDefault), runtime);
|
||||
baseConfig = {};
|
||||
} else if (action === "keep" && !snapshot.valid) {
|
||||
baseConfig = {};
|
||||
}
|
||||
}
|
||||
|
||||
const localPort = resolveGatewayPort(baseConfig);
|
||||
const localUrl = `ws://127.0.0.1:${localPort}`;
|
||||
const localProbe = await probeGatewayReachable({
|
||||
url: localUrl,
|
||||
token: process.env.CLAWDIS_GATEWAY_TOKEN,
|
||||
password:
|
||||
baseConfig.gateway?.auth?.password ??
|
||||
process.env.CLAWDIS_GATEWAY_PASSWORD,
|
||||
});
|
||||
const remoteUrl = baseConfig.gateway?.remote?.url?.trim() ?? "";
|
||||
const remoteProbe = remoteUrl
|
||||
? await probeGatewayReachable({
|
||||
url: remoteUrl,
|
||||
token: baseConfig.gateway?.remote?.token,
|
||||
})
|
||||
: null;
|
||||
|
||||
const mode =
|
||||
opts.mode ??
|
||||
((await prompter.select({
|
||||
message: "Where will the Gateway run?",
|
||||
options: [
|
||||
{
|
||||
value: "local",
|
||||
label: "Local (this machine)",
|
||||
hint: localProbe.ok
|
||||
? `Gateway reachable (${localUrl})`
|
||||
: `No gateway detected (${localUrl})`,
|
||||
},
|
||||
{
|
||||
value: "remote",
|
||||
label: "Remote (info-only)",
|
||||
hint: !remoteUrl
|
||||
? "No remote URL configured yet"
|
||||
: remoteProbe?.ok
|
||||
? `Gateway reachable (${remoteUrl})`
|
||||
: `Configured but unreachable (${remoteUrl})`,
|
||||
},
|
||||
],
|
||||
})) as OnboardMode);
|
||||
|
||||
if (mode === "remote") {
|
||||
let nextConfig = await promptRemoteGatewayConfig(baseConfig, prompter);
|
||||
nextConfig = applyWizardMetadata(nextConfig, { command: "onboard", mode });
|
||||
await writeConfigFile(nextConfig);
|
||||
runtime.log(`Updated ${CONFIG_PATH_CLAWDIS}`);
|
||||
await prompter.outro("Remote gateway configured.");
|
||||
return;
|
||||
}
|
||||
|
||||
const workspaceInput =
|
||||
opts.workspace ??
|
||||
(await prompter.text({
|
||||
message: "Workspace directory",
|
||||
initialValue: baseConfig.agent?.workspace ?? DEFAULT_WORKSPACE,
|
||||
}));
|
||||
|
||||
const workspaceDir = resolveUserPath(
|
||||
workspaceInput.trim() || DEFAULT_WORKSPACE,
|
||||
);
|
||||
|
||||
let nextConfig: ClawdisConfig = {
|
||||
...baseConfig,
|
||||
agent: {
|
||||
...baseConfig.agent,
|
||||
workspace: workspaceDir,
|
||||
},
|
||||
gateway: {
|
||||
...baseConfig.gateway,
|
||||
mode: "local",
|
||||
},
|
||||
};
|
||||
|
||||
const authChoice = (await prompter.select({
|
||||
message: "Model/auth choice",
|
||||
options: [
|
||||
{ value: "oauth", label: "Anthropic OAuth (Claude Pro/Max)" },
|
||||
{
|
||||
value: "antigravity",
|
||||
label: "Google Antigravity (Claude Opus 4.5, Gemini 3, etc.)",
|
||||
},
|
||||
{ value: "apiKey", label: "Anthropic API key" },
|
||||
{ value: "minimax", label: "Minimax M2.1 (LM Studio)" },
|
||||
{ value: "skip", label: "Skip for now" },
|
||||
],
|
||||
})) as AuthChoice;
|
||||
|
||||
if (authChoice === "oauth") {
|
||||
await prompter.note(
|
||||
"Browser will open. Paste the code shown after login (code#state).",
|
||||
"Anthropic OAuth",
|
||||
);
|
||||
const spin = prompter.progress("Waiting for authorization…");
|
||||
let oauthCreds: OAuthCredentials | null = null;
|
||||
try {
|
||||
oauthCreds = await loginAnthropic(
|
||||
async (url) => {
|
||||
await openUrl(url);
|
||||
runtime.log(`Open: ${url}`);
|
||||
},
|
||||
async () => {
|
||||
const code = await prompter.text({
|
||||
message: "Paste authorization code (code#state)",
|
||||
validate: (value) => (value?.trim() ? undefined : "Required"),
|
||||
});
|
||||
return String(code);
|
||||
},
|
||||
);
|
||||
spin.stop("OAuth complete");
|
||||
if (oauthCreds) {
|
||||
await writeOAuthCredentials("anthropic", oauthCreds);
|
||||
}
|
||||
} catch (err) {
|
||||
spin.stop("OAuth failed");
|
||||
runtime.error(String(err));
|
||||
}
|
||||
} else if (authChoice === "antigravity") {
|
||||
const isRemote = isRemoteEnvironment();
|
||||
await prompter.note(
|
||||
isRemote
|
||||
? [
|
||||
"You are running in a remote/VPS environment.",
|
||||
"A URL will be shown for you to open in your LOCAL browser.",
|
||||
"After signing in, copy the redirect URL and paste it back here.",
|
||||
].join("\n")
|
||||
: [
|
||||
"Browser will open for Google authentication.",
|
||||
"Sign in with your Google account that has Antigravity access.",
|
||||
"The callback will be captured automatically on localhost:51121.",
|
||||
].join("\n"),
|
||||
"Google Antigravity OAuth",
|
||||
);
|
||||
const spin = prompter.progress("Starting OAuth flow…");
|
||||
let oauthCreds: OAuthCredentials | null = null;
|
||||
try {
|
||||
oauthCreds = await loginAntigravityVpsAware(
|
||||
async (url) => {
|
||||
if (isRemote) {
|
||||
spin.stop("OAuth URL ready");
|
||||
runtime.log(`\nOpen this URL in your LOCAL browser:\n\n${url}\n`);
|
||||
} else {
|
||||
spin.update("Complete sign-in in browser…");
|
||||
await openUrl(url);
|
||||
runtime.log(`Open: ${url}`);
|
||||
}
|
||||
},
|
||||
(msg) => spin.update(msg),
|
||||
);
|
||||
spin.stop("Antigravity OAuth complete");
|
||||
if (oauthCreds) {
|
||||
await writeOAuthCredentials("google-antigravity", oauthCreds);
|
||||
nextConfig = {
|
||||
...nextConfig,
|
||||
agent: {
|
||||
...nextConfig.agent,
|
||||
model: "google-antigravity/claude-opus-4-5-thinking",
|
||||
},
|
||||
};
|
||||
await prompter.note(
|
||||
"Default model set to google-antigravity/claude-opus-4-5-thinking",
|
||||
"Model configured",
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
spin.stop("Antigravity OAuth failed");
|
||||
runtime.error(String(err));
|
||||
}
|
||||
} else if (authChoice === "apiKey") {
|
||||
const key = await prompter.text({
|
||||
message: "Enter Anthropic API key",
|
||||
validate: (value) => (value?.trim() ? undefined : "Required"),
|
||||
});
|
||||
await setAnthropicApiKey(String(key).trim());
|
||||
} else if (authChoice === "minimax") {
|
||||
nextConfig = applyMinimaxConfig(nextConfig);
|
||||
}
|
||||
|
||||
const portRaw = await prompter.text({
|
||||
message: "Gateway port",
|
||||
initialValue: String(localPort),
|
||||
validate: (value) =>
|
||||
Number.isFinite(Number(value)) ? undefined : "Invalid port",
|
||||
});
|
||||
const port = Number.parseInt(String(portRaw), 10);
|
||||
|
||||
let bind = (await prompter.select({
|
||||
message: "Gateway bind",
|
||||
options: [
|
||||
{ value: "loopback", label: "Loopback (127.0.0.1)" },
|
||||
{ value: "lan", label: "LAN" },
|
||||
{ value: "tailnet", label: "Tailnet" },
|
||||
{ value: "auto", label: "Auto" },
|
||||
],
|
||||
})) as "loopback" | "lan" | "tailnet" | "auto";
|
||||
|
||||
let authMode = (await prompter.select({
|
||||
message: "Gateway auth",
|
||||
options: [
|
||||
{
|
||||
value: "off",
|
||||
label: "Off (loopback only)",
|
||||
hint: "Recommended for single-machine setups",
|
||||
},
|
||||
{
|
||||
value: "token",
|
||||
label: "Token",
|
||||
hint: "Use for multi-machine access or non-loopback binds",
|
||||
},
|
||||
{ value: "password", label: "Password" },
|
||||
],
|
||||
})) as GatewayAuthChoice;
|
||||
|
||||
const tailscaleMode = (await prompter.select({
|
||||
message: "Tailscale exposure",
|
||||
options: [
|
||||
{ value: "off", label: "Off", hint: "No Tailscale exposure" },
|
||||
{
|
||||
value: "serve",
|
||||
label: "Serve",
|
||||
hint: "Private HTTPS for your tailnet (devices on Tailscale)",
|
||||
},
|
||||
{
|
||||
value: "funnel",
|
||||
label: "Funnel",
|
||||
hint: "Public HTTPS via Tailscale Funnel (internet)",
|
||||
},
|
||||
],
|
||||
})) as "off" | "serve" | "funnel";
|
||||
|
||||
let tailscaleResetOnExit = false;
|
||||
if (tailscaleMode !== "off") {
|
||||
tailscaleResetOnExit = Boolean(
|
||||
await prompter.confirm({
|
||||
message: "Reset Tailscale serve/funnel on exit?",
|
||||
initialValue: false,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
if (tailscaleMode !== "off" && bind !== "loopback") {
|
||||
await prompter.note(
|
||||
"Tailscale requires bind=loopback. Adjusting bind to loopback.",
|
||||
"Note",
|
||||
);
|
||||
bind = "loopback";
|
||||
}
|
||||
|
||||
if (authMode === "off" && bind !== "loopback") {
|
||||
await prompter.note(
|
||||
"Non-loopback bind requires auth. Switching to token auth.",
|
||||
"Note",
|
||||
);
|
||||
authMode = "token";
|
||||
}
|
||||
|
||||
if (tailscaleMode === "funnel" && authMode !== "password") {
|
||||
await prompter.note("Tailscale funnel requires password auth.", "Note");
|
||||
authMode = "password";
|
||||
}
|
||||
|
||||
let gatewayToken: string | undefined;
|
||||
if (authMode === "token") {
|
||||
const tokenInput = await prompter.text({
|
||||
message: "Gateway token (blank to generate)",
|
||||
placeholder: "Needed for multi-machine or non-loopback access",
|
||||
initialValue: randomToken(),
|
||||
});
|
||||
gatewayToken = String(tokenInput).trim() || randomToken();
|
||||
}
|
||||
|
||||
if (authMode === "password") {
|
||||
const password = await prompter.text({
|
||||
message: "Gateway password",
|
||||
validate: (value) => (value?.trim() ? undefined : "Required"),
|
||||
});
|
||||
nextConfig = {
|
||||
...nextConfig,
|
||||
gateway: {
|
||||
...nextConfig.gateway,
|
||||
auth: {
|
||||
...nextConfig.gateway?.auth,
|
||||
mode: "password",
|
||||
password: String(password).trim(),
|
||||
},
|
||||
},
|
||||
};
|
||||
} else if (authMode === "token") {
|
||||
nextConfig = {
|
||||
...nextConfig,
|
||||
gateway: {
|
||||
...nextConfig.gateway,
|
||||
auth: {
|
||||
...nextConfig.gateway?.auth,
|
||||
mode: "token",
|
||||
token: gatewayToken,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
nextConfig = {
|
||||
...nextConfig,
|
||||
gateway: {
|
||||
...nextConfig.gateway,
|
||||
port,
|
||||
bind,
|
||||
tailscale: {
|
||||
...nextConfig.gateway?.tailscale,
|
||||
mode: tailscaleMode,
|
||||
resetOnExit: tailscaleResetOnExit,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
nextConfig = await setupProviders(nextConfig, runtime, prompter, {
|
||||
allowSignalInstall: true,
|
||||
});
|
||||
|
||||
await writeConfigFile(nextConfig);
|
||||
runtime.log(`Updated ${CONFIG_PATH_CLAWDIS}`);
|
||||
await ensureWorkspaceAndSessions(workspaceDir, runtime);
|
||||
|
||||
nextConfig = await setupSkills(nextConfig, workspaceDir, runtime, prompter);
|
||||
nextConfig = applyWizardMetadata(nextConfig, { command: "onboard", mode });
|
||||
await writeConfigFile(nextConfig);
|
||||
|
||||
const installDaemon = await prompter.confirm({
|
||||
message: "Install Gateway daemon (recommended)",
|
||||
initialValue: true,
|
||||
});
|
||||
|
||||
if (installDaemon) {
|
||||
const service = resolveGatewayService();
|
||||
const loaded = await service.isLoaded({ env: process.env });
|
||||
if (loaded) {
|
||||
const action = (await prompter.select({
|
||||
message: "Gateway service already installed",
|
||||
options: [
|
||||
{ value: "restart", label: "Restart" },
|
||||
{ value: "reinstall", label: "Reinstall" },
|
||||
{ value: "skip", label: "Skip" },
|
||||
],
|
||||
})) as "restart" | "reinstall" | "skip";
|
||||
if (action === "restart") {
|
||||
await service.restart({ stdout: process.stdout });
|
||||
} else if (action === "reinstall") {
|
||||
await service.uninstall({ env: process.env, stdout: process.stdout });
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
!loaded ||
|
||||
(loaded && (await service.isLoaded({ env: process.env })) === false)
|
||||
) {
|
||||
const devMode =
|
||||
process.argv[1]?.includes(`${path.sep}src${path.sep}`) &&
|
||||
process.argv[1]?.endsWith(".ts");
|
||||
const { programArguments, workingDirectory } =
|
||||
await resolveGatewayProgramArguments({ port, dev: devMode });
|
||||
const environment: Record<string, string | undefined> = {
|
||||
PATH: process.env.PATH,
|
||||
CLAWDIS_GATEWAY_TOKEN: gatewayToken,
|
||||
CLAWDIS_LAUNCHD_LABEL:
|
||||
process.platform === "darwin"
|
||||
? GATEWAY_LAUNCH_AGENT_LABEL
|
||||
: undefined,
|
||||
};
|
||||
await service.install({
|
||||
env: process.env,
|
||||
stdout: process.stdout,
|
||||
programArguments,
|
||||
workingDirectory,
|
||||
environment,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
await sleep(1500);
|
||||
try {
|
||||
await healthCommand({ json: false, timeoutMs: 10_000 }, runtime);
|
||||
} catch (err) {
|
||||
runtime.error(`Health check failed: ${String(err)}`);
|
||||
}
|
||||
|
||||
await prompter.note(
|
||||
[
|
||||
"Add nodes for extra features:",
|
||||
"- macOS app (system + notifications)",
|
||||
"- iOS app (camera/canvas)",
|
||||
"- Android app (camera/canvas)",
|
||||
].join("\n"),
|
||||
"Optional apps",
|
||||
);
|
||||
|
||||
await prompter.note(
|
||||
(() => {
|
||||
const links = resolveControlUiLinks({ bind, port });
|
||||
const tokenParam =
|
||||
authMode === "token" && gatewayToken
|
||||
? `?token=${encodeURIComponent(gatewayToken)}`
|
||||
: "";
|
||||
const authedUrl = `${links.httpUrl}${tokenParam}`;
|
||||
return [
|
||||
`Web UI: ${links.httpUrl}`,
|
||||
tokenParam ? `Web UI (with token): ${authedUrl}` : undefined,
|
||||
`Gateway WS: ${links.wsUrl}`,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n");
|
||||
})(),
|
||||
"Control UI",
|
||||
);
|
||||
|
||||
const wantsOpen = await prompter.confirm({
|
||||
message: "Open Control UI now?",
|
||||
initialValue: true,
|
||||
});
|
||||
if (wantsOpen) {
|
||||
const links = resolveControlUiLinks({ bind, port });
|
||||
const tokenParam =
|
||||
authMode === "token" && gatewayToken
|
||||
? `?token=${encodeURIComponent(gatewayToken)}`
|
||||
: "";
|
||||
await openUrl(`${links.httpUrl}${tokenParam}`);
|
||||
}
|
||||
|
||||
await prompter.outro("Onboarding complete.");
|
||||
}
|
||||
52
src/wizard/prompts.ts
Normal file
52
src/wizard/prompts.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
export type WizardSelectOption<T = string> = {
|
||||
value: T;
|
||||
label: string;
|
||||
hint?: string;
|
||||
};
|
||||
|
||||
export type WizardSelectParams<T = string> = {
|
||||
message: string;
|
||||
options: Array<WizardSelectOption<T>>;
|
||||
initialValue?: T;
|
||||
};
|
||||
|
||||
export type WizardMultiSelectParams<T = string> = {
|
||||
message: string;
|
||||
options: Array<WizardSelectOption<T>>;
|
||||
initialValues?: T[];
|
||||
};
|
||||
|
||||
export type WizardTextParams = {
|
||||
message: string;
|
||||
initialValue?: string;
|
||||
placeholder?: string;
|
||||
validate?: (value: string) => string | undefined;
|
||||
};
|
||||
|
||||
export type WizardConfirmParams = {
|
||||
message: string;
|
||||
initialValue?: boolean;
|
||||
};
|
||||
|
||||
export type WizardProgress = {
|
||||
update: (message: string) => void;
|
||||
stop: (message?: string) => void;
|
||||
};
|
||||
|
||||
export type WizardPrompter = {
|
||||
intro: (title: string) => Promise<void>;
|
||||
outro: (message: string) => Promise<void>;
|
||||
note: (message: string, title?: string) => Promise<void>;
|
||||
select: <T>(params: WizardSelectParams<T>) => Promise<T>;
|
||||
multiselect: <T>(params: WizardMultiSelectParams<T>) => Promise<T[]>;
|
||||
text: (params: WizardTextParams) => Promise<string>;
|
||||
confirm: (params: WizardConfirmParams) => Promise<boolean>;
|
||||
progress: (label: string) => WizardProgress;
|
||||
};
|
||||
|
||||
export class WizardCancelledError extends Error {
|
||||
constructor(message = "wizard cancelled") {
|
||||
super(message);
|
||||
this.name = "WizardCancelledError";
|
||||
}
|
||||
}
|
||||
69
src/wizard/session.test.ts
Normal file
69
src/wizard/session.test.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { WizardSession } from "./session.js";
|
||||
|
||||
function noteRunner() {
|
||||
return new WizardSession(async (prompter) => {
|
||||
await prompter.note("Welcome");
|
||||
const name = await prompter.text({ message: "Name" });
|
||||
await prompter.note(`Hello ${name}`);
|
||||
});
|
||||
}
|
||||
|
||||
describe("WizardSession", () => {
|
||||
test("steps progress in order", async () => {
|
||||
const session = noteRunner();
|
||||
|
||||
const first = await session.next();
|
||||
expect(first.done).toBe(false);
|
||||
expect(first.step?.type).toBe("note");
|
||||
|
||||
const secondPeek = await session.next();
|
||||
expect(secondPeek.step?.id).toBe(first.step?.id);
|
||||
|
||||
if (!first.step) throw new Error("expected first step");
|
||||
await session.answer(first.step.id, null);
|
||||
|
||||
const second = await session.next();
|
||||
expect(second.done).toBe(false);
|
||||
expect(second.step?.type).toBe("text");
|
||||
|
||||
if (!second.step) throw new Error("expected second step");
|
||||
await session.answer(second.step.id, "Peter");
|
||||
|
||||
const third = await session.next();
|
||||
expect(third.step?.type).toBe("note");
|
||||
|
||||
if (!third.step) throw new Error("expected third step");
|
||||
await session.answer(third.step.id, null);
|
||||
|
||||
const done = await session.next();
|
||||
expect(done.done).toBe(true);
|
||||
expect(done.status).toBe("done");
|
||||
});
|
||||
|
||||
test("invalid answers throw", async () => {
|
||||
const session = noteRunner();
|
||||
const first = await session.next();
|
||||
await expect(session.answer("bad-id", null)).rejects.toThrow(
|
||||
/wizard: no pending step/i,
|
||||
);
|
||||
if (!first.step) throw new Error("expected first step");
|
||||
await session.answer(first.step.id, null);
|
||||
});
|
||||
|
||||
test("cancel marks session and unblocks", async () => {
|
||||
const session = new WizardSession(async (prompter) => {
|
||||
await prompter.text({ message: "Name" });
|
||||
});
|
||||
|
||||
const step = await session.next();
|
||||
expect(step.step?.type).toBe("text");
|
||||
|
||||
session.cancel();
|
||||
|
||||
const done = await session.next();
|
||||
expect(done.done).toBe(true);
|
||||
expect(done.status).toBe("cancelled");
|
||||
});
|
||||
});
|
||||
268
src/wizard/session.ts
Normal file
268
src/wizard/session.ts
Normal file
@@ -0,0 +1,268 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import {
|
||||
WizardCancelledError,
|
||||
type WizardProgress,
|
||||
type WizardPrompter,
|
||||
} from "./prompts.js";
|
||||
|
||||
export type WizardStepOption = {
|
||||
value: unknown;
|
||||
label: string;
|
||||
hint?: string;
|
||||
};
|
||||
|
||||
export type WizardStep = {
|
||||
id: string;
|
||||
type:
|
||||
| "note"
|
||||
| "select"
|
||||
| "text"
|
||||
| "confirm"
|
||||
| "multiselect"
|
||||
| "progress"
|
||||
| "action";
|
||||
title?: string;
|
||||
message?: string;
|
||||
options?: WizardStepOption[];
|
||||
initialValue?: unknown;
|
||||
placeholder?: string;
|
||||
sensitive?: boolean;
|
||||
executor?: "gateway" | "client";
|
||||
};
|
||||
|
||||
export type WizardSessionStatus = "running" | "done" | "cancelled" | "error";
|
||||
|
||||
export type WizardNextResult = {
|
||||
done: boolean;
|
||||
step?: WizardStep;
|
||||
status: WizardSessionStatus;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
type Deferred<T> = {
|
||||
promise: Promise<T>;
|
||||
resolve: (value: T) => void;
|
||||
reject: (err: unknown) => void;
|
||||
};
|
||||
|
||||
function createDeferred<T>(): Deferred<T> {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (err: unknown) => void;
|
||||
const promise = new Promise<T>((res, rej) => {
|
||||
resolve = res;
|
||||
reject = rej;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
class WizardSessionPrompter implements WizardPrompter {
|
||||
constructor(private session: WizardSession) {}
|
||||
|
||||
async intro(title: string): Promise<void> {
|
||||
await this.prompt({
|
||||
type: "note",
|
||||
title,
|
||||
message: "",
|
||||
executor: "client",
|
||||
});
|
||||
}
|
||||
|
||||
async outro(message: string): Promise<void> {
|
||||
await this.prompt({
|
||||
type: "note",
|
||||
title: "Done",
|
||||
message,
|
||||
executor: "client",
|
||||
});
|
||||
}
|
||||
|
||||
async note(message: string, title?: string): Promise<void> {
|
||||
await this.prompt({ type: "note", title, message, executor: "client" });
|
||||
}
|
||||
|
||||
async select<T>(params: {
|
||||
message: string;
|
||||
options: Array<{ value: T; label: string; hint?: string }>;
|
||||
initialValue?: T;
|
||||
}): Promise<T> {
|
||||
const res = await this.prompt({
|
||||
type: "select",
|
||||
message: params.message,
|
||||
options: params.options.map((opt) => ({
|
||||
value: opt.value,
|
||||
label: opt.label,
|
||||
hint: opt.hint,
|
||||
})),
|
||||
initialValue: params.initialValue,
|
||||
executor: "client",
|
||||
});
|
||||
return res as T;
|
||||
}
|
||||
|
||||
async multiselect<T>(params: {
|
||||
message: string;
|
||||
options: Array<{ value: T; label: string; hint?: string }>;
|
||||
initialValues?: T[];
|
||||
}): Promise<T[]> {
|
||||
const res = await this.prompt({
|
||||
type: "multiselect",
|
||||
message: params.message,
|
||||
options: params.options.map((opt) => ({
|
||||
value: opt.value,
|
||||
label: opt.label,
|
||||
hint: opt.hint,
|
||||
})),
|
||||
initialValue: params.initialValues,
|
||||
executor: "client",
|
||||
});
|
||||
return (Array.isArray(res) ? res : []) as T[];
|
||||
}
|
||||
|
||||
async text(params: {
|
||||
message: string;
|
||||
initialValue?: string;
|
||||
placeholder?: string;
|
||||
validate?: (value: string) => string | undefined;
|
||||
}): Promise<string> {
|
||||
const res = await this.prompt({
|
||||
type: "text",
|
||||
message: params.message,
|
||||
initialValue: params.initialValue,
|
||||
placeholder: params.placeholder,
|
||||
executor: "client",
|
||||
});
|
||||
const value = String(res ?? "");
|
||||
const error = params.validate?.(value);
|
||||
if (error) {
|
||||
throw new Error(error);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
async confirm(params: {
|
||||
message: string;
|
||||
initialValue?: boolean;
|
||||
}): Promise<boolean> {
|
||||
const res = await this.prompt({
|
||||
type: "confirm",
|
||||
message: params.message,
|
||||
initialValue: params.initialValue,
|
||||
executor: "client",
|
||||
});
|
||||
return Boolean(res);
|
||||
}
|
||||
|
||||
progress(_label: string): WizardProgress {
|
||||
return {
|
||||
update: (_message) => {},
|
||||
stop: (_message) => {},
|
||||
};
|
||||
}
|
||||
|
||||
private async prompt(step: Omit<WizardStep, "id">): Promise<unknown> {
|
||||
return await this.session.awaitAnswer({
|
||||
...step,
|
||||
id: randomUUID(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export class WizardSession {
|
||||
private currentStep: WizardStep | null = null;
|
||||
private stepDeferred: Deferred<WizardStep | null> | null = null;
|
||||
private answerDeferred = new Map<string, Deferred<unknown>>();
|
||||
private status: WizardSessionStatus = "running";
|
||||
private error: string | undefined;
|
||||
|
||||
constructor(private runner: (prompter: WizardPrompter) => Promise<void>) {
|
||||
const prompter = new WizardSessionPrompter(this);
|
||||
void this.run(prompter);
|
||||
}
|
||||
|
||||
async next(): Promise<WizardNextResult> {
|
||||
if (this.currentStep) {
|
||||
return { done: false, step: this.currentStep, status: this.status };
|
||||
}
|
||||
if (this.status !== "running") {
|
||||
return { done: true, status: this.status, error: this.error };
|
||||
}
|
||||
if (!this.stepDeferred) {
|
||||
this.stepDeferred = createDeferred();
|
||||
}
|
||||
const step = await this.stepDeferred.promise;
|
||||
if (step) {
|
||||
return { done: false, step, status: this.status };
|
||||
}
|
||||
return { done: true, status: this.status, error: this.error };
|
||||
}
|
||||
|
||||
async answer(stepId: string, value: unknown): Promise<void> {
|
||||
const deferred = this.answerDeferred.get(stepId);
|
||||
if (!deferred) {
|
||||
throw new Error("wizard: no pending step");
|
||||
}
|
||||
this.answerDeferred.delete(stepId);
|
||||
this.currentStep = null;
|
||||
deferred.resolve(value);
|
||||
}
|
||||
|
||||
cancel() {
|
||||
if (this.status !== "running") return;
|
||||
this.status = "cancelled";
|
||||
this.error = "cancelled";
|
||||
this.currentStep = null;
|
||||
for (const [, deferred] of this.answerDeferred) {
|
||||
deferred.reject(new WizardCancelledError());
|
||||
}
|
||||
this.answerDeferred.clear();
|
||||
this.resolveStep(null);
|
||||
}
|
||||
|
||||
pushStep(step: WizardStep) {
|
||||
this.currentStep = step;
|
||||
this.resolveStep(step);
|
||||
}
|
||||
|
||||
private async run(prompter: WizardPrompter) {
|
||||
try {
|
||||
await this.runner(prompter);
|
||||
this.status = "done";
|
||||
} catch (err) {
|
||||
if (err instanceof WizardCancelledError) {
|
||||
this.status = "cancelled";
|
||||
this.error = err.message;
|
||||
} else {
|
||||
this.status = "error";
|
||||
this.error = String(err);
|
||||
}
|
||||
} finally {
|
||||
this.resolveStep(null);
|
||||
}
|
||||
}
|
||||
|
||||
async awaitAnswer(step: WizardStep): Promise<unknown> {
|
||||
if (this.status !== "running") {
|
||||
throw new Error("wizard: session not running");
|
||||
}
|
||||
this.pushStep(step);
|
||||
const deferred = createDeferred<unknown>();
|
||||
this.answerDeferred.set(step.id, deferred);
|
||||
return await deferred.promise;
|
||||
}
|
||||
|
||||
private resolveStep(step: WizardStep | null) {
|
||||
if (!this.stepDeferred) return;
|
||||
const deferred = this.stepDeferred;
|
||||
this.stepDeferred = null;
|
||||
deferred.resolve(step);
|
||||
}
|
||||
|
||||
getStatus(): WizardSessionStatus {
|
||||
return this.status;
|
||||
}
|
||||
|
||||
getError(): string | undefined {
|
||||
return this.error;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user