devanvil 0.0.0-stage → 2.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.
Files changed (93) hide show
  1. package/LICENSE +21 -0
  2. package/README.ar.md +113 -0
  3. package/README.md +272 -2
  4. package/SECURITY.md +49 -0
  5. package/dist/cli.d.ts +2 -0
  6. package/dist/cli.js +659 -0
  7. package/dist/core/contract-drift.d.ts +49 -0
  8. package/dist/core/contract-drift.js +302 -0
  9. package/dist/core/converters.d.ts +18 -0
  10. package/dist/core/converters.js +981 -0
  11. package/dist/core/cron.d.ts +33 -0
  12. package/dist/core/cron.js +306 -0
  13. package/dist/core/crypto.d.ts +59 -0
  14. package/dist/core/crypto.js +250 -0
  15. package/dist/core/curl.d.ts +17 -0
  16. package/dist/core/curl.js +170 -0
  17. package/dist/core/diff.d.ts +36 -0
  18. package/dist/core/diff.js +148 -0
  19. package/dist/core/encoding.d.ts +3 -0
  20. package/dist/core/encoding.js +143 -0
  21. package/dist/core/importers.d.ts +65 -0
  22. package/dist/core/importers.js +361 -0
  23. package/dist/core/jwt.d.ts +39 -0
  24. package/dist/core/jwt.js +256 -0
  25. package/dist/core/llm-tokens.d.ts +38 -0
  26. package/dist/core/llm-tokens.js +125 -0
  27. package/dist/core/log-analyzer.d.ts +30 -0
  28. package/dist/core/log-analyzer.js +155 -0
  29. package/dist/core/network.d.ts +72 -0
  30. package/dist/core/network.js +185 -0
  31. package/dist/core/oauth-protobuf.d.ts +74 -0
  32. package/dist/core/oauth-protobuf.js +390 -0
  33. package/dist/core/openapi.d.ts +27 -0
  34. package/dist/core/openapi.js +257 -0
  35. package/dist/core/pipeline.d.ts +28 -0
  36. package/dist/core/pipeline.js +154 -0
  37. package/dist/core/regex.d.ts +50 -0
  38. package/dist/core/regex.js +351 -0
  39. package/dist/core/runner.d.ts +53 -0
  40. package/dist/core/runner.js +250 -0
  41. package/dist/core/secrets.d.ts +87 -0
  42. package/dist/core/secrets.js +599 -0
  43. package/dist/core/security.d.ts +34 -0
  44. package/dist/core/security.js +284 -0
  45. package/dist/core/sql-explain.d.ts +50 -0
  46. package/dist/core/sql-explain.js +259 -0
  47. package/dist/core/tls.d.ts +44 -0
  48. package/dist/core/tls.js +166 -0
  49. package/dist/index.d.ts +31 -0
  50. package/dist/index.js +31 -0
  51. package/dist/server/app.d.ts +31 -0
  52. package/dist/server/app.js +348 -0
  53. package/dist/server/http-proxy.d.ts +55 -0
  54. package/dist/server/http-proxy.js +364 -0
  55. package/dist/server/http-utils.d.ts +28 -0
  56. package/dist/server/http-utils.js +106 -0
  57. package/dist/server/load-tester.d.ts +53 -0
  58. package/dist/server/load-tester.js +134 -0
  59. package/dist/server/mcp.d.ts +35 -0
  60. package/dist/server/mcp.js +466 -0
  61. package/dist/server/mock-store.d.ts +38 -0
  62. package/dist/server/mock-store.js +197 -0
  63. package/dist/server/plugin-loader.d.ts +60 -0
  64. package/dist/server/plugin-loader.js +285 -0
  65. package/dist/server/recorder-store.d.ts +35 -0
  66. package/dist/server/recorder-store.js +146 -0
  67. package/dist/server/routes/network-routes.d.ts +3 -0
  68. package/dist/server/routes/network-routes.js +391 -0
  69. package/dist/server/routes/tools-routes.d.ts +3 -0
  70. package/dist/server/routes/tools-routes.js +292 -0
  71. package/dist/server/routes/workspace-routes.d.ts +3 -0
  72. package/dist/server/routes/workspace-routes.js +240 -0
  73. package/dist/server/webhook-store.d.ts +29 -0
  74. package/dist/server/webhook-store.js +90 -0
  75. package/dist/server/workspace-store.d.ts +91 -0
  76. package/dist/server/workspace-store.js +447 -0
  77. package/dist/server/ws-probe.d.ts +34 -0
  78. package/dist/server/ws-probe.js +283 -0
  79. package/dist/ui/app.js +274 -0
  80. package/dist/ui/favicon.svg +14 -0
  81. package/dist/ui/index.html +83 -0
  82. package/dist/ui/logo.png +0 -0
  83. package/dist/ui/styles.css +694 -0
  84. package/dist/ui/tools-data.js +704 -0
  85. package/dist/ui/tools-network.js +727 -0
  86. package/dist/ui/tools-ops.js +295 -0
  87. package/dist/ui/tools-pro.js +500 -0
  88. package/dist/ui/tools-security.js +389 -0
  89. package/dist/ui/tools-v12.js +745 -0
  90. package/dist/ui/tools-v13.js +321 -0
  91. package/dist/ui/tools-v20.js +563 -0
  92. package/dist/ui/tools-v21.js +395 -0
  93. package/package.json +75 -4
