codestation-mcp 1.1.0 → 1.2.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 +62 -4
- package/bin/codestation-mcp.mjs +1562 -14
- package/package.json +1 -1
package/bin/codestation-mcp.mjs
CHANGED
|
@@ -32,7 +32,11 @@ var PRO_TOOLS = /* @__PURE__ */ new Set([
|
|
|
32
32
|
"codestation_regex_test",
|
|
33
33
|
"codestation_json_schema",
|
|
34
34
|
"codestation_json_to_typescript",
|
|
35
|
-
"codestation_json_to_zod"
|
|
35
|
+
"codestation_json_to_zod",
|
|
36
|
+
"codestation_curl_to_code",
|
|
37
|
+
"codestation_env_audit",
|
|
38
|
+
"codestation_mock_data",
|
|
39
|
+
"codestation_git_conflict"
|
|
36
40
|
]);
|
|
37
41
|
var CACHE_DIR = path.join(os.homedir(), ".codestation");
|
|
38
42
|
var CACHE_FILE = path.join(CACHE_DIR, "license.json");
|
|
@@ -864,30 +868,30 @@ var SPECS = [
|
|
|
864
868
|
{ name: "dayOfWeek", label: "Day of week", min: 0, max: 7 }
|
|
865
869
|
];
|
|
866
870
|
function parseField(expression, spec) {
|
|
867
|
-
const
|
|
871
|
+
const fail2 = (message) => {
|
|
868
872
|
throw new Error(`${spec.label}: ${message}`);
|
|
869
873
|
};
|
|
870
|
-
if (expression.length > 128)
|
|
871
|
-
if (!expression)
|
|
874
|
+
if (expression.length > 128) fail2("field exceeds the 128-character limit.");
|
|
875
|
+
if (!expression) fail2("field cannot be empty.");
|
|
872
876
|
const endpoint = (text2) => {
|
|
873
877
|
let value;
|
|
874
878
|
if (/^\d+$/.test(text2)) value = Number(text2);
|
|
875
879
|
else if (spec.name === "month" && MONTH_NAMES.includes(text2.toUpperCase())) value = MONTH_NAMES.indexOf(text2.toUpperCase()) + 1;
|
|
876
880
|
else if (spec.name === "dayOfWeek" && WEEKDAY_NAMES.includes(text2.toUpperCase())) value = WEEKDAY_NAMES.indexOf(text2.toUpperCase());
|
|
877
|
-
else return
|
|
878
|
-
if (!Number.isSafeInteger(value) || value < spec.min || value > spec.max)
|
|
881
|
+
else return fail2("use integer values, permitted month/weekday names, *, ranges, lists or steps.");
|
|
882
|
+
if (!Number.isSafeInteger(value) || value < spec.min || value > spec.max) fail2(`value must be between ${spec.min} and ${spec.max}.`);
|
|
879
883
|
return value;
|
|
880
884
|
};
|
|
881
885
|
const selected = /* @__PURE__ */ new Set();
|
|
882
886
|
for (const item of expression.split(",")) {
|
|
883
|
-
if (!item)
|
|
887
|
+
if (!item) fail2("lists cannot contain empty items.");
|
|
884
888
|
const pieces = item.split("/");
|
|
885
|
-
if (pieces.length > 2 || !pieces[0])
|
|
889
|
+
if (pieces.length > 2 || !pieces[0]) fail2("malformed step notation.");
|
|
886
890
|
let step = 1;
|
|
887
891
|
if (pieces.length === 2) {
|
|
888
|
-
if (!/^\d+$/.test(pieces[1]))
|
|
892
|
+
if (!/^\d+$/.test(pieces[1])) fail2("step must be a positive integer.");
|
|
889
893
|
step = Number(pieces[1]);
|
|
890
|
-
if (!Number.isSafeInteger(step) || step < 1 || step > spec.max - spec.min + 1)
|
|
894
|
+
if (!Number.isSafeInteger(step) || step < 1 || step > spec.max - spec.min + 1) fail2(`step must be between 1 and ${spec.max - spec.min + 1}.`);
|
|
891
895
|
}
|
|
892
896
|
const base = pieces[0];
|
|
893
897
|
let first;
|
|
@@ -897,10 +901,10 @@ function parseField(expression, spec) {
|
|
|
897
901
|
last = spec.max;
|
|
898
902
|
} else {
|
|
899
903
|
const range = base.split("-");
|
|
900
|
-
if (range.length > 2 || range.some((value) => !value))
|
|
904
|
+
if (range.length > 2 || range.some((value) => !value)) fail2("malformed range; negative values are not supported.");
|
|
901
905
|
first = endpoint(range[0]);
|
|
902
906
|
last = range.length === 2 ? endpoint(range[1]) : pieces.length === 2 ? spec.max : first;
|
|
903
|
-
if (last < first)
|
|
907
|
+
if (last < first) fail2("descending or wrapping ranges are not supported.");
|
|
904
908
|
}
|
|
905
909
|
for (let value = first; value <= last; value += step) selected.add(spec.name === "dayOfWeek" && value === 7 ? 0 : value);
|
|
906
910
|
}
|
|
@@ -1166,13 +1170,1321 @@ export type ${typeName} = z.infer<typeof ${safeRootName}>;`;
|
|
|
1166
1170
|
return header + (schemaDeclarations ? `${schemaDeclarations}${typeExport}` : `export const ${safeRootName} = ${rootResult};${typeExport}`);
|
|
1167
1171
|
}
|
|
1168
1172
|
|
|
1173
|
+
// lib/tools/api/types.ts
|
|
1174
|
+
var ApiError = class extends Error {
|
|
1175
|
+
constructor(message, field) {
|
|
1176
|
+
super(message);
|
|
1177
|
+
this.field = field;
|
|
1178
|
+
this.name = "ApiError";
|
|
1179
|
+
}
|
|
1180
|
+
};
|
|
1181
|
+
var apiText = (values, field) => typeof values[field] === "string" ? values[field] : "";
|
|
1182
|
+
|
|
1183
|
+
// lib/tools/api/curl.ts
|
|
1184
|
+
var MAX_INPUT = 2e5;
|
|
1185
|
+
var MAX_OUTPUT = 1e6;
|
|
1186
|
+
var MAX_TOKENS = 1e4;
|
|
1187
|
+
var MAX_OPTIONS = 1e3;
|
|
1188
|
+
var MAX_HEADERS = 200;
|
|
1189
|
+
function fail(message) {
|
|
1190
|
+
throw new ApiError(message, "input");
|
|
1191
|
+
}
|
|
1192
|
+
function boundedInput(values) {
|
|
1193
|
+
const source = apiText(values, "command") || apiText(values, "input") || apiText(values, "source") || apiText(values, "code") || apiText(values, "curl") || apiText(values, "value");
|
|
1194
|
+
if (source.length > MAX_INPUT) fail("Input exceeds the 200,000-character limit. Use a smaller request.");
|
|
1195
|
+
if (/\0/.test(source)) fail("Request input cannot contain NUL characters.");
|
|
1196
|
+
if (/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/.test(source)) fail("Request input contains an invalid Unicode surrogate.");
|
|
1197
|
+
return source;
|
|
1198
|
+
}
|
|
1199
|
+
function ensureOutput(text2) {
|
|
1200
|
+
if (text2.length > MAX_OUTPUT) fail("Generated output exceeds the 1,000,000-character limit. Use a smaller request.");
|
|
1201
|
+
return text2;
|
|
1202
|
+
}
|
|
1203
|
+
function jsonString(value) {
|
|
1204
|
+
return JSON.stringify(value).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
|
|
1205
|
+
}
|
|
1206
|
+
function pyString(value) {
|
|
1207
|
+
return jsonString(value);
|
|
1208
|
+
}
|
|
1209
|
+
function shellQuote(value) {
|
|
1210
|
+
return `'${value.replace(/'/g, `'"'"'`)}'`;
|
|
1211
|
+
}
|
|
1212
|
+
function base64Utf8(value) {
|
|
1213
|
+
const bytes2 = new TextEncoder().encode(value);
|
|
1214
|
+
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
1215
|
+
let out = "";
|
|
1216
|
+
for (let i = 0; i < bytes2.length; i += 3) {
|
|
1217
|
+
const a = bytes2[i], b = bytes2[i + 1] ?? 0, c = bytes2[i + 2] ?? 0;
|
|
1218
|
+
out += alphabet[a >> 2] + alphabet[(a & 3) << 4 | b >> 4] + (i + 1 < bytes2.length ? alphabet[(b & 15) << 2 | c >> 6] : "=") + (i + 2 < bytes2.length ? alphabet[c & 63] : "=");
|
|
1219
|
+
}
|
|
1220
|
+
return out;
|
|
1221
|
+
}
|
|
1222
|
+
function checkUrl(url, globDisabled = false) {
|
|
1223
|
+
let parsed;
|
|
1224
|
+
try {
|
|
1225
|
+
parsed = new URL(url);
|
|
1226
|
+
} catch {
|
|
1227
|
+
fail("Request URL must be an absolute HTTP or HTTPS URL.");
|
|
1228
|
+
}
|
|
1229
|
+
if (!/^https?:$/.test(parsed.protocol)) fail("Only HTTP and HTTPS request URLs are supported.");
|
|
1230
|
+
if (parsed.username || parsed.password) fail("URL-embedded credentials are unsupported; use explicit cURL --user authentication.");
|
|
1231
|
+
if (/[\r\n\0]/.test(url)) fail("Request URL contains an invalid control character.");
|
|
1232
|
+
if (!globDisabled && /[{}]/.test(url)) fail("cURL URL glob patterns are unsupported; use --globoff or percent-encode literal braces.");
|
|
1233
|
+
if (!globDisabled && /[\[\]]/.test(parsed.pathname + parsed.search + parsed.hash)) fail("cURL URL range patterns are unsupported; use --globoff or percent-encode literal brackets.");
|
|
1234
|
+
}
|
|
1235
|
+
function validateHeaders(headers) {
|
|
1236
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1237
|
+
for (const [name, value] of headers) {
|
|
1238
|
+
if (!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name)) fail("Invalid header name.");
|
|
1239
|
+
if (name === "__proto__") fail("The __proto__ header name is unsupported in generated object literals.");
|
|
1240
|
+
if (/[\r\n\0]/.test(value)) fail("Header values cannot contain carriage returns, newlines, or NUL.");
|
|
1241
|
+
if (seen.has(name.toLowerCase())) fail("Duplicate header names are unsupported; combine their values explicitly.");
|
|
1242
|
+
seen.add(name.toLowerCase());
|
|
1243
|
+
}
|
|
1244
|
+
if (headers.length > MAX_HEADERS) fail("Too many headers (limit 200).");
|
|
1245
|
+
}
|
|
1246
|
+
function checkStaticData(value, depth = 0, budget = { nodes: 0 }) {
|
|
1247
|
+
if (depth > 32 || ++budget.nodes > MAX_TOKENS) fail("Static data exceeds the 32-level or 10,000-value limit.");
|
|
1248
|
+
if (typeof value === "number") return Number.isFinite(value) && (!Number.isInteger(value) || Number.isSafeInteger(value));
|
|
1249
|
+
if (Array.isArray(value)) return value.every((item) => checkStaticData(item, depth + 1, budget));
|
|
1250
|
+
if (value && typeof value === "object") return Object.entries(value).every(([key, item]) => key !== "__proto__" && checkStaticData(item, depth + 1, budget));
|
|
1251
|
+
return true;
|
|
1252
|
+
}
|
|
1253
|
+
function inspectJson(request) {
|
|
1254
|
+
if (request.body === void 0 || !request.headers.some(([name, value]) => name.toLowerCase() === "content-type" && /^application\/(?:[\w.-]+\+)?json(?:\s*;|$)/i.test(value))) return;
|
|
1255
|
+
try {
|
|
1256
|
+
const data = JSON.parse(request.body);
|
|
1257
|
+
if (!checkStaticData(data)) {
|
|
1258
|
+
request.warnings.push("JSON with unsafe numeric precision or __proto__ keys is kept as raw text.");
|
|
1259
|
+
return;
|
|
1260
|
+
}
|
|
1261
|
+
if (request.headers.some(([name]) => name.toLowerCase() === "content-length")) {
|
|
1262
|
+
request.warnings.push("The body is kept as raw text to preserve its explicit Content-Length.");
|
|
1263
|
+
return;
|
|
1264
|
+
}
|
|
1265
|
+
request.jsonBody = data;
|
|
1266
|
+
if (JSON.stringify(data) !== request.body) request.warnings.push("The JSON body is reserialized; formatting and escape spelling may change.");
|
|
1267
|
+
} catch (error) {
|
|
1268
|
+
if (error instanceof ApiError) throw error;
|
|
1269
|
+
request.warnings.push("Content-Type declares JSON, but the body is not valid JSON; it is kept as raw text.");
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1272
|
+
function tokenizeShell(source) {
|
|
1273
|
+
const out = [];
|
|
1274
|
+
let token = "";
|
|
1275
|
+
let quote;
|
|
1276
|
+
let started = false;
|
|
1277
|
+
const push = () => {
|
|
1278
|
+
if (started) {
|
|
1279
|
+
out.push(token);
|
|
1280
|
+
token = "";
|
|
1281
|
+
started = false;
|
|
1282
|
+
}
|
|
1283
|
+
};
|
|
1284
|
+
for (let i = 0; i < source.length; i += 1) {
|
|
1285
|
+
const ch = source[i];
|
|
1286
|
+
if (quote === "single") {
|
|
1287
|
+
if (ch === "'") quote = void 0;
|
|
1288
|
+
else token += ch;
|
|
1289
|
+
started = true;
|
|
1290
|
+
continue;
|
|
1291
|
+
}
|
|
1292
|
+
if (quote === "double") {
|
|
1293
|
+
if (ch === '"') {
|
|
1294
|
+
quote = void 0;
|
|
1295
|
+
started = true;
|
|
1296
|
+
continue;
|
|
1297
|
+
}
|
|
1298
|
+
if (ch === "$") fail("Shell variable expansion is unsupported; use literal cURL values.");
|
|
1299
|
+
if (ch === "`") fail("Shell substitutions and command separators are unsupported.");
|
|
1300
|
+
if (ch === "\\") {
|
|
1301
|
+
const next = source[++i];
|
|
1302
|
+
if (next === void 0) fail("Malformed cURL: unterminated escape.");
|
|
1303
|
+
if (next === "\n") continue;
|
|
1304
|
+
token += ['"', "\\", "$", "`"].includes(next) ? next : `\\${next}`;
|
|
1305
|
+
} else token += ch;
|
|
1306
|
+
started = true;
|
|
1307
|
+
continue;
|
|
1308
|
+
}
|
|
1309
|
+
if (ch === "'") {
|
|
1310
|
+
quote = "single";
|
|
1311
|
+
started = true;
|
|
1312
|
+
continue;
|
|
1313
|
+
}
|
|
1314
|
+
if (ch === '"') {
|
|
1315
|
+
quote = "double";
|
|
1316
|
+
started = true;
|
|
1317
|
+
continue;
|
|
1318
|
+
}
|
|
1319
|
+
if (/\s/.test(ch)) {
|
|
1320
|
+
push();
|
|
1321
|
+
continue;
|
|
1322
|
+
}
|
|
1323
|
+
if (ch === "$") fail("Shell variable expansion is unsupported; use literal cURL values.");
|
|
1324
|
+
if ("`;|><&()".includes(ch)) fail("Shell substitutions, redirections, and command separators are unsupported; quote literal values.");
|
|
1325
|
+
if (ch === "\\") {
|
|
1326
|
+
const next = source[++i];
|
|
1327
|
+
if (next === void 0) fail("Malformed cURL: unterminated escape.");
|
|
1328
|
+
if (next !== "\n") token += next;
|
|
1329
|
+
} else token += ch;
|
|
1330
|
+
started = true;
|
|
1331
|
+
if (out.length > MAX_TOKENS) fail("cURL request has too many tokens (limit 10,000).");
|
|
1332
|
+
}
|
|
1333
|
+
if (quote) fail("Malformed cURL: unterminated quote.");
|
|
1334
|
+
push();
|
|
1335
|
+
if (out.length > MAX_TOKENS) fail("cURL request has too many tokens (limit 10,000).");
|
|
1336
|
+
return out;
|
|
1337
|
+
}
|
|
1338
|
+
function addHeader(headers, value) {
|
|
1339
|
+
const colon = value.indexOf(":");
|
|
1340
|
+
if (colon < 0 && value.endsWith(";")) {
|
|
1341
|
+
headers.push([value.slice(0, -1), ""]);
|
|
1342
|
+
validateHeaders(headers);
|
|
1343
|
+
return;
|
|
1344
|
+
}
|
|
1345
|
+
if (colon <= 0) fail("Invalid header: expected `Name: value`.");
|
|
1346
|
+
const name = value.slice(0, colon).trim();
|
|
1347
|
+
if (!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name)) fail("Invalid header name.");
|
|
1348
|
+
if (!value.slice(colon + 1).trim()) fail("cURL header suppression or empty headers are unsupported.");
|
|
1349
|
+
headers.push([name, value.slice(colon + 1).trim()]);
|
|
1350
|
+
if (headers.length > MAX_HEADERS) fail("Too many headers (limit 200).");
|
|
1351
|
+
}
|
|
1352
|
+
function parseCurl(source) {
|
|
1353
|
+
const tokens = tokenizeShell(source.trim());
|
|
1354
|
+
if (!tokens.length) fail("Enter a cURL command.");
|
|
1355
|
+
if (tokens[0].toLowerCase() !== "curl") fail("cURL input must start with `curl`.");
|
|
1356
|
+
const headers = [];
|
|
1357
|
+
const bodyParts = [];
|
|
1358
|
+
let method;
|
|
1359
|
+
let url;
|
|
1360
|
+
let basicAuth;
|
|
1361
|
+
let globDisabled = false;
|
|
1362
|
+
const warnings = [];
|
|
1363
|
+
let optionCount = 0;
|
|
1364
|
+
const need = (index, option) => {
|
|
1365
|
+
const value = tokens[index + 1];
|
|
1366
|
+
if (value === void 0) fail(`Option ${option} requires a value.`);
|
|
1367
|
+
return value;
|
|
1368
|
+
};
|
|
1369
|
+
for (let i = 1; i < tokens.length; i += 1) {
|
|
1370
|
+
const token = tokens[i];
|
|
1371
|
+
if (token.startsWith("-") && ++optionCount > MAX_OPTIONS) fail("cURL request has too many options (limit 1,000).");
|
|
1372
|
+
let option = token;
|
|
1373
|
+
let inline;
|
|
1374
|
+
const equals = option.indexOf("=");
|
|
1375
|
+
if (option.startsWith("--") && equals > 2) {
|
|
1376
|
+
inline = option.slice(equals + 1);
|
|
1377
|
+
option = option.slice(0, equals);
|
|
1378
|
+
}
|
|
1379
|
+
const take = (name) => {
|
|
1380
|
+
if (inline !== void 0) return inline;
|
|
1381
|
+
const value = need(i, name);
|
|
1382
|
+
i += 1;
|
|
1383
|
+
return value;
|
|
1384
|
+
};
|
|
1385
|
+
if ((option === "--globoff" || option === "-g") && inline === void 0) {
|
|
1386
|
+
globDisabled = true;
|
|
1387
|
+
continue;
|
|
1388
|
+
}
|
|
1389
|
+
if (option === "--url") {
|
|
1390
|
+
if (url !== void 0) fail("Multiple URLs are unsupported.");
|
|
1391
|
+
url = take(option);
|
|
1392
|
+
continue;
|
|
1393
|
+
}
|
|
1394
|
+
if (option === "--request") {
|
|
1395
|
+
method = take(option);
|
|
1396
|
+
continue;
|
|
1397
|
+
}
|
|
1398
|
+
if (option === "-X") {
|
|
1399
|
+
method = take(option);
|
|
1400
|
+
continue;
|
|
1401
|
+
}
|
|
1402
|
+
if (option.startsWith("-X") && option.length > 2) {
|
|
1403
|
+
method = option.slice(2);
|
|
1404
|
+
continue;
|
|
1405
|
+
}
|
|
1406
|
+
if (option === "--header") {
|
|
1407
|
+
addHeader(headers, take(option));
|
|
1408
|
+
continue;
|
|
1409
|
+
}
|
|
1410
|
+
if (option === "-H") {
|
|
1411
|
+
addHeader(headers, take(option));
|
|
1412
|
+
continue;
|
|
1413
|
+
}
|
|
1414
|
+
if (option.startsWith("-H") && option.length > 2) {
|
|
1415
|
+
addHeader(headers, option.slice(2));
|
|
1416
|
+
continue;
|
|
1417
|
+
}
|
|
1418
|
+
if (option === "--data" || option === "--data-raw" || option === "--data-binary" || option === "-d") {
|
|
1419
|
+
const value = take(option);
|
|
1420
|
+
if (option !== "--data-raw" && value.startsWith("@")) fail("cURL body file references are unsupported; provide literal data using --data-raw.");
|
|
1421
|
+
bodyParts.push(value);
|
|
1422
|
+
if (bodyParts.length > 200) fail("Too many body options (limit 200).");
|
|
1423
|
+
continue;
|
|
1424
|
+
}
|
|
1425
|
+
if (option.startsWith("-d") && option.length > 2) {
|
|
1426
|
+
if (option[2] === "@") fail("cURL body file references are unsupported; provide literal data using --data-raw.");
|
|
1427
|
+
bodyParts.push(option.slice(2));
|
|
1428
|
+
continue;
|
|
1429
|
+
}
|
|
1430
|
+
if (option === "--data-urlencode") {
|
|
1431
|
+
const value = take(option);
|
|
1432
|
+
const at = value.indexOf("@");
|
|
1433
|
+
if (at >= 0 && (at === 0 || value.slice(0, at).indexOf("=") < 0)) fail("--data-urlencode file references are unsupported; provide literal data.");
|
|
1434
|
+
const eq = value.indexOf("=");
|
|
1435
|
+
const encode = (text2) => encodeURIComponent(text2).replace(/[!'()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
1436
|
+
try {
|
|
1437
|
+
bodyParts.push(eq < 0 ? encode(value) : `${eq > 0 ? `${value.slice(0, eq)}=` : ""}${encode(value.slice(eq + 1))}`);
|
|
1438
|
+
} catch {
|
|
1439
|
+
fail("URL-encoded body data contains an invalid Unicode surrogate.");
|
|
1440
|
+
}
|
|
1441
|
+
continue;
|
|
1442
|
+
}
|
|
1443
|
+
if (option === "-u" || option === "--user") {
|
|
1444
|
+
const value = take(option);
|
|
1445
|
+
const colon = value.indexOf(":");
|
|
1446
|
+
if (colon < 0) fail("Basic authentication must use the literal `username:password` form.");
|
|
1447
|
+
basicAuth = [value.slice(0, colon), value.slice(colon + 1)];
|
|
1448
|
+
continue;
|
|
1449
|
+
}
|
|
1450
|
+
if (option.startsWith("-u") && option.length > 2) {
|
|
1451
|
+
const value = option.slice(2);
|
|
1452
|
+
const colon = value.indexOf(":");
|
|
1453
|
+
if (colon < 0) fail("Basic authentication must use the literal `username:password` form.");
|
|
1454
|
+
basicAuth = [value.slice(0, colon), value.slice(colon + 1)];
|
|
1455
|
+
continue;
|
|
1456
|
+
}
|
|
1457
|
+
if (option === "--") {
|
|
1458
|
+
if (tokens.length - i !== 2 || url !== void 0) fail("Expected one URL after --; multiple URLs are unsupported.");
|
|
1459
|
+
url = tokens[++i];
|
|
1460
|
+
continue;
|
|
1461
|
+
}
|
|
1462
|
+
if (option.startsWith("-")) fail(`Unsupported cURL option${/^--?[A-Za-z][A-Za-z-]{0,40}$/.test(option) ? `: ${option}` : ""}. The request was not converted.`);
|
|
1463
|
+
if (url) fail("Multiple URLs are unsupported.");
|
|
1464
|
+
url = token;
|
|
1465
|
+
}
|
|
1466
|
+
if (!url) fail("cURL request is missing a URL.");
|
|
1467
|
+
if (!url.trim()) fail("cURL request URL cannot be empty.");
|
|
1468
|
+
if (bodyParts.length > 200) fail("Too many body options (limit 200).");
|
|
1469
|
+
const body = bodyParts.length ? bodyParts.join("&") : void 0;
|
|
1470
|
+
if (method === void 0) method = body === void 0 ? "GET" : "POST";
|
|
1471
|
+
if (!/^[A-Za-z][A-Za-z0-9!#$%&'*+.^_`|~-]{0,31}$/.test(method)) fail("HTTP method is invalid.");
|
|
1472
|
+
if (body !== void 0 && !headers.some(([name]) => name.toLowerCase() === "content-type")) headers.push(["Content-Type", "application/x-www-form-urlencoded"]);
|
|
1473
|
+
if (basicAuth) {
|
|
1474
|
+
if (headers.some(([name]) => name.toLowerCase() === "authorization")) warnings.push("The explicit Authorization header takes precedence over --user.");
|
|
1475
|
+
else headers.push(["Authorization", `Basic ${base64Utf8(`${basicAuth[0]}:${basicAuth[1]}`)}`]);
|
|
1476
|
+
}
|
|
1477
|
+
checkUrl(url, globDisabled);
|
|
1478
|
+
validateHeaders(headers);
|
|
1479
|
+
const request = { method, url, headers, body, warnings };
|
|
1480
|
+
inspectJson(request);
|
|
1481
|
+
return request;
|
|
1482
|
+
}
|
|
1483
|
+
function lexJs(source) {
|
|
1484
|
+
const tokens = [];
|
|
1485
|
+
let i = 0;
|
|
1486
|
+
const add = (kind, value) => {
|
|
1487
|
+
tokens.push({ kind, value });
|
|
1488
|
+
if (tokens.length > MAX_TOKENS) fail("Fetch expression has too many tokens (limit 10,000).");
|
|
1489
|
+
};
|
|
1490
|
+
while (i < source.length) {
|
|
1491
|
+
const ch = source[i];
|
|
1492
|
+
if (/\s/.test(ch)) {
|
|
1493
|
+
i += 1;
|
|
1494
|
+
continue;
|
|
1495
|
+
}
|
|
1496
|
+
if (ch === "/" && source[i + 1] === "/") fail("Comments are unsupported in Fetch input; provide a static expression.");
|
|
1497
|
+
if (ch === "'" || ch === '"') {
|
|
1498
|
+
const quote = ch;
|
|
1499
|
+
let value = "";
|
|
1500
|
+
let closed = false;
|
|
1501
|
+
i += 1;
|
|
1502
|
+
while (i < source.length) {
|
|
1503
|
+
const c = source[i++];
|
|
1504
|
+
if (c === quote) {
|
|
1505
|
+
closed = true;
|
|
1506
|
+
break;
|
|
1507
|
+
}
|
|
1508
|
+
if (c === "\\") {
|
|
1509
|
+
const e = source[i++];
|
|
1510
|
+
if (e === void 0) fail("Malformed Fetch expression: unterminated string.");
|
|
1511
|
+
if (e === "n") value += "\n";
|
|
1512
|
+
else if (e === "r") value += "\r";
|
|
1513
|
+
else if (e === "t") value += " ";
|
|
1514
|
+
else if (e === "b") value += "\b";
|
|
1515
|
+
else if (e === "f") value += "\f";
|
|
1516
|
+
else if (e === "v") value += "\v";
|
|
1517
|
+
else if (e === "0") {
|
|
1518
|
+
if (/\d/.test(source[i] ?? "")) fail("Legacy octal string escapes are unsupported.");
|
|
1519
|
+
value += "\0";
|
|
1520
|
+
} else if (e === "u") {
|
|
1521
|
+
if (source[i] === "{") {
|
|
1522
|
+
const end = source.indexOf("}", i + 1);
|
|
1523
|
+
const hex2 = source.slice(i + 1, end);
|
|
1524
|
+
if (end < 0 || !/^[0-9A-Fa-f]{1,6}$/.test(hex2) || parseInt(hex2, 16) > 1114111) fail("Malformed Fetch expression: invalid Unicode escape.");
|
|
1525
|
+
value += String.fromCodePoint(parseInt(hex2, 16));
|
|
1526
|
+
i = end + 1;
|
|
1527
|
+
} else {
|
|
1528
|
+
const hex2 = source.slice(i, i + 4);
|
|
1529
|
+
if (!/^[0-9A-Fa-f]{4}$/.test(hex2)) fail("Malformed Fetch expression: invalid Unicode escape.");
|
|
1530
|
+
value += String.fromCharCode(parseInt(hex2, 16));
|
|
1531
|
+
i += 4;
|
|
1532
|
+
}
|
|
1533
|
+
} else if (e === "x") {
|
|
1534
|
+
const hex2 = source.slice(i, i + 2);
|
|
1535
|
+
if (!/^[0-9A-Fa-f]{2}$/.test(hex2)) fail("Malformed Fetch expression: invalid hexadecimal escape.");
|
|
1536
|
+
value += String.fromCharCode(parseInt(hex2, 16));
|
|
1537
|
+
i += 2;
|
|
1538
|
+
} else if (e === "\n") {
|
|
1539
|
+
} else if (e === "\r") {
|
|
1540
|
+
if (source[i] === "\n") i += 1;
|
|
1541
|
+
} else if (/\d/.test(e)) fail("Legacy octal string escapes are unsupported.");
|
|
1542
|
+
else value += e;
|
|
1543
|
+
} else {
|
|
1544
|
+
if (c === "\n" || c === "\r") fail("Malformed Fetch expression: unescaped newline in string.");
|
|
1545
|
+
value += c;
|
|
1546
|
+
}
|
|
1547
|
+
}
|
|
1548
|
+
if (!closed) fail("Malformed Fetch expression: unterminated string.");
|
|
1549
|
+
add("string", value);
|
|
1550
|
+
continue;
|
|
1551
|
+
}
|
|
1552
|
+
if (ch === "`") fail("Fetch templates are dynamic and unsupported; use a quoted URL/string.");
|
|
1553
|
+
if (/[A-Za-z_$]/.test(ch)) {
|
|
1554
|
+
const start = i++;
|
|
1555
|
+
while (i < source.length && /[A-Za-z0-9_$]/.test(source[i])) i += 1;
|
|
1556
|
+
add("identifier", source.slice(start, i));
|
|
1557
|
+
continue;
|
|
1558
|
+
}
|
|
1559
|
+
if (/[0-9-]/.test(ch)) {
|
|
1560
|
+
const start = i++;
|
|
1561
|
+
while (i < source.length && /[0-9.eE+-]/.test(source[i])) i += 1;
|
|
1562
|
+
const value = source.slice(start, i);
|
|
1563
|
+
if (!/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(value)) fail("Malformed Fetch expression: invalid number.");
|
|
1564
|
+
add("number", value);
|
|
1565
|
+
continue;
|
|
1566
|
+
}
|
|
1567
|
+
if ("{}[]():,;.".includes(ch)) {
|
|
1568
|
+
add("punct", ch);
|
|
1569
|
+
i += 1;
|
|
1570
|
+
continue;
|
|
1571
|
+
}
|
|
1572
|
+
fail(`Unsupported Fetch syntax at character ${i + 1}; use only static literals.`);
|
|
1573
|
+
}
|
|
1574
|
+
add("eof", "");
|
|
1575
|
+
return tokens;
|
|
1576
|
+
}
|
|
1577
|
+
var StaticJson = class {
|
|
1578
|
+
constructor(value) {
|
|
1579
|
+
this.value = value;
|
|
1580
|
+
}
|
|
1581
|
+
};
|
|
1582
|
+
var JsReader = class {
|
|
1583
|
+
constructor(tokens) {
|
|
1584
|
+
this.tokens = tokens;
|
|
1585
|
+
this.index = 0;
|
|
1586
|
+
this.nodes = 0;
|
|
1587
|
+
}
|
|
1588
|
+
peek() {
|
|
1589
|
+
return this.tokens[this.index];
|
|
1590
|
+
}
|
|
1591
|
+
take(value) {
|
|
1592
|
+
const token = this.tokens[this.index++];
|
|
1593
|
+
if (value !== void 0 && token.value !== value) fail(`Malformed Fetch expression: expected '${value}'.`);
|
|
1594
|
+
return token;
|
|
1595
|
+
}
|
|
1596
|
+
expression(depth = 0, stringifyAllowed = true) {
|
|
1597
|
+
if (depth > 32 || ++this.nodes > MAX_TOKENS) fail("Static data exceeds the 32-level or 10,000-value limit.");
|
|
1598
|
+
const token = this.peek();
|
|
1599
|
+
if (token.kind === "string") {
|
|
1600
|
+
this.take();
|
|
1601
|
+
return token.value;
|
|
1602
|
+
}
|
|
1603
|
+
if (token.kind === "number") {
|
|
1604
|
+
this.take();
|
|
1605
|
+
const value = Number(token.value);
|
|
1606
|
+
if (!Number.isFinite(value) || Number.isInteger(value) && !Number.isSafeInteger(value)) fail("Static numeric values must be finite and use safe integer precision.");
|
|
1607
|
+
return value;
|
|
1608
|
+
}
|
|
1609
|
+
if (token.kind === "identifier") {
|
|
1610
|
+
if (token.value === "true" || token.value === "false") {
|
|
1611
|
+
this.take();
|
|
1612
|
+
return token.value === "true";
|
|
1613
|
+
}
|
|
1614
|
+
if (token.value === "null") {
|
|
1615
|
+
this.take();
|
|
1616
|
+
return null;
|
|
1617
|
+
}
|
|
1618
|
+
if (token.value === "JSON" && stringifyAllowed) {
|
|
1619
|
+
this.take("JSON");
|
|
1620
|
+
this.take(".");
|
|
1621
|
+
this.take("stringify");
|
|
1622
|
+
this.take("(");
|
|
1623
|
+
const value = this.expression(depth + 1, false);
|
|
1624
|
+
this.take(")");
|
|
1625
|
+
return new StaticJson(value);
|
|
1626
|
+
}
|
|
1627
|
+
fail("Fetch values must be static literals or JSON.stringify(static data).");
|
|
1628
|
+
}
|
|
1629
|
+
if (token.value === "{") {
|
|
1630
|
+
this.take("{");
|
|
1631
|
+
const object = /* @__PURE__ */ Object.create(null);
|
|
1632
|
+
if (this.peek().value !== "}") while (true) {
|
|
1633
|
+
const key = this.take();
|
|
1634
|
+
if (key.kind !== "identifier" && key.kind !== "string") fail("Fetch object keys must be static identifiers or strings.");
|
|
1635
|
+
if (key.value === "__proto__") fail("__proto__ object-literal keys are unsupported; provide a static JSON string body instead.");
|
|
1636
|
+
if (Object.hasOwn(object, key.value)) fail("Duplicate object-literal keys are unsupported.");
|
|
1637
|
+
this.take(":");
|
|
1638
|
+
object[key.value] = this.expression(depth + 1, stringifyAllowed && depth === 0);
|
|
1639
|
+
if (this.peek().value === "}") break;
|
|
1640
|
+
this.take(",");
|
|
1641
|
+
if (this.peek().value === "}") break;
|
|
1642
|
+
}
|
|
1643
|
+
this.take("}");
|
|
1644
|
+
return object;
|
|
1645
|
+
}
|
|
1646
|
+
if (token.value === "[") {
|
|
1647
|
+
this.take("[");
|
|
1648
|
+
const array = [];
|
|
1649
|
+
if (this.peek().value !== "]") while (true) {
|
|
1650
|
+
array.push(this.expression(depth + 1, false));
|
|
1651
|
+
if (this.peek().value === "]") break;
|
|
1652
|
+
this.take(",");
|
|
1653
|
+
if (this.peek().value === "]") break;
|
|
1654
|
+
}
|
|
1655
|
+
this.take("]");
|
|
1656
|
+
return array;
|
|
1657
|
+
}
|
|
1658
|
+
fail("Fetch values must be static literals.");
|
|
1659
|
+
}
|
|
1660
|
+
};
|
|
1661
|
+
function parseFetch(source) {
|
|
1662
|
+
const tokens = lexJs(source.trim());
|
|
1663
|
+
const reader = new JsReader(tokens);
|
|
1664
|
+
if (reader.peek().value !== "fetch") fail("Fetch input must be a static fetch(...) call.");
|
|
1665
|
+
reader.take("fetch");
|
|
1666
|
+
reader.take("(");
|
|
1667
|
+
const urlToken = reader.take();
|
|
1668
|
+
if (urlToken.kind !== "string") fail("Fetch URL must be a static string literal.");
|
|
1669
|
+
const url = urlToken.value;
|
|
1670
|
+
let method = "GET";
|
|
1671
|
+
let headers = [];
|
|
1672
|
+
let body;
|
|
1673
|
+
let jsonBody;
|
|
1674
|
+
if (reader.peek().value === ",") {
|
|
1675
|
+
reader.take(",");
|
|
1676
|
+
if (reader.peek().value !== ")") {
|
|
1677
|
+
const options = reader.expression();
|
|
1678
|
+
if (!options || typeof options !== "object" || Array.isArray(options) || options instanceof StaticJson) fail("Fetch options must be a static object literal.");
|
|
1679
|
+
for (const [key, value] of Object.entries(options)) {
|
|
1680
|
+
if (key === "method") {
|
|
1681
|
+
if (typeof value !== "string") fail("Fetch method must be a static string.");
|
|
1682
|
+
method = /^(?:delete|get|head|options|post|put)$/i.test(value) ? value.toUpperCase() : value;
|
|
1683
|
+
} else if (key === "headers") {
|
|
1684
|
+
if (!value || typeof value !== "object" || Array.isArray(value) || value instanceof StaticJson) fail("Fetch headers must be a static object literal.");
|
|
1685
|
+
headers = Object.entries(value).map(([name, headerValue]) => {
|
|
1686
|
+
if (typeof headerValue !== "string") fail("Fetch header values must be static strings.");
|
|
1687
|
+
return [name, headerValue];
|
|
1688
|
+
});
|
|
1689
|
+
if (headers.length > MAX_HEADERS) fail("Too many headers (limit 200).");
|
|
1690
|
+
} else if (key === "body") {
|
|
1691
|
+
if (typeof value === "string") body = value;
|
|
1692
|
+
else if (value instanceof StaticJson) {
|
|
1693
|
+
body = JSON.stringify(value.value);
|
|
1694
|
+
jsonBody = value.value;
|
|
1695
|
+
} else fail("Fetch body must be a static string or JSON.stringify(static data).");
|
|
1696
|
+
} else fail(`Unsupported Fetch option: ${key}. Use only method, headers, and body.`);
|
|
1697
|
+
}
|
|
1698
|
+
if (reader.peek().value === ",") reader.take(",");
|
|
1699
|
+
}
|
|
1700
|
+
}
|
|
1701
|
+
reader.take(")");
|
|
1702
|
+
if (reader.peek().value === ";") reader.take(";");
|
|
1703
|
+
if (reader.peek().kind !== "eof") fail("Malformed Fetch expression: trailing syntax is unsupported.");
|
|
1704
|
+
if (body !== void 0 && (method === "GET" || method === "HEAD")) fail("Fetch does not support a body with GET or HEAD; use an explicit body-capable method.");
|
|
1705
|
+
if (!/^[A-Za-z][A-Za-z0-9!#$%&'*+.^_`|~-]{0,31}$/.test(method)) fail("HTTP method is invalid.");
|
|
1706
|
+
if (/^(?:CONNECT|TRACE|TRACK)$/i.test(method)) fail("Fetch forbids CONNECT, TRACE, and TRACK methods.");
|
|
1707
|
+
checkUrl(url, true);
|
|
1708
|
+
if (body !== void 0 && /\0/.test(body)) fail("A NUL-containing Fetch body cannot be represented as a cURL argument.");
|
|
1709
|
+
if (body !== void 0 && /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/.test(body)) fail("Fetch body contains an invalid Unicode surrogate.");
|
|
1710
|
+
if (body !== void 0 && !headers.some(([name]) => name.toLowerCase() === "content-type")) headers.push(["Content-Type", "text/plain;charset=UTF-8"]);
|
|
1711
|
+
validateHeaders(headers);
|
|
1712
|
+
return { method, url, headers, body, jsonBody, warnings: [] };
|
|
1713
|
+
}
|
|
1714
|
+
function renderHeaders(headers, indent) {
|
|
1715
|
+
return headers.map(([name, value]) => `${indent}${jsonString(name)}: ${jsonString(value)}`).join(",\n");
|
|
1716
|
+
}
|
|
1717
|
+
function jsData(value, indent) {
|
|
1718
|
+
return JSON.stringify(value, null, 2).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029").split("\n").map((line, index) => index ? " ".repeat(indent) + line : line).join("\n");
|
|
1719
|
+
}
|
|
1720
|
+
function pythonLiteral(value) {
|
|
1721
|
+
if (value === null) return "None";
|
|
1722
|
+
if (typeof value === "string") return pyString(value);
|
|
1723
|
+
if (typeof value === "boolean") return value ? "True" : "False";
|
|
1724
|
+
if (typeof value === "number") return Number.isFinite(value) ? String(value) : fail("JSON body contains a non-finite number.");
|
|
1725
|
+
if (Array.isArray(value)) return `[${value.map((item) => pythonLiteral(item)).join(", ")}]`;
|
|
1726
|
+
if (value && typeof value === "object") return `{${Object.entries(value).map(([key, item]) => `${pyString(key)}: ${pythonLiteral(item)}`).join(", ")}}`;
|
|
1727
|
+
fail("JSON body contains an unsupported value.");
|
|
1728
|
+
}
|
|
1729
|
+
function fetchCode(request) {
|
|
1730
|
+
const hasBody = request.body !== void 0;
|
|
1731
|
+
const lines = [`const response = await fetch(${jsonString(request.url)}${hasBody || request.headers.length || request.method !== "GET" ? ", {" : ");"}`];
|
|
1732
|
+
if (lines[0].endsWith(", {")) {
|
|
1733
|
+
lines.push(` method: ${jsonString(request.method)},`);
|
|
1734
|
+
if (request.headers.length) lines.push(" headers: {", renderHeaders(request.headers, " "), " },");
|
|
1735
|
+
if (hasBody) lines.push(` body: ${request.jsonBody !== void 0 ? `JSON.stringify(${jsData(request.jsonBody, 2)})` : jsonString(request.body ?? "")},`);
|
|
1736
|
+
lines.push("});");
|
|
1737
|
+
}
|
|
1738
|
+
lines.push("const data = await response.text();");
|
|
1739
|
+
return lines.join("\n");
|
|
1740
|
+
}
|
|
1741
|
+
function axiosCode(request) {
|
|
1742
|
+
const lines = ['import axios from "axios";', "", "const response = await axios({", ` method: ${jsonString(request.method)},`, ` url: ${jsonString(request.url)},`];
|
|
1743
|
+
if (request.headers.length) lines.push(" headers: {", renderHeaders(request.headers, " "), " },");
|
|
1744
|
+
if (request.body !== void 0) {
|
|
1745
|
+
const structured = request.jsonBody !== null && typeof request.jsonBody === "object";
|
|
1746
|
+
lines.push(` data: ${structured ? jsData(request.jsonBody, 2) : jsonString(request.body)},`);
|
|
1747
|
+
if (!structured) lines.push(" transformRequest: [(data) => data],");
|
|
1748
|
+
}
|
|
1749
|
+
lines.push("});", "", "const data = response.data;");
|
|
1750
|
+
return lines.join("\n");
|
|
1751
|
+
}
|
|
1752
|
+
function pythonCode(request) {
|
|
1753
|
+
const lines = ["import requests"];
|
|
1754
|
+
lines.push("", "headers = {");
|
|
1755
|
+
for (const [name, value] of request.headers) {
|
|
1756
|
+
lines.push(` ${pyString(name)}: ${pyString(value)},`);
|
|
1757
|
+
}
|
|
1758
|
+
lines.push("}", "", `response = requests.request(`, ` ${pyString(request.method)},`, ` ${pyString(request.url)},`, " headers=headers,");
|
|
1759
|
+
if (request.body !== void 0) {
|
|
1760
|
+
lines[lines.length - 1] = request.jsonBody !== void 0 && request.jsonBody !== null ? ` headers=headers,
|
|
1761
|
+
json=${pythonLiteral(request.jsonBody)},` : ` headers=headers,
|
|
1762
|
+
data=${pyString(request.body)}.encode("utf-8"),`;
|
|
1763
|
+
}
|
|
1764
|
+
lines.push(")", "", "data = response.text");
|
|
1765
|
+
return lines.join("\n");
|
|
1766
|
+
}
|
|
1767
|
+
function curlCode(request) {
|
|
1768
|
+
const parts = ["curl", "--request", shellQuote(request.method)];
|
|
1769
|
+
if (/[{}\[\]]/.test(request.url)) parts.push("--globoff");
|
|
1770
|
+
for (const [name, value] of request.headers) parts.push("--header", shellQuote(value ? `${name}: ${value}` : `${name};`));
|
|
1771
|
+
if (request.body !== void 0) parts.push("--data-raw", shellQuote(request.body));
|
|
1772
|
+
parts.push(shellQuote(request.url));
|
|
1773
|
+
return parts.join(" ");
|
|
1774
|
+
}
|
|
1775
|
+
function resultFor(id, request) {
|
|
1776
|
+
let output;
|
|
1777
|
+
if (id === "curl-to-fetch") {
|
|
1778
|
+
if (request.body !== void 0 && /^(?:GET|HEAD)$/i.test(request.method)) fail("Fetch does not support a body with GET or HEAD; choose another conversion or a body-capable method.");
|
|
1779
|
+
if (/^(?:CONNECT|TRACE|TRACK)$/i.test(request.method)) fail("Fetch forbids CONNECT, TRACE, and TRACK methods.");
|
|
1780
|
+
output = fetchCode(request);
|
|
1781
|
+
if (request.headers.some(([name]) => /^(?:host|cookie|content-length|connection|origin|referer|accept-encoding)$/i.test(name))) request.warnings.push("Browser Fetch may ignore forbidden request headers; run the snippet in a compatible environment to preserve them.");
|
|
1782
|
+
if (/^(?:delete|get|head|options|post|put)$/i.test(request.method) && request.method !== request.method.toUpperCase()) request.warnings.push("Fetch normalizes the casing of standard HTTP methods.");
|
|
1783
|
+
} else if (id === "curl-to-axios") {
|
|
1784
|
+
output = axiosCode(request);
|
|
1785
|
+
if (request.method !== request.method.toUpperCase()) request.warnings.push("Axios transports may normalize HTTP method casing.");
|
|
1786
|
+
if (request.body !== void 0 && /^(?:GET|HEAD)$/i.test(request.method)) request.warnings.push("Browser Axios transports may omit a GET or HEAD body; use a body-capable transport.");
|
|
1787
|
+
} else if (id === "curl-to-python-requests") output = pythonCode(request);
|
|
1788
|
+
else output = curlCode(request);
|
|
1789
|
+
if ((id === "curl-to-fetch" || id === "curl-to-axios") && request.headers.some(([, value]) => /[^\x00-\xFF]/.test(value))) request.warnings.push("Non-Latin-1 header values may be rejected by browser header APIs.");
|
|
1790
|
+
output = ensureOutput(output);
|
|
1791
|
+
return { text: output, copyText: output, data: { method: request.method, url: request.url, headers: request.headers, body: request.body ?? null }, warnings: request.warnings };
|
|
1792
|
+
}
|
|
1793
|
+
async function convertApi(id, values) {
|
|
1794
|
+
try {
|
|
1795
|
+
if (!["curl-to-fetch", "fetch-to-curl", "curl-to-axios", "curl-to-python-requests"].includes(id)) fail(`Unsupported API conversion: ${id}.`);
|
|
1796
|
+
const source = boundedInput(values);
|
|
1797
|
+
if (!source.trim()) fail("Enter a cURL or Fetch request.");
|
|
1798
|
+
const request = id === "fetch-to-curl" ? parseFetch(source) : parseCurl(source);
|
|
1799
|
+
return resultFor(id, request);
|
|
1800
|
+
} catch (error) {
|
|
1801
|
+
if (error instanceof ApiError) throw new ApiError(error.message, id === "fetch-to-curl" ? "code" : "command");
|
|
1802
|
+
throw error;
|
|
1803
|
+
}
|
|
1804
|
+
}
|
|
1805
|
+
|
|
1806
|
+
// lib/tools/curl-to-code.ts
|
|
1807
|
+
function goEscapeString(str) {
|
|
1808
|
+
return JSON.stringify(str);
|
|
1809
|
+
}
|
|
1810
|
+
function generateGoHttp(req) {
|
|
1811
|
+
const lines = [
|
|
1812
|
+
"package main",
|
|
1813
|
+
"",
|
|
1814
|
+
"import (",
|
|
1815
|
+
' "fmt"',
|
|
1816
|
+
' "io"',
|
|
1817
|
+
' "net/http"'
|
|
1818
|
+
];
|
|
1819
|
+
if (req.body !== void 0 && req.body !== "") {
|
|
1820
|
+
lines.push(' "strings"');
|
|
1821
|
+
}
|
|
1822
|
+
lines.push(")", "", "func main() {", " client := &http.Client{}", "");
|
|
1823
|
+
if (req.body !== void 0 && req.body !== "") {
|
|
1824
|
+
lines.push(` body := strings.NewReader(${goEscapeString(req.body)})`);
|
|
1825
|
+
lines.push(` req, err := http.NewRequest(${goEscapeString(req.method)}, ${goEscapeString(req.url)}, body)`);
|
|
1826
|
+
} else {
|
|
1827
|
+
lines.push(` req, err := http.NewRequest(${goEscapeString(req.method)}, ${goEscapeString(req.url)}, nil)`);
|
|
1828
|
+
}
|
|
1829
|
+
lines.push(" if err != nil {", " panic(err)", " }", "");
|
|
1830
|
+
if (req.headers.length > 0) {
|
|
1831
|
+
for (const [name, val] of req.headers) {
|
|
1832
|
+
lines.push(` req.Header.Set(${goEscapeString(name)}, ${goEscapeString(val)})`);
|
|
1833
|
+
}
|
|
1834
|
+
lines.push("");
|
|
1835
|
+
}
|
|
1836
|
+
lines.push(
|
|
1837
|
+
" resp, err := client.Do(req)",
|
|
1838
|
+
" if err != nil {",
|
|
1839
|
+
" panic(err)",
|
|
1840
|
+
" }",
|
|
1841
|
+
" defer resp.Body.Close()",
|
|
1842
|
+
"",
|
|
1843
|
+
" resBody, err := io.ReadAll(resp.Body)",
|
|
1844
|
+
" if err != nil {",
|
|
1845
|
+
" panic(err)",
|
|
1846
|
+
" }",
|
|
1847
|
+
"",
|
|
1848
|
+
" fmt.Println(string(resBody))",
|
|
1849
|
+
"}"
|
|
1850
|
+
);
|
|
1851
|
+
return lines.join("\n");
|
|
1852
|
+
}
|
|
1853
|
+
async function curlToCode(curlCommand, target = "fetch") {
|
|
1854
|
+
const trimmed = curlCommand.trim();
|
|
1855
|
+
if (!trimmed) {
|
|
1856
|
+
throw new Error("cURL command cannot be empty.");
|
|
1857
|
+
}
|
|
1858
|
+
if (target === "go") {
|
|
1859
|
+
const model = parseCurl(trimmed);
|
|
1860
|
+
const code = generateGoHttp(model);
|
|
1861
|
+
return {
|
|
1862
|
+
code,
|
|
1863
|
+
language: "go",
|
|
1864
|
+
target: "go",
|
|
1865
|
+
warnings: model.warnings || []
|
|
1866
|
+
};
|
|
1867
|
+
}
|
|
1868
|
+
const mapTarget = {
|
|
1869
|
+
fetch: "curl-to-fetch",
|
|
1870
|
+
axios: "curl-to-axios",
|
|
1871
|
+
python: "curl-to-python-requests"
|
|
1872
|
+
};
|
|
1873
|
+
const toolId = mapTarget[target] || "curl-to-fetch";
|
|
1874
|
+
const result = await convertApi(toolId, { command: trimmed });
|
|
1875
|
+
const lang = target === "python" ? "python" : "typescript";
|
|
1876
|
+
return {
|
|
1877
|
+
code: result.text,
|
|
1878
|
+
language: lang,
|
|
1879
|
+
target,
|
|
1880
|
+
warnings: result.warnings || []
|
|
1881
|
+
};
|
|
1882
|
+
}
|
|
1883
|
+
|
|
1884
|
+
// lib/tools/env-audit.ts
|
|
1885
|
+
function parseEnvLines(content) {
|
|
1886
|
+
const lines = content.split(/\r?\n/);
|
|
1887
|
+
const entries = [];
|
|
1888
|
+
const errors = [];
|
|
1889
|
+
for (let i = 0; i < lines.length; i++) {
|
|
1890
|
+
const rawLine = lines[i];
|
|
1891
|
+
const trimmed = rawLine.trim();
|
|
1892
|
+
if (!trimmed || trimmed.startsWith("#")) {
|
|
1893
|
+
continue;
|
|
1894
|
+
}
|
|
1895
|
+
const match = trimmed.match(/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
|
|
1896
|
+
if (!match) {
|
|
1897
|
+
if (trimmed.includes("=")) {
|
|
1898
|
+
const potentialKey = trimmed.split("=")[0].trim();
|
|
1899
|
+
errors.push({
|
|
1900
|
+
line: i + 1,
|
|
1901
|
+
key: potentialKey,
|
|
1902
|
+
severity: "MEDIUM",
|
|
1903
|
+
category: "SYNTAX_ISSUE",
|
|
1904
|
+
message: `Variable key contains invalid identifier characters: "${potentialKey}"`,
|
|
1905
|
+
recommendation: "Ensure environment variable names only use letters, digits, and underscores."
|
|
1906
|
+
});
|
|
1907
|
+
}
|
|
1908
|
+
continue;
|
|
1909
|
+
}
|
|
1910
|
+
const key = match[1];
|
|
1911
|
+
let value = match[2];
|
|
1912
|
+
if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
|
|
1913
|
+
value = value.slice(1, -1);
|
|
1914
|
+
} else {
|
|
1915
|
+
const commentIdx = value.indexOf(" #");
|
|
1916
|
+
if (commentIdx !== -1) {
|
|
1917
|
+
value = value.slice(0, commentIdx).trim();
|
|
1918
|
+
}
|
|
1919
|
+
}
|
|
1920
|
+
entries.push({
|
|
1921
|
+
line: i + 1,
|
|
1922
|
+
key,
|
|
1923
|
+
value,
|
|
1924
|
+
raw: rawLine
|
|
1925
|
+
});
|
|
1926
|
+
}
|
|
1927
|
+
return { entries, errors };
|
|
1928
|
+
}
|
|
1929
|
+
function maskSecret(val) {
|
|
1930
|
+
if (val.length <= 8) return "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022";
|
|
1931
|
+
return val.slice(0, 4) + "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022" + val.slice(-4);
|
|
1932
|
+
}
|
|
1933
|
+
var WEAK_PASSWORD_PATTERNS = /* @__PURE__ */ new Set([
|
|
1934
|
+
"password",
|
|
1935
|
+
"123456",
|
|
1936
|
+
"12345678",
|
|
1937
|
+
"admin",
|
|
1938
|
+
"secret",
|
|
1939
|
+
"test",
|
|
1940
|
+
"changeme",
|
|
1941
|
+
"root",
|
|
1942
|
+
"qwerty"
|
|
1943
|
+
]);
|
|
1944
|
+
function auditEnv(envContent, exampleContent) {
|
|
1945
|
+
const { entries, errors } = parseEnvLines(envContent);
|
|
1946
|
+
const findings = [...errors];
|
|
1947
|
+
const seenKeys = /* @__PURE__ */ new Map();
|
|
1948
|
+
for (const entry of entries) {
|
|
1949
|
+
const { line, key, value } = entry;
|
|
1950
|
+
if (seenKeys.has(key)) {
|
|
1951
|
+
findings.push({
|
|
1952
|
+
line,
|
|
1953
|
+
key,
|
|
1954
|
+
severity: "HIGH",
|
|
1955
|
+
category: "DUPLICATE_KEY",
|
|
1956
|
+
message: `Duplicate key "${key}" already defined at line ${seenKeys.get(key)}`,
|
|
1957
|
+
recommendation: "Remove duplicate definitions; the later entry will silently overwrite earlier ones."
|
|
1958
|
+
});
|
|
1959
|
+
} else {
|
|
1960
|
+
seenKeys.set(key, line);
|
|
1961
|
+
}
|
|
1962
|
+
if (value.trim() === "") {
|
|
1963
|
+
findings.push({
|
|
1964
|
+
line,
|
|
1965
|
+
key,
|
|
1966
|
+
severity: "INFO",
|
|
1967
|
+
category: "EMPTY_VALUE",
|
|
1968
|
+
message: `Variable "${key}" has an empty value`,
|
|
1969
|
+
recommendation: "Provide a default or populate the required configuration value."
|
|
1970
|
+
});
|
|
1971
|
+
continue;
|
|
1972
|
+
}
|
|
1973
|
+
if (/(?:AKIA|ABIA|ACCA|ASIA)[0-9A-Z]{16}/.test(value)) {
|
|
1974
|
+
findings.push({
|
|
1975
|
+
line,
|
|
1976
|
+
key,
|
|
1977
|
+
severity: "CRITICAL",
|
|
1978
|
+
category: "SECRET_LEAK",
|
|
1979
|
+
message: `Live AWS Access Key detected in "${key}"`,
|
|
1980
|
+
recommendation: "Revoke key in AWS IAM immediately and use AWS Secrets Manager or IAM roles.",
|
|
1981
|
+
maskedValue: maskSecret(value)
|
|
1982
|
+
});
|
|
1983
|
+
}
|
|
1984
|
+
if (/(?:sk|rk)_live_[0-9a-zA-Z]{24,}/.test(value)) {
|
|
1985
|
+
findings.push({
|
|
1986
|
+
line,
|
|
1987
|
+
key,
|
|
1988
|
+
severity: "CRITICAL",
|
|
1989
|
+
category: "SECRET_LEAK",
|
|
1990
|
+
message: `Live Stripe Secret Key detected in "${key}"`,
|
|
1991
|
+
recommendation: "Roll this key in the Stripe dashboard. Never commit live secret keys to version control.",
|
|
1992
|
+
maskedValue: maskSecret(value)
|
|
1993
|
+
});
|
|
1994
|
+
}
|
|
1995
|
+
if (/gh[pousr]_[0-9a-zA-Z]{36}/.test(value) || /github_pat_[0-9a-zA-Z_]{82}/.test(value)) {
|
|
1996
|
+
findings.push({
|
|
1997
|
+
line,
|
|
1998
|
+
key,
|
|
1999
|
+
severity: "CRITICAL",
|
|
2000
|
+
category: "SECRET_LEAK",
|
|
2001
|
+
message: `GitHub Personal Access Token detected in "${key}"`,
|
|
2002
|
+
recommendation: "Revoke token under GitHub Settings > Developer settings > Personal access tokens.",
|
|
2003
|
+
maskedValue: maskSecret(value)
|
|
2004
|
+
});
|
|
2005
|
+
}
|
|
2006
|
+
if (/sk-(?:proj-|live-)?[a-zA-Z0-9_-]{32,}/.test(value)) {
|
|
2007
|
+
findings.push({
|
|
2008
|
+
line,
|
|
2009
|
+
key,
|
|
2010
|
+
severity: "HIGH",
|
|
2011
|
+
category: "SECRET_LEAK",
|
|
2012
|
+
message: `OpenAI API Key detected in "${key}"`,
|
|
2013
|
+
recommendation: "Rotate this key in OpenAI platform dashboard.",
|
|
2014
|
+
maskedValue: maskSecret(value)
|
|
2015
|
+
});
|
|
2016
|
+
}
|
|
2017
|
+
if (/sk-ant-[a-zA-Z0-9_-]{32,}/.test(value)) {
|
|
2018
|
+
findings.push({
|
|
2019
|
+
line,
|
|
2020
|
+
key,
|
|
2021
|
+
severity: "HIGH",
|
|
2022
|
+
category: "SECRET_LEAK",
|
|
2023
|
+
message: `Anthropic API Key detected in "${key}"`,
|
|
2024
|
+
recommendation: "Rotate this key in Anthropic Console.",
|
|
2025
|
+
maskedValue: maskSecret(value)
|
|
2026
|
+
});
|
|
2027
|
+
}
|
|
2028
|
+
if (/xox[baprs]-[0-9a-zA-Z]{10,48}/.test(value)) {
|
|
2029
|
+
findings.push({
|
|
2030
|
+
line,
|
|
2031
|
+
key,
|
|
2032
|
+
severity: "HIGH",
|
|
2033
|
+
category: "SECRET_LEAK",
|
|
2034
|
+
message: `Slack Token detected in "${key}"`,
|
|
2035
|
+
recommendation: "Rotate token in Slack API app settings.",
|
|
2036
|
+
maskedValue: maskSecret(value)
|
|
2037
|
+
});
|
|
2038
|
+
}
|
|
2039
|
+
if (/-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/.test(value)) {
|
|
2040
|
+
findings.push({
|
|
2041
|
+
line,
|
|
2042
|
+
key,
|
|
2043
|
+
severity: "CRITICAL",
|
|
2044
|
+
category: "SECRET_LEAK",
|
|
2045
|
+
message: `Asymmetric Private Key detected in "${key}"`,
|
|
2046
|
+
recommendation: "Store private keys in a secure key vault or file, never unencrypted in environment variables.",
|
|
2047
|
+
maskedValue: "\u2022\u2022\u2022\u2022\u2022[PRIVATE KEY]\u2022\u2022\u2022\u2022\u2022"
|
|
2048
|
+
});
|
|
2049
|
+
}
|
|
2050
|
+
const lowerKey = key.toLowerCase();
|
|
2051
|
+
if ((lowerKey.includes("pass") || lowerKey.includes("pwd") || lowerKey.includes("secret")) && WEAK_PASSWORD_PATTERNS.has(value.toLowerCase())) {
|
|
2052
|
+
findings.push({
|
|
2053
|
+
line,
|
|
2054
|
+
key,
|
|
2055
|
+
severity: "HIGH",
|
|
2056
|
+
category: "WEAK_VALUE",
|
|
2057
|
+
message: `Weak / default value detected for "${key}": "${value}"`,
|
|
2058
|
+
recommendation: "Generate a cryptographically random secret with at least 32 characters."
|
|
2059
|
+
});
|
|
2060
|
+
}
|
|
2061
|
+
}
|
|
2062
|
+
if (exampleContent) {
|
|
2063
|
+
const { entries: exampleEntries } = parseEnvLines(exampleContent);
|
|
2064
|
+
const exampleKeyMap = /* @__PURE__ */ new Map();
|
|
2065
|
+
for (const e of exampleEntries) {
|
|
2066
|
+
exampleKeyMap.set(e.key, e.line);
|
|
2067
|
+
}
|
|
2068
|
+
for (const [eKey] of exampleKeyMap) {
|
|
2069
|
+
if (!seenKeys.has(eKey)) {
|
|
2070
|
+
findings.push({
|
|
2071
|
+
key: eKey,
|
|
2072
|
+
severity: "HIGH",
|
|
2073
|
+
category: "MISSING_VAR",
|
|
2074
|
+
message: `Variable "${eKey}" documented in .env.example is missing from your environment`,
|
|
2075
|
+
recommendation: `Add "${eKey}" to your .env file or local environment.`
|
|
2076
|
+
});
|
|
2077
|
+
}
|
|
2078
|
+
}
|
|
2079
|
+
for (const [actualKey, line] of seenKeys) {
|
|
2080
|
+
if (!exampleKeyMap.has(actualKey)) {
|
|
2081
|
+
findings.push({
|
|
2082
|
+
line,
|
|
2083
|
+
key: actualKey,
|
|
2084
|
+
severity: "LOW",
|
|
2085
|
+
category: "EXTRA_VAR",
|
|
2086
|
+
message: `Variable "${actualKey}" is present in .env but undocumented in .env.example`,
|
|
2087
|
+
recommendation: `Document "${actualKey}" in .env.example for teammates and CI setups.`
|
|
2088
|
+
});
|
|
2089
|
+
}
|
|
2090
|
+
}
|
|
2091
|
+
}
|
|
2092
|
+
const stats = { critical: 0, high: 0, medium: 0, low: 0, info: 0 };
|
|
2093
|
+
for (const f of findings) {
|
|
2094
|
+
if (f.severity === "CRITICAL") stats.critical++;
|
|
2095
|
+
else if (f.severity === "HIGH") stats.high++;
|
|
2096
|
+
else if (f.severity === "MEDIUM") stats.medium++;
|
|
2097
|
+
else if (f.severity === "LOW") stats.low++;
|
|
2098
|
+
else if (f.severity === "INFO") stats.info++;
|
|
2099
|
+
}
|
|
2100
|
+
const isSecure = stats.critical === 0 && stats.high === 0;
|
|
2101
|
+
const summary = isSecure ? `\u2705 Audit Passed: ${entries.length} variables analyzed. No critical secrets or high-severity vulnerabilities found.` : `\u26A0\uFE0F Audit Warning: Found ${stats.critical} critical and ${stats.high} high severity issues out of ${entries.length} variables.`;
|
|
2102
|
+
return {
|
|
2103
|
+
totalVariables: entries.length,
|
|
2104
|
+
findings,
|
|
2105
|
+
stats,
|
|
2106
|
+
isSecure,
|
|
2107
|
+
summary
|
|
2108
|
+
};
|
|
2109
|
+
}
|
|
2110
|
+
function formatEnvAuditReport(result) {
|
|
2111
|
+
const lines = [];
|
|
2112
|
+
lines.push("\n=== CODE STATION ENVIRONMENT AUDIT REPORT ===");
|
|
2113
|
+
lines.push(`Total Variables: ${result.totalVariables}`);
|
|
2114
|
+
lines.push(
|
|
2115
|
+
`Findings: ${result.findings.length} (Critical: ${result.stats.critical}, High: ${result.stats.high}, Medium: ${result.stats.medium}, Low: ${result.stats.low}, Info: ${result.stats.info})`
|
|
2116
|
+
);
|
|
2117
|
+
lines.push(`Status: ${result.summary}
|
|
2118
|
+
`);
|
|
2119
|
+
if (result.findings.length === 0) {
|
|
2120
|
+
lines.push("\u2728 Clean! No security issues or synchronization discrepancies detected.\n");
|
|
2121
|
+
return lines.join("\n");
|
|
2122
|
+
}
|
|
2123
|
+
lines.push("--- Detailed Findings ---");
|
|
2124
|
+
for (const f of result.findings) {
|
|
2125
|
+
const loc = f.line ? `[Line ${f.line}] ` : "";
|
|
2126
|
+
const badge = `[${f.severity}]`.padEnd(11);
|
|
2127
|
+
lines.push(`${badge} ${loc}${f.key}: ${f.message}`);
|
|
2128
|
+
if (f.maskedValue) {
|
|
2129
|
+
lines.push(` Masked: ${f.maskedValue}`);
|
|
2130
|
+
}
|
|
2131
|
+
lines.push(` Fix: ${f.recommendation}`);
|
|
2132
|
+
}
|
|
2133
|
+
lines.push("");
|
|
2134
|
+
return lines.join("\n");
|
|
2135
|
+
}
|
|
2136
|
+
|
|
2137
|
+
// lib/tools/mock-data.ts
|
|
2138
|
+
var Prng = class {
|
|
2139
|
+
constructor(seed) {
|
|
2140
|
+
this.state = seed !== void 0 ? seed : Math.floor(Math.random() * 2147483647);
|
|
2141
|
+
}
|
|
2142
|
+
next() {
|
|
2143
|
+
this.state = this.state * 16807 % 2147483647;
|
|
2144
|
+
return (this.state - 1) / 2147483646;
|
|
2145
|
+
}
|
|
2146
|
+
int(min, max) {
|
|
2147
|
+
return Math.floor(this.next() * (max - min + 1)) + min;
|
|
2148
|
+
}
|
|
2149
|
+
pick(items) {
|
|
2150
|
+
return items[Math.floor(this.next() * items.length)];
|
|
2151
|
+
}
|
|
2152
|
+
uuid() {
|
|
2153
|
+
const hex2 = "0123456789abcdef";
|
|
2154
|
+
let s = "";
|
|
2155
|
+
for (let i = 0; i < 36; i++) {
|
|
2156
|
+
if (i === 8 || i === 13 || i === 18 || i === 23) {
|
|
2157
|
+
s += "-";
|
|
2158
|
+
} else if (i === 14) {
|
|
2159
|
+
s += "4";
|
|
2160
|
+
} else if (i === 19) {
|
|
2161
|
+
s += hex2[Math.floor(this.next() * 4) + 8];
|
|
2162
|
+
} else {
|
|
2163
|
+
s += hex2[Math.floor(this.next() * 16)];
|
|
2164
|
+
}
|
|
2165
|
+
}
|
|
2166
|
+
return s;
|
|
2167
|
+
}
|
|
2168
|
+
};
|
|
2169
|
+
var FIRST_NAMES = [
|
|
2170
|
+
"Ada",
|
|
2171
|
+
"Alan",
|
|
2172
|
+
"Linus",
|
|
2173
|
+
"Grace",
|
|
2174
|
+
"Tim",
|
|
2175
|
+
"Margaret",
|
|
2176
|
+
"Donald",
|
|
2177
|
+
"Barbara",
|
|
2178
|
+
"Guido",
|
|
2179
|
+
"Ken",
|
|
2180
|
+
"Dennis",
|
|
2181
|
+
"Bjarne",
|
|
2182
|
+
"James",
|
|
2183
|
+
"Brendan",
|
|
2184
|
+
"Sophie",
|
|
2185
|
+
"Leslie",
|
|
2186
|
+
"Edsger",
|
|
2187
|
+
"Claude",
|
|
2188
|
+
"Radia",
|
|
2189
|
+
"Katherine"
|
|
2190
|
+
];
|
|
2191
|
+
var LAST_NAMES = [
|
|
2192
|
+
"Lovelace",
|
|
2193
|
+
"Turing",
|
|
2194
|
+
"Torvalds",
|
|
2195
|
+
"Hopper",
|
|
2196
|
+
"Berners-Lee",
|
|
2197
|
+
"Hamilton",
|
|
2198
|
+
"Knuth",
|
|
2199
|
+
"Liskov",
|
|
2200
|
+
"van Rossum",
|
|
2201
|
+
"Thompson",
|
|
2202
|
+
"Ritchie",
|
|
2203
|
+
"Stroustrup",
|
|
2204
|
+
"Gosling",
|
|
2205
|
+
"Eich",
|
|
2206
|
+
"Wilson",
|
|
2207
|
+
"Lamport",
|
|
2208
|
+
"Dijkstra",
|
|
2209
|
+
"Shannon",
|
|
2210
|
+
"Perlman",
|
|
2211
|
+
"Johnson"
|
|
2212
|
+
];
|
|
2213
|
+
var DOMAINS = ["example.com", "codestation.in", "acme.dev", "testmail.org", "infra.net"];
|
|
2214
|
+
var CITIES = ["San Francisco", "London", "Bengaluru", "Berlin", "Tokyo", "Seattle", "Toronto", "Sydney", "Singapore", "Amsterdam"];
|
|
2215
|
+
var COUNTRIES = ["United States", "United Kingdom", "India", "Germany", "Japan", "Canada", "Australia", "Singapore", "Netherlands", "France"];
|
|
2216
|
+
var PRODUCT_PREFIXES = ["Pro", "Cloud", "Hyper", "Ultra", "Tactile", "Quantum", "Nexus", "Dev", "Micro", "Turbo"];
|
|
2217
|
+
var PRODUCT_NOUNS = ["Station", "Terminal", "Gateway", "Engine", "Workspace", "Proxy", "Optimizer", "Parser", "Vault", "Pipeline"];
|
|
2218
|
+
var CATEGORIES = ["Developer Tools", "Cloud Services", "Security & Auth", "Database", "Networking", "Analytics"];
|
|
2219
|
+
var ROLES = ["admin", "developer", "maintainer", "viewer", "operator"];
|
|
2220
|
+
var STATUSES = ["active", "pending", "suspended", "archived"];
|
|
2221
|
+
var ORDER_STATUSES = ["completed", "processing", "shipped", "refunded"];
|
|
2222
|
+
var PAYMENT_METHODS = ["card", "upi", "netbanking", "wire"];
|
|
2223
|
+
function generateFieldValue(type, prng, context) {
|
|
2224
|
+
switch (type) {
|
|
2225
|
+
case "uuid":
|
|
2226
|
+
return prng.uuid();
|
|
2227
|
+
case "firstName":
|
|
2228
|
+
return prng.pick(FIRST_NAMES);
|
|
2229
|
+
case "lastName":
|
|
2230
|
+
return prng.pick(LAST_NAMES);
|
|
2231
|
+
case "name": {
|
|
2232
|
+
const f = prng.pick(FIRST_NAMES);
|
|
2233
|
+
const l = prng.pick(LAST_NAMES);
|
|
2234
|
+
return `${f} ${l}`;
|
|
2235
|
+
}
|
|
2236
|
+
case "email": {
|
|
2237
|
+
const f = (context.firstName || prng.pick(FIRST_NAMES)).toLowerCase();
|
|
2238
|
+
const l = (context.lastName || prng.pick(LAST_NAMES)).toLowerCase();
|
|
2239
|
+
const num = prng.int(10, 99);
|
|
2240
|
+
const domain = prng.pick(DOMAINS);
|
|
2241
|
+
return `${f}.${l}${num}@${domain}`;
|
|
2242
|
+
}
|
|
2243
|
+
case "number":
|
|
2244
|
+
return prng.int(1, 1e3);
|
|
2245
|
+
case "price":
|
|
2246
|
+
return parseFloat((prng.int(10, 500) + prng.int(0, 99) / 100).toFixed(2));
|
|
2247
|
+
case "boolean":
|
|
2248
|
+
return prng.next() > 0.5;
|
|
2249
|
+
case "date": {
|
|
2250
|
+
const pastDays = prng.int(1, 180);
|
|
2251
|
+
const d = new Date(Date.now() - pastDays * 24 * 60 * 60 * 1e3);
|
|
2252
|
+
return d.toISOString();
|
|
2253
|
+
}
|
|
2254
|
+
case "status":
|
|
2255
|
+
return prng.pick(STATUSES);
|
|
2256
|
+
case "role":
|
|
2257
|
+
return prng.pick(ROLES);
|
|
2258
|
+
case "city":
|
|
2259
|
+
return prng.pick(CITIES);
|
|
2260
|
+
case "country":
|
|
2261
|
+
return prng.pick(COUNTRIES);
|
|
2262
|
+
case "sku": {
|
|
2263
|
+
const prefix = prng.pick(PRODUCT_PREFIXES).toUpperCase().slice(0, 3);
|
|
2264
|
+
return `${prefix}-${prng.int(1e3, 9999)}`;
|
|
2265
|
+
}
|
|
2266
|
+
case "phone":
|
|
2267
|
+
return `+1-555-${prng.int(100, 999)}-${prng.int(1e3, 9999)}`;
|
|
2268
|
+
default:
|
|
2269
|
+
return "mock_value";
|
|
2270
|
+
}
|
|
2271
|
+
}
|
|
2272
|
+
function escapeSqlValue(val) {
|
|
2273
|
+
if (val === null || val === void 0) return "NULL";
|
|
2274
|
+
if (typeof val === "number") return String(val);
|
|
2275
|
+
if (typeof val === "boolean") return val ? "TRUE" : "FALSE";
|
|
2276
|
+
if (typeof val === "object") return `'${JSON.stringify(val).replace(/'/g, "''")}'`;
|
|
2277
|
+
return `'${String(val).replace(/'/g, "''")}'`;
|
|
2278
|
+
}
|
|
2279
|
+
function generateMockDataset(options = {}) {
|
|
2280
|
+
const {
|
|
2281
|
+
template = "users",
|
|
2282
|
+
count = 10,
|
|
2283
|
+
format = "json",
|
|
2284
|
+
tableName = template,
|
|
2285
|
+
customSchema,
|
|
2286
|
+
seed
|
|
2287
|
+
} = options;
|
|
2288
|
+
const validCount = Math.max(1, Math.min(count, 1e3));
|
|
2289
|
+
const prng = new Prng(seed);
|
|
2290
|
+
const records = [];
|
|
2291
|
+
for (let i = 0; i < validCount; i++) {
|
|
2292
|
+
const row = {};
|
|
2293
|
+
if (template === "users") {
|
|
2294
|
+
const first = prng.pick(FIRST_NAMES);
|
|
2295
|
+
const last = prng.pick(LAST_NAMES);
|
|
2296
|
+
row.id = prng.uuid();
|
|
2297
|
+
row.first_name = first;
|
|
2298
|
+
row.last_name = last;
|
|
2299
|
+
row.name = `${first} ${last}`;
|
|
2300
|
+
row.email = `${first.toLowerCase()}.${last.toLowerCase()}${prng.int(10, 99)}@${prng.pick(DOMAINS)}`;
|
|
2301
|
+
row.role = prng.pick(ROLES);
|
|
2302
|
+
row.status = prng.pick(STATUSES);
|
|
2303
|
+
row.created_at = new Date(Date.now() - prng.int(1, 180) * 864e5).toISOString();
|
|
2304
|
+
} else if (template === "products") {
|
|
2305
|
+
const pName = `${prng.pick(PRODUCT_PREFIXES)} ${prng.pick(PRODUCT_NOUNS)}`;
|
|
2306
|
+
row.id = prng.uuid();
|
|
2307
|
+
row.sku = `SKU-${prng.int(1e3, 9999)}`;
|
|
2308
|
+
row.title = pName;
|
|
2309
|
+
row.category = prng.pick(CATEGORIES);
|
|
2310
|
+
row.price = parseFloat((prng.int(19, 499) + 0.99).toFixed(2));
|
|
2311
|
+
row.stock = prng.int(0, 250);
|
|
2312
|
+
row.in_stock = row.stock > 0;
|
|
2313
|
+
} else if (template === "orders") {
|
|
2314
|
+
row.id = prng.uuid();
|
|
2315
|
+
row.order_number = `ORD-${prng.int(1e4, 99999)}`;
|
|
2316
|
+
row.customer_email = `${prng.pick(FIRST_NAMES).toLowerCase()}@${prng.pick(DOMAINS)}`;
|
|
2317
|
+
row.total = parseFloat((prng.int(25, 1200) + prng.int(0, 99) / 100).toFixed(2));
|
|
2318
|
+
row.status = prng.pick(ORDER_STATUSES);
|
|
2319
|
+
row.payment_method = prng.pick(PAYMENT_METHODS);
|
|
2320
|
+
row.items_count = prng.int(1, 8);
|
|
2321
|
+
row.created_at = new Date(Date.now() - prng.int(1, 90) * 864e5).toISOString();
|
|
2322
|
+
} else if (template === "custom" && customSchema) {
|
|
2323
|
+
for (const [col, colType] of Object.entries(customSchema)) {
|
|
2324
|
+
row[col] = generateFieldValue(colType, prng, row);
|
|
2325
|
+
}
|
|
2326
|
+
} else {
|
|
2327
|
+
row.id = prng.uuid();
|
|
2328
|
+
row.name = `${prng.pick(FIRST_NAMES)} ${prng.pick(LAST_NAMES)}`;
|
|
2329
|
+
}
|
|
2330
|
+
records.push(row);
|
|
2331
|
+
}
|
|
2332
|
+
const jsonStr = JSON.stringify(records, null, 2);
|
|
2333
|
+
let sqlStr;
|
|
2334
|
+
if (format === "sql" || options.tableName) {
|
|
2335
|
+
if (records.length > 0) {
|
|
2336
|
+
const columns = Object.keys(records[0]);
|
|
2337
|
+
const colList = columns.join(", ");
|
|
2338
|
+
const valueRows = records.map((r) => {
|
|
2339
|
+
const rowVals = columns.map((c) => escapeSqlValue(r[c])).join(", ");
|
|
2340
|
+
return ` (${rowVals})`;
|
|
2341
|
+
});
|
|
2342
|
+
sqlStr = `INSERT INTO ${tableName} (${colList})
|
|
2343
|
+
VALUES
|
|
2344
|
+
${valueRows.join(",\n")};`;
|
|
2345
|
+
}
|
|
2346
|
+
}
|
|
2347
|
+
return {
|
|
2348
|
+
data: records,
|
|
2349
|
+
json: jsonStr,
|
|
2350
|
+
sql: sqlStr,
|
|
2351
|
+
count: records.length
|
|
2352
|
+
};
|
|
2353
|
+
}
|
|
2354
|
+
|
|
2355
|
+
// lib/tools/git-conflict.ts
|
|
2356
|
+
function parseAndResolveGitConflicts(content, strategy = "analyze") {
|
|
2357
|
+
const lines = content.split(/\r?\n/);
|
|
2358
|
+
const hunks = [];
|
|
2359
|
+
let inConflict = false;
|
|
2360
|
+
let inBase = false;
|
|
2361
|
+
let inTheirs = false;
|
|
2362
|
+
let currentHunkStart = 0;
|
|
2363
|
+
let currentOursBranch = "";
|
|
2364
|
+
let currentTheirsBranch = "";
|
|
2365
|
+
let currentOursLines = [];
|
|
2366
|
+
let currentBaseLines = [];
|
|
2367
|
+
let currentTheirsLines = [];
|
|
2368
|
+
const outputLines = [];
|
|
2369
|
+
for (let i = 0; i < lines.length; i++) {
|
|
2370
|
+
const line = lines[i];
|
|
2371
|
+
if (line.startsWith("<<<<<<<")) {
|
|
2372
|
+
if (inConflict) {
|
|
2373
|
+
throw new Error(`Malformed Git conflict: Nested <<<<<<< marker at line ${i + 1}`);
|
|
2374
|
+
}
|
|
2375
|
+
inConflict = true;
|
|
2376
|
+
inBase = false;
|
|
2377
|
+
inTheirs = false;
|
|
2378
|
+
currentHunkStart = i + 1;
|
|
2379
|
+
currentOursBranch = line.slice(7).trim() || "HEAD";
|
|
2380
|
+
currentOursLines = [];
|
|
2381
|
+
currentBaseLines = [];
|
|
2382
|
+
currentTheirsLines = [];
|
|
2383
|
+
continue;
|
|
2384
|
+
}
|
|
2385
|
+
if (inConflict && !inTheirs && line.startsWith("|||||||")) {
|
|
2386
|
+
inBase = true;
|
|
2387
|
+
continue;
|
|
2388
|
+
}
|
|
2389
|
+
if (inConflict && !inTheirs && line.startsWith("=======")) {
|
|
2390
|
+
inBase = false;
|
|
2391
|
+
inTheirs = true;
|
|
2392
|
+
continue;
|
|
2393
|
+
}
|
|
2394
|
+
if (inConflict && inTheirs && line.startsWith(">>>>>>>")) {
|
|
2395
|
+
currentTheirsBranch = line.slice(7).trim() || "incoming";
|
|
2396
|
+
const hunk = {
|
|
2397
|
+
hunkIndex: hunks.length + 1,
|
|
2398
|
+
startLine: currentHunkStart,
|
|
2399
|
+
endLine: i + 1,
|
|
2400
|
+
oursBranch: currentOursBranch,
|
|
2401
|
+
theirsBranch: currentTheirsBranch,
|
|
2402
|
+
oursLines: currentOursLines,
|
|
2403
|
+
theirsLines: currentTheirsLines,
|
|
2404
|
+
...currentBaseLines.length > 0 ? { baseLines: currentBaseLines } : {}
|
|
2405
|
+
};
|
|
2406
|
+
hunks.push(hunk);
|
|
2407
|
+
if (strategy === "ours") {
|
|
2408
|
+
outputLines.push(...currentOursLines);
|
|
2409
|
+
} else if (strategy === "theirs") {
|
|
2410
|
+
outputLines.push(...currentTheirsLines);
|
|
2411
|
+
} else if (strategy === "both") {
|
|
2412
|
+
outputLines.push(...currentOursLines);
|
|
2413
|
+
outputLines.push(...currentTheirsLines);
|
|
2414
|
+
}
|
|
2415
|
+
inConflict = false;
|
|
2416
|
+
inBase = false;
|
|
2417
|
+
inTheirs = false;
|
|
2418
|
+
continue;
|
|
2419
|
+
}
|
|
2420
|
+
if (inConflict) {
|
|
2421
|
+
if (inTheirs) {
|
|
2422
|
+
currentTheirsLines.push(line);
|
|
2423
|
+
} else if (inBase) {
|
|
2424
|
+
currentBaseLines.push(line);
|
|
2425
|
+
} else {
|
|
2426
|
+
currentOursLines.push(line);
|
|
2427
|
+
}
|
|
2428
|
+
} else {
|
|
2429
|
+
outputLines.push(line);
|
|
2430
|
+
}
|
|
2431
|
+
}
|
|
2432
|
+
if (inConflict) {
|
|
2433
|
+
throw new Error(`Malformed Git conflict: Unclosed conflict marker starting at line ${currentHunkStart}`);
|
|
2434
|
+
}
|
|
2435
|
+
const hasConflicts = hunks.length > 0;
|
|
2436
|
+
const resolvedContent = strategy !== "analyze" ? outputLines.join("\n") : void 0;
|
|
2437
|
+
let summary = "";
|
|
2438
|
+
if (!hasConflicts) {
|
|
2439
|
+
summary = "No merge conflict markers detected in input.";
|
|
2440
|
+
} else if (strategy === "analyze") {
|
|
2441
|
+
summary = `Found ${hunks.length} conflict hunk${hunks.length === 1 ? "" : "s"}. Inspect branches and choose a resolution strategy (ours, theirs, or both).`;
|
|
2442
|
+
} else {
|
|
2443
|
+
summary = `Successfully resolved ${hunks.length} conflict hunk${hunks.length === 1 ? "" : "s"} using "${strategy}" strategy.`;
|
|
2444
|
+
}
|
|
2445
|
+
return {
|
|
2446
|
+
hasConflicts,
|
|
2447
|
+
conflictCount: hunks.length,
|
|
2448
|
+
hunks,
|
|
2449
|
+
resolvedContent,
|
|
2450
|
+
summary
|
|
2451
|
+
};
|
|
2452
|
+
}
|
|
2453
|
+
function formatConflictReport(result) {
|
|
2454
|
+
const lines = [];
|
|
2455
|
+
lines.push("\n=== CODE STATION GIT CONFLICT RESOLVER ===");
|
|
2456
|
+
lines.push(`Total Conflicts: ${result.conflictCount}`);
|
|
2457
|
+
lines.push(`Status: ${result.summary}
|
|
2458
|
+
`);
|
|
2459
|
+
if (!result.hasConflicts) {
|
|
2460
|
+
return lines.join("\n");
|
|
2461
|
+
}
|
|
2462
|
+
for (const hunk of result.hunks) {
|
|
2463
|
+
lines.push(`[Hunk #${hunk.hunkIndex}] Lines ${hunk.startLine} to ${hunk.endLine}`);
|
|
2464
|
+
lines.push(` Ours (${hunk.oursBranch}): ${hunk.oursLines.length} lines`);
|
|
2465
|
+
lines.push(` Theirs (${hunk.theirsBranch}): ${hunk.theirsLines.length} lines`);
|
|
2466
|
+
lines.push(" Preview Ours:");
|
|
2467
|
+
for (const l of hunk.oursLines.slice(0, 3)) {
|
|
2468
|
+
lines.push(` | ${l}`);
|
|
2469
|
+
}
|
|
2470
|
+
if (hunk.oursLines.length > 3) lines.push(` | ... (+${hunk.oursLines.length - 3} more lines)`);
|
|
2471
|
+
lines.push(" Preview Theirs:");
|
|
2472
|
+
for (const l of hunk.theirsLines.slice(0, 3)) {
|
|
2473
|
+
lines.push(` | ${l}`);
|
|
2474
|
+
}
|
|
2475
|
+
if (hunk.theirsLines.length > 3) lines.push(` | ... (+${hunk.theirsLines.length - 3} more lines)`);
|
|
2476
|
+
lines.push("");
|
|
2477
|
+
}
|
|
2478
|
+
return lines.join("\n");
|
|
2479
|
+
}
|
|
2480
|
+
|
|
1169
2481
|
// mcp/server.ts
|
|
1170
2482
|
function createMcpServer(cliKey) {
|
|
1171
2483
|
const license = resolveLicense(cliKey);
|
|
1172
2484
|
const server = new Server(
|
|
1173
2485
|
{
|
|
1174
2486
|
name: "codestation-mcp",
|
|
1175
|
-
version: "1.
|
|
2487
|
+
version: "1.2.0"
|
|
1176
2488
|
},
|
|
1177
2489
|
{
|
|
1178
2490
|
capabilities: {
|
|
@@ -1498,6 +2810,88 @@ function createMcpServer(cliKey) {
|
|
|
1498
2810
|
},
|
|
1499
2811
|
required: ["json"]
|
|
1500
2812
|
}
|
|
2813
|
+
},
|
|
2814
|
+
{
|
|
2815
|
+
name: "codestation_curl_to_code",
|
|
2816
|
+
description: "Convert cURL commands to TypeScript fetch/axios, Python requests, or Go net/http. [Pro Tier: \u20B9199/mo or $2.99/mo]",
|
|
2817
|
+
inputSchema: {
|
|
2818
|
+
type: "object",
|
|
2819
|
+
properties: {
|
|
2820
|
+
curl: { type: "string", description: "cURL command string" },
|
|
2821
|
+
target: {
|
|
2822
|
+
type: "string",
|
|
2823
|
+
enum: ["fetch", "axios", "python", "go"],
|
|
2824
|
+
description: "Target programming language/library (default: 'fetch')"
|
|
2825
|
+
}
|
|
2826
|
+
},
|
|
2827
|
+
required: ["curl"]
|
|
2828
|
+
}
|
|
2829
|
+
},
|
|
2830
|
+
{
|
|
2831
|
+
name: "codestation_env_audit",
|
|
2832
|
+
description: "Scan environment variables for secret leaks (Stripe, AWS, OpenAI, GitHub PAT, private keys) and validate against .env.example. [Pro Tier: \u20B9199/mo or $2.99/mo]",
|
|
2833
|
+
inputSchema: {
|
|
2834
|
+
type: "object",
|
|
2835
|
+
properties: {
|
|
2836
|
+
env: { type: "string", description: "Contents of the .env file" },
|
|
2837
|
+
example: { type: "string", description: "Optional contents of .env.example to diff against" },
|
|
2838
|
+
format: {
|
|
2839
|
+
type: "string",
|
|
2840
|
+
enum: ["report", "json"],
|
|
2841
|
+
description: "Output format (default: 'report')"
|
|
2842
|
+
}
|
|
2843
|
+
},
|
|
2844
|
+
required: ["env"]
|
|
2845
|
+
}
|
|
2846
|
+
},
|
|
2847
|
+
{
|
|
2848
|
+
name: "codestation_mock_data",
|
|
2849
|
+
description: "Generate realistic mock data and SQL seeders for users, products, orders, or custom schemas. [Pro Tier: \u20B9199/mo or $2.99/mo]",
|
|
2850
|
+
inputSchema: {
|
|
2851
|
+
type: "object",
|
|
2852
|
+
properties: {
|
|
2853
|
+
template: {
|
|
2854
|
+
type: "string",
|
|
2855
|
+
enum: ["users", "products", "orders", "custom"],
|
|
2856
|
+
description: "Template type (default: 'users')"
|
|
2857
|
+
},
|
|
2858
|
+
count: {
|
|
2859
|
+
type: "integer",
|
|
2860
|
+
minimum: 1,
|
|
2861
|
+
maximum: 1e3,
|
|
2862
|
+
description: "Number of records to generate (default: 10)"
|
|
2863
|
+
},
|
|
2864
|
+
format: {
|
|
2865
|
+
type: "string",
|
|
2866
|
+
enum: ["json", "sql"],
|
|
2867
|
+
description: "Output format (default: 'json')"
|
|
2868
|
+
},
|
|
2869
|
+
tableName: {
|
|
2870
|
+
type: "string",
|
|
2871
|
+
description: "Optional SQL table name (defaults to template name)"
|
|
2872
|
+
},
|
|
2873
|
+
customSchema: {
|
|
2874
|
+
type: "object",
|
|
2875
|
+
description: "Optional custom schema mapping field names to types (uuid, name, email, price, date, boolean, number, status, role)"
|
|
2876
|
+
}
|
|
2877
|
+
}
|
|
2878
|
+
}
|
|
2879
|
+
},
|
|
2880
|
+
{
|
|
2881
|
+
name: "codestation_git_conflict",
|
|
2882
|
+
description: "Parse and resolve Git merge conflict markers (<<<<<<< HEAD, =======, >>>>>>>). [Pro Tier: \u20B9199/mo or $2.99/mo]",
|
|
2883
|
+
inputSchema: {
|
|
2884
|
+
type: "object",
|
|
2885
|
+
properties: {
|
|
2886
|
+
content: { type: "string", description: "File content containing Git conflict markers" },
|
|
2887
|
+
strategy: {
|
|
2888
|
+
type: "string",
|
|
2889
|
+
enum: ["analyze", "ours", "theirs", "both"],
|
|
2890
|
+
description: "Resolution strategy: analyze (report), ours (keep current), theirs (keep incoming), or both (keep both). Default: 'analyze'"
|
|
2891
|
+
}
|
|
2892
|
+
},
|
|
2893
|
+
required: ["content"]
|
|
2894
|
+
}
|
|
1501
2895
|
}
|
|
1502
2896
|
];
|
|
1503
2897
|
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
@@ -1676,6 +3070,42 @@ function createMcpServer(cliKey) {
|
|
|
1676
3070
|
outputText = jsonToZod(json, rootName);
|
|
1677
3071
|
break;
|
|
1678
3072
|
}
|
|
3073
|
+
case "codestation_curl_to_code": {
|
|
3074
|
+
const curl = String(args.curl ?? "");
|
|
3075
|
+
const target = args.target ? String(args.target) : "fetch";
|
|
3076
|
+
const result = await curlToCode(curl, target);
|
|
3077
|
+
outputText = result.code;
|
|
3078
|
+
break;
|
|
3079
|
+
}
|
|
3080
|
+
case "codestation_env_audit": {
|
|
3081
|
+
const env = String(args.env ?? "");
|
|
3082
|
+
const example = args.example ? String(args.example) : void 0;
|
|
3083
|
+
const format = args.format ? String(args.format) : "report";
|
|
3084
|
+
const result = auditEnv(env, example);
|
|
3085
|
+
outputText = format === "json" ? JSON.stringify(result, null, 2) : formatEnvAuditReport(result);
|
|
3086
|
+
break;
|
|
3087
|
+
}
|
|
3088
|
+
case "codestation_mock_data": {
|
|
3089
|
+
const template = args.template ? String(args.template) : "users";
|
|
3090
|
+
const count = args.count ? Number(args.count) : 10;
|
|
3091
|
+
const format = args.format ? String(args.format) : "json";
|
|
3092
|
+
const tableName = args.tableName ? String(args.tableName) : void 0;
|
|
3093
|
+
const customSchema = args.customSchema;
|
|
3094
|
+
const result = generateMockDataset({ template, count, format, tableName, customSchema });
|
|
3095
|
+
outputText = format === "sql" && result.sql ? result.sql : result.json;
|
|
3096
|
+
break;
|
|
3097
|
+
}
|
|
3098
|
+
case "codestation_git_conflict": {
|
|
3099
|
+
const content = String(args.content ?? "");
|
|
3100
|
+
const strategy = args.strategy ? String(args.strategy) : "analyze";
|
|
3101
|
+
const result = parseAndResolveGitConflicts(content, strategy);
|
|
3102
|
+
if (strategy === "analyze") {
|
|
3103
|
+
outputText = formatConflictReport(result);
|
|
3104
|
+
} else {
|
|
3105
|
+
outputText = result.resolvedContent ?? content;
|
|
3106
|
+
}
|
|
3107
|
+
break;
|
|
3108
|
+
}
|
|
1679
3109
|
default:
|
|
1680
3110
|
throw new Error(`Unknown tool: ${name}`);
|
|
1681
3111
|
}
|
|
@@ -2104,6 +3534,113 @@ Expression: ${input}
|
|
|
2104
3534
|
process.stdout.write(formatted + "\n");
|
|
2105
3535
|
} catch (err) {
|
|
2106
3536
|
process.stderr.write(`[Error] ${err instanceof Error ? err.message : String(err)}
|
|
3537
|
+
`);
|
|
3538
|
+
}
|
|
3539
|
+
return true;
|
|
3540
|
+
}
|
|
3541
|
+
case "curl": {
|
|
3542
|
+
const input = await readInput(args[0]);
|
|
3543
|
+
if (!input) {
|
|
3544
|
+
process.stderr.write('Usage: npx codestation-mcp curl "<curl_command>" [--target fetch|axios|python|go]\n');
|
|
3545
|
+
return true;
|
|
3546
|
+
}
|
|
3547
|
+
let target = "fetch";
|
|
3548
|
+
const targetIdx = args.indexOf("--target");
|
|
3549
|
+
if (targetIdx !== -1 && args[targetIdx + 1]) {
|
|
3550
|
+
target = args[targetIdx + 1].toLowerCase();
|
|
3551
|
+
}
|
|
3552
|
+
try {
|
|
3553
|
+
const res = await curlToCode(input, target);
|
|
3554
|
+
process.stdout.write(res.code + "\n");
|
|
3555
|
+
} catch (err) {
|
|
3556
|
+
process.stderr.write(`[Error] ${err instanceof Error ? err.message : String(err)}
|
|
3557
|
+
`);
|
|
3558
|
+
}
|
|
3559
|
+
return true;
|
|
3560
|
+
}
|
|
3561
|
+
case "env": {
|
|
3562
|
+
let envPath = args[0] && !args[0].startsWith("-") ? args[0] : ".env";
|
|
3563
|
+
let envContent = "";
|
|
3564
|
+
if (fs3.existsSync(envPath)) {
|
|
3565
|
+
envContent = fs3.readFileSync(envPath, "utf-8");
|
|
3566
|
+
} else {
|
|
3567
|
+
envContent = await readInput(args[0]);
|
|
3568
|
+
}
|
|
3569
|
+
if (!envContent) {
|
|
3570
|
+
process.stderr.write("Usage: npx codestation-mcp env [path/to/.env] [--example path/to/.env.example] [--json]\n");
|
|
3571
|
+
return true;
|
|
3572
|
+
}
|
|
3573
|
+
let exampleContent;
|
|
3574
|
+
const exIdx = args.indexOf("--example");
|
|
3575
|
+
if (exIdx !== -1 && args[exIdx + 1] && fs3.existsSync(args[exIdx + 1])) {
|
|
3576
|
+
exampleContent = fs3.readFileSync(args[exIdx + 1], "utf-8");
|
|
3577
|
+
} else if (fs3.existsSync(".env.example")) {
|
|
3578
|
+
exampleContent = fs3.readFileSync(".env.example", "utf-8");
|
|
3579
|
+
}
|
|
3580
|
+
const isJson = args.includes("--json");
|
|
3581
|
+
try {
|
|
3582
|
+
const res = auditEnv(envContent, exampleContent);
|
|
3583
|
+
if (isJson) {
|
|
3584
|
+
process.stdout.write(JSON.stringify(res, null, 2) + "\n");
|
|
3585
|
+
} else {
|
|
3586
|
+
process.stdout.write(formatEnvAuditReport(res) + "\n");
|
|
3587
|
+
}
|
|
3588
|
+
} catch (err) {
|
|
3589
|
+
process.stderr.write(`[Error] ${err instanceof Error ? err.message : String(err)}
|
|
3590
|
+
`);
|
|
3591
|
+
}
|
|
3592
|
+
return true;
|
|
3593
|
+
}
|
|
3594
|
+
case "mock": {
|
|
3595
|
+
let template = "users";
|
|
3596
|
+
if (args[0] && !args[0].startsWith("-")) {
|
|
3597
|
+
template = args[0].toLowerCase();
|
|
3598
|
+
}
|
|
3599
|
+
let count = 10;
|
|
3600
|
+
const countIdx = args.indexOf("--count");
|
|
3601
|
+
if (countIdx !== -1 && args[countIdx + 1]) {
|
|
3602
|
+
count = parseInt(args[countIdx + 1], 10) || 10;
|
|
3603
|
+
}
|
|
3604
|
+
const isSql = args.includes("--sql");
|
|
3605
|
+
let tableName;
|
|
3606
|
+
const tableIdx = args.indexOf("--table");
|
|
3607
|
+
if (tableIdx !== -1 && args[tableIdx + 1]) {
|
|
3608
|
+
tableName = args[tableIdx + 1];
|
|
3609
|
+
}
|
|
3610
|
+
try {
|
|
3611
|
+
const res = generateMockDataset({
|
|
3612
|
+
template,
|
|
3613
|
+
count,
|
|
3614
|
+
format: isSql ? "sql" : "json",
|
|
3615
|
+
tableName
|
|
3616
|
+
});
|
|
3617
|
+
process.stdout.write((isSql && res.sql ? res.sql : res.json) + "\n");
|
|
3618
|
+
} catch (err) {
|
|
3619
|
+
process.stderr.write(`[Error] ${err instanceof Error ? err.message : String(err)}
|
|
3620
|
+
`);
|
|
3621
|
+
}
|
|
3622
|
+
return true;
|
|
3623
|
+
}
|
|
3624
|
+
case "conflict": {
|
|
3625
|
+
const input = await readInput(args[0]);
|
|
3626
|
+
if (!input) {
|
|
3627
|
+
process.stderr.write("Usage: npx codestation-mcp conflict <file_or_content> [--strategy analyze|ours|theirs|both]\n");
|
|
3628
|
+
return true;
|
|
3629
|
+
}
|
|
3630
|
+
let strategy = "analyze";
|
|
3631
|
+
const stratIdx = args.indexOf("--strategy");
|
|
3632
|
+
if (stratIdx !== -1 && args[stratIdx + 1]) {
|
|
3633
|
+
strategy = args[stratIdx + 1].toLowerCase();
|
|
3634
|
+
}
|
|
3635
|
+
try {
|
|
3636
|
+
const res = parseAndResolveGitConflicts(input, strategy);
|
|
3637
|
+
if (strategy === "analyze") {
|
|
3638
|
+
process.stdout.write(formatConflictReport(res) + "\n");
|
|
3639
|
+
} else {
|
|
3640
|
+
process.stdout.write((res.resolvedContent ?? input) + "\n");
|
|
3641
|
+
}
|
|
3642
|
+
} catch (err) {
|
|
3643
|
+
process.stderr.write(`[Error] ${err instanceof Error ? err.message : String(err)}
|
|
2107
3644
|
`);
|
|
2108
3645
|
}
|
|
2109
3646
|
return true;
|
|
@@ -2114,6 +3651,12 @@ Expression: ${input}
|
|
|
2114
3651
|
}
|
|
2115
3652
|
|
|
2116
3653
|
// mcp/cli.ts
|
|
3654
|
+
var PRO_ASCII_BADGE = `
|
|
3655
|
+
\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510
|
|
3656
|
+
\u2502 CODE STATION [PRO] \u2022 LOCAL MCP & DEVELOPER TOOLBOX \u2502
|
|
3657
|
+
\u2502 Zero-Latency Engine \u2022 Device Memory \u2022 Edge Crypto \u2502
|
|
3658
|
+
\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518
|
|
3659
|
+
`;
|
|
2117
3660
|
function printHelp() {
|
|
2118
3661
|
process.stderr.write(`
|
|
2119
3662
|
Code Station MCP Server & Developer CLI
|
|
@@ -2133,6 +3676,10 @@ Terminal Subcommands:
|
|
|
2133
3676
|
hash "<text>" [--alg] Compute digest (sha256, sha512, md5, sha1, crc32)
|
|
2134
3677
|
ts "<json_string|file>" Generate clean TypeScript interfaces from JSON
|
|
2135
3678
|
zod "<json_string|file>" Generate production-ready Zod schema from JSON
|
|
3679
|
+
curl "<curl_cmd>" [--target] Convert cURL to fetch, axios, python, or go
|
|
3680
|
+
env [path/.env] [--example] Audit .env for leaked secrets & diff with .env.example
|
|
3681
|
+
mock [template] [--count] Generate realistic mock data (users, products, orders)
|
|
3682
|
+
conflict <file> [--strategy] Parse & resolve Git merge conflicts (ours, theirs, both)
|
|
2136
3683
|
uuid [count] Generate random RFC 4122 v4 UUIDs
|
|
2137
3684
|
json "<raw_json>" Validate & pretty-print JSON
|
|
2138
3685
|
|
|
@@ -2156,7 +3703,7 @@ async function main() {
|
|
|
2156
3703
|
process.exit(0);
|
|
2157
3704
|
}
|
|
2158
3705
|
if (args.includes("--version") || args.includes("-v")) {
|
|
2159
|
-
process.stderr.write("codestation-mcp v1.
|
|
3706
|
+
process.stderr.write("codestation-mcp v1.2.0\n");
|
|
2160
3707
|
process.exit(0);
|
|
2161
3708
|
}
|
|
2162
3709
|
if (args[0] === "setup") {
|
|
@@ -2198,6 +3745,7 @@ async function main() {
|
|
|
2198
3745
|
}
|
|
2199
3746
|
const { server, license } = createMcpServer(cliKey);
|
|
2200
3747
|
if (license.isPro) {
|
|
3748
|
+
process.stderr.write(PRO_ASCII_BADGE);
|
|
2201
3749
|
process.stderr.write(`[Code Station MCP] Pro Tier Active (License: ${license.licenseKey?.slice(0, 8)}...). All tools unlocked.
|
|
2202
3750
|
`);
|
|
2203
3751
|
} else {
|