@clifn/core 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +383 -0
- package/dist/client.d.ts +46 -0
- package/dist/client.js +198 -0
- package/dist/config-loader.d.ts +18 -0
- package/dist/config-loader.js +125 -0
- package/dist/config.d.ts +13 -0
- package/dist/config.js +57 -0
- package/dist/credentials.d.ts +19 -0
- package/dist/credentials.js +79 -0
- package/dist/diagnostics.d.ts +19 -0
- package/dist/diagnostics.js +152 -0
- package/dist/env.d.ts +20 -0
- package/dist/env.js +74 -0
- package/dist/exec.d.ts +29 -0
- package/dist/exec.js +143 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +13 -0
- package/dist/output.d.ts +37 -0
- package/dist/output.js +217 -0
- package/dist/prompt.d.ts +18 -0
- package/dist/prompt.js +83 -0
- package/dist/runner.d.ts +36 -0
- package/dist/runner.js +94 -0
- package/dist/scaffold.d.ts +26 -0
- package/dist/scaffold.js +94 -0
- package/dist/stdio.d.ts +7 -0
- package/dist/stdio.js +33 -0
- package/dist/ui.d.ts +10 -0
- package/dist/ui.js +25 -0
- package/package.json +120 -0
package/dist/exec.js
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
const DEFAULT_TIMEOUT_MS = 30_000;
|
|
3
|
+
const DEFAULT_MAX_BUFFER_BYTES = 1_048_576;
|
|
4
|
+
const DEFAULT_TIMEOUT_GRACE_MS = 250;
|
|
5
|
+
export class ExecTimeoutError extends Error {
|
|
6
|
+
code;
|
|
7
|
+
result;
|
|
8
|
+
constructor(message, result) {
|
|
9
|
+
super(message);
|
|
10
|
+
this.name = "ExecTimeoutError";
|
|
11
|
+
this.code = "CLIFN_EXEC_TIMEOUT";
|
|
12
|
+
this.result = result;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
function formatCommand(file, args) {
|
|
16
|
+
const parts = [file, ...args];
|
|
17
|
+
return parts
|
|
18
|
+
.map((part) => {
|
|
19
|
+
if (/^[A-Za-z0-9_./:-]+$/.test(part)) {
|
|
20
|
+
return part;
|
|
21
|
+
}
|
|
22
|
+
return JSON.stringify(part);
|
|
23
|
+
})
|
|
24
|
+
.join(" ");
|
|
25
|
+
}
|
|
26
|
+
function appendChunk(current, chunk, maxBufferBytes) {
|
|
27
|
+
const next = current + chunk;
|
|
28
|
+
const nextBytes = Buffer.byteLength(next);
|
|
29
|
+
if (nextBytes <= maxBufferBytes) {
|
|
30
|
+
return next;
|
|
31
|
+
}
|
|
32
|
+
let allowedBytes = Math.max(maxBufferBytes - Buffer.byteLength(current), 0);
|
|
33
|
+
const buffer = Buffer.from(chunk);
|
|
34
|
+
while (allowedBytes > 0 && allowedBytes < buffer.length && (buffer[allowedBytes] & 0b1100_0000) === 0b1000_0000) {
|
|
35
|
+
allowedBytes -= 1;
|
|
36
|
+
}
|
|
37
|
+
return current + buffer.subarray(0, allowedBytes).toString("utf8");
|
|
38
|
+
}
|
|
39
|
+
export function createExec() {
|
|
40
|
+
return {
|
|
41
|
+
async command(file, args = [], options = {}) {
|
|
42
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
43
|
+
const maxBufferBytes = options.maxBufferBytes ?? DEFAULT_MAX_BUFFER_BYTES;
|
|
44
|
+
const command = formatCommand(file, args);
|
|
45
|
+
const startedAt = Date.now();
|
|
46
|
+
return await new Promise((resolve, reject) => {
|
|
47
|
+
const child = spawn(file, [...args], {
|
|
48
|
+
cwd: options.cwd,
|
|
49
|
+
env: options.env,
|
|
50
|
+
stdio: "pipe",
|
|
51
|
+
});
|
|
52
|
+
let stdout = "";
|
|
53
|
+
let stderr = "";
|
|
54
|
+
let timedOut = false;
|
|
55
|
+
let settled = false;
|
|
56
|
+
let timeoutId = null;
|
|
57
|
+
let killId = null;
|
|
58
|
+
const finalize = (exitCode, signal) => {
|
|
59
|
+
if (settled) {
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
settled = true;
|
|
63
|
+
if (timeoutId) {
|
|
64
|
+
clearTimeout(timeoutId);
|
|
65
|
+
}
|
|
66
|
+
if (killId) {
|
|
67
|
+
clearTimeout(killId);
|
|
68
|
+
}
|
|
69
|
+
const result = {
|
|
70
|
+
command,
|
|
71
|
+
exitCode,
|
|
72
|
+
signal,
|
|
73
|
+
stdout,
|
|
74
|
+
stderr,
|
|
75
|
+
timedOut,
|
|
76
|
+
durationMs: Date.now() - startedAt,
|
|
77
|
+
};
|
|
78
|
+
if (timedOut) {
|
|
79
|
+
reject(new ExecTimeoutError(`Command timed out after ${timeoutMs} ms.`, result));
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
resolve(result);
|
|
83
|
+
};
|
|
84
|
+
if (timeoutMs > 0) {
|
|
85
|
+
timeoutId = setTimeout(() => {
|
|
86
|
+
if (settled) {
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
timedOut = true;
|
|
90
|
+
child.kill("SIGTERM");
|
|
91
|
+
killId = setTimeout(() => {
|
|
92
|
+
if (!settled) {
|
|
93
|
+
child.kill("SIGKILL");
|
|
94
|
+
}
|
|
95
|
+
}, DEFAULT_TIMEOUT_GRACE_MS);
|
|
96
|
+
}, timeoutMs);
|
|
97
|
+
}
|
|
98
|
+
child.stdout?.setEncoding("utf8");
|
|
99
|
+
child.stderr?.setEncoding("utf8");
|
|
100
|
+
child.stdout?.on("data", (chunk) => {
|
|
101
|
+
stdout = appendChunk(stdout, chunk, maxBufferBytes);
|
|
102
|
+
if (options.stdout) {
|
|
103
|
+
options.stdout?.(chunk);
|
|
104
|
+
}
|
|
105
|
+
else if (options.streamOutput) {
|
|
106
|
+
process.stdout.write(chunk);
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
child.stderr?.on("data", (chunk) => {
|
|
110
|
+
stderr = appendChunk(stderr, chunk, maxBufferBytes);
|
|
111
|
+
if (options.stderr) {
|
|
112
|
+
options.stderr?.(chunk);
|
|
113
|
+
}
|
|
114
|
+
else if (options.streamOutput) {
|
|
115
|
+
process.stderr.write(chunk);
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
child.on("error", (error) => {
|
|
119
|
+
if (timeoutId) {
|
|
120
|
+
clearTimeout(timeoutId);
|
|
121
|
+
}
|
|
122
|
+
if (killId) {
|
|
123
|
+
clearTimeout(killId);
|
|
124
|
+
}
|
|
125
|
+
if (settled) {
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
settled = true;
|
|
129
|
+
reject(error);
|
|
130
|
+
});
|
|
131
|
+
child.on("close", (exitCode, signal) => {
|
|
132
|
+
finalize(exitCode, signal);
|
|
133
|
+
});
|
|
134
|
+
if (options.stdin !== undefined) {
|
|
135
|
+
child.stdin?.end(options.stdin);
|
|
136
|
+
}
|
|
137
|
+
else {
|
|
138
|
+
child.stdin?.end();
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
},
|
|
142
|
+
};
|
|
143
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export { createOutput, type OutputLevel, type OutputMessage, type OutputMode, type OutputOptions, type OutputService, type Spinner, type OutputTable, } from "./output.js";
|
|
2
|
+
export { runAction, type RunnerActionResult, type RunnerContext, type RunnerDiagnosticsListener, type RunnerDiagnosticsSink, type RunnerOptions, } from "./runner.js";
|
|
3
|
+
export { ConfigLoaderError, defineConfig, loadConfig, type ConfigLoaderOptions, type ConfigLoaderErrorCode, type LoadedConfig, } from "./config-loader.js";
|
|
4
|
+
export { readBooleanEnv, readIntEnv, readRequiredStringEnv, readStringEnv, type BooleanEnvOptions, type EnvErrorCode, type IntEnvOptions, type StringEnvOptions, } from "./env.js";
|
|
5
|
+
export { createDiagnostic, formatDiagnosticsJson, formatDiagnosticsText, redactDiagnostics, redactValue, sortDiagnostics, type DiagnosticDetails, type Diagnostic, type DiagnosticReport, type DiagnosticSeverity, } from "./diagnostics.js";
|
|
6
|
+
export { createExec, ExecTimeoutError, type ExecErrorCode, type ExecOptions, type ExecResult, type ExecService, } from "./exec.js";
|
|
7
|
+
export { createScaffold, ScaffoldError, type FileExistsBehavior, type ScaffoldErrorCode, type ScaffoldOperation, type ScaffoldResult, type ScaffoldService, } from "./scaffold.js";
|
|
8
|
+
export { createCredentialStore, MissingProfileError, type CredentialProfile, type CredentialStore, } from "./credentials.js";
|
|
9
|
+
export { createProjectConfig, InvalidConfigError, type ProjectConfigStore, } from "./config.js";
|
|
10
|
+
export { createApiClient, HttpFailureError, HttpRequestError, type ApiClient, type ApiClientConfig, type ApiRequestOptions, type ApiResponse, } from "./client.js";
|
|
11
|
+
export { ui } from "./ui.js";
|
|
12
|
+
export { readJsonStdin, writeJsonStdout, InvalidJsonStdinError } from "./stdio.js";
|
|
13
|
+
export { createPrompt, prompt, PromptInputError, type PromptApi } from "./prompt.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export { createOutput, } from "./output.js";
|
|
2
|
+
export { runAction, } from "./runner.js";
|
|
3
|
+
export { ConfigLoaderError, defineConfig, loadConfig, } from "./config-loader.js";
|
|
4
|
+
export { readBooleanEnv, readIntEnv, readRequiredStringEnv, readStringEnv, } from "./env.js";
|
|
5
|
+
export { createDiagnostic, formatDiagnosticsJson, formatDiagnosticsText, redactDiagnostics, redactValue, sortDiagnostics, } from "./diagnostics.js";
|
|
6
|
+
export { createExec, ExecTimeoutError, } from "./exec.js";
|
|
7
|
+
export { createScaffold, ScaffoldError, } from "./scaffold.js";
|
|
8
|
+
export { createCredentialStore, MissingProfileError, } from "./credentials.js";
|
|
9
|
+
export { createProjectConfig, InvalidConfigError, } from "./config.js";
|
|
10
|
+
export { createApiClient, HttpFailureError, HttpRequestError, } from "./client.js";
|
|
11
|
+
export { ui } from "./ui.js";
|
|
12
|
+
export { readJsonStdin, writeJsonStdout, InvalidJsonStdinError } from "./stdio.js";
|
|
13
|
+
export { createPrompt, prompt, PromptInputError } from "./prompt.js";
|
package/dist/output.d.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
export type OutputMode = "text" | "json";
|
|
2
|
+
export type OutputLevel = "debug" | "info" | "success" | "warn" | "error";
|
|
3
|
+
export interface OutputMessage {
|
|
4
|
+
level: OutputLevel;
|
|
5
|
+
message: string;
|
|
6
|
+
details?: unknown;
|
|
7
|
+
}
|
|
8
|
+
export interface OutputTable {
|
|
9
|
+
columns: readonly string[];
|
|
10
|
+
rows: ReadonlyArray<Record<string, string | number | boolean | null | undefined>>;
|
|
11
|
+
}
|
|
12
|
+
export interface OutputOptions {
|
|
13
|
+
quiet?: boolean;
|
|
14
|
+
verbose?: boolean;
|
|
15
|
+
color?: boolean;
|
|
16
|
+
mode?: OutputMode;
|
|
17
|
+
stdout?: (text: string) => void;
|
|
18
|
+
stderr?: (text: string) => void;
|
|
19
|
+
}
|
|
20
|
+
export interface Spinner {
|
|
21
|
+
start(): void;
|
|
22
|
+
stop(): void;
|
|
23
|
+
succeed(message?: string): void;
|
|
24
|
+
fail(message?: string): void;
|
|
25
|
+
}
|
|
26
|
+
export interface OutputService {
|
|
27
|
+
readonly mode: OutputMode;
|
|
28
|
+
debug(message: string, details?: unknown): void;
|
|
29
|
+
info(message: string, details?: unknown): void;
|
|
30
|
+
success(message: string, details?: unknown): void;
|
|
31
|
+
warn(message: string, details?: unknown): void;
|
|
32
|
+
error(message: string, details?: unknown): void;
|
|
33
|
+
json(value: unknown): void;
|
|
34
|
+
table(input: OutputTable): void;
|
|
35
|
+
spinner(message: string): Spinner;
|
|
36
|
+
}
|
|
37
|
+
export declare function createOutput(options?: OutputOptions): OutputService;
|
package/dist/output.js
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
const COLOR = {
|
|
2
|
+
blue: "\u001b[34m",
|
|
3
|
+
green: "\u001b[32m",
|
|
4
|
+
red: "\u001b[31m",
|
|
5
|
+
yellow: "\u001b[33m",
|
|
6
|
+
reset: "\u001b[0m",
|
|
7
|
+
};
|
|
8
|
+
const LEVEL_PREFIX = {
|
|
9
|
+
debug: "[d]",
|
|
10
|
+
info: "[i]",
|
|
11
|
+
success: "[ok]",
|
|
12
|
+
warn: "[!]",
|
|
13
|
+
error: "[x]",
|
|
14
|
+
};
|
|
15
|
+
const LEVEL_COLOR = {
|
|
16
|
+
debug: null,
|
|
17
|
+
info: "blue",
|
|
18
|
+
success: "green",
|
|
19
|
+
warn: "yellow",
|
|
20
|
+
error: "red",
|
|
21
|
+
};
|
|
22
|
+
function normalizeJsonValue(value, seen = new WeakSet()) {
|
|
23
|
+
if (typeof value === "bigint") {
|
|
24
|
+
return value.toString();
|
|
25
|
+
}
|
|
26
|
+
if (Array.isArray(value)) {
|
|
27
|
+
if (seen.has(value)) {
|
|
28
|
+
return "[Circular]";
|
|
29
|
+
}
|
|
30
|
+
seen.add(value);
|
|
31
|
+
try {
|
|
32
|
+
return value.map((item) => normalizeJsonValue(item, seen));
|
|
33
|
+
}
|
|
34
|
+
finally {
|
|
35
|
+
seen.delete(value);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
if (value && typeof value === "object") {
|
|
39
|
+
if (seen.has(value)) {
|
|
40
|
+
return "[Circular]";
|
|
41
|
+
}
|
|
42
|
+
seen.add(value);
|
|
43
|
+
try {
|
|
44
|
+
if (typeof value.toJSON === "function") {
|
|
45
|
+
return normalizeJsonValue(value.toJSON(), seen);
|
|
46
|
+
}
|
|
47
|
+
return Object.fromEntries(Object.entries(value).map(([key, nested]) => [
|
|
48
|
+
key,
|
|
49
|
+
normalizeJsonValue(nested, seen),
|
|
50
|
+
]));
|
|
51
|
+
}
|
|
52
|
+
finally {
|
|
53
|
+
seen.delete(value);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return value;
|
|
57
|
+
}
|
|
58
|
+
function serializeJson(value) {
|
|
59
|
+
try {
|
|
60
|
+
const serialized = JSON.stringify(normalizeJsonValue(value));
|
|
61
|
+
return serialized ?? "null";
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
return JSON.stringify({
|
|
65
|
+
error: "Unable to serialize value",
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
function stringifyJson(value) {
|
|
70
|
+
return `${serializeJson(value)}\n`;
|
|
71
|
+
}
|
|
72
|
+
function colorize(enabled, level, message) {
|
|
73
|
+
const color = LEVEL_COLOR[level];
|
|
74
|
+
if (!enabled || color === null) {
|
|
75
|
+
return message;
|
|
76
|
+
}
|
|
77
|
+
return `${COLOR[color]}${message}${COLOR.reset}`;
|
|
78
|
+
}
|
|
79
|
+
function formatTextMessage(enabledColor, level, message, details) {
|
|
80
|
+
const suffix = details === undefined ? "" : ` ${serializeJson(details)}`;
|
|
81
|
+
return `${colorize(enabledColor, level, `${LEVEL_PREFIX[level]} ${message}`)}${suffix}\n`;
|
|
82
|
+
}
|
|
83
|
+
function shouldSkip(level, options) {
|
|
84
|
+
if (options.quiet && level !== "error") {
|
|
85
|
+
return true;
|
|
86
|
+
}
|
|
87
|
+
if (level === "debug" && !options.verbose) {
|
|
88
|
+
return true;
|
|
89
|
+
}
|
|
90
|
+
return false;
|
|
91
|
+
}
|
|
92
|
+
function createNoopSpinner() {
|
|
93
|
+
return {
|
|
94
|
+
start() { },
|
|
95
|
+
stop() { },
|
|
96
|
+
succeed() { },
|
|
97
|
+
fail() { },
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
function createSpinner(message, writer, enabledColor) {
|
|
101
|
+
const frames = ["-", "\\", "|", "/"];
|
|
102
|
+
let timer = null;
|
|
103
|
+
let frameIndex = 0;
|
|
104
|
+
let current = message;
|
|
105
|
+
const render = () => {
|
|
106
|
+
writer(`\r${frames[frameIndex % frames.length]} ${current}`);
|
|
107
|
+
frameIndex += 1;
|
|
108
|
+
};
|
|
109
|
+
const stop = () => {
|
|
110
|
+
if (timer) {
|
|
111
|
+
clearInterval(timer);
|
|
112
|
+
timer = null;
|
|
113
|
+
}
|
|
114
|
+
writer("\r");
|
|
115
|
+
writer(" ".repeat(Math.max(current.length + 2, 3)));
|
|
116
|
+
writer("\r");
|
|
117
|
+
};
|
|
118
|
+
return {
|
|
119
|
+
start() {
|
|
120
|
+
if (timer) {
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
render();
|
|
124
|
+
timer = setInterval(render, 80);
|
|
125
|
+
},
|
|
126
|
+
stop,
|
|
127
|
+
succeed(nextMessage) {
|
|
128
|
+
if (nextMessage) {
|
|
129
|
+
current = nextMessage;
|
|
130
|
+
}
|
|
131
|
+
stop();
|
|
132
|
+
writer(formatTextMessage(enabledColor, "success", current));
|
|
133
|
+
},
|
|
134
|
+
fail(nextMessage) {
|
|
135
|
+
if (nextMessage) {
|
|
136
|
+
current = nextMessage;
|
|
137
|
+
}
|
|
138
|
+
stop();
|
|
139
|
+
writer(formatTextMessage(enabledColor, "error", current));
|
|
140
|
+
},
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
function formatTable(input) {
|
|
144
|
+
if (input.rows.length === 0) {
|
|
145
|
+
return "(empty)\n";
|
|
146
|
+
}
|
|
147
|
+
const widths = input.columns.map((column) => {
|
|
148
|
+
const values = input.rows.map((row) => String(row[column] ?? ""));
|
|
149
|
+
return Math.max(column.length, ...values.map((value) => value.length));
|
|
150
|
+
});
|
|
151
|
+
const renderLine = (values) => values
|
|
152
|
+
.map((value, index) => value.padEnd(widths[index], " "))
|
|
153
|
+
.join(" | ");
|
|
154
|
+
const lines = [
|
|
155
|
+
renderLine(input.columns),
|
|
156
|
+
renderLine(widths.map((width) => "-".repeat(width))),
|
|
157
|
+
...input.rows.map((row) => renderLine(input.columns.map((column) => String(row[column] ?? "")))),
|
|
158
|
+
];
|
|
159
|
+
return `${lines.join("\n")}\n`;
|
|
160
|
+
}
|
|
161
|
+
export function createOutput(options = {}) {
|
|
162
|
+
const mode = options.mode ?? "text";
|
|
163
|
+
const quiet = options.quiet ?? false;
|
|
164
|
+
const verbose = options.verbose ?? false;
|
|
165
|
+
const color = options.color ?? true;
|
|
166
|
+
const stdout = options.stdout ?? ((text) => process.stdout.write(text));
|
|
167
|
+
const stderr = options.stderr ?? ((text) => process.stderr.write(text));
|
|
168
|
+
const writeMessage = (level, message, details) => {
|
|
169
|
+
if (shouldSkip(level, { quiet, verbose })) {
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
const payload = details === undefined ? { level, message } : { level, message, details };
|
|
173
|
+
const writer = level === "error" ? stderr : stdout;
|
|
174
|
+
if (mode === "json") {
|
|
175
|
+
writer(stringifyJson(payload));
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
writer(formatTextMessage(color, level, message, details));
|
|
179
|
+
};
|
|
180
|
+
return {
|
|
181
|
+
mode,
|
|
182
|
+
debug(message, details) {
|
|
183
|
+
writeMessage("debug", message, details);
|
|
184
|
+
},
|
|
185
|
+
info(message, details) {
|
|
186
|
+
writeMessage("info", message, details);
|
|
187
|
+
},
|
|
188
|
+
success(message, details) {
|
|
189
|
+
writeMessage("success", message, details);
|
|
190
|
+
},
|
|
191
|
+
warn(message, details) {
|
|
192
|
+
writeMessage("warn", message, details);
|
|
193
|
+
},
|
|
194
|
+
error(message, details) {
|
|
195
|
+
writeMessage("error", message, details);
|
|
196
|
+
},
|
|
197
|
+
json(value) {
|
|
198
|
+
stdout(stringifyJson(value));
|
|
199
|
+
},
|
|
200
|
+
table(input) {
|
|
201
|
+
if (quiet) {
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
if (mode === "json") {
|
|
205
|
+
stdout(stringifyJson(input));
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
stdout(formatTable(input));
|
|
209
|
+
},
|
|
210
|
+
spinner(message) {
|
|
211
|
+
if (quiet || mode === "json") {
|
|
212
|
+
return createNoopSpinner();
|
|
213
|
+
}
|
|
214
|
+
return createSpinner(message, stderr, color);
|
|
215
|
+
},
|
|
216
|
+
};
|
|
217
|
+
}
|
package/dist/prompt.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export declare class PromptInputError extends Error {
|
|
2
|
+
readonly code = "CLIFN_PROMPT_INPUT_ERROR";
|
|
3
|
+
constructor(message: string);
|
|
4
|
+
}
|
|
5
|
+
type AskFn = (label: string) => Promise<string>;
|
|
6
|
+
export interface PromptApi {
|
|
7
|
+
select<T extends string>(label: string, choices: T[]): Promise<T>;
|
|
8
|
+
multiSelect<T extends string>(label: string, choices: T[]): Promise<T[]>;
|
|
9
|
+
text(label: string, options?: {
|
|
10
|
+
default?: string;
|
|
11
|
+
}): Promise<string>;
|
|
12
|
+
confirm(label: string): Promise<boolean>;
|
|
13
|
+
}
|
|
14
|
+
export declare function createPrompt(options?: {
|
|
15
|
+
ask?: AskFn;
|
|
16
|
+
}): PromptApi;
|
|
17
|
+
export declare const prompt: PromptApi;
|
|
18
|
+
export {};
|
package/dist/prompt.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import readline from "node:readline";
|
|
2
|
+
export class PromptInputError extends Error {
|
|
3
|
+
code = "CLIFN_PROMPT_INPUT_ERROR";
|
|
4
|
+
constructor(message) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.name = "PromptInputError";
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
function assertChoices(choices) {
|
|
10
|
+
if (choices.length === 0) {
|
|
11
|
+
throw new PromptInputError("choices cannot be empty");
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
function createReadlineAskFn() {
|
|
15
|
+
return async (label) => {
|
|
16
|
+
const rl = readline.createInterface({
|
|
17
|
+
input: process.stdin,
|
|
18
|
+
output: process.stdout,
|
|
19
|
+
});
|
|
20
|
+
return await new Promise((resolve) => {
|
|
21
|
+
rl.question(label, (answer) => {
|
|
22
|
+
rl.close();
|
|
23
|
+
resolve(answer);
|
|
24
|
+
});
|
|
25
|
+
});
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
function resolveChoice(value, choices) {
|
|
29
|
+
const trimmed = value.trim();
|
|
30
|
+
const byLabel = choices.find((choice) => choice === trimmed);
|
|
31
|
+
if (byLabel) {
|
|
32
|
+
return byLabel;
|
|
33
|
+
}
|
|
34
|
+
const idx = Number(trimmed);
|
|
35
|
+
if (Number.isInteger(idx) && idx >= 1 && idx <= choices.length) {
|
|
36
|
+
return choices[idx - 1];
|
|
37
|
+
}
|
|
38
|
+
throw new PromptInputError(`invalid selection "${value}"`);
|
|
39
|
+
}
|
|
40
|
+
export function createPrompt(options) {
|
|
41
|
+
const ask = options?.ask ?? createReadlineAskFn();
|
|
42
|
+
return {
|
|
43
|
+
async select(label, choices) {
|
|
44
|
+
assertChoices(choices);
|
|
45
|
+
const menu = choices.map((choice, idx) => `${idx + 1}) ${choice}`).join(", ");
|
|
46
|
+
const input = await ask(`${label} [${menu}]: `);
|
|
47
|
+
return resolveChoice(input, choices);
|
|
48
|
+
},
|
|
49
|
+
async multiSelect(label, choices) {
|
|
50
|
+
assertChoices(choices);
|
|
51
|
+
const menu = choices.map((choice, idx) => `${idx + 1}) ${choice}`).join(", ");
|
|
52
|
+
const input = await ask(`${label} [${menu}] (comma-separated): `);
|
|
53
|
+
const tokens = input
|
|
54
|
+
.split(",")
|
|
55
|
+
.map((token) => token.trim())
|
|
56
|
+
.filter((token) => token.length > 0);
|
|
57
|
+
if (tokens.length === 0) {
|
|
58
|
+
return [];
|
|
59
|
+
}
|
|
60
|
+
const selected = tokens.map((token) => resolveChoice(token, choices));
|
|
61
|
+
return Array.from(new Set(selected));
|
|
62
|
+
},
|
|
63
|
+
async text(label, options) {
|
|
64
|
+
const input = await ask(`${label}: `);
|
|
65
|
+
const trimmed = input.trim();
|
|
66
|
+
if (trimmed.length === 0 && options?.default !== undefined) {
|
|
67
|
+
return options.default;
|
|
68
|
+
}
|
|
69
|
+
return trimmed;
|
|
70
|
+
},
|
|
71
|
+
async confirm(label) {
|
|
72
|
+
const input = (await ask(`${label} [y/n]: `)).trim().toLowerCase();
|
|
73
|
+
if (input === "y" || input === "yes") {
|
|
74
|
+
return true;
|
|
75
|
+
}
|
|
76
|
+
if (input === "n" || input === "no") {
|
|
77
|
+
return false;
|
|
78
|
+
}
|
|
79
|
+
throw new PromptInputError(`invalid confirmation "${input}"`);
|
|
80
|
+
},
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
export const prompt = createPrompt();
|
package/dist/runner.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { Diagnostic } from "./diagnostics.js";
|
|
2
|
+
import { type ExecService } from "./exec.js";
|
|
3
|
+
import { type OutputService } from "./output.js";
|
|
4
|
+
import { type ScaffoldService } from "./scaffold.js";
|
|
5
|
+
export interface RunnerDiagnosticsSink {
|
|
6
|
+
add(input: Diagnostic): void;
|
|
7
|
+
list(): readonly Diagnostic[];
|
|
8
|
+
}
|
|
9
|
+
export type RunnerDiagnosticsListener = (diagnostics: readonly Diagnostic[]) => void;
|
|
10
|
+
export interface RunnerOptions {
|
|
11
|
+
cwd?: string;
|
|
12
|
+
env?: NodeJS.ProcessEnv;
|
|
13
|
+
quiet?: boolean;
|
|
14
|
+
verbose?: boolean;
|
|
15
|
+
color?: boolean;
|
|
16
|
+
mode?: "text" | "json";
|
|
17
|
+
stdout?: (text: string) => void;
|
|
18
|
+
stderr?: (text: string) => void;
|
|
19
|
+
nonInteractive?: boolean;
|
|
20
|
+
onDiagnostics?: RunnerDiagnosticsListener;
|
|
21
|
+
}
|
|
22
|
+
export interface RunnerContext {
|
|
23
|
+
readonly cwd: string;
|
|
24
|
+
readonly env: NodeJS.ProcessEnv;
|
|
25
|
+
readonly output: OutputService;
|
|
26
|
+
readonly diagnostics: RunnerDiagnosticsSink;
|
|
27
|
+
readonly exec: ExecService;
|
|
28
|
+
readonly scaffold: ScaffoldService;
|
|
29
|
+
readonly nonInteractive: boolean;
|
|
30
|
+
}
|
|
31
|
+
export type RunnerActionResult = void | {
|
|
32
|
+
exitCode?: number;
|
|
33
|
+
data?: unknown;
|
|
34
|
+
diagnostics?: readonly Diagnostic[];
|
|
35
|
+
};
|
|
36
|
+
export declare function runAction<TOptions>(action: (options: TOptions, ctx: RunnerContext) => Promise<RunnerActionResult> | RunnerActionResult, options: TOptions, runnerOptions?: RunnerOptions): Promise<number>;
|
package/dist/runner.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { createExec } from "./exec.js";
|
|
2
|
+
import { createOutput } from "./output.js";
|
|
3
|
+
import { createScaffold } from "./scaffold.js";
|
|
4
|
+
function normalizeExitCode(exitCode) {
|
|
5
|
+
if (typeof exitCode !== "number" || !Number.isInteger(exitCode) || exitCode < 0) {
|
|
6
|
+
return 0;
|
|
7
|
+
}
|
|
8
|
+
return exitCode;
|
|
9
|
+
}
|
|
10
|
+
function normalizeError(error) {
|
|
11
|
+
if (error instanceof Error) {
|
|
12
|
+
return {
|
|
13
|
+
code: "CLIFN_RUNNER_FAILED",
|
|
14
|
+
message: error.message || error.name,
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
return {
|
|
18
|
+
code: "CLIFN_RUNNER_FAILED",
|
|
19
|
+
message: typeof error === "string" ? error : "Unknown runner failure",
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
export async function runAction(action, options, runnerOptions = {}) {
|
|
23
|
+
const cwd = runnerOptions.cwd ?? process.cwd();
|
|
24
|
+
const env = runnerOptions.env ?? process.env;
|
|
25
|
+
const diagnostics = [];
|
|
26
|
+
const baseExec = createExec();
|
|
27
|
+
const baseScaffold = createScaffold();
|
|
28
|
+
const output = createOutput({
|
|
29
|
+
quiet: runnerOptions.quiet,
|
|
30
|
+
verbose: runnerOptions.verbose,
|
|
31
|
+
color: runnerOptions.color,
|
|
32
|
+
mode: runnerOptions.mode,
|
|
33
|
+
stdout: runnerOptions.stdout,
|
|
34
|
+
stderr: runnerOptions.stderr,
|
|
35
|
+
});
|
|
36
|
+
const diagnosticSink = {
|
|
37
|
+
add(input) {
|
|
38
|
+
diagnostics.push(input);
|
|
39
|
+
},
|
|
40
|
+
list() {
|
|
41
|
+
return diagnostics;
|
|
42
|
+
},
|
|
43
|
+
};
|
|
44
|
+
const ctx = {
|
|
45
|
+
cwd,
|
|
46
|
+
env,
|
|
47
|
+
output,
|
|
48
|
+
diagnostics: diagnosticSink,
|
|
49
|
+
exec: {
|
|
50
|
+
command(file, args, options) {
|
|
51
|
+
return baseExec.command(file, args, {
|
|
52
|
+
...options,
|
|
53
|
+
cwd: options?.cwd ?? cwd,
|
|
54
|
+
env: options?.env ?? env,
|
|
55
|
+
});
|
|
56
|
+
},
|
|
57
|
+
},
|
|
58
|
+
scaffold: {
|
|
59
|
+
apply(operations, options) {
|
|
60
|
+
return baseScaffold.apply(operations, {
|
|
61
|
+
...options,
|
|
62
|
+
cwd: options?.cwd ?? cwd,
|
|
63
|
+
});
|
|
64
|
+
},
|
|
65
|
+
},
|
|
66
|
+
nonInteractive: runnerOptions.nonInteractive ?? false,
|
|
67
|
+
};
|
|
68
|
+
try {
|
|
69
|
+
const result = await action(options, ctx);
|
|
70
|
+
for (const diagnostic of result?.diagnostics ?? []) {
|
|
71
|
+
diagnosticSink.add(diagnostic);
|
|
72
|
+
}
|
|
73
|
+
const collectedDiagnostics = diagnosticSink.list();
|
|
74
|
+
runnerOptions.onDiagnostics?.(collectedDiagnostics);
|
|
75
|
+
if (runnerOptions.mode === "json" && result?.data !== undefined) {
|
|
76
|
+
output.json(result.data);
|
|
77
|
+
}
|
|
78
|
+
return normalizeExitCode(result?.exitCode);
|
|
79
|
+
}
|
|
80
|
+
catch (error) {
|
|
81
|
+
const failure = normalizeError(error);
|
|
82
|
+
runnerOptions.onDiagnostics?.(diagnosticSink.list());
|
|
83
|
+
if (runnerOptions.mode === "json") {
|
|
84
|
+
output.json({
|
|
85
|
+
ok: false,
|
|
86
|
+
error: failure,
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
else {
|
|
90
|
+
output.error(failure.message);
|
|
91
|
+
}
|
|
92
|
+
return 1;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export type FileExistsBehavior = "error" | "skip" | "overwrite";
|
|
2
|
+
export type ScaffoldErrorCode = "CLIFN_SCAFFOLD_EXISTS" | "CLIFN_SCAFFOLD_INVALID_PATH";
|
|
3
|
+
export type ScaffoldOperation = {
|
|
4
|
+
kind: "mkdir";
|
|
5
|
+
path: string;
|
|
6
|
+
} | {
|
|
7
|
+
kind: "write-file";
|
|
8
|
+
path: string;
|
|
9
|
+
content: string;
|
|
10
|
+
ifExists?: FileExistsBehavior;
|
|
11
|
+
};
|
|
12
|
+
export interface ScaffoldResult {
|
|
13
|
+
written: string[];
|
|
14
|
+
skipped: string[];
|
|
15
|
+
}
|
|
16
|
+
export interface ScaffoldService {
|
|
17
|
+
apply(operations: readonly ScaffoldOperation[], options?: {
|
|
18
|
+
cwd?: string;
|
|
19
|
+
dryRun?: boolean;
|
|
20
|
+
}): Promise<ScaffoldResult>;
|
|
21
|
+
}
|
|
22
|
+
export declare class ScaffoldError extends Error {
|
|
23
|
+
readonly code: ScaffoldErrorCode;
|
|
24
|
+
constructor(code: ScaffoldErrorCode, message: string);
|
|
25
|
+
}
|
|
26
|
+
export declare function createScaffold(): ScaffoldService;
|