@answerlayer/cli 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/LICENSE +201 -0
- package/README.md +156 -0
- package/bin/answerlayer.js +14 -0
- package/package.json +42 -0
- package/src/cli.js +1330 -0
- package/src/client.js +182 -0
- package/src/config.js +58 -0
- package/src/format.js +94 -0
package/src/client.js
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
export class AnswerLayerApiError extends Error {
|
|
2
|
+
constructor(message, { status, body } = {}) {
|
|
3
|
+
super(message);
|
|
4
|
+
this.name = "AnswerLayerApiError";
|
|
5
|
+
this.status = status;
|
|
6
|
+
this.body = body;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export class AnswerLayerClient {
|
|
11
|
+
constructor({ baseUrl, apiKey, fetchImpl = globalThis.fetch }) {
|
|
12
|
+
if (!baseUrl) {
|
|
13
|
+
throw new Error("Missing API base URL. Run `answerlayer configure --base-url <url> --api-key <key>` or set ANSWERLAYER_BASE_URL.");
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
if (!fetchImpl) {
|
|
17
|
+
throw new Error("This CLI requires Node.js 20+ with global fetch support.");
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
this.baseUrl = baseUrl;
|
|
21
|
+
this.apiKey = apiKey;
|
|
22
|
+
this.fetchImpl = fetchImpl;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async request(method, path, { body, query, auth = true } = {}) {
|
|
26
|
+
const result = await this.rawRequest(method, path, {
|
|
27
|
+
body,
|
|
28
|
+
query,
|
|
29
|
+
auth,
|
|
30
|
+
headers: { Accept: "application/json" },
|
|
31
|
+
});
|
|
32
|
+
return result.data;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async rawRequest(method, path, { body, query, headers = {}, auth = true } = {}) {
|
|
36
|
+
if (auth && !this.apiKey) {
|
|
37
|
+
throw new Error("Missing API key. Run `answerlayer configure --base-url <url> --api-key <key>` or set ANSWERLAYER_API_KEY.");
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const apiPath = path.startsWith("/") ? path : `/${path}`;
|
|
41
|
+
const url = new URL(`${this.baseUrl}${apiPath}`);
|
|
42
|
+
if (query) {
|
|
43
|
+
for (const [key, value] of Object.entries(query)) {
|
|
44
|
+
if (Array.isArray(value)) {
|
|
45
|
+
for (const item of value) {
|
|
46
|
+
if (item !== undefined && item !== null && item !== "") {
|
|
47
|
+
url.searchParams.append(key, String(item));
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
} else if (value !== undefined && value !== null && value !== "") {
|
|
51
|
+
url.searchParams.set(key, String(value));
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const requestHeaders = {
|
|
57
|
+
Accept: "application/json",
|
|
58
|
+
"User-Agent": "answerlayer-cli/0.1.0",
|
|
59
|
+
...headers,
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
if (auth) {
|
|
63
|
+
requestHeaders["X-API-Key"] = this.apiKey;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const init = { method, headers: requestHeaders };
|
|
67
|
+
if (body !== undefined) {
|
|
68
|
+
if (isFormData(body) || typeof body === "string" || Buffer.isBuffer(body)) {
|
|
69
|
+
init.body = body;
|
|
70
|
+
} else {
|
|
71
|
+
requestHeaders["Content-Type"] = requestHeaders["Content-Type"] || "application/json";
|
|
72
|
+
init.body = JSON.stringify(body);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const response = await this.fetchImpl(url, init);
|
|
77
|
+
const arrayBuffer = await response.arrayBuffer();
|
|
78
|
+
const buffer = Buffer.from(arrayBuffer);
|
|
79
|
+
const text = buffer.toString("utf8");
|
|
80
|
+
const responseHeaders = Object.fromEntries(response.headers.entries());
|
|
81
|
+
const contentType = response.headers.get("content-type") || "";
|
|
82
|
+
const data = parseResponseBody(text, contentType);
|
|
83
|
+
|
|
84
|
+
if (!response.ok) {
|
|
85
|
+
const detail = data && typeof data === "object" && "detail" in data
|
|
86
|
+
? data.detail
|
|
87
|
+
: text;
|
|
88
|
+
const message = detail
|
|
89
|
+
? `API request failed (${response.status}): ${formatDetail(detail)}`
|
|
90
|
+
: `API request failed (${response.status})`;
|
|
91
|
+
throw new AnswerLayerApiError(message, { status: response.status, body: data });
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
return {
|
|
95
|
+
status: response.status,
|
|
96
|
+
headers: responseHeaders,
|
|
97
|
+
contentType,
|
|
98
|
+
buffer,
|
|
99
|
+
text,
|
|
100
|
+
data,
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
health() {
|
|
105
|
+
return this.request("GET", "/api/v1/health", { auth: false });
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
listConnections() {
|
|
109
|
+
return this.request("GET", "/api/v1/connections/");
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
getConnection(id) {
|
|
113
|
+
return this.request("GET", `/api/v1/connections/${encodeURIComponent(id)}`);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
runQuery(connectionId, payload) {
|
|
117
|
+
return this.request("POST", `/api/v1/query/${encodeURIComponent(connectionId)}`, {
|
|
118
|
+
body: payload,
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
validateQuery(connectionId, payload) {
|
|
123
|
+
return this.request("POST", `/api/v1/query/${encodeURIComponent(connectionId)}/validate`, {
|
|
124
|
+
body: payload,
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
listSavedQueries() {
|
|
129
|
+
return this.request("GET", "/api/v1/saved-queries");
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
getSavedQuery(id) {
|
|
133
|
+
return this.request("GET", `/api/v1/saved-queries/${encodeURIComponent(id)}`);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
createSavedQuery(payload) {
|
|
137
|
+
return this.request("POST", "/api/v1/saved-queries", { body: payload });
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
executeSavedQuery(id, payload) {
|
|
141
|
+
return this.request("POST", `/api/v1/saved-queries/${encodeURIComponent(id)}/execute`, {
|
|
142
|
+
body: payload,
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
createInquirySession(payload) {
|
|
147
|
+
return this.request("POST", "/api/v1/inquiry/sessions", { body: payload });
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
runInquiryTurnSync(sessionId, payload) {
|
|
151
|
+
return this.request("POST", `/api/v1/inquiry/sessions/${encodeURIComponent(sessionId)}/sync`, {
|
|
152
|
+
body: payload,
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function parseResponseBody(text, contentType) {
|
|
158
|
+
if (!text) {
|
|
159
|
+
return null;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
if (contentType && contentType.includes("application/json")) {
|
|
163
|
+
return JSON.parse(text);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
try {
|
|
167
|
+
return JSON.parse(text);
|
|
168
|
+
} catch {
|
|
169
|
+
return text;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function formatDetail(detail) {
|
|
174
|
+
if (typeof detail === "string") {
|
|
175
|
+
return detail;
|
|
176
|
+
}
|
|
177
|
+
return JSON.stringify(detail);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function isFormData(value) {
|
|
181
|
+
return typeof FormData !== "undefined" && value instanceof FormData;
|
|
182
|
+
}
|
package/src/config.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
|
|
5
|
+
// Default to the hosted AnswerLayer SaaS. Override with --base-url, the
|
|
6
|
+
// ANSWERLAYER_BASE_URL env var, or `answerlayer configure` for BYOC /
|
|
7
|
+
// self-hosted installs.
|
|
8
|
+
export const DEFAULT_BASE_URL = "https://app.answerlayer.io";
|
|
9
|
+
|
|
10
|
+
export function defaultConfigPath(env = process.env) {
|
|
11
|
+
return env.ANSWERLAYER_CONFIG || path.join(os.homedir(), ".answerlayer", "config.json");
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function readConfig(env = process.env) {
|
|
15
|
+
const configPath = defaultConfigPath(env);
|
|
16
|
+
if (!fs.existsSync(configPath)) {
|
|
17
|
+
return {};
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const raw = fs.readFileSync(configPath, "utf8");
|
|
21
|
+
if (!raw.trim()) {
|
|
22
|
+
return {};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
try {
|
|
26
|
+
return JSON.parse(raw);
|
|
27
|
+
} catch (error) {
|
|
28
|
+
throw new Error(`Invalid config JSON at ${configPath}: ${error.message}`);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function writeConfig(config, env = process.env) {
|
|
33
|
+
const configPath = defaultConfigPath(env);
|
|
34
|
+
fs.mkdirSync(path.dirname(configPath), { recursive: true, mode: 0o700 });
|
|
35
|
+
fs.writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`, {
|
|
36
|
+
encoding: "utf8",
|
|
37
|
+
mode: 0o600,
|
|
38
|
+
});
|
|
39
|
+
return configPath;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function resolveAuth(options, env = process.env) {
|
|
43
|
+
const fileConfig = readConfig(env);
|
|
44
|
+
const baseUrl = normalizeBaseUrl(
|
|
45
|
+
options.baseUrl || env.ANSWERLAYER_BASE_URL || fileConfig.baseUrl || DEFAULT_BASE_URL,
|
|
46
|
+
);
|
|
47
|
+
const apiKey = options.apiKey || env.ANSWERLAYER_API_KEY || fileConfig.apiKey;
|
|
48
|
+
|
|
49
|
+
return { baseUrl, apiKey };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function normalizeBaseUrl(baseUrl) {
|
|
53
|
+
if (!baseUrl) {
|
|
54
|
+
return undefined;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
return String(baseUrl).replace(/\/+$/, "");
|
|
58
|
+
}
|
package/src/format.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
export function formatJson(value) {
|
|
2
|
+
return `${JSON.stringify(value, null, 2)}\n`;
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
export function formatCsv(columns, rows) {
|
|
6
|
+
const lines = [columns.map(csvCell).join(",")];
|
|
7
|
+
for (const row of rows) {
|
|
8
|
+
lines.push(row.map(csvCell).join(","));
|
|
9
|
+
}
|
|
10
|
+
return `${lines.join("\n")}\n`;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function formatTable(columns, rows, { maxWidth = 120 } = {}) {
|
|
14
|
+
if (!columns || columns.length === 0) {
|
|
15
|
+
return "(no columns)\n";
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const normalizedRows = rows || [];
|
|
19
|
+
const widths = columns.map((column, index) => {
|
|
20
|
+
const values = normalizedRows.map((row) => stringifyCell(row[index]));
|
|
21
|
+
const max = Math.max(String(column).length, ...values.map((value) => value.length));
|
|
22
|
+
return Math.min(max, Math.max(8, Math.floor(maxWidth / columns.length) - 3));
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
const header = renderRow(columns, widths);
|
|
26
|
+
const separator = widths.map((width) => "-".repeat(width)).join("-+-");
|
|
27
|
+
const body = normalizedRows.map((row) => renderRow(row, widths));
|
|
28
|
+
|
|
29
|
+
return `${[header, separator, ...body].join("\n")}\n`;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function formatQueryResult(result, format) {
|
|
33
|
+
if (format === "json") {
|
|
34
|
+
return formatJson(result);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
if (format === "csv") {
|
|
38
|
+
return formatCsv(result.columns || [], result.rows || []);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
return formatTable(result.columns || [], result.rows || []);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function formatList(items, columns) {
|
|
45
|
+
const rows = items.map((item) => columns.map((column) => getPath(item, column.key)));
|
|
46
|
+
return formatTable(columns.map((column) => column.label), rows);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function renderRow(row, widths) {
|
|
50
|
+
return widths
|
|
51
|
+
.map((width, index) => padRight(truncate(stringifyCell(row[index]), width), width))
|
|
52
|
+
.join(" | ");
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function stringifyCell(value) {
|
|
56
|
+
if (value === null || value === undefined) {
|
|
57
|
+
return "";
|
|
58
|
+
}
|
|
59
|
+
if (typeof value === "object") {
|
|
60
|
+
return JSON.stringify(value);
|
|
61
|
+
}
|
|
62
|
+
return String(value);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function truncate(value, width) {
|
|
66
|
+
if (value.length <= width) {
|
|
67
|
+
return value;
|
|
68
|
+
}
|
|
69
|
+
if (width <= 1) {
|
|
70
|
+
return value.slice(0, width);
|
|
71
|
+
}
|
|
72
|
+
return `${value.slice(0, width - 3)}...`;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function padRight(value, width) {
|
|
76
|
+
return value + " ".repeat(Math.max(0, width - value.length));
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function csvCell(value) {
|
|
80
|
+
const text = stringifyCell(value);
|
|
81
|
+
if (!/[",\n\r]/.test(text)) {
|
|
82
|
+
return text;
|
|
83
|
+
}
|
|
84
|
+
return `"${text.replaceAll('"', '""')}"`;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function getPath(value, path) {
|
|
88
|
+
return path.split(".").reduce((current, segment) => {
|
|
89
|
+
if (current === null || current === undefined) {
|
|
90
|
+
return undefined;
|
|
91
|
+
}
|
|
92
|
+
return current[segment];
|
|
93
|
+
}, value);
|
|
94
|
+
}
|