@utilix-tech/sdk 0.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 (106) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +199 -0
  3. package/dist/api-8aZtWhSj.d.cts +308 -0
  4. package/dist/api-8aZtWhSj.d.ts +308 -0
  5. package/dist/chunk-2CJSLYWI.js +520 -0
  6. package/dist/chunk-3BAHSW4C.js +1385 -0
  7. package/dist/chunk-6YPV2AB5.js +1246 -0
  8. package/dist/chunk-BPVAB4P2.js +1126 -0
  9. package/dist/chunk-FL53T24A.js +257 -0
  10. package/dist/chunk-L6KCTHUW.js +1086 -0
  11. package/dist/chunk-MLKGABMK.js +7 -0
  12. package/dist/chunk-ROTPLW7T.js +265 -0
  13. package/dist/chunk-TSAGO3XP.js +1253 -0
  14. package/dist/chunk-UC656APA.js +1080 -0
  15. package/dist/chunk-W4UBLYFU.js +1219 -0
  16. package/dist/chunk-XST6X3HT.js +896 -0
  17. package/dist/chunk-XXYZLLHI.js +2227 -0
  18. package/dist/chunk-ZKL2VX2G.js +2215 -0
  19. package/dist/chunk-ZPQZEIXP.js +685 -0
  20. package/dist/code-QNrdLIR3.d.cts +327 -0
  21. package/dist/code-QNrdLIR3.d.ts +327 -0
  22. package/dist/color-tPwZCr9H.d.cts +229 -0
  23. package/dist/color-tPwZCr9H.d.ts +229 -0
  24. package/dist/css-Cf7AMGM-.d.cts +318 -0
  25. package/dist/css-Cf7AMGM-.d.ts +318 -0
  26. package/dist/data-rMjWNiOJ.d.cts +215 -0
  27. package/dist/data-rMjWNiOJ.d.ts +215 -0
  28. package/dist/encoding-7gmq-vkV.d.cts +108 -0
  29. package/dist/encoding-7gmq-vkV.d.ts +108 -0
  30. package/dist/generators-BGtRGpJZ.d.cts +118 -0
  31. package/dist/generators-BGtRGpJZ.d.ts +118 -0
  32. package/dist/hashing-CnetQFD_.d.cts +76 -0
  33. package/dist/hashing-CnetQFD_.d.ts +76 -0
  34. package/dist/index.cjs +15466 -0
  35. package/dist/index.d.cts +18 -0
  36. package/dist/index.d.ts +18 -0
  37. package/dist/index.js +20 -0
  38. package/dist/json-BjSoIS1h.d.cts +198 -0
  39. package/dist/json-BjSoIS1h.d.ts +198 -0
  40. package/dist/misc-DcVBManm.d.cts +201 -0
  41. package/dist/misc-DcVBManm.d.ts +201 -0
  42. package/dist/network-CNtmrDeN.d.cts +170 -0
  43. package/dist/network-CNtmrDeN.d.ts +170 -0
  44. package/dist/text-DqAjPtQ0.d.cts +319 -0
  45. package/dist/text-DqAjPtQ0.d.ts +319 -0
  46. package/dist/time-DbT8fjaF.d.cts +145 -0
  47. package/dist/time-DbT8fjaF.d.ts +145 -0
  48. package/dist/tools/api.cjs +1216 -0
  49. package/dist/tools/api.d.cts +1 -0
  50. package/dist/tools/api.d.ts +1 -0
  51. package/dist/tools/api.js +2 -0
  52. package/dist/tools/code.cjs +2212 -0
  53. package/dist/tools/code.d.cts +1 -0
  54. package/dist/tools/code.d.ts +1 -0
  55. package/dist/tools/code.js +2 -0
  56. package/dist/tools/color.cjs +1122 -0
  57. package/dist/tools/color.d.cts +1 -0
  58. package/dist/tools/color.d.ts +1 -0
  59. package/dist/tools/color.js +2 -0
  60. package/dist/tools/css.cjs +1242 -0
  61. package/dist/tools/css.d.cts +1 -0
  62. package/dist/tools/css.d.ts +1 -0
  63. package/dist/tools/css.js +2 -0
  64. package/dist/tools/data.cjs +1097 -0
  65. package/dist/tools/data.d.cts +1 -0
  66. package/dist/tools/data.d.ts +1 -0
  67. package/dist/tools/data.js +2 -0
  68. package/dist/tools/encoding.cjs +261 -0
  69. package/dist/tools/encoding.d.cts +1 -0
  70. package/dist/tools/encoding.d.ts +1 -0
  71. package/dist/tools/encoding.js +2 -0
  72. package/dist/tools/generators.cjs +521 -0
  73. package/dist/tools/generators.d.cts +1 -0
  74. package/dist/tools/generators.d.ts +1 -0
  75. package/dist/tools/generators.js +2 -0
  76. package/dist/tools/hashing.cjs +259 -0
  77. package/dist/tools/hashing.d.cts +1 -0
  78. package/dist/tools/hashing.d.ts +1 -0
  79. package/dist/tools/hashing.js +2 -0
  80. package/dist/tools/json.cjs +1270 -0
  81. package/dist/tools/json.d.cts +1 -0
  82. package/dist/tools/json.d.ts +1 -0
  83. package/dist/tools/json.js +2 -0
  84. package/dist/tools/misc.cjs +1082 -0
  85. package/dist/tools/misc.d.cts +1 -0
  86. package/dist/tools/misc.d.ts +1 -0
  87. package/dist/tools/misc.js +2 -0
  88. package/dist/tools/network.cjs +1381 -0
  89. package/dist/tools/network.d.cts +1 -0
  90. package/dist/tools/network.d.ts +1 -0
  91. package/dist/tools/network.js +2 -0
  92. package/dist/tools/text.cjs +2224 -0
  93. package/dist/tools/text.d.cts +1 -0
  94. package/dist/tools/text.d.ts +1 -0
  95. package/dist/tools/text.js +2 -0
  96. package/dist/tools/time.cjs +681 -0
  97. package/dist/tools/time.d.cts +1 -0
  98. package/dist/tools/time.d.ts +1 -0
  99. package/dist/tools/time.js +2 -0
  100. package/dist/tools/units.cjs +892 -0
  101. package/dist/tools/units.d.cts +1 -0
  102. package/dist/tools/units.d.ts +1 -0
  103. package/dist/tools/units.js +2 -0
  104. package/dist/units-6lwDYBvX.d.cts +302 -0
  105. package/dist/units-6lwDYBvX.d.ts +302 -0
  106. package/package.json +148 -0
