codestation-mcp 1.0.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 +2366 -1605
- package/package.json +1 -1
package/bin/codestation-mcp.mjs
CHANGED
|
@@ -1,901 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var __defProp = Object.defineProperty;
|
|
3
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
-
var __esm = (fn, res, err) => function __init() {
|
|
5
|
-
if (err) throw err[0];
|
|
6
|
-
try {
|
|
7
|
-
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
8
|
-
} catch (e) {
|
|
9
|
-
throw err = [e], e;
|
|
10
|
-
}
|
|
11
|
-
};
|
|
12
|
-
var __export = (target, all) => {
|
|
13
|
-
for (var name2 in all)
|
|
14
|
-
__defProp(target, name2, { get: all[name2], enumerable: true });
|
|
15
|
-
};
|
|
16
|
-
|
|
17
|
-
// lib/tools/sql/types.ts
|
|
18
|
-
var SQL_DIALECTS, VALUE_TYPES, CONDITION_OPERATORS;
|
|
19
|
-
var init_types = __esm({
|
|
20
|
-
"lib/tools/sql/types.ts"() {
|
|
21
|
-
"use strict";
|
|
22
|
-
SQL_DIALECTS = ["PostgreSQL", "MySQL", "SQLite", "SQL Server"];
|
|
23
|
-
VALUE_TYPES = ["String", "Number", "Boolean", "NULL"];
|
|
24
|
-
CONDITION_OPERATORS = ["=", "!=", ">", ">=", "<", "<=", "LIKE", "NOT LIKE", "IN", "NOT IN", "IS NULL", "IS NOT NULL"];
|
|
25
|
-
}
|
|
26
|
-
});
|
|
27
|
-
|
|
28
|
-
// lib/tools/sql/literals.ts
|
|
29
|
-
function readDialect(value) {
|
|
30
|
-
if (typeof value !== "string" || !SQL_DIALECTS.includes(value)) {
|
|
31
|
-
throw new Error("Choose PostgreSQL, MySQL, SQLite, or SQL Server.");
|
|
32
|
-
}
|
|
33
|
-
return value;
|
|
34
|
-
}
|
|
35
|
-
function sqlText(value, label) {
|
|
36
|
-
if (typeof value !== "string") throw new Error(`${label} must be text.`);
|
|
37
|
-
if (value.length > SQL_TEXT_LIMIT) throw new Error(`${label} exceeds the 200,000-character limit.`);
|
|
38
|
-
return value;
|
|
39
|
-
}
|
|
40
|
-
function quoteIdentifier(name2, dialect, qualified2 = false) {
|
|
41
|
-
readDialect(dialect);
|
|
42
|
-
if (typeof name2 !== "string") throw new Error("Identifiers must be text.");
|
|
43
|
-
const parts = qualified2 ? name2.split(".") : [name2];
|
|
44
|
-
const maximumParts = dialect === "SQL Server" ? 4 : dialect === "PostgreSQL" ? 3 : 2;
|
|
45
|
-
if (parts.some((part) => dialect === "PostgreSQL" ? new TextEncoder().encode(part).length > 63 : dialect === "MySQL" ? [...part].length > 64 : part.length > 128)) {
|
|
46
|
-
throw new Error("Identifiers exceed the supported length: PostgreSQL 63 UTF-8 bytes, MySQL 64 characters, SQLite/SQL Server 128 UTF-16 units.");
|
|
47
|
-
}
|
|
48
|
-
if (parts.length > maximumParts || parts.some((part) => part.length > 128 || !/^[\p{L}_][\p{L}\p{M}\p{N}_$]*$/u.test(part))) {
|
|
49
|
-
throw new Error(`Use raw identifiers of 1\u2013128 characters: start with a letter or underscore, then letters, marks, numbers, underscore, or $. This dialect allows at most ${maximumParts} table qualification parts.`);
|
|
50
|
-
}
|
|
51
|
-
return parts.map((part) => dialect === "MySQL" ? `\`${part}\`` : dialect === "SQL Server" ? `[${part}]` : `"${part}"`).join(".");
|
|
52
|
-
}
|
|
53
|
-
function stringLiteral(value, dialect) {
|
|
54
|
-
if (value.includes("\0")) throw new Error("SQL strings cannot contain a NUL character.");
|
|
55
|
-
if (/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(value)) {
|
|
56
|
-
throw new Error("SQL strings must contain valid Unicode, without unpaired surrogates.");
|
|
57
|
-
}
|
|
58
|
-
let escaped = value;
|
|
59
|
-
if (dialect === "MySQL") escaped = escaped.replace(/\\/g, "\\\\").replace(/\x1a/g, "\\Z");
|
|
60
|
-
escaped = escaped.replace(/'/g, "''");
|
|
61
|
-
return `${dialect === "SQL Server" ? "N" : ""}'${escaped}'`;
|
|
62
|
-
}
|
|
63
|
-
function sqlLiteral(literal, dialect) {
|
|
64
|
-
readDialect(dialect);
|
|
65
|
-
if (!literal || typeof literal !== "object" || Array.isArray(literal) || !VALUE_TYPES.includes(literal.type)) {
|
|
66
|
-
throw new Error("Choose String, Number, Boolean, or NULL for each value.");
|
|
67
|
-
}
|
|
68
|
-
const value = sqlText(literal.value, "Literal value");
|
|
69
|
-
if (literal.type === "NULL") return "NULL";
|
|
70
|
-
if (literal.type === "String") return stringLiteral(value, dialect);
|
|
71
|
-
if (literal.type === "Boolean") {
|
|
72
|
-
if (!/^(true|false)$/i.test(value)) throw new Error("Boolean values must be true or false.");
|
|
73
|
-
const truth = value.toLowerCase() === "true";
|
|
74
|
-
return dialect === "SQL Server" ? truth ? "1" : "0" : truth ? "TRUE" : "FALSE";
|
|
75
|
-
}
|
|
76
|
-
if (!/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(value) || !Number.isFinite(Number(value))) {
|
|
77
|
-
throw new Error("Number values must be finite decimal numbers, with an optional exponent and no SQL expressions.");
|
|
78
|
-
}
|
|
79
|
-
if (Number(value) === 0 && /[1-9]/.test(value.split(/[eE]/)[0])) throw new Error("Number is too small to represent as a finite nonzero number.");
|
|
80
|
-
return value;
|
|
81
|
-
}
|
|
82
|
-
function jsonLiteral(value, dialect) {
|
|
83
|
-
if (value === null) return sqlLiteral({ type: "NULL", value: "" }, dialect);
|
|
84
|
-
if (typeof value === "string") return sqlLiteral({ type: "String", value }, dialect);
|
|
85
|
-
if (typeof value === "boolean") return sqlLiteral({ type: "Boolean", value: String(value) }, dialect);
|
|
86
|
-
if (typeof value === "number") {
|
|
87
|
-
if (!Number.isFinite(value) || Number.isInteger(value) && !Number.isSafeInteger(value)) {
|
|
88
|
-
throw new Error("JSON numbers must be finite and integers must be safe; quote precision-sensitive numbers as strings.");
|
|
89
|
-
}
|
|
90
|
-
return sqlLiteral({ type: "Number", value: String(value) }, dialect);
|
|
91
|
-
}
|
|
92
|
-
throw new Error("JSON SQL values must be strings, numbers, booleans, or null; nested arrays and objects are unsupported.");
|
|
93
|
-
}
|
|
94
|
-
var SQL_TEXT_LIMIT;
|
|
95
|
-
var init_literals = __esm({
|
|
96
|
-
"lib/tools/sql/literals.ts"() {
|
|
97
|
-
"use strict";
|
|
98
|
-
init_types();
|
|
99
|
-
SQL_TEXT_LIMIT = 2e5;
|
|
100
|
-
}
|
|
101
|
-
});
|
|
102
|
-
|
|
103
|
-
// lib/tools/sql/lexer.ts
|
|
104
|
-
function dollarDelimiter(text3) {
|
|
105
|
-
return /^(?:\$\$|\$[\p{L}_][\p{L}\p{M}\p{N}_]*\$)/u.exec(text3)?.[0];
|
|
106
|
-
}
|
|
107
|
-
function lexSql(sql, dialect) {
|
|
108
|
-
if (typeof sql !== "string" || !sql.trim()) throw new SqlSyntaxError("Enter SQL to process.");
|
|
109
|
-
if (sql.length > 2e5) throw new SqlSyntaxError("SQL exceeds the 200,000-character limit.");
|
|
110
|
-
const tokens = [];
|
|
111
|
-
let i = 0, line = 1, column = 1, depth = 0, statements = 0;
|
|
112
|
-
const fail = (message) => {
|
|
113
|
-
throw new SqlSyntaxError(message, { line, column });
|
|
114
|
-
};
|
|
115
|
-
const push = (kind, end) => {
|
|
116
|
-
const text3 = sql.slice(i, end);
|
|
117
|
-
tokens.push({ kind, text: text3, start: i, end, line, column });
|
|
118
|
-
for (let j = i; j < end; j++) {
|
|
119
|
-
if (sql[j] === "\n" || sql[j] === "\r" && sql[j + 1] !== "\n") {
|
|
120
|
-
line++;
|
|
121
|
-
column = 1;
|
|
122
|
-
} else column++;
|
|
123
|
-
}
|
|
124
|
-
i = end;
|
|
125
|
-
if (tokens.length > 5e4) fail("SQL exceeds the 50,000-token limit.");
|
|
126
|
-
};
|
|
127
|
-
while (i < sql.length) {
|
|
128
|
-
const ch = sql[i];
|
|
129
|
-
if (/\s/.test(ch)) {
|
|
130
|
-
let j = i + 1;
|
|
131
|
-
while (j < sql.length && /\s/.test(sql[j])) j++;
|
|
132
|
-
push("space", j);
|
|
133
|
-
continue;
|
|
134
|
-
}
|
|
135
|
-
if (ch === "\0") fail("SQL contains an unsupported NUL character.");
|
|
136
|
-
if (sql.startsWith("--", i) && (dialect !== "MySQL" || i + 2 === sql.length || /[\s\x00-\x1f]/.test(sql[i + 2])) || ch === "#" && dialect === "MySQL") {
|
|
137
|
-
let j = i + 1;
|
|
138
|
-
while (j < sql.length && !/[\r\n]/.test(sql[j])) j++;
|
|
139
|
-
push("comment", j);
|
|
140
|
-
continue;
|
|
141
|
-
}
|
|
142
|
-
if (sql.startsWith("/*", i)) {
|
|
143
|
-
const protectedComment = sql[i + 2] === "!" || sql[i + 2] === "+";
|
|
144
|
-
if (sql[i + 2] === "!" && dialect !== "MySQL") fail("Executable comments are supported only for MySQL.");
|
|
145
|
-
let nesting = 1, j = i + 2;
|
|
146
|
-
while (j < sql.length && nesting) {
|
|
147
|
-
if (sql.startsWith("/*", j)) {
|
|
148
|
-
if (dialect !== "PostgreSQL" && dialect !== "SQL Server") fail("Nested block comments are unsupported for the selected dialect.");
|
|
149
|
-
if (++nesting > 128) fail("SQL comment nesting exceeds the 128-level limit.");
|
|
150
|
-
j += 2;
|
|
151
|
-
} else if (sql.startsWith("*/", j)) {
|
|
152
|
-
nesting--;
|
|
153
|
-
j += 2;
|
|
154
|
-
} else j++;
|
|
155
|
-
}
|
|
156
|
-
if (nesting) fail("Unterminated SQL block comment.");
|
|
157
|
-
push(protectedComment ? "protected" : "comment", j);
|
|
158
|
-
continue;
|
|
159
|
-
}
|
|
160
|
-
if (dialect === "PostgreSQL" && ch === "$") {
|
|
161
|
-
const delimiter = dollarDelimiter(sql.slice(i));
|
|
162
|
-
if (delimiter) {
|
|
163
|
-
const end = sql.indexOf(delimiter, i + delimiter.length);
|
|
164
|
-
if (end < 0) fail("Unterminated PostgreSQL dollar-quoted string.");
|
|
165
|
-
push("string", end + delimiter.length);
|
|
166
|
-
continue;
|
|
167
|
-
}
|
|
168
|
-
}
|
|
169
|
-
const prefixed = (dialect === "PostgreSQL" && /[eE]/.test(ch) || (dialect === "SQL Server" || dialect === "MySQL") && /[nN]/.test(ch)) && sql[i + 1] === "'";
|
|
170
|
-
const quote = prefixed ? "'" : ch;
|
|
171
|
-
if (quote === "'" || quote === '"' || quote === "`" || quote === "[") {
|
|
172
|
-
if (quote === "`" && dialect !== "MySQL" && dialect !== "SQLite") fail("Backtick identifiers are unsupported for the selected dialect.");
|
|
173
|
-
if (quote === "[" && dialect !== "SQL Server" && dialect !== "SQLite") {
|
|
174
|
-
push("symbol", i + 1);
|
|
175
|
-
continue;
|
|
176
|
-
}
|
|
177
|
-
const closing = quote === "[" ? "]" : quote;
|
|
178
|
-
const kind = quote === "'" || quote === '"' && dialect === "MySQL" ? "string" : "identifier";
|
|
179
|
-
const escapes = kind === "string" && dialect === "MySQL" || prefixed && dialect === "PostgreSQL";
|
|
180
|
-
let j = i + (prefixed ? 2 : 1), closed = false;
|
|
181
|
-
while (j < sql.length) {
|
|
182
|
-
if (escapes && sql[j] === "\\") {
|
|
183
|
-
j += 2;
|
|
184
|
-
continue;
|
|
185
|
-
}
|
|
186
|
-
if (sql[j] === closing) {
|
|
187
|
-
if (sql[j + 1] === closing) {
|
|
188
|
-
j += 2;
|
|
189
|
-
continue;
|
|
190
|
-
}
|
|
191
|
-
j++;
|
|
192
|
-
closed = true;
|
|
193
|
-
break;
|
|
194
|
-
}
|
|
195
|
-
j++;
|
|
196
|
-
}
|
|
197
|
-
if (!closed) fail(kind === "string" ? "Unterminated SQL string literal." : "Unterminated quoted SQL identifier.");
|
|
198
|
-
push(kind, j);
|
|
199
|
-
continue;
|
|
200
|
-
}
|
|
201
|
-
if (/[A-Za-z_\u0080-\uffff]/.test(ch) || ch === "@" && dialect === "SQL Server" || ch === "#" && dialect === "SQL Server") {
|
|
202
|
-
let j = i + 1;
|
|
203
|
-
while (j < sql.length && /[A-Za-z0-9_$@#\u0080-\uffff]/.test(sql[j])) j++;
|
|
204
|
-
push("word", j);
|
|
205
|
-
continue;
|
|
206
|
-
}
|
|
207
|
-
if (/[0-9]/.test(ch) || ch === "." && /[0-9]/.test(sql[i + 1] ?? "")) {
|
|
208
|
-
const number = /^(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/.exec(sql.slice(i))[0];
|
|
209
|
-
push("number", i + number.length);
|
|
210
|
-
continue;
|
|
211
|
-
}
|
|
212
|
-
if (ch === "(") {
|
|
213
|
-
if (++depth > 128) fail("SQL nesting exceeds the 128-level limit.");
|
|
214
|
-
}
|
|
215
|
-
if (ch === ")") {
|
|
216
|
-
if (--depth < 0) fail("Unexpected closing parenthesis.");
|
|
217
|
-
}
|
|
218
|
-
if (ch === ";" && ++statements > 200) fail("SQL exceeds the 200-statement limit.");
|
|
219
|
-
const operator = /^(?:->>|->|#>>|#>|::|>=|<=|<>|!=|\|\||&&|:=|!~\*|!~|~\*|<<|>>)/.exec(sql.slice(i))?.[0];
|
|
220
|
-
if (operator === "::" && dialect !== "PostgreSQL") fail("PostgreSQL :: casts are unsupported for the selected dialect.");
|
|
221
|
-
push("symbol", i + (operator?.length ?? 1));
|
|
222
|
-
}
|
|
223
|
-
if (depth) throw new SqlSyntaxError("Unclosed SQL parenthesis.", { line, column });
|
|
224
|
-
if (!tokens.some((t) => t.kind !== "space" && t.kind !== "comment")) throw new SqlSyntaxError("Enter a SQL statement, not only comments.");
|
|
225
|
-
return tokens;
|
|
226
|
-
}
|
|
227
|
-
function significantTokens(tokens) {
|
|
228
|
-
return tokens.filter((t) => t.kind !== "space" && t.kind !== "comment");
|
|
229
|
-
}
|
|
230
|
-
function identifierValue(token) {
|
|
231
|
-
if (!token || token.kind !== "word" && token.kind !== "identifier") throw new SqlSyntaxError("A named SQL identifier is required.", token);
|
|
232
|
-
if (token.kind === "word") return token.text;
|
|
233
|
-
const end = token.text[0] === "[" ? "]" : token.text[0];
|
|
234
|
-
return token.text.slice(1, -1).split(end + end).join(end);
|
|
235
|
-
}
|
|
236
|
-
var SqlSyntaxError, TokenCursor;
|
|
237
|
-
var init_lexer = __esm({
|
|
238
|
-
"lib/tools/sql/lexer.ts"() {
|
|
239
|
-
"use strict";
|
|
240
|
-
SqlSyntaxError = class extends Error {
|
|
241
|
-
constructor(message, location) {
|
|
242
|
-
super(message);
|
|
243
|
-
this.name = "SqlSyntaxError";
|
|
244
|
-
this.line = location?.line;
|
|
245
|
-
this.column = location?.column;
|
|
246
|
-
this.stack = `${this.name}: ${message}`;
|
|
247
|
-
}
|
|
248
|
-
};
|
|
249
|
-
TokenCursor = class {
|
|
250
|
-
constructor(tokens) {
|
|
251
|
-
this.tokens = tokens;
|
|
252
|
-
this.index = 0;
|
|
253
|
-
}
|
|
254
|
-
peek() {
|
|
255
|
-
return this.tokens[this.index];
|
|
256
|
-
}
|
|
257
|
-
is(text3) {
|
|
258
|
-
return this.peek()?.text.toUpperCase() === text3.toUpperCase();
|
|
259
|
-
}
|
|
260
|
-
take() {
|
|
261
|
-
const token = this.tokens[this.index++];
|
|
262
|
-
if (!token) this.fail("Unexpected end of SQL.");
|
|
263
|
-
return token;
|
|
264
|
-
}
|
|
265
|
-
accept(text3) {
|
|
266
|
-
if (!this.is(text3)) return false;
|
|
267
|
-
this.index++;
|
|
268
|
-
return true;
|
|
269
|
-
}
|
|
270
|
-
expect(text3) {
|
|
271
|
-
if (!this.accept(text3)) this.fail("Unexpected SQL syntax in the supported statement subset.");
|
|
272
|
-
}
|
|
273
|
-
identifier() {
|
|
274
|
-
return identifierValue(this.take());
|
|
275
|
-
}
|
|
276
|
-
qualifiedIdentifier() {
|
|
277
|
-
const parts = [this.identifier()];
|
|
278
|
-
while (this.accept(".")) parts.push(this.identifier());
|
|
279
|
-
if (parts.length > 3) this.fail("SQL identifiers may have at most three qualification parts.");
|
|
280
|
-
return parts.join(".");
|
|
281
|
-
}
|
|
282
|
-
fail(message) {
|
|
283
|
-
throw new SqlSyntaxError(message, this.peek() ?? this.tokens[this.tokens.length - 1]);
|
|
284
|
-
}
|
|
285
|
-
};
|
|
286
|
-
}
|
|
287
|
-
});
|
|
288
|
-
|
|
289
|
-
// lib/tools/sql/parser.ts
|
|
290
|
-
async function parseSql(sql, dialect) {
|
|
291
|
-
dialect = readDialect(dialect);
|
|
292
|
-
lexSql(sql, dialect);
|
|
293
|
-
const parserModule = await engines[dialect]();
|
|
294
|
-
try {
|
|
295
|
-
const exported = parserModule;
|
|
296
|
-
const Parser = exported.Parser ?? exported.default?.Parser;
|
|
297
|
-
if (!Parser) throw new SqlSyntaxError("The local dialect parser could not initialize.");
|
|
298
|
-
const ast = new Parser().astify(sql);
|
|
299
|
-
const statements = Array.isArray(ast) ? ast : [ast];
|
|
300
|
-
if (!statements.length || statements.length > 200) throw new SqlSyntaxError("SQL must contain between 1 and 200 statements.");
|
|
301
|
-
if (statements.some((statement) => typeof statement.type !== "string")) throw new SqlSyntaxError("The selected parser returned an unsupported statement form.");
|
|
302
|
-
if (dialect === "SQL Server") {
|
|
303
|
-
const pending = [...statements];
|
|
304
|
-
while (pending.length) {
|
|
305
|
-
const value = pending.pop();
|
|
306
|
-
if (!value || typeof value !== "object") continue;
|
|
307
|
-
const record2 = value;
|
|
308
|
-
if (record2.type === "select" && record2.limit) throw new SqlSyntaxError("LIMIT is unsupported for SQL Server; use its native TOP or OFFSET/FETCH syntax.");
|
|
309
|
-
pending.push(...Object.values(record2).filter((child) => child && typeof child === "object"));
|
|
310
|
-
}
|
|
311
|
-
}
|
|
312
|
-
return statements;
|
|
313
|
-
} catch (error) {
|
|
314
|
-
if (error instanceof SqlSyntaxError) throw error;
|
|
315
|
-
const location = error?.location?.start;
|
|
316
|
-
const safeLocation = typeof location?.line === "number" && typeof location.column === "number" ? { line: location.line, column: location.column } : void 0;
|
|
317
|
-
throw new SqlSyntaxError(`SQL is invalid or unsupported by the ${dialect} parser's supported syntax subset.`, safeLocation);
|
|
318
|
-
}
|
|
319
|
-
}
|
|
320
|
-
var engines;
|
|
321
|
-
var init_parser = __esm({
|
|
322
|
-
"lib/tools/sql/parser.ts"() {
|
|
323
|
-
"use strict";
|
|
324
|
-
init_lexer();
|
|
325
|
-
init_literals();
|
|
326
|
-
init_lexer();
|
|
327
|
-
engines = {
|
|
328
|
-
PostgreSQL: () => import("node-sql-parser/build/postgresql"),
|
|
329
|
-
MySQL: () => import("node-sql-parser/build/mysql"),
|
|
330
|
-
SQLite: () => import("node-sql-parser/build/sqlite"),
|
|
331
|
-
"SQL Server": () => import("node-sql-parser/build/transactsql")
|
|
332
|
-
};
|
|
333
|
-
}
|
|
334
|
-
});
|
|
335
|
-
|
|
336
|
-
// lib/tools/sql/ddl.ts
|
|
337
|
-
var ddl_exports = {};
|
|
338
|
-
__export(ddl_exports, {
|
|
339
|
-
ddlOutput: () => ddlOutput,
|
|
340
|
-
parseDdl: () => parseDdl
|
|
341
|
-
});
|
|
342
|
-
function key(name2, dialect) {
|
|
343
|
-
return dialect === "PostgreSQL" ? name2 : name2.toLowerCase();
|
|
344
|
-
}
|
|
345
|
-
function name(cursor, dialect) {
|
|
346
|
-
const token = cursor.take(), value = identifierValue(token);
|
|
347
|
-
if (value.length > 128) cursor.fail("DDL identifiers are limited to 128 characters.");
|
|
348
|
-
return dialect === "PostgreSQL" && token.kind === "word" ? value.toLowerCase() : value;
|
|
349
|
-
}
|
|
350
|
-
function qualified(cursor, dialect) {
|
|
351
|
-
const parts = [name(cursor, dialect)];
|
|
352
|
-
while (cursor.accept(".")) parts.push(name(cursor, dialect));
|
|
353
|
-
if (parts.length > 3) cursor.fail("Table names may have at most three qualification parts.");
|
|
354
|
-
if (parts.some((part) => part.includes("."))) cursor.fail("Quoted identifiers containing dots are unsupported; use explicit qualification parts.");
|
|
355
|
-
return parts.join(".");
|
|
356
|
-
}
|
|
357
|
-
function columns(cursor, dialect) {
|
|
358
|
-
cursor.expect("(");
|
|
359
|
-
const values = [];
|
|
360
|
-
do {
|
|
361
|
-
values.push(name(cursor, dialect));
|
|
362
|
-
} while (cursor.accept(","));
|
|
363
|
-
cursor.expect(")");
|
|
364
|
-
if (new Set(values.map((value) => key(value, dialect))).size !== values.length) cursor.fail("Duplicate columns in a key constraint.");
|
|
365
|
-
return values;
|
|
366
|
-
}
|
|
367
|
-
function parenthesized(cursor, allowEmpty = false) {
|
|
368
|
-
cursor.expect("(");
|
|
369
|
-
let depth = 1;
|
|
370
|
-
const result2 = [];
|
|
371
|
-
while (depth) {
|
|
372
|
-
const token = cursor.take();
|
|
373
|
-
if (token.text === "(") depth++;
|
|
374
|
-
if (token.text === ")") depth--;
|
|
375
|
-
if (depth) result2.push(token);
|
|
376
|
-
}
|
|
377
|
-
if (!result2.length && !allowEmpty) cursor.fail("Empty parenthesized SQL definition is unsupported.");
|
|
378
|
-
return result2;
|
|
379
|
-
}
|
|
380
|
-
function reference(cursor, dialect, localColumns) {
|
|
381
|
-
cursor.expect("REFERENCES");
|
|
382
|
-
const referencedTable = qualified(cursor, dialect), referencedColumns = columns(cursor, dialect);
|
|
383
|
-
if (localColumns.length !== referencedColumns.length) cursor.fail("Foreign-key column counts do not match the referenced column counts.");
|
|
384
|
-
let match = false;
|
|
385
|
-
const actions = /* @__PURE__ */ new Set();
|
|
386
|
-
while (cursor.is("MATCH") || cursor.is("ON")) {
|
|
387
|
-
if (cursor.accept("MATCH")) {
|
|
388
|
-
if (match) cursor.fail("Duplicate foreign-key MATCH clause.");
|
|
389
|
-
match = true;
|
|
390
|
-
if (!cursor.accept("SIMPLE") && !cursor.accept("FULL") && !cursor.accept("PARTIAL")) cursor.fail("Unsupported foreign-key MATCH clause.");
|
|
391
|
-
} else {
|
|
392
|
-
cursor.expect("ON");
|
|
393
|
-
const action = cursor.take().text.toUpperCase();
|
|
394
|
-
if (action !== "DELETE" && action !== "UPDATE" || actions.has(action)) cursor.fail("Invalid or duplicate foreign-key action.");
|
|
395
|
-
actions.add(action);
|
|
396
|
-
if (cursor.accept("SET")) {
|
|
397
|
-
if (!cursor.accept("NULL") && !cursor.accept("DEFAULT")) cursor.fail("Unsupported foreign-key SET action.");
|
|
398
|
-
} else if (cursor.accept("NO")) cursor.expect("ACTION");
|
|
399
|
-
else if (!cursor.accept("CASCADE") && !cursor.accept("RESTRICT")) cursor.fail("Unsupported foreign-key action.");
|
|
400
|
-
}
|
|
401
|
-
}
|
|
402
|
-
return { columns: localColumns, referencedTable, referencedColumns };
|
|
403
|
-
}
|
|
404
|
-
function dataType(cursor, dialect, sql) {
|
|
405
|
-
const start = cursor.peek()?.start;
|
|
406
|
-
if (start === void 0) cursor.fail("A declared column type is required.");
|
|
407
|
-
const first = name(cursor, dialect).toUpperCase();
|
|
408
|
-
while (cursor.accept(".")) name(cursor, dialect);
|
|
409
|
-
if (first === "DOUBLE") cursor.accept("PRECISION");
|
|
410
|
-
if (first === "CHARACTER" || first === "CHAR" || first === "BIT") cursor.accept("VARYING");
|
|
411
|
-
if (first === "NATIONAL") {
|
|
412
|
-
if (!cursor.accept("VARCHAR") && !cursor.accept("CHAR") && !cursor.accept("CHARACTER")) cursor.fail("Unsupported NATIONAL column type.");
|
|
413
|
-
cursor.accept("VARYING");
|
|
414
|
-
}
|
|
415
|
-
if (cursor.is("(")) {
|
|
416
|
-
const args = parenthesized(cursor);
|
|
417
|
-
if (args.some((token, i) => i % 2 === 1 ? token.text !== "," : token.kind !== "number" && token.kind !== "string" && token.text.toUpperCase() !== "MAX") || args.length % 2 === 0) cursor.fail("Unsupported column-type parameters.");
|
|
418
|
-
}
|
|
419
|
-
if (first === "TIMESTAMP" || first === "TIME") {
|
|
420
|
-
if (cursor.accept("WITH") || cursor.accept("WITHOUT")) {
|
|
421
|
-
cursor.expect("TIME");
|
|
422
|
-
cursor.expect("ZONE");
|
|
423
|
-
}
|
|
424
|
-
}
|
|
425
|
-
if (dialect === "MySQL") {
|
|
426
|
-
cursor.accept("UNSIGNED");
|
|
427
|
-
cursor.accept("ZEROFILL");
|
|
428
|
-
}
|
|
429
|
-
if (dialect === "PostgreSQL") while (cursor.accept("[")) {
|
|
430
|
-
if (cursor.peek()?.kind === "number") cursor.take();
|
|
431
|
-
cursor.expect("]");
|
|
432
|
-
}
|
|
433
|
-
const end = cursor.tokens[cursor.index - 1].end;
|
|
434
|
-
return sql.slice(start, end).trim();
|
|
435
|
-
}
|
|
436
|
-
function parseDefinition(tokens, table, dialect, sql) {
|
|
437
|
-
const cursor = new TokenCursor(tokens);
|
|
438
|
-
if (cursor.accept("CONSTRAINT")) name(cursor, dialect);
|
|
439
|
-
if (cursor.accept("PRIMARY")) {
|
|
440
|
-
cursor.expect("KEY");
|
|
441
|
-
if (dialect === "SQL Server") {
|
|
442
|
-
cursor.accept("CLUSTERED");
|
|
443
|
-
cursor.accept("NONCLUSTERED");
|
|
444
|
-
}
|
|
445
|
-
if (table.primaryKeys.length) cursor.fail("A table may declare only one primary key.");
|
|
446
|
-
table.primaryKeys = columns(cursor, dialect);
|
|
447
|
-
} else if (cursor.accept("FOREIGN")) {
|
|
448
|
-
cursor.expect("KEY");
|
|
449
|
-
const localColumns = columns(cursor, dialect);
|
|
450
|
-
table.foreignKeys.push(reference(cursor, dialect, localColumns));
|
|
451
|
-
} else if (cursor.accept("UNIQUE")) {
|
|
452
|
-
columns(cursor, dialect);
|
|
453
|
-
} else if (cursor.accept("CHECK")) {
|
|
454
|
-
parenthesized(cursor);
|
|
455
|
-
} else {
|
|
456
|
-
const columnName = name(cursor, dialect);
|
|
457
|
-
if (table.columns.some((column2) => key(column2.name, dialect) === key(columnName, dialect))) cursor.fail("Duplicate column identifiers in CREATE TABLE.");
|
|
458
|
-
const declaredType = dataType(cursor, dialect, sql);
|
|
459
|
-
const column = { name: columnName, dataType: declaredType, primaryKey: false, nullable: true };
|
|
460
|
-
let explicitNullability = false, hasDefault = false, hasReference = false, primary = false;
|
|
461
|
-
while (cursor.peek()) {
|
|
462
|
-
if (cursor.accept("CONSTRAINT")) {
|
|
463
|
-
name(cursor, dialect);
|
|
464
|
-
continue;
|
|
465
|
-
}
|
|
466
|
-
if (cursor.accept("PRIMARY")) {
|
|
467
|
-
cursor.expect("KEY");
|
|
468
|
-
if (primary || table.primaryKeys.length) cursor.fail("A table may declare only one primary key.");
|
|
469
|
-
primary = true;
|
|
470
|
-
table.primaryKeys = [columnName];
|
|
471
|
-
column.primaryKey = true;
|
|
472
|
-
} else if (cursor.accept("NOT")) {
|
|
473
|
-
cursor.expect("NULL");
|
|
474
|
-
if (explicitNullability) cursor.fail("Duplicate column nullability declaration.");
|
|
475
|
-
explicitNullability = true;
|
|
476
|
-
column.nullable = false;
|
|
477
|
-
} else if (cursor.accept("NULL")) {
|
|
478
|
-
if (explicitNullability) cursor.fail("Duplicate column nullability declaration.");
|
|
479
|
-
explicitNullability = true;
|
|
480
|
-
column.nullable = true;
|
|
481
|
-
} else if (cursor.is("REFERENCES")) {
|
|
482
|
-
if (hasReference) cursor.fail("Duplicate inline foreign-key declaration.");
|
|
483
|
-
hasReference = true;
|
|
484
|
-
table.foreignKeys.push(reference(cursor, dialect, [columnName]));
|
|
485
|
-
} else if (cursor.accept("DEFAULT")) {
|
|
486
|
-
if (hasDefault) cursor.fail("Duplicate column DEFAULT declaration.");
|
|
487
|
-
hasDefault = true;
|
|
488
|
-
const start = cursor.index;
|
|
489
|
-
if (cursor.is("(")) parenthesized(cursor);
|
|
490
|
-
else {
|
|
491
|
-
if (cursor.is("+") || cursor.is("-")) cursor.take();
|
|
492
|
-
cursor.take();
|
|
493
|
-
if (cursor.is("(")) parenthesized(cursor, true);
|
|
494
|
-
while (cursor.accept("::")) qualified(cursor, dialect);
|
|
495
|
-
}
|
|
496
|
-
if (cursor.index === start) cursor.fail("A DEFAULT expression is required.");
|
|
497
|
-
} else if (cursor.accept("UNIQUE")) {
|
|
498
|
-
} else if (cursor.accept("CHECK")) parenthesized(cursor);
|
|
499
|
-
else if (cursor.accept("COLLATE")) qualified(cursor, dialect);
|
|
500
|
-
else if (cursor.accept("AUTO_INCREMENT")) {
|
|
501
|
-
if (dialect !== "MySQL") cursor.fail("AUTO_INCREMENT is supported only for MySQL.");
|
|
502
|
-
} else if (cursor.accept("AUTOINCREMENT")) {
|
|
503
|
-
if (dialect !== "SQLite" || !primary || declaredType.toUpperCase() !== "INTEGER") cursor.fail("SQLite AUTOINCREMENT requires an INTEGER PRIMARY KEY.");
|
|
504
|
-
} else if (cursor.accept("IDENTITY")) {
|
|
505
|
-
if (dialect !== "SQL Server") cursor.fail("IDENTITY is supported only for SQL Server.");
|
|
506
|
-
if (cursor.is("(")) parenthesized(cursor);
|
|
507
|
-
} else cursor.fail("Unsupported column constraint or definition; no schema details were discarded.");
|
|
508
|
-
}
|
|
509
|
-
table.columns.push(column);
|
|
510
|
-
}
|
|
511
|
-
if (cursor.peek()) cursor.fail("Unsupported table constraint options; no schema details were discarded.");
|
|
512
|
-
}
|
|
513
|
-
async function parseDdl(sql, dialect) {
|
|
514
|
-
dialect = readDialect(dialect);
|
|
515
|
-
const tokens = significantTokens(lexSql(sql, dialect)), cursor = new TokenCursor(tokens);
|
|
516
|
-
const tables = [];
|
|
517
|
-
let totalColumns = 0, totalRelationships = 0;
|
|
518
|
-
const serverValidationTokens = [];
|
|
519
|
-
while (cursor.peek()) {
|
|
520
|
-
const tableStart = cursor.index;
|
|
521
|
-
cursor.expect("CREATE");
|
|
522
|
-
if (cursor.accept("TEMP") || cursor.accept("TEMPORARY")) {
|
|
523
|
-
if (dialect === "SQL Server") cursor.fail("SQL Server temporary tables use a # table name.");
|
|
524
|
-
}
|
|
525
|
-
cursor.expect("TABLE");
|
|
526
|
-
if (cursor.accept("IF")) {
|
|
527
|
-
if (dialect === "SQL Server") cursor.fail("IF NOT EXISTS is unsupported for SQL Server CREATE TABLE.");
|
|
528
|
-
cursor.expect("NOT");
|
|
529
|
-
cursor.expect("EXISTS");
|
|
530
|
-
}
|
|
531
|
-
const table = { name: qualified(cursor, dialect), columns: [], primaryKeys: [], foreignKeys: [] };
|
|
532
|
-
if (tables.some((existing) => key(existing.name, dialect) === key(table.name, dialect))) cursor.fail("Duplicate CREATE TABLE identifiers.");
|
|
533
|
-
cursor.expect("(");
|
|
534
|
-
const openIndex = cursor.index - 1;
|
|
535
|
-
const definitions = [];
|
|
536
|
-
let segment = [], depth = 0;
|
|
537
|
-
while (cursor.peek() && !(cursor.is(")") && depth === 0)) {
|
|
538
|
-
const token = cursor.take();
|
|
539
|
-
if (token.text === "," && depth === 0) {
|
|
540
|
-
if (!segment.length) cursor.fail("Empty CREATE TABLE definition.");
|
|
541
|
-
definitions.push(segment);
|
|
542
|
-
segment = [];
|
|
543
|
-
} else {
|
|
544
|
-
if (token.text === "(") depth++;
|
|
545
|
-
else if (token.text === ")") depth--;
|
|
546
|
-
segment.push(token);
|
|
547
|
-
}
|
|
548
|
-
}
|
|
549
|
-
if (!segment.length) cursor.fail("CREATE TABLE needs nonempty named columns and no trailing comma.");
|
|
550
|
-
definitions.push(segment);
|
|
551
|
-
cursor.expect(")");
|
|
552
|
-
const closeIndex = cursor.index - 1;
|
|
553
|
-
for (const definition of definitions) parseDefinition(definition, table, dialect, sql);
|
|
554
|
-
if (!table.columns.length) cursor.fail("CREATE TABLE needs at least one named column.");
|
|
555
|
-
const local = new Set(table.columns.map((column) => key(column.name, dialect)));
|
|
556
|
-
for (const primaryKey of table.primaryKeys) if (!local.has(key(primaryKey, dialect))) cursor.fail("A primary-key column is not declared in its table.");
|
|
557
|
-
for (const foreignKey of table.foreignKeys) for (const column of foreignKey.columns) if (!local.has(key(column, dialect))) cursor.fail("A foreign-key column is not declared in its table.");
|
|
558
|
-
for (const column of table.columns) {
|
|
559
|
-
column.primaryKey = table.primaryKeys.some((primaryKey) => key(primaryKey, dialect) === key(column.name, dialect));
|
|
560
|
-
if (column.primaryKey && (dialect !== "SQLite" || table.primaryKeys.length === 1 && column.dataType.toUpperCase() === "INTEGER")) column.nullable = false;
|
|
561
|
-
}
|
|
562
|
-
tables.push(table);
|
|
563
|
-
totalColumns += table.columns.length;
|
|
564
|
-
totalRelationships += table.foreignKeys.length;
|
|
565
|
-
if (tables.length > 50 || totalColumns > 500 || totalRelationships > 200) cursor.fail("DDL is limited to 50 tables, 500 columns and 200 foreign-key relationships.");
|
|
566
|
-
if (cursor.peek() && !cursor.accept(";")) cursor.fail("Only CREATE TABLE statements are supported; table options, ALTER and other statements are unsupported.");
|
|
567
|
-
if (dialect === "SQL Server") {
|
|
568
|
-
serverValidationTokens.push(...tokens.slice(tableStart, openIndex + 1));
|
|
569
|
-
const retained = [];
|
|
570
|
-
for (const definition of definitions) {
|
|
571
|
-
let start = 0;
|
|
572
|
-
if (definition[0]?.text.toUpperCase() === "CONSTRAINT") start = 2;
|
|
573
|
-
if (definition[start]?.text.toUpperCase() === "FOREIGN") continue;
|
|
574
|
-
const referenceIndex = definition.findIndex((token) => token.kind === "word" && token.text.toUpperCase() === "REFERENCES");
|
|
575
|
-
if (referenceIndex < 0) retained.push(definition);
|
|
576
|
-
else {
|
|
577
|
-
const refCursor = new TokenCursor(definition);
|
|
578
|
-
refCursor.index = referenceIndex;
|
|
579
|
-
reference(refCursor, dialect, ["column"]);
|
|
580
|
-
const refStart = definition[referenceIndex - 2]?.text.toUpperCase() === "CONSTRAINT" ? referenceIndex - 2 : referenceIndex;
|
|
581
|
-
retained.push([...definition.slice(0, refStart), ...definition.slice(refCursor.index)]);
|
|
582
|
-
}
|
|
583
|
-
}
|
|
584
|
-
retained.forEach((definition, index) => {
|
|
585
|
-
if (index) serverValidationTokens.push({ ...tokens[openIndex], text: "," });
|
|
586
|
-
serverValidationTokens.push(...definition);
|
|
587
|
-
});
|
|
588
|
-
serverValidationTokens.push(tokens[closeIndex], { ...tokens[closeIndex], text: ";" });
|
|
589
|
-
}
|
|
590
|
-
}
|
|
591
|
-
await parseSql(dialect === "SQL Server" ? serverValidationTokens.map((token) => token.text).join(" ") : sql, dialect);
|
|
592
|
-
const relationships = tables.flatMap((table) => table.foreignKeys.map((foreignKey) => ({ fromTable: table.name, fromColumns: foreignKey.columns, toTable: foreignKey.referencedTable, toColumns: foreignKey.referencedColumns })));
|
|
593
|
-
for (const relationship of relationships) {
|
|
594
|
-
const target = tables.find((table) => key(table.name, dialect) === key(relationship.toTable, dialect));
|
|
595
|
-
if (target && relationship.toColumns.some((column) => !target.columns.some((candidate) => key(candidate.name, dialect) === key(column, dialect)))) throw new SqlSyntaxError("A foreign key references a missing column in a locally declared table.");
|
|
596
|
-
if (target) relationship.toTable = target.name;
|
|
597
|
-
}
|
|
598
|
-
return { tables, relationships };
|
|
599
|
-
}
|
|
600
|
-
async function ddlOutput(sql, dialect) {
|
|
601
|
-
const schema = await parseDdl(sql, dialect);
|
|
602
|
-
const columns2 = schema.tables.flatMap((table) => table.columns.map((column) => `${table.name}.${column.name}: ${column.dataType}${column.primaryKey ? " [PK]" : ""}${column.nullable === false ? " NOT NULL" : ""}`));
|
|
603
|
-
const primaryKeys = schema.tables.filter((table) => table.primaryKeys.length).map((table) => `${table.name}: (${table.primaryKeys.join(", ")})`);
|
|
604
|
-
const relationships = schema.relationships.map((link) => `${link.fromTable} (${link.fromColumns.join(", ")}) \u2192 ${link.toTable} (${link.toColumns.join(", ")})`);
|
|
605
|
-
return { schema, rows: [
|
|
606
|
-
{ label: "Entity relationship diagram", value: [`Tables: ${schema.tables.map((table) => table.name).join(", ")}`, ...relationships].join("\n") },
|
|
607
|
-
{ label: "Parsed tables", value: schema.tables.map((table) => table.name).join("\n") },
|
|
608
|
-
{ label: "Columns", value: columns2.join("\n") },
|
|
609
|
-
{ label: "Primary keys", value: primaryKeys.join("\n") || "None declared" },
|
|
610
|
-
{ label: "Foreign-key relationships", value: relationships.join("\n") || "None declared" }
|
|
611
|
-
], warnings: ["Relationships come only from explicitly declared foreign keys. External referenced tables are retained. This does not verify database objects or referential integrity."] };
|
|
612
|
-
}
|
|
613
|
-
var init_ddl = __esm({
|
|
614
|
-
"lib/tools/sql/ddl.ts"() {
|
|
615
|
-
"use strict";
|
|
616
|
-
init_lexer();
|
|
617
|
-
init_literals();
|
|
618
|
-
init_parser();
|
|
619
|
-
}
|
|
620
|
-
});
|
|
621
|
-
|
|
622
|
-
// lib/tools/sql/transforms.ts
|
|
623
|
-
var transforms_exports = {};
|
|
624
|
-
__export(transforms_exports, {
|
|
625
|
-
formatSqlTool: () => formatSqlTool,
|
|
626
|
-
insertOutput: () => insertOutput,
|
|
627
|
-
minifySqlTool: () => minifySqlTool,
|
|
628
|
-
parseInsertData: () => parseInsertData,
|
|
629
|
-
validateSqlTool: () => validateSqlTool
|
|
630
|
-
});
|
|
631
|
-
async function validateSqlTool(sql, dialect) {
|
|
632
|
-
dialect = readDialect(dialect);
|
|
633
|
-
try {
|
|
634
|
-
await parseSql(sql, dialect);
|
|
635
|
-
return { rows: [{ label: "Valid/Invalid status", value: "Valid" }, { label: "Syntax error message", value: "None" }, { label: "Error location", value: "None" }], warnings: [parserWarning] };
|
|
636
|
-
} catch (error) {
|
|
637
|
-
const safe = error instanceof SqlSyntaxError ? error : new SqlSyntaxError("The selected dialect parser could not process this SQL.");
|
|
638
|
-
return { rows: [{ label: "Valid/Invalid status", value: "Invalid" }, { label: "Syntax error message", value: safe.message }, { label: "Error location", value: safe.line && safe.column ? `Line ${safe.line}, Column ${safe.column}` : "Unavailable" }], warnings: [parserWarning] };
|
|
639
|
-
}
|
|
640
|
-
}
|
|
641
|
-
async function minifySqlTool(sql, dialect) {
|
|
642
|
-
dialect = readDialect(dialect);
|
|
643
|
-
const tokens = lexSql(sql, dialect);
|
|
644
|
-
const surviving = significantTokens(tokens);
|
|
645
|
-
const containsContinuation = dialect === "PostgreSQL" && surviving.some((token, i) => i > 0 && token.kind === "string" && surviving[i - 1].kind === "string" && /[\r\n]/.test(sql.slice(surviving[i - 1].end, token.start)));
|
|
646
|
-
const knownParserExtension = containsContinuation || tokens.some((token) => token.kind === "protected" || token.kind === "comment" && token.text.slice(2).includes("/*"));
|
|
647
|
-
await parseSql(sql, dialect).catch(async (error) => {
|
|
648
|
-
if (!(error instanceof SqlSyntaxError)) throw error;
|
|
649
|
-
if (dialect === "SQL Server" && surviving[0]?.text.toUpperCase() === "CREATE" && surviving.some((token) => token.kind === "word" && token.text.toUpperCase() === "REFERENCES")) {
|
|
650
|
-
const { parseDdl: parseDdl2 } = await Promise.resolve().then(() => (init_ddl(), ddl_exports));
|
|
651
|
-
await parseDdl2(sql, dialect);
|
|
652
|
-
return;
|
|
653
|
-
}
|
|
654
|
-
if (!knownParserExtension) throw error;
|
|
655
|
-
});
|
|
656
|
-
let output2 = "", pending = "", previous;
|
|
657
|
-
for (const token of tokens) {
|
|
658
|
-
if (token.kind === "space") {
|
|
659
|
-
pending += token.text;
|
|
660
|
-
continue;
|
|
661
|
-
}
|
|
662
|
-
if (token.kind === "comment") {
|
|
663
|
-
pending += token.text.includes("\n") || token.text.includes("\r") ? "\n" : " ";
|
|
664
|
-
continue;
|
|
665
|
-
}
|
|
666
|
-
if (previous && pending) {
|
|
667
|
-
const continuation = /[\r\n]/.test(pending) && (dialect === "PostgreSQL" && previous.kind === "string" && token.kind === "string" || dialect === "SQL Server");
|
|
668
|
-
output2 += continuation ? "\n" : " ";
|
|
669
|
-
}
|
|
670
|
-
output2 += token.text;
|
|
671
|
-
previous = token;
|
|
672
|
-
pending = "";
|
|
673
|
-
}
|
|
674
|
-
return { rows: [{ label: "Minified SQL", value: output2 }], warnings: ["Formatting whitespace and ordinary comments are removed conservatively. Executable/hint comments and newline-sensitive PostgreSQL string continuation are preserved. This is not a database syntax check."] };
|
|
675
|
-
}
|
|
676
|
-
async function formatSqlTool(sql, dialect) {
|
|
677
|
-
dialect = readDialect(dialect);
|
|
678
|
-
const sourceTokens = significantTokens(lexSql(sql, dialect));
|
|
679
|
-
let warning;
|
|
680
|
-
try {
|
|
681
|
-
await parseSql(sql, dialect);
|
|
682
|
-
} catch (error) {
|
|
683
|
-
if (!(error instanceof SqlSyntaxError)) throw error;
|
|
684
|
-
const continuation = dialect === "PostgreSQL" && sourceTokens.some((token, index) => index > 0 && token.kind === "string" && sourceTokens[index - 1].kind === "string" && /[\r\n]/.test(sql.slice(sourceTokens[index - 1].end, token.start)));
|
|
685
|
-
const specialComments = lexSql(sql, dialect).some((token) => token.kind === "protected" || token.kind === "comment" && token.text.slice(2).includes("/*"));
|
|
686
|
-
if (dialect === "SQL Server" && sourceTokens[0]?.text.toUpperCase() === "CREATE" && sourceTokens.some((token) => token.kind === "word" && token.text.toUpperCase() === "REFERENCES")) {
|
|
687
|
-
const { parseDdl: parseDdl2 } = await Promise.resolve().then(() => (init_ddl(), ddl_exports));
|
|
688
|
-
await parseDdl2(sql, dialect);
|
|
689
|
-
} else if (continuation || specialComments) warning = "Layout preserves this dialect extension, but the local parser could not validate its complete syntax. This result is not syntax-validation proof.";
|
|
690
|
-
else throw error;
|
|
691
|
-
}
|
|
692
|
-
const { format } = await import("sql-formatter");
|
|
693
|
-
let output2;
|
|
694
|
-
try {
|
|
695
|
-
output2 = format(sql, { language: formatterLanguages[dialect], tabWidth: 2 });
|
|
696
|
-
} catch (error) {
|
|
697
|
-
const message = error instanceof Error ? error.message : "";
|
|
698
|
-
const position = /\bline (\d+) column (\d+)\b/i.exec(message);
|
|
699
|
-
throw new SqlSyntaxError("The selected dialect formatter cannot process this syntax. Check syntax or unsupported dialect extensions.", position ? { line: Number(position[1]), column: Number(position[2]) } : void 0);
|
|
700
|
-
}
|
|
701
|
-
const targetTokens = significantTokens(lexSql(output2, dialect));
|
|
702
|
-
if (sourceTokens.length !== targetTokens.length || sourceTokens.some((token, i) => token.kind !== targetTokens[i].kind || token.text !== targetTokens[i].text)) {
|
|
703
|
-
throw new SqlSyntaxError("Formatting would change SQL tokens; this dialect syntax is unsupported by the formatter.");
|
|
704
|
-
}
|
|
705
|
-
const fixes = [];
|
|
706
|
-
if (dialect === "PostgreSQL") for (let i = 1; i < sourceTokens.length; i++) {
|
|
707
|
-
const before = sourceTokens[i - 1], current = sourceTokens[i];
|
|
708
|
-
if (before.kind === "string" && current.kind === "string") {
|
|
709
|
-
const sourceGap = sql.slice(before.end, current.start);
|
|
710
|
-
const targetGap = output2.slice(targetTokens[i - 1].end, targetTokens[i].start);
|
|
711
|
-
if (/[\r\n]/.test(sourceGap) !== /[\r\n]/.test(targetGap)) {
|
|
712
|
-
fixes.push({ start: targetTokens[i - 1].end, end: targetTokens[i].start, value: sourceGap });
|
|
713
|
-
}
|
|
714
|
-
}
|
|
715
|
-
}
|
|
716
|
-
for (const fix of fixes.reverse()) output2 = output2.slice(0, fix.start) + fix.value + output2.slice(fix.end);
|
|
717
|
-
return { rows: [{ label: "Formatted SQL", value: output2 }], ...warning ? { warnings: [warning] } : {} };
|
|
718
|
-
}
|
|
719
|
-
function canonicalNumber(text3) {
|
|
720
|
-
const match = /^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/.exec(text3);
|
|
721
|
-
let digits = (match[2] + (match[3] ?? "")).replace(/^0+/, "");
|
|
722
|
-
if (!digits) return "0";
|
|
723
|
-
let exponent = Number(match[4] ?? 0) - (match[3]?.length ?? 0);
|
|
724
|
-
while (digits.endsWith("0")) {
|
|
725
|
-
digits = digits.slice(0, -1);
|
|
726
|
-
exponent++;
|
|
727
|
-
}
|
|
728
|
-
return `${match[1] === "-" ? "-" : ""}${digits}e${exponent}`;
|
|
729
|
-
}
|
|
730
|
-
function exactNumber(text3, token) {
|
|
731
|
-
const value = Number(text3);
|
|
732
|
-
if (!Number.isFinite(value) || Number.isInteger(value) && !Number.isSafeInteger(value) || canonicalNumber(text3) !== canonicalNumber(String(value))) {
|
|
733
|
-
throw new SqlSyntaxError("A SQL number cannot be represented safely as a JavaScript/JSON number; conversion would lose precision.", token);
|
|
734
|
-
}
|
|
735
|
-
return value;
|
|
736
|
-
}
|
|
737
|
-
function decodeString(token, dialect) {
|
|
738
|
-
let text3 = token.text;
|
|
739
|
-
if (text3[0] === "$") {
|
|
740
|
-
const tag = dollarDelimiter(text3);
|
|
741
|
-
return text3.slice(tag.length, -tag.length);
|
|
742
|
-
}
|
|
743
|
-
const prefix = /^[eEnN]'/.test(text3) ? text3[0].toUpperCase() : "";
|
|
744
|
-
if (prefix) text3 = text3.slice(1);
|
|
745
|
-
const quote = text3[0];
|
|
746
|
-
text3 = text3.slice(1, -1).split(quote + quote).join(quote);
|
|
747
|
-
if (dialect !== "MySQL" && !(dialect === "PostgreSQL" && prefix === "E")) return text3;
|
|
748
|
-
let output2 = "";
|
|
749
|
-
for (let i = 0; i < text3.length; i++) {
|
|
750
|
-
if (text3[i] !== "\\") {
|
|
751
|
-
output2 += text3[i];
|
|
752
|
-
continue;
|
|
753
|
-
}
|
|
754
|
-
const next = text3[++i];
|
|
755
|
-
if (next === void 0) throw new SqlSyntaxError("Incomplete SQL string escape.", token);
|
|
756
|
-
const common = { "0": "\0", b: "\b", f: "\f", n: "\n", r: "\r", t: " ", v: "\v", "\\": "\\", "'": "'", '"': '"' };
|
|
757
|
-
if (dialect === "MySQL") {
|
|
758
|
-
const mysql = { "0": "\0", b: "\b", n: "\n", r: "\r", t: " ", Z: "", "\\": "\\", "'": "'", '"': '"', "%": "\\%", "_": "\\_" };
|
|
759
|
-
output2 += mysql[next] ?? next;
|
|
760
|
-
continue;
|
|
761
|
-
}
|
|
762
|
-
if (/[0-7]/.test(next)) {
|
|
763
|
-
const digits = /^[0-7]{1,3}/.exec(text3.slice(i))[0], value = parseInt(digits, 8);
|
|
764
|
-
if (value > 127) throw new SqlSyntaxError("Non-ASCII PostgreSQL byte escapes need a database encoding and are unsupported.", token);
|
|
765
|
-
if (value === 0) throw new SqlSyntaxError("PostgreSQL string literals cannot contain a zero byte.", token);
|
|
766
|
-
output2 += String.fromCharCode(value);
|
|
767
|
-
i += digits.length - 1;
|
|
768
|
-
} else if (next === "x") {
|
|
769
|
-
const digits = /^[0-9a-fA-F]{1,2}/.exec(text3.slice(i + 1))?.[0];
|
|
770
|
-
if (!digits) throw new SqlSyntaxError("Invalid PostgreSQL hexadecimal string escape.", token);
|
|
771
|
-
const value = parseInt(digits, 16);
|
|
772
|
-
if (value > 127) throw new SqlSyntaxError("Non-ASCII PostgreSQL byte escapes need a database encoding and are unsupported.", token);
|
|
773
|
-
if (value === 0) throw new SqlSyntaxError("PostgreSQL string literals cannot contain a zero byte.", token);
|
|
774
|
-
output2 += String.fromCharCode(value);
|
|
775
|
-
i += digits.length;
|
|
776
|
-
} else if (next === "u" || next === "U") {
|
|
777
|
-
const length = next === "u" ? 4 : 8, digits = text3.slice(i + 1, i + 1 + length);
|
|
778
|
-
if (!new RegExp(`^[0-9a-fA-F]{${length}}$`).test(digits)) throw new SqlSyntaxError("Invalid PostgreSQL Unicode string escape.", token);
|
|
779
|
-
const value = parseInt(digits, 16);
|
|
780
|
-
if (value === 0 || value > 1114111 || value >= 55296 && value <= 57343) throw new SqlSyntaxError("Unsupported Unicode code point in PostgreSQL escape.", token);
|
|
781
|
-
output2 += String.fromCodePoint(value);
|
|
782
|
-
i += length;
|
|
783
|
-
} else output2 += common[next] ?? next;
|
|
784
|
-
}
|
|
785
|
-
return output2;
|
|
786
|
-
}
|
|
787
|
-
function readCell(cursor, dialect, sql) {
|
|
788
|
-
let token = cursor.take();
|
|
789
|
-
if (token.kind === "string") {
|
|
790
|
-
let value = decodeString(token, dialect);
|
|
791
|
-
while (cursor.peek()?.kind === "string") {
|
|
792
|
-
const next = cursor.peek();
|
|
793
|
-
if (dialect !== "PostgreSQL" || !/[\r\n]/.test(sql.slice(token.end, next.start)) || next.text[0] !== "'") cursor.fail("Adjacent string literals are unsupported except PostgreSQL newline continuation.");
|
|
794
|
-
cursor.take();
|
|
795
|
-
value += decodeString(next, dialect);
|
|
796
|
-
token = next;
|
|
797
|
-
}
|
|
798
|
-
return value;
|
|
799
|
-
}
|
|
800
|
-
let sign = "";
|
|
801
|
-
if (token.text === "+" || token.text === "-") {
|
|
802
|
-
sign = token.text;
|
|
803
|
-
token = cursor.take();
|
|
804
|
-
}
|
|
805
|
-
if (token.kind === "number") return exactNumber(sign + token.text, token);
|
|
806
|
-
if (sign) cursor.fail("Unary signs require a numeric literal.");
|
|
807
|
-
if (token.text.toUpperCase() === "NULL") return null;
|
|
808
|
-
if (token.text.toUpperCase() === "TRUE" || token.text.toUpperCase() === "FALSE") {
|
|
809
|
-
if (dialect === "SQL Server") cursor.fail("SQL Server Boolean values must be numeric 1/0 literals.");
|
|
810
|
-
return token.text.toUpperCase() === "TRUE";
|
|
811
|
-
}
|
|
812
|
-
cursor.fail("INSERT conversion supports literal VALUES only; expressions, functions, casts, DEFAULT and SELECT are unsupported.");
|
|
813
|
-
}
|
|
814
|
-
function nameKey(name2, dialect) {
|
|
815
|
-
return dialect === "PostgreSQL" ? name2 : name2.toLowerCase();
|
|
816
|
-
}
|
|
817
|
-
function readName(cursor, dialect) {
|
|
818
|
-
const token = cursor.take(), name2 = identifierValue(token);
|
|
819
|
-
if (name2.length > 128) cursor.fail("INSERT identifiers are limited to 128 characters.");
|
|
820
|
-
return dialect === "PostgreSQL" && token.kind === "word" ? name2.toLowerCase() : name2;
|
|
821
|
-
}
|
|
822
|
-
function readQualifiedName(cursor, dialect) {
|
|
823
|
-
const parts = [readName(cursor, dialect)];
|
|
824
|
-
while (cursor.accept(".")) parts.push(readName(cursor, dialect));
|
|
825
|
-
const maximumParts = dialect === "SQL Server" ? 4 : dialect === "PostgreSQL" ? 3 : 2;
|
|
826
|
-
if (parts.length > maximumParts) cursor.fail("The table identifier has unsupported qualification for the selected dialect.");
|
|
827
|
-
if (parts.some((part) => part.includes("."))) cursor.fail("Quoted table identifiers containing dots are unsupported; use explicit qualification parts.");
|
|
828
|
-
return parts.join(".");
|
|
829
|
-
}
|
|
830
|
-
async function parseInsertData(sql, dialect) {
|
|
831
|
-
dialect = readDialect(dialect);
|
|
832
|
-
const cursor = new TokenCursor(significantTokens(lexSql(sql, dialect)));
|
|
833
|
-
let columns2, table, statements = 0;
|
|
834
|
-
const rows = [];
|
|
835
|
-
while (cursor.peek()) {
|
|
836
|
-
if (++statements > 200) cursor.fail("SQL exceeds the 200-statement limit.");
|
|
837
|
-
cursor.expect("INSERT");
|
|
838
|
-
cursor.expect("INTO");
|
|
839
|
-
const currentTable = readQualifiedName(cursor, dialect);
|
|
840
|
-
cursor.expect("(");
|
|
841
|
-
const currentColumns = [];
|
|
842
|
-
do {
|
|
843
|
-
currentColumns.push(readName(cursor, dialect));
|
|
844
|
-
} while (cursor.accept(","));
|
|
845
|
-
cursor.expect(")");
|
|
846
|
-
if (currentColumns.length > 500) cursor.fail("INSERT conversion is limited to 500 columns.");
|
|
847
|
-
if (new Set(currentColumns.map((name2) => nameKey(name2, dialect))).size !== currentColumns.length) cursor.fail("Duplicate INSERT column names are unsupported.");
|
|
848
|
-
if (columns2 && (currentTable !== table || currentColumns.length !== columns2.length || currentColumns.some((name2, i) => name2 !== columns2[i]))) cursor.fail("All INSERT statements must use the same exact table identifier and identical ordered column names.");
|
|
849
|
-
columns2 ??= currentColumns;
|
|
850
|
-
table ??= currentTable;
|
|
851
|
-
cursor.expect("VALUES");
|
|
852
|
-
do {
|
|
853
|
-
cursor.expect("(");
|
|
854
|
-
const row = [];
|
|
855
|
-
do {
|
|
856
|
-
row.push(readCell(cursor, dialect, sql));
|
|
857
|
-
} while (cursor.accept(","));
|
|
858
|
-
cursor.expect(")");
|
|
859
|
-
if (row.length !== columns2.length) cursor.fail("INSERT row arity does not match the named columns.");
|
|
860
|
-
rows.push(row);
|
|
861
|
-
if (rows.length > 1e4) cursor.fail("INSERT conversion is limited to 10,000 rows.");
|
|
862
|
-
} while (cursor.accept(","));
|
|
863
|
-
if (cursor.peek() && !cursor.accept(";")) cursor.fail("INSERT modifiers, conflict/duplicate clauses, RETURNING, and additional expressions are unsupported.");
|
|
864
|
-
}
|
|
865
|
-
if (!columns2 || !rows.length) throw new SqlSyntaxError("Enter INSERT statements with named columns and literal VALUES.");
|
|
866
|
-
return { columns: columns2, rows };
|
|
867
|
-
}
|
|
868
|
-
async function insertOutput(toolId, sql, dialect) {
|
|
869
|
-
const { columns: columns2, rows } = await parseInsertData(sql, dialect);
|
|
870
|
-
const keySize = columns2.reduce((total, column) => total + JSON.stringify(column).length + 10, 0);
|
|
871
|
-
let projectedSize = columns2.join(",").length + 100;
|
|
872
|
-
for (const row of rows) {
|
|
873
|
-
projectedSize += keySize + row.reduce((total, value) => total + JSON.stringify(value).length + 6, 0);
|
|
874
|
-
if (projectedSize > 2e6) throw new SqlSyntaxError("INSERT conversion exceeds the 2,000,000-character output budget.");
|
|
875
|
-
}
|
|
876
|
-
if (toolId === "sql-to-json") return { rows: [{ label: "JSON array of objects", value: JSON.stringify(rows.map((row) => Object.fromEntries(columns2.map((column, i) => [column, row[i]]))), null, 2) }] };
|
|
877
|
-
if (toolId === "sql-to-csv") {
|
|
878
|
-
const csv = (value) => value === null ? "" : typeof value === "string" ? `"${value.replace(/"/g, '""')}"` : String(value);
|
|
879
|
-
return { rows: [{ label: "CSV text", value: [columns2.map(csv).join(","), ...rows.map((row) => row.map(csv).join(","))].join("\r\n") }], warnings: ["CSV has no intrinsic null type: SQL NULL is an unquoted empty cell; empty strings are quoted empty cells. A CSV reader may discard this distinction."] };
|
|
880
|
-
}
|
|
881
|
-
if (toolId === "sql-to-markdown") {
|
|
882
|
-
const markdown = (value) => value === null ? "NULL" : String(value).replace(/\\/g, "\\\\").replace(/\|/g, "\\|").replace(/\r\n|\r|\n/g, "<br>");
|
|
883
|
-
const line = (values) => `| ${values.map(markdown).join(" | ")} |`;
|
|
884
|
-
return { rows: [{ label: "Markdown table", value: [line(columns2), line(columns2.map(() => "---")), ...rows.map(line)].join("\n") }] };
|
|
885
|
-
}
|
|
886
|
-
throw new SqlSyntaxError("Unsupported SQL INSERT conversion tool.");
|
|
887
|
-
}
|
|
888
|
-
var formatterLanguages, parserWarning;
|
|
889
|
-
var init_transforms = __esm({
|
|
890
|
-
"lib/tools/sql/transforms.ts"() {
|
|
891
|
-
"use strict";
|
|
892
|
-
init_lexer();
|
|
893
|
-
init_parser();
|
|
894
|
-
init_literals();
|
|
895
|
-
formatterLanguages = { PostgreSQL: "postgresql", MySQL: "mysql", SQLite: "sqlite", "SQL Server": "transactsql" };
|
|
896
|
-
parserWarning = "Acceptance is limited to the selected dialect's local parser subset; this does not check database objects, permissions, or execution semantics.";
|
|
897
|
-
}
|
|
898
|
-
});
|
|
899
2
|
|
|
900
3
|
// mcp/cli.ts
|
|
901
4
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
@@ -927,7 +30,13 @@ var PRO_TOOLS = /* @__PURE__ */ new Set([
|
|
|
927
30
|
"codestation_timezone_convert",
|
|
928
31
|
"codestation_business_days",
|
|
929
32
|
"codestation_regex_test",
|
|
930
|
-
"codestation_json_schema"
|
|
33
|
+
"codestation_json_schema",
|
|
34
|
+
"codestation_json_to_typescript",
|
|
35
|
+
"codestation_json_to_zod",
|
|
36
|
+
"codestation_curl_to_code",
|
|
37
|
+
"codestation_env_audit",
|
|
38
|
+
"codestation_mock_data",
|
|
39
|
+
"codestation_git_conflict"
|
|
931
40
|
]);
|
|
932
41
|
var CACHE_DIR = path.join(os.homedir(), ".codestation");
|
|
933
42
|
var CACHE_FILE = path.join(CACHE_DIR, "license.json");
|
|
@@ -943,14 +52,14 @@ function readCachedLicense() {
|
|
|
943
52
|
}
|
|
944
53
|
return null;
|
|
945
54
|
}
|
|
946
|
-
function saveCachedLicense(
|
|
55
|
+
function saveCachedLicense(key, isPro) {
|
|
947
56
|
try {
|
|
948
57
|
if (process.env.NODE_ENV === "test") return;
|
|
949
58
|
if (!fs.existsSync(CACHE_DIR)) {
|
|
950
59
|
fs.mkdirSync(CACHE_DIR, { recursive: true });
|
|
951
60
|
}
|
|
952
61
|
const cache = {
|
|
953
|
-
key
|
|
62
|
+
key,
|
|
954
63
|
verifiedAt: Date.now(),
|
|
955
64
|
isPro
|
|
956
65
|
};
|
|
@@ -960,12 +69,12 @@ function saveCachedLicense(key2, isPro) {
|
|
|
960
69
|
}
|
|
961
70
|
function validateLicenseKey(rawKey) {
|
|
962
71
|
if (!rawKey) return false;
|
|
963
|
-
const
|
|
964
|
-
if (!
|
|
965
|
-
if (/^CS-PRO-[A-Za-z0-9_-]+$/i.test(
|
|
72
|
+
const key = rawKey.trim();
|
|
73
|
+
if (!key) return false;
|
|
74
|
+
if (/^CS-PRO-[A-Za-z0-9_-]+$/i.test(key) || key.startsWith("cspro_")) {
|
|
966
75
|
return true;
|
|
967
76
|
}
|
|
968
|
-
if (
|
|
77
|
+
if (key === "PRO_DEMO_KEY" || key === "CS-PRO-DEV") {
|
|
969
78
|
return true;
|
|
970
79
|
}
|
|
971
80
|
return false;
|
|
@@ -1077,7 +186,7 @@ function generateJsonSchema(value) {
|
|
|
1077
186
|
if (node === null) return { type: "null" };
|
|
1078
187
|
if (Array.isArray(node)) return { type: "array", items: node.length ? infer(node[0]) : {} };
|
|
1079
188
|
if (typeof node === "object") {
|
|
1080
|
-
const properties = Object.fromEntries(Object.entries(node).map(([
|
|
189
|
+
const properties = Object.fromEntries(Object.entries(node).map(([key, child]) => [key, infer(child)]));
|
|
1081
190
|
return { type: "object", properties, required: Object.keys(properties), additionalProperties: false };
|
|
1082
191
|
}
|
|
1083
192
|
return { type: typeof node === "number" && Number.isInteger(node) ? "integer" : typeof node };
|
|
@@ -1096,7 +205,7 @@ function decodeJwt(value) {
|
|
|
1096
205
|
throw new Error("JWT header and payload must contain valid Base64URL-encoded JSON.");
|
|
1097
206
|
}
|
|
1098
207
|
}
|
|
1099
|
-
function testRegex(pattern, flags,
|
|
208
|
+
function testRegex(pattern, flags, text2) {
|
|
1100
209
|
let regex;
|
|
1101
210
|
try {
|
|
1102
211
|
regex = new RegExp(pattern, flags);
|
|
@@ -1105,11 +214,11 @@ function testRegex(pattern, flags, text3) {
|
|
|
1105
214
|
}
|
|
1106
215
|
const matches = [];
|
|
1107
216
|
if (!regex.global) {
|
|
1108
|
-
const match = regex.exec(
|
|
217
|
+
const match = regex.exec(text2);
|
|
1109
218
|
if (match) matches.push({ match: match[0], index: match.index, groups: match.groups ?? {}, captures: match.slice(1) });
|
|
1110
219
|
} else {
|
|
1111
220
|
let match;
|
|
1112
|
-
while ((match = regex.exec(
|
|
221
|
+
while ((match = regex.exec(text2)) !== null) {
|
|
1113
222
|
matches.push({ match: match[0], index: match.index, groups: match.groups ?? {}, captures: match.slice(1) });
|
|
1114
223
|
if (match[0] === "") regex.lastIndex += 1;
|
|
1115
224
|
}
|
|
@@ -1117,7 +226,7 @@ function testRegex(pattern, flags, text3) {
|
|
|
1117
226
|
return JSON.stringify({ count: matches.length, matches }, null, 2);
|
|
1118
227
|
}
|
|
1119
228
|
function utf8Decode(bytes2) {
|
|
1120
|
-
let
|
|
229
|
+
let result = "";
|
|
1121
230
|
for (let i = 0; i < bytes2.length; ) {
|
|
1122
231
|
const first = bytes2[i++];
|
|
1123
232
|
let code;
|
|
@@ -1126,13 +235,13 @@ function utf8Decode(bytes2) {
|
|
|
1126
235
|
else if (first >= 224 && first <= 239 && i + 1 < bytes2.length) code = (first & 15) << 12 | (bytes2[i++] & 63) << 6 | bytes2[i++] & 63;
|
|
1127
236
|
else if (first >= 240 && first <= 244 && i + 2 < bytes2.length) code = (first & 7) << 18 | (bytes2[i++] & 63) << 12 | (bytes2[i++] & 63) << 6 | bytes2[i++] & 63;
|
|
1128
237
|
else throw new Error("Invalid UTF-8 data");
|
|
1129
|
-
if (code <= 65535)
|
|
238
|
+
if (code <= 65535) result += String.fromCharCode(code);
|
|
1130
239
|
else {
|
|
1131
240
|
const n = code - 65536;
|
|
1132
|
-
|
|
241
|
+
result += String.fromCharCode(55296 | n >> 10, 56320 | n & 1023);
|
|
1133
242
|
}
|
|
1134
243
|
}
|
|
1135
|
-
return
|
|
244
|
+
return result;
|
|
1136
245
|
}
|
|
1137
246
|
var BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
1138
247
|
function decodeBase64(value) {
|
|
@@ -1249,16 +358,16 @@ function sha1(input) {
|
|
|
1249
358
|
return [h0, h1, h2, h3, h4].map((value) => (value >>> 0).toString(16).padStart(8, "0")).join("");
|
|
1250
359
|
}
|
|
1251
360
|
async function hash(input, algorithm = "SHA-256") {
|
|
1252
|
-
const
|
|
1253
|
-
return hex(new Uint8Array(
|
|
361
|
+
const result = await requireCrypto().subtle.digest(algorithm, webBytes(input));
|
|
362
|
+
return hex(new Uint8Array(result));
|
|
1254
363
|
}
|
|
1255
364
|
var sha256 = (input) => hash(input, "SHA-256");
|
|
1256
365
|
var sha384 = (input) => hash(input, "SHA-384");
|
|
1257
366
|
var sha512 = (input) => hash(input, "SHA-512");
|
|
1258
367
|
async function hmac(input, secret, algorithm = "SHA-256") {
|
|
1259
368
|
const crypto2 = requireCrypto();
|
|
1260
|
-
const
|
|
1261
|
-
return hex(new Uint8Array(await crypto2.subtle.sign("HMAC",
|
|
369
|
+
const key = await crypto2.subtle.importKey("raw", webBytes(secret), { name: "HMAC", hash: algorithm }, false, ["sign"]);
|
|
370
|
+
return hex(new Uint8Array(await crypto2.subtle.sign("HMAC", key, webBytes(input))));
|
|
1262
371
|
}
|
|
1263
372
|
var hmacSha256 = (input, secret) => hmac(input, secret, "SHA-256");
|
|
1264
373
|
var hmacSha512 = (input, secret) => hmac(input, secret, "SHA-512");
|
|
@@ -1339,9 +448,9 @@ var LOREM_WORDS = [
|
|
|
1339
448
|
"est",
|
|
1340
449
|
"laborum"
|
|
1341
450
|
].map((word) => word.trim());
|
|
1342
|
-
function assertText(value,
|
|
1343
|
-
if (typeof value !== "string") throw new TypeError(`${
|
|
1344
|
-
if (value.length > MAX_TEXT_LENGTH) throw new RangeError(`${
|
|
451
|
+
function assertText(value, name = "text") {
|
|
452
|
+
if (typeof value !== "string") throw new TypeError(`${name} must be a string.`);
|
|
453
|
+
if (value.length > MAX_TEXT_LENGTH) throw new RangeError(`${name} must be at most ${MAX_TEXT_LENGTH.toLocaleString()} characters.`);
|
|
1345
454
|
return value;
|
|
1346
455
|
}
|
|
1347
456
|
function parseLines(value) {
|
|
@@ -1430,8 +539,8 @@ function buildUnified(operations) {
|
|
|
1430
539
|
added += 1;
|
|
1431
540
|
return { type: "addition", text: operation.text, oldLine: null, newLine: newLine++ };
|
|
1432
541
|
});
|
|
1433
|
-
const
|
|
1434
|
-
return { lines, text:
|
|
542
|
+
const text2 = ["--- left", "+++ right", ...lines.map((line) => `${line.type === "context" ? " " : line.type === "deletion" ? "-" : "+"}${line.text}`)].join("\n");
|
|
543
|
+
return { lines, text: text2, added, removed };
|
|
1435
544
|
}
|
|
1436
545
|
function buildSideBySide(operations) {
|
|
1437
546
|
const rows = [];
|
|
@@ -1498,16 +607,16 @@ var HOUR = 60 * MINUTE;
|
|
|
1498
607
|
var DAY = 24 * HOUR;
|
|
1499
608
|
var MIN_DATE = -621355968e5;
|
|
1500
609
|
var MAX_DATE = 253402300799999;
|
|
1501
|
-
function integer(value,
|
|
1502
|
-
if (!Number.isInteger(value) || value < min || value > max) throw new RangeError(`${
|
|
610
|
+
function integer(value, name, min, max) {
|
|
611
|
+
if (!Number.isInteger(value) || value < min || value > max) throw new RangeError(`${name} must be an integer between ${min} and ${max}.`);
|
|
1503
612
|
return value;
|
|
1504
613
|
}
|
|
1505
|
-
function inputText(value,
|
|
1506
|
-
if (typeof value !== "string") throw new TypeError(`${
|
|
1507
|
-
const
|
|
1508
|
-
if (!
|
|
1509
|
-
if (
|
|
1510
|
-
return
|
|
614
|
+
function inputText(value, name = "Date", max = 256) {
|
|
615
|
+
if (typeof value !== "string") throw new TypeError(`${name} must be text.`);
|
|
616
|
+
const text2 = value.trim();
|
|
617
|
+
if (!text2) throw new Error(`${name} cannot be empty.`);
|
|
618
|
+
if (text2.length > max) throw new RangeError(`${name} must be at most ${max} characters.`);
|
|
619
|
+
return text2;
|
|
1511
620
|
}
|
|
1512
621
|
function isGregorianLeapYear(year) {
|
|
1513
622
|
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
@@ -1543,9 +652,9 @@ function timestampToDate(value, unit = "seconds") {
|
|
|
1543
652
|
timestampUnit(unit);
|
|
1544
653
|
let number;
|
|
1545
654
|
if (typeof value === "string") {
|
|
1546
|
-
const
|
|
1547
|
-
if (!/^[+-]?\d+(?:\.\d+)?$/.test(
|
|
1548
|
-
number = Number(
|
|
655
|
+
const text2 = inputText(value, "Timestamp");
|
|
656
|
+
if (!/^[+-]?\d+(?:\.\d+)?$/.test(text2)) throw new Error("Timestamp must be a decimal number, without exponent notation.");
|
|
657
|
+
number = Number(text2);
|
|
1549
658
|
} else if (typeof value === "number") number = value;
|
|
1550
659
|
else throw new TypeError("Timestamp must be a number or numeric text.");
|
|
1551
660
|
if (!Number.isFinite(number)) throw new RangeError("Timestamp must be finite.");
|
|
@@ -1629,9 +738,9 @@ function parseDateTime(value, options = {}) {
|
|
|
1629
738
|
if (options.timeZone !== void 0) validateTimeZone(options.timeZone);
|
|
1630
739
|
if (value instanceof Date) return checkedDate(value.getTime());
|
|
1631
740
|
if (typeof value === "number") return timestampToDate(value, options.timestampUnit ?? "milliseconds");
|
|
1632
|
-
const
|
|
1633
|
-
if (/^[+-]?\d+(?:\.\d+)?$/.test(
|
|
1634
|
-
const match = /^(\d{4})-(\d{2})-(\d{2})(?:[Tt ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?([Zz]|[+-]\d{2}:?\d{2})?)?$/.exec(
|
|
741
|
+
const text2 = inputText(value);
|
|
742
|
+
if (/^[+-]?\d+(?:\.\d+)?$/.test(text2)) return timestampToDate(text2, options.timestampUnit ?? "milliseconds");
|
|
743
|
+
const match = /^(\d{4})-(\d{2})-(\d{2})(?:[Tt ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?([Zz]|[+-]\d{2}:?\d{2})?)?$/.exec(text2);
|
|
1635
744
|
if (!match) throw new Error("Use YYYY-MM-DD, an ISO date/time with up to 3 fractional digits, or an explicit numeric timestamp.");
|
|
1636
745
|
return partsToDate({
|
|
1637
746
|
year: Number(match[1]),
|
|
@@ -1759,30 +868,30 @@ var SPECS = [
|
|
|
1759
868
|
{ name: "dayOfWeek", label: "Day of week", min: 0, max: 7 }
|
|
1760
869
|
];
|
|
1761
870
|
function parseField(expression, spec) {
|
|
1762
|
-
const
|
|
871
|
+
const fail2 = (message) => {
|
|
1763
872
|
throw new Error(`${spec.label}: ${message}`);
|
|
1764
873
|
};
|
|
1765
|
-
if (expression.length > 128)
|
|
1766
|
-
if (!expression)
|
|
1767
|
-
const endpoint = (
|
|
874
|
+
if (expression.length > 128) fail2("field exceeds the 128-character limit.");
|
|
875
|
+
if (!expression) fail2("field cannot be empty.");
|
|
876
|
+
const endpoint = (text2) => {
|
|
1768
877
|
let value;
|
|
1769
|
-
if (/^\d+$/.test(
|
|
1770
|
-
else if (spec.name === "month" && MONTH_NAMES.includes(
|
|
1771
|
-
else if (spec.name === "dayOfWeek" && WEEKDAY_NAMES.includes(
|
|
1772
|
-
else return
|
|
1773
|
-
if (!Number.isSafeInteger(value) || value < spec.min || value > spec.max)
|
|
878
|
+
if (/^\d+$/.test(text2)) value = Number(text2);
|
|
879
|
+
else if (spec.name === "month" && MONTH_NAMES.includes(text2.toUpperCase())) value = MONTH_NAMES.indexOf(text2.toUpperCase()) + 1;
|
|
880
|
+
else if (spec.name === "dayOfWeek" && WEEKDAY_NAMES.includes(text2.toUpperCase())) value = WEEKDAY_NAMES.indexOf(text2.toUpperCase());
|
|
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}.`);
|
|
1774
883
|
return value;
|
|
1775
884
|
};
|
|
1776
885
|
const selected = /* @__PURE__ */ new Set();
|
|
1777
886
|
for (const item of expression.split(",")) {
|
|
1778
|
-
if (!item)
|
|
887
|
+
if (!item) fail2("lists cannot contain empty items.");
|
|
1779
888
|
const pieces = item.split("/");
|
|
1780
|
-
if (pieces.length > 2 || !pieces[0])
|
|
889
|
+
if (pieces.length > 2 || !pieces[0]) fail2("malformed step notation.");
|
|
1781
890
|
let step = 1;
|
|
1782
891
|
if (pieces.length === 2) {
|
|
1783
|
-
if (!/^\d+$/.test(pieces[1]))
|
|
892
|
+
if (!/^\d+$/.test(pieces[1])) fail2("step must be a positive integer.");
|
|
1784
893
|
step = Number(pieces[1]);
|
|
1785
|
-
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}.`);
|
|
1786
895
|
}
|
|
1787
896
|
const base = pieces[0];
|
|
1788
897
|
let first;
|
|
@@ -1792,10 +901,10 @@ function parseField(expression, spec) {
|
|
|
1792
901
|
last = spec.max;
|
|
1793
902
|
} else {
|
|
1794
903
|
const range = base.split("-");
|
|
1795
|
-
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.");
|
|
1796
905
|
first = endpoint(range[0]);
|
|
1797
906
|
last = range.length === 2 ? endpoint(range[1]) : pieces.length === 2 ? spec.max : first;
|
|
1798
|
-
if (last < first)
|
|
907
|
+
if (last < first) fail2("descending or wrapping ranges are not supported.");
|
|
1799
908
|
}
|
|
1800
909
|
for (let value = first; value <= last; value += step) selected.add(spec.name === "dayOfWeek" && value === 7 ? 0 : value);
|
|
1801
910
|
}
|
|
@@ -1816,6 +925,12 @@ function parseCron(expression) {
|
|
|
1816
925
|
const [minute, hour, dayOfMonth, month, dayOfWeek] = fields.slice(hasSeconds ? 1 : 0);
|
|
1817
926
|
return { expression, hasSeconds, fields, second, minute, hour, dayOfMonth, month, dayOfWeek, dayMode: dayOfMonth.wildcard || dayOfWeek.wildcard ? "and" : "or" };
|
|
1818
927
|
}
|
|
928
|
+
function matchesCronDate(cron, year, month, day) {
|
|
929
|
+
if (!cron.month.values.includes(month)) return false;
|
|
930
|
+
const dom = cron.dayOfMonth.values.includes(day);
|
|
931
|
+
const dow = cron.dayOfWeek.values.includes(new Date(Date.UTC(year, month - 1, day)).getUTCDay());
|
|
932
|
+
return cron.dayMode === "and" ? dom && dow : dom || dow;
|
|
933
|
+
}
|
|
1819
934
|
|
|
1820
935
|
// lib/tools/cron/explain.ts
|
|
1821
936
|
var FULL_MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
|
|
@@ -1837,638 +952,1546 @@ function explainCron(cron) {
|
|
|
1837
952
|
return `${timing}; ${days}${months}.`;
|
|
1838
953
|
}
|
|
1839
954
|
|
|
1840
|
-
// lib/tools/
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
}
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
}
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
const white = () => {
|
|
1887
|
-
while (position < input.length && /[ \t\r\n]/.test(input[position])) position++;
|
|
1888
|
-
};
|
|
1889
|
-
const punctuation = () => {
|
|
1890
|
-
const raw = input[position++];
|
|
1891
|
-
tokens.push({ raw, kind: "punctuation" });
|
|
1892
|
-
return raw;
|
|
1893
|
-
};
|
|
1894
|
-
const string = () => {
|
|
1895
|
-
const start = position++;
|
|
1896
|
-
while (position < input.length) {
|
|
1897
|
-
const char = input[position++];
|
|
1898
|
-
if (char === '"') {
|
|
1899
|
-
const raw = input.slice(start, position);
|
|
1900
|
-
try {
|
|
1901
|
-
const value2 = JSON.parse(raw);
|
|
1902
|
-
tokens.push({ raw, kind: "literal" });
|
|
1903
|
-
return value2;
|
|
1904
|
-
} catch {
|
|
1905
|
-
return fail("Invalid JSON string or escape sequence", start);
|
|
955
|
+
// lib/tools/json-to-types.ts
|
|
956
|
+
function toPascalCase(str) {
|
|
957
|
+
const clean = str.replace(/[^a-zA-Z0-9]/g, " ");
|
|
958
|
+
return clean.split(/\s+/).filter(Boolean).map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("") || "NestedType";
|
|
959
|
+
}
|
|
960
|
+
function isValidIdentifier(name) {
|
|
961
|
+
return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);
|
|
962
|
+
}
|
|
963
|
+
function formatKey(key) {
|
|
964
|
+
return isValidIdentifier(key) ? key : JSON.stringify(key);
|
|
965
|
+
}
|
|
966
|
+
function jsonToTypescript(jsonInput, rootName = "Root") {
|
|
967
|
+
let parsed;
|
|
968
|
+
try {
|
|
969
|
+
parsed = JSON.parse(jsonInput);
|
|
970
|
+
} catch (err) {
|
|
971
|
+
throw new Error(`Invalid JSON: ${err instanceof Error ? err.message : String(err)}`);
|
|
972
|
+
}
|
|
973
|
+
const interfaces = [];
|
|
974
|
+
const createdNames = /* @__PURE__ */ new Set();
|
|
975
|
+
function getUniqueName(base) {
|
|
976
|
+
let name = toPascalCase(base);
|
|
977
|
+
let counter = 1;
|
|
978
|
+
while (createdNames.has(name)) {
|
|
979
|
+
counter += 1;
|
|
980
|
+
name = `${toPascalCase(base)}${counter}`;
|
|
981
|
+
}
|
|
982
|
+
createdNames.add(name);
|
|
983
|
+
return name;
|
|
984
|
+
}
|
|
985
|
+
function resolveType(val, keyHint) {
|
|
986
|
+
if (val === null) return "null";
|
|
987
|
+
if (val === void 0) return "undefined";
|
|
988
|
+
const type = typeof val;
|
|
989
|
+
if (type === "string" || type === "number" || type === "boolean") {
|
|
990
|
+
return type;
|
|
991
|
+
}
|
|
992
|
+
if (Array.isArray(val)) {
|
|
993
|
+
if (val.length === 0) return "unknown[]";
|
|
994
|
+
const itemTypes = /* @__PURE__ */ new Set();
|
|
995
|
+
const sampleObjects = [];
|
|
996
|
+
for (const item of val) {
|
|
997
|
+
if (item && typeof item === "object" && !Array.isArray(item)) {
|
|
998
|
+
sampleObjects.push(item);
|
|
999
|
+
} else {
|
|
1000
|
+
itemTypes.add(resolveType(item, `${keyHint}Item`));
|
|
1906
1001
|
}
|
|
1907
1002
|
}
|
|
1908
|
-
if (
|
|
1909
|
-
|
|
1910
|
-
const
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
|
|
1915
|
-
}
|
|
1916
|
-
}
|
|
1917
|
-
return fail("Unterminated JSON string", start);
|
|
1918
|
-
};
|
|
1919
|
-
const value = (depth) => {
|
|
1920
|
-
white();
|
|
1921
|
-
if (depth > MAX_DEPTH) fail(`JSON nesting exceeds the ${MAX_DEPTH}-level limit`);
|
|
1922
|
-
if (++nodes > MAX_NODES) fail(`JSON exceeds the ${MAX_NODES.toLocaleString("en-US")}-node limit`);
|
|
1923
|
-
const char = input[position];
|
|
1924
|
-
if (char === '"') return string();
|
|
1925
|
-
if (char === "{" || char === "[") {
|
|
1926
|
-
const isArray = punctuation() === "[";
|
|
1927
|
-
const close = isArray ? "]" : "}";
|
|
1928
|
-
const result2 = isArray ? [] : /* @__PURE__ */ Object.create(null);
|
|
1929
|
-
const ordered = [];
|
|
1930
|
-
white();
|
|
1931
|
-
if (input[position] !== close) {
|
|
1932
|
-
while (true) {
|
|
1933
|
-
white();
|
|
1934
|
-
if (isArray) result2.push(value(depth + 1));
|
|
1935
|
-
else {
|
|
1936
|
-
if (input[position] !== '"') fail("Expected a double-quoted object property name");
|
|
1937
|
-
const keyPosition = position;
|
|
1938
|
-
const key2 = string();
|
|
1939
|
-
if (!preserveNumbers && own(result2, key2)) fail(`Duplicate object key ${JSON.stringify(key2)} is ambiguous for this transformation; no values were discarded`, keyPosition);
|
|
1940
|
-
white();
|
|
1941
|
-
if (input[position] !== ":") fail("Expected ':' after object property name");
|
|
1942
|
-
punctuation();
|
|
1943
|
-
result2[key2] = value(depth + 1);
|
|
1944
|
-
ordered.push(key2);
|
|
1003
|
+
if (sampleObjects.length > 0) {
|
|
1004
|
+
const merged = {};
|
|
1005
|
+
for (const obj of sampleObjects) {
|
|
1006
|
+
for (const [k, v] of Object.entries(obj)) {
|
|
1007
|
+
if (!merged[k]) merged[k] = { types: /* @__PURE__ */ new Set(), count: 0 };
|
|
1008
|
+
merged[k].count += 1;
|
|
1009
|
+
merged[k].types.add(resolveType(v, k));
|
|
1945
1010
|
}
|
|
1946
|
-
white();
|
|
1947
|
-
if (input[position] === close) break;
|
|
1948
|
-
if (input[position] !== ",") fail(`Expected ',' or '${close}'`);
|
|
1949
|
-
punctuation();
|
|
1950
1011
|
}
|
|
1012
|
+
const lines = [];
|
|
1013
|
+
for (const [k, meta] of Object.entries(merged)) {
|
|
1014
|
+
const isOptional = meta.count < sampleObjects.length;
|
|
1015
|
+
const typeStr = Array.from(meta.types).join(" | ") || "unknown";
|
|
1016
|
+
const formattedKey = formatKey(k) + (isOptional ? "?" : "");
|
|
1017
|
+
lines.push(` ${formattedKey}: ${typeStr};`);
|
|
1018
|
+
}
|
|
1019
|
+
const interfaceName = getUniqueName(`${keyHint}Item`);
|
|
1020
|
+
interfaces.unshift({
|
|
1021
|
+
name: interfaceName,
|
|
1022
|
+
body: `export interface ${interfaceName} {
|
|
1023
|
+
${lines.join("\n")}
|
|
1024
|
+
}`
|
|
1025
|
+
});
|
|
1026
|
+
itemTypes.add(interfaceName);
|
|
1951
1027
|
}
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
1028
|
+
const union = Array.from(itemTypes).join(" | ");
|
|
1029
|
+
return union.includes(" | ") ? `(${union})[]` : `${union}[]`;
|
|
1030
|
+
}
|
|
1031
|
+
if (type === "object") {
|
|
1032
|
+
const obj = val;
|
|
1033
|
+
const lines = [];
|
|
1034
|
+
for (const [k, v] of Object.entries(obj)) {
|
|
1035
|
+
const typeStr = resolveType(v, k);
|
|
1036
|
+
lines.push(` ${formatKey(k)}: ${typeStr};`);
|
|
1037
|
+
}
|
|
1038
|
+
const interfaceName = getUniqueName(keyHint);
|
|
1039
|
+
interfaces.unshift({
|
|
1040
|
+
name: interfaceName,
|
|
1041
|
+
body: `export interface ${interfaceName} {
|
|
1042
|
+
${lines.join("\n")}
|
|
1043
|
+
}`
|
|
1044
|
+
});
|
|
1045
|
+
return interfaceName;
|
|
1046
|
+
}
|
|
1047
|
+
return "unknown";
|
|
1048
|
+
}
|
|
1049
|
+
const rootTypeName = toPascalCase(rootName) || "Root";
|
|
1050
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
1051
|
+
const rootType = resolveType(parsed, rootTypeName);
|
|
1052
|
+
const found = interfaces.find((i) => i.name === rootType);
|
|
1053
|
+
if (found) {
|
|
1054
|
+
found.name = rootTypeName;
|
|
1055
|
+
found.body = found.body.replace(`export interface ${rootType}`, `export interface ${rootTypeName}`);
|
|
1056
|
+
}
|
|
1057
|
+
return interfaces.map((i) => i.body).join("\n\n");
|
|
1058
|
+
} else if (Array.isArray(parsed)) {
|
|
1059
|
+
const itemType = resolveType(parsed, rootTypeName);
|
|
1060
|
+
return `${interfaces.map((i) => i.body).join("\n\n")}
|
|
1978
1061
|
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
|
|
1982
|
-
}
|
|
1983
|
-
function checkDelimiter(delimiter) {
|
|
1984
|
-
if (delimiter.length !== 1 || /["\r\n]/.test(delimiter)) {
|
|
1985
|
-
throw new Error("Choose a single delimiter other than a quote or line break.");
|
|
1062
|
+
export type ${rootTypeName} = ${itemType};`.trim();
|
|
1063
|
+
} else {
|
|
1064
|
+
const primitiveType = resolveType(parsed, rootTypeName);
|
|
1065
|
+
return `export type ${rootTypeName} = ${primitiveType};`;
|
|
1986
1066
|
}
|
|
1987
1067
|
}
|
|
1988
|
-
function
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
const
|
|
1997
|
-
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
if (
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
|
|
2015
|
-
|
|
2016
|
-
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
|
|
1068
|
+
function jsonToZod(jsonInput, rootName = "rootSchema") {
|
|
1069
|
+
let parsed;
|
|
1070
|
+
try {
|
|
1071
|
+
parsed = JSON.parse(jsonInput);
|
|
1072
|
+
} catch (err) {
|
|
1073
|
+
throw new Error(`Invalid JSON: ${err instanceof Error ? err.message : String(err)}`);
|
|
1074
|
+
}
|
|
1075
|
+
const schemas = [];
|
|
1076
|
+
const createdNames = /* @__PURE__ */ new Set();
|
|
1077
|
+
function getUniqueName(base) {
|
|
1078
|
+
let name = base.endsWith("Schema") ? base : `${base}Schema`;
|
|
1079
|
+
let counter = 1;
|
|
1080
|
+
while (createdNames.has(name)) {
|
|
1081
|
+
counter += 1;
|
|
1082
|
+
name = `${base}${counter}Schema`;
|
|
1083
|
+
}
|
|
1084
|
+
createdNames.add(name);
|
|
1085
|
+
return name;
|
|
1086
|
+
}
|
|
1087
|
+
function resolveZod(val, keyHint) {
|
|
1088
|
+
if (val === null) return "z.null()";
|
|
1089
|
+
if (val === void 0) return "z.undefined()";
|
|
1090
|
+
if (typeof val === "string") return "z.string()";
|
|
1091
|
+
if (typeof val === "number") return Number.isInteger(val) ? "z.number().int()" : "z.number()";
|
|
1092
|
+
if (typeof val === "boolean") return "z.boolean()";
|
|
1093
|
+
if (Array.isArray(val)) {
|
|
1094
|
+
if (val.length === 0) return "z.array(z.unknown())";
|
|
1095
|
+
const sampleObjects = [];
|
|
1096
|
+
const itemSchemas = /* @__PURE__ */ new Set();
|
|
1097
|
+
for (const item of val) {
|
|
1098
|
+
if (item && typeof item === "object" && !Array.isArray(item)) {
|
|
1099
|
+
sampleObjects.push(item);
|
|
1100
|
+
} else {
|
|
1101
|
+
itemSchemas.add(resolveZod(item, `${keyHint}Item`));
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
if (sampleObjects.length > 0) {
|
|
1105
|
+
const merged = {};
|
|
1106
|
+
for (const obj of sampleObjects) {
|
|
1107
|
+
for (const [k, v] of Object.entries(obj)) {
|
|
1108
|
+
if (!merged[k]) merged[k] = { schemas: /* @__PURE__ */ new Set(), count: 0 };
|
|
1109
|
+
merged[k].count += 1;
|
|
1110
|
+
merged[k].schemas.add(resolveZod(v, k));
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
const lines = [];
|
|
1114
|
+
for (const [k, meta] of Object.entries(merged)) {
|
|
1115
|
+
const isOptional = meta.count < sampleObjects.length;
|
|
1116
|
+
let schemaStr = Array.from(meta.schemas)[0] || "z.unknown()";
|
|
1117
|
+
if (meta.schemas.size > 1) {
|
|
1118
|
+
schemaStr = `z.union([${Array.from(meta.schemas).join(", ")}])`;
|
|
1119
|
+
}
|
|
1120
|
+
if (isOptional) {
|
|
1121
|
+
schemaStr += ".optional()";
|
|
1122
|
+
}
|
|
1123
|
+
lines.push(` ${formatKey(k)}: ${schemaStr},`);
|
|
1124
|
+
}
|
|
1125
|
+
const schemaName = getUniqueName(`${keyHint}Item`);
|
|
1126
|
+
schemas.unshift({
|
|
1127
|
+
name: schemaName,
|
|
1128
|
+
body: `export const ${schemaName} = z.object({
|
|
1129
|
+
${lines.join("\n")}
|
|
1130
|
+
});`
|
|
1131
|
+
});
|
|
1132
|
+
itemSchemas.add(schemaName);
|
|
1133
|
+
}
|
|
1134
|
+
const union = Array.from(itemSchemas);
|
|
1135
|
+
if (union.length === 1) return `z.array(${union[0]})`;
|
|
1136
|
+
return `z.array(z.union([${union.join(", ")}]))`;
|
|
1137
|
+
}
|
|
1138
|
+
if (typeof val === "object") {
|
|
1139
|
+
const obj = val;
|
|
1140
|
+
const lines = [];
|
|
1141
|
+
for (const [k, v] of Object.entries(obj)) {
|
|
1142
|
+
lines.push(` ${formatKey(k)}: ${resolveZod(v, k)},`);
|
|
1143
|
+
}
|
|
1144
|
+
const schemaName = getUniqueName(keyHint);
|
|
1145
|
+
schemas.unshift({
|
|
1146
|
+
name: schemaName,
|
|
1147
|
+
body: `export const ${schemaName} = z.object({
|
|
1148
|
+
${lines.join("\n")}
|
|
1149
|
+
});`
|
|
1150
|
+
});
|
|
1151
|
+
return schemaName;
|
|
2037
1152
|
}
|
|
1153
|
+
return "z.unknown()";
|
|
2038
1154
|
}
|
|
2039
|
-
|
|
2040
|
-
|
|
2041
|
-
|
|
2042
|
-
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
for (const record2 of records) {
|
|
2047
|
-
if (record2.values.length !== width) {
|
|
2048
|
-
throw csvError(`Expected ${width} columns but found ${record2.values.length}.`, record2.row, Math.min(width, record2.values.length) + 1);
|
|
2049
|
-
}
|
|
1155
|
+
const safeRootName = rootName.endsWith("Schema") ? rootName : `${rootName}Schema`;
|
|
1156
|
+
const typeName = toPascalCase(rootName.replace(/Schema$/i, "")) || "Root";
|
|
1157
|
+
const rootResult = resolveZod(parsed, safeRootName);
|
|
1158
|
+
const found = schemas.find((s) => s.name === rootResult);
|
|
1159
|
+
if (found) {
|
|
1160
|
+
found.name = safeRootName;
|
|
1161
|
+
found.body = found.body.replace(`export const ${rootResult}`, `export const ${safeRootName}`);
|
|
2050
1162
|
}
|
|
2051
|
-
|
|
2052
|
-
}
|
|
2053
|
-
function parseCsv(input, delimiter = ",") {
|
|
2054
|
-
return rectangular(readRecords(input, delimiter));
|
|
2055
|
-
}
|
|
1163
|
+
const header = `import { z } from "zod";
|
|
2056
1164
|
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
if (value.length > maximum) throw new Error(`${label} exceeds the ${maximum}-item limit.`);
|
|
2061
|
-
return value;
|
|
2062
|
-
}
|
|
2063
|
-
function record(value, label) {
|
|
2064
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${label} must be an object.`);
|
|
2065
|
-
return value;
|
|
2066
|
-
}
|
|
2067
|
-
function identifiers(value, dialect, label = "Columns", allowEmpty = false) {
|
|
2068
|
-
const names = list(value, label, 100).map((name2) => sqlText(name2, label));
|
|
2069
|
-
if (!allowEmpty && !names.length) throw new Error(`${label} must contain at least one column.`);
|
|
2070
|
-
names.forEach((name2) => quoteIdentifier(name2, dialect));
|
|
2071
|
-
if (new Set(names.map((name2) => dialect === "PostgreSQL" ? name2 : name2.toLocaleLowerCase("en-US"))).size !== names.length) throw new Error(`${label} cannot contain duplicate column names.`);
|
|
2072
|
-
return names;
|
|
2073
|
-
}
|
|
2074
|
-
function result(label, value, warnings) {
|
|
2075
|
-
if (value.length > 2e6) throw new Error("Generated SQL exceeds the 2,000,000-character output limit.");
|
|
2076
|
-
return { rows: [{ label, value }], ...warnings?.length ? { warnings } : {} };
|
|
2077
|
-
}
|
|
2078
|
-
function buildConditions(value, dialect, logicalOperator = "AND") {
|
|
2079
|
-
if (logicalOperator !== "AND" && logicalOperator !== "OR") throw new Error("Logical operator must be AND or OR.");
|
|
2080
|
-
let outputLength = 0;
|
|
2081
|
-
const checkedLiteral = (literal) => {
|
|
2082
|
-
const output2 = sqlLiteral(literal, dialect);
|
|
2083
|
-
outputLength += output2.length;
|
|
2084
|
-
if (outputLength > 2e6) throw new Error("Generated SQL exceeds the 2,000,000-character output limit.");
|
|
2085
|
-
return output2;
|
|
2086
|
-
};
|
|
2087
|
-
return list(value, "Conditions", 100).map((item, index) => {
|
|
2088
|
-
const condition = record(item, `Condition ${index + 1}`);
|
|
2089
|
-
const column = quoteIdentifier(sqlText(condition.column, "Condition column"), dialect);
|
|
2090
|
-
const operator = condition.operator;
|
|
2091
|
-
if (typeof operator !== "string" || !CONDITION_OPERATORS.includes(operator)) throw new Error("Choose a supported condition operator.");
|
|
2092
|
-
const values = list(condition.values, "Condition values", 100);
|
|
2093
|
-
if (operator === "IS NULL" || operator === "IS NOT NULL") {
|
|
2094
|
-
if (values.length) throw new Error(`${operator} must have no values.`);
|
|
2095
|
-
return `${column} ${operator}`;
|
|
2096
|
-
}
|
|
2097
|
-
const multiple = operator === "IN" || operator === "NOT IN";
|
|
2098
|
-
if (!values.length || !multiple && values.length !== 1) throw new Error(multiple ? `${operator} requires at least one value.` : `${operator} requires exactly one value.`);
|
|
2099
|
-
const literals = values.map((item2) => {
|
|
2100
|
-
const literal = record(item2, "Condition value");
|
|
2101
|
-
if (literal.type === "NULL") throw new Error("Use IS NULL or IS NOT NULL to compare NULL values.");
|
|
2102
|
-
if ((operator === "LIKE" || operator === "NOT LIKE") && literal.type !== "String") throw new Error("LIKE and NOT LIKE require a String value.");
|
|
2103
|
-
return checkedLiteral(literal);
|
|
2104
|
-
});
|
|
2105
|
-
return `${column} ${operator} ${multiple ? `(${literals.join(", ")})` : literals[0]}`;
|
|
2106
|
-
}).join(` ${logicalOperator} `);
|
|
2107
|
-
}
|
|
2108
|
-
function insert(table, columns2, rows, dialect) {
|
|
2109
|
-
if (!rows.length) throw new Error("No rows. Provide at least one data row.");
|
|
2110
|
-
if (rows.length > 1e3) throw new Error("Rows exceed the 1,000-row limit.");
|
|
2111
|
-
return `INSERT INTO ${table} (${columns2.map((column) => quoteIdentifier(column, dialect)).join(", ")})
|
|
2112
|
-
VALUES
|
|
2113
|
-
${rows.map((row) => {
|
|
2114
|
-
if (row.length !== columns2.length) throw new Error("Every row must have exactly one value per column.");
|
|
2115
|
-
return ` (${row.join(", ")})`;
|
|
2116
|
-
}).join(",\n")};`;
|
|
2117
|
-
}
|
|
2118
|
-
async function runBuilder(toolId, values) {
|
|
2119
|
-
const dialect = readDialect(values.dialect);
|
|
2120
|
-
let outputLength = 0;
|
|
2121
|
-
const checkedLiteral = (literal) => {
|
|
2122
|
-
const output2 = sqlLiteral(literal, dialect);
|
|
2123
|
-
outputLength += output2.length;
|
|
2124
|
-
if (outputLength > 2e6) throw new Error("Generated SQL exceeds the 2,000,000-character output limit.");
|
|
2125
|
-
return output2;
|
|
2126
|
-
};
|
|
2127
|
-
if (toolId === "sql-escape-helper") {
|
|
2128
|
-
return result("Escaped SQL literal", sqlLiteral({ type: values.valueType, value: sqlText(values.value, "Value") }, dialect));
|
|
2129
|
-
}
|
|
2130
|
-
if (toolId === "sql-where-builder") {
|
|
2131
|
-
const logicalOperator = values.logicalOperator;
|
|
2132
|
-
if (logicalOperator !== "AND" && logicalOperator !== "OR") throw new Error("Logical operator must be AND or OR.");
|
|
2133
|
-
const conditions2 = buildConditions(values.conditions, dialect, logicalOperator);
|
|
2134
|
-
if (!conditions2) throw new Error("Provide at least one condition.");
|
|
2135
|
-
return result("SQL WHERE clause", `WHERE ${conditions2}`);
|
|
2136
|
-
}
|
|
2137
|
-
const table = quoteIdentifier(sqlText(values.table, "Table"), dialect, true);
|
|
2138
|
-
if (toolId === "json-to-sql") {
|
|
2139
|
-
const parsed = parseJson(sqlText(values.json, "JSON"));
|
|
2140
|
-
const rows = list(parsed, "JSON rows", 1e3);
|
|
2141
|
-
if (!rows.length) throw new Error("No rows. Provide a nonempty JSON array of objects.");
|
|
2142
|
-
const objects = rows.map((row, index) => record(row, `JSON row ${index + 1}`));
|
|
2143
|
-
const columns2 = identifiers(jsonObjectKeys(objects[0]), dialect);
|
|
2144
|
-
const keys2 = new Set(columns2);
|
|
2145
|
-
const literals = objects.map((object, index) => {
|
|
2146
|
-
const rowKeys = jsonObjectKeys(object);
|
|
2147
|
-
if (rowKeys.length !== columns2.length || rowKeys.some((key2) => !keys2.has(key2))) throw new Error(`JSON row ${index + 1} must have exactly the same keys as the first row.`);
|
|
2148
|
-
return columns2.map((column) => jsonLiteral(object[column], dialect));
|
|
2149
|
-
});
|
|
2150
|
-
return result("SQL INSERT statements", insert(table, columns2, literals, dialect));
|
|
2151
|
-
}
|
|
2152
|
-
if (toolId === "csv-to-sql") {
|
|
2153
|
-
const csv = sqlText(values.csv, "CSV").replace(/^\uFEFF/, "");
|
|
2154
|
-
const records = parseCsv(csv);
|
|
2155
|
-
const columns2 = identifiers(records[0], dialect, "CSV headers");
|
|
2156
|
-
if (records.length > 1001) throw new Error("CSV data exceeds the 1,000-row limit.");
|
|
2157
|
-
return result("SQL INSERT statements", insert(table, columns2, records.slice(1).map((row) => row.map((value) => sqlLiteral({ type: "String", value }, dialect))), dialect));
|
|
2158
|
-
}
|
|
2159
|
-
if (toolId === "sql-insert-generator") {
|
|
2160
|
-
const columns2 = identifiers(values.columns, dialect);
|
|
2161
|
-
const rows = list(values.rows, "Rows", 1e3).map((row) => {
|
|
2162
|
-
const cells = list(row, "Row values", 100);
|
|
2163
|
-
if (cells.length !== columns2.length) throw new Error("Every row must have exactly one value per column.");
|
|
2164
|
-
return cells.map((cell) => checkedLiteral(record(cell, "Row value")));
|
|
2165
|
-
});
|
|
2166
|
-
return result("SQL INSERT statement", insert(table, columns2, rows, dialect));
|
|
2167
|
-
}
|
|
2168
|
-
const conditions = buildConditions(values.conditions, dialect);
|
|
2169
|
-
const where = conditions ? `
|
|
2170
|
-
WHERE ${conditions}` : "";
|
|
2171
|
-
if (toolId === "sql-update-generator") {
|
|
2172
|
-
const assignments = list(values.assignments, "Assignments", 100).map((item) => record(item, "Assignment"));
|
|
2173
|
-
const columns2 = identifiers(assignments.map((item) => item.column), dialect, "Assignment columns");
|
|
2174
|
-
const set = assignments.map((item, index) => `${quoteIdentifier(columns2[index], dialect)} = ${checkedLiteral(record(item.value, "Assignment value"))}`).join(",\n ");
|
|
2175
|
-
return result("SQL UPDATE statement", `UPDATE ${table}
|
|
2176
|
-
SET ${set}${where};`, conditions ? void 0 : ["This UPDATE has no WHERE clause and may affect every row."]);
|
|
2177
|
-
}
|
|
2178
|
-
if (toolId === "sql-delete-generator") {
|
|
2179
|
-
return result("SQL DELETE statement", `DELETE FROM ${table}${where};`, conditions ? void 0 : ["This DELETE has no WHERE clause and may delete every row."]);
|
|
2180
|
-
}
|
|
2181
|
-
if (toolId === "sql-select-builder") {
|
|
2182
|
-
const columns2 = identifiers(values.columns, dialect, "Columns", true);
|
|
2183
|
-
const orders = list(values.orderBy, "ORDER BY", 100).map((item) => record(item, "Order"));
|
|
2184
|
-
identifiers(orders.map((order) => order.column), dialect, "ORDER BY columns", true);
|
|
2185
|
-
const orderSql = orders.map((order) => {
|
|
2186
|
-
if (order.direction !== "ASC" && order.direction !== "DESC") throw new Error("ORDER BY direction must be ASC or DESC.");
|
|
2187
|
-
return `${quoteIdentifier(sqlText(order.column, "ORDER BY column"), dialect)} ${order.direction}`;
|
|
2188
|
-
});
|
|
2189
|
-
const limit = values.limit === void 0 ? "" : sqlText(values.limit, "Limit");
|
|
2190
|
-
if (limit && (!/^[1-9]\d{0,6}$/.test(limit) || Number(limit) > 1e6)) throw new Error("Limit must be a positive integer from 1 to 1,000,000.");
|
|
2191
|
-
const top = limit && dialect === "SQL Server" ? ` TOP (${limit})` : "";
|
|
2192
|
-
const tail = limit && dialect !== "SQL Server" ? `
|
|
2193
|
-
LIMIT ${limit}` : "";
|
|
2194
|
-
return result("SQL SELECT statement", `SELECT${top} ${columns2.length ? columns2.map((column) => quoteIdentifier(column, dialect)).join(", ") : "*"}
|
|
2195
|
-
FROM ${table}${where}${orderSql.length ? `
|
|
2196
|
-
ORDER BY ${orderSql.join(", ")}` : ""}${tail};`);
|
|
2197
|
-
}
|
|
2198
|
-
throw new Error("Unsupported SQL builder.");
|
|
2199
|
-
}
|
|
1165
|
+
`;
|
|
1166
|
+
const schemaDeclarations = schemas.map((s) => s.body).join("\n\n");
|
|
1167
|
+
const typeExport = `
|
|
2200
1168
|
|
|
2201
|
-
|
|
2202
|
-
|
|
2203
|
-
var defaults = { PostgreSQL: "5432", MySQL: "3306", "SQL Server": "1433" };
|
|
2204
|
-
var mask = "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022";
|
|
2205
|
-
var normalize = (key2) => key2.toLowerCase().replace(/[\s_-]/g, "");
|
|
2206
|
-
var coreNames = /* @__PURE__ */ new Set(["host", "hostname", "server", "datasource", "address", "addr", "networkaddress", "port", "database", "dbname", "initialcatalog", "username", "user", "userid", "uid", "password", "pwd", "pass"]);
|
|
2207
|
-
var privateName = (key2) => /password|pwd|passphrase|token|secret|credential|auth|(?:^|[\s_-])key|accesskey|privatekey|sslkey|clientkey|certificate|signature|sastoken/i.test(key2) || /^(pass|apikey|key)$/i.test(normalize(key2));
|
|
2208
|
-
function text2(value, label, required = false) {
|
|
2209
|
-
const result2 = sqlText(value, label);
|
|
2210
|
-
if (/[\x00-\x1f\x7f]/.test(result2)) throw new Error(`${label} cannot contain control characters.`);
|
|
2211
|
-
if (/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(result2)) throw new Error(`${label} must contain valid Unicode.`);
|
|
2212
|
-
if (required && !result2.trim()) throw new Error(`${label} is required.`);
|
|
2213
|
-
return result2;
|
|
2214
|
-
}
|
|
2215
|
-
function port(value, type) {
|
|
2216
|
-
if (!value) return defaults[type];
|
|
2217
|
-
if (!/^[1-9]\d{0,4}$/.test(value) || Number(value) > 65535) throw new Error("Port must be an integer from 1 to 65,535, or blank for the database default.");
|
|
2218
|
-
return value;
|
|
1169
|
+
export type ${typeName} = z.infer<typeof ${safeRootName}>;`;
|
|
1170
|
+
return header + (schemaDeclarations ? `${schemaDeclarations}${typeExport}` : `export const ${safeRootName} = ${rootResult};${typeExport}`);
|
|
2219
1171
|
}
|
|
2220
|
-
|
|
2221
|
-
|
|
2222
|
-
|
|
2223
|
-
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
|
|
2227
|
-
return url.hostname;
|
|
2228
|
-
} catch {
|
|
2229
|
-
throw new Error("Enter a valid IPv6 address; zone identifiers and host:port syntax are unsupported.");
|
|
2230
|
-
}
|
|
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";
|
|
2231
1179
|
}
|
|
2232
|
-
|
|
2233
|
-
|
|
2234
|
-
|
|
2235
|
-
|
|
2236
|
-
|
|
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] : "=");
|
|
2237
1219
|
}
|
|
1220
|
+
return out;
|
|
2238
1221
|
}
|
|
2239
|
-
function
|
|
1222
|
+
function checkUrl(url, globDisabled = false) {
|
|
1223
|
+
let parsed;
|
|
2240
1224
|
try {
|
|
2241
|
-
|
|
1225
|
+
parsed = new URL(url);
|
|
2242
1226
|
} catch {
|
|
2243
|
-
|
|
1227
|
+
fail("Request URL must be an absolute HTTP or HTTPS URL.");
|
|
2244
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.");
|
|
2245
1234
|
}
|
|
2246
|
-
function
|
|
2247
|
-
if (parameters2.length > 100) throw new Error("Parameters exceed the 100-entry limit.");
|
|
1235
|
+
function validateHeaders(headers) {
|
|
2248
1236
|
const seen = /* @__PURE__ */ new Set();
|
|
2249
|
-
|
|
2250
|
-
if (!/^[
|
|
2251
|
-
|
|
2252
|
-
if (
|
|
2253
|
-
seen.
|
|
2254
|
-
|
|
2255
|
-
|
|
2256
|
-
|
|
2257
|
-
}
|
|
2258
|
-
function
|
|
2259
|
-
if (
|
|
2260
|
-
if (value
|
|
2261
|
-
|
|
2262
|
-
|
|
2263
|
-
|
|
2264
|
-
|
|
2265
|
-
|
|
2266
|
-
|
|
2267
|
-
|
|
2268
|
-
|
|
2269
|
-
|
|
2270
|
-
|
|
2271
|
-
|
|
2272
|
-
|
|
2273
|
-
|
|
2274
|
-
|
|
2275
|
-
|
|
2276
|
-
|
|
2277
|
-
|
|
2278
|
-
|
|
2279
|
-
|
|
2280
|
-
|
|
2281
|
-
|
|
2282
|
-
const serverPort = port(text2(values.port, "Port"), type);
|
|
2283
|
-
const database = text2(values.database, "Database", true);
|
|
2284
|
-
const username = text2(values.username, "Username", true);
|
|
2285
|
-
const password = text2(values.password, "Password");
|
|
2286
|
-
const extra = parameters(values.parameters === void 0 ? "" : sqlText(values.parameters, "Parameters"));
|
|
2287
|
-
let connection;
|
|
2288
|
-
if (type === "SQL Server") {
|
|
2289
|
-
connection = `Data Source=${adoQuote(`${hostname},${serverPort}`)};Initial Catalog=${adoQuote(database)};User ID=${adoQuote(username)};Password=${adoQuote(password)};${extra.map((item) => `${item.key}=${adoQuote(item.value)};`).join("")}`;
|
|
2290
|
-
} else {
|
|
2291
|
-
const query = extra.length ? `?${extra.map((item) => `${encodeURIComponent(item.key)}=${encodeURIComponent(item.value)}`).join("&")}` : "";
|
|
2292
|
-
connection = `${type === "PostgreSQL" ? "postgresql" : "mysql"}://${encodeURIComponent(username)}:${encodeURIComponent(password)}@${hostname}:${serverPort}/${encodeURIComponent(database)}${query}`;
|
|
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.");
|
|
2293
1270
|
}
|
|
2294
|
-
if (connection.length > 2e6) throw new Error("Connection string exceeds the output limit.");
|
|
2295
|
-
return { rows: [{ label: "Connection string", value: connection }] };
|
|
2296
1271
|
}
|
|
2297
|
-
function
|
|
2298
|
-
|
|
2299
|
-
|
|
2300
|
-
|
|
2301
|
-
|
|
2302
|
-
|
|
2303
|
-
|
|
2304
|
-
|
|
2305
|
-
|
|
2306
|
-
|
|
2307
|
-
|
|
2308
|
-
}
|
|
2309
|
-
function output(type, hostname, serverPort, database, username, extra) {
|
|
2310
|
-
return { rows: [
|
|
2311
|
-
{ label: "Database type", value: type },
|
|
2312
|
-
{ label: "Host", value: hostname },
|
|
2313
|
-
{ label: "Port", value: serverPort },
|
|
2314
|
-
{ label: "Database name", value: database },
|
|
2315
|
-
{ label: "Username", value: username },
|
|
2316
|
-
{ label: "Masked password", value: mask },
|
|
2317
|
-
{ label: "Parameters", value: extra.length ? extra.map(redacted).map((item) => `${item.key}=${item.value}`).join("\n") : "None" }
|
|
2318
|
-
] };
|
|
2319
|
-
}
|
|
2320
|
-
function parseUri(input) {
|
|
2321
|
-
const scheme = /^(postgresql|postgres|mysql):\/\//i.exec(input);
|
|
2322
|
-
if (!scheme) throw new Error("Use a PostgreSQL/MySQL URI or a SQL Server ADO.NET connection string.");
|
|
2323
|
-
const type = scheme[1].toLowerCase() === "mysql" ? "MySQL" : "PostgreSQL";
|
|
2324
|
-
const authority = input.slice(scheme[0].length).split(/[/?#]/, 1)[0];
|
|
2325
|
-
if ((authority.match(/@/g) ?? []).length > 1) throw new Error("Encode @ inside URI credentials; multiple userinfo separators are ambiguous.");
|
|
2326
|
-
if (input.includes("#")) throw new Error("Connection URI fragments are unsupported; encode # inside field values.");
|
|
2327
|
-
let url;
|
|
2328
|
-
try {
|
|
2329
|
-
url = new URL(input);
|
|
2330
|
-
} catch {
|
|
2331
|
-
throw new Error("Invalid database connection URI.");
|
|
2332
|
-
}
|
|
2333
|
-
const username = text2(decode(url.username), "Username");
|
|
2334
|
-
text2(decode(url.password), "Password");
|
|
2335
|
-
const database = text2(decode(url.pathname.replace(/^\//, "")), "Database", true);
|
|
2336
|
-
if (url.pathname.slice(1).includes("/")) throw new Error("Database paths must be one encoded path segment.");
|
|
2337
|
-
const hostname = host(url.hostname);
|
|
2338
|
-
const serverPort = port(url.port, type);
|
|
2339
|
-
const extra = queryParameters(url.search.replace(/^\?/, ""));
|
|
2340
|
-
return output(type, hostname, serverPort, database, username, extra);
|
|
2341
|
-
}
|
|
2342
|
-
function adoParameters(input) {
|
|
2343
|
-
const pairs = [];
|
|
2344
|
-
let position = 0;
|
|
2345
|
-
while (position < input.length) {
|
|
2346
|
-
while (/[\s;]/.test(input[position] ?? "") && position < input.length) position++;
|
|
2347
|
-
if (position === input.length) break;
|
|
2348
|
-
const start = position;
|
|
2349
|
-
while (position < input.length && input[position] !== "=" && input[position] !== ";") position++;
|
|
2350
|
-
if (input[position] !== "=") throw new Error("ADO.NET connection entries must use key=value syntax.");
|
|
2351
|
-
const key2 = input.slice(start, position++).trim();
|
|
2352
|
-
while (input[position] === " ") position++;
|
|
2353
|
-
let value = "";
|
|
2354
|
-
const quote = input[position];
|
|
2355
|
-
if (quote === '"' || quote === "'") {
|
|
2356
|
-
position++;
|
|
2357
|
-
let closed = false;
|
|
2358
|
-
while (position < input.length) {
|
|
2359
|
-
const character = input[position++];
|
|
2360
|
-
if (character !== quote) {
|
|
2361
|
-
value += character;
|
|
2362
|
-
continue;
|
|
2363
|
-
}
|
|
2364
|
-
if (input[position] === quote) {
|
|
2365
|
-
value += quote;
|
|
2366
|
-
position++;
|
|
2367
|
-
} else {
|
|
2368
|
-
closed = true;
|
|
2369
|
-
break;
|
|
2370
|
-
}
|
|
2371
|
-
}
|
|
2372
|
-
if (!closed) throw new Error("ADO.NET connection string has an unclosed quoted value.");
|
|
2373
|
-
while (input[position] === " ") position++;
|
|
2374
|
-
if (position < input.length && input[position] !== ";") throw new Error("Unexpected text after a quoted ADO.NET value.");
|
|
2375
|
-
} else {
|
|
2376
|
-
const startValue = position;
|
|
2377
|
-
while (position < input.length && input[position] !== ";") position++;
|
|
2378
|
-
value = input.slice(startValue, position).trim();
|
|
2379
|
-
if (/["']/.test(value)) throw new Error("Quote the entire ADO.NET value when it contains quotes.");
|
|
2380
|
-
}
|
|
2381
|
-
pairs.push({ key: key2, value });
|
|
2382
|
-
if (input[position] === ";") position++;
|
|
2383
|
-
if (pairs.length > 100) throw new Error("Connection entries exceed the 100-entry limit.");
|
|
2384
|
-
}
|
|
2385
|
-
return validateParameters(pairs, false);
|
|
2386
|
-
}
|
|
2387
|
-
function parseAdo(input) {
|
|
2388
|
-
const pairs = adoParameters(input);
|
|
2389
|
-
const aliases = {
|
|
2390
|
-
server: "host",
|
|
2391
|
-
datasource: "host",
|
|
2392
|
-
address: "host",
|
|
2393
|
-
addr: "host",
|
|
2394
|
-
networkaddress: "host",
|
|
2395
|
-
host: "host",
|
|
2396
|
-
initialcatalog: "database",
|
|
2397
|
-
database: "database",
|
|
2398
|
-
dbname: "database",
|
|
2399
|
-
userid: "username",
|
|
2400
|
-
uid: "username",
|
|
2401
|
-
user: "username",
|
|
2402
|
-
username: "username",
|
|
2403
|
-
password: "password",
|
|
2404
|
-
pwd: "password",
|
|
2405
|
-
pass: "password",
|
|
2406
|
-
port: "port"
|
|
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
|
+
}
|
|
2407
1283
|
};
|
|
2408
|
-
|
|
2409
|
-
|
|
2410
|
-
|
|
2411
|
-
|
|
2412
|
-
|
|
2413
|
-
|
|
2414
|
-
extra.push(pair);
|
|
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;
|
|
2415
1290
|
continue;
|
|
2416
1291
|
}
|
|
2417
|
-
if (
|
|
2418
|
-
|
|
2419
|
-
|
|
2420
|
-
|
|
2421
|
-
|
|
2422
|
-
|
|
2423
|
-
|
|
2424
|
-
|
|
2425
|
-
|
|
2426
|
-
|
|
2427
|
-
|
|
2428
|
-
|
|
2429
|
-
|
|
2430
|
-
|
|
2431
|
-
|
|
2432
|
-
|
|
2433
|
-
|
|
2434
|
-
|
|
2435
|
-
|
|
2436
|
-
|
|
2437
|
-
|
|
2438
|
-
|
|
2439
|
-
|
|
2440
|
-
|
|
2441
|
-
|
|
2442
|
-
|
|
2443
|
-
|
|
2444
|
-
|
|
2445
|
-
|
|
2446
|
-
|
|
2447
|
-
const { ddlOutput: ddlOutput2 } = await Promise.resolve().then(() => (init_ddl(), ddl_exports));
|
|
2448
|
-
result2 = await ddlOutput2(sql, dialect);
|
|
2449
|
-
} else {
|
|
2450
|
-
const { formatSqlTool: formatSqlTool2, minifySqlTool: minifySqlTool2, validateSqlTool: validateSqlTool2, insertOutput: insertOutput2 } = await Promise.resolve().then(() => (init_transforms(), transforms_exports));
|
|
2451
|
-
result2 = toolId === "sql-formatter" ? await formatSqlTool2(sql, dialect) : toolId === "sql-minifier" ? await minifySqlTool2(sql, dialect) : toolId === "sql-validator" ? await validateSqlTool2(sql, dialect) : await insertOutput2(toolId, sql, dialect);
|
|
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;
|
|
2452
1322
|
}
|
|
2453
|
-
|
|
2454
|
-
|
|
2455
|
-
|
|
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;
|
|
2456
1337
|
}
|
|
2457
|
-
|
|
2458
|
-
|
|
2459
|
-
|
|
2460
|
-
|
|
2461
|
-
|
|
2462
|
-
|
|
2463
|
-
|
|
2464
|
-
|
|
2465
|
-
|
|
2466
|
-
|
|
2467
|
-
|
|
2468
|
-
|
|
2469
|
-
|
|
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;
|
|
2470
1388
|
}
|
|
2471
|
-
|
|
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
|
+
|
|
2481
|
+
// mcp/server.ts
|
|
2482
|
+
function createMcpServer(cliKey) {
|
|
2483
|
+
const license = resolveLicense(cliKey);
|
|
2484
|
+
const server = new Server(
|
|
2485
|
+
{
|
|
2486
|
+
name: "codestation-mcp",
|
|
2487
|
+
version: "1.2.0"
|
|
2488
|
+
},
|
|
2489
|
+
{
|
|
2490
|
+
capabilities: {
|
|
2491
|
+
tools: {}
|
|
2492
|
+
}
|
|
2493
|
+
}
|
|
2494
|
+
);
|
|
2472
2495
|
const tools = [
|
|
2473
2496
|
// ----------------- FREE TOOLS -----------------
|
|
2474
2497
|
{
|
|
@@ -2763,19 +2786,125 @@ function createMcpServer(cliKey) {
|
|
|
2763
2786
|
},
|
|
2764
2787
|
required: ["json"]
|
|
2765
2788
|
}
|
|
2789
|
+
},
|
|
2790
|
+
{
|
|
2791
|
+
name: "codestation_json_to_typescript",
|
|
2792
|
+
description: "Generate clean TypeScript interfaces and types from sample JSON data. [Pro Tier: \u20B9199/mo or $2.99/mo]",
|
|
2793
|
+
inputSchema: {
|
|
2794
|
+
type: "object",
|
|
2795
|
+
properties: {
|
|
2796
|
+
json: { type: "string", description: "Sample JSON string or object representation" },
|
|
2797
|
+
rootName: { type: "string", description: "Name for the root interface (default: 'Root')" }
|
|
2798
|
+
},
|
|
2799
|
+
required: ["json"]
|
|
2800
|
+
}
|
|
2801
|
+
},
|
|
2802
|
+
{
|
|
2803
|
+
name: "codestation_json_to_zod",
|
|
2804
|
+
description: "Generate production-ready Zod validation schema and inferred types from sample JSON data. [Pro Tier: \u20B9199/mo or $2.99/mo]",
|
|
2805
|
+
inputSchema: {
|
|
2806
|
+
type: "object",
|
|
2807
|
+
properties: {
|
|
2808
|
+
json: { type: "string", description: "Sample JSON string or object representation" },
|
|
2809
|
+
rootName: { type: "string", description: "Name for the root schema (default: 'rootSchema')" }
|
|
2810
|
+
},
|
|
2811
|
+
required: ["json"]
|
|
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
|
+
}
|
|
2766
2895
|
}
|
|
2767
2896
|
];
|
|
2768
2897
|
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
2769
2898
|
return { tools };
|
|
2770
2899
|
});
|
|
2771
2900
|
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
2772
|
-
const { name
|
|
2773
|
-
if (PRO_TOOLS.has(
|
|
2901
|
+
const { name, arguments: args = {} } = request.params;
|
|
2902
|
+
if (PRO_TOOLS.has(name) && !license.isPro) {
|
|
2774
2903
|
return {
|
|
2775
2904
|
content: [
|
|
2776
2905
|
{
|
|
2777
2906
|
type: "text",
|
|
2778
|
-
text: getProUpgradeNotice(
|
|
2907
|
+
text: getProUpgradeNotice(name)
|
|
2779
2908
|
}
|
|
2780
2909
|
],
|
|
2781
2910
|
isError: true
|
|
@@ -2783,7 +2912,7 @@ function createMcpServer(cliKey) {
|
|
|
2783
2912
|
}
|
|
2784
2913
|
try {
|
|
2785
2914
|
let outputText = "";
|
|
2786
|
-
switch (
|
|
2915
|
+
switch (name) {
|
|
2787
2916
|
// --- Free tools ---
|
|
2788
2917
|
case "codestation_uuid": {
|
|
2789
2918
|
const count = Math.min(Math.max(Number(args.count ?? 1), 1), 50);
|
|
@@ -2792,34 +2921,34 @@ function createMcpServer(cliKey) {
|
|
|
2792
2921
|
break;
|
|
2793
2922
|
}
|
|
2794
2923
|
case "codestation_base64": {
|
|
2795
|
-
const
|
|
2924
|
+
const text2 = String(args.text ?? "");
|
|
2796
2925
|
const action = String(args.action ?? "encode");
|
|
2797
2926
|
const urlSafe = Boolean(args.urlSafe);
|
|
2798
2927
|
if (action === "encode") {
|
|
2799
2928
|
if (urlSafe) {
|
|
2800
|
-
outputText = encodeBase64Url(
|
|
2929
|
+
outputText = encodeBase64Url(text2);
|
|
2801
2930
|
} else {
|
|
2802
|
-
outputText = Buffer.from(
|
|
2931
|
+
outputText = Buffer.from(text2, "utf-8").toString("base64");
|
|
2803
2932
|
}
|
|
2804
2933
|
} else {
|
|
2805
2934
|
if (urlSafe) {
|
|
2806
|
-
outputText = decodeBase64Url(
|
|
2935
|
+
outputText = decodeBase64Url(text2);
|
|
2807
2936
|
} else {
|
|
2808
|
-
outputText = Buffer.from(
|
|
2937
|
+
outputText = Buffer.from(text2, "base64").toString("utf-8");
|
|
2809
2938
|
}
|
|
2810
2939
|
}
|
|
2811
2940
|
break;
|
|
2812
2941
|
}
|
|
2813
2942
|
case "codestation_url_codec": {
|
|
2814
|
-
const
|
|
2943
|
+
const text2 = String(args.text ?? "");
|
|
2815
2944
|
const action = String(args.action ?? "encode");
|
|
2816
|
-
outputText = action === "encode" ? encodeUrlComponent(
|
|
2945
|
+
outputText = action === "encode" ? encodeUrlComponent(text2) : decodeUrlComponent(text2);
|
|
2817
2946
|
break;
|
|
2818
2947
|
}
|
|
2819
2948
|
case "codestation_hex_codec": {
|
|
2820
|
-
const
|
|
2949
|
+
const text2 = String(args.text ?? "");
|
|
2821
2950
|
const action = String(args.action ?? "encode");
|
|
2822
|
-
outputText = action === "encode" ? encodeHexadecimal(
|
|
2951
|
+
outputText = action === "encode" ? encodeHexadecimal(text2) : decodeHexadecimal(text2);
|
|
2823
2952
|
break;
|
|
2824
2953
|
}
|
|
2825
2954
|
case "codestation_format_json": {
|
|
@@ -2841,9 +2970,9 @@ function createMcpServer(cliKey) {
|
|
|
2841
2970
|
break;
|
|
2842
2971
|
}
|
|
2843
2972
|
case "codestation_case_convert": {
|
|
2844
|
-
const
|
|
2973
|
+
const text2 = String(args.text ?? "");
|
|
2845
2974
|
const targetCase = String(args.targetCase ?? "camel");
|
|
2846
|
-
outputText = convertCase(
|
|
2975
|
+
outputText = convertCase(text2, targetCase);
|
|
2847
2976
|
break;
|
|
2848
2977
|
}
|
|
2849
2978
|
case "codestation_text_diff": {
|
|
@@ -2856,25 +2985,25 @@ function createMcpServer(cliKey) {
|
|
|
2856
2985
|
}
|
|
2857
2986
|
// --- Pro tools ---
|
|
2858
2987
|
case "codestation_hash": {
|
|
2859
|
-
const
|
|
2988
|
+
const text2 = String(args.text ?? "");
|
|
2860
2989
|
const algo = String(args.algorithm ?? "SHA-256").toUpperCase();
|
|
2861
|
-
if (algo === "MD5") outputText = md5(
|
|
2862
|
-
else if (algo === "SHA-1") outputText = sha1(
|
|
2863
|
-
else if (algo === "SHA-256") outputText = await sha256(
|
|
2864
|
-
else if (algo === "SHA-384") outputText = await sha384(
|
|
2865
|
-
else if (algo === "SHA-512") outputText = await sha512(
|
|
2866
|
-
else if (algo === "CRC32") outputText = crc32(
|
|
2990
|
+
if (algo === "MD5") outputText = md5(text2);
|
|
2991
|
+
else if (algo === "SHA-1") outputText = sha1(text2);
|
|
2992
|
+
else if (algo === "SHA-256") outputText = await sha256(text2);
|
|
2993
|
+
else if (algo === "SHA-384") outputText = await sha384(text2);
|
|
2994
|
+
else if (algo === "SHA-512") outputText = await sha512(text2);
|
|
2995
|
+
else if (algo === "CRC32") outputText = crc32(text2);
|
|
2867
2996
|
else throw new Error(`Unsupported hash algorithm: ${algo}`);
|
|
2868
2997
|
break;
|
|
2869
2998
|
}
|
|
2870
2999
|
case "codestation_hmac": {
|
|
2871
|
-
const
|
|
3000
|
+
const text2 = String(args.text ?? "");
|
|
2872
3001
|
const secret = String(args.secret ?? "");
|
|
2873
3002
|
const algo = String(args.algorithm ?? "SHA-256").toUpperCase();
|
|
2874
3003
|
if (algo === "SHA-512") {
|
|
2875
|
-
outputText = await hmacSha512(
|
|
3004
|
+
outputText = await hmacSha512(text2, secret);
|
|
2876
3005
|
} else {
|
|
2877
|
-
outputText = await hmacSha256(
|
|
3006
|
+
outputText = await hmacSha256(text2, secret);
|
|
2878
3007
|
}
|
|
2879
3008
|
break;
|
|
2880
3009
|
}
|
|
@@ -2884,9 +3013,19 @@ function createMcpServer(cliKey) {
|
|
|
2884
3013
|
}
|
|
2885
3014
|
case "codestation_format_sql": {
|
|
2886
3015
|
const sql = String(args.sql ?? "");
|
|
2887
|
-
const dialect = String(args.dialect ?? "PostgreSQL");
|
|
2888
|
-
const
|
|
2889
|
-
|
|
3016
|
+
const dialect = String(args.dialect ?? "PostgreSQL").toLowerCase();
|
|
3017
|
+
const { format } = await import("sql-formatter");
|
|
3018
|
+
const dialectMap = {
|
|
3019
|
+
postgresql: "postgresql",
|
|
3020
|
+
postgres: "postgresql",
|
|
3021
|
+
mysql: "mysql",
|
|
3022
|
+
sqlite: "sqlite",
|
|
3023
|
+
sqlserver: "transactsql",
|
|
3024
|
+
tsql: "transactsql",
|
|
3025
|
+
"sql server": "transactsql"
|
|
3026
|
+
};
|
|
3027
|
+
const lang = dialectMap[dialect] || "sql";
|
|
3028
|
+
outputText = format(sql, { language: lang, tabWidth: 2 });
|
|
2890
3029
|
break;
|
|
2891
3030
|
}
|
|
2892
3031
|
case "codestation_cron_explain": {
|
|
@@ -2910,17 +3049,65 @@ function createMcpServer(cliKey) {
|
|
|
2910
3049
|
}
|
|
2911
3050
|
case "codestation_regex_test": {
|
|
2912
3051
|
const pattern = String(args.pattern ?? "");
|
|
2913
|
-
const
|
|
3052
|
+
const text2 = String(args.text ?? "");
|
|
2914
3053
|
const flags = String(args.flags ?? "g");
|
|
2915
|
-
outputText = testRegex(pattern, flags,
|
|
3054
|
+
outputText = testRegex(pattern, flags, text2);
|
|
2916
3055
|
break;
|
|
2917
3056
|
}
|
|
2918
3057
|
case "codestation_json_schema": {
|
|
2919
3058
|
outputText = generateJsonSchema(String(args.json ?? ""));
|
|
2920
3059
|
break;
|
|
2921
3060
|
}
|
|
3061
|
+
case "codestation_json_to_typescript": {
|
|
3062
|
+
const json = String(args.json ?? "");
|
|
3063
|
+
const rootName = args.rootName ? String(args.rootName) : "Root";
|
|
3064
|
+
outputText = jsonToTypescript(json, rootName);
|
|
3065
|
+
break;
|
|
3066
|
+
}
|
|
3067
|
+
case "codestation_json_to_zod": {
|
|
3068
|
+
const json = String(args.json ?? "");
|
|
3069
|
+
const rootName = args.rootName ? String(args.rootName) : "rootSchema";
|
|
3070
|
+
outputText = jsonToZod(json, rootName);
|
|
3071
|
+
break;
|
|
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
|
+
}
|
|
2922
3109
|
default:
|
|
2923
|
-
throw new Error(`Unknown tool: ${
|
|
3110
|
+
throw new Error(`Unknown tool: ${name}`);
|
|
2924
3111
|
}
|
|
2925
3112
|
return {
|
|
2926
3113
|
content: [{ type: "text", text: outputText }]
|
|
@@ -2936,35 +3123,576 @@ function createMcpServer(cliKey) {
|
|
|
2936
3123
|
return { server, license };
|
|
2937
3124
|
}
|
|
2938
3125
|
|
|
3126
|
+
// mcp/setup.ts
|
|
3127
|
+
import * as fs2 from "node:fs";
|
|
3128
|
+
import * as path2 from "node:path";
|
|
3129
|
+
import * as os2 from "node:os";
|
|
3130
|
+
function getClaudeDesktopConfigPath() {
|
|
3131
|
+
const platform = process.platform;
|
|
3132
|
+
if (platform === "darwin") {
|
|
3133
|
+
return path2.join(os2.homedir(), "Library", "Application Support", "Claude", "claude_desktop_config.json");
|
|
3134
|
+
} else if (platform === "win32") {
|
|
3135
|
+
const appData = process.env.APPDATA || path2.join(os2.homedir(), "AppData", "Roaming");
|
|
3136
|
+
return path2.join(appData, "Claude", "claude_desktop_config.json");
|
|
3137
|
+
} else {
|
|
3138
|
+
return path2.join(os2.homedir(), ".config", "Claude", "claude_desktop_config.json");
|
|
3139
|
+
}
|
|
3140
|
+
}
|
|
3141
|
+
function getCursorGlobalConfigPath() {
|
|
3142
|
+
return path2.join(os2.homedir(), ".cursor", "mcp.json");
|
|
3143
|
+
}
|
|
3144
|
+
function getWindsurfConfigPath() {
|
|
3145
|
+
return path2.join(os2.homedir(), ".codeium", "windsurf", "mcp_config.json");
|
|
3146
|
+
}
|
|
3147
|
+
function mergeMcpConfig(filePath, mcpEntry) {
|
|
3148
|
+
try {
|
|
3149
|
+
const dir = path2.dirname(filePath);
|
|
3150
|
+
if (!fs2.existsSync(dir)) {
|
|
3151
|
+
fs2.mkdirSync(dir, { recursive: true });
|
|
3152
|
+
}
|
|
3153
|
+
let config = {};
|
|
3154
|
+
if (fs2.existsSync(filePath)) {
|
|
3155
|
+
try {
|
|
3156
|
+
const raw = fs2.readFileSync(filePath, "utf-8");
|
|
3157
|
+
config = JSON.parse(raw);
|
|
3158
|
+
} catch {
|
|
3159
|
+
config = {};
|
|
3160
|
+
}
|
|
3161
|
+
}
|
|
3162
|
+
if (!config.mcpServers || typeof config.mcpServers !== "object") {
|
|
3163
|
+
config.mcpServers = {};
|
|
3164
|
+
}
|
|
3165
|
+
config.mcpServers.codestation = mcpEntry;
|
|
3166
|
+
fs2.writeFileSync(filePath, JSON.stringify(config, null, 2) + "\n", "utf-8");
|
|
3167
|
+
return { target: path2.basename(filePath), path: filePath, status: "configured" };
|
|
3168
|
+
} catch (err) {
|
|
3169
|
+
return {
|
|
3170
|
+
target: path2.basename(filePath),
|
|
3171
|
+
path: filePath,
|
|
3172
|
+
status: "error",
|
|
3173
|
+
message: err instanceof Error ? err.message : String(err)
|
|
3174
|
+
};
|
|
3175
|
+
}
|
|
3176
|
+
}
|
|
3177
|
+
async function runAutoSetup(licenseKey) {
|
|
3178
|
+
const cleanKey = licenseKey?.trim();
|
|
3179
|
+
if (cleanKey && validateLicenseKey(cleanKey)) {
|
|
3180
|
+
saveCachedLicense(cleanKey, true);
|
|
3181
|
+
}
|
|
3182
|
+
const mcpEntry = {
|
|
3183
|
+
command: "npx",
|
|
3184
|
+
args: cleanKey ? ["-y", "codestation-mcp", "--key", cleanKey] : ["-y", "codestation-mcp"]
|
|
3185
|
+
};
|
|
3186
|
+
const targets = [
|
|
3187
|
+
{ name: "Claude Desktop", path: getClaudeDesktopConfigPath() },
|
|
3188
|
+
{ name: "Cursor IDE (Global)", path: getCursorGlobalConfigPath() },
|
|
3189
|
+
{ name: "Windsurf / Codeium", path: getWindsurfConfigPath() }
|
|
3190
|
+
];
|
|
3191
|
+
const localCursorPath = path2.join(process.cwd(), ".cursor", "mcp.json");
|
|
3192
|
+
if (fs2.existsSync(path2.join(process.cwd(), ".cursor"))) {
|
|
3193
|
+
targets.push({ name: "Cursor IDE (Local Project)", path: localCursorPath });
|
|
3194
|
+
}
|
|
3195
|
+
const results = [];
|
|
3196
|
+
for (const t of targets) {
|
|
3197
|
+
const res = mergeMcpConfig(t.path, mcpEntry);
|
|
3198
|
+
res.target = t.name;
|
|
3199
|
+
results.push(res);
|
|
3200
|
+
}
|
|
3201
|
+
return results;
|
|
3202
|
+
}
|
|
3203
|
+
|
|
3204
|
+
// mcp/cli-tools.ts
|
|
3205
|
+
import * as fs3 from "node:fs";
|
|
3206
|
+
|
|
3207
|
+
// lib/tools/cron/next-run.ts
|
|
3208
|
+
var DAY2 = 864e5;
|
|
3209
|
+
var SIX_HOURS = 6 * 36e5;
|
|
3210
|
+
var pad3 = (value, width = 2) => String(value).padStart(width, "0");
|
|
3211
|
+
function parseCronReference(reference) {
|
|
3212
|
+
if (reference.length > 64) throw new Error("Reference exceeds the 64-character limit.");
|
|
3213
|
+
const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?(Z|[+-]\d{2}:\d{2})$/.exec(reference);
|
|
3214
|
+
if (!match) throw new Error("Reference must be an absolute ISO date/time: YYYY-MM-DDTHH:mm[:ss[.sss]] followed by Z or \xB1HH:mm.");
|
|
3215
|
+
const [year, month, day, hour, minute, second] = [match[1], match[2], match[3], match[4], match[5], match[6] ?? "0"].map(Number);
|
|
3216
|
+
if (year < 1970 || year > 2099) throw new Error("Reference years must be between 1970 and 2099.");
|
|
3217
|
+
const days = new Date(Date.UTC(year, month, 0)).getUTCDate();
|
|
3218
|
+
if (month < 1 || month > 12 || day < 1 || day > days || hour > 23 || minute > 59 || second > 59) throw new Error("Reference contains an impossible calendar date or time.");
|
|
3219
|
+
const milliseconds = Number((match[7] ?? "").padEnd(3, "0"));
|
|
3220
|
+
let offset = 0;
|
|
3221
|
+
if (match[8] !== "Z") {
|
|
3222
|
+
const offsetHour = Number(match[8].slice(1, 3));
|
|
3223
|
+
const offsetMinute = Number(match[8].slice(4, 6));
|
|
3224
|
+
if (offsetMinute > 59 || offsetHour > 14 || offsetHour === 14 && offsetMinute !== 0) throw new Error("Reference offset must be within \xB114:00, with valid minutes.");
|
|
3225
|
+
offset = (offsetHour * 60 + offsetMinute) * 6e4 * (match[8][0] === "-" ? -1 : 1);
|
|
3226
|
+
}
|
|
3227
|
+
const instant = Date.UTC(year, month - 1, day, hour, minute, second, milliseconds) - offset;
|
|
3228
|
+
const utcYear = new Date(instant).getUTCFullYear();
|
|
3229
|
+
if (utcYear < 1970 || utcYear > 2099) throw new Error("Reference instant must fall within UTC years 1970\u20132099.");
|
|
3230
|
+
return instant;
|
|
3231
|
+
}
|
|
3232
|
+
function zoneFormatter2(timezone) {
|
|
3233
|
+
if (!timezone || timezone !== timezone.trim()) throw new Error("Select a nonempty IANA timezone.");
|
|
3234
|
+
if (timezone.length > 128 || !/^[A-Za-z][A-Za-z0-9_+\-/]*$/.test(timezone)) throw new Error("Enter a valid IANA timezone name; numeric offsets are not timezone names.");
|
|
3235
|
+
try {
|
|
3236
|
+
return new Intl.DateTimeFormat("en-GB-u-ca-gregory-nu-latn", {
|
|
3237
|
+
timeZone: timezone,
|
|
3238
|
+
year: "numeric",
|
|
3239
|
+
month: "2-digit",
|
|
3240
|
+
day: "2-digit",
|
|
3241
|
+
hour: "2-digit",
|
|
3242
|
+
minute: "2-digit",
|
|
3243
|
+
second: "2-digit",
|
|
3244
|
+
hourCycle: "h23"
|
|
3245
|
+
});
|
|
3246
|
+
} catch {
|
|
3247
|
+
throw new Error("Timezone is not a recognized IANA timezone in this runtime.");
|
|
3248
|
+
}
|
|
3249
|
+
}
|
|
3250
|
+
function wallTime(formatter, instant) {
|
|
3251
|
+
const parts = formatter.formatToParts(instant);
|
|
3252
|
+
const get = (name) => Number(parts.find((part) => part.type === name)?.value);
|
|
3253
|
+
return { year: get("year"), month: get("month"), day: get("day"), hour: get("hour"), minute: get("minute"), second: get("second") };
|
|
3254
|
+
}
|
|
3255
|
+
function offsetAt(formatter, instant) {
|
|
3256
|
+
const wholeSecond = Math.floor(instant / 1e3) * 1e3;
|
|
3257
|
+
const wall = wallTime(formatter, wholeSecond);
|
|
3258
|
+
return Date.UTC(wall.year, wall.month - 1, wall.day, wall.hour, wall.minute, wall.second) - wholeSecond;
|
|
3259
|
+
}
|
|
3260
|
+
function offsetIntervals(formatter, midnight) {
|
|
3261
|
+
const start = midnight - 2 * DAY2;
|
|
3262
|
+
const end = midnight + 3 * DAY2;
|
|
3263
|
+
const intervals = [];
|
|
3264
|
+
let intervalStart = start;
|
|
3265
|
+
let priorOffset = offsetAt(formatter, start);
|
|
3266
|
+
for (let probe = start + SIX_HOURS; probe <= end; probe += SIX_HOURS) {
|
|
3267
|
+
const nextOffset = offsetAt(formatter, probe);
|
|
3268
|
+
if (nextOffset !== priorOffset) {
|
|
3269
|
+
let low = probe - SIX_HOURS;
|
|
3270
|
+
let high = probe;
|
|
3271
|
+
while (high - low > 1e3) {
|
|
3272
|
+
const middle = Math.floor((low + high) / 2e3) * 1e3;
|
|
3273
|
+
if (offsetAt(formatter, middle) === priorOffset) low = middle;
|
|
3274
|
+
else high = middle;
|
|
3275
|
+
}
|
|
3276
|
+
intervals.push({ start: intervalStart, end: high, offset: priorOffset });
|
|
3277
|
+
intervalStart = high;
|
|
3278
|
+
priorOffset = nextOffset;
|
|
3279
|
+
}
|
|
3280
|
+
}
|
|
3281
|
+
intervals.push({ start: intervalStart, end, offset: priorOffset });
|
|
3282
|
+
return intervals;
|
|
3283
|
+
}
|
|
3284
|
+
function selectedSecond(cron, lower, upper) {
|
|
3285
|
+
if (lower >= upper || lower >= 86400) return void 0;
|
|
3286
|
+
lower = Math.max(0, Math.ceil(lower));
|
|
3287
|
+
const firstHour = Math.floor(lower / 3600);
|
|
3288
|
+
for (const hour of cron.hour.values) {
|
|
3289
|
+
if (hour < firstHour) continue;
|
|
3290
|
+
const firstMinute = hour === firstHour ? Math.floor(lower % 3600 / 60) : 0;
|
|
3291
|
+
for (const minute of cron.minute.values) {
|
|
3292
|
+
if (minute < firstMinute) continue;
|
|
3293
|
+
const base = hour * 3600 + minute * 60;
|
|
3294
|
+
if (base >= upper) return void 0;
|
|
3295
|
+
const second = cron.second.values.find((value) => base + value >= lower);
|
|
3296
|
+
if (second !== void 0) return base + second < upper ? base + second : void 0;
|
|
3297
|
+
}
|
|
3298
|
+
}
|
|
3299
|
+
return void 0;
|
|
3300
|
+
}
|
|
3301
|
+
function formatCronDuration(milliseconds) {
|
|
3302
|
+
if (!Number.isSafeInteger(milliseconds)) throw new Error("Duration is outside supported integer precision.");
|
|
3303
|
+
const sign = milliseconds < 0 ? "-" : "+";
|
|
3304
|
+
let remainder = Math.abs(milliseconds);
|
|
3305
|
+
const pieces = [];
|
|
3306
|
+
for (const [size, name] of [[DAY2, "day"], [36e5, "hour"], [6e4, "minute"], [1e3, "second"], [1, "millisecond"]]) {
|
|
3307
|
+
const count = Math.floor(remainder / size);
|
|
3308
|
+
remainder %= size;
|
|
3309
|
+
if (count) pieces.push(`${count} ${name}${count === 1 ? "" : "s"}`);
|
|
3310
|
+
}
|
|
3311
|
+
return sign + (pieces.join(", ") || "0 seconds");
|
|
3312
|
+
}
|
|
3313
|
+
function nextCronRun(expression, reference, timezone) {
|
|
3314
|
+
const cron = typeof expression === "string" ? parseCron(expression) : expression;
|
|
3315
|
+
const instant = parseCronReference(reference);
|
|
3316
|
+
const formatter = zoneFormatter2(timezone);
|
|
3317
|
+
const referenceWall = wallTime(formatter, instant);
|
|
3318
|
+
if (referenceWall.year < 1970 || referenceWall.year > 2099) throw new Error("Reference in the selected timezone must fall within years 1970\u20132099.");
|
|
3319
|
+
const referenceDay = Date.UTC(referenceWall.year, referenceWall.month - 1, referenceWall.day);
|
|
3320
|
+
const firstDay = Math.max(Date.UTC(1970, 0, 1), referenceDay - 2 * DAY2);
|
|
3321
|
+
const searchEnd = Math.min(Date.UTC(2100, 0, 1), Date.UTC(referenceWall.year + 8, referenceWall.month - 1, referenceWall.day + 1));
|
|
3322
|
+
const utcReference = new Date(instant);
|
|
3323
|
+
const eightYearLimit = Date.UTC(utcReference.getUTCFullYear() + 8, utcReference.getUTCMonth(), utcReference.getUTCDate(), utcReference.getUTCHours(), utcReference.getUTCMinutes(), utcReference.getUTCSeconds(), utcReference.getUTCMilliseconds());
|
|
3324
|
+
const absoluteEnd = Math.min(Date.UTC(2100, 0, 1), eightYearLimit + 1);
|
|
3325
|
+
let best;
|
|
3326
|
+
let bestOffset = 0;
|
|
3327
|
+
for (let midnight = firstDay; midnight < searchEnd; midnight += DAY2) {
|
|
3328
|
+
if (best !== void 0 && midnight - DAY2 > best) break;
|
|
3329
|
+
const date = new Date(midnight);
|
|
3330
|
+
const year = date.getUTCFullYear();
|
|
3331
|
+
const month = date.getUTCMonth() + 1;
|
|
3332
|
+
const day = date.getUTCDate();
|
|
3333
|
+
if (!matchesCronDate(cron, year, month, day)) continue;
|
|
3334
|
+
for (const interval of offsetIntervals(formatter, midnight)) {
|
|
3335
|
+
const lowerUtc = Math.max(interval.start, instant + 1, midnight - interval.offset, Date.UTC(1970, 0, 1));
|
|
3336
|
+
const upperUtc = Math.min(interval.end, midnight + DAY2 - interval.offset, absoluteEnd, best ?? Infinity);
|
|
3337
|
+
const second = selectedSecond(cron, (lowerUtc + interval.offset - midnight) / 1e3, (upperUtc + interval.offset - midnight) / 1e3);
|
|
3338
|
+
if (second === void 0) continue;
|
|
3339
|
+
const candidate = midnight + second * 1e3 - interval.offset;
|
|
3340
|
+
const actual = wallTime(formatter, candidate);
|
|
3341
|
+
if (actual.year !== year || actual.month !== month || actual.day !== day || actual.hour !== Math.floor(second / 3600) || actual.minute !== Math.floor(second % 3600 / 60) || actual.second !== second % 60) continue;
|
|
3342
|
+
if (candidate > instant && (best === void 0 || candidate < best)) {
|
|
3343
|
+
best = candidate;
|
|
3344
|
+
bestOffset = interval.offset;
|
|
3345
|
+
}
|
|
3346
|
+
}
|
|
3347
|
+
}
|
|
3348
|
+
if (best === void 0) throw new Error("No occurrence found within eight calendar years after the reference, ending no later than 2099. The expression may select impossible calendar dates.");
|
|
3349
|
+
if (bestOffset % 6e4 !== 0) throw new Error("This historical timezone offset includes seconds and cannot be represented by an RFC 3339 \xB1HH:mm offset; choose a reference after the zone adopted minute-based offsets.");
|
|
3350
|
+
const wall = wallTime(formatter, best);
|
|
3351
|
+
const offsetMinutes = Math.abs(bestOffset / 6e4);
|
|
3352
|
+
const offset = `${bestOffset < 0 ? "-" : "+"}${pad3(Math.floor(offsetMinutes / 60))}:${pad3(offsetMinutes % 60)}`;
|
|
3353
|
+
const dateTime = `${pad3(wall.year, 4)}-${pad3(wall.month)}-${pad3(wall.day)}T${pad3(wall.hour)}:${pad3(wall.minute)}:${pad3(wall.second)}${offset}[${timezone}]`;
|
|
3354
|
+
const durationMilliseconds = best - instant;
|
|
3355
|
+
return { instant: best, dateTime, timezone, durationMilliseconds, duration: formatCronDuration(durationMilliseconds) };
|
|
3356
|
+
}
|
|
3357
|
+
|
|
3358
|
+
// mcp/cli-tools.ts
|
|
3359
|
+
async function readInput(arg) {
|
|
3360
|
+
if (arg && arg !== "-") {
|
|
3361
|
+
if (fs3.existsSync(arg)) {
|
|
3362
|
+
return fs3.readFileSync(arg, "utf-8");
|
|
3363
|
+
}
|
|
3364
|
+
return arg;
|
|
3365
|
+
}
|
|
3366
|
+
if (!process.stdin.isTTY) {
|
|
3367
|
+
return new Promise((resolve, reject) => {
|
|
3368
|
+
let data = "";
|
|
3369
|
+
process.stdin.setEncoding("utf-8");
|
|
3370
|
+
process.stdin.on("data", (chunk) => {
|
|
3371
|
+
data += chunk;
|
|
3372
|
+
});
|
|
3373
|
+
process.stdin.on("end", () => resolve(data.trim()));
|
|
3374
|
+
process.stdin.on("error", reject);
|
|
3375
|
+
});
|
|
3376
|
+
}
|
|
3377
|
+
return "";
|
|
3378
|
+
}
|
|
3379
|
+
async function handleCliSubcommand(command, args) {
|
|
3380
|
+
switch (command.toLowerCase()) {
|
|
3381
|
+
case "jwt": {
|
|
3382
|
+
const input = await readInput(args[0]);
|
|
3383
|
+
if (!input) {
|
|
3384
|
+
process.stderr.write("Usage: npx codestation-mcp jwt <jwt_token>\n");
|
|
3385
|
+
return true;
|
|
3386
|
+
}
|
|
3387
|
+
try {
|
|
3388
|
+
const decoded = JSON.parse(decodeJwt(input));
|
|
3389
|
+
process.stdout.write("\n=== JWT HEADER ===\n");
|
|
3390
|
+
process.stdout.write(JSON.stringify(decoded.header, null, 2) + "\n");
|
|
3391
|
+
process.stdout.write("\n=== JWT PAYLOAD ===\n");
|
|
3392
|
+
process.stdout.write(JSON.stringify(decoded.payload, null, 2) + "\n");
|
|
3393
|
+
if (decoded.payload.exp) {
|
|
3394
|
+
const expDate = new Date(decoded.payload.exp * 1e3);
|
|
3395
|
+
const isExpired = Date.now() > expDate.getTime();
|
|
3396
|
+
process.stdout.write(
|
|
3397
|
+
`
|
|
3398
|
+
Expiry: ${expDate.toISOString()} (${isExpired ? "EXPIRED" : "Valid until " + expDate.toLocaleString()})
|
|
3399
|
+
|
|
3400
|
+
`
|
|
3401
|
+
);
|
|
3402
|
+
}
|
|
3403
|
+
} catch (err) {
|
|
3404
|
+
process.stderr.write(`[Error] ${err instanceof Error ? err.message : String(err)}
|
|
3405
|
+
`);
|
|
3406
|
+
}
|
|
3407
|
+
return true;
|
|
3408
|
+
}
|
|
3409
|
+
case "sql": {
|
|
3410
|
+
const input = await readInput(args[0]);
|
|
3411
|
+
if (!input) {
|
|
3412
|
+
process.stderr.write('Usage: npx codestation-mcp sql "<query>" [--dialect postgresql|mysql|sqlite|sqlserver]\n');
|
|
3413
|
+
return true;
|
|
3414
|
+
}
|
|
3415
|
+
let dialect = "postgresql";
|
|
3416
|
+
const dialectIdx = args.indexOf("--dialect");
|
|
3417
|
+
if (dialectIdx !== -1 && args[dialectIdx + 1]) {
|
|
3418
|
+
dialect = args[dialectIdx + 1].toLowerCase();
|
|
3419
|
+
}
|
|
3420
|
+
const dialectMap = {
|
|
3421
|
+
postgresql: "postgresql",
|
|
3422
|
+
postgres: "postgresql",
|
|
3423
|
+
mysql: "mysql",
|
|
3424
|
+
sqlite: "sqlite",
|
|
3425
|
+
sqlserver: "transactsql",
|
|
3426
|
+
tsql: "transactsql",
|
|
3427
|
+
"sql server": "transactsql"
|
|
3428
|
+
};
|
|
3429
|
+
const lang = dialectMap[dialect] || "sql";
|
|
3430
|
+
try {
|
|
3431
|
+
const { format } = await import("sql-formatter");
|
|
3432
|
+
const formatted = format(input, { language: lang, tabWidth: 2 });
|
|
3433
|
+
process.stdout.write(formatted + "\n");
|
|
3434
|
+
} catch (err) {
|
|
3435
|
+
process.stderr.write(`[Error] ${err instanceof Error ? err.message : String(err)}
|
|
3436
|
+
`);
|
|
3437
|
+
}
|
|
3438
|
+
return true;
|
|
3439
|
+
}
|
|
3440
|
+
case "cron": {
|
|
3441
|
+
const input = args.join(" ").replace(/--key\s+[^\s]+/g, "").trim();
|
|
3442
|
+
if (!input) {
|
|
3443
|
+
process.stderr.write('Usage: npx codestation-mcp cron "<cron_expression>"\nExample: npx codestation-mcp cron "0 9 * * 1-5"\n');
|
|
3444
|
+
return true;
|
|
3445
|
+
}
|
|
3446
|
+
try {
|
|
3447
|
+
const parsed = parseCron(input);
|
|
3448
|
+
const explanation = explainCron(parsed);
|
|
3449
|
+
const next = nextCronRun(parsed, (/* @__PURE__ */ new Date()).toISOString(), "UTC");
|
|
3450
|
+
process.stdout.write(`
|
|
3451
|
+
Expression: ${input}
|
|
3452
|
+
`);
|
|
3453
|
+
process.stdout.write(`Description: ${explanation}
|
|
3454
|
+
`);
|
|
3455
|
+
process.stdout.write(`Next run: ${next.dateTime} (${next.duration})
|
|
3456
|
+
|
|
3457
|
+
`);
|
|
3458
|
+
} catch (err) {
|
|
3459
|
+
process.stderr.write(`[Error] ${err instanceof Error ? err.message : String(err)}
|
|
3460
|
+
`);
|
|
3461
|
+
}
|
|
3462
|
+
return true;
|
|
3463
|
+
}
|
|
3464
|
+
case "hash": {
|
|
3465
|
+
const input = await readInput(args[0]);
|
|
3466
|
+
if (!input) {
|
|
3467
|
+
process.stderr.write('Usage: npx codestation-mcp hash "<string>" [--alg sha256|sha512|md5|sha1|crc32]\n');
|
|
3468
|
+
return true;
|
|
3469
|
+
}
|
|
3470
|
+
let alg = "sha256";
|
|
3471
|
+
const algIdx = args.indexOf("--alg");
|
|
3472
|
+
if (algIdx !== -1 && args[algIdx + 1]) {
|
|
3473
|
+
alg = args[algIdx + 1].toLowerCase();
|
|
3474
|
+
}
|
|
3475
|
+
let result = "";
|
|
3476
|
+
if (alg === "sha256") result = await sha256(input);
|
|
3477
|
+
else if (alg === "sha512") result = await sha512(input);
|
|
3478
|
+
else if (alg === "md5") result = md5(input);
|
|
3479
|
+
else if (alg === "sha1") result = sha1(input);
|
|
3480
|
+
else if (alg === "crc32") result = crc32(input);
|
|
3481
|
+
else result = await sha256(input);
|
|
3482
|
+
process.stdout.write(`${alg.toUpperCase()}: ${result}
|
|
3483
|
+
`);
|
|
3484
|
+
return true;
|
|
3485
|
+
}
|
|
3486
|
+
case "ts":
|
|
3487
|
+
case "types": {
|
|
3488
|
+
const input = await readInput(args[0]);
|
|
3489
|
+
if (!input) {
|
|
3490
|
+
process.stderr.write('Usage: npx codestation-mcp ts "<json_string_or_file>" [RootName]\n');
|
|
3491
|
+
return true;
|
|
3492
|
+
}
|
|
3493
|
+
const rootName = args[1] || "Root";
|
|
3494
|
+
try {
|
|
3495
|
+
const tsOutput = jsonToTypescript(input, rootName);
|
|
3496
|
+
process.stdout.write(tsOutput + "\n");
|
|
3497
|
+
} catch (err) {
|
|
3498
|
+
process.stderr.write(`[Error] ${err instanceof Error ? err.message : String(err)}
|
|
3499
|
+
`);
|
|
3500
|
+
}
|
|
3501
|
+
return true;
|
|
3502
|
+
}
|
|
3503
|
+
case "zod": {
|
|
3504
|
+
const input = await readInput(args[0]);
|
|
3505
|
+
if (!input) {
|
|
3506
|
+
process.stderr.write('Usage: npx codestation-mcp zod "<json_string_or_file>" [rootSchema]\n');
|
|
3507
|
+
return true;
|
|
3508
|
+
}
|
|
3509
|
+
const rootName = args[1] || "rootSchema";
|
|
3510
|
+
try {
|
|
3511
|
+
const zodOutput = jsonToZod(input, rootName);
|
|
3512
|
+
process.stdout.write(zodOutput + "\n");
|
|
3513
|
+
} catch (err) {
|
|
3514
|
+
process.stderr.write(`[Error] ${err instanceof Error ? err.message : String(err)}
|
|
3515
|
+
`);
|
|
3516
|
+
}
|
|
3517
|
+
return true;
|
|
3518
|
+
}
|
|
3519
|
+
case "uuid": {
|
|
3520
|
+
const count = parseInt(args[0], 10) || 1;
|
|
3521
|
+
for (let i = 0; i < count; i++) {
|
|
3522
|
+
process.stdout.write(crypto.randomUUID() + "\n");
|
|
3523
|
+
}
|
|
3524
|
+
return true;
|
|
3525
|
+
}
|
|
3526
|
+
case "json": {
|
|
3527
|
+
const input = await readInput(args[0]);
|
|
3528
|
+
if (!input) {
|
|
3529
|
+
process.stderr.write('Usage: npx codestation-mcp json "<raw_json>"\n');
|
|
3530
|
+
return true;
|
|
3531
|
+
}
|
|
3532
|
+
try {
|
|
3533
|
+
const formatted = formatJson(input, 2);
|
|
3534
|
+
process.stdout.write(formatted + "\n");
|
|
3535
|
+
} catch (err) {
|
|
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)}
|
|
3644
|
+
`);
|
|
3645
|
+
}
|
|
3646
|
+
return true;
|
|
3647
|
+
}
|
|
3648
|
+
default:
|
|
3649
|
+
return false;
|
|
3650
|
+
}
|
|
3651
|
+
}
|
|
3652
|
+
|
|
2939
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
|
+
`;
|
|
2940
3660
|
function printHelp() {
|
|
2941
3661
|
process.stderr.write(`
|
|
2942
|
-
Code Station MCP Server
|
|
2943
|
-
Local-first developer toolbox for AI assistants (Cursor, Claude Desktop,
|
|
3662
|
+
Code Station MCP Server & Developer CLI
|
|
3663
|
+
Local-first developer toolbox for AI assistants (Cursor, Claude Desktop, Windsurf) and terminal workflows.
|
|
2944
3664
|
|
|
2945
3665
|
Usage:
|
|
2946
|
-
npx codestation-mcp [options]
|
|
3666
|
+
npx codestation-mcp [command|options]
|
|
2947
3667
|
|
|
2948
|
-
|
|
2949
|
-
--key <license_key>
|
|
2950
|
-
|
|
2951
|
-
--version, -v Show version information
|
|
3668
|
+
1-Click AI Assistant Setup:
|
|
3669
|
+
npx codestation-mcp setup [--key <license_key>]
|
|
3670
|
+
Automatically configures Claude Desktop, Cursor IDE, and Windsurf.
|
|
2952
3671
|
|
|
2953
|
-
|
|
2954
|
-
|
|
2955
|
-
|
|
2956
|
-
|
|
2957
|
-
|
|
3672
|
+
Terminal Subcommands:
|
|
3673
|
+
jwt <token> Decode & inspect JWT header, payload, and expiry
|
|
3674
|
+
sql "<query>" [--dialect] Format SQL query (postgresql, mysql, sqlite, sqlserver)
|
|
3675
|
+
cron "<expression>" Explain cron schedule & project next 5 runtimes
|
|
3676
|
+
hash "<text>" [--alg] Compute digest (sha256, sha512, md5, sha1, crc32)
|
|
3677
|
+
ts "<json_string|file>" Generate clean TypeScript interfaces from JSON
|
|
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)
|
|
3683
|
+
uuid [count] Generate random RFC 4122 v4 UUIDs
|
|
3684
|
+
json "<raw_json>" Validate & pretty-print JSON
|
|
2958
3685
|
|
|
2959
|
-
|
|
2960
|
-
|
|
2961
|
-
|
|
2962
|
-
|
|
2963
|
-
|
|
2964
|
-
|
|
2965
|
-
|
|
2966
|
-
|
|
2967
|
-
}
|
|
3686
|
+
Stdio Server Options (for AI Assistants):
|
|
3687
|
+
--key <license_key> Activate Code Station Pro features
|
|
3688
|
+
--help, -h Show this help message
|
|
3689
|
+
--version, -v Show version information
|
|
3690
|
+
|
|
3691
|
+
Pricing:
|
|
3692
|
+
\u2022 Free Tier: Unlimited Base64, JSON, YAML, UUID, Text Diff, Case conversion
|
|
3693
|
+
\u2022 Pro Tier (India): ${PRICING.inr} (or ${PRICING.lifetimeInr})
|
|
3694
|
+
\u2022 Pro Tier (Global): ${PRICING.usd} (or ${PRICING.lifetimeUsd})
|
|
3695
|
+
\u2022 Upgrade / Account: ${PRICING.upgradeUrl}
|
|
2968
3696
|
|
|
2969
3697
|
`);
|
|
2970
3698
|
}
|
|
@@ -2975,9 +3703,41 @@ async function main() {
|
|
|
2975
3703
|
process.exit(0);
|
|
2976
3704
|
}
|
|
2977
3705
|
if (args.includes("--version") || args.includes("-v")) {
|
|
2978
|
-
process.stderr.write("codestation-mcp v1.
|
|
3706
|
+
process.stderr.write("codestation-mcp v1.2.0\n");
|
|
2979
3707
|
process.exit(0);
|
|
2980
3708
|
}
|
|
3709
|
+
if (args[0] === "setup") {
|
|
3710
|
+
let key;
|
|
3711
|
+
const keyIdx = args.indexOf("--key");
|
|
3712
|
+
if (keyIdx !== -1 && args[keyIdx + 1]) {
|
|
3713
|
+
key = args[keyIdx + 1];
|
|
3714
|
+
}
|
|
3715
|
+
process.stdout.write("\n=== Code Station 1-Click AI Setup ===\n");
|
|
3716
|
+
if (key) {
|
|
3717
|
+
process.stdout.write(`Activating with Pro Key: ${key.slice(0, 8)}...
|
|
3718
|
+
`);
|
|
3719
|
+
} else {
|
|
3720
|
+
process.stdout.write("Configuring in Free Tier mode (run with --key anytime to activate Pro).\n");
|
|
3721
|
+
}
|
|
3722
|
+
const results = await runAutoSetup(key);
|
|
3723
|
+
for (const r of results) {
|
|
3724
|
+
if (r.status === "configured") {
|
|
3725
|
+
process.stdout.write(` \u2714 ${r.target.padEnd(26)} Configured (${r.path})
|
|
3726
|
+
`);
|
|
3727
|
+
} else {
|
|
3728
|
+
process.stdout.write(` \u2716 ${r.target.padEnd(26)} Error: ${r.message}
|
|
3729
|
+
`);
|
|
3730
|
+
}
|
|
3731
|
+
}
|
|
3732
|
+
process.stdout.write("\n\u2728 Setup complete! Restart your editor(s) to start using Code Station tools.\n\n");
|
|
3733
|
+
process.exit(0);
|
|
3734
|
+
}
|
|
3735
|
+
if (args.length > 0 && !args[0].startsWith("-")) {
|
|
3736
|
+
const handled = await handleCliSubcommand(args[0], args.slice(1));
|
|
3737
|
+
if (handled) {
|
|
3738
|
+
process.exit(0);
|
|
3739
|
+
}
|
|
3740
|
+
}
|
|
2981
3741
|
let cliKey;
|
|
2982
3742
|
const keyIndex = args.indexOf("--key");
|
|
2983
3743
|
if (keyIndex !== -1 && args[keyIndex + 1]) {
|
|
@@ -2985,6 +3745,7 @@ async function main() {
|
|
|
2985
3745
|
}
|
|
2986
3746
|
const { server, license } = createMcpServer(cliKey);
|
|
2987
3747
|
if (license.isPro) {
|
|
3748
|
+
process.stderr.write(PRO_ASCII_BADGE);
|
|
2988
3749
|
process.stderr.write(`[Code Station MCP] Pro Tier Active (License: ${license.licenseKey?.slice(0, 8)}...). All tools unlocked.
|
|
2989
3750
|
`);
|
|
2990
3751
|
} else {
|