devanvil 0.0.0-stage → 2.1.1

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