@@ -0,0 +1,1270 @@
1
+ 'use strict';
2
+
3
+ var yaml = require('js-yaml');
4
+
5
+ function _interopNamespace(e) {
6
+ if (e && e.__esModule) return e;
7
+ var n = Object.create(null);
8
+ if (e) {
9
+ Object.keys(e).forEach(function (k) {
10
+ if (k !== 'default') {
11
+ var d = Object.getOwnPropertyDescriptor(e, k);
12
+ Object.defineProperty(n, k, d.get ? d : {
13
+ enumerable: true,
14
+ get: function () { return e[k]; }
15
+ });
16
+ }
17
+ });
18
+ }
19
+ n.default = e;
20
+ return Object.freeze(n);
21
+ }
22
+
23
+ var yaml__namespace = /*#__PURE__*/_interopNamespace(yaml);
24
+
25
+ // src/tools/json.ts
26
+ function parseJson(input, indent) {
27
+ const trimmed = input.trim();
28
+ if (!trimmed) {
29
+ return { status: "idle", output: "", error: null, lines: 0, bytes: 0 };
30
+ }
31
+ try {
32
+ const parsed = JSON.parse(trimmed);
33
+ const output = indent === null ? JSON.stringify(parsed) : JSON.stringify(parsed, null, indent);
34
+ return {
35
+ status: "valid",
36
+ output,
37
+ error: null,
38
+ lines: output.split("\n").length,
39
+ bytes: Buffer.byteLength(output, "utf8")
40
+ };
41
+ } catch (e) {
42
+ return {
43
+ status: "error",
44
+ output: trimmed,
45
+ error: e.message,
46
+ lines: 0,
47
+ bytes: 0
48
+ };
49
+ }
50
+ }
51
+ function minifyJson(input) {
52
+ if (input.trim() === "") return { error: "Input is empty" };
53
+ try {
54
+ return JSON.stringify(JSON.parse(input));
55
+ } catch {
56
+ return { error: "Invalid JSON" };
57
+ }
58
+ }
59
+ function formatJson(input, indent = 2) {
60
+ if (input.trim() === "") return { error: "Input is empty" };
61
+ try {
62
+ return JSON.stringify(JSON.parse(input), null, indent);
63
+ } catch {
64
+ return { error: "Invalid JSON" };
65
+ }
66
+ }
67
+ function getJsonStats(input) {
68
+ if (input.trim() === "") return { error: "Input is empty" };
69
+ try {
70
+ const minified = JSON.stringify(JSON.parse(input));
71
+ const originalSize = Buffer.byteLength(input, "utf8");
72
+ const minifiedSize = Buffer.byteLength(minified, "utf8");
73
+ const savingPercent = originalSize === 0 ? 0 : Math.round((originalSize - minifiedSize) / originalSize * 1e4) / 100;
74
+ return { originalSize, minifiedSize, savingPercent };
75
+ } catch {
76
+ return { error: "Invalid JSON" };
77
+ }
78
+ }
79
+ function _isObject(value) {
80
+ return value !== null && typeof value === "object" && !Array.isArray(value);
81
+ }
82
+ function _isArray(value) {
83
+ return Array.isArray(value);
84
+ }
85
+ function _diffValues(left, right, path, counts) {
86
+ if (_isObject(left) && _isObject(right)) {
87
+ const children = _diffObjects(left, right, path, counts);
88
+ const allUnchanged = children.every((c) => c.type === "unchanged");
89
+ return { type: allUnchanged ? "unchanged" : "changed", path, children };
90
+ }
91
+ if (_isArray(left) && _isArray(right)) {
92
+ const children = _diffArrays(left, right, path, counts);
93
+ const allUnchanged = children.every((c) => c.type === "unchanged");
94
+ return { type: allUnchanged ? "unchanged" : "changed", path, children };
95
+ }
96
+ if (JSON.stringify(left) === JSON.stringify(right)) {
97
+ return { type: "unchanged", path, leftValue: left, rightValue: right };
98
+ }
99
+ counts.changed++;
100
+ return { type: "changed", path, leftValue: left, rightValue: right };
101
+ }
102
+ function _diffObjects(left, right, basePath, counts) {
103
+ const nodes = [];
104
+ const allKeys = /* @__PURE__ */ new Set([...Object.keys(left), ...Object.keys(right)]);
105
+ for (const key of allKeys) {
106
+ const childPath = `${basePath}.${key}`;
107
+ const inLeft = Object.prototype.hasOwnProperty.call(left, key);
108
+ const inRight = Object.prototype.hasOwnProperty.call(right, key);
109
+ if (inLeft && !inRight) {
110
+ counts.removed++;
111
+ nodes.push({ type: "removed", path: childPath, leftValue: left[key] });
112
+ } else if (!inLeft && inRight) {
113
+ counts.added++;
114
+ nodes.push({ type: "added", path: childPath, rightValue: right[key] });
115
+ } else {
116
+ nodes.push(_diffValues(left[key], right[key], childPath, counts));
117
+ }
118
+ }
119
+ return nodes;
120
+ }
121
+ function _diffArrays(left, right, basePath, counts) {
122
+ const nodes = [];
123
+ const maxLen = Math.max(left.length, right.length);
124
+ for (let i = 0; i < maxLen; i++) {
125
+ const childPath = `${basePath}[${i}]`;
126
+ const inLeft = i < left.length;
127
+ const inRight = i < right.length;
128
+ if (inLeft && !inRight) {
129
+ counts.removed++;
130
+ nodes.push({ type: "removed", path: childPath, leftValue: left[i] });
131
+ } else if (!inLeft && inRight) {
132
+ counts.added++;
133
+ nodes.push({ type: "added", path: childPath, rightValue: right[i] });
134
+ } else {
135
+ nodes.push(_diffValues(left[i], right[i], childPath, counts));
136
+ }
137
+ }
138
+ return nodes;
139
+ }
140
+ function diffJson(left, right) {
141
+ let leftVal;
142
+ let rightVal;
143
+ try {
144
+ leftVal = JSON.parse(left);
145
+ } catch {
146
+ return { error: "Invalid JSON in left input" };
147
+ }
148
+ try {
149
+ rightVal = JSON.parse(right);
150
+ } catch {
151
+ return { error: "Invalid JSON in right input" };
152
+ }
153
+ const counts = { added: 0, removed: 0, changed: 0 };
154
+ let nodes;
155
+ if (_isObject(leftVal) && _isObject(rightVal)) {
156
+ nodes = _diffObjects(leftVal, rightVal, "$", counts);
157
+ } else if (_isArray(leftVal) && _isArray(rightVal)) {
158
+ nodes = _diffArrays(leftVal, rightVal, "$", counts);
159
+ } else {
160
+ const node = _diffValues(leftVal, rightVal, "$", counts);
161
+ nodes = [node];
162
+ }
163
+ const unchanged = counts.added === 0 && counts.removed === 0 && counts.changed === 0;
164
+ return {
165
+ nodes,
166
+ addedCount: counts.added,
167
+ removedCount: counts.removed,
168
+ changedCount: counts.changed,
169
+ unchanged
170
+ };
171
+ }
172
+ function formatDiffLine(node) {
173
+ switch (node.type) {
174
+ case "added":
175
+ return `+ ${node.path}: ${JSON.stringify(node.rightValue)}`;
176
+ case "removed":
177
+ return `- ${node.path}: ${JSON.stringify(node.leftValue)}`;
178
+ case "changed":
179
+ if (node.children) {
180
+ return `~ ${node.path}`;
181
+ }
182
+ return `~ ${node.path}: ${JSON.stringify(node.leftValue)} \u2192 ${JSON.stringify(node.rightValue)}`;
183
+ case "unchanged":
184
+ return ` ${node.path}: ${JSON.stringify(node.leftValue ?? node.rightValue)}`;
185
+ }
186
+ }
187
+ function _escapeField(value, delimiter) {
188
+ const needsQuoting = value.includes(delimiter) || value.includes("\n") || value.includes("\r") || value.includes('"');
189
+ if (needsQuoting) {
190
+ return `"${value.replace(/"/g, '""')}"`;
191
+ }
192
+ return value;
193
+ }
194
+ function _valueToString(value, nullAs) {
195
+ if (value === null || value === void 0) return nullAs;
196
+ if (typeof value === "boolean") return value.toString();
197
+ if (typeof value === "number") return value.toString();
198
+ return String(value);
199
+ }
200
+ function jsonToCsv(json, options) {
201
+ let parsed;
202
+ try {
203
+ parsed = JSON.parse(json);
204
+ } catch {
205
+ return { error: "Invalid JSON input" };
206
+ }
207
+ if (!Array.isArray(parsed)) {
208
+ return { error: "Input must be a JSON array" };
209
+ }
210
+ const delimiter = options?.delimiter ?? ",";
211
+ const includeHeaders = options?.includeHeaders ?? true;
212
+ const nullAs = options?.nullAs ?? "";
213
+ if (parsed.length === 0) {
214
+ return "";
215
+ }
216
+ const allPrimitives = parsed.every(
217
+ (item) => item === null || typeof item !== "object"
218
+ );
219
+ if (allPrimitives) {
220
+ const rows2 = [];
221
+ if (includeHeaders) {
222
+ rows2.push(_escapeField("value", delimiter));
223
+ }
224
+ for (const item of parsed) {
225
+ rows2.push(_escapeField(_valueToString(item, nullAs), delimiter));
226
+ }
227
+ return rows2.join("\n");
228
+ }
229
+ const keySet = /* @__PURE__ */ new Set();
230
+ for (const item of parsed) {
231
+ if (item !== null && typeof item === "object" && !Array.isArray(item)) {
232
+ for (const key of Object.keys(item)) {
233
+ keySet.add(key);
234
+ }
235
+ }
236
+ }
237
+ const headers = [...keySet];
238
+ const rows = [];
239
+ if (includeHeaders) {
240
+ rows.push(headers.map((h) => _escapeField(h, delimiter)).join(delimiter));
241
+ }
242
+ for (const item of parsed) {
243
+ if (item === null || typeof item !== "object" || Array.isArray(item)) {
244
+ rows.push(headers.map(() => _escapeField(nullAs, delimiter)).join(delimiter));
245
+ continue;
246
+ }
247
+ const obj = item;
248
+ const cells = headers.map((h) => {
249
+ const val = Object.prototype.hasOwnProperty.call(obj, h) ? obj[h] : void 0;
250
+ return _escapeField(_valueToString(val, nullAs), delimiter);
251
+ });
252
+ rows.push(cells.join(delimiter));
253
+ }
254
+ return rows.join("\n");
255
+ }
256
+ function _parseRow(line, delimiter) {
257
+ const fields = [];
258
+ let i = 0;
259
+ while (i <= line.length) {
260
+ if (i === line.length) {
261
+ if (line[line.length - 1] === delimiter) {
262
+ fields.push("");
263
+ }
264
+ break;
265
+ }
266
+ if (line[i] === '"') {
267
+ let field = "";
268
+ i++;
269
+ while (i < line.length) {
270
+ if (line[i] === '"') {
271
+ if (line[i + 1] === '"') {
272
+ field += '"';
273
+ i += 2;
274
+ } else {
275
+ i++;
276
+ break;
277
+ }
278
+ } else {
279
+ field += line[i];
280
+ i++;
281
+ }
282
+ }
283
+ fields.push(field);
284
+ if (i < line.length && line[i] === delimiter) {
285
+ i++;
286
+ }
287
+ } else {
288
+ const end = line.indexOf(delimiter, i);
289
+ if (end === -1) {
290
+ fields.push(line.slice(i));
291
+ break;
292
+ } else {
293
+ fields.push(line.slice(i, end));
294
+ i = end + 1;
295
+ }
296
+ }
297
+ }
298
+ return fields;
299
+ }
300
+ function csvToJson(csv, delimiter = ",") {
301
+ if (!csv || csv.trim() === "") {
302
+ return { error: "Empty CSV input" };
303
+ }
304
+ const lines = csv.split(/\r?\n/).filter((line) => line.trim() !== "");
305
+ if (lines.length === 0) {
306
+ return { error: "No data in CSV" };
307
+ }
308
+ if (lines.length === 1) {
309
+ return JSON.stringify([]);
310
+ }
311
+ const headers = _parseRow(lines[0], delimiter);
312
+ const result = [];
313
+ for (let i = 1; i < lines.length; i++) {
314
+ const fields = _parseRow(lines[i], delimiter);
315
+ const obj = {};
316
+ for (let j = 0; j < headers.length; j++) {
317
+ obj[headers[j]] = fields[j] ?? "";
318
+ }
319
+ result.push(obj);
320
+ }
321
+ return JSON.stringify(result);
322
+ }
323
+ function _tokenize(path) {
324
+ const segments = [];
325
+ let i = 0;
326
+ if (path[i] !== "$") {
327
+ return { error: "Path must start with $" };
328
+ }
329
+ segments.push({ kind: "root" });
330
+ i++;
331
+ while (i < path.length) {
332
+ if (path[i] === "." && path[i + 1] === ".") {
333
+ i += 2;
334
+ const start = i;
335
+ while (i < path.length && path[i] !== "." && path[i] !== "[") {
336
+ i++;
337
+ }
338
+ const key = path.slice(start, i);
339
+ if (!key) return { error: "Expected key after .." };
340
+ segments.push({ kind: "recursive", key });
341
+ continue;
342
+ }
343
+ if (path[i] === ".") {
344
+ i++;
345
+ if (path[i] === "*") {
346
+ segments.push({ kind: "wildcardValues" });
347
+ i++;
348
+ continue;
349
+ }
350
+ const start = i;
351
+ while (i < path.length && path[i] !== "." && path[i] !== "[") {
352
+ i++;
353
+ }
354
+ const key = path.slice(start, i);
355
+ if (!key) return { error: "Expected key after ." };
356
+ segments.push({ kind: "key", key });
357
+ continue;
358
+ }
359
+ if (path[i] === "[") {
360
+ i++;
361
+ if (path[i] === "*") {
362
+ i++;
363
+ if (path[i] !== "]") return { error: "Expected ']' after [*" };
364
+ i++;
365
+ segments.push({ kind: "wildcard" });
366
+ continue;
367
+ }
368
+ if (path[i] === "'" || path[i] === '"') {
369
+ const quote = path[i];
370
+ i++;
371
+ const start2 = i;
372
+ while (i < path.length && path[i] !== quote) {
373
+ i++;
374
+ }
375
+ const key = path.slice(start2, i);
376
+ i++;
377
+ if (path[i] !== "]") return { error: "Expected ']'" };
378
+ i++;
379
+ segments.push({ kind: "key", key });
380
+ continue;
381
+ }
382
+ const start = i;
383
+ if (path[i] === "-") i++;
384
+ while (i < path.length && path[i] >= "0" && path[i] <= "9") {
385
+ i++;
386
+ }
387
+ const numStr = path.slice(start, i);
388
+ if (numStr === "" || numStr === "-") return { error: "Invalid index" };
389
+ const index = parseInt(numStr, 10);
390
+ if (path[i] !== "]") return { error: "Expected ']'" };
391
+ i++;
392
+ segments.push({ kind: "index", index });
393
+ continue;
394
+ }
395
+ return { error: `Unexpected character at position ${i}: '${path[i]}'` };
396
+ }
397
+ return segments;
398
+ }
399
+ function _applySegment(items, segment) {
400
+ const result = [];
401
+ for (const { value, path } of items) {
402
+ switch (segment.kind) {
403
+ case "root":
404
+ result.push({ value, path });
405
+ break;
406
+ case "key": {
407
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) {
408
+ const obj = value;
409
+ if (Object.prototype.hasOwnProperty.call(obj, segment.key)) {
410
+ result.push({
411
+ value: obj[segment.key],
412
+ path: `${path}.${segment.key}`
413
+ });
414
+ }
415
+ }
416
+ break;
417
+ }
418
+ case "index": {
419
+ if (Array.isArray(value)) {
420
+ const idx = segment.index < 0 ? value.length + segment.index : segment.index;
421
+ if (idx >= 0 && idx < value.length) {
422
+ result.push({ value: value[idx], path: `${path}[${idx}]` });
423
+ }
424
+ }
425
+ break;
426
+ }
427
+ case "wildcard": {
428
+ if (Array.isArray(value)) {
429
+ for (let i = 0; i < value.length; i++) {
430
+ result.push({ value: value[i], path: `${path}[${i}]` });
431
+ }
432
+ }
433
+ break;
434
+ }
435
+ case "wildcardValues": {
436
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) {
437
+ const obj = value;
438
+ for (const [k, v] of Object.entries(obj)) {
439
+ result.push({ value: v, path: `${path}.${k}` });
440
+ }
441
+ }
442
+ break;
443
+ }
444
+ case "recursive": {
445
+ let recurse2 = function(val, p) {
446
+ if (val !== null && typeof val === "object") {
447
+ if (!Array.isArray(val)) {
448
+ const obj = val;
449
+ if (Object.prototype.hasOwnProperty.call(obj, recursiveKey)) {
450
+ collected.push({ value: obj[recursiveKey], path: `${p}.${recursiveKey}` });
451
+ }
452
+ for (const [k, v] of Object.entries(obj)) {
453
+ recurse2(v, `${p}.${k}`);
454
+ }
455
+ } else {
456
+ for (let i = 0; i < val.length; i++) {
457
+ recurse2(val[i], `${p}[${i}]`);
458
+ }
459
+ }
460
+ }
461
+ };
462
+ const recursiveKey = segment.key;
463
+ const collected = [];
464
+ recurse2(value, path);
465
+ result.push(...collected);
466
+ break;
467
+ }
468
+ }
469
+ }
470
+ return result;
471
+ }
472
+ function evaluateJsonPath(json, path) {
473
+ let parsed;
474
+ try {
475
+ parsed = JSON.parse(json);
476
+ } catch {
477
+ return { matches: [], count: 0, paths: [], error: "Invalid JSON input" };
478
+ }
479
+ const validation = validateJsonPath(path);
480
+ if (!validation.valid) {
481
+ return { matches: [], count: 0, paths: [], error: validation.error };
482
+ }
483
+ const segments = _tokenize(path);
484
+ if ("error" in segments) {
485
+ return { matches: [], count: 0, paths: [], error: segments.error };
486
+ }
487
+ let current = [{ value: parsed, path: "$" }];
488
+ for (const segment of segments) {
489
+ if (segment.kind === "root") continue;
490
+ current = _applySegment(current, segment);
491
+ }
492
+ return {
493
+ matches: current.map((c) => c.value),
494
+ count: current.length,
495
+ paths: current.map((c) => c.path)
496
+ };
497
+ }
498
+ function validateJsonPath(path) {
499
+ if (!path || typeof path !== "string") {
500
+ return { valid: false, error: "Path must be a non-empty string" };
501
+ }
502
+ if (!path.startsWith("$")) {
503
+ return { valid: false, error: "Path must start with '$'" };
504
+ }
505
+ const invalidChars = /[^a-zA-Z0-9$._\[\]*'"@\-]/;
506
+ if (invalidChars.test(path)) {
507
+ return { valid: false, error: "Path contains invalid characters" };
508
+ }
509
+ return { valid: true };
510
+ }
511
+ function _resolveRef(ref, root) {
512
+ const parts = ref.replace(/^#\//, "").split("/");
513
+ let node = root;
514
+ for (const part of parts) {
515
+ if (!_isObject(node)) return null;
516
+ node = node[part];
517
+ }
518
+ return _isObject(node) ? node : null;
519
+ }
520
+ function _validateSchema(data, schema, path, root, errors) {
521
+ if (schema["$ref"] !== void 0) {
522
+ const ref = schema["$ref"];
523
+ const resolved = _resolveRef(ref, root);
524
+ if (!resolved) {
525
+ errors.push({ path, message: `Cannot resolve $ref: ${ref}` });
526
+ return;
527
+ }
528
+ _validateSchema(data, resolved, path, root, errors);
529
+ return;
530
+ }
531
+ if ("const" in schema) {
532
+ if (JSON.stringify(data) !== JSON.stringify(schema["const"])) {
533
+ errors.push({ path, message: `Value must be ${JSON.stringify(schema["const"])}` });
534
+ }
535
+ }
536
+ if ("enum" in schema) {
537
+ const enums = schema["enum"];
538
+ if (!enums.some((e) => JSON.stringify(e) === JSON.stringify(data))) {
539
+ errors.push({ path, message: `Value must be one of: ${enums.map((e) => JSON.stringify(e)).join(", ")}` });
540
+ }
541
+ }
542
+ if ("type" in schema) {
543
+ const types = Array.isArray(schema["type"]) ? schema["type"] : [schema["type"]];
544
+ const valid = types.some((t) => _matchesType(data, t));
545
+ if (!valid) {
546
+ errors.push({ path, message: `Expected type ${types.join(" or ")}, got ${_getType(data)}` });
547
+ return;
548
+ }
549
+ }
550
+ if ("allOf" in schema) {
551
+ const allOf = schema["allOf"];
552
+ for (const sub of allOf) {
553
+ _validateSchema(data, sub, path, root, errors);
554
+ }
555
+ }
556
+ if ("anyOf" in schema) {
557
+ const anyOf = schema["anyOf"];
558
+ const anyValid = anyOf.some((sub) => {
559
+ const subErrors = [];
560
+ _validateSchema(data, sub, path, root, subErrors);
561
+ return subErrors.length === 0;
562
+ });
563
+ if (!anyValid) {
564
+ errors.push({ path, message: "Value must match at least one of the anyOf schemas" });
565
+ }
566
+ }
567
+ if ("oneOf" in schema) {
568
+ const oneOf = schema["oneOf"];
569
+ const matchCount = oneOf.filter((sub) => {
570
+ const subErrors = [];
571
+ _validateSchema(data, sub, path, root, subErrors);
572
+ return subErrors.length === 0;
573
+ }).length;
574
+ if (matchCount !== 1) {
575
+ errors.push({ path, message: `Value must match exactly one of the oneOf schemas, matched ${matchCount}` });
576
+ }
577
+ }
578
+ if ("not" in schema) {
579
+ const notErrors = [];
580
+ _validateSchema(data, schema["not"], path, root, notErrors);
581
+ if (notErrors.length === 0) {
582
+ errors.push({ path, message: "Value must not match the not schema" });
583
+ }
584
+ }
585
+ if (typeof data === "string") {
586
+ _validateString(data, schema, path, errors);
587
+ }
588
+ if (typeof data === "number") {
589
+ _validateNumber(data, schema, path, errors);
590
+ }
591
+ if (Array.isArray(data)) {
592
+ _validateArray(data, schema, path, root, errors);
593
+ }
594
+ if (_isObject(data)) {
595
+ _validateObject(data, schema, path, root, errors);
596
+ }
597
+ }
598
+ function _matchesType(data, type) {
599
+ switch (type) {
600
+ case "string":
601
+ return typeof data === "string";
602
+ case "number":
603
+ return typeof data === "number";
604
+ case "integer":
605
+ return typeof data === "number" && Number.isInteger(data);
606
+ case "boolean":
607
+ return typeof data === "boolean";
608
+ case "null":
609
+ return data === null;
610
+ case "array":
611
+ return Array.isArray(data);
612
+ case "object":
613
+ return _isObject(data);
614
+ default:
615
+ return true;
616
+ }
617
+ }
618
+ function _getType(data) {
619
+ if (data === null) return "null";
620
+ if (Array.isArray(data)) return "array";
621
+ return typeof data;
622
+ }
623
+ function _validateString(data, schema, path, errors) {
624
+ if ("minLength" in schema && data.length < schema["minLength"]) {
625
+ errors.push({ path, message: `String must be at least ${schema["minLength"]} characters` });
626
+ }
627
+ if ("maxLength" in schema && data.length > schema["maxLength"]) {
628
+ errors.push({ path, message: `String must be at most ${schema["maxLength"]} characters` });
629
+ }
630
+ if ("pattern" in schema) {
631
+ const re = new RegExp(schema["pattern"]);
632
+ if (!re.test(data)) {
633
+ errors.push({ path, message: `String must match pattern ${schema["pattern"]}` });
634
+ }
635
+ }
636
+ }
637
+ function _validateNumber(data, schema, path, errors) {
638
+ if ("minimum" in schema && data < schema["minimum"]) {
639
+ errors.push({ path, message: `Value must be >= ${schema["minimum"]}` });
640
+ }
641
+ if ("maximum" in schema && data > schema["maximum"]) {
642
+ errors.push({ path, message: `Value must be <= ${schema["maximum"]}` });
643
+ }
644
+ if ("exclusiveMinimum" in schema) {
645
+ const excMin = schema["exclusiveMinimum"];
646
+ if (typeof excMin === "number" && data <= excMin) {
647
+ errors.push({ path, message: `Value must be > ${excMin}` });
648
+ } else if (excMin === true && "minimum" in schema && data <= schema["minimum"]) {
649
+ errors.push({ path, message: `Value must be > ${schema["minimum"]}` });
650
+ }
651
+ }
652
+ if ("exclusiveMaximum" in schema) {
653
+ const excMax = schema["exclusiveMaximum"];
654
+ if (typeof excMax === "number" && data >= excMax) {
655
+ errors.push({ path, message: `Value must be < ${excMax}` });
656
+ } else if (excMax === true && "maximum" in schema && data >= schema["maximum"]) {
657
+ errors.push({ path, message: `Value must be < ${schema["maximum"]}` });
658
+ }
659
+ }
660
+ if ("multipleOf" in schema) {
661
+ const mo = schema["multipleOf"];
662
+ if (data % mo !== 0) {
663
+ errors.push({ path, message: `Value must be a multiple of ${mo}` });
664
+ }
665
+ }
666
+ }
667
+ function _validateArray(data, schema, path, root, errors) {
668
+ if ("minItems" in schema && data.length < schema["minItems"]) {
669
+ errors.push({ path, message: `Array must have at least ${schema["minItems"]} items` });
670
+ }
671
+ if ("maxItems" in schema && data.length > schema["maxItems"]) {
672
+ errors.push({ path, message: `Array must have at most ${schema["maxItems"]} items` });
673
+ }
674
+ if ("uniqueItems" in schema && schema["uniqueItems"] === true) {
675
+ const seen = /* @__PURE__ */ new Set();
676
+ for (let i = 0; i < data.length; i++) {
677
+ const key = JSON.stringify(data[i]);
678
+ if (seen.has(key)) {
679
+ errors.push({ path: `${path}/${i}`, message: "Array items must be unique" });
680
+ }
681
+ seen.add(key);
682
+ }
683
+ }
684
+ if ("items" in schema) {
685
+ const items = schema["items"];
686
+ if (_isObject(items)) {
687
+ for (let i = 0; i < data.length; i++) {
688
+ _validateSchema(data[i], items, `${path}/${i}`, root, errors);
689
+ }
690
+ } else if (Array.isArray(items)) {
691
+ for (let i = 0; i < items.length; i++) {
692
+ if (i < data.length) {
693
+ _validateSchema(data[i], items[i], `${path}/${i}`, root, errors);
694
+ }
695
+ }
696
+ }
697
+ }
698
+ }
699
+ function _validateObject(data, schema, path, root, errors) {
700
+ const keys = Object.keys(data);
701
+ if ("minProperties" in schema && keys.length < schema["minProperties"]) {
702
+ errors.push({ path, message: `Object must have at least ${schema["minProperties"]} properties` });
703
+ }
704
+ if ("maxProperties" in schema && keys.length > schema["maxProperties"]) {
705
+ errors.push({ path, message: `Object must have at most ${schema["maxProperties"]} properties` });
706
+ }
707
+ if ("required" in schema) {
708
+ const required = schema["required"];
709
+ for (const key of required) {
710
+ if (!(key in data)) {
711
+ errors.push({ path: `${path}/${key}`, message: `Required property '${key}' is missing` });
712
+ }
713
+ }
714
+ }
715
+ const properties = _isObject(schema["properties"]) ? schema["properties"] : {};
716
+ for (const key of keys) {
717
+ if (key in properties) {
718
+ _validateSchema(data[key], properties[key], `${path}/${key}`, root, errors);
719
+ } else if ("additionalProperties" in schema) {
720
+ const ap = schema["additionalProperties"];
721
+ if (ap === false) {
722
+ errors.push({ path: `${path}/${key}`, message: `Additional property '${key}' is not allowed` });
723
+ } else if (_isObject(ap)) {
724
+ _validateSchema(data[key], ap, `${path}/${key}`, root, errors);
725
+ }
726
+ }
727
+ }
728
+ }
729
+ function validateJson(data, schema) {
730
+ const errors = [];
731
+ _validateSchema(data, schema, "#", schema, errors);
732
+ return { valid: errors.length === 0, errors };
733
+ }
734
+ function validateJsonString(dataStr, schemaStr) {
735
+ let data;
736
+ let schema;
737
+ try {
738
+ data = JSON.parse(dataStr);
739
+ } catch (e) {
740
+ return { parseError: `Invalid data JSON: ${e.message}` };
741
+ }
742
+ try {
743
+ schema = JSON.parse(schemaStr);
744
+ } catch (e) {
745
+ return { parseError: `Invalid schema JSON: ${e.message}` };
746
+ }
747
+ return validateJson(data, schema);
748
+ }
749
+ function generateExample(schema) {
750
+ return _generateExampleFromSchema(schema, schema);
751
+ }
752
+ function _generateExampleFromSchema(schema, root) {
753
+ if (schema["$ref"] !== void 0) {
754
+ const resolved = _resolveRef(schema["$ref"], root);
755
+ if (resolved) return _generateExampleFromSchema(resolved, root);
756
+ return null;
757
+ }
758
+ if ("const" in schema) return schema["const"];
759
+ if ("enum" in schema) return schema["enum"][0];
760
+ if ("examples" in schema) return schema["examples"][0];
761
+ if ("default" in schema) return schema["default"];
762
+ if ("allOf" in schema) {
763
+ const result = {};
764
+ for (const sub of schema["allOf"]) {
765
+ const ex = _generateExampleFromSchema(sub, root);
766
+ if (_isObject(ex)) Object.assign(result, ex);
767
+ }
768
+ return result;
769
+ }
770
+ if ("anyOf" in schema) return _generateExampleFromSchema(schema["anyOf"][0], root);
771
+ if ("oneOf" in schema) return _generateExampleFromSchema(schema["oneOf"][0], root);
772
+ const type = Array.isArray(schema["type"]) ? schema["type"][0] : schema["type"];
773
+ switch (type) {
774
+ case "string": {
775
+ if (schema["pattern"]) return "example";
776
+ const minLen = schema["minLength"] || 0;
777
+ return "example".padEnd(Math.max(minLen, 7), "x").slice(0, schema["maxLength"] || 100);
778
+ }
779
+ case "number":
780
+ case "integer": {
781
+ const min = schema["minimum"] ?? schema["exclusiveMinimum"] ?? 0;
782
+ return type === "integer" ? Math.ceil(min) : min;
783
+ }
784
+ case "boolean":
785
+ return true;
786
+ case "null":
787
+ return null;
788
+ case "array": {
789
+ const items = schema["items"];
790
+ const minItems = schema["minItems"] || 1;
791
+ const count = Math.max(minItems, 1);
792
+ if (_isObject(items)) {
793
+ return Array.from({ length: count }, () => _generateExampleFromSchema(items, root));
794
+ }
795
+ return [];
796
+ }
797
+ case "object": {
798
+ const result = {};
799
+ const props = _isObject(schema["properties"]) ? schema["properties"] : {};
800
+ const required = schema["required"] || Object.keys(props).slice(0, 3);
801
+ for (const key of required) {
802
+ if (key in props) {
803
+ result[key] = _generateExampleFromSchema(props[key], root);
804
+ } else {
805
+ result[key] = "value";
806
+ }
807
+ }
808
+ return result;
809
+ }
810
+ default: {
811
+ if (_isObject(schema["properties"])) {
812
+ return _generateExampleFromSchema({ ...schema, type: "object" }, root);
813
+ }
814
+ return null;
815
+ }
816
+ }
817
+ }
818
+ function yamlToJson(input, pretty = true) {
819
+ try {
820
+ const trimmed = input.trim();
821
+ if (trimmed === "") return JSON.stringify(null, null, pretty ? 2 : void 0);
822
+ const parsed = yaml__namespace.load(trimmed);
823
+ const value = parsed === void 0 ? null : parsed;
824
+ return JSON.stringify(value, null, pretty ? 2 : void 0);
825
+ } catch (err) {
826
+ return { error: err instanceof Error ? err.message : String(err) };
827
+ }
828
+ }
829
+ function jsonToYaml(input) {
830
+ try {
831
+ const parsed = JSON.parse(input);
832
+ return yaml__namespace.dump(parsed);
833
+ } catch (err) {
834
+ return { error: err instanceof Error ? err.message : String(err) };
835
+ }
836
+ }
837
+ function detectFormat(input) {
838
+ const trimmed = input.trim();
839
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
840
+ return "json";
841
+ }
842
+ if (trimmed.includes(": ") && !trimmed.startsWith("{")) {
843
+ return "yaml";
844
+ }
845
+ return "unknown";
846
+ }
847
+ function inferType(value, name, interfaces) {
848
+ if (value === null) return "null";
849
+ if (typeof value === "string") return "string";
850
+ if (typeof value === "number") return "number";
851
+ if (typeof value === "boolean") return "boolean";
852
+ if (Array.isArray(value)) {
853
+ if (value.length === 0) return "unknown[]";
854
+ const elementTypes = value.map((item) => inferType(item, `${name}Item`, interfaces));
855
+ const uniqueTypes = [...new Set(elementTypes)];
856
+ if (uniqueTypes.length === 1) {
857
+ return `${uniqueTypes[0]}[]`;
858
+ }
859
+ const allObjects = value.every((item) => item !== null && typeof item === "object" && !Array.isArray(item));
860
+ if (allObjects) {
861
+ const merged = {};
862
+ for (const item of value) {
863
+ for (const [k, v] of Object.entries(item)) {
864
+ if (!(k in merged)) merged[k] = v;
865
+ }
866
+ }
867
+ const itemName = `${name}Item`;
868
+ _buildInterface(merged, itemName, interfaces);
869
+ return `${itemName}[]`;
870
+ }
871
+ return "unknown[]";
872
+ }
873
+ if (typeof value === "object" && value !== null) {
874
+ _buildInterface(value, name, interfaces);
875
+ return name;
876
+ }
877
+ return "unknown";
878
+ }
879
+ function _buildInterface(obj, name, interfaces, useType, optionalFields = false) {
880
+ const lines = [];
881
+ {
882
+ lines.push(`interface ${name} {`);
883
+ }
884
+ for (const [key, val] of Object.entries(obj)) {
885
+ const fieldName = optionalFields ? `${key}?` : key;
886
+ const subName = _capitalize(key);
887
+ const subInterfaces = [];
888
+ const typeName = inferType(val, subName, subInterfaces);
889
+ for (const sub of subInterfaces) {
890
+ if (!interfaces.includes(sub)) {
891
+ interfaces.push(sub);
892
+ }
893
+ }
894
+ lines.push(` ${fieldName}: ${typeName};`);
895
+ }
896
+ lines.push("}");
897
+ const result = lines.join("\n");
898
+ if (!interfaces.includes(result)) {
899
+ interfaces.push(result);
900
+ }
901
+ }
902
+ function _capitalize(str) {
903
+ if (!str) return str;
904
+ return str.charAt(0).toUpperCase() + str.slice(1);
905
+ }
906
+ function jsonToTypescript(json, options) {
907
+ let parsed;
908
+ try {
909
+ parsed = JSON.parse(json);
910
+ } catch {
911
+ return { error: "Invalid JSON input" };
912
+ }
913
+ const rootName = options?.rootName ?? "Root";
914
+ const useInterface = options?.useInterface ?? true;
915
+ const optionalFields = options?.optionalFields ?? false;
916
+ const interfaces = [];
917
+ if (parsed === null) {
918
+ return `type ${rootName} = null;`;
919
+ }
920
+ if (typeof parsed !== "object" && !Array.isArray(parsed)) {
921
+ const t = inferType(parsed, rootName, interfaces);
922
+ return `type ${rootName} = ${t};`;
923
+ }
924
+ if (Array.isArray(parsed)) {
925
+ const subInterfaces = [];
926
+ const elementType = inferType(parsed, rootName, subInterfaces);
927
+ const parts = [...subInterfaces];
928
+ const declaration = `type ${rootName} = ${elementType};`;
929
+ parts.push(declaration);
930
+ return parts.join("\n\n");
931
+ }
932
+ const obj = parsed;
933
+ const lines = [];
934
+ const fieldLines = [];
935
+ for (const [key, val] of Object.entries(obj)) {
936
+ const fieldName = optionalFields ? `${key}?` : key;
937
+ const subName = _capitalize(key);
938
+ const subInterfaces = [];
939
+ const typeName = inferType(val, subName, subInterfaces);
940
+ for (const sub of subInterfaces) {
941
+ interfaces.push(sub);
942
+ }
943
+ fieldLines.push(` ${fieldName}: ${typeName};`);
944
+ }
945
+ if (useInterface) {
946
+ lines.push(`interface ${rootName} {`);
947
+ } else {
948
+ lines.push(`type ${rootName} = {`);
949
+ }
950
+ lines.push(...fieldLines);
951
+ lines.push("}");
952
+ const rootDecl = lines.join("\n");
953
+ const allParts = [...interfaces, rootDecl];
954
+ return allParts.join("\n\n");
955
+ }
956
+ function toPascalCase(key) {
957
+ return key.replace(/[-_\s]+(.)/g, (_, char) => char.toUpperCase()).replace(/([a-z])([A-Z])/g, "$1 $2").split(" ").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("").replace(/^(.)/, (c) => c.toUpperCase());
958
+ }
959
+ function inferGoType(value, fieldName) {
960
+ if (value === null) return "interface{}";
961
+ if (typeof value === "string") return "string";
962
+ if (typeof value === "boolean") return "bool";
963
+ if (typeof value === "number") {
964
+ return Number.isInteger(value) ? "int64" : "float64";
965
+ }
966
+ if (Array.isArray(value)) {
967
+ if (value.length === 0) return "[]interface{}";
968
+ const allObjects = value.every((v) => v !== null && typeof v === "object" && !Array.isArray(v));
969
+ if (allObjects) {
970
+ if (fieldName) {
971
+ const singular = _toSingular(toPascalCase(fieldName));
972
+ return `[]${singular}`;
973
+ }
974
+ return "[]interface{}";
975
+ }
976
+ const elementTypes = new Set(value.map((v) => inferGoType(v)));
977
+ if (elementTypes.size > 1) return "[]interface{}";
978
+ const elemType = elementTypes.values().next().value;
979
+ if (elemType === "string") return "[]string";
980
+ if (elemType === "int64") return "[]int64";
981
+ if (elemType === "float64") return "[]float64";
982
+ if (elemType === "bool") return "[]bool";
983
+ return "[]interface{}";
984
+ }
985
+ if (typeof value === "object") {
986
+ if (fieldName) return toPascalCase(fieldName);
987
+ return "interface{}";
988
+ }
989
+ return "interface{}";
990
+ }
991
+ function _toSingular(name) {
992
+ if (name.endsWith("ies")) return name.slice(0, -3) + "y";
993
+ if (name.endsWith("ses") || name.endsWith("xes") || name.endsWith("zes")) return name.slice(0, -2);
994
+ if (name.endsWith("s") && !name.endsWith("ss")) return name.slice(0, -1);
995
+ return name;
996
+ }
997
+ function _collectStructs(obj, structName, structs) {
998
+ const fields = [];
999
+ for (const [key, value] of Object.entries(obj)) {
1000
+ const fieldName = toPascalCase(key);
1001
+ let goType = inferGoType(value, key);
1002
+ const omitempty = value === null || value === void 0;
1003
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) {
1004
+ const nestedName = toPascalCase(key);
1005
+ _collectStructs(value, nestedName, structs);
1006
+ goType = nestedName;
1007
+ }
1008
+ if (Array.isArray(value) && value.length > 0) {
1009
+ const firstNonNull = value.find((v) => v !== null && typeof v === "object" && !Array.isArray(v));
1010
+ if (firstNonNull) {
1011
+ const elemName = _toSingular(toPascalCase(key));
1012
+ _collectStructs(firstNonNull, elemName, structs);
1013
+ goType = `[]${elemName}`;
1014
+ }
1015
+ }
1016
+ fields.push({ name: fieldName, jsonKey: key, goType, omitempty });
1017
+ }
1018
+ structs.set(structName, { name: structName, fields });
1019
+ }
1020
+ function parseStructs(json, rootName = "Root") {
1021
+ let parsed;
1022
+ try {
1023
+ parsed = JSON.parse(json);
1024
+ } catch {
1025
+ return { error: "Invalid JSON" };
1026
+ }
1027
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
1028
+ if (Array.isArray(parsed)) {
1029
+ const firstObj = parsed.find(
1030
+ (v) => v !== null && typeof v === "object" && !Array.isArray(v)
1031
+ );
1032
+ if (firstObj) {
1033
+ const structs2 = /* @__PURE__ */ new Map();
1034
+ _collectStructs(firstObj, rootName, structs2);
1035
+ return Array.from(structs2.values());
1036
+ }
1037
+ return [{ name: rootName, fields: [] }];
1038
+ }
1039
+ return { error: "JSON root must be an object or array of objects" };
1040
+ }
1041
+ const structs = /* @__PURE__ */ new Map();
1042
+ _collectStructs(parsed, rootName, structs);
1043
+ return Array.from(structs.values());
1044
+ }
1045
+ function _formatStructs(structs) {
1046
+ return structs.map((s) => {
1047
+ const maxNameLen = s.fields.reduce((m, f) => Math.max(m, f.name.length), 0);
1048
+ const maxTypeLen = s.fields.reduce((m, f) => Math.max(m, f.goType.length), 0);
1049
+ const fieldLines = s.fields.map((f) => {
1050
+ const paddedName = f.name.padEnd(maxNameLen + 1);
1051
+ const paddedType = f.goType.padEnd(maxTypeLen + 1);
1052
+ const tag = f.omitempty ? `\`json:"${f.jsonKey},omitempty"\`` : `\`json:"${f.jsonKey}"\``;
1053
+ return ` ${paddedName}${paddedType}${tag}`;
1054
+ });
1055
+ return `type ${s.name} struct {
1056
+ ${fieldLines.join("\n")}
1057
+ }`;
1058
+ }).join("\n\n");
1059
+ }
1060
+ function jsonToGo(json, rootTypeName = "Root") {
1061
+ const structsResult = parseStructs(json, rootTypeName);
1062
+ if ("error" in structsResult) return structsResult;
1063
+ if (structsResult.length === 0) {
1064
+ return `type ${rootTypeName} struct {}`;
1065
+ }
1066
+ return _formatStructs(structsResult);
1067
+ }
1068
+ function toSnakeCase(key) {
1069
+ return key.replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").replace(/([a-z\d])([A-Z])/g, "$1_$2").replace(/-/g, "_").toLowerCase();
1070
+ }
1071
+ function inferPythonType(value, fieldName) {
1072
+ if (value === null) return "None";
1073
+ if (typeof value === "boolean") return "bool";
1074
+ if (typeof value === "string") return "str";
1075
+ if (typeof value === "number") {
1076
+ return Number.isInteger(value) ? "int" : "float";
1077
+ }
1078
+ if (Array.isArray(value)) {
1079
+ if (value.length === 0) return "List[Any]";
1080
+ const allStrings = value.every((v) => typeof v === "string");
1081
+ if (allStrings) return "List[str]";
1082
+ const allInts = value.every((v) => typeof v === "number" && Number.isInteger(v));
1083
+ if (allInts) return "List[int]";
1084
+ const allFloats = value.every((v) => typeof v === "number");
1085
+ if (allFloats) return "List[float]";
1086
+ const allBools = value.every((v) => typeof v === "boolean");
1087
+ if (allBools) return "List[bool]";
1088
+ const allObjects = value.every(
1089
+ (v) => v !== null && typeof v === "object" && !Array.isArray(v)
1090
+ );
1091
+ if (allObjects) {
1092
+ const className = fieldName ? fieldName.charAt(0).toUpperCase() + fieldName.slice(1) : "Item";
1093
+ return `List[${className}]`;
1094
+ }
1095
+ return "List[Any]";
1096
+ }
1097
+ if (typeof value === "object") {
1098
+ const className = fieldName ? fieldName.charAt(0).toUpperCase() + fieldName.slice(1) : "Object";
1099
+ return className;
1100
+ }
1101
+ return "Any";
1102
+ }
1103
+ function _collectPythonClasses(obj, className, mode, classes) {
1104
+ const fields = [];
1105
+ for (const [key, value] of Object.entries(obj)) {
1106
+ const snakeKey = toSnakeCase(key);
1107
+ let optional = false;
1108
+ if (value === null) {
1109
+ optional = true;
1110
+ }
1111
+ const pyType = inferPythonType(value, snakeKey);
1112
+ fields.push({ name: snakeKey, jsonKey: key, pyType, optional });
1113
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) {
1114
+ const nestedClassName = snakeKey.charAt(0).toUpperCase() + snakeKey.slice(1);
1115
+ _collectPythonClasses(value, nestedClassName, mode, classes);
1116
+ }
1117
+ if (Array.isArray(value) && value.length > 0) {
1118
+ const allObjects = value.every(
1119
+ (v) => v !== null && typeof v === "object" && !Array.isArray(v)
1120
+ );
1121
+ if (allObjects) {
1122
+ const nestedClassName = snakeKey.charAt(0).toUpperCase() + snakeKey.slice(1);
1123
+ const merged = {};
1124
+ for (const item of value) {
1125
+ for (const [k, v] of Object.entries(item)) {
1126
+ if (!(k in merged)) {
1127
+ merged[k] = v;
1128
+ }
1129
+ }
1130
+ }
1131
+ _collectPythonClasses(merged, nestedClassName, mode, classes);
1132
+ }
1133
+ }
1134
+ }
1135
+ classes.push({ name: className, fields, mode });
1136
+ }
1137
+ function _renderPythonClass(cls) {
1138
+ const { name, fields, mode } = cls;
1139
+ const lines = [];
1140
+ if (mode === "typeddict") {
1141
+ lines.push(`class ${name}(TypedDict):`);
1142
+ if (fields.length === 0) {
1143
+ lines.push(" pass");
1144
+ } else {
1145
+ for (const field of fields) {
1146
+ const t = field.optional ? `Optional[${field.pyType}]` : field.pyType;
1147
+ lines.push(` ${field.name}: ${t}`);
1148
+ }
1149
+ }
1150
+ } else if (mode === "dataclass") {
1151
+ lines.push("@dataclass");
1152
+ lines.push(`class ${name}:`);
1153
+ if (fields.length === 0) {
1154
+ lines.push(" pass");
1155
+ } else {
1156
+ for (const field of fields) {
1157
+ const t = field.optional ? `Optional[${field.pyType}]` : field.pyType;
1158
+ const defaultVal = field.optional ? " = None" : "";
1159
+ lines.push(` ${field.name}: ${t}${defaultVal}`);
1160
+ }
1161
+ }
1162
+ } else {
1163
+ lines.push(`class ${name}(BaseModel):`);
1164
+ if (fields.length === 0) {
1165
+ lines.push(" pass");
1166
+ } else {
1167
+ for (const field of fields) {
1168
+ const t = field.optional ? `Optional[${field.pyType}]` : field.pyType;
1169
+ const defaultVal = field.optional ? " = None" : "";
1170
+ lines.push(` ${field.name}: ${t}${defaultVal}`);
1171
+ }
1172
+ }
1173
+ }
1174
+ return lines.join("\n");
1175
+ }
1176
+ function jsonToPython(json, rootName, mode) {
1177
+ let parsed;
1178
+ try {
1179
+ parsed = JSON.parse(json);
1180
+ } catch (e) {
1181
+ return { error: `Invalid JSON: ${e.message}` };
1182
+ }
1183
+ const resolvedMode = mode ?? "typeddict";
1184
+ const resolvedRoot = rootName ?? "Root";
1185
+ let topObj;
1186
+ if (Array.isArray(parsed)) {
1187
+ topObj = { items: parsed };
1188
+ } else if (parsed !== null && typeof parsed === "object") {
1189
+ topObj = parsed;
1190
+ } else {
1191
+ return { error: "Top-level JSON must be an object or array" };
1192
+ }
1193
+ const classes = [];
1194
+ _collectPythonClasses(topObj, resolvedRoot, resolvedMode, classes);
1195
+ const headerLines = [];
1196
+ if (resolvedMode === "typeddict") {
1197
+ headerLines.push("from typing import TypedDict, List, Optional, Any");
1198
+ } else if (resolvedMode === "dataclass") {
1199
+ headerLines.push("from dataclasses import dataclass");
1200
+ headerLines.push("from typing import List, Optional, Any");
1201
+ } else {
1202
+ headerLines.push("from pydantic import BaseModel");
1203
+ headerLines.push("from typing import List, Optional, Any");
1204
+ }
1205
+ const classBlocks = classes.map(_renderPythonClass);
1206
+ const output = [...headerLines, "", ...classBlocks].join("\n\n");
1207
+ return output;
1208
+ }
1209
+ function _valueToZodType(value, coerce = false) {
1210
+ if (value === null) return "z.null()";
1211
+ if (typeof value === "string") return "z.string()";
1212
+ if (typeof value === "number") return coerce ? "z.coerce.number()" : "z.number()";
1213
+ if (typeof value === "boolean") return coerce ? "z.coerce.boolean()" : "z.boolean()";
1214
+ if (Array.isArray(value)) {
1215
+ if (value.length === 0) return "z.array(z.unknown())";
1216
+ const elementType = _valueToZodType(value[0], coerce);
1217
+ return `z.array(${elementType})`;
1218
+ }
1219
+ if (typeof value === "object") {
1220
+ return _objectToZodSchema(value, coerce);
1221
+ }
1222
+ return "z.unknown()";
1223
+ }
1224
+ function _objectToZodSchema(obj, coerce = false) {
1225
+ const entries = Object.entries(obj).map(([key, val]) => ` ${key}: ${_valueToZodType(val, coerce)}`).join(",\n");
1226
+ return `z.object({
1227
+ ${entries}
1228
+ })`;
1229
+ }
1230
+ function jsonToZod(json, options) {
1231
+ const rootName = options?.rootName ?? "Root";
1232
+ const coerce = options?.coerce ?? false;
1233
+ let parsed;
1234
+ try {
1235
+ parsed = JSON.parse(json);
1236
+ } catch (err) {
1237
+ return { error: err instanceof Error ? err.message : String(err) };
1238
+ }
1239
+ const schema = _valueToZodType(parsed, coerce);
1240
+ return `import { z } from 'zod'
1241
+
1242
+ export const ${rootName}Schema = ${schema}`;
1243
+ }
1244
+
1245
+ exports.csvToJson = csvToJson;
1246
+ exports.detectFormat = detectFormat;
1247
+ exports.diffJson = diffJson;
1248
+ exports.evaluateJsonPath = evaluateJsonPath;
1249
+ exports.formatDiffLine = formatDiffLine;
1250
+ exports.formatJson = formatJson;
1251
+ exports.generateExample = generateExample;
1252
+ exports.getJsonStats = getJsonStats;
1253
+ exports.inferGoType = inferGoType;
1254
+ exports.inferPythonType = inferPythonType;
1255
+ exports.inferType = inferType;
1256
+ exports.jsonToCsv = jsonToCsv;
1257
+ exports.jsonToGo = jsonToGo;
1258
+ exports.jsonToPython = jsonToPython;
1259
+ exports.jsonToTypescript = jsonToTypescript;
1260
+ exports.jsonToYaml = jsonToYaml;
1261
+ exports.jsonToZod = jsonToZod;
1262
+ exports.minifyJson = minifyJson;
1263
+ exports.parseJson = parseJson;
1264
+ exports.parseStructs = parseStructs;
1265
+ exports.toPascalCase = toPascalCase;
1266
+ exports.toSnakeCase = toSnakeCase;
1267
+ exports.validateJson = validateJson;
1268
+ exports.validateJsonPath = validateJsonPath;
1269
+ exports.validateJsonString = validateJsonString;
1270
+ exports.yamlToJson = yamlToJson;