@@ -0,0 +1,981 @@
1
+ import { isDangerousKey, safeJsonParse, sanitizeObject } from './security.js';
2
+ // ─────────────────────────────────────────────────────────────────────────────
3
+ // YAML Parser & Serializer (Zero-dependency, supports objects, arrays, quotes,
4
+ // inline collections, comments, booleans, numbers, null, multiline | / > blocks)
5
+ // ─────────────────────────────────────────────────────────────────────────────
6
+ function parseYamlScalar(raw) {
7
+ const s = raw.trim();
8
+ if (s === '' || s === 'null' || s === '~' || s === 'Null' || s === 'NULL')
9
+ return null;
10
+ if (s === 'true' || s === 'True' || s === 'TRUE')
11
+ return true;
12
+ if (s === 'false' || s === 'False' || s === 'FALSE')
13
+ return false;
14
+ if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
15
+ if (s.startsWith('"')) {
16
+ try {
17
+ return JSON.parse(s);
18
+ }
19
+ catch {
20
+ return s.slice(1, -1);
21
+ }
22
+ }
23
+ return s.slice(1, -1).replace(/''/g, "'");
24
+ }
25
+ if ((s.startsWith('[') && s.endsWith(']')) || (s.startsWith('{') && s.endsWith('}'))) {
26
+ try {
27
+ return safeJsonParse(s);
28
+ }
29
+ catch {
30
+ if (s.startsWith('[') && s.endsWith(']')) {
31
+ const inner = s.slice(1, -1).trim();
32
+ if (!inner)
33
+ return [];
34
+ return splitTopLevel(inner, ',').map((part) => parseYamlScalar(part));
35
+ }
36
+ if (s.startsWith('{') && s.endsWith('}')) {
37
+ const inner = s.slice(1, -1).trim();
38
+ const obj = Object.create(null);
39
+ if (!inner)
40
+ return {};
41
+ for (const pair of splitTopLevel(inner, ',')) {
42
+ const colonIdx = findUnquotedChar(pair, ':');
43
+ if (colonIdx > 0) {
44
+ const k = stripQuotes(pair.slice(0, colonIdx).trim());
45
+ if (isDangerousKey(k))
46
+ continue;
47
+ const v = parseYamlScalar(pair.slice(colonIdx + 1));
48
+ obj[k] = v;
49
+ }
50
+ }
51
+ return sanitizeObject(obj);
52
+ }
53
+ }
54
+ }
55
+ if (/^[+-]?0x[0-9a-fA-F]+$/.test(s))
56
+ return parseInt(s, 16);
57
+ if (/^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(s)) {
58
+ const n = Number(s);
59
+ if (Number.isFinite(n))
60
+ return n;
61
+ }
62
+ return s;
63
+ }
64
+ function stripQuotes(s) {
65
+ if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
66
+ return s.slice(1, -1);
67
+ }
68
+ return s;
69
+ }
70
+ function stripYamlComment(line) {
71
+ let inSingle = false;
72
+ let inDouble = false;
73
+ for (let i = 0; i < line.length; i++) {
74
+ const ch = line[i];
75
+ if (ch === "'" && !inDouble)
76
+ inSingle = !inSingle;
77
+ else if (ch === '"' && !inSingle && line[i - 1] !== '\\')
78
+ inDouble = !inDouble;
79
+ else if (ch === '#' && !inSingle && !inDouble && (i === 0 || /\s/.test(line[i - 1]))) {
80
+ return line.slice(0, i).trimEnd();
81
+ }
82
+ }
83
+ return line;
84
+ }
85
+ function findUnquotedChar(str, target) {
86
+ let inSingle = false;
87
+ let inDouble = false;
88
+ let depth = 0;
89
+ for (let i = 0; i < str.length; i++) {
90
+ const ch = str[i];
91
+ if (ch === "'" && !inDouble)
92
+ inSingle = !inSingle;
93
+ else if (ch === '"' && !inSingle && str[i - 1] !== '\\')
94
+ inDouble = !inDouble;
95
+ else if (!inSingle && !inDouble) {
96
+ if (ch === '[' || ch === '{')
97
+ depth++;
98
+ else if (ch === ']' || ch === '}')
99
+ depth = Math.max(0, depth - 1);
100
+ else if (ch === target && depth === 0)
101
+ return i;
102
+ }
103
+ }
104
+ return -1;
105
+ }
106
+ function splitTopLevel(str, sep) {
107
+ const parts = [];
108
+ let current = '';
109
+ let inSingle = false;
110
+ let inDouble = false;
111
+ let depth = 0;
112
+ for (let i = 0; i < str.length; i++) {
113
+ const ch = str[i];
114
+ if (ch === "'" && !inDouble)
115
+ inSingle = !inSingle;
116
+ else if (ch === '"' && !inSingle && str[i - 1] !== '\\')
117
+ inDouble = !inDouble;
118
+ else if (!inSingle && !inDouble) {
119
+ if (ch === '[' || ch === '{')
120
+ depth++;
121
+ else if (ch === ']' || ch === '}')
122
+ depth = Math.max(0, depth - 1);
123
+ else if (ch === sep && depth === 0) {
124
+ parts.push(current.trim());
125
+ current = '';
126
+ continue;
127
+ }
128
+ }
129
+ current += ch;
130
+ }
131
+ if (current.trim().length > 0)
132
+ parts.push(current.trim());
133
+ return parts;
134
+ }
135
+ export function parseYaml(input) {
136
+ const rawLines = input.replace(/\r\n/g, '\n').split('\n');
137
+ const lines = [];
138
+ for (const raw of rawLines) {
139
+ const cleaned = stripYamlComment(raw);
140
+ const trimmed = cleaned.trim();
141
+ if (!trimmed || trimmed === '---' || trimmed === '...')
142
+ continue;
143
+ const indent = cleaned.length - cleaned.trimStart().length;
144
+ lines.push({ indent, text: trimmed, raw });
145
+ }
146
+ if (lines.length === 0)
147
+ return {};
148
+ let idx = 0;
149
+ function parseBlock(minIndent) {
150
+ if (idx >= lines.length)
151
+ return null;
152
+ const first = lines[idx];
153
+ if (first.text.startsWith('- ') || first.text === '-') {
154
+ return parseSequence(first.indent);
155
+ }
156
+ if (findUnquotedChar(first.text, ':') !== -1) {
157
+ return parseMapping(first.indent);
158
+ }
159
+ idx++;
160
+ return parseYamlScalar(first.text);
161
+ }
162
+ function parseSequence(seqIndent) {
163
+ const arr = [];
164
+ while (idx < lines.length) {
165
+ const line = lines[idx];
166
+ if (line.indent < seqIndent)
167
+ break;
168
+ if (line.indent !== seqIndent || (!line.text.startsWith('- ') && line.text !== '-'))
169
+ break;
170
+ const rest = line.text === '-' ? '' : line.text.slice(2).trim();
171
+ idx++;
172
+ if (!rest) {
173
+ if (idx < lines.length && lines[idx].indent > seqIndent) {
174
+ arr.push(parseBlock(lines[idx].indent));
175
+ }
176
+ else {
177
+ arr.push(null);
178
+ }
179
+ }
180
+ else {
181
+ const colonIdx = findUnquotedChar(rest, ':');
182
+ const isInlineMap = colonIdx > 0 && (colonIdx === rest.length - 1 || rest[colonIdx + 1] === ' ');
183
+ if (isInlineMap && !rest.startsWith('{') && !rest.startsWith('[')) {
184
+ const itemObj = Object.create(null);
185
+ const k = stripQuotes(rest.slice(0, colonIdx).trim());
186
+ const vRaw = rest.slice(colonIdx + 1).trim();
187
+ const itemIndent = seqIndent + 2;
188
+ let firstVal;
189
+ if (vRaw) {
190
+ firstVal = parseYamlScalar(vRaw);
191
+ }
192
+ else if (idx < lines.length && lines[idx].indent > itemIndent) {
193
+ firstVal = parseBlock(lines[idx].indent);
194
+ }
195
+ else {
196
+ firstVal = null;
197
+ }
198
+ if (!isDangerousKey(k))
199
+ itemObj[k] = firstVal;
200
+ // Gather sibling keys belonging to this sequence item's object
201
+ while (idx < lines.length && lines[idx].indent >= itemIndent) {
202
+ const sub = lines[idx];
203
+ if (sub.indent === seqIndent && sub.text.startsWith('-'))
204
+ break;
205
+ const subColon = findUnquotedChar(sub.text, ':');
206
+ if (subColon === -1)
207
+ break;
208
+ const subKey = stripQuotes(sub.text.slice(0, subColon).trim());
209
+ const subVal = sub.text.slice(subColon + 1).trim();
210
+ idx++;
211
+ let parsedSubVal;
212
+ if (subVal === '|' || subVal === '>') {
213
+ parsedSubVal = readMultiline(sub.indent, subVal === '>');
214
+ }
215
+ else if (subVal) {
216
+ parsedSubVal = parseYamlScalar(subVal);
217
+ }
218
+ else if (idx < lines.length && lines[idx].indent > sub.indent) {
219
+ parsedSubVal = parseBlock(lines[idx].indent);
220
+ }
221
+ else {
222
+ parsedSubVal = null;
223
+ }
224
+ if (!isDangerousKey(subKey))
225
+ itemObj[subKey] = parsedSubVal;
226
+ }
227
+ arr.push(itemObj);
228
+ }
229
+ else {
230
+ arr.push(parseYamlScalar(rest));
231
+ }
232
+ }
233
+ }
234
+ return arr;
235
+ }
236
+ function readMultiline(parentIndent, folded) {
237
+ const chunks = [];
238
+ while (idx < lines.length && lines[idx].indent > parentIndent) {
239
+ chunks.push(lines[idx].text);
240
+ idx++;
241
+ }
242
+ return chunks.join(folded ? ' ' : '\n');
243
+ }
244
+ function parseMapping(mapIndent) {
245
+ const obj = Object.create(null);
246
+ while (idx < lines.length) {
247
+ const line = lines[idx];
248
+ if (line.indent < mapIndent)
249
+ break;
250
+ if (line.indent > mapIndent)
251
+ break;
252
+ if (line.text.startsWith('- ') || line.text === '-')
253
+ break;
254
+ const colonIdx = findUnquotedChar(line.text, ':');
255
+ if (colonIdx === -1) {
256
+ throw new Error(`Invalid YAML mapping line: "${line.text}"`);
257
+ }
258
+ const key = stripQuotes(line.text.slice(0, colonIdx).trim());
259
+ const valRaw = line.text.slice(colonIdx + 1).trim();
260
+ idx++;
261
+ let parsedVal;
262
+ if (valRaw === '|' || valRaw === '>') {
263
+ parsedVal = readMultiline(mapIndent, valRaw === '>');
264
+ }
265
+ else if (valRaw !== '') {
266
+ parsedVal = parseYamlScalar(valRaw);
267
+ }
268
+ else if (idx < lines.length && lines[idx].indent > mapIndent) {
269
+ parsedVal = parseBlock(lines[idx].indent);
270
+ }
271
+ else if (idx < lines.length && lines[idx].indent === mapIndent && lines[idx].text.startsWith('-')) {
272
+ parsedVal = parseSequence(mapIndent);
273
+ }
274
+ else {
275
+ parsedVal = null;
276
+ }
277
+ if (!isDangerousKey(key)) {
278
+ obj[key] = parsedVal;
279
+ }
280
+ }
281
+ return obj;
282
+ }
283
+ return sanitizeObject(parseBlock(lines[0].indent));
284
+ }
285
+ function needsYamlQuotes(str) {
286
+ if (str === '')
287
+ return true;
288
+ if (/^(true|false|null|~|yes|no|on|off)$/i.test(str))
289
+ return true;
290
+ if (/^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(str))
291
+ return true;
292
+ if (/[:#\[\]{},&*!|>'"%@`\n\r\t]|^\s|\s$|^[-?]/.test(str))
293
+ return true;
294
+ return false;
295
+ }
296
+ export function stringifyYaml(value, indent = 0) {
297
+ const pad = ' '.repeat(indent);
298
+ if (value === null || value === undefined)
299
+ return 'null';
300
+ if (typeof value === 'boolean' || typeof value === 'number')
301
+ return String(value);
302
+ if (typeof value === 'string') {
303
+ if (value.includes('\n')) {
304
+ const blockPad = ' '.repeat(indent + 2);
305
+ return `|\n${value
306
+ .split('\n')
307
+ .map((l) => `${blockPad}${l}`)
308
+ .join('\n')}`;
309
+ }
310
+ return needsYamlQuotes(value) ? JSON.stringify(value) : value;
311
+ }
312
+ if (Array.isArray(value)) {
313
+ if (value.length === 0)
314
+ return '[]';
315
+ return value
316
+ .map((item) => {
317
+ if (item !== null && typeof item === 'object') {
318
+ const nested = stringifyYaml(item, indent + 2);
319
+ if (Array.isArray(item) && item.length === 0)
320
+ return `${pad}- []`;
321
+ if (!Array.isArray(item) && Object.keys(item).length === 0)
322
+ return `${pad}- {}`;
323
+ const nestedLines = nested.split('\n');
324
+ return `${pad}- ${nestedLines[0].trimStart()}${nestedLines.length > 1 ? '\n' + nestedLines.slice(1).join('\n') : ''}`;
325
+ }
326
+ return `${pad}- ${stringifyYaml(item, indent + 2)}`;
327
+ })
328
+ .join('\n');
329
+ }
330
+ const entries = Object.entries(value);
331
+ if (entries.length === 0)
332
+ return '{}';
333
+ return entries
334
+ .map(([k, v]) => {
335
+ const safeKey = needsYamlQuotes(k) ? JSON.stringify(k) : k;
336
+ if (v !== null && typeof v === 'object') {
337
+ if (Array.isArray(v) && v.length === 0)
338
+ return `${pad}${safeKey}: []`;
339
+ if (!Array.isArray(v) && Object.keys(v).length === 0)
340
+ return `${pad}${safeKey}: {}`;
341
+ return `${pad}${safeKey}:\n${stringifyYaml(v, indent + 2)}`;
342
+ }
343
+ return `${pad}${safeKey}: ${stringifyYaml(v, indent)}`;
344
+ })
345
+ .join('\n');
346
+ }
347
+ // ─────────────────────────────────────────────────────────────────────────────
348
+ // TOML Parser & Serializer
349
+ // ─────────────────────────────────────────────────────────────────────────────
350
+ function parseTomlValue(raw) {
351
+ const s = raw.trim();
352
+ if (s === 'true')
353
+ return true;
354
+ if (s === 'false')
355
+ return false;
356
+ if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
357
+ if (s.startsWith('"'))
358
+ return JSON.parse(s);
359
+ return s.slice(1, -1);
360
+ }
361
+ if (s.startsWith('[') && s.endsWith(']')) {
362
+ const inner = s.slice(1, -1).trim();
363
+ if (!inner)
364
+ return [];
365
+ return splitTopLevel(inner, ',').map((part) => parseTomlValue(part));
366
+ }
367
+ if (s.startsWith('{') && s.endsWith('}')) {
368
+ const inner = s.slice(1, -1).trim();
369
+ const obj = Object.create(null);
370
+ if (!inner)
371
+ return {};
372
+ for (const pair of splitTopLevel(inner, ',')) {
373
+ const eq = findUnquotedChar(pair, '=');
374
+ if (eq > 0) {
375
+ const k = stripQuotes(pair.slice(0, eq).trim());
376
+ if (!isDangerousKey(k)) {
377
+ obj[k] = parseTomlValue(pair.slice(eq + 1));
378
+ }
379
+ }
380
+ }
381
+ return sanitizeObject(obj);
382
+ }
383
+ const numCandidate = s.replace(/_/g, '');
384
+ if (/^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(numCandidate)) {
385
+ return Number(numCandidate);
386
+ }
387
+ return s;
388
+ }
389
+ export function parseToml(input) {
390
+ const root = Object.create(null);
391
+ let current = root;
392
+ let ignoreCurrentTable = false;
393
+ const lines = input.replace(/\r\n/g, '\n').split('\n');
394
+ for (const rawLine of lines) {
395
+ const line = stripYamlComment(rawLine).trim();
396
+ if (!line)
397
+ continue;
398
+ if (line.startsWith('[[') && line.endsWith(']]')) {
399
+ const pathParts = line
400
+ .slice(2, -2)
401
+ .split('.')
402
+ .map((p) => stripQuotes(p.trim()));
403
+ if (pathParts.some(isDangerousKey)) {
404
+ ignoreCurrentTable = true;
405
+ continue;
406
+ }
407
+ ignoreCurrentTable = false;
408
+ let target = root;
409
+ for (let i = 0; i < pathParts.length - 1; i++) {
410
+ const key = pathParts[i];
411
+ if (!target[key] || typeof target[key] !== 'object')
412
+ target[key] = Object.create(null);
413
+ const next = target[key];
414
+ target = Array.isArray(next) ? next[next.length - 1] : next;
415
+ }
416
+ const last = pathParts[pathParts.length - 1];
417
+ if (!Array.isArray(target[last]))
418
+ target[last] = [];
419
+ const newTable = Object.create(null);
420
+ target[last].push(newTable);
421
+ current = newTable;
422
+ continue;
423
+ }
424
+ if (line.startsWith('[') && line.endsWith(']')) {
425
+ const pathParts = line
426
+ .slice(1, -1)
427
+ .split('.')
428
+ .map((p) => stripQuotes(p.trim()));
429
+ if (pathParts.some(isDangerousKey)) {
430
+ ignoreCurrentTable = true;
431
+ continue;
432
+ }
433
+ ignoreCurrentTable = false;
434
+ let target = root;
435
+ for (const key of pathParts) {
436
+ if (!target[key] || typeof target[key] !== 'object')
437
+ target[key] = Object.create(null);
438
+ const next = target[key];
439
+ target = Array.isArray(next) ? next[next.length - 1] : next;
440
+ }
441
+ current = target;
442
+ continue;
443
+ }
444
+ if (ignoreCurrentTable)
445
+ continue;
446
+ const eqIdx = findUnquotedChar(line, '=');
447
+ if (eqIdx === -1) {
448
+ throw new Error(`Invalid TOML line: "${line}"`);
449
+ }
450
+ const keyPath = line
451
+ .slice(0, eqIdx)
452
+ .split('.')
453
+ .map((p) => stripQuotes(p.trim()));
454
+ if (keyPath.some(isDangerousKey))
455
+ continue;
456
+ const val = parseTomlValue(line.slice(eqIdx + 1));
457
+ let target = current;
458
+ for (let i = 0; i < keyPath.length - 1; i++) {
459
+ const k = keyPath[i];
460
+ if (!target[k] || typeof target[k] !== 'object')
461
+ target[k] = Object.create(null);
462
+ target = target[k];
463
+ }
464
+ target[keyPath[keyPath.length - 1]] = val;
465
+ }
466
+ return sanitizeObject(root);
467
+ }
468
+ function formatTomlScalar(v) {
469
+ if (v === null || v === undefined)
470
+ return '""';
471
+ if (typeof v === 'boolean' || typeof v === 'number')
472
+ return String(v);
473
+ if (typeof v === 'string')
474
+ return JSON.stringify(v);
475
+ if (Array.isArray(v)) {
476
+ return `[${v.map((item) => formatTomlScalar(item)).join(', ')}]`;
477
+ }
478
+ const pairs = Object.entries(v).map(([k, val]) => `${formatTomlKey(k)} = ${formatTomlScalar(val)}`);
479
+ return `{ ${pairs.join(', ')} }`;
480
+ }
481
+ function formatTomlKey(key) {
482
+ return /^[A-Za-z0-9_-]+$/.test(key) ? key : JSON.stringify(key);
483
+ }
484
+ export function stringifyToml(value, prefix = '') {
485
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
486
+ throw new Error('TOML root must be an object/table');
487
+ }
488
+ const obj = value;
489
+ const scalarLines = [];
490
+ const sectionBlocks = [];
491
+ for (const [k, v] of Object.entries(obj)) {
492
+ if (v === undefined)
493
+ continue;
494
+ const key = formatTomlKey(k);
495
+ const fullPath = prefix ? `${prefix}.${key}` : key;
496
+ if (Array.isArray(v) && v.length > 0 && v.every((item) => item && typeof item === 'object' && !Array.isArray(item))) {
497
+ for (const item of v) {
498
+ const body = stringifyToml(item, fullPath);
499
+ sectionBlocks.push(`[[${fullPath}]]\n${body}`);
500
+ }
501
+ }
502
+ else if (v !== null && typeof v === 'object' && !Array.isArray(v)) {
503
+ const body = stringifyToml(v, fullPath);
504
+ sectionBlocks.push(`[${fullPath}]\n${body}`);
505
+ }
506
+ else {
507
+ scalarLines.push(`${key} = ${formatTomlScalar(v)}`);
508
+ }
509
+ }
510
+ const out = [];
511
+ if (scalarLines.length > 0)
512
+ out.push(scalarLines.join('\n'));
513
+ if (sectionBlocks.length > 0)
514
+ out.push(sectionBlocks.join('\n\n'));
515
+ return out.join('\n\n');
516
+ }
517
+ // ─────────────────────────────────────────────────────────────────────────────
518
+ // CSV Parser & Serializer (RFC 4180)
519
+ // ─────────────────────────────────────────────────────────────────────────────
520
+ export function parseCsv(input, delimiter = ',') {
521
+ const rows = [];
522
+ let row = [];
523
+ let cell = '';
524
+ let inQuotes = false;
525
+ const text = input.replace(/\r\n/g, '\n');
526
+ for (let i = 0; i < text.length; i++) {
527
+ const ch = text[i];
528
+ if (inQuotes) {
529
+ if (ch === '"') {
530
+ if (text[i + 1] === '"') {
531
+ cell += '"';
532
+ i++;
533
+ }
534
+ else {
535
+ inQuotes = false;
536
+ }
537
+ }
538
+ else {
539
+ cell += ch;
540
+ }
541
+ }
542
+ else {
543
+ if (ch === '"') {
544
+ inQuotes = true;
545
+ }
546
+ else if (ch === delimiter) {
547
+ row.push(cell);
548
+ cell = '';
549
+ }
550
+ else if (ch === '\n') {
551
+ row.push(cell);
552
+ if (row.some((c) => c !== ''))
553
+ rows.push(row);
554
+ row = [];
555
+ cell = '';
556
+ }
557
+ else {
558
+ cell += ch;
559
+ }
560
+ }
561
+ }
562
+ row.push(cell);
563
+ if (row.some((c) => c !== ''))
564
+ rows.push(row);
565
+ if (rows.length < 2)
566
+ return [];
567
+ const headers = rows[0].map((h) => h.trim());
568
+ const records = [];
569
+ for (let r = 1; r < rows.length; r++) {
570
+ const currentRow = rows[r];
571
+ const obj = Object.create(null);
572
+ for (let c = 0; c < headers.length; c++) {
573
+ const header = headers[c] || `col_${c}`;
574
+ if (isDangerousKey(header))
575
+ continue;
576
+ const rawVal = currentRow[c] ?? '';
577
+ if (rawVal === 'true')
578
+ obj[header] = true;
579
+ else if (rawVal === 'false')
580
+ obj[header] = false;
581
+ else if (rawVal !== '' && /^[+-]?\d+(\.\d+)?$/.test(rawVal))
582
+ obj[header] = Number(rawVal);
583
+ else
584
+ obj[header] = rawVal;
585
+ }
586
+ records.push(sanitizeObject(obj));
587
+ }
588
+ return records;
589
+ }
590
+ export function stringifyCsv(value, delimiter = ',') {
591
+ const rows = Array.isArray(value) ? value : [value];
592
+ if (rows.length === 0)
593
+ return '';
594
+ const objects = rows.map((r) => r && typeof r === 'object' && !Array.isArray(r) ? r : { value: r });
595
+ const headerSet = new Set();
596
+ for (const obj of objects) {
597
+ for (const k of Object.keys(obj))
598
+ headerSet.add(k);
599
+ }
600
+ const headers = Array.from(headerSet);
601
+ const escapeCell = (val) => {
602
+ const str = val === null || val === undefined ? '' : typeof val === 'object' ? JSON.stringify(val) : String(val);
603
+ if (str.includes(delimiter) || str.includes('"') || str.includes('\n')) {
604
+ return `"${str.replace(/"/g, '""')}"`;
605
+ }
606
+ return str;
607
+ };
608
+ const lines = [headers.map(escapeCell).join(delimiter)];
609
+ for (const obj of objects) {
610
+ lines.push(headers.map((h) => escapeCell(obj[h])).join(delimiter));
611
+ }
612
+ return lines.join('\n');
613
+ }
614
+ // ─────────────────────────────────────────────────────────────────────────────
615
+ // URL Query String Parser & Serializer
616
+ // ─────────────────────────────────────────────────────────────────────────────
617
+ export function parseQueryString(input) {
618
+ const cleaned = input.trim().replace(/^[?#]/, '');
619
+ const params = new URLSearchParams(cleaned);
620
+ const out = Object.create(null);
621
+ for (const [k, v] of params.entries()) {
622
+ if (isDangerousKey(k))
623
+ continue;
624
+ if (k in out) {
625
+ const existing = out[k];
626
+ out[k] = Array.isArray(existing) ? [...existing, v] : [existing, v];
627
+ }
628
+ else {
629
+ out[k] = v;
630
+ }
631
+ }
632
+ return sanitizeObject(out);
633
+ }
634
+ export function stringifyQueryString(value) {
635
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
636
+ throw new Error('Query string serialization requires a flat JSON object');
637
+ }
638
+ const params = new URLSearchParams();
639
+ for (const [k, v] of Object.entries(value)) {
640
+ if (Array.isArray(v)) {
641
+ for (const item of v)
642
+ params.append(k, String(item ?? ''));
643
+ }
644
+ else if (v !== undefined && v !== null) {
645
+ params.append(k, typeof v === 'object' ? JSON.stringify(v) : String(v));
646
+ }
647
+ }
648
+ return params.toString();
649
+ }
650
+ // ─────────────────────────────────────────────────────────────────────────────
651
+ // JSON -> TypeScript Interface & JSON Schema Generator
652
+ // ─────────────────────────────────────────────────────────────────────────────
653
+ function toPascalCase(name) {
654
+ const cleaned = name
655
+ .replace(/[^a-zA-Z0-9]+/g, ' ')
656
+ .trim()
657
+ .split(/\s+/)
658
+ .map((w) => (w ? w[0].toUpperCase() + w.slice(1) : ''))
659
+ .join('');
660
+ return cleaned || 'RootObject';
661
+ }
662
+ export function generateTypeScriptInterfaces(value, rootName = 'Root') {
663
+ const definitions = new Map();
664
+ function inferType(val, nameHint) {
665
+ if (val === null)
666
+ return 'null';
667
+ if (typeof val === 'string')
668
+ return 'string';
669
+ if (typeof val === 'number')
670
+ return 'number';
671
+ if (typeof val === 'boolean')
672
+ return 'boolean';
673
+ if (Array.isArray(val)) {
674
+ if (val.length === 0)
675
+ return 'unknown[]';
676
+ const itemTypes = Array.from(new Set(val.map((item) => inferType(item, `${nameHint}Item`))));
677
+ return itemTypes.length === 1 ? `${itemTypes[0]}[]` : `(${itemTypes.join(' | ')})[]`;
678
+ }
679
+ if (typeof val === 'object') {
680
+ const ifaceName = toPascalCase(nameHint);
681
+ const entries = Object.entries(val);
682
+ const lines = entries.map(([k, v]) => {
683
+ const propName = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(k) ? k : JSON.stringify(k);
684
+ return ` ${propName}: ${inferType(v, k)};`;
685
+ });
686
+ definitions.set(ifaceName, `export interface ${ifaceName} {\n${lines.join('\n')}\n}`);
687
+ return ifaceName;
688
+ }
689
+ return 'unknown';
690
+ }
691
+ const rootType = inferType(value, rootName);
692
+ if (definitions.size === 0) {
693
+ return `export type ${toPascalCase(rootName)} = ${rootType};`;
694
+ }
695
+ return Array.from(definitions.values()).reverse().join('\n\n');
696
+ }
697
+ export function generateJsonSchema(value, title = 'GeneratedSchema') {
698
+ function inferSchema(val) {
699
+ if (val === null)
700
+ return { type: 'null' };
701
+ if (typeof val === 'boolean')
702
+ return { type: 'boolean' };
703
+ if (typeof val === 'number')
704
+ return { type: Number.isInteger(val) ? 'integer' : 'number' };
705
+ if (typeof val === 'string') {
706
+ const schema = { type: 'string' };
707
+ if (/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(val))
708
+ schema.format = 'email';
709
+ else if (/^https?:\/\/\S+$/.test(val))
710
+ schema.format = 'uri';
711
+ else if (/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(val))
712
+ schema.format = 'uuid';
713
+ else if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(val))
714
+ schema.format = 'date-time';
715
+ return schema;
716
+ }
717
+ if (Array.isArray(val)) {
718
+ return {
719
+ type: 'array',
720
+ items: val.length > 0 ? inferSchema(val[0]) : {},
721
+ };
722
+ }
723
+ if (typeof val === 'object') {
724
+ const entries = Object.entries(val);
725
+ const properties = {};
726
+ const required = [];
727
+ for (const [k, v] of entries) {
728
+ properties[k] = inferSchema(v);
729
+ if (v !== null && v !== undefined)
730
+ required.push(k);
731
+ }
732
+ return {
733
+ type: 'object',
734
+ properties,
735
+ required,
736
+ additionalProperties: false,
737
+ };
738
+ }
739
+ return {};
740
+ }
741
+ return {
742
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
743
+ title,
744
+ ...inferSchema(value),
745
+ };
746
+ }
747
+ // ─────────────────────────────────────────────────────────────────────────────
748
+ // Unified Data Converter
749
+ // ─────────────────────────────────────────────────────────────────────────────
750
+ export function convertData(input, from, to, options = {}) {
751
+ let data;
752
+ switch (from) {
753
+ case 'json':
754
+ data = safeJsonParse(input);
755
+ break;
756
+ case 'yaml':
757
+ data = parseYaml(input);
758
+ break;
759
+ case 'toml':
760
+ data = parseToml(input);
761
+ break;
762
+ case 'csv':
763
+ data = parseCsv(input);
764
+ break;
765
+ case 'query':
766
+ data = parseQueryString(input);
767
+ break;
768
+ default:
769
+ throw new Error(`Unsupported source format: ${String(from)}`);
770
+ }
771
+ if (options.sortKeys) {
772
+ data = sortKeysDeep(data);
773
+ }
774
+ const indent = options.minify ? 0 : (options.indent ?? 2);
775
+ switch (to) {
776
+ case 'json':
777
+ return JSON.stringify(data, null, indent);
778
+ case 'yaml':
779
+ return stringifyYaml(data);
780
+ case 'toml':
781
+ return stringifyToml(data);
782
+ case 'csv':
783
+ return stringifyCsv(data);
784
+ case 'query':
785
+ return stringifyQueryString(data);
786
+ case 'typescript':
787
+ return generateTypeScriptInterfaces(data);
788
+ case 'jsonschema':
789
+ return JSON.stringify(generateJsonSchema(data), null, 2);
790
+ default:
791
+ throw new Error(`Unsupported target format: ${String(to)}`);
792
+ }
793
+ }
794
+ function sortKeysDeep(val) {
795
+ if (Array.isArray(val))
796
+ return val.map(sortKeysDeep);
797
+ if (val && typeof val === 'object') {
798
+ const sorted = {};
799
+ for (const k of Object.keys(val).sort()) {
800
+ sorted[k] = sortKeysDeep(val[k]);
801
+ }
802
+ return sorted;
803
+ }
804
+ return val;
805
+ }
806
+ // ─────────────────────────────────────────────────────────────────────────────
807
+ // Lightweight JSONPath Evaluator ($.a.b[0], $.items[*].name, $..key)
808
+ // ─────────────────────────────────────────────────────────────────────────────
809
+ export function queryJsonPath(data, expression) {
810
+ const expr = expression.trim();
811
+ if (!expr || expr === '$')
812
+ return [data];
813
+ const normalized = expr.startsWith('$') ? expr.slice(1) : expr;
814
+ const tokens = [];
815
+ let i = 0;
816
+ while (i < normalized.length) {
817
+ if (normalized.startsWith('..', i)) {
818
+ i += 2;
819
+ let name = '';
820
+ while (i < normalized.length && !'.['.includes(normalized[i])) {
821
+ name += normalized[i];
822
+ i++;
823
+ }
824
+ if (name)
825
+ tokens.push({ type: 'recursive', value: name });
826
+ }
827
+ else if (normalized[i] === '.') {
828
+ i++;
829
+ if (normalized[i] === '*') {
830
+ tokens.push({ type: 'wildcard', value: '*' });
831
+ i++;
832
+ }
833
+ else {
834
+ let name = '';
835
+ while (i < normalized.length && !'.['.includes(normalized[i])) {
836
+ name += normalized[i];
837
+ i++;
838
+ }
839
+ if (name)
840
+ tokens.push({ type: 'prop', value: name });
841
+ }
842
+ }
843
+ else if (normalized[i] === '[') {
844
+ const end = normalized.indexOf(']', i);
845
+ if (end === -1)
846
+ throw new Error('Unclosed "[" in JSONPath expression');
847
+ const inner = normalized.slice(i + 1, end).trim();
848
+ i = end + 1;
849
+ if (inner === '*') {
850
+ tokens.push({ type: 'wildcard', value: '*' });
851
+ }
852
+ else if (/^-?\d+$/.test(inner)) {
853
+ tokens.push({ type: 'index', value: inner });
854
+ }
855
+ else {
856
+ tokens.push({ type: 'prop', value: stripQuotes(inner) });
857
+ }
858
+ }
859
+ else {
860
+ let name = '';
861
+ while (i < normalized.length && !'.['.includes(normalized[i])) {
862
+ name += normalized[i];
863
+ i++;
864
+ }
865
+ if (name)
866
+ tokens.push({ type: 'prop', value: name });
867
+ }
868
+ }
869
+ let results = [data];
870
+ for (const tok of tokens) {
871
+ const next = [];
872
+ for (const item of results) {
873
+ if (item === null || typeof item !== 'object')
874
+ continue;
875
+ if (tok.type === 'prop') {
876
+ if (!Array.isArray(item) &&
877
+ !isDangerousKey(tok.value) &&
878
+ Object.prototype.hasOwnProperty.call(item, tok.value)) {
879
+ next.push(item[tok.value]);
880
+ }
881
+ }
882
+ else if (tok.type === 'index') {
883
+ if (Array.isArray(item)) {
884
+ const idx = Number(tok.value);
885
+ const resolved = idx < 0 ? item.length + idx : idx;
886
+ if (resolved >= 0 && resolved < item.length)
887
+ next.push(item[resolved]);
888
+ }
889
+ }
890
+ else if (tok.type === 'wildcard') {
891
+ if (Array.isArray(item))
892
+ next.push(...item);
893
+ else
894
+ next.push(...Object.values(item));
895
+ }
896
+ else if (tok.type === 'recursive') {
897
+ collectRecursive(item, tok.value, next);
898
+ }
899
+ }
900
+ results = next;
901
+ }
902
+ return results;
903
+ }
904
+ function collectRecursive(node, key, acc) {
905
+ if (!node || typeof node !== 'object' || isDangerousKey(key))
906
+ return;
907
+ if (Array.isArray(node)) {
908
+ for (const el of node)
909
+ collectRecursive(el, key, acc);
910
+ return;
911
+ }
912
+ const obj = node;
913
+ if (Object.prototype.hasOwnProperty.call(obj, key))
914
+ acc.push(obj[key]);
915
+ for (const val of Object.values(obj)) {
916
+ collectRecursive(val, key, acc);
917
+ }
918
+ }
919
+ // ─────────────────────────────────────────────────────────────────────────────
920
+ // SQL Formatter (Preserves strings/comments, formats major clauses cleanly)
921
+ // ─────────────────────────────────────────────────────────────────────────────
922
+ const SQL_CLAUSE_BREAKS = [
923
+ 'LEFT OUTER JOIN',
924
+ 'RIGHT OUTER JOIN',
925
+ 'FULL OUTER JOIN',
926
+ 'INNER JOIN',
927
+ 'LEFT JOIN',
928
+ 'RIGHT JOIN',
929
+ 'CROSS JOIN',
930
+ 'ORDER BY',
931
+ 'GROUP BY',
932
+ 'INSERT INTO',
933
+ 'DELETE FROM',
934
+ 'UNION ALL',
935
+ 'SELECT',
936
+ 'FROM',
937
+ 'WHERE',
938
+ 'HAVING',
939
+ 'LIMIT',
940
+ 'OFFSET',
941
+ 'VALUES',
942
+ 'UPDATE',
943
+ 'SET',
944
+ 'JOIN',
945
+ 'UNION',
946
+ 'RETURNING',
947
+ ];
948
+ const SQL_KEYWORDS = new Set([
949
+ 'SELECT', 'FROM', 'WHERE', 'AND', 'OR', 'NOT', 'IN', 'IS', 'NULL', 'AS', 'ON',
950
+ 'JOIN', 'INNER', 'LEFT', 'RIGHT', 'FULL', 'OUTER', 'CROSS', 'GROUP', 'BY',
951
+ 'ORDER', 'ASC', 'DESC', 'HAVING', 'LIMIT', 'OFFSET', 'DISTINCT', 'UNION',
952
+ 'ALL', 'INSERT', 'INTO', 'VALUES', 'UPDATE', 'SET', 'DELETE', 'CREATE',
953
+ 'TABLE', 'INDEX', 'DROP', 'ALTER', 'ADD', 'PRIMARY', 'KEY', 'FOREIGN',
954
+ 'REFERENCES', 'CASE', 'WHEN', 'THEN', 'ELSE', 'END', 'COUNT', 'SUM', 'AVG',
955
+ 'MIN', 'MAX', 'COALESCE', 'LIKE', 'ILIKE', 'BETWEEN', 'EXISTS', 'RETURNING',
956
+ 'WITH', 'TRUE', 'FALSE',
957
+ ]);
958
+ export function formatSql(sql) {
959
+ // Mask single-quoted and double-quoted literals so formatting never mutates data
960
+ const placeholders = [];
961
+ const masked = sql.replace(/'(?:''|[^'])*'|"(?:""|[^"])*"/g, (match) => {
962
+ const id = `__SQL_STR_${placeholders.length}__`;
963
+ placeholders.push(match);
964
+ return id;
965
+ });
966
+ let normalized = masked.replace(/\s+/g, ' ').trim();
967
+ // Uppercase SQL keywords
968
+ normalized = normalized.replace(/\b[A-Za-z_]+\b/g, (word) => {
969
+ const up = word.toUpperCase();
970
+ return SQL_KEYWORDS.has(up) ? up : word;
971
+ });
972
+ for (const clause of SQL_CLAUSE_BREAKS) {
973
+ const re = new RegExp(`\\s+${clause.replace(/\s+/g, '\\s+')}\\b`, 'g');
974
+ normalized = normalized.replace(re, `\n${clause}`);
975
+ }
976
+ normalized = normalized
977
+ .replace(/\s+(AND|OR)\b/g, '\n $1')
978
+ .replace(/,\s*/g, ',\n ');
979
+ // Restore literals
980
+ return normalized.replace(/__SQL_STR_(\d+)__/g, (_, i) => placeholders[Number(i)] ?? '');
981
+ }