codestation-mcp 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2217 @@
1
+ #!/usr/bin/env node
2
+
3
+ // mcp/cli.ts
4
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5
+
6
+ // mcp/server.ts
7
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
8
+ import {
9
+ CallToolRequestSchema,
10
+ ListToolsRequestSchema
11
+ } from "@modelcontextprotocol/sdk/types.js";
12
+
13
+ // mcp/config.ts
14
+ import * as fs from "node:fs";
15
+ import * as path from "node:path";
16
+ import * as os from "node:os";
17
+ var PRICING = {
18
+ inr: "\u20B9199 / month",
19
+ usd: "$2.99 / month",
20
+ lifetimeInr: "\u20B9999 one-time",
21
+ lifetimeUsd: "$19.00 one-time",
22
+ upgradeUrl: "https://codestation.in/pro"
23
+ };
24
+ var PRO_TOOLS = /* @__PURE__ */ new Set([
25
+ "codestation_hash",
26
+ "codestation_hmac",
27
+ "codestation_jwt_decode",
28
+ "codestation_format_sql",
29
+ "codestation_cron_explain",
30
+ "codestation_timezone_convert",
31
+ "codestation_business_days",
32
+ "codestation_regex_test",
33
+ "codestation_json_schema",
34
+ "codestation_json_to_typescript",
35
+ "codestation_json_to_zod"
36
+ ]);
37
+ var CACHE_DIR = path.join(os.homedir(), ".codestation");
38
+ var CACHE_FILE = path.join(CACHE_DIR, "license.json");
39
+ function readCachedLicense() {
40
+ try {
41
+ if (fs.existsSync(CACHE_FILE)) {
42
+ const data = JSON.parse(fs.readFileSync(CACHE_FILE, "utf-8"));
43
+ if (Date.now() - data.verifiedAt < 30 * 24 * 60 * 60 * 1e3) {
44
+ return data;
45
+ }
46
+ }
47
+ } catch {
48
+ }
49
+ return null;
50
+ }
51
+ function saveCachedLicense(key, isPro) {
52
+ try {
53
+ if (process.env.NODE_ENV === "test") return;
54
+ if (!fs.existsSync(CACHE_DIR)) {
55
+ fs.mkdirSync(CACHE_DIR, { recursive: true });
56
+ }
57
+ const cache = {
58
+ key,
59
+ verifiedAt: Date.now(),
60
+ isPro
61
+ };
62
+ fs.writeFileSync(CACHE_FILE, JSON.stringify(cache, null, 2), "utf-8");
63
+ } catch {
64
+ }
65
+ }
66
+ function validateLicenseKey(rawKey) {
67
+ if (!rawKey) return false;
68
+ const key = rawKey.trim();
69
+ if (!key) return false;
70
+ if (/^CS-PRO-[A-Za-z0-9_-]+$/i.test(key) || key.startsWith("cspro_")) {
71
+ return true;
72
+ }
73
+ if (key === "PRO_DEMO_KEY" || key === "CS-PRO-DEV") {
74
+ return true;
75
+ }
76
+ return false;
77
+ }
78
+ function resolveLicense(cliKey) {
79
+ if (cliKey) {
80
+ const valid = validateLicenseKey(cliKey);
81
+ if (valid) {
82
+ saveCachedLicense(cliKey, true);
83
+ return { isPro: true, licenseKey: cliKey, source: "cli", tier: "pro" };
84
+ }
85
+ }
86
+ const envKey = process.env.CODESTATION_LICENSE_KEY;
87
+ if (envKey) {
88
+ const valid = validateLicenseKey(envKey);
89
+ if (valid) {
90
+ saveCachedLicense(envKey, true);
91
+ return { isPro: true, licenseKey: envKey, source: "env", tier: "pro" };
92
+ }
93
+ }
94
+ const cached = readCachedLicense();
95
+ if (cached && cached.isPro) {
96
+ return { isPro: true, licenseKey: cached.key, source: "cache", tier: "pro" };
97
+ }
98
+ return { isPro: false, source: "none", tier: "free" };
99
+ }
100
+ function getProUpgradeNotice(toolName) {
101
+ return [
102
+ `\u{1F512} Tool "${toolName}" is a Code Station Pro feature.`,
103
+ ``,
104
+ `Get Code Station Pro:`,
105
+ ` \u2022 India: ${PRICING.inr} (or ${PRICING.lifetimeInr})`,
106
+ ` \u2022 Global: ${PRICING.usd} (or ${PRICING.lifetimeUsd})`,
107
+ ` \u2022 Upgrade URL: ${PRICING.upgradeUrl}`,
108
+ ``,
109
+ `To activate, launch with:`,
110
+ ` npx codestation-mcp --key CS-PRO-YOURKEY`,
111
+ `or set environment variable:`,
112
+ ` export CODESTATION_LICENSE_KEY=CS-PRO-YOURKEY`
113
+ ].join("\n");
114
+ }
115
+
116
+ // lib/tools/index.ts
117
+ import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
118
+
119
+ // lib/tools/encoding-station.ts
120
+ function utf8(value) {
121
+ return new TextEncoder().encode(value);
122
+ }
123
+ function text(bytes2) {
124
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes2);
125
+ }
126
+ function encodeBase64Url(value) {
127
+ const bytes2 = utf8(value);
128
+ let binary = "";
129
+ for (const byte of bytes2) binary += String.fromCharCode(byte);
130
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
131
+ }
132
+ function decodeBase64Url(value) {
133
+ if (!/^[A-Za-z0-9_-]*$/.test(value)) throw new Error("Invalid Base64URL input.");
134
+ const padded = value.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - value.length % 4) % 4);
135
+ try {
136
+ const binary = atob(padded);
137
+ return text(Uint8Array.from(binary, (character) => character.charCodeAt(0)));
138
+ } catch {
139
+ throw new Error("Base64URL input is not valid Base64 or UTF-8 text.");
140
+ }
141
+ }
142
+ var encodeUrlComponent = encodeURIComponent;
143
+ function decodeUrlComponent(value) {
144
+ try {
145
+ return decodeURIComponent(value);
146
+ } catch {
147
+ throw new Error("URL component contains invalid percent escapes.");
148
+ }
149
+ }
150
+ function encodeHexadecimal(value) {
151
+ return Array.from(utf8(value), (byte) => byte.toString(16).padStart(2, "0")).join(" ");
152
+ }
153
+ function decodeHexadecimal(value) {
154
+ const clean = value.replace(/[\s:-]/g, "");
155
+ if (!/^(?:[\da-f]{2})+$/i.test(clean)) throw new Error("Use hexadecimal byte pairs such as 48 65 6c 6c 6f.");
156
+ try {
157
+ return text(Uint8Array.from(clean.match(/../g), (byte) => parseInt(byte, 16)));
158
+ } catch {
159
+ throw new Error("Hexadecimal input is not valid UTF-8 text.");
160
+ }
161
+ }
162
+
163
+ // lib/tools/index.ts
164
+ function formatJson(value, indent = 2) {
165
+ if (!Number.isInteger(indent) || indent < 0 || indent > 10) {
166
+ throw new RangeError("indent must be an integer between 0 and 10");
167
+ }
168
+ return JSON.stringify(JSON.parse(value), null, indent);
169
+ }
170
+ function minifyJson(value) {
171
+ return JSON.stringify(JSON.parse(value));
172
+ }
173
+ function jsonToYaml(value) {
174
+ return stringifyYaml(JSON.parse(value));
175
+ }
176
+ function yamlToJson(value) {
177
+ return JSON.stringify(parseYaml(value), null, 2);
178
+ }
179
+ function generateJsonSchema(value) {
180
+ const sample = JSON.parse(value);
181
+ const infer = (node) => {
182
+ if (node === null) return { type: "null" };
183
+ if (Array.isArray(node)) return { type: "array", items: node.length ? infer(node[0]) : {} };
184
+ if (typeof node === "object") {
185
+ const properties = Object.fromEntries(Object.entries(node).map(([key, child]) => [key, infer(child)]));
186
+ return { type: "object", properties, required: Object.keys(properties), additionalProperties: false };
187
+ }
188
+ return { type: typeof node === "number" && Number.isInteger(node) ? "integer" : typeof node };
189
+ };
190
+ return JSON.stringify({ $schema: "https://json-schema.org/draft/2020-12/schema", ...infer(sample) }, null, 2);
191
+ }
192
+ function decodeBase64Url2(value) {
193
+ return decodeBase64(value.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - value.length % 4) % 4));
194
+ }
195
+ function decodeJwt(value) {
196
+ const parts = value.trim().split(".");
197
+ if (parts.length !== 3) throw new Error("A JWT must contain three dot-separated sections.");
198
+ try {
199
+ return JSON.stringify({ header: JSON.parse(decodeBase64Url2(parts[0])), payload: JSON.parse(decodeBase64Url2(parts[1])), signature: parts[2], note: "Decoded for inspection only. Signature validity was not verified." }, null, 2);
200
+ } catch {
201
+ throw new Error("JWT header and payload must contain valid Base64URL-encoded JSON.");
202
+ }
203
+ }
204
+ function testRegex(pattern, flags, text2) {
205
+ let regex;
206
+ try {
207
+ regex = new RegExp(pattern, flags);
208
+ } catch (cause) {
209
+ throw new Error(cause instanceof Error ? cause.message : "Invalid regular expression.");
210
+ }
211
+ const matches = [];
212
+ if (!regex.global) {
213
+ const match = regex.exec(text2);
214
+ if (match) matches.push({ match: match[0], index: match.index, groups: match.groups ?? {}, captures: match.slice(1) });
215
+ } else {
216
+ let match;
217
+ while ((match = regex.exec(text2)) !== null) {
218
+ matches.push({ match: match[0], index: match.index, groups: match.groups ?? {}, captures: match.slice(1) });
219
+ if (match[0] === "") regex.lastIndex += 1;
220
+ }
221
+ }
222
+ return JSON.stringify({ count: matches.length, matches }, null, 2);
223
+ }
224
+ function utf8Decode(bytes2) {
225
+ let result = "";
226
+ for (let i = 0; i < bytes2.length; ) {
227
+ const first = bytes2[i++];
228
+ let code;
229
+ if (first < 128) code = first;
230
+ else if (first >= 194 && first <= 223 && i < bytes2.length) code = (first & 31) << 6 | bytes2[i++] & 63;
231
+ else if (first >= 224 && first <= 239 && i + 1 < bytes2.length) code = (first & 15) << 12 | (bytes2[i++] & 63) << 6 | bytes2[i++] & 63;
232
+ 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;
233
+ else throw new Error("Invalid UTF-8 data");
234
+ if (code <= 65535) result += String.fromCharCode(code);
235
+ else {
236
+ const n = code - 65536;
237
+ result += String.fromCharCode(55296 | n >> 10, 56320 | n & 1023);
238
+ }
239
+ }
240
+ return result;
241
+ }
242
+ var BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
243
+ function decodeBase64(value) {
244
+ if (value.length % 4 !== 0 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value)) throw new Error("Invalid Base64 string");
245
+ const bytes2 = [];
246
+ for (let i = 0; i < value.length; i += 4) {
247
+ const a = BASE64.indexOf(value[i]);
248
+ const b = BASE64.indexOf(value[i + 1]);
249
+ const c = value[i + 2] === "=" ? 0 : BASE64.indexOf(value[i + 2]);
250
+ const d = value[i + 3] === "=" ? 0 : BASE64.indexOf(value[i + 3]);
251
+ bytes2.push(a << 2 | b >> 4);
252
+ if (value[i + 2] !== "=") bytes2.push((b & 15) << 4 | c >> 2);
253
+ if (value[i + 3] !== "=") bytes2.push((c & 3) << 6 | d);
254
+ }
255
+ return utf8Decode(bytes2);
256
+ }
257
+
258
+ // lib/tools/security-station.ts
259
+ var encoder = () => new TextEncoder();
260
+ function bytes(input) {
261
+ return typeof input === "string" ? encoder().encode(input) : input instanceof Uint8Array ? input : new Uint8Array(input);
262
+ }
263
+ function webBytes(input) {
264
+ return bytes(input).slice().buffer;
265
+ }
266
+ function hex(input) {
267
+ return Array.from(input, (byte) => byte.toString(16).padStart(2, "0")).join("");
268
+ }
269
+ function requireCrypto() {
270
+ if (!globalThis.crypto?.subtle) throw new Error("Web Crypto is unavailable in this environment.");
271
+ return globalThis.crypto;
272
+ }
273
+ function words(input) {
274
+ const length = input.length + 9 + 63 >> 6 << 4;
275
+ const out = new Array(length).fill(0);
276
+ input.forEach((byte, index) => {
277
+ out[index >> 2] |= byte << (index & 3) * 8;
278
+ });
279
+ out[input.length >> 2] |= 128 << (input.length & 3) * 8;
280
+ const bitLength = input.length * 8;
281
+ out[length - 2] = bitLength & 4294967295;
282
+ out[length - 1] = Math.floor(bitLength / 4294967296);
283
+ return out;
284
+ }
285
+ function rotl(value, count) {
286
+ return value << count | value >>> 32 - count;
287
+ }
288
+ function littleHex(value) {
289
+ return [0, 8, 16, 24].map((shift) => (value >>> shift & 255).toString(16).padStart(2, "0")).join("");
290
+ }
291
+ function md5(input) {
292
+ const k = Array.from({ length: 64 }, (_, i) => Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296));
293
+ const s = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21];
294
+ let a = 1732584193, b = 4023233417, c = 2562383102, d = 271733878;
295
+ const m = words(bytes(input));
296
+ for (let offset = 0; offset < m.length; offset += 16) {
297
+ let aa = a, bb = b, cc = c, dd = d;
298
+ for (let i = 0; i < 64; i++) {
299
+ let f, g;
300
+ if (i < 16) {
301
+ f = bb & cc | ~bb & dd;
302
+ g = i;
303
+ } else if (i < 32) {
304
+ f = dd & bb | ~dd & cc;
305
+ g = (5 * i + 1) % 16;
306
+ } else if (i < 48) {
307
+ f = bb ^ cc ^ dd;
308
+ g = (3 * i + 5) % 16;
309
+ } else {
310
+ f = cc ^ (bb | ~dd);
311
+ g = 7 * i % 16;
312
+ }
313
+ const next = dd;
314
+ dd = cc;
315
+ cc = bb;
316
+ bb = bb + rotl(aa + f + k[i] + m[offset + g] | 0, s[i]) | 0;
317
+ aa = next;
318
+ }
319
+ a = a + aa | 0;
320
+ b = b + bb | 0;
321
+ c = c + cc | 0;
322
+ d = d + dd | 0;
323
+ }
324
+ return littleHex(a) + littleHex(b) + littleHex(c) + littleHex(d);
325
+ }
326
+ function sha1(input) {
327
+ const source = bytes(input);
328
+ const padded = new Uint8Array(source.length + 9 + 63 >> 6 << 6);
329
+ padded.set(source);
330
+ padded[source.length] = 128;
331
+ const view = new DataView(padded.buffer);
332
+ view.setUint32(padded.length - 4, source.length * 8);
333
+ let h0 = 1732584193, h1 = 4023233417, h2 = 2562383102, h3 = 271733878, h4 = 3285377520;
334
+ for (let offset = 0; offset < padded.length; offset += 64) {
335
+ const w = new Uint32Array(80);
336
+ for (let i = 0; i < 16; i++) w[i] = view.getUint32(offset + i * 4);
337
+ for (let i = 16; i < 80; i++) w[i] = rotl(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1) >>> 0;
338
+ let a = h0, b = h1, c = h2, d = h3, e = h4;
339
+ for (let i = 0; i < 80; i++) {
340
+ const f = i < 20 ? b & c | ~b & d : i < 40 ? b ^ c ^ d : i < 60 ? b & c | b & d | c & d : b ^ c ^ d;
341
+ const t = rotl(a, 5) + f + e + w[i] + (i < 20 ? 1518500249 : i < 40 ? 1859775393 : i < 60 ? 2400959708 : 3395469782) | 0;
342
+ e = d;
343
+ d = c;
344
+ c = rotl(b, 30);
345
+ b = a;
346
+ a = t;
347
+ }
348
+ h0 = h0 + a | 0;
349
+ h1 = h1 + b | 0;
350
+ h2 = h2 + c | 0;
351
+ h3 = h3 + d | 0;
352
+ h4 = h4 + e | 0;
353
+ }
354
+ return [h0, h1, h2, h3, h4].map((value) => (value >>> 0).toString(16).padStart(8, "0")).join("");
355
+ }
356
+ async function hash(input, algorithm = "SHA-256") {
357
+ const result = await requireCrypto().subtle.digest(algorithm, webBytes(input));
358
+ return hex(new Uint8Array(result));
359
+ }
360
+ var sha256 = (input) => hash(input, "SHA-256");
361
+ var sha384 = (input) => hash(input, "SHA-384");
362
+ var sha512 = (input) => hash(input, "SHA-512");
363
+ async function hmac(input, secret, algorithm = "SHA-256") {
364
+ const crypto2 = requireCrypto();
365
+ const key = await crypto2.subtle.importKey("raw", webBytes(secret), { name: "HMAC", hash: algorithm }, false, ["sign"]);
366
+ return hex(new Uint8Array(await crypto2.subtle.sign("HMAC", key, webBytes(input))));
367
+ }
368
+ var hmacSha256 = (input, secret) => hmac(input, secret, "SHA-256");
369
+ var hmacSha512 = (input, secret) => hmac(input, secret, "SHA-512");
370
+ function crc32(input) {
371
+ let crc = 4294967295;
372
+ for (const byte of bytes(input)) {
373
+ crc ^= byte;
374
+ for (let i = 0; i < 8; i++) crc = crc >>> 1 ^ (crc & 1 ? 3988292384 : 0);
375
+ }
376
+ return ((crc ^ 4294967295) >>> 0).toString(16).padStart(8, "0");
377
+ }
378
+
379
+ // lib/tools/text-station.ts
380
+ var MAX_TEXT_LENGTH = 1e6;
381
+ var MAX_DIFF_LINES = 2e3;
382
+ var MAX_DIFF_CELLS = 4e6;
383
+ var LOREM_WORDS = [
384
+ "lorem",
385
+ "ipsum",
386
+ "dolor",
387
+ "sit",
388
+ "amet",
389
+ "consectetur",
390
+ "adipiscing",
391
+ "elit",
392
+ "sed",
393
+ "do",
394
+ "eiusmod",
395
+ "tempor",
396
+ "incididunt",
397
+ "ut",
398
+ "labore",
399
+ "et",
400
+ "dolore",
401
+ "magna",
402
+ "aliqua",
403
+ "enim",
404
+ "ad",
405
+ "minim",
406
+ "veniam",
407
+ "quis",
408
+ "nostrud",
409
+ "exercitation",
410
+ "ullamco",
411
+ "laboris",
412
+ "nisi",
413
+ "aliquip",
414
+ "ex",
415
+ "ea",
416
+ "commodo",
417
+ " consequat",
418
+ "duis",
419
+ "aute",
420
+ "irure",
421
+ "in",
422
+ "reprehenderit",
423
+ "voluptate",
424
+ "velit",
425
+ "esse",
426
+ "cillum",
427
+ "fugiat",
428
+ "nulla",
429
+ "pariatur",
430
+ "excepteur",
431
+ "sint",
432
+ "occaecat",
433
+ "cupidatat",
434
+ "non",
435
+ "proident",
436
+ "sunt",
437
+ "culpa",
438
+ "qui",
439
+ "officia",
440
+ "deserunt",
441
+ "mollit",
442
+ "anim",
443
+ "id",
444
+ "est",
445
+ "laborum"
446
+ ].map((word) => word.trim());
447
+ function assertText(value, name = "text") {
448
+ if (typeof value !== "string") throw new TypeError(`${name} must be a string.`);
449
+ if (value.length > MAX_TEXT_LENGTH) throw new RangeError(`${name} must be at most ${MAX_TEXT_LENGTH.toLocaleString()} characters.`);
450
+ return value;
451
+ }
452
+ function parseLines(value) {
453
+ assertText(value);
454
+ const firstCrLf = value.indexOf("\r\n");
455
+ const firstLf = value.indexOf("\n");
456
+ const firstCr = value.indexOf("\r");
457
+ let ending = "\n";
458
+ if (firstCrLf >= 0 && (firstLf < 0 || firstCrLf <= firstLf)) ending = "\r\n";
459
+ else if (firstCr >= 0 && (firstLf < 0 || firstCr < firstLf)) ending = "\r";
460
+ const normalized = value.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
461
+ if (!normalized) return { lines: [], ending, trailingBreak: false };
462
+ const trailingBreak = normalized.endsWith("\n");
463
+ const body = trailingBreak ? normalized.slice(0, -1) : normalized;
464
+ return { lines: body ? body.split("\n") : [""], ending, trailingBreak };
465
+ }
466
+ function firstCharacterUpper(value, locale) {
467
+ const characters = Array.from(value);
468
+ if (!characters.length) return value;
469
+ return characters[0].toLocaleUpperCase(locale) + characters.slice(1).join("");
470
+ }
471
+ function wordsOf(value) {
472
+ return value.replace(/([\p{Ll}\p{N}])([\p{Lu}])/gu, "$1 $2").match(/[\p{L}\p{N}]+/gu) ?? [];
473
+ }
474
+ function convertCase(value, style, options = {}) {
475
+ assertText(value);
476
+ const locale = options.locale;
477
+ if (style === "upper") return value.toLocaleUpperCase(locale);
478
+ if (style === "lower") return value.toLocaleLowerCase(locale);
479
+ if (style === "title") {
480
+ return value.toLocaleLowerCase(locale).replace(/(^|[\s\-_\/.])([\p{L}\p{N}])/gu, (_, separator, character) => `${separator}${character.toLocaleUpperCase(locale)}`);
481
+ }
482
+ if (style === "sentence") {
483
+ const lower = value.toLocaleLowerCase(locale);
484
+ return lower.replace(/(^|[.!?…。!?]\s+)(\s*)([\p{L}\p{N}])/gu, (_, boundary, whitespace, character) => `${boundary}${whitespace}${character.toLocaleUpperCase(locale)}`);
485
+ }
486
+ const words2 = wordsOf(value).map((word) => word.toLocaleLowerCase(locale));
487
+ if (style === "camel") return words2.map((word, index) => index === 0 ? word : firstCharacterUpper(word, locale)).join("");
488
+ if (style === "pascal") return words2.map((word) => firstCharacterUpper(word, locale)).join("");
489
+ if (style === "snake") return words2.join("_");
490
+ if (style === "kebab") return words2.join("-");
491
+ if (style === "constant") return words2.map((word) => word.toLocaleUpperCase(locale)).join("_");
492
+ throw new Error(`Unsupported case style: ${String(style)}.`);
493
+ }
494
+ function escapeRegex(value) {
495
+ return value.replace(/[\\^$.*+?()[\]{}|/]/g, "\\$&");
496
+ }
497
+ function diffOperations(left, right) {
498
+ if (left.length > MAX_DIFF_LINES || right.length > MAX_DIFF_LINES) throw new RangeError(`Text diff supports at most ${MAX_DIFF_LINES.toLocaleString()} lines per side.`);
499
+ if (left.length * right.length > MAX_DIFF_CELLS) throw new RangeError("Text diff inputs are too large to compare safely; reduce the number of lines.");
500
+ const table = Array.from({ length: left.length + 1 }, () => new Uint32Array(right.length + 1));
501
+ for (let i2 = left.length - 1; i2 >= 0; i2 -= 1) {
502
+ for (let j2 = right.length - 1; j2 >= 0; j2 -= 1) table[i2][j2] = left[i2] === right[j2] ? table[i2 + 1][j2 + 1] + 1 : Math.max(table[i2 + 1][j2], table[i2][j2 + 1]);
503
+ }
504
+ const operations = [];
505
+ let i = 0;
506
+ let j = 0;
507
+ while (i < left.length && j < right.length) {
508
+ if (left[i] === right[j]) {
509
+ operations.push({ type: "equal", text: left[i] });
510
+ i += 1;
511
+ j += 1;
512
+ } else if (table[i + 1][j] >= table[i][j + 1]) {
513
+ operations.push({ type: "deletion", text: left[i] });
514
+ i += 1;
515
+ } else {
516
+ operations.push({ type: "addition", text: right[j] });
517
+ j += 1;
518
+ }
519
+ }
520
+ while (i < left.length) operations.push({ type: "deletion", text: left[i++] });
521
+ while (j < right.length) operations.push({ type: "addition", text: right[j++] });
522
+ return operations;
523
+ }
524
+ function buildUnified(operations) {
525
+ let oldLine = 1;
526
+ let newLine = 1;
527
+ let added = 0;
528
+ let removed = 0;
529
+ const lines = operations.map((operation) => {
530
+ if (operation.type === "equal") return { type: "context", text: operation.text, oldLine: oldLine++, newLine: newLine++ };
531
+ if (operation.type === "deletion") {
532
+ removed += 1;
533
+ return { type: "deletion", text: operation.text, oldLine: oldLine++, newLine: null };
534
+ }
535
+ added += 1;
536
+ return { type: "addition", text: operation.text, oldLine: null, newLine: newLine++ };
537
+ });
538
+ const text2 = ["--- left", "+++ right", ...lines.map((line) => `${line.type === "context" ? " " : line.type === "deletion" ? "-" : "+"}${line.text}`)].join("\n");
539
+ return { lines, text: text2, added, removed };
540
+ }
541
+ function buildSideBySide(operations) {
542
+ const rows = [];
543
+ let leftLine = 1;
544
+ let rightLine = 1;
545
+ for (let i = 0; i < operations.length; i += 1) {
546
+ const operation = operations[i];
547
+ if (operation.type === "equal") {
548
+ rows.push({ type: "equal", left: { line: leftLine++, text: operation.text }, right: { line: rightLine++, text: operation.text } });
549
+ continue;
550
+ }
551
+ const deleted = [];
552
+ const added = [];
553
+ while (i < operations.length && operations[i].type !== "equal") {
554
+ if (operations[i].type === "deletion") deleted.push(operations[i].text);
555
+ else added.push(operations[i].text);
556
+ i += 1;
557
+ }
558
+ i -= 1;
559
+ const width = Math.max(deleted.length, added.length);
560
+ for (let offset = 0; offset < width; offset += 1) {
561
+ const left = deleted[offset];
562
+ const right = added[offset];
563
+ rows.push({
564
+ type: left !== void 0 && right !== void 0 ? "changed" : left !== void 0 ? "removed" : "added",
565
+ left: left === void 0 ? null : { line: leftLine++, text: left },
566
+ right: right === void 0 ? null : { line: rightLine++, text: right }
567
+ });
568
+ }
569
+ }
570
+ return rows;
571
+ }
572
+ function textDiff(left, right) {
573
+ const leftParsed = parseLines(left);
574
+ const rightParsed = parseLines(right);
575
+ const operations = diffOperations(leftParsed.lines, rightParsed.lines);
576
+ const unified = buildUnified(operations);
577
+ const sideBySide = buildSideBySide(operations);
578
+ return {
579
+ changed: unified.added > 0 || unified.removed > 0,
580
+ added: unified.added,
581
+ removed: unified.removed,
582
+ unified: unified.text,
583
+ unifiedLines: unified.lines,
584
+ sideBySide,
585
+ unifiedData: unified.lines,
586
+ sideBySideData: sideBySide
587
+ };
588
+ }
589
+ function diffText(left, right) {
590
+ return textDiff(left, right).unified;
591
+ }
592
+ function slugify(value, separator = "-") {
593
+ assertText(value);
594
+ assertText(separator, "separator");
595
+ if (!separator || separator.length > 16 || /[\p{L}\p{N}]/u.test(separator)) throw new Error("Slug separator must be 1\u201316 non-alphanumeric characters.");
596
+ return value.normalize("NFKD").replace(/[\u0300-\u036f]/gu, "").toLocaleLowerCase().replace(/[^\p{L}\p{N}]+/gu, separator).replace(new RegExp(`(?:${escapeRegex(separator)})+`, "g"), separator).replace(new RegExp(`^${escapeRegex(separator)}|${escapeRegex(separator)}$`, "g"), "");
597
+ }
598
+
599
+ // lib/tools/date-time-station.ts
600
+ var SECOND = 1e3;
601
+ var MINUTE = 60 * SECOND;
602
+ var HOUR = 60 * MINUTE;
603
+ var DAY = 24 * HOUR;
604
+ var MIN_DATE = -621355968e5;
605
+ var MAX_DATE = 253402300799999;
606
+ function integer(value, name, min, max) {
607
+ if (!Number.isInteger(value) || value < min || value > max) throw new RangeError(`${name} must be an integer between ${min} and ${max}.`);
608
+ return value;
609
+ }
610
+ function inputText(value, name = "Date", max = 256) {
611
+ if (typeof value !== "string") throw new TypeError(`${name} must be text.`);
612
+ const text2 = value.trim();
613
+ if (!text2) throw new Error(`${name} cannot be empty.`);
614
+ if (text2.length > max) throw new RangeError(`${name} must be at most ${max} characters.`);
615
+ return text2;
616
+ }
617
+ function isGregorianLeapYear(year) {
618
+ return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
619
+ }
620
+ function daysInMonth(year, month) {
621
+ return [31, isGregorianLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1];
622
+ }
623
+ function validateParts(parts) {
624
+ integer(parts.year, "Year", 1, 9999);
625
+ integer(parts.month, "Month", 1, 12);
626
+ integer(parts.day, "Day", 1, daysInMonth(parts.year, parts.month));
627
+ integer(parts.hour, "Hour", 0, 23);
628
+ integer(parts.minute, "Minute", 0, 59);
629
+ integer(parts.second, "Second", 0, 59);
630
+ integer(parts.millisecond, "Millisecond", 0, 999);
631
+ }
632
+ function utcMilliseconds(parts) {
633
+ const date = /* @__PURE__ */ new Date(0);
634
+ date.setUTCFullYear(parts.year, parts.month - 1, parts.day);
635
+ date.setUTCHours(parts.hour ?? 0, parts.minute ?? 0, parts.second ?? 0, parts.millisecond ?? 0);
636
+ return date.getTime();
637
+ }
638
+ function checkedDate(milliseconds) {
639
+ if (!Number.isFinite(milliseconds)) throw new RangeError("Date or timestamp must be finite and valid.");
640
+ if (milliseconds < MIN_DATE || milliseconds > MAX_DATE) throw new RangeError("Date must be within Gregorian years 0001\u20139999 in UTC.");
641
+ return new Date(milliseconds);
642
+ }
643
+ function timestampUnit(unit) {
644
+ if (unit !== "seconds" && unit !== "milliseconds") throw new Error("Timestamp unit must be seconds or milliseconds.");
645
+ return unit;
646
+ }
647
+ function timestampToDate(value, unit = "seconds") {
648
+ timestampUnit(unit);
649
+ let number;
650
+ if (typeof value === "string") {
651
+ const text2 = inputText(value, "Timestamp");
652
+ if (!/^[+-]?\d+(?:\.\d+)?$/.test(text2)) throw new Error("Timestamp must be a decimal number, without exponent notation.");
653
+ number = Number(text2);
654
+ } else if (typeof value === "number") number = value;
655
+ else throw new TypeError("Timestamp must be a number or numeric text.");
656
+ if (!Number.isFinite(number)) throw new RangeError("Timestamp must be finite.");
657
+ if (unit === "milliseconds" && !Number.isInteger(number)) throw new RangeError("A millisecond timestamp must be an integer.");
658
+ return checkedDate(unit === "seconds" ? Math.round(number * SECOND) : number);
659
+ }
660
+ function zoneFormatter(timeZone) {
661
+ const zone = inputText(timeZone, "Time zone", 128);
662
+ if (/^[+-]/.test(zone)) throw new Error("Use an IANA time zone such as America/New_York, Asia/Kolkata, or UTC.");
663
+ try {
664
+ return new Intl.DateTimeFormat("en-US", {
665
+ timeZone: zone,
666
+ calendar: "gregory",
667
+ numberingSystem: "latn",
668
+ era: "short",
669
+ year: "numeric",
670
+ month: "2-digit",
671
+ day: "2-digit",
672
+ hour: "2-digit",
673
+ minute: "2-digit",
674
+ second: "2-digit",
675
+ hourCycle: "h23"
676
+ });
677
+ } catch {
678
+ throw new Error(`Unknown or unsupported IANA time zone: ${zone}.`);
679
+ }
680
+ }
681
+ function validateTimeZone(timeZone) {
682
+ return zoneFormatter(timeZone).resolvedOptions().timeZone;
683
+ }
684
+ function zoneParts(milliseconds, formatter) {
685
+ const fields = Object.fromEntries(formatter.formatToParts(new Date(milliseconds)).map((part) => [part.type, part.value]));
686
+ return {
687
+ year: fields.era === "BC" ? 1 - Number(fields.year) : Number(fields.year),
688
+ month: Number(fields.month),
689
+ day: Number(fields.day),
690
+ hour: Number(fields.hour),
691
+ minute: Number(fields.minute),
692
+ second: Number(fields.second),
693
+ millisecond: (milliseconds % SECOND + SECOND) % SECOND
694
+ };
695
+ }
696
+ function disambiguation(value = "reject") {
697
+ if (!["reject", "earlier", "later"].includes(value)) throw new Error("Time disambiguation must be reject, earlier, or later.");
698
+ return value;
699
+ }
700
+ function sameParts(left, right) {
701
+ return left.year === right.year && left.month === right.month && left.day === right.day && left.hour === right.hour && left.minute === right.minute && left.second === right.second && left.millisecond === right.millisecond;
702
+ }
703
+ function localToDate(parts, formatter, choice) {
704
+ const wall = utcMilliseconds(parts);
705
+ const offsets = /* @__PURE__ */ new Set();
706
+ for (let hours = -48; hours <= 48; hours += 12) {
707
+ const sample = wall + hours * HOUR;
708
+ offsets.add(utcMilliseconds(zoneParts(sample, formatter)) - sample);
709
+ }
710
+ const matches = [...offsets].map((offset) => wall - offset).filter((candidate) => sameParts(zoneParts(candidate, formatter), parts)).sort((a, b) => a - b);
711
+ const zone = formatter.resolvedOptions().timeZone;
712
+ if (!matches.length) throw new Error(`This local time does not exist in ${zone} because of a time-zone clock change. Choose another time or an explicit UTC offset.`);
713
+ if (matches.length > 1 && choice === "reject") throw new Error(`This local time occurs twice in ${zone}. Choose earlier or later, or supply an explicit UTC offset.`);
714
+ return checkedDate(choice === "later" ? matches[matches.length - 1] : matches[0]);
715
+ }
716
+ function offsetMilliseconds(value) {
717
+ if (/^z$/i.test(value)) return 0;
718
+ const match = /^([+-])(\d{2}):?(\d{2})$/.exec(value);
719
+ if (!match) throw new Error("UTC offset must be Z or \xB1HH:mm.");
720
+ const hours = integer(Number(match[2]), "Offset hour", 0, 23);
721
+ const minutes = integer(Number(match[3]), "Offset minute", 0, 59);
722
+ if (match[1] === "-" && hours === 0 && minutes === 0) throw new Error("The unknown UTC offset -00:00 cannot identify an instant. Use Z or a known offset.");
723
+ return (match[1] === "-" ? -1 : 1) * (hours * HOUR + minutes * MINUTE);
724
+ }
725
+ function partsToDate(parts, offset, options) {
726
+ validateParts(parts);
727
+ const choice = disambiguation(options.disambiguation);
728
+ const formatter = zoneFormatter(options.timeZone ?? "UTC");
729
+ return offset ? checkedDate(utcMilliseconds(parts) - offsetMilliseconds(offset)) : localToDate(parts, formatter, choice);
730
+ }
731
+ function parseDateTime(value, options = {}) {
732
+ timestampUnit(options.timestampUnit ?? "milliseconds");
733
+ disambiguation(options.disambiguation);
734
+ if (options.timeZone !== void 0) validateTimeZone(options.timeZone);
735
+ if (value instanceof Date) return checkedDate(value.getTime());
736
+ if (typeof value === "number") return timestampToDate(value, options.timestampUnit ?? "milliseconds");
737
+ const text2 = inputText(value);
738
+ if (/^[+-]?\d+(?:\.\d+)?$/.test(text2)) return timestampToDate(text2, options.timestampUnit ?? "milliseconds");
739
+ 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);
740
+ if (!match) throw new Error("Use YYYY-MM-DD, an ISO date/time with up to 3 fractional digits, or an explicit numeric timestamp.");
741
+ return partsToDate({
742
+ year: Number(match[1]),
743
+ month: Number(match[2]),
744
+ day: Number(match[3]),
745
+ hour: Number(match[4] ?? 0),
746
+ minute: Number(match[5] ?? 0),
747
+ second: Number(match[6] ?? 0),
748
+ millisecond: Number((match[7] ?? "").padEnd(3, "0"))
749
+ }, match[8], options);
750
+ }
751
+ function pad(value, length = 2) {
752
+ return String(value).padStart(length, "0");
753
+ }
754
+ function calendarText(parts) {
755
+ return `${pad(parts.year, 4)}-${pad(parts.month)}-${pad(parts.day)}`;
756
+ }
757
+ function clockText(parts) {
758
+ return `${pad(parts.hour)}:${pad(parts.minute)}:${pad(parts.second)}.${pad(parts.millisecond, 3)}`;
759
+ }
760
+ function offsetText(milliseconds) {
761
+ if (!milliseconds) return "Z";
762
+ const seconds = Math.abs(milliseconds) / SECOND;
763
+ const hours = Math.floor(seconds / 3600);
764
+ const minutes = Math.floor(seconds % 3600 / 60);
765
+ const remainder = seconds % 60;
766
+ return `${milliseconds < 0 ? "-" : "+"}${pad(hours)}:${pad(minutes)}${remainder ? `:${pad(remainder)}` : ""}`;
767
+ }
768
+ function getZonedDateTime(value, timeZone = "UTC", options = {}) {
769
+ const date = parseDateTime(value, options);
770
+ const formatter = zoneFormatter(timeZone);
771
+ const parts = zoneParts(date.getTime(), formatter);
772
+ validateParts(parts);
773
+ const offset = utcMilliseconds(parts) - date.getTime();
774
+ const renderedOffset = offsetText(offset);
775
+ return {
776
+ ...parts,
777
+ timeZone: formatter.resolvedOptions().timeZone,
778
+ offsetMinutes: offset / MINUTE,
779
+ offset: renderedOffset,
780
+ unixMilliseconds: date.getTime(),
781
+ iso: date.toISOString(),
782
+ dateTime: `${calendarText(parts)}T${clockText(parts)}${renderedOffset}`
783
+ };
784
+ }
785
+ function formatRfc3339(value, timeZoneOrOptions = "UTC", options = {}) {
786
+ const timeZone = typeof timeZoneOrOptions === "string" ? timeZoneOrOptions : timeZoneOrOptions.timeZone ?? "UTC";
787
+ const parseOptions = typeof timeZoneOrOptions === "string" ? options : timeZoneOrOptions;
788
+ const zoned = getZonedDateTime(value, timeZone, parseOptions);
789
+ if (!Number.isInteger(zoned.offsetMinutes)) throw new Error("RFC3339 cannot represent this historical sub-minute UTC offset. Format in UTC instead.");
790
+ return zoned.dateTime;
791
+ }
792
+ function convertTimeZone(value, targetTimeZone, options = {}) {
793
+ const parseOptions = typeof options === "string" ? { timeZone: options } : options;
794
+ return formatRfc3339(value, targetTimeZone, parseOptions);
795
+ }
796
+ function convertBetweenTimeZones(value, sourceTimeZone, targetTimeZone) {
797
+ return convertTimeZone(value, targetTimeZone, { timeZone: sourceTimeZone });
798
+ }
799
+ var relativeUnits = [
800
+ { unit: "year", milliseconds: 365 * DAY },
801
+ { unit: "quarter", milliseconds: 91 * DAY },
802
+ { unit: "month", milliseconds: 30 * DAY },
803
+ { unit: "week", milliseconds: 7 * DAY },
804
+ { unit: "day", milliseconds: DAY },
805
+ { unit: "hour", milliseconds: HOUR },
806
+ { unit: "minute", milliseconds: MINUTE },
807
+ { unit: "second", milliseconds: SECOND }
808
+ ];
809
+ function calendarCompare(left, right) {
810
+ return utcMilliseconds(left) - utcMilliseconds(right);
811
+ }
812
+ function calendarDayNumber(date) {
813
+ return Math.floor(utcMilliseconds(date) / DAY);
814
+ }
815
+ function calendarFromDayNumber(day) {
816
+ const date = new Date(day * DAY);
817
+ return { year: date.getUTCFullYear(), month: date.getUTCMonth() + 1, day: date.getUTCDate() };
818
+ }
819
+ function calendarWeekday(date) {
820
+ return new Date(utcMilliseconds(date)).getUTCDay();
821
+ }
822
+ function dateCalendar(value, options) {
823
+ const zoned = getZonedDateTime(value, options.timeZone ?? "UTC", { timeZone: options.timeZone ?? "UTC" });
824
+ return { year: zoned.year, month: zoned.month, day: zoned.day };
825
+ }
826
+ function weekdaysInclusive(start, end) {
827
+ if (calendarCompare(start, end) > 0) return -weekdaysInclusive(end, start);
828
+ const first = calendarDayNumber(start);
829
+ const total = calendarDayNumber(end) - first + 1;
830
+ const weeks = Math.floor(total / 7);
831
+ let count = weeks * 5;
832
+ for (let day = first + weeks * 7; day <= calendarDayNumber(end); day += 1) {
833
+ const weekday = new Date(day * DAY).getUTCDay();
834
+ if (weekday !== 0 && weekday !== 6) count += 1;
835
+ }
836
+ return count;
837
+ }
838
+ function businessDaysBetween(start, end, options = {}) {
839
+ const left = dateCalendar(start, options);
840
+ const right = dateCalendar(end, options);
841
+ if (calendarCompare(left, right) === 0) return (options.inclusiveStart ?? true) && (options.inclusiveEnd ?? false) && calendarWeekday(left) !== 0 && calendarWeekday(left) !== 6 ? 1 : 0;
842
+ const direction = calendarCompare(left, right) < 0 ? 1 : -1;
843
+ const earlier = direction > 0 ? left : right;
844
+ const later = direction > 0 ? right : left;
845
+ let first = calendarDayNumber(earlier);
846
+ let last = calendarDayNumber(later);
847
+ const includeEarlier = direction > 0 ? options.inclusiveStart ?? true : options.inclusiveEnd ?? false;
848
+ const includeLater = direction > 0 ? options.inclusiveEnd ?? false : options.inclusiveStart ?? true;
849
+ if (!includeEarlier) first += 1;
850
+ if (!includeLater) last -= 1;
851
+ if (first > last) return 0;
852
+ return direction * weekdaysInclusive(calendarFromDayNumber(first), calendarFromDayNumber(last));
853
+ }
854
+
855
+ // lib/tools/cron/parser.ts
856
+ var MONTH_NAMES = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
857
+ var WEEKDAY_NAMES = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"];
858
+ var SPECS = [
859
+ { name: "second", label: "Second", min: 0, max: 59 },
860
+ { name: "minute", label: "Minute", min: 0, max: 59 },
861
+ { name: "hour", label: "Hour", min: 0, max: 23 },
862
+ { name: "dayOfMonth", label: "Day of month", min: 1, max: 31 },
863
+ { name: "month", label: "Month", min: 1, max: 12 },
864
+ { name: "dayOfWeek", label: "Day of week", min: 0, max: 7 }
865
+ ];
866
+ function parseField(expression, spec) {
867
+ const fail = (message) => {
868
+ throw new Error(`${spec.label}: ${message}`);
869
+ };
870
+ if (expression.length > 128) fail("field exceeds the 128-character limit.");
871
+ if (!expression) fail("field cannot be empty.");
872
+ const endpoint = (text2) => {
873
+ let value;
874
+ if (/^\d+$/.test(text2)) value = Number(text2);
875
+ else if (spec.name === "month" && MONTH_NAMES.includes(text2.toUpperCase())) value = MONTH_NAMES.indexOf(text2.toUpperCase()) + 1;
876
+ else if (spec.name === "dayOfWeek" && WEEKDAY_NAMES.includes(text2.toUpperCase())) value = WEEKDAY_NAMES.indexOf(text2.toUpperCase());
877
+ else return fail("use integer values, permitted month/weekday names, *, ranges, lists or steps.");
878
+ if (!Number.isSafeInteger(value) || value < spec.min || value > spec.max) fail(`value must be between ${spec.min} and ${spec.max}.`);
879
+ return value;
880
+ };
881
+ const selected = /* @__PURE__ */ new Set();
882
+ for (const item of expression.split(",")) {
883
+ if (!item) fail("lists cannot contain empty items.");
884
+ const pieces = item.split("/");
885
+ if (pieces.length > 2 || !pieces[0]) fail("malformed step notation.");
886
+ let step = 1;
887
+ if (pieces.length === 2) {
888
+ if (!/^\d+$/.test(pieces[1])) fail("step must be a positive integer.");
889
+ step = Number(pieces[1]);
890
+ if (!Number.isSafeInteger(step) || step < 1 || step > spec.max - spec.min + 1) fail(`step must be between 1 and ${spec.max - spec.min + 1}.`);
891
+ }
892
+ const base = pieces[0];
893
+ let first;
894
+ let last;
895
+ if (base === "*") {
896
+ first = spec.min;
897
+ last = spec.max;
898
+ } else {
899
+ const range = base.split("-");
900
+ if (range.length > 2 || range.some((value) => !value)) fail("malformed range; negative values are not supported.");
901
+ first = endpoint(range[0]);
902
+ last = range.length === 2 ? endpoint(range[1]) : pieces.length === 2 ? spec.max : first;
903
+ if (last < first) fail("descending or wrapping ranges are not supported.");
904
+ }
905
+ for (let value = first; value <= last; value += step) selected.add(spec.name === "dayOfWeek" && value === 7 ? 0 : value);
906
+ }
907
+ return { ...spec, expression, values: [...selected].sort((a, b) => a - b), wildcard: expression.startsWith("*") };
908
+ }
909
+ function parseCron(expression) {
910
+ if (typeof expression !== "string" || !expression.trim()) throw new Error("Enter a cron expression.");
911
+ if (expression.length > 1024) throw new Error("Cron expression exceeds the 1,024-character limit.");
912
+ if (/[?#]/.test(expression) || /(?:^|[\s,/-])(?:L|LW|\d+[LW]|W|H(?:\([^)]*\))?)(?=$|[\s,/-])/i.test(expression) || /\b(?:cron|rate)\s*\(/i.test(expression)) {
913
+ throw new Error("Quartz, AWS and Jenkins extensions (?, L, W, # and H) are not supported; use Unix numeric cron notation.");
914
+ }
915
+ if (expression.includes("@")) throw new Error("Cron macros are not supported; enter five Unix fields or six seconds-first fields.");
916
+ const tokens = expression.trim().split(/\s+/);
917
+ if (tokens.length !== 5 && tokens.length !== 6) throw new Error("Expected five Unix fields or six seconds-first fields; years, commands, comments and environment assignments are not supported.");
918
+ const hasSeconds = tokens.length === 6;
919
+ const fields = tokens.map((token, index) => parseField(token, SPECS[index + (hasSeconds ? 0 : 1)]));
920
+ const second = hasSeconds ? fields[0] : parseField("0", SPECS[0]);
921
+ const [minute, hour, dayOfMonth, month, dayOfWeek] = fields.slice(hasSeconds ? 1 : 0);
922
+ return { expression, hasSeconds, fields, second, minute, hour, dayOfMonth, month, dayOfWeek, dayMode: dayOfMonth.wildcard || dayOfWeek.wildcard ? "and" : "or" };
923
+ }
924
+ function matchesCronDate(cron, year, month, day) {
925
+ if (!cron.month.values.includes(month)) return false;
926
+ const dom = cron.dayOfMonth.values.includes(day);
927
+ const dow = cron.dayOfWeek.values.includes(new Date(Date.UTC(year, month - 1, day)).getUTCDay());
928
+ return cron.dayMode === "and" ? dom && dow : dom || dow;
929
+ }
930
+
931
+ // lib/tools/cron/explain.ts
932
+ var FULL_MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
933
+ var FULL_WEEKDAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
934
+ var pad2 = (value) => String(value).padStart(2, "0");
935
+ function explainCron(cron) {
936
+ let timing;
937
+ if (cron.hour.values.length === 1 && cron.minute.values.length === 1 && cron.second.values.length === 1) {
938
+ timing = `At ${pad2(cron.hour.values[0])}:${pad2(cron.minute.values[0])}${cron.hasSeconds ? `:${pad2(cron.second.values[0])}` : ""}`;
939
+ } else if (cron.hasSeconds && cron.hour.expression === "*" && cron.minute.expression === "*" && cron.second.expression === "*") timing = "Every second";
940
+ else if (cron.hour.expression === "*" && cron.minute.expression === "*" && !cron.hasSeconds) timing = "Every minute (at second 0)";
941
+ else if (cron.hour.expression === "*" && /^\*\/\d+$/.test(cron.minute.expression) && !cron.hasSeconds) timing = `Every ${Number(cron.minute.expression.slice(2))} minutes within each hour (at second 0)`;
942
+ else if (cron.hour.expression === "*" && cron.minute.values.length === 1 && cron.second.values.length === 1) timing = `Every hour at minute ${cron.minute.values[0]}, second ${cron.second.values[0]}`;
943
+ else timing = `${cron.hasSeconds ? "Seconds-first schedule" : "Unix schedule (at second 0)"}: hours ${cron.hour.expression === "*" ? "every hour" : cron.hour.values.map(pad2).join(", ")}; minutes ${cron.minute.expression === "*" ? "every minute" : cron.minute.values.map(pad2).join(", ")}${cron.hasSeconds ? `; seconds ${cron.second.expression === "*" ? "every second" : cron.second.values.map(pad2).join(", ")}` : ""}`;
944
+ const months = cron.month.values.length === 12 ? "" : `; in ${cron.month.values.map((value) => FULL_MONTHS[value - 1]).join(", ")}`;
945
+ const dom = cron.dayOfMonth.values.length === 31 ? "every day of month" : `day of month ${cron.dayOfMonth.values.join(", ")}`;
946
+ const dow = cron.dayOfWeek.values.length === 7 ? "every weekday (Sunday\u2013Saturday)" : cron.dayOfWeek.values.map((value) => FULL_WEEKDAYS[value]).join(", ");
947
+ const days = cron.dayMode === "or" ? `when either ${dom} OR weekday ${dow} matches` : cron.dayOfMonth.values.length === 31 && cron.dayOfWeek.values.length === 7 ? "every day" : cron.dayOfMonth.values.length === 31 ? `on ${dow}` : cron.dayOfWeek.values.length === 7 ? `on ${dom}` : `when both ${dom} AND weekday ${dow} match`;
948
+ return `${timing}; ${days}${months}.`;
949
+ }
950
+
951
+ // lib/tools/json-to-types.ts
952
+ function toPascalCase(str) {
953
+ const clean = str.replace(/[^a-zA-Z0-9]/g, " ");
954
+ return clean.split(/\s+/).filter(Boolean).map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("") || "NestedType";
955
+ }
956
+ function isValidIdentifier(name) {
957
+ return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);
958
+ }
959
+ function formatKey(key) {
960
+ return isValidIdentifier(key) ? key : JSON.stringify(key);
961
+ }
962
+ function jsonToTypescript(jsonInput, rootName = "Root") {
963
+ let parsed;
964
+ try {
965
+ parsed = JSON.parse(jsonInput);
966
+ } catch (err) {
967
+ throw new Error(`Invalid JSON: ${err instanceof Error ? err.message : String(err)}`);
968
+ }
969
+ const interfaces = [];
970
+ const createdNames = /* @__PURE__ */ new Set();
971
+ function getUniqueName(base) {
972
+ let name = toPascalCase(base);
973
+ let counter = 1;
974
+ while (createdNames.has(name)) {
975
+ counter += 1;
976
+ name = `${toPascalCase(base)}${counter}`;
977
+ }
978
+ createdNames.add(name);
979
+ return name;
980
+ }
981
+ function resolveType(val, keyHint) {
982
+ if (val === null) return "null";
983
+ if (val === void 0) return "undefined";
984
+ const type = typeof val;
985
+ if (type === "string" || type === "number" || type === "boolean") {
986
+ return type;
987
+ }
988
+ if (Array.isArray(val)) {
989
+ if (val.length === 0) return "unknown[]";
990
+ const itemTypes = /* @__PURE__ */ new Set();
991
+ const sampleObjects = [];
992
+ for (const item of val) {
993
+ if (item && typeof item === "object" && !Array.isArray(item)) {
994
+ sampleObjects.push(item);
995
+ } else {
996
+ itemTypes.add(resolveType(item, `${keyHint}Item`));
997
+ }
998
+ }
999
+ if (sampleObjects.length > 0) {
1000
+ const merged = {};
1001
+ for (const obj of sampleObjects) {
1002
+ for (const [k, v] of Object.entries(obj)) {
1003
+ if (!merged[k]) merged[k] = { types: /* @__PURE__ */ new Set(), count: 0 };
1004
+ merged[k].count += 1;
1005
+ merged[k].types.add(resolveType(v, k));
1006
+ }
1007
+ }
1008
+ const lines = [];
1009
+ for (const [k, meta] of Object.entries(merged)) {
1010
+ const isOptional = meta.count < sampleObjects.length;
1011
+ const typeStr = Array.from(meta.types).join(" | ") || "unknown";
1012
+ const formattedKey = formatKey(k) + (isOptional ? "?" : "");
1013
+ lines.push(` ${formattedKey}: ${typeStr};`);
1014
+ }
1015
+ const interfaceName = getUniqueName(`${keyHint}Item`);
1016
+ interfaces.unshift({
1017
+ name: interfaceName,
1018
+ body: `export interface ${interfaceName} {
1019
+ ${lines.join("\n")}
1020
+ }`
1021
+ });
1022
+ itemTypes.add(interfaceName);
1023
+ }
1024
+ const union = Array.from(itemTypes).join(" | ");
1025
+ return union.includes(" | ") ? `(${union})[]` : `${union}[]`;
1026
+ }
1027
+ if (type === "object") {
1028
+ const obj = val;
1029
+ const lines = [];
1030
+ for (const [k, v] of Object.entries(obj)) {
1031
+ const typeStr = resolveType(v, k);
1032
+ lines.push(` ${formatKey(k)}: ${typeStr};`);
1033
+ }
1034
+ const interfaceName = getUniqueName(keyHint);
1035
+ interfaces.unshift({
1036
+ name: interfaceName,
1037
+ body: `export interface ${interfaceName} {
1038
+ ${lines.join("\n")}
1039
+ }`
1040
+ });
1041
+ return interfaceName;
1042
+ }
1043
+ return "unknown";
1044
+ }
1045
+ const rootTypeName = toPascalCase(rootName) || "Root";
1046
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
1047
+ const rootType = resolveType(parsed, rootTypeName);
1048
+ const found = interfaces.find((i) => i.name === rootType);
1049
+ if (found) {
1050
+ found.name = rootTypeName;
1051
+ found.body = found.body.replace(`export interface ${rootType}`, `export interface ${rootTypeName}`);
1052
+ }
1053
+ return interfaces.map((i) => i.body).join("\n\n");
1054
+ } else if (Array.isArray(parsed)) {
1055
+ const itemType = resolveType(parsed, rootTypeName);
1056
+ return `${interfaces.map((i) => i.body).join("\n\n")}
1057
+
1058
+ export type ${rootTypeName} = ${itemType};`.trim();
1059
+ } else {
1060
+ const primitiveType = resolveType(parsed, rootTypeName);
1061
+ return `export type ${rootTypeName} = ${primitiveType};`;
1062
+ }
1063
+ }
1064
+ function jsonToZod(jsonInput, rootName = "rootSchema") {
1065
+ let parsed;
1066
+ try {
1067
+ parsed = JSON.parse(jsonInput);
1068
+ } catch (err) {
1069
+ throw new Error(`Invalid JSON: ${err instanceof Error ? err.message : String(err)}`);
1070
+ }
1071
+ const schemas = [];
1072
+ const createdNames = /* @__PURE__ */ new Set();
1073
+ function getUniqueName(base) {
1074
+ let name = base.endsWith("Schema") ? base : `${base}Schema`;
1075
+ let counter = 1;
1076
+ while (createdNames.has(name)) {
1077
+ counter += 1;
1078
+ name = `${base}${counter}Schema`;
1079
+ }
1080
+ createdNames.add(name);
1081
+ return name;
1082
+ }
1083
+ function resolveZod(val, keyHint) {
1084
+ if (val === null) return "z.null()";
1085
+ if (val === void 0) return "z.undefined()";
1086
+ if (typeof val === "string") return "z.string()";
1087
+ if (typeof val === "number") return Number.isInteger(val) ? "z.number().int()" : "z.number()";
1088
+ if (typeof val === "boolean") return "z.boolean()";
1089
+ if (Array.isArray(val)) {
1090
+ if (val.length === 0) return "z.array(z.unknown())";
1091
+ const sampleObjects = [];
1092
+ const itemSchemas = /* @__PURE__ */ new Set();
1093
+ for (const item of val) {
1094
+ if (item && typeof item === "object" && !Array.isArray(item)) {
1095
+ sampleObjects.push(item);
1096
+ } else {
1097
+ itemSchemas.add(resolveZod(item, `${keyHint}Item`));
1098
+ }
1099
+ }
1100
+ if (sampleObjects.length > 0) {
1101
+ const merged = {};
1102
+ for (const obj of sampleObjects) {
1103
+ for (const [k, v] of Object.entries(obj)) {
1104
+ if (!merged[k]) merged[k] = { schemas: /* @__PURE__ */ new Set(), count: 0 };
1105
+ merged[k].count += 1;
1106
+ merged[k].schemas.add(resolveZod(v, k));
1107
+ }
1108
+ }
1109
+ const lines = [];
1110
+ for (const [k, meta] of Object.entries(merged)) {
1111
+ const isOptional = meta.count < sampleObjects.length;
1112
+ let schemaStr = Array.from(meta.schemas)[0] || "z.unknown()";
1113
+ if (meta.schemas.size > 1) {
1114
+ schemaStr = `z.union([${Array.from(meta.schemas).join(", ")}])`;
1115
+ }
1116
+ if (isOptional) {
1117
+ schemaStr += ".optional()";
1118
+ }
1119
+ lines.push(` ${formatKey(k)}: ${schemaStr},`);
1120
+ }
1121
+ const schemaName = getUniqueName(`${keyHint}Item`);
1122
+ schemas.unshift({
1123
+ name: schemaName,
1124
+ body: `export const ${schemaName} = z.object({
1125
+ ${lines.join("\n")}
1126
+ });`
1127
+ });
1128
+ itemSchemas.add(schemaName);
1129
+ }
1130
+ const union = Array.from(itemSchemas);
1131
+ if (union.length === 1) return `z.array(${union[0]})`;
1132
+ return `z.array(z.union([${union.join(", ")}]))`;
1133
+ }
1134
+ if (typeof val === "object") {
1135
+ const obj = val;
1136
+ const lines = [];
1137
+ for (const [k, v] of Object.entries(obj)) {
1138
+ lines.push(` ${formatKey(k)}: ${resolveZod(v, k)},`);
1139
+ }
1140
+ const schemaName = getUniqueName(keyHint);
1141
+ schemas.unshift({
1142
+ name: schemaName,
1143
+ body: `export const ${schemaName} = z.object({
1144
+ ${lines.join("\n")}
1145
+ });`
1146
+ });
1147
+ return schemaName;
1148
+ }
1149
+ return "z.unknown()";
1150
+ }
1151
+ const safeRootName = rootName.endsWith("Schema") ? rootName : `${rootName}Schema`;
1152
+ const typeName = toPascalCase(rootName.replace(/Schema$/i, "")) || "Root";
1153
+ const rootResult = resolveZod(parsed, safeRootName);
1154
+ const found = schemas.find((s) => s.name === rootResult);
1155
+ if (found) {
1156
+ found.name = safeRootName;
1157
+ found.body = found.body.replace(`export const ${rootResult}`, `export const ${safeRootName}`);
1158
+ }
1159
+ const header = `import { z } from "zod";
1160
+
1161
+ `;
1162
+ const schemaDeclarations = schemas.map((s) => s.body).join("\n\n");
1163
+ const typeExport = `
1164
+
1165
+ export type ${typeName} = z.infer<typeof ${safeRootName}>;`;
1166
+ return header + (schemaDeclarations ? `${schemaDeclarations}${typeExport}` : `export const ${safeRootName} = ${rootResult};${typeExport}`);
1167
+ }
1168
+
1169
+ // mcp/server.ts
1170
+ function createMcpServer(cliKey) {
1171
+ const license = resolveLicense(cliKey);
1172
+ const server = new Server(
1173
+ {
1174
+ name: "codestation-mcp",
1175
+ version: "1.0.0"
1176
+ },
1177
+ {
1178
+ capabilities: {
1179
+ tools: {}
1180
+ }
1181
+ }
1182
+ );
1183
+ const tools = [
1184
+ // ----------------- FREE TOOLS -----------------
1185
+ {
1186
+ name: "codestation_uuid",
1187
+ description: "Generate cryptographically secure v4 UUIDs. [Free Tier]",
1188
+ inputSchema: {
1189
+ type: "object",
1190
+ properties: {
1191
+ count: {
1192
+ type: "integer",
1193
+ description: "Number of UUIDs to generate (1 to 50, default: 1)",
1194
+ minimum: 1,
1195
+ maximum: 50
1196
+ }
1197
+ }
1198
+ }
1199
+ },
1200
+ {
1201
+ name: "codestation_base64",
1202
+ description: "Encode or decode Base64 and URL-safe Base64 strings. [Free Tier]",
1203
+ inputSchema: {
1204
+ type: "object",
1205
+ properties: {
1206
+ text: { type: "string", description: "The string to encode or decode" },
1207
+ action: {
1208
+ type: "string",
1209
+ enum: ["encode", "decode"],
1210
+ description: "Whether to encode or decode"
1211
+ },
1212
+ urlSafe: {
1213
+ type: "boolean",
1214
+ description: "Whether to use URL-safe Base64 (default: false)"
1215
+ }
1216
+ },
1217
+ required: ["text", "action"]
1218
+ }
1219
+ },
1220
+ {
1221
+ name: "codestation_url_codec",
1222
+ description: "URL encode or decode string components. [Free Tier]",
1223
+ inputSchema: {
1224
+ type: "object",
1225
+ properties: {
1226
+ text: { type: "string", description: "Text to URL-encode or URL-decode" },
1227
+ action: {
1228
+ type: "string",
1229
+ enum: ["encode", "decode"],
1230
+ description: "Action to perform"
1231
+ }
1232
+ },
1233
+ required: ["text", "action"]
1234
+ }
1235
+ },
1236
+ {
1237
+ name: "codestation_hex_codec",
1238
+ description: "Encode UTF-8 string to hexadecimal byte pairs or decode hex to text. [Free Tier]",
1239
+ inputSchema: {
1240
+ type: "object",
1241
+ properties: {
1242
+ text: { type: "string", description: "Text or hex string" },
1243
+ action: {
1244
+ type: "string",
1245
+ enum: ["encode", "decode"],
1246
+ description: "Action to perform"
1247
+ }
1248
+ },
1249
+ required: ["text", "action"]
1250
+ }
1251
+ },
1252
+ {
1253
+ name: "codestation_format_json",
1254
+ description: "Prettify, format, and validate a JSON string. [Free Tier]",
1255
+ inputSchema: {
1256
+ type: "object",
1257
+ properties: {
1258
+ json: { type: "string", description: "Raw JSON string to format" },
1259
+ indent: {
1260
+ type: "integer",
1261
+ description: "Number of spaces for indentation (0-8, default: 2)",
1262
+ minimum: 0,
1263
+ maximum: 8
1264
+ }
1265
+ },
1266
+ required: ["json"]
1267
+ }
1268
+ },
1269
+ {
1270
+ name: "codestation_minify_json",
1271
+ description: "Minify JSON by stripping all whitespace. [Free Tier]",
1272
+ inputSchema: {
1273
+ type: "object",
1274
+ properties: {
1275
+ json: { type: "string", description: "JSON string to minify" }
1276
+ },
1277
+ required: ["json"]
1278
+ }
1279
+ },
1280
+ {
1281
+ name: "codestation_json_to_yaml",
1282
+ description: "Convert JSON to clean YAML format. [Free Tier]",
1283
+ inputSchema: {
1284
+ type: "object",
1285
+ properties: {
1286
+ json: { type: "string", description: "Valid JSON string" }
1287
+ },
1288
+ required: ["json"]
1289
+ }
1290
+ },
1291
+ {
1292
+ name: "codestation_yaml_to_json",
1293
+ description: "Convert YAML formatted text to JSON. [Free Tier]",
1294
+ inputSchema: {
1295
+ type: "object",
1296
+ properties: {
1297
+ yaml: { type: "string", description: "YAML text string" }
1298
+ },
1299
+ required: ["yaml"]
1300
+ }
1301
+ },
1302
+ {
1303
+ name: "codestation_case_convert",
1304
+ description: "Convert text into different naming conventions (camelCase, snake_case, kebab-case, PascalCase, CONSTANT_CASE, etc.). [Free Tier]",
1305
+ inputSchema: {
1306
+ type: "object",
1307
+ properties: {
1308
+ text: { type: "string", description: "The string or identifier to convert" },
1309
+ targetCase: {
1310
+ type: "string",
1311
+ enum: ["camel", "pascal", "snake", "kebab", "constant", "title", "sentence", "upper", "lower"],
1312
+ description: "Target casing style"
1313
+ }
1314
+ },
1315
+ required: ["text", "targetCase"]
1316
+ }
1317
+ },
1318
+ {
1319
+ name: "codestation_text_diff",
1320
+ description: "Generate a clean line-by-line unified diff between original and modified text. [Free Tier]",
1321
+ inputSchema: {
1322
+ type: "object",
1323
+ properties: {
1324
+ original: { type: "string", description: "The original text content" },
1325
+ modified: { type: "string", description: "The updated text content" }
1326
+ },
1327
+ required: ["original", "modified"]
1328
+ }
1329
+ },
1330
+ {
1331
+ name: "codestation_slugify",
1332
+ description: "Convert strings to clean, SEO-friendly URL slugs. [Free Tier]",
1333
+ inputSchema: {
1334
+ type: "object",
1335
+ properties: {
1336
+ text: { type: "string", description: "Text to slugify" },
1337
+ separator: { type: "string", description: "Separator character (default: '-')" }
1338
+ },
1339
+ required: ["text"]
1340
+ }
1341
+ },
1342
+ // ----------------- PRO TOOLS (₹199 / $2.99) -----------------
1343
+ {
1344
+ name: "codestation_hash",
1345
+ description: "Generate cryptographic hashes (SHA-256, SHA-512, MD5, SHA-1, CRC-32). [Pro Tier: \u20B9199/mo or $2.99/mo]",
1346
+ inputSchema: {
1347
+ type: "object",
1348
+ properties: {
1349
+ text: { type: "string", description: "Text to hash" },
1350
+ algorithm: {
1351
+ type: "string",
1352
+ enum: ["SHA-256", "SHA-384", "SHA-512", "MD5", "SHA-1", "CRC32"],
1353
+ description: "Hash algorithm to apply (default: SHA-256)"
1354
+ }
1355
+ },
1356
+ required: ["text"]
1357
+ }
1358
+ },
1359
+ {
1360
+ name: "codestation_hmac",
1361
+ description: "Compute HMAC signatures using Web Crypto. [Pro Tier: \u20B9199/mo or $2.99/mo]",
1362
+ inputSchema: {
1363
+ type: "object",
1364
+ properties: {
1365
+ text: { type: "string", description: "Input message string" },
1366
+ secret: { type: "string", description: "Secret key" },
1367
+ algorithm: {
1368
+ type: "string",
1369
+ enum: ["SHA-256", "SHA-512"],
1370
+ description: "HMAC algorithm (default: SHA-256)"
1371
+ }
1372
+ },
1373
+ required: ["text", "secret"]
1374
+ }
1375
+ },
1376
+ {
1377
+ name: "codestation_jwt_decode",
1378
+ description: "Inspect & decode JSON Web Token (JWT) header, payload claims, and signature in local memory without transmitting secrets. [Pro Tier: \u20B9199/mo or $2.99/mo]",
1379
+ inputSchema: {
1380
+ type: "object",
1381
+ properties: {
1382
+ token: { type: "string", description: "Full JWT string (header.payload.signature)" }
1383
+ },
1384
+ required: ["token"]
1385
+ }
1386
+ },
1387
+ {
1388
+ name: "codestation_format_sql",
1389
+ description: "Format, beautify, and indent SQL queries across PostgreSQL, MySQL, SQLite, and standard SQL. [Pro Tier: \u20B9199/mo or $2.99/mo]",
1390
+ inputSchema: {
1391
+ type: "object",
1392
+ properties: {
1393
+ sql: { type: "string", description: "Raw SQL query to format" },
1394
+ dialect: {
1395
+ type: "string",
1396
+ enum: ["PostgreSQL", "MySQL", "SQLite", "SQL Server"],
1397
+ description: "SQL dialect (default: PostgreSQL)"
1398
+ }
1399
+ },
1400
+ required: ["sql"]
1401
+ }
1402
+ },
1403
+ {
1404
+ name: "codestation_cron_explain",
1405
+ description: "Parse and explain 5-field Unix cron expressions in clear plain English. [Pro Tier: \u20B9199/mo or $2.99/mo]",
1406
+ inputSchema: {
1407
+ type: "object",
1408
+ properties: {
1409
+ expression: {
1410
+ type: "string",
1411
+ description: "5-field cron expression, e.g. '*/15 9-17 * * 1-5'"
1412
+ }
1413
+ },
1414
+ required: ["expression"]
1415
+ }
1416
+ },
1417
+ {
1418
+ name: "codestation_timezone_convert",
1419
+ description: "Accurately convert a date/time string from one IANA timezone to another using runtime IANA rules. [Pro Tier: \u20B9199/mo or $2.99/mo]",
1420
+ inputSchema: {
1421
+ type: "object",
1422
+ properties: {
1423
+ dateTime: {
1424
+ type: "string",
1425
+ description: "ISO date-time string, e.g. '2026-10-09T14:30:00'"
1426
+ },
1427
+ sourceTimeZone: {
1428
+ type: "string",
1429
+ description: "Source IANA timezone (e.g. 'America/New_York', 'Asia/Kolkata', 'UTC')"
1430
+ },
1431
+ targetTimeZone: {
1432
+ type: "string",
1433
+ description: "Target IANA timezone (e.g. 'Asia/Kolkata', 'Europe/London', 'UTC')"
1434
+ }
1435
+ },
1436
+ required: ["dateTime", "sourceTimeZone", "targetTimeZone"]
1437
+ }
1438
+ },
1439
+ {
1440
+ name: "codestation_business_days",
1441
+ description: "Calculate exact working/business days between two dates, excluding weekends. [Pro Tier: \u20B9199/mo or $2.99/mo]",
1442
+ inputSchema: {
1443
+ type: "object",
1444
+ properties: {
1445
+ startDate: { type: "string", description: "Start date (YYYY-MM-DD)" },
1446
+ endDate: { type: "string", description: "End date (YYYY-MM-DD)" }
1447
+ },
1448
+ required: ["startDate", "endDate"]
1449
+ }
1450
+ },
1451
+ {
1452
+ name: "codestation_regex_test",
1453
+ description: "Test regular expressions against target text and return structured match groups and indices. [Pro Tier: \u20B9199/mo or $2.99/mo]",
1454
+ inputSchema: {
1455
+ type: "object",
1456
+ properties: {
1457
+ pattern: { type: "string", description: "Regex pattern (without bounding slashes)" },
1458
+ text: { type: "string", description: "Text to search within" },
1459
+ flags: {
1460
+ type: "string",
1461
+ description: "Regex flags (e.g. 'g', 'i', 'm', default: 'g')"
1462
+ }
1463
+ },
1464
+ required: ["pattern", "text"]
1465
+ }
1466
+ },
1467
+ {
1468
+ name: "codestation_json_schema",
1469
+ description: "Infer a Draft 2020-12 JSON Schema structure from sample JSON data. [Pro Tier: \u20B9199/mo or $2.99/mo]",
1470
+ inputSchema: {
1471
+ type: "object",
1472
+ properties: {
1473
+ json: { type: "string", description: "Sample JSON string" }
1474
+ },
1475
+ required: ["json"]
1476
+ }
1477
+ },
1478
+ {
1479
+ name: "codestation_json_to_typescript",
1480
+ description: "Generate clean TypeScript interfaces and types from sample JSON data. [Pro Tier: \u20B9199/mo or $2.99/mo]",
1481
+ inputSchema: {
1482
+ type: "object",
1483
+ properties: {
1484
+ json: { type: "string", description: "Sample JSON string or object representation" },
1485
+ rootName: { type: "string", description: "Name for the root interface (default: 'Root')" }
1486
+ },
1487
+ required: ["json"]
1488
+ }
1489
+ },
1490
+ {
1491
+ name: "codestation_json_to_zod",
1492
+ description: "Generate production-ready Zod validation schema and inferred types from sample JSON data. [Pro Tier: \u20B9199/mo or $2.99/mo]",
1493
+ inputSchema: {
1494
+ type: "object",
1495
+ properties: {
1496
+ json: { type: "string", description: "Sample JSON string or object representation" },
1497
+ rootName: { type: "string", description: "Name for the root schema (default: 'rootSchema')" }
1498
+ },
1499
+ required: ["json"]
1500
+ }
1501
+ }
1502
+ ];
1503
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
1504
+ return { tools };
1505
+ });
1506
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
1507
+ const { name, arguments: args = {} } = request.params;
1508
+ if (PRO_TOOLS.has(name) && !license.isPro) {
1509
+ return {
1510
+ content: [
1511
+ {
1512
+ type: "text",
1513
+ text: getProUpgradeNotice(name)
1514
+ }
1515
+ ],
1516
+ isError: true
1517
+ };
1518
+ }
1519
+ try {
1520
+ let outputText = "";
1521
+ switch (name) {
1522
+ // --- Free tools ---
1523
+ case "codestation_uuid": {
1524
+ const count = Math.min(Math.max(Number(args.count ?? 1), 1), 50);
1525
+ const uuids = Array.from({ length: count }, () => crypto.randomUUID());
1526
+ outputText = count === 1 ? uuids[0] : uuids.join("\n");
1527
+ break;
1528
+ }
1529
+ case "codestation_base64": {
1530
+ const text2 = String(args.text ?? "");
1531
+ const action = String(args.action ?? "encode");
1532
+ const urlSafe = Boolean(args.urlSafe);
1533
+ if (action === "encode") {
1534
+ if (urlSafe) {
1535
+ outputText = encodeBase64Url(text2);
1536
+ } else {
1537
+ outputText = Buffer.from(text2, "utf-8").toString("base64");
1538
+ }
1539
+ } else {
1540
+ if (urlSafe) {
1541
+ outputText = decodeBase64Url(text2);
1542
+ } else {
1543
+ outputText = Buffer.from(text2, "base64").toString("utf-8");
1544
+ }
1545
+ }
1546
+ break;
1547
+ }
1548
+ case "codestation_url_codec": {
1549
+ const text2 = String(args.text ?? "");
1550
+ const action = String(args.action ?? "encode");
1551
+ outputText = action === "encode" ? encodeUrlComponent(text2) : decodeUrlComponent(text2);
1552
+ break;
1553
+ }
1554
+ case "codestation_hex_codec": {
1555
+ const text2 = String(args.text ?? "");
1556
+ const action = String(args.action ?? "encode");
1557
+ outputText = action === "encode" ? encodeHexadecimal(text2) : decodeHexadecimal(text2);
1558
+ break;
1559
+ }
1560
+ case "codestation_format_json": {
1561
+ const json = String(args.json ?? "");
1562
+ const indent = args.indent !== void 0 ? Number(args.indent) : 2;
1563
+ outputText = formatJson(json, indent);
1564
+ break;
1565
+ }
1566
+ case "codestation_minify_json": {
1567
+ outputText = minifyJson(String(args.json ?? ""));
1568
+ break;
1569
+ }
1570
+ case "codestation_json_to_yaml": {
1571
+ outputText = jsonToYaml(String(args.json ?? ""));
1572
+ break;
1573
+ }
1574
+ case "codestation_yaml_to_json": {
1575
+ outputText = yamlToJson(String(args.yaml ?? ""));
1576
+ break;
1577
+ }
1578
+ case "codestation_case_convert": {
1579
+ const text2 = String(args.text ?? "");
1580
+ const targetCase = String(args.targetCase ?? "camel");
1581
+ outputText = convertCase(text2, targetCase);
1582
+ break;
1583
+ }
1584
+ case "codestation_text_diff": {
1585
+ outputText = diffText(String(args.original ?? ""), String(args.modified ?? ""));
1586
+ break;
1587
+ }
1588
+ case "codestation_slugify": {
1589
+ outputText = slugify(String(args.text ?? ""), String(args.separator ?? "-"));
1590
+ break;
1591
+ }
1592
+ // --- Pro tools ---
1593
+ case "codestation_hash": {
1594
+ const text2 = String(args.text ?? "");
1595
+ const algo = String(args.algorithm ?? "SHA-256").toUpperCase();
1596
+ if (algo === "MD5") outputText = md5(text2);
1597
+ else if (algo === "SHA-1") outputText = sha1(text2);
1598
+ else if (algo === "SHA-256") outputText = await sha256(text2);
1599
+ else if (algo === "SHA-384") outputText = await sha384(text2);
1600
+ else if (algo === "SHA-512") outputText = await sha512(text2);
1601
+ else if (algo === "CRC32") outputText = crc32(text2);
1602
+ else throw new Error(`Unsupported hash algorithm: ${algo}`);
1603
+ break;
1604
+ }
1605
+ case "codestation_hmac": {
1606
+ const text2 = String(args.text ?? "");
1607
+ const secret = String(args.secret ?? "");
1608
+ const algo = String(args.algorithm ?? "SHA-256").toUpperCase();
1609
+ if (algo === "SHA-512") {
1610
+ outputText = await hmacSha512(text2, secret);
1611
+ } else {
1612
+ outputText = await hmacSha256(text2, secret);
1613
+ }
1614
+ break;
1615
+ }
1616
+ case "codestation_jwt_decode": {
1617
+ outputText = decodeJwt(String(args.token ?? ""));
1618
+ break;
1619
+ }
1620
+ case "codestation_format_sql": {
1621
+ const sql = String(args.sql ?? "");
1622
+ const dialect = String(args.dialect ?? "PostgreSQL").toLowerCase();
1623
+ const { format } = await import("sql-formatter");
1624
+ const dialectMap = {
1625
+ postgresql: "postgresql",
1626
+ postgres: "postgresql",
1627
+ mysql: "mysql",
1628
+ sqlite: "sqlite",
1629
+ sqlserver: "transactsql",
1630
+ tsql: "transactsql",
1631
+ "sql server": "transactsql"
1632
+ };
1633
+ const lang = dialectMap[dialect] || "sql";
1634
+ outputText = format(sql, { language: lang, tabWidth: 2 });
1635
+ break;
1636
+ }
1637
+ case "codestation_cron_explain": {
1638
+ const parsed = parseCron(String(args.expression ?? ""));
1639
+ outputText = explainCron(parsed);
1640
+ break;
1641
+ }
1642
+ case "codestation_timezone_convert": {
1643
+ const dateTime = String(args.dateTime ?? "");
1644
+ const sourceZone = String(args.sourceTimeZone ?? "UTC");
1645
+ const targetZone = String(args.targetTimeZone ?? "UTC");
1646
+ outputText = convertBetweenTimeZones(dateTime, sourceZone, targetZone);
1647
+ break;
1648
+ }
1649
+ case "codestation_business_days": {
1650
+ const start = String(args.startDate ?? "");
1651
+ const end = String(args.endDate ?? "");
1652
+ const days = businessDaysBetween(start, end);
1653
+ outputText = `${days} business day${days === 1 ? "" : "s"}`;
1654
+ break;
1655
+ }
1656
+ case "codestation_regex_test": {
1657
+ const pattern = String(args.pattern ?? "");
1658
+ const text2 = String(args.text ?? "");
1659
+ const flags = String(args.flags ?? "g");
1660
+ outputText = testRegex(pattern, flags, text2);
1661
+ break;
1662
+ }
1663
+ case "codestation_json_schema": {
1664
+ outputText = generateJsonSchema(String(args.json ?? ""));
1665
+ break;
1666
+ }
1667
+ case "codestation_json_to_typescript": {
1668
+ const json = String(args.json ?? "");
1669
+ const rootName = args.rootName ? String(args.rootName) : "Root";
1670
+ outputText = jsonToTypescript(json, rootName);
1671
+ break;
1672
+ }
1673
+ case "codestation_json_to_zod": {
1674
+ const json = String(args.json ?? "");
1675
+ const rootName = args.rootName ? String(args.rootName) : "rootSchema";
1676
+ outputText = jsonToZod(json, rootName);
1677
+ break;
1678
+ }
1679
+ default:
1680
+ throw new Error(`Unknown tool: ${name}`);
1681
+ }
1682
+ return {
1683
+ content: [{ type: "text", text: outputText }]
1684
+ };
1685
+ } catch (err) {
1686
+ const message = err instanceof Error ? err.message : String(err);
1687
+ return {
1688
+ content: [{ type: "text", text: `Error: ${message}` }],
1689
+ isError: true
1690
+ };
1691
+ }
1692
+ });
1693
+ return { server, license };
1694
+ }
1695
+
1696
+ // mcp/setup.ts
1697
+ import * as fs2 from "node:fs";
1698
+ import * as path2 from "node:path";
1699
+ import * as os2 from "node:os";
1700
+ function getClaudeDesktopConfigPath() {
1701
+ const platform = process.platform;
1702
+ if (platform === "darwin") {
1703
+ return path2.join(os2.homedir(), "Library", "Application Support", "Claude", "claude_desktop_config.json");
1704
+ } else if (platform === "win32") {
1705
+ const appData = process.env.APPDATA || path2.join(os2.homedir(), "AppData", "Roaming");
1706
+ return path2.join(appData, "Claude", "claude_desktop_config.json");
1707
+ } else {
1708
+ return path2.join(os2.homedir(), ".config", "Claude", "claude_desktop_config.json");
1709
+ }
1710
+ }
1711
+ function getCursorGlobalConfigPath() {
1712
+ return path2.join(os2.homedir(), ".cursor", "mcp.json");
1713
+ }
1714
+ function getWindsurfConfigPath() {
1715
+ return path2.join(os2.homedir(), ".codeium", "windsurf", "mcp_config.json");
1716
+ }
1717
+ function mergeMcpConfig(filePath, mcpEntry) {
1718
+ try {
1719
+ const dir = path2.dirname(filePath);
1720
+ if (!fs2.existsSync(dir)) {
1721
+ fs2.mkdirSync(dir, { recursive: true });
1722
+ }
1723
+ let config = {};
1724
+ if (fs2.existsSync(filePath)) {
1725
+ try {
1726
+ const raw = fs2.readFileSync(filePath, "utf-8");
1727
+ config = JSON.parse(raw);
1728
+ } catch {
1729
+ config = {};
1730
+ }
1731
+ }
1732
+ if (!config.mcpServers || typeof config.mcpServers !== "object") {
1733
+ config.mcpServers = {};
1734
+ }
1735
+ config.mcpServers.codestation = mcpEntry;
1736
+ fs2.writeFileSync(filePath, JSON.stringify(config, null, 2) + "\n", "utf-8");
1737
+ return { target: path2.basename(filePath), path: filePath, status: "configured" };
1738
+ } catch (err) {
1739
+ return {
1740
+ target: path2.basename(filePath),
1741
+ path: filePath,
1742
+ status: "error",
1743
+ message: err instanceof Error ? err.message : String(err)
1744
+ };
1745
+ }
1746
+ }
1747
+ async function runAutoSetup(licenseKey) {
1748
+ const cleanKey = licenseKey?.trim();
1749
+ if (cleanKey && validateLicenseKey(cleanKey)) {
1750
+ saveCachedLicense(cleanKey, true);
1751
+ }
1752
+ const mcpEntry = {
1753
+ command: "npx",
1754
+ args: cleanKey ? ["-y", "codestation-mcp", "--key", cleanKey] : ["-y", "codestation-mcp"]
1755
+ };
1756
+ const targets = [
1757
+ { name: "Claude Desktop", path: getClaudeDesktopConfigPath() },
1758
+ { name: "Cursor IDE (Global)", path: getCursorGlobalConfigPath() },
1759
+ { name: "Windsurf / Codeium", path: getWindsurfConfigPath() }
1760
+ ];
1761
+ const localCursorPath = path2.join(process.cwd(), ".cursor", "mcp.json");
1762
+ if (fs2.existsSync(path2.join(process.cwd(), ".cursor"))) {
1763
+ targets.push({ name: "Cursor IDE (Local Project)", path: localCursorPath });
1764
+ }
1765
+ const results = [];
1766
+ for (const t of targets) {
1767
+ const res = mergeMcpConfig(t.path, mcpEntry);
1768
+ res.target = t.name;
1769
+ results.push(res);
1770
+ }
1771
+ return results;
1772
+ }
1773
+
1774
+ // mcp/cli-tools.ts
1775
+ import * as fs3 from "node:fs";
1776
+
1777
+ // lib/tools/cron/next-run.ts
1778
+ var DAY2 = 864e5;
1779
+ var SIX_HOURS = 6 * 36e5;
1780
+ var pad3 = (value, width = 2) => String(value).padStart(width, "0");
1781
+ function parseCronReference(reference) {
1782
+ if (reference.length > 64) throw new Error("Reference exceeds the 64-character limit.");
1783
+ 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);
1784
+ 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.");
1785
+ const [year, month, day, hour, minute, second] = [match[1], match[2], match[3], match[4], match[5], match[6] ?? "0"].map(Number);
1786
+ if (year < 1970 || year > 2099) throw new Error("Reference years must be between 1970 and 2099.");
1787
+ const days = new Date(Date.UTC(year, month, 0)).getUTCDate();
1788
+ 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.");
1789
+ const milliseconds = Number((match[7] ?? "").padEnd(3, "0"));
1790
+ let offset = 0;
1791
+ if (match[8] !== "Z") {
1792
+ const offsetHour = Number(match[8].slice(1, 3));
1793
+ const offsetMinute = Number(match[8].slice(4, 6));
1794
+ if (offsetMinute > 59 || offsetHour > 14 || offsetHour === 14 && offsetMinute !== 0) throw new Error("Reference offset must be within \xB114:00, with valid minutes.");
1795
+ offset = (offsetHour * 60 + offsetMinute) * 6e4 * (match[8][0] === "-" ? -1 : 1);
1796
+ }
1797
+ const instant = Date.UTC(year, month - 1, day, hour, minute, second, milliseconds) - offset;
1798
+ const utcYear = new Date(instant).getUTCFullYear();
1799
+ if (utcYear < 1970 || utcYear > 2099) throw new Error("Reference instant must fall within UTC years 1970\u20132099.");
1800
+ return instant;
1801
+ }
1802
+ function zoneFormatter2(timezone) {
1803
+ if (!timezone || timezone !== timezone.trim()) throw new Error("Select a nonempty IANA timezone.");
1804
+ 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.");
1805
+ try {
1806
+ return new Intl.DateTimeFormat("en-GB-u-ca-gregory-nu-latn", {
1807
+ timeZone: timezone,
1808
+ year: "numeric",
1809
+ month: "2-digit",
1810
+ day: "2-digit",
1811
+ hour: "2-digit",
1812
+ minute: "2-digit",
1813
+ second: "2-digit",
1814
+ hourCycle: "h23"
1815
+ });
1816
+ } catch {
1817
+ throw new Error("Timezone is not a recognized IANA timezone in this runtime.");
1818
+ }
1819
+ }
1820
+ function wallTime(formatter, instant) {
1821
+ const parts = formatter.formatToParts(instant);
1822
+ const get = (name) => Number(parts.find((part) => part.type === name)?.value);
1823
+ return { year: get("year"), month: get("month"), day: get("day"), hour: get("hour"), minute: get("minute"), second: get("second") };
1824
+ }
1825
+ function offsetAt(formatter, instant) {
1826
+ const wholeSecond = Math.floor(instant / 1e3) * 1e3;
1827
+ const wall = wallTime(formatter, wholeSecond);
1828
+ return Date.UTC(wall.year, wall.month - 1, wall.day, wall.hour, wall.minute, wall.second) - wholeSecond;
1829
+ }
1830
+ function offsetIntervals(formatter, midnight) {
1831
+ const start = midnight - 2 * DAY2;
1832
+ const end = midnight + 3 * DAY2;
1833
+ const intervals = [];
1834
+ let intervalStart = start;
1835
+ let priorOffset = offsetAt(formatter, start);
1836
+ for (let probe = start + SIX_HOURS; probe <= end; probe += SIX_HOURS) {
1837
+ const nextOffset = offsetAt(formatter, probe);
1838
+ if (nextOffset !== priorOffset) {
1839
+ let low = probe - SIX_HOURS;
1840
+ let high = probe;
1841
+ while (high - low > 1e3) {
1842
+ const middle = Math.floor((low + high) / 2e3) * 1e3;
1843
+ if (offsetAt(formatter, middle) === priorOffset) low = middle;
1844
+ else high = middle;
1845
+ }
1846
+ intervals.push({ start: intervalStart, end: high, offset: priorOffset });
1847
+ intervalStart = high;
1848
+ priorOffset = nextOffset;
1849
+ }
1850
+ }
1851
+ intervals.push({ start: intervalStart, end, offset: priorOffset });
1852
+ return intervals;
1853
+ }
1854
+ function selectedSecond(cron, lower, upper) {
1855
+ if (lower >= upper || lower >= 86400) return void 0;
1856
+ lower = Math.max(0, Math.ceil(lower));
1857
+ const firstHour = Math.floor(lower / 3600);
1858
+ for (const hour of cron.hour.values) {
1859
+ if (hour < firstHour) continue;
1860
+ const firstMinute = hour === firstHour ? Math.floor(lower % 3600 / 60) : 0;
1861
+ for (const minute of cron.minute.values) {
1862
+ if (minute < firstMinute) continue;
1863
+ const base = hour * 3600 + minute * 60;
1864
+ if (base >= upper) return void 0;
1865
+ const second = cron.second.values.find((value) => base + value >= lower);
1866
+ if (second !== void 0) return base + second < upper ? base + second : void 0;
1867
+ }
1868
+ }
1869
+ return void 0;
1870
+ }
1871
+ function formatCronDuration(milliseconds) {
1872
+ if (!Number.isSafeInteger(milliseconds)) throw new Error("Duration is outside supported integer precision.");
1873
+ const sign = milliseconds < 0 ? "-" : "+";
1874
+ let remainder = Math.abs(milliseconds);
1875
+ const pieces = [];
1876
+ for (const [size, name] of [[DAY2, "day"], [36e5, "hour"], [6e4, "minute"], [1e3, "second"], [1, "millisecond"]]) {
1877
+ const count = Math.floor(remainder / size);
1878
+ remainder %= size;
1879
+ if (count) pieces.push(`${count} ${name}${count === 1 ? "" : "s"}`);
1880
+ }
1881
+ return sign + (pieces.join(", ") || "0 seconds");
1882
+ }
1883
+ function nextCronRun(expression, reference, timezone) {
1884
+ const cron = typeof expression === "string" ? parseCron(expression) : expression;
1885
+ const instant = parseCronReference(reference);
1886
+ const formatter = zoneFormatter2(timezone);
1887
+ const referenceWall = wallTime(formatter, instant);
1888
+ if (referenceWall.year < 1970 || referenceWall.year > 2099) throw new Error("Reference in the selected timezone must fall within years 1970\u20132099.");
1889
+ const referenceDay = Date.UTC(referenceWall.year, referenceWall.month - 1, referenceWall.day);
1890
+ const firstDay = Math.max(Date.UTC(1970, 0, 1), referenceDay - 2 * DAY2);
1891
+ const searchEnd = Math.min(Date.UTC(2100, 0, 1), Date.UTC(referenceWall.year + 8, referenceWall.month - 1, referenceWall.day + 1));
1892
+ const utcReference = new Date(instant);
1893
+ const eightYearLimit = Date.UTC(utcReference.getUTCFullYear() + 8, utcReference.getUTCMonth(), utcReference.getUTCDate(), utcReference.getUTCHours(), utcReference.getUTCMinutes(), utcReference.getUTCSeconds(), utcReference.getUTCMilliseconds());
1894
+ const absoluteEnd = Math.min(Date.UTC(2100, 0, 1), eightYearLimit + 1);
1895
+ let best;
1896
+ let bestOffset = 0;
1897
+ for (let midnight = firstDay; midnight < searchEnd; midnight += DAY2) {
1898
+ if (best !== void 0 && midnight - DAY2 > best) break;
1899
+ const date = new Date(midnight);
1900
+ const year = date.getUTCFullYear();
1901
+ const month = date.getUTCMonth() + 1;
1902
+ const day = date.getUTCDate();
1903
+ if (!matchesCronDate(cron, year, month, day)) continue;
1904
+ for (const interval of offsetIntervals(formatter, midnight)) {
1905
+ const lowerUtc = Math.max(interval.start, instant + 1, midnight - interval.offset, Date.UTC(1970, 0, 1));
1906
+ const upperUtc = Math.min(interval.end, midnight + DAY2 - interval.offset, absoluteEnd, best ?? Infinity);
1907
+ const second = selectedSecond(cron, (lowerUtc + interval.offset - midnight) / 1e3, (upperUtc + interval.offset - midnight) / 1e3);
1908
+ if (second === void 0) continue;
1909
+ const candidate = midnight + second * 1e3 - interval.offset;
1910
+ const actual = wallTime(formatter, candidate);
1911
+ 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;
1912
+ if (candidate > instant && (best === void 0 || candidate < best)) {
1913
+ best = candidate;
1914
+ bestOffset = interval.offset;
1915
+ }
1916
+ }
1917
+ }
1918
+ 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.");
1919
+ 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.");
1920
+ const wall = wallTime(formatter, best);
1921
+ const offsetMinutes = Math.abs(bestOffset / 6e4);
1922
+ const offset = `${bestOffset < 0 ? "-" : "+"}${pad3(Math.floor(offsetMinutes / 60))}:${pad3(offsetMinutes % 60)}`;
1923
+ const dateTime = `${pad3(wall.year, 4)}-${pad3(wall.month)}-${pad3(wall.day)}T${pad3(wall.hour)}:${pad3(wall.minute)}:${pad3(wall.second)}${offset}[${timezone}]`;
1924
+ const durationMilliseconds = best - instant;
1925
+ return { instant: best, dateTime, timezone, durationMilliseconds, duration: formatCronDuration(durationMilliseconds) };
1926
+ }
1927
+
1928
+ // mcp/cli-tools.ts
1929
+ async function readInput(arg) {
1930
+ if (arg && arg !== "-") {
1931
+ if (fs3.existsSync(arg)) {
1932
+ return fs3.readFileSync(arg, "utf-8");
1933
+ }
1934
+ return arg;
1935
+ }
1936
+ if (!process.stdin.isTTY) {
1937
+ return new Promise((resolve, reject) => {
1938
+ let data = "";
1939
+ process.stdin.setEncoding("utf-8");
1940
+ process.stdin.on("data", (chunk) => {
1941
+ data += chunk;
1942
+ });
1943
+ process.stdin.on("end", () => resolve(data.trim()));
1944
+ process.stdin.on("error", reject);
1945
+ });
1946
+ }
1947
+ return "";
1948
+ }
1949
+ async function handleCliSubcommand(command, args) {
1950
+ switch (command.toLowerCase()) {
1951
+ case "jwt": {
1952
+ const input = await readInput(args[0]);
1953
+ if (!input) {
1954
+ process.stderr.write("Usage: npx codestation-mcp jwt <jwt_token>\n");
1955
+ return true;
1956
+ }
1957
+ try {
1958
+ const decoded = JSON.parse(decodeJwt(input));
1959
+ process.stdout.write("\n=== JWT HEADER ===\n");
1960
+ process.stdout.write(JSON.stringify(decoded.header, null, 2) + "\n");
1961
+ process.stdout.write("\n=== JWT PAYLOAD ===\n");
1962
+ process.stdout.write(JSON.stringify(decoded.payload, null, 2) + "\n");
1963
+ if (decoded.payload.exp) {
1964
+ const expDate = new Date(decoded.payload.exp * 1e3);
1965
+ const isExpired = Date.now() > expDate.getTime();
1966
+ process.stdout.write(
1967
+ `
1968
+ Expiry: ${expDate.toISOString()} (${isExpired ? "EXPIRED" : "Valid until " + expDate.toLocaleString()})
1969
+
1970
+ `
1971
+ );
1972
+ }
1973
+ } catch (err) {
1974
+ process.stderr.write(`[Error] ${err instanceof Error ? err.message : String(err)}
1975
+ `);
1976
+ }
1977
+ return true;
1978
+ }
1979
+ case "sql": {
1980
+ const input = await readInput(args[0]);
1981
+ if (!input) {
1982
+ process.stderr.write('Usage: npx codestation-mcp sql "<query>" [--dialect postgresql|mysql|sqlite|sqlserver]\n');
1983
+ return true;
1984
+ }
1985
+ let dialect = "postgresql";
1986
+ const dialectIdx = args.indexOf("--dialect");
1987
+ if (dialectIdx !== -1 && args[dialectIdx + 1]) {
1988
+ dialect = args[dialectIdx + 1].toLowerCase();
1989
+ }
1990
+ const dialectMap = {
1991
+ postgresql: "postgresql",
1992
+ postgres: "postgresql",
1993
+ mysql: "mysql",
1994
+ sqlite: "sqlite",
1995
+ sqlserver: "transactsql",
1996
+ tsql: "transactsql",
1997
+ "sql server": "transactsql"
1998
+ };
1999
+ const lang = dialectMap[dialect] || "sql";
2000
+ try {
2001
+ const { format } = await import("sql-formatter");
2002
+ const formatted = format(input, { language: lang, tabWidth: 2 });
2003
+ process.stdout.write(formatted + "\n");
2004
+ } catch (err) {
2005
+ process.stderr.write(`[Error] ${err instanceof Error ? err.message : String(err)}
2006
+ `);
2007
+ }
2008
+ return true;
2009
+ }
2010
+ case "cron": {
2011
+ const input = args.join(" ").replace(/--key\s+[^\s]+/g, "").trim();
2012
+ if (!input) {
2013
+ process.stderr.write('Usage: npx codestation-mcp cron "<cron_expression>"\nExample: npx codestation-mcp cron "0 9 * * 1-5"\n');
2014
+ return true;
2015
+ }
2016
+ try {
2017
+ const parsed = parseCron(input);
2018
+ const explanation = explainCron(parsed);
2019
+ const next = nextCronRun(parsed, (/* @__PURE__ */ new Date()).toISOString(), "UTC");
2020
+ process.stdout.write(`
2021
+ Expression: ${input}
2022
+ `);
2023
+ process.stdout.write(`Description: ${explanation}
2024
+ `);
2025
+ process.stdout.write(`Next run: ${next.dateTime} (${next.duration})
2026
+
2027
+ `);
2028
+ } catch (err) {
2029
+ process.stderr.write(`[Error] ${err instanceof Error ? err.message : String(err)}
2030
+ `);
2031
+ }
2032
+ return true;
2033
+ }
2034
+ case "hash": {
2035
+ const input = await readInput(args[0]);
2036
+ if (!input) {
2037
+ process.stderr.write('Usage: npx codestation-mcp hash "<string>" [--alg sha256|sha512|md5|sha1|crc32]\n');
2038
+ return true;
2039
+ }
2040
+ let alg = "sha256";
2041
+ const algIdx = args.indexOf("--alg");
2042
+ if (algIdx !== -1 && args[algIdx + 1]) {
2043
+ alg = args[algIdx + 1].toLowerCase();
2044
+ }
2045
+ let result = "";
2046
+ if (alg === "sha256") result = await sha256(input);
2047
+ else if (alg === "sha512") result = await sha512(input);
2048
+ else if (alg === "md5") result = md5(input);
2049
+ else if (alg === "sha1") result = sha1(input);
2050
+ else if (alg === "crc32") result = crc32(input);
2051
+ else result = await sha256(input);
2052
+ process.stdout.write(`${alg.toUpperCase()}: ${result}
2053
+ `);
2054
+ return true;
2055
+ }
2056
+ case "ts":
2057
+ case "types": {
2058
+ const input = await readInput(args[0]);
2059
+ if (!input) {
2060
+ process.stderr.write('Usage: npx codestation-mcp ts "<json_string_or_file>" [RootName]\n');
2061
+ return true;
2062
+ }
2063
+ const rootName = args[1] || "Root";
2064
+ try {
2065
+ const tsOutput = jsonToTypescript(input, rootName);
2066
+ process.stdout.write(tsOutput + "\n");
2067
+ } catch (err) {
2068
+ process.stderr.write(`[Error] ${err instanceof Error ? err.message : String(err)}
2069
+ `);
2070
+ }
2071
+ return true;
2072
+ }
2073
+ case "zod": {
2074
+ const input = await readInput(args[0]);
2075
+ if (!input) {
2076
+ process.stderr.write('Usage: npx codestation-mcp zod "<json_string_or_file>" [rootSchema]\n');
2077
+ return true;
2078
+ }
2079
+ const rootName = args[1] || "rootSchema";
2080
+ try {
2081
+ const zodOutput = jsonToZod(input, rootName);
2082
+ process.stdout.write(zodOutput + "\n");
2083
+ } catch (err) {
2084
+ process.stderr.write(`[Error] ${err instanceof Error ? err.message : String(err)}
2085
+ `);
2086
+ }
2087
+ return true;
2088
+ }
2089
+ case "uuid": {
2090
+ const count = parseInt(args[0], 10) || 1;
2091
+ for (let i = 0; i < count; i++) {
2092
+ process.stdout.write(crypto.randomUUID() + "\n");
2093
+ }
2094
+ return true;
2095
+ }
2096
+ case "json": {
2097
+ const input = await readInput(args[0]);
2098
+ if (!input) {
2099
+ process.stderr.write('Usage: npx codestation-mcp json "<raw_json>"\n');
2100
+ return true;
2101
+ }
2102
+ try {
2103
+ const formatted = formatJson(input, 2);
2104
+ process.stdout.write(formatted + "\n");
2105
+ } catch (err) {
2106
+ process.stderr.write(`[Error] ${err instanceof Error ? err.message : String(err)}
2107
+ `);
2108
+ }
2109
+ return true;
2110
+ }
2111
+ default:
2112
+ return false;
2113
+ }
2114
+ }
2115
+
2116
+ // mcp/cli.ts
2117
+ function printHelp() {
2118
+ process.stderr.write(`
2119
+ Code Station MCP Server & Developer CLI
2120
+ Local-first developer toolbox for AI assistants (Cursor, Claude Desktop, Windsurf) and terminal workflows.
2121
+
2122
+ Usage:
2123
+ npx codestation-mcp [command|options]
2124
+
2125
+ 1-Click AI Assistant Setup:
2126
+ npx codestation-mcp setup [--key <license_key>]
2127
+ Automatically configures Claude Desktop, Cursor IDE, and Windsurf.
2128
+
2129
+ Terminal Subcommands:
2130
+ jwt <token> Decode & inspect JWT header, payload, and expiry
2131
+ sql "<query>" [--dialect] Format SQL query (postgresql, mysql, sqlite, sqlserver)
2132
+ cron "<expression>" Explain cron schedule & project next 5 runtimes
2133
+ hash "<text>" [--alg] Compute digest (sha256, sha512, md5, sha1, crc32)
2134
+ ts "<json_string|file>" Generate clean TypeScript interfaces from JSON
2135
+ zod "<json_string|file>" Generate production-ready Zod schema from JSON
2136
+ uuid [count] Generate random RFC 4122 v4 UUIDs
2137
+ json "<raw_json>" Validate & pretty-print JSON
2138
+
2139
+ Stdio Server Options (for AI Assistants):
2140
+ --key <license_key> Activate Code Station Pro features
2141
+ --help, -h Show this help message
2142
+ --version, -v Show version information
2143
+
2144
+ Pricing:
2145
+ \u2022 Free Tier: Unlimited Base64, JSON, YAML, UUID, Text Diff, Case conversion
2146
+ \u2022 Pro Tier (India): ${PRICING.inr} (or ${PRICING.lifetimeInr})
2147
+ \u2022 Pro Tier (Global): ${PRICING.usd} (or ${PRICING.lifetimeUsd})
2148
+ \u2022 Upgrade / Account: ${PRICING.upgradeUrl}
2149
+
2150
+ `);
2151
+ }
2152
+ async function main() {
2153
+ const args = process.argv.slice(2);
2154
+ if (args.includes("--help") || args.includes("-h")) {
2155
+ printHelp();
2156
+ process.exit(0);
2157
+ }
2158
+ if (args.includes("--version") || args.includes("-v")) {
2159
+ process.stderr.write("codestation-mcp v1.1.0\n");
2160
+ process.exit(0);
2161
+ }
2162
+ if (args[0] === "setup") {
2163
+ let key;
2164
+ const keyIdx = args.indexOf("--key");
2165
+ if (keyIdx !== -1 && args[keyIdx + 1]) {
2166
+ key = args[keyIdx + 1];
2167
+ }
2168
+ process.stdout.write("\n=== Code Station 1-Click AI Setup ===\n");
2169
+ if (key) {
2170
+ process.stdout.write(`Activating with Pro Key: ${key.slice(0, 8)}...
2171
+ `);
2172
+ } else {
2173
+ process.stdout.write("Configuring in Free Tier mode (run with --key anytime to activate Pro).\n");
2174
+ }
2175
+ const results = await runAutoSetup(key);
2176
+ for (const r of results) {
2177
+ if (r.status === "configured") {
2178
+ process.stdout.write(` \u2714 ${r.target.padEnd(26)} Configured (${r.path})
2179
+ `);
2180
+ } else {
2181
+ process.stdout.write(` \u2716 ${r.target.padEnd(26)} Error: ${r.message}
2182
+ `);
2183
+ }
2184
+ }
2185
+ process.stdout.write("\n\u2728 Setup complete! Restart your editor(s) to start using Code Station tools.\n\n");
2186
+ process.exit(0);
2187
+ }
2188
+ if (args.length > 0 && !args[0].startsWith("-")) {
2189
+ const handled = await handleCliSubcommand(args[0], args.slice(1));
2190
+ if (handled) {
2191
+ process.exit(0);
2192
+ }
2193
+ }
2194
+ let cliKey;
2195
+ const keyIndex = args.indexOf("--key");
2196
+ if (keyIndex !== -1 && args[keyIndex + 1]) {
2197
+ cliKey = args[keyIndex + 1];
2198
+ }
2199
+ const { server, license } = createMcpServer(cliKey);
2200
+ if (license.isPro) {
2201
+ process.stderr.write(`[Code Station MCP] Pro Tier Active (License: ${license.licenseKey?.slice(0, 8)}...). All tools unlocked.
2202
+ `);
2203
+ } else {
2204
+ process.stderr.write(
2205
+ `[Code Station MCP] Running in Free Tier. Pro tools available at ${PRICING.inr} / ${PRICING.usd} (${PRICING.upgradeUrl})
2206
+ `
2207
+ );
2208
+ }
2209
+ const transport = new StdioServerTransport();
2210
+ await server.connect(transport);
2211
+ process.stderr.write("[Code Station MCP] Connected to stdio. Ready for tool requests.\n");
2212
+ }
2213
+ main().catch((err) => {
2214
+ process.stderr.write(`[Code Station MCP Error] ${err instanceof Error ? err.stack : String(err)}
2215
+ `);
2216
+ process.exit(1);
2217
+ });