@atmaticai/agent-tools-core 1.0.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 (142) hide show
  1. package/README.md +742 -0
  2. package/dist/archive/index.d.mts +1 -0
  3. package/dist/archive/index.d.ts +1 -0
  4. package/dist/archive/index.js +90 -0
  5. package/dist/archive/index.js.map +1 -0
  6. package/dist/archive/index.mjs +80 -0
  7. package/dist/archive/index.mjs.map +1 -0
  8. package/dist/color/index.d.mts +1 -0
  9. package/dist/color/index.d.ts +1 -0
  10. package/dist/color/index.js +347 -0
  11. package/dist/color/index.js.map +1 -0
  12. package/dist/color/index.mjs +336 -0
  13. package/dist/color/index.mjs.map +1 -0
  14. package/dist/crypto/index.d.mts +1 -0
  15. package/dist/crypto/index.d.ts +1 -0
  16. package/dist/crypto/index.js +116 -0
  17. package/dist/crypto/index.js.map +1 -0
  18. package/dist/crypto/index.mjs +108 -0
  19. package/dist/crypto/index.mjs.map +1 -0
  20. package/dist/csv/index.d.mts +1 -0
  21. package/dist/csv/index.d.ts +1 -0
  22. package/dist/csv/index.js +371 -0
  23. package/dist/csv/index.js.map +1 -0
  24. package/dist/csv/index.mjs +348 -0
  25. package/dist/csv/index.mjs.map +1 -0
  26. package/dist/datetime/index.d.mts +1 -0
  27. package/dist/datetime/index.d.ts +1 -0
  28. package/dist/datetime/index.js +234 -0
  29. package/dist/datetime/index.js.map +1 -0
  30. package/dist/datetime/index.mjs +224 -0
  31. package/dist/datetime/index.mjs.map +1 -0
  32. package/dist/diff/index.d.mts +2 -0
  33. package/dist/diff/index.d.ts +2 -0
  34. package/dist/diff/index.js +84 -0
  35. package/dist/diff/index.js.map +1 -0
  36. package/dist/diff/index.mjs +78 -0
  37. package/dist/diff/index.mjs.map +1 -0
  38. package/dist/excel/index.d.mts +1 -0
  39. package/dist/excel/index.d.ts +1 -0
  40. package/dist/excel/index.js +163 -0
  41. package/dist/excel/index.js.map +1 -0
  42. package/dist/excel/index.mjs +153 -0
  43. package/dist/excel/index.mjs.map +1 -0
  44. package/dist/image/index.d.mts +1 -0
  45. package/dist/image/index.d.ts +1 -0
  46. package/dist/image/index.js +123 -0
  47. package/dist/image/index.js.map +1 -0
  48. package/dist/image/index.mjs +107 -0
  49. package/dist/image/index.mjs.map +1 -0
  50. package/dist/index--vbnYfdE.d.mts +142 -0
  51. package/dist/index--vbnYfdE.d.ts +142 -0
  52. package/dist/index-7FZQloN-.d.mts +62 -0
  53. package/dist/index-7FZQloN-.d.ts +62 -0
  54. package/dist/index-7XgaTVH5.d.mts +93 -0
  55. package/dist/index-7XgaTVH5.d.ts +93 -0
  56. package/dist/index-7bvFmh45.d.mts +87 -0
  57. package/dist/index-7bvFmh45.d.ts +87 -0
  58. package/dist/index-BDZcIVCU.d.mts +53 -0
  59. package/dist/index-BDZcIVCU.d.ts +53 -0
  60. package/dist/index-BN00EnUU.d.mts +55 -0
  61. package/dist/index-BN00EnUU.d.ts +55 -0
  62. package/dist/index-CQ1EukC4.d.mts +59 -0
  63. package/dist/index-CQ1EukC4.d.ts +59 -0
  64. package/dist/index-CgRVnFOt.d.mts +91 -0
  65. package/dist/index-CgRVnFOt.d.ts +91 -0
  66. package/dist/index-DjBDZzuj.d.mts +54 -0
  67. package/dist/index-DjBDZzuj.d.ts +54 -0
  68. package/dist/index-FFrvmr-n.d.mts +50 -0
  69. package/dist/index-FFrvmr-n.d.ts +50 -0
  70. package/dist/index-QWC8yIgW.d.mts +106 -0
  71. package/dist/index-QWC8yIgW.d.ts +106 -0
  72. package/dist/index-RVqNunxE.d.mts +193 -0
  73. package/dist/index-RVqNunxE.d.ts +193 -0
  74. package/dist/index-fJD8SORm.d.mts +61 -0
  75. package/dist/index-fJD8SORm.d.ts +61 -0
  76. package/dist/index-pPy_XDQU.d.mts +56 -0
  77. package/dist/index-pPy_XDQU.d.ts +56 -0
  78. package/dist/index-rwh9hdD9.d.mts +68 -0
  79. package/dist/index-rwh9hdD9.d.ts +68 -0
  80. package/dist/index-uXdkAfea.d.mts +93 -0
  81. package/dist/index-uXdkAfea.d.ts +93 -0
  82. package/dist/index.d.mts +17 -0
  83. package/dist/index.d.ts +17 -0
  84. package/dist/index.js +3744 -0
  85. package/dist/index.js.map +1 -0
  86. package/dist/index.mjs +3694 -0
  87. package/dist/index.mjs.map +1 -0
  88. package/dist/json/index.d.mts +1 -0
  89. package/dist/json/index.d.ts +1 -0
  90. package/dist/json/index.js +599 -0
  91. package/dist/json/index.js.map +1 -0
  92. package/dist/json/index.mjs +552 -0
  93. package/dist/json/index.mjs.map +1 -0
  94. package/dist/markdown/index.d.mts +1 -0
  95. package/dist/markdown/index.d.ts +1 -0
  96. package/dist/markdown/index.js +151 -0
  97. package/dist/markdown/index.js.map +1 -0
  98. package/dist/markdown/index.mjs +139 -0
  99. package/dist/markdown/index.mjs.map +1 -0
  100. package/dist/math/index.d.mts +1 -0
  101. package/dist/math/index.d.ts +1 -0
  102. package/dist/math/index.js +247 -0
  103. package/dist/math/index.js.map +1 -0
  104. package/dist/math/index.mjs +240 -0
  105. package/dist/math/index.mjs.map +1 -0
  106. package/dist/pdf/index.d.mts +1 -0
  107. package/dist/pdf/index.d.ts +1 -0
  108. package/dist/pdf/index.js +546 -0
  109. package/dist/pdf/index.js.map +1 -0
  110. package/dist/pdf/index.mjs +518 -0
  111. package/dist/pdf/index.mjs.map +1 -0
  112. package/dist/regex/index.d.mts +1 -0
  113. package/dist/regex/index.d.ts +1 -0
  114. package/dist/regex/index.js +93 -0
  115. package/dist/regex/index.js.map +1 -0
  116. package/dist/regex/index.mjs +88 -0
  117. package/dist/regex/index.mjs.map +1 -0
  118. package/dist/settings/index.d.mts +41 -0
  119. package/dist/settings/index.d.ts +41 -0
  120. package/dist/settings/index.js +146 -0
  121. package/dist/settings/index.js.map +1 -0
  122. package/dist/settings/index.mjs +139 -0
  123. package/dist/settings/index.mjs.map +1 -0
  124. package/dist/sql/index.d.mts +1 -0
  125. package/dist/sql/index.d.ts +1 -0
  126. package/dist/sql/index.js +146 -0
  127. package/dist/sql/index.js.map +1 -0
  128. package/dist/sql/index.mjs +139 -0
  129. package/dist/sql/index.mjs.map +1 -0
  130. package/dist/text/index.d.mts +1 -0
  131. package/dist/text/index.d.ts +1 -0
  132. package/dist/text/index.js +250 -0
  133. package/dist/text/index.js.map +1 -0
  134. package/dist/text/index.mjs +242 -0
  135. package/dist/text/index.mjs.map +1 -0
  136. package/dist/xml/index.d.mts +1 -0
  137. package/dist/xml/index.d.ts +1 -0
  138. package/dist/xml/index.js +188 -0
  139. package/dist/xml/index.js.map +1 -0
  140. package/dist/xml/index.mjs +180 -0
  141. package/dist/xml/index.mjs.map +1 -0
  142. package/package.json +150 -0
package/dist/index.js ADDED
@@ -0,0 +1,3744 @@
1
+ 'use strict';
2
+
3
+ var Ajv = require('ajv');
4
+ var addFormats = require('ajv-formats');
5
+ var jsonpathPlus = require('jsonpath-plus');
6
+ var jmespath = require('jmespath');
7
+ var JSON5 = require('json5');
8
+ var yaml = require('js-yaml');
9
+ var TOML = require('smol-toml');
10
+ var fastJsonPatch = require('fast-json-patch');
11
+ var Papa = require('papaparse');
12
+ var pdfLib = require('pdf-lib');
13
+ var fastXmlParser = require('fast-xml-parser');
14
+ var ExcelJS = require('exceljs');
15
+ var sharp2 = require('sharp');
16
+ var marked = require('marked');
17
+ var TurndownService = require('turndown');
18
+ var archiver = require('archiver');
19
+ var stream = require('stream');
20
+ var AdmZip = require('adm-zip');
21
+ var diff$1 = require('diff');
22
+ var sqlFormatter = require('sql-formatter');
23
+ var nodeSqlParser = require('node-sql-parser');
24
+ var crypto = require('crypto');
25
+ var luxon = require('luxon');
26
+
27
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
28
+
29
+ function _interopNamespace(e) {
30
+ if (e && e.__esModule) return e;
31
+ var n = Object.create(null);
32
+ if (e) {
33
+ Object.keys(e).forEach(function (k) {
34
+ if (k !== 'default') {
35
+ var d = Object.getOwnPropertyDescriptor(e, k);
36
+ Object.defineProperty(n, k, d.get ? d : {
37
+ enumerable: true,
38
+ get: function () { return e[k]; }
39
+ });
40
+ }
41
+ });
42
+ }
43
+ n.default = e;
44
+ return Object.freeze(n);
45
+ }
46
+
47
+ var Ajv__default = /*#__PURE__*/_interopDefault(Ajv);
48
+ var addFormats__default = /*#__PURE__*/_interopDefault(addFormats);
49
+ var jmespath__default = /*#__PURE__*/_interopDefault(jmespath);
50
+ var JSON5__default = /*#__PURE__*/_interopDefault(JSON5);
51
+ var yaml__default = /*#__PURE__*/_interopDefault(yaml);
52
+ var TOML__namespace = /*#__PURE__*/_interopNamespace(TOML);
53
+ var Papa__default = /*#__PURE__*/_interopDefault(Papa);
54
+ var ExcelJS__default = /*#__PURE__*/_interopDefault(ExcelJS);
55
+ var sharp2__default = /*#__PURE__*/_interopDefault(sharp2);
56
+ var TurndownService__default = /*#__PURE__*/_interopDefault(TurndownService);
57
+ var archiver__default = /*#__PURE__*/_interopDefault(archiver);
58
+ var AdmZip__default = /*#__PURE__*/_interopDefault(AdmZip);
59
+
60
+ var __defProp = Object.defineProperty;
61
+ var __export = (target, all) => {
62
+ for (var name in all)
63
+ __defProp(target, name, { get: all[name], enumerable: true });
64
+ };
65
+
66
+ // src/json/index.ts
67
+ var json_exports = {};
68
+ __export(json_exports, {
69
+ applyPatch: () => applyPatch,
70
+ convert: () => convert,
71
+ detectFormat: () => detectFormat,
72
+ diff: () => diff,
73
+ diffValues: () => diffValues,
74
+ format: () => format,
75
+ fromJson: () => fromJson,
76
+ getSizeInfo: () => getSizeInfo,
77
+ getStats: () => getStats,
78
+ isValidJson: () => isValidJson,
79
+ minify: () => minify,
80
+ parse: () => parse,
81
+ query: () => query,
82
+ queryMultiple: () => queryMultiple,
83
+ queryValue: () => queryValue,
84
+ stringify: () => stringify,
85
+ toJson: () => toJson,
86
+ validate: () => validate,
87
+ validateWithSummary: () => validateWithSummary
88
+ });
89
+
90
+ // src/json/format.ts
91
+ function getIndentString(indent) {
92
+ if (indent === "tab") return " ";
93
+ return indent;
94
+ }
95
+ function sortObjectKeys(obj) {
96
+ if (obj === null || typeof obj !== "object") {
97
+ return obj;
98
+ }
99
+ if (Array.isArray(obj)) {
100
+ return obj.map(sortObjectKeys);
101
+ }
102
+ const sorted = {};
103
+ const keys = Object.keys(obj).sort();
104
+ for (const key of keys) {
105
+ sorted[key] = sortObjectKeys(obj[key]);
106
+ }
107
+ return sorted;
108
+ }
109
+ function format(input, options = {}) {
110
+ const { indent = 2, sortKeys = false } = options;
111
+ let parsed;
112
+ try {
113
+ parsed = JSON.parse(input);
114
+ } catch (error) {
115
+ throw new Error(`Invalid JSON: ${error.message}`);
116
+ }
117
+ if (sortKeys) {
118
+ parsed = sortObjectKeys(parsed);
119
+ }
120
+ const indentValue = getIndentString(indent);
121
+ return JSON.stringify(parsed, null, indentValue);
122
+ }
123
+ function minify(input) {
124
+ const parsed = JSON.parse(input);
125
+ return JSON.stringify(parsed);
126
+ }
127
+ function parse(input) {
128
+ return JSON.parse(input);
129
+ }
130
+ function stringify(value, options = {}) {
131
+ const { indent = 2, sortKeys = false } = options;
132
+ let data = value;
133
+ if (sortKeys) {
134
+ data = sortObjectKeys(value);
135
+ }
136
+ const indentValue = getIndentString(indent);
137
+ return JSON.stringify(data, null, indentValue);
138
+ }
139
+ var ajv = new Ajv__default.default({ allErrors: true, verbose: true });
140
+ addFormats__default.default(ajv);
141
+ function validate(input, schema) {
142
+ let parsed;
143
+ try {
144
+ parsed = JSON.parse(input);
145
+ } catch (error) {
146
+ return {
147
+ valid: false,
148
+ errors: [
149
+ {
150
+ path: "",
151
+ message: `Invalid JSON: ${error.message}`,
152
+ keyword: "parse"
153
+ }
154
+ ]
155
+ };
156
+ }
157
+ if (!schema) {
158
+ return { valid: true };
159
+ }
160
+ let schemaObj;
161
+ try {
162
+ schemaObj = JSON.parse(schema);
163
+ } catch (error) {
164
+ return {
165
+ valid: false,
166
+ errors: [
167
+ {
168
+ path: "",
169
+ message: `Invalid schema: ${error.message}`,
170
+ keyword: "schema"
171
+ }
172
+ ]
173
+ };
174
+ }
175
+ const validateFn = ajv.compile(schemaObj);
176
+ const valid = validateFn(parsed);
177
+ if (valid) {
178
+ return { valid: true };
179
+ }
180
+ const errors = (validateFn.errors || []).map((err) => ({
181
+ path: err.instancePath || "/",
182
+ message: err.message || "Unknown validation error",
183
+ keyword: err.keyword
184
+ }));
185
+ return { valid: false, errors };
186
+ }
187
+ function isValidJson(input) {
188
+ try {
189
+ JSON.parse(input);
190
+ return true;
191
+ } catch {
192
+ return false;
193
+ }
194
+ }
195
+ var ajv2 = new Ajv__default.default({ allErrors: true, verbose: true });
196
+ addFormats__default.default(ajv2);
197
+ function countSchemaProperties(schema) {
198
+ const props = schema.properties;
199
+ const totalProperties = props ? Object.keys(props).length : 0;
200
+ const requiredFields = schema.required || [];
201
+ return { totalProperties, requiredFields };
202
+ }
203
+ function buildSuggestion(err) {
204
+ const path = err.instancePath || "/";
205
+ switch (err.keyword) {
206
+ case "type":
207
+ return `Change value at '${path}' from ${typeof err.data} to ${err.schema}`;
208
+ case "required":
209
+ return `Add missing required field '${err.params?.missingProperty}'`;
210
+ case "enum":
211
+ return `Change value at '${path}' to one of: ${err.schema?.join(", ")}`;
212
+ case "minimum":
213
+ return `Adjust value at '${path}' to be >= ${err.schema}`;
214
+ case "maximum":
215
+ return `Adjust value at '${path}' to be <= ${err.schema}`;
216
+ case "pattern":
217
+ return `Change value at '${path}' to match pattern: ${err.schema}`;
218
+ case "additionalProperties":
219
+ return `Remove unexpected property '${err.params?.additionalProperty}'`;
220
+ case "minLength":
221
+ return `Value at '${path}' must have at least ${err.schema} character(s)`;
222
+ case "maxLength":
223
+ return `Value at '${path}' must have at most ${err.schema} character(s)`;
224
+ case "minItems":
225
+ return `Array at '${path}' must have at least ${err.schema} item(s)`;
226
+ case "maxItems":
227
+ return `Array at '${path}' must have at most ${err.schema} item(s)`;
228
+ case "format":
229
+ return `Value at '${path}' must be a valid ${err.params?.format ?? err.schema}`;
230
+ default:
231
+ return `Fix value at '${path}': ${err.keyword}`;
232
+ }
233
+ }
234
+ function validateWithSummary(input, schema) {
235
+ let parsed;
236
+ try {
237
+ parsed = JSON.parse(input);
238
+ } catch (error) {
239
+ return {
240
+ valid: false,
241
+ summary: `Invalid JSON input: ${error.message}`,
242
+ errorCount: 1,
243
+ errors: [{
244
+ path: "",
245
+ message: `Invalid JSON: ${error.message}`,
246
+ keyword: "parse",
247
+ suggestion: "Fix JSON syntax errors before validating against a schema"
248
+ }],
249
+ coverage: { totalProperties: 0, validProperties: 0, missingRequired: [], extraProperties: [] },
250
+ suggestions: ["Fix JSON syntax errors before validating against a schema"]
251
+ };
252
+ }
253
+ let schemaObj;
254
+ try {
255
+ schemaObj = JSON.parse(schema);
256
+ } catch (error) {
257
+ return {
258
+ valid: false,
259
+ summary: `Invalid JSON Schema: ${error.message}`,
260
+ errorCount: 1,
261
+ errors: [{
262
+ path: "",
263
+ message: `Invalid schema: ${error.message}`,
264
+ keyword: "schema",
265
+ suggestion: "Fix the JSON Schema syntax before validating"
266
+ }],
267
+ coverage: { totalProperties: 0, validProperties: 0, missingRequired: [], extraProperties: [] },
268
+ suggestions: ["Fix the JSON Schema syntax before validating"]
269
+ };
270
+ }
271
+ const { totalProperties } = countSchemaProperties(schemaObj);
272
+ const validateFn = ajv2.compile(schemaObj);
273
+ const valid = validateFn(parsed);
274
+ if (valid) {
275
+ return {
276
+ valid: true,
277
+ summary: `Validation passed. All ${totalProperties} schema properties satisfied (100%).`,
278
+ errorCount: 0,
279
+ errors: [],
280
+ coverage: {
281
+ totalProperties,
282
+ validProperties: totalProperties,
283
+ missingRequired: [],
284
+ extraProperties: []
285
+ },
286
+ suggestions: []
287
+ };
288
+ }
289
+ const ajvErrors = validateFn.errors || [];
290
+ const missingRequired = [];
291
+ const extraProperties = [];
292
+ const errors = ajvErrors.map((err) => {
293
+ if (err.keyword === "required") {
294
+ const field = err.params?.missingProperty;
295
+ if (field) missingRequired.push(field);
296
+ }
297
+ if (err.keyword === "additionalProperties") {
298
+ const prop = err.params?.additionalProperty;
299
+ if (prop) extraProperties.push(prop);
300
+ }
301
+ return {
302
+ path: err.instancePath || "/",
303
+ message: err.message || "Unknown validation error",
304
+ keyword: err.keyword,
305
+ expected: err.schema,
306
+ received: err.data,
307
+ suggestion: buildSuggestion({
308
+ keyword: err.keyword,
309
+ instancePath: err.instancePath,
310
+ params: err.params,
311
+ schema: err.schema,
312
+ data: err.data
313
+ })
314
+ };
315
+ });
316
+ const propertyErrorCount = new Set(
317
+ ajvErrors.filter((e) => e.keyword !== "required" && e.keyword !== "additionalProperties").map((e) => e.instancePath)
318
+ ).size;
319
+ const validProperties = Math.max(0, totalProperties - missingRequired.length - propertyErrorCount);
320
+ const coverage = {
321
+ totalProperties,
322
+ validProperties,
323
+ missingRequired,
324
+ extraProperties
325
+ };
326
+ const pct = totalProperties > 0 ? Math.round(validProperties / totalProperties * 100) : 0;
327
+ const parts = [
328
+ `Validation failed with ${errors.length} error(s).`
329
+ ];
330
+ if (totalProperties > 0) {
331
+ parts.push(`${validProperties} of ${totalProperties} schema properties satisfied (${pct}%).`);
332
+ }
333
+ if (missingRequired.length > 0) {
334
+ parts.push(`Missing required: ${missingRequired.join(", ")}.`);
335
+ }
336
+ if (extraProperties.length > 0) {
337
+ parts.push(`Unexpected properties: ${extraProperties.join(", ")}.`);
338
+ }
339
+ const suggestions = [...new Set(errors.map((e) => e.suggestion))];
340
+ return {
341
+ valid: false,
342
+ summary: parts.join(" "),
343
+ errorCount: errors.length,
344
+ errors,
345
+ coverage,
346
+ suggestions
347
+ };
348
+ }
349
+ function query(input, path, options = {}) {
350
+ const { dialect = "jsonpath" } = options;
351
+ let parsed;
352
+ try {
353
+ parsed = JSON.parse(input);
354
+ } catch (error) {
355
+ throw new Error(`Invalid JSON: ${error.message}`);
356
+ }
357
+ return queryValue(parsed, path, dialect);
358
+ }
359
+ function queryValue(data, path, dialect = "jsonpath") {
360
+ if (dialect === "jsonpath") {
361
+ return jsonpathPlus.JSONPath({ path, json: data, wrap: false });
362
+ }
363
+ if (dialect === "jmespath") {
364
+ return jmespath__default.default.search(data, path);
365
+ }
366
+ throw new Error(`Unknown query dialect: ${dialect}`);
367
+ }
368
+ function queryMultiple(input, paths, dialect = "jsonpath") {
369
+ let parsed;
370
+ try {
371
+ parsed = JSON.parse(input);
372
+ } catch (error) {
373
+ throw new Error(`Invalid JSON: ${error.message}`);
374
+ }
375
+ const results = {};
376
+ for (const path of paths) {
377
+ results[path] = queryValue(parsed, path, dialect);
378
+ }
379
+ return results;
380
+ }
381
+ function getIndent(indent = 2) {
382
+ if (indent === "tab") return 2;
383
+ return indent;
384
+ }
385
+ function parseInput(input, from) {
386
+ switch (from) {
387
+ case "json":
388
+ return JSON.parse(input);
389
+ case "json5":
390
+ case "jsonc":
391
+ return JSON5__default.default.parse(input);
392
+ case "yaml":
393
+ return yaml__default.default.load(input);
394
+ case "toml":
395
+ return TOML__namespace.parse(input);
396
+ default:
397
+ throw new Error(`Unsupported input format: ${from}`);
398
+ }
399
+ }
400
+ function stringifyOutput(data, to, indent = 2) {
401
+ const indentNum = getIndent(indent);
402
+ switch (to) {
403
+ case "json":
404
+ return JSON.stringify(data, null, indentNum);
405
+ case "json5":
406
+ case "jsonc":
407
+ return JSON5__default.default.stringify(data, null, indentNum);
408
+ case "yaml":
409
+ return yaml__default.default.dump(data, { indent: indentNum, lineWidth: -1 });
410
+ case "toml":
411
+ if (typeof data !== "object" || data === null || Array.isArray(data)) {
412
+ throw new Error("TOML requires a root object");
413
+ }
414
+ return TOML__namespace.stringify(data);
415
+ default:
416
+ throw new Error(`Unsupported output format: ${to}`);
417
+ }
418
+ }
419
+ function convert(input, options) {
420
+ const { from, to, indent = 2 } = options;
421
+ if (from === to) {
422
+ const parsed2 = parseInput(input, from);
423
+ return stringifyOutput(parsed2, to, indent);
424
+ }
425
+ const parsed = parseInput(input, from);
426
+ return stringifyOutput(parsed, to, indent);
427
+ }
428
+ function toJson(input, from) {
429
+ return convert(input, { from, to: "json" });
430
+ }
431
+ function fromJson(input, to) {
432
+ return convert(input, { from: "json", to });
433
+ }
434
+ function detectFormat(input) {
435
+ const trimmed = input.trim();
436
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
437
+ try {
438
+ JSON.parse(trimmed);
439
+ return "json";
440
+ } catch {
441
+ try {
442
+ JSON5__default.default.parse(trimmed);
443
+ return "json5";
444
+ } catch {
445
+ return null;
446
+ }
447
+ }
448
+ }
449
+ if (trimmed.includes(":") && !trimmed.includes("=")) {
450
+ try {
451
+ yaml__default.default.load(trimmed);
452
+ return "yaml";
453
+ } catch {
454
+ return null;
455
+ }
456
+ }
457
+ if (trimmed.includes("=") && (trimmed.includes("[") || trimmed.includes('"'))) {
458
+ try {
459
+ TOML__namespace.parse(trimmed);
460
+ return "toml";
461
+ } catch {
462
+ return null;
463
+ }
464
+ }
465
+ return null;
466
+ }
467
+ function diff(a, b) {
468
+ let parsedA;
469
+ let parsedB;
470
+ try {
471
+ parsedA = JSON.parse(a);
472
+ } catch (error) {
473
+ throw new Error(`Invalid JSON (first argument): ${error.message}`);
474
+ }
475
+ try {
476
+ parsedB = JSON.parse(b);
477
+ } catch (error) {
478
+ throw new Error(`Invalid JSON (second argument): ${error.message}`);
479
+ }
480
+ return diffValues(parsedA, parsedB);
481
+ }
482
+ function diffValues(a, b) {
483
+ const operations = fastJsonPatch.compare(
484
+ a,
485
+ b
486
+ );
487
+ const summary = {
488
+ added: 0,
489
+ removed: 0,
490
+ changed: 0
491
+ };
492
+ for (const op of operations) {
493
+ switch (op.op) {
494
+ case "add":
495
+ summary.added++;
496
+ break;
497
+ case "remove":
498
+ summary.removed++;
499
+ break;
500
+ case "replace":
501
+ summary.changed++;
502
+ break;
503
+ }
504
+ }
505
+ return {
506
+ identical: operations.length === 0,
507
+ operations,
508
+ summary
509
+ };
510
+ }
511
+ function applyPatch(input, operations) {
512
+ const parsed = JSON.parse(input);
513
+ for (const op of operations) {
514
+ applyOperation(parsed, op);
515
+ }
516
+ return JSON.stringify(parsed, null, 2);
517
+ }
518
+ function applyOperation(obj, operation) {
519
+ const pathParts = operation.path.split("/").filter(Boolean);
520
+ if (pathParts.length === 0) {
521
+ throw new Error("Cannot apply operation to root");
522
+ }
523
+ const parent = getParent(obj, pathParts);
524
+ const key = pathParts[pathParts.length - 1];
525
+ switch (operation.op) {
526
+ case "add":
527
+ case "replace":
528
+ if (Array.isArray(parent)) {
529
+ const index = parseInt(key, 10);
530
+ if (operation.op === "add") {
531
+ parent.splice(index, 0, operation.value);
532
+ } else {
533
+ parent[index] = operation.value;
534
+ }
535
+ } else if (typeof parent === "object" && parent !== null) {
536
+ parent[key] = operation.value;
537
+ }
538
+ break;
539
+ case "remove":
540
+ if (Array.isArray(parent)) {
541
+ parent.splice(parseInt(key, 10), 1);
542
+ } else if (typeof parent === "object" && parent !== null) {
543
+ delete parent[key];
544
+ }
545
+ break;
546
+ }
547
+ }
548
+ function getParent(obj, pathParts) {
549
+ let current = obj;
550
+ for (let i = 0; i < pathParts.length - 1; i++) {
551
+ const part = pathParts[i];
552
+ if (Array.isArray(current)) {
553
+ current = current[parseInt(part, 10)];
554
+ } else if (typeof current === "object" && current !== null) {
555
+ current = current[part];
556
+ }
557
+ }
558
+ return current;
559
+ }
560
+
561
+ // src/json/stats.ts
562
+ function getStats(input) {
563
+ const parsed = JSON.parse(input);
564
+ const stats = {
565
+ keys: 0,
566
+ depth: 0,
567
+ arrays: 0,
568
+ objects: 0,
569
+ strings: 0,
570
+ numbers: 0,
571
+ booleans: 0,
572
+ nulls: 0,
573
+ sizeBytes: new TextEncoder().encode(input).length
574
+ };
575
+ analyzeValue(parsed, stats, 0);
576
+ return stats;
577
+ }
578
+ function analyzeValue(value, stats, depth) {
579
+ stats.depth = Math.max(stats.depth, depth);
580
+ if (value === null) {
581
+ stats.nulls++;
582
+ return;
583
+ }
584
+ switch (typeof value) {
585
+ case "string":
586
+ stats.strings++;
587
+ break;
588
+ case "number":
589
+ stats.numbers++;
590
+ break;
591
+ case "boolean":
592
+ stats.booleans++;
593
+ break;
594
+ case "object":
595
+ if (Array.isArray(value)) {
596
+ stats.arrays++;
597
+ for (const item of value) {
598
+ analyzeValue(item, stats, depth + 1);
599
+ }
600
+ } else {
601
+ stats.objects++;
602
+ const keys = Object.keys(value);
603
+ stats.keys += keys.length;
604
+ for (const key of keys) {
605
+ analyzeValue(value[key], stats, depth + 1);
606
+ }
607
+ }
608
+ break;
609
+ }
610
+ }
611
+ function getSizeInfo(input) {
612
+ const bytes = new TextEncoder().encode(input).length;
613
+ const minified = JSON.stringify(JSON.parse(input));
614
+ const minifiedBytes = new TextEncoder().encode(minified).length;
615
+ return {
616
+ bytes,
617
+ formatted: formatBytes(bytes),
618
+ minifiedBytes,
619
+ savings: bytes - minifiedBytes
620
+ };
621
+ }
622
+ function formatBytes(bytes) {
623
+ if (bytes === 0) return "0 B";
624
+ const k = 1024;
625
+ const sizes = ["B", "KB", "MB", "GB"];
626
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
627
+ return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
628
+ }
629
+
630
+ // src/csv/index.ts
631
+ var csv_exports = {};
632
+ __export(csv_exports, {
633
+ detectDelimiter: () => detectDelimiter,
634
+ exportData: () => exportData,
635
+ exportFromData: () => exportFromData,
636
+ filter: () => filter,
637
+ filterByColumn: () => filterByColumn,
638
+ filterData: () => filterData,
639
+ getColumnStats: () => getColumnStats,
640
+ getHeaders: () => getHeaders,
641
+ getStats: () => getStats2,
642
+ getStatsFromData: () => getStatsFromData,
643
+ parse: () => parse3,
644
+ parseToArray: () => parseToArray,
645
+ sortData: () => sortData,
646
+ toArray: () => toArray,
647
+ toJson: () => toJson2,
648
+ toJsonLines: () => toJsonLines,
649
+ transform: () => transform,
650
+ transformData: () => transformData
651
+ });
652
+ function parse3(input, options = {}) {
653
+ const {
654
+ delimiter = ",",
655
+ header = true,
656
+ skipRows = 0,
657
+ trimFields = true,
658
+ dynamicTyping = true
659
+ } = options;
660
+ let processedInput = input;
661
+ if (skipRows > 0) {
662
+ const lines = input.split("\n");
663
+ processedInput = lines.slice(skipRows).join("\n");
664
+ }
665
+ const result = Papa__default.default.parse(processedInput, {
666
+ delimiter,
667
+ header,
668
+ skipEmptyLines: true,
669
+ transformHeader: trimFields ? (h) => h.trim() : void 0,
670
+ transform: trimFields ? (v) => v.trim() : void 0,
671
+ dynamicTyping
672
+ });
673
+ const errors = result.errors.map((e) => ({
674
+ row: e.row ?? -1,
675
+ message: e.message
676
+ }));
677
+ const headers = header ? result.meta.fields || [] : Array.from({ length: result.data[0]?.length || 0 }, (_, i) => `col_${i}`);
678
+ const data = header ? result.data : result.data.map((row) => {
679
+ const obj = {};
680
+ headers.forEach((h, i) => {
681
+ obj[h] = row[i];
682
+ });
683
+ return obj;
684
+ });
685
+ return {
686
+ data,
687
+ headers,
688
+ rowCount: data.length,
689
+ errors
690
+ };
691
+ }
692
+ function parseToArray(input, options = {}) {
693
+ const result = parse3(input, { ...options, header: false });
694
+ return result.data.map((row) => Object.values(row));
695
+ }
696
+ function detectDelimiter(input) {
697
+ const delimiters = [",", " ", ";", "|"];
698
+ const firstLine = input.split("\n")[0];
699
+ let maxCount = 0;
700
+ let detected = ",";
701
+ for (const d of delimiters) {
702
+ const count = (firstLine.match(new RegExp(`\\${d}`, "g")) || []).length;
703
+ if (count > maxCount) {
704
+ maxCount = count;
705
+ detected = d;
706
+ }
707
+ }
708
+ return detected;
709
+ }
710
+ function getHeaders(input, delimiter) {
711
+ const d = delimiter || detectDelimiter(input);
712
+ const firstLine = input.split("\n")[0];
713
+ return Papa__default.default.parse(firstLine, { delimiter: d }).data[0];
714
+ }
715
+
716
+ // src/csv/filter.ts
717
+ function filter(input, filters) {
718
+ const result = parse3(input);
719
+ const filteredData = filterData(result.data, filters);
720
+ return toCSV(filteredData, result.headers);
721
+ }
722
+ function filterData(data, filters) {
723
+ return data.filter((row) => {
724
+ return filters.every((f) => matchesFilter(row, f));
725
+ });
726
+ }
727
+ function matchesFilter(row, filter2) {
728
+ const value = row[filter2.column];
729
+ const filterValue = filter2.value;
730
+ switch (filter2.operator) {
731
+ case "eq":
732
+ return value === filterValue;
733
+ case "neq":
734
+ return value !== filterValue;
735
+ case "gt":
736
+ return Number(value) > Number(filterValue);
737
+ case "gte":
738
+ return Number(value) >= Number(filterValue);
739
+ case "lt":
740
+ return Number(value) < Number(filterValue);
741
+ case "lte":
742
+ return Number(value) <= Number(filterValue);
743
+ case "contains":
744
+ return String(value).toLowerCase().includes(String(filterValue).toLowerCase());
745
+ case "startsWith":
746
+ return String(value).toLowerCase().startsWith(String(filterValue).toLowerCase());
747
+ case "endsWith":
748
+ return String(value).toLowerCase().endsWith(String(filterValue).toLowerCase());
749
+ case "matches":
750
+ return new RegExp(String(filterValue), "i").test(String(value));
751
+ case "isNull":
752
+ return value === null || value === void 0 || value === "";
753
+ case "isNotNull":
754
+ return value !== null && value !== void 0 && value !== "";
755
+ default:
756
+ return true;
757
+ }
758
+ }
759
+ function toCSV(data, headers) {
760
+ const headerRow = headers.map(escapeCSVField).join(",");
761
+ const dataRows = data.map(
762
+ (row) => headers.map((h) => escapeCSVField(row[h])).join(",")
763
+ );
764
+ return [headerRow, ...dataRows].join("\n");
765
+ }
766
+ function escapeCSVField(value) {
767
+ if (value === null || value === void 0) {
768
+ return "";
769
+ }
770
+ const str = String(value);
771
+ if (str.includes(",") || str.includes('"') || str.includes("\n")) {
772
+ return `"${str.replace(/"/g, '""')}"`;
773
+ }
774
+ return str;
775
+ }
776
+ function filterByColumn(input, column, operator, value) {
777
+ return filter(input, [{ column, operator, value }]);
778
+ }
779
+
780
+ // src/csv/stats.ts
781
+ function getStats2(input) {
782
+ const result = parse3(input);
783
+ return getStatsFromData(result);
784
+ }
785
+ function getStatsFromData(result) {
786
+ const { data, headers } = result;
787
+ return headers.map((header) => {
788
+ const values = data.map((row) => row[header]);
789
+ return analyzeColumn(header, values);
790
+ });
791
+ }
792
+ function analyzeColumn(name, values) {
793
+ const nonNullValues = values.filter(
794
+ (v) => v !== null && v !== void 0 && v !== ""
795
+ );
796
+ const nullCount = values.length - nonNullValues.length;
797
+ const type = detectType(nonNullValues);
798
+ const stats = {
799
+ name,
800
+ type,
801
+ count: values.length,
802
+ nullCount,
803
+ uniqueCount: new Set(nonNullValues.map(String)).size
804
+ };
805
+ if (type === "number") {
806
+ const numbers = nonNullValues.map(Number).filter((n) => !isNaN(n));
807
+ if (numbers.length > 0) {
808
+ stats.min = Math.min(...numbers);
809
+ stats.max = Math.max(...numbers);
810
+ stats.sum = numbers.reduce((a, b) => a + b, 0);
811
+ stats.mean = stats.sum / numbers.length;
812
+ }
813
+ } else if (type === "string" || type === "date") {
814
+ const sorted = [...nonNullValues].map(String).sort();
815
+ if (sorted.length > 0) {
816
+ stats.min = sorted[0];
817
+ stats.max = sorted[sorted.length - 1];
818
+ }
819
+ }
820
+ stats.topValues = getTopValues(nonNullValues, 5);
821
+ return stats;
822
+ }
823
+ function detectType(values) {
824
+ if (values.length === 0) return "empty";
825
+ const types = /* @__PURE__ */ new Set();
826
+ for (const value of values) {
827
+ if (typeof value === "number" || !isNaN(Number(value))) {
828
+ types.add("number");
829
+ } else if (typeof value === "boolean" || value === "true" || value === "false") {
830
+ types.add("boolean");
831
+ } else if (isDateLike(String(value))) {
832
+ types.add("date");
833
+ } else {
834
+ types.add("string");
835
+ }
836
+ }
837
+ if (types.size === 1) {
838
+ return types.values().next().value;
839
+ }
840
+ if (types.size === 2 && types.has("number") && types.has("string")) {
841
+ const numberRatio = values.filter((v) => !isNaN(Number(v))).length / values.length;
842
+ if (numberRatio > 0.9) return "number";
843
+ }
844
+ return "mixed";
845
+ }
846
+ function isDateLike(value) {
847
+ const datePatterns = [
848
+ /^\d{4}-\d{2}-\d{2}$/,
849
+ /^\d{2}\/\d{2}\/\d{4}$/,
850
+ /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/
851
+ ];
852
+ return datePatterns.some((p) => p.test(value));
853
+ }
854
+ function getTopValues(values, limit) {
855
+ const counts = /* @__PURE__ */ new Map();
856
+ for (const value of values) {
857
+ const key = String(value);
858
+ const existing = counts.get(key);
859
+ if (existing) {
860
+ existing.count++;
861
+ } else {
862
+ counts.set(key, { value, count: 1 });
863
+ }
864
+ }
865
+ return [...counts.values()].sort((a, b) => b.count - a.count).slice(0, limit);
866
+ }
867
+ function getColumnStats(input, column) {
868
+ const stats = getStats2(input);
869
+ return stats.find((s) => s.name === column) || null;
870
+ }
871
+
872
+ // src/csv/transform.ts
873
+ function transform(input, options) {
874
+ const result = parse3(input);
875
+ const transformed = transformData(result, options);
876
+ return toCSV2(transformed.data, transformed.headers);
877
+ }
878
+ function transformData(result, options) {
879
+ let { data, headers } = result;
880
+ if (options.select) {
881
+ headers = options.select.filter((h) => headers.includes(h));
882
+ }
883
+ if (options.exclude) {
884
+ headers = headers.filter((h) => !options.exclude.includes(h));
885
+ }
886
+ if (options.rename) {
887
+ headers = headers.map((h) => options.rename[h] || h);
888
+ }
889
+ data = data.map((row) => {
890
+ const newRow = {};
891
+ for (const header of result.headers) {
892
+ if (options.select && !options.select.includes(header)) continue;
893
+ if (options.exclude && options.exclude.includes(header)) continue;
894
+ const newKey = options.rename?.[header] || header;
895
+ newRow[newKey] = row[header];
896
+ }
897
+ if (options.derive) {
898
+ for (const [key, fn] of Object.entries(options.derive)) {
899
+ newRow[key] = fn(row);
900
+ }
901
+ }
902
+ return newRow;
903
+ });
904
+ if (options.derive) {
905
+ headers = [...headers, ...Object.keys(options.derive)];
906
+ }
907
+ return { data, headers, rowCount: data.length, errors: [] };
908
+ }
909
+ function toCSV2(data, headers) {
910
+ const headerRow = headers.map(escapeCSVField2).join(",");
911
+ const dataRows = data.map(
912
+ (row) => headers.map((h) => escapeCSVField2(row[h])).join(",")
913
+ );
914
+ return [headerRow, ...dataRows].join("\n");
915
+ }
916
+ function escapeCSVField2(value) {
917
+ if (value === null || value === void 0) {
918
+ return "";
919
+ }
920
+ const str = String(value);
921
+ if (str.includes(",") || str.includes('"') || str.includes("\n")) {
922
+ return `"${str.replace(/"/g, '""')}"`;
923
+ }
924
+ return str;
925
+ }
926
+ function sortData(data, column, direction = "asc") {
927
+ return [...data].sort((a, b) => {
928
+ const aVal = a[column];
929
+ const bVal = b[column];
930
+ if (aVal === bVal) return 0;
931
+ if (aVal === null || aVal === void 0) return 1;
932
+ if (bVal === null || bVal === void 0) return -1;
933
+ const comparison = typeof aVal === "number" && typeof bVal === "number" ? aVal - bVal : String(aVal).localeCompare(String(bVal));
934
+ return direction === "asc" ? comparison : -comparison;
935
+ });
936
+ }
937
+
938
+ // src/csv/export.ts
939
+ function exportData(input, options) {
940
+ const result = parse3(input);
941
+ return exportFromData(result, options);
942
+ }
943
+ function exportFromData(result, options) {
944
+ const { format: format4, headers = true, delimiter } = options;
945
+ switch (format4) {
946
+ case "csv":
947
+ return toCSV3(result.data, result.headers, delimiter || ",", headers);
948
+ case "tsv":
949
+ return toCSV3(result.data, result.headers, " ", headers);
950
+ case "json":
951
+ return JSON.stringify(result.data, null, 2);
952
+ case "jsonl":
953
+ return result.data.map((row) => JSON.stringify(row)).join("\n");
954
+ default:
955
+ throw new Error(`Unsupported export format: ${format4}`);
956
+ }
957
+ }
958
+ function toCSV3(data, headers, delimiter, includeHeaders) {
959
+ const lines = [];
960
+ if (includeHeaders) {
961
+ lines.push(headers.map((h) => escapeField(h, delimiter)).join(delimiter));
962
+ }
963
+ for (const row of data) {
964
+ lines.push(
965
+ headers.map((h) => escapeField(row[h], delimiter)).join(delimiter)
966
+ );
967
+ }
968
+ return lines.join("\n");
969
+ }
970
+ function escapeField(value, delimiter) {
971
+ if (value === null || value === void 0) {
972
+ return "";
973
+ }
974
+ const str = String(value);
975
+ const needsQuoting = str.includes(delimiter) || str.includes('"') || str.includes("\n");
976
+ if (needsQuoting) {
977
+ return `"${str.replace(/"/g, '""')}"`;
978
+ }
979
+ return str;
980
+ }
981
+ function toJson2(input, pretty = true) {
982
+ const result = parse3(input);
983
+ return pretty ? JSON.stringify(result.data, null, 2) : JSON.stringify(result.data);
984
+ }
985
+ function toJsonLines(input) {
986
+ const result = parse3(input);
987
+ return result.data.map((row) => JSON.stringify(row)).join("\n");
988
+ }
989
+ function toArray(input) {
990
+ const result = parse3(input);
991
+ return result.data;
992
+ }
993
+
994
+ // src/pdf/index.ts
995
+ var pdf_exports = {};
996
+ __export(pdf_exports, {
997
+ addWatermark: () => addWatermark,
998
+ appendPages: () => appendPages,
999
+ compress: () => compress,
1000
+ deletePage: () => deletePage,
1001
+ extractPages: () => extractPages,
1002
+ extractText: () => extractText,
1003
+ extractTextFromPages: () => extractTextFromPages,
1004
+ formatBytes: () => formatBytes2,
1005
+ getInfo: () => getInfo,
1006
+ getMetadata: () => getMetadata,
1007
+ getPageCount: () => getPageCount,
1008
+ getPageInfo: () => getPageInfo,
1009
+ hasText: () => hasText,
1010
+ merge: () => merge,
1011
+ mergeAll: () => mergeAll,
1012
+ parsePageRanges: () => parsePageRanges,
1013
+ parseRangesToGroups: () => parseRangesToGroups,
1014
+ pdfToTemplate: () => pdfToTemplate,
1015
+ reorderPages: () => reorderPages,
1016
+ rotate: () => rotate,
1017
+ setMetadata: () => setMetadata,
1018
+ split: () => split,
1019
+ splitEveryN: () => splitEveryN,
1020
+ splitIntoSingle: () => splitIntoSingle,
1021
+ templateToPdf: () => templateToPdf,
1022
+ toUint8Array: () => toUint8Array,
1023
+ validateTemplate: () => validateTemplate
1024
+ });
1025
+
1026
+ // src/pdf/utils.ts
1027
+ function parsePageRanges(rangeStr, totalPages) {
1028
+ const pages = /* @__PURE__ */ new Set();
1029
+ const parts = rangeStr.split(",").map((s) => s.trim());
1030
+ for (const part of parts) {
1031
+ if (part.toLowerCase() === "all") {
1032
+ for (let i = 1; i <= totalPages; i++) {
1033
+ pages.add(i);
1034
+ }
1035
+ continue;
1036
+ }
1037
+ if (part.includes("-")) {
1038
+ const [startStr, endStr] = part.split("-").map((s) => s.trim());
1039
+ const start = parseInt(startStr, 10) || 1;
1040
+ const end = parseInt(endStr, 10) || totalPages;
1041
+ for (let i = Math.max(1, start); i <= Math.min(totalPages, end); i++) {
1042
+ pages.add(i);
1043
+ }
1044
+ } else {
1045
+ const page = parseInt(part, 10);
1046
+ if (page >= 1 && page <= totalPages) {
1047
+ pages.add(page);
1048
+ }
1049
+ }
1050
+ }
1051
+ return [...pages].sort((a, b) => a - b);
1052
+ }
1053
+ function parseRangesToGroups(rangeStr, totalPages) {
1054
+ const ranges = [];
1055
+ const parts = rangeStr.split(",").map((s) => s.trim());
1056
+ for (const part of parts) {
1057
+ if (part.toLowerCase() === "all") {
1058
+ ranges.push({ start: 1, end: totalPages });
1059
+ continue;
1060
+ }
1061
+ if (part.includes("-")) {
1062
+ const [startStr, endStr] = part.split("-").map((s) => s.trim());
1063
+ const start = parseInt(startStr, 10) || 1;
1064
+ const end = parseInt(endStr, 10) || totalPages;
1065
+ ranges.push({
1066
+ start: Math.max(1, start),
1067
+ end: Math.min(totalPages, end)
1068
+ });
1069
+ } else {
1070
+ const page = parseInt(part, 10);
1071
+ if (page >= 1 && page <= totalPages) {
1072
+ ranges.push({ start: page, end: page });
1073
+ }
1074
+ }
1075
+ }
1076
+ return ranges;
1077
+ }
1078
+ function formatBytes2(bytes) {
1079
+ if (bytes === 0) return "0 B";
1080
+ const k = 1024;
1081
+ const sizes = ["B", "KB", "MB", "GB"];
1082
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
1083
+ return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
1084
+ }
1085
+ function toUint8Array(data) {
1086
+ if (data instanceof Uint8Array) {
1087
+ return data;
1088
+ }
1089
+ if (data instanceof ArrayBuffer) {
1090
+ return new Uint8Array(data);
1091
+ }
1092
+ if (Buffer.isBuffer(data)) {
1093
+ return new Uint8Array(data);
1094
+ }
1095
+ throw new Error("Invalid data type");
1096
+ }
1097
+ async function merge(files, options = {}) {
1098
+ const { pageRanges } = options;
1099
+ const mergedPdf = await pdfLib.PDFDocument.create();
1100
+ for (let i = 0; i < files.length; i++) {
1101
+ const fileData = toUint8Array(files[i]);
1102
+ const sourcePdf = await pdfLib.PDFDocument.load(fileData);
1103
+ const totalPages = sourcePdf.getPageCount();
1104
+ let pagesToCopy;
1105
+ if (pageRanges && pageRanges[i]) {
1106
+ pagesToCopy = parsePageRanges(pageRanges[i], totalPages);
1107
+ } else {
1108
+ pagesToCopy = Array.from({ length: totalPages }, (_, j) => j + 1);
1109
+ }
1110
+ const pageIndices = pagesToCopy.map((p) => p - 1);
1111
+ const copiedPages = await mergedPdf.copyPages(sourcePdf, pageIndices);
1112
+ for (const page of copiedPages) {
1113
+ mergedPdf.addPage(page);
1114
+ }
1115
+ }
1116
+ return mergedPdf.save();
1117
+ }
1118
+ async function mergeAll(files) {
1119
+ return merge(files);
1120
+ }
1121
+ async function appendPages(target, source, pageRange) {
1122
+ const targetPdf = await pdfLib.PDFDocument.load(toUint8Array(target));
1123
+ const sourcePdf = await pdfLib.PDFDocument.load(toUint8Array(source));
1124
+ const totalPages = sourcePdf.getPageCount();
1125
+ const pagesToCopy = pageRange ? parsePageRanges(pageRange, totalPages) : Array.from({ length: totalPages }, (_, i) => i + 1);
1126
+ const pageIndices = pagesToCopy.map((p) => p - 1);
1127
+ const copiedPages = await targetPdf.copyPages(sourcePdf, pageIndices);
1128
+ for (const page of copiedPages) {
1129
+ targetPdf.addPage(page);
1130
+ }
1131
+ return targetPdf.save();
1132
+ }
1133
+ async function split(file, options) {
1134
+ const { ranges } = options;
1135
+ const fileData = toUint8Array(file);
1136
+ const sourcePdf = await pdfLib.PDFDocument.load(fileData);
1137
+ const totalPages = sourcePdf.getPageCount();
1138
+ const rangeGroups = parseRangesToGroups(ranges, totalPages);
1139
+ const results = [];
1140
+ for (const range of rangeGroups) {
1141
+ const newPdf = await pdfLib.PDFDocument.create();
1142
+ const pageIndices = [];
1143
+ for (let i = range.start; i <= range.end; i++) {
1144
+ pageIndices.push(i - 1);
1145
+ }
1146
+ const copiedPages = await newPdf.copyPages(sourcePdf, pageIndices);
1147
+ for (const page of copiedPages) {
1148
+ newPdf.addPage(page);
1149
+ }
1150
+ results.push(await newPdf.save());
1151
+ }
1152
+ return results;
1153
+ }
1154
+ async function extractPages(file, pageRange) {
1155
+ const fileData = toUint8Array(file);
1156
+ const sourcePdf = await pdfLib.PDFDocument.load(fileData);
1157
+ const totalPages = sourcePdf.getPageCount();
1158
+ const pages = parsePageRanges(pageRange, totalPages);
1159
+ const newPdf = await pdfLib.PDFDocument.create();
1160
+ const pageIndices = pages.map((p) => p - 1);
1161
+ const copiedPages = await newPdf.copyPages(sourcePdf, pageIndices);
1162
+ for (const page of copiedPages) {
1163
+ newPdf.addPage(page);
1164
+ }
1165
+ return newPdf.save();
1166
+ }
1167
+ async function splitEveryN(file, n) {
1168
+ const fileData = toUint8Array(file);
1169
+ const sourcePdf = await pdfLib.PDFDocument.load(fileData);
1170
+ const totalPages = sourcePdf.getPageCount();
1171
+ const ranges = [];
1172
+ for (let i = 1; i <= totalPages; i += n) {
1173
+ const end = Math.min(i + n - 1, totalPages);
1174
+ ranges.push(`${i}-${end}`);
1175
+ }
1176
+ return split(file, { ranges: ranges.join(",") });
1177
+ }
1178
+ async function splitIntoSingle(file) {
1179
+ return splitEveryN(file, 1);
1180
+ }
1181
+ async function getInfo(file) {
1182
+ const fileData = toUint8Array(file);
1183
+ const pdf = await pdfLib.PDFDocument.load(fileData, { ignoreEncryption: true });
1184
+ return {
1185
+ pageCount: pdf.getPageCount(),
1186
+ metadata: {
1187
+ title: pdf.getTitle(),
1188
+ author: pdf.getAuthor(),
1189
+ subject: pdf.getSubject(),
1190
+ keywords: pdf.getKeywords()?.split(",").map((k) => k.trim()),
1191
+ creator: pdf.getCreator(),
1192
+ producer: pdf.getProducer(),
1193
+ creationDate: pdf.getCreationDate(),
1194
+ modificationDate: pdf.getModificationDate()
1195
+ },
1196
+ encrypted: false,
1197
+ version: "PDF-1.7"
1198
+ };
1199
+ }
1200
+ async function getMetadata(file) {
1201
+ const info = await getInfo(file);
1202
+ return info.metadata;
1203
+ }
1204
+ async function setMetadata(file, metadata) {
1205
+ const fileData = toUint8Array(file);
1206
+ const pdf = await pdfLib.PDFDocument.load(fileData);
1207
+ if (metadata.title !== void 0) pdf.setTitle(metadata.title);
1208
+ if (metadata.author !== void 0) pdf.setAuthor(metadata.author);
1209
+ if (metadata.subject !== void 0) pdf.setSubject(metadata.subject);
1210
+ if (metadata.keywords !== void 0) pdf.setKeywords(metadata.keywords);
1211
+ if (metadata.creator !== void 0) pdf.setCreator(metadata.creator);
1212
+ if (metadata.producer !== void 0) pdf.setProducer(metadata.producer);
1213
+ return pdf.save();
1214
+ }
1215
+ async function getPageInfo(file) {
1216
+ const fileData = toUint8Array(file);
1217
+ const pdf = await pdfLib.PDFDocument.load(fileData);
1218
+ const pages = pdf.getPages();
1219
+ return pages.map((page, index) => ({
1220
+ index,
1221
+ width: page.getWidth(),
1222
+ height: page.getHeight(),
1223
+ rotation: page.getRotation().angle
1224
+ }));
1225
+ }
1226
+ async function getPageCount(file) {
1227
+ const fileData = toUint8Array(file);
1228
+ const pdf = await pdfLib.PDFDocument.load(fileData);
1229
+ return pdf.getPageCount();
1230
+ }
1231
+ async function rotate(file, options) {
1232
+ const { pages: pageRange, degrees: deg } = options;
1233
+ const fileData = toUint8Array(file);
1234
+ const pdf = await pdfLib.PDFDocument.load(fileData);
1235
+ const allPages = pdf.getPages();
1236
+ const pagesToRotate = pageRange ? parsePageRanges(pageRange.join(","), allPages.length) : Array.from({ length: allPages.length }, (_, i) => i + 1);
1237
+ for (const pageNum of pagesToRotate) {
1238
+ const page = allPages[pageNum - 1];
1239
+ if (page) {
1240
+ const currentRotation = page.getRotation().angle;
1241
+ page.setRotation(pdfLib.degrees(currentRotation + deg));
1242
+ }
1243
+ }
1244
+ return pdf.save();
1245
+ }
1246
+ async function addWatermark(file, options) {
1247
+ const {
1248
+ text = "WATERMARK",
1249
+ opacity = 0.3,
1250
+ rotation = -45,
1251
+ position = "center",
1252
+ fontSize = 50,
1253
+ color = { r: 0.5, g: 0.5, b: 0.5 }
1254
+ } = options;
1255
+ const fileData = toUint8Array(file);
1256
+ const pdf = await pdfLib.PDFDocument.load(fileData);
1257
+ const font = await pdf.embedFont(pdfLib.StandardFonts.Helvetica);
1258
+ const pages = pdf.getPages();
1259
+ for (const page of pages) {
1260
+ const { width, height } = page.getSize();
1261
+ const textWidth = font.widthOfTextAtSize(text, fontSize);
1262
+ const x = (width - textWidth) / 2;
1263
+ let y = height / 2;
1264
+ if (position === "top") {
1265
+ y = height - fontSize - 20;
1266
+ } else if (position === "bottom") {
1267
+ y = 20;
1268
+ }
1269
+ page.drawText(text, {
1270
+ x,
1271
+ y,
1272
+ size: fontSize,
1273
+ font,
1274
+ color: pdfLib.rgb(color.r, color.g, color.b),
1275
+ opacity,
1276
+ rotate: pdfLib.degrees(rotation)
1277
+ });
1278
+ }
1279
+ return pdf.save();
1280
+ }
1281
+ async function reorderPages(file, newOrder) {
1282
+ const fileData = toUint8Array(file);
1283
+ const sourcePdf = await pdfLib.PDFDocument.load(fileData);
1284
+ const newPdf = await pdfLib.PDFDocument.create();
1285
+ const pageIndices = newOrder.map((p) => p - 1);
1286
+ const copiedPages = await newPdf.copyPages(sourcePdf, pageIndices);
1287
+ for (const page of copiedPages) {
1288
+ newPdf.addPage(page);
1289
+ }
1290
+ return newPdf.save();
1291
+ }
1292
+ async function deletePage(file, pageNumbers) {
1293
+ const fileData = toUint8Array(file);
1294
+ const pdf = await pdfLib.PDFDocument.load(fileData);
1295
+ const totalPages = pdf.getPageCount();
1296
+ const sortedPageNumbers = [...pageNumbers].sort((a, b) => b - a);
1297
+ for (const pageNum of sortedPageNumbers) {
1298
+ if (pageNum >= 1 && pageNum <= totalPages) {
1299
+ pdf.removePage(pageNum - 1);
1300
+ }
1301
+ }
1302
+ return pdf.save();
1303
+ }
1304
+ async function compress(file, _options = { quality: "medium" }) {
1305
+ const fileData = toUint8Array(file);
1306
+ const pdf = await pdfLib.PDFDocument.load(fileData);
1307
+ return pdf.save({
1308
+ useObjectStreams: true,
1309
+ addDefaultPage: false
1310
+ });
1311
+ }
1312
+
1313
+ // src/pdf/extract.ts
1314
+ async function extractText(file, options = {}) {
1315
+ const { pages: pageNums } = options;
1316
+ const fileData = toUint8Array(file);
1317
+ try {
1318
+ const pdfParse = await import('pdf-parse');
1319
+ const parser = pdfParse.default || pdfParse;
1320
+ if (pageNums && pageNums.length > 0) {
1321
+ const result2 = await parser(Buffer.from(fileData), {
1322
+ max: Math.max(...pageNums)
1323
+ });
1324
+ return result2.text;
1325
+ }
1326
+ const result = await parser(Buffer.from(fileData));
1327
+ return result.text;
1328
+ } catch (error) {
1329
+ throw new Error(`Failed to extract text: ${error.message}`);
1330
+ }
1331
+ }
1332
+ async function extractTextFromPages(file, pageRange) {
1333
+ const fileData = toUint8Array(file);
1334
+ try {
1335
+ const pdfParse = await import('pdf-parse');
1336
+ const parser = pdfParse.default || pdfParse;
1337
+ const result = await parser(Buffer.from(fileData));
1338
+ const totalPages = result.numpages;
1339
+ const pages = parsePageRanges(pageRange, totalPages);
1340
+ const pageTexts = {};
1341
+ const fullText = result.text;
1342
+ const textPerPage = fullText.length / totalPages;
1343
+ for (const pageNum of pages) {
1344
+ const start = (pageNum - 1) * textPerPage;
1345
+ const end = pageNum * textPerPage;
1346
+ pageTexts[pageNum] = fullText.slice(start, end).trim();
1347
+ }
1348
+ return pageTexts;
1349
+ } catch (error) {
1350
+ throw new Error(`Failed to extract text: ${error.message}`);
1351
+ }
1352
+ }
1353
+ async function hasText(file) {
1354
+ try {
1355
+ const text = await extractText(file);
1356
+ return text.trim().length > 0;
1357
+ } catch {
1358
+ return false;
1359
+ }
1360
+ }
1361
+ var PLACEHOLDER_REGEX = /\{\{(\w+)\}\}/g;
1362
+ function extractFieldName(content) {
1363
+ const match = content.match(/^\{\{(\w+)\}\}$/);
1364
+ return match ? match[1] : void 0;
1365
+ }
1366
+ function resolveContent(content, data, missingFieldBehavior, fields) {
1367
+ return content.replace(PLACEHOLDER_REGEX, (match, fieldName) => {
1368
+ if (fieldName in data) {
1369
+ return data[fieldName];
1370
+ }
1371
+ switch (missingFieldBehavior) {
1372
+ case "use_default": {
1373
+ const field = fields.find((f) => f.name === fieldName);
1374
+ return field?.defaultValue ?? "";
1375
+ }
1376
+ case "empty_string":
1377
+ return "";
1378
+ case "leave_placeholder":
1379
+ default:
1380
+ return match;
1381
+ }
1382
+ });
1383
+ }
1384
+ function resolveFont(font, defaults) {
1385
+ return font ?? defaults?.font ?? { name: "Helvetica", size: 12 };
1386
+ }
1387
+ async function pdfToTemplate(file, options = {}) {
1388
+ const fileData = toUint8Array(file);
1389
+ const pdfDoc = await pdfLib.PDFDocument.load(fileData, { ignoreEncryption: true });
1390
+ const pageCount = pdfDoc.getPageCount();
1391
+ const pdfPages = pdfDoc.getPages();
1392
+ let fullText = "";
1393
+ try {
1394
+ const pdfParse = await import('pdf-parse');
1395
+ const parser = pdfParse.default || pdfParse;
1396
+ const parsed = await parser(Buffer.from(fileData));
1397
+ fullText = parsed.text;
1398
+ } catch {
1399
+ fullText = "";
1400
+ }
1401
+ const textPerPage = pageCount > 0 ? fullText.length / pageCount : 0;
1402
+ const fieldsMap = /* @__PURE__ */ new Map();
1403
+ const fonts = {};
1404
+ const defaultFont = { name: "Helvetica", size: 12 };
1405
+ fonts["Helvetica-12"] = defaultFont;
1406
+ const pages = pdfPages.map((page, pageIndex) => {
1407
+ const { width, height } = page.getSize();
1408
+ const start = Math.floor(pageIndex * textPerPage);
1409
+ const end = Math.floor((pageIndex + 1) * textPerPage);
1410
+ const pageText = fullText.slice(start, end).trim();
1411
+ const elements = [];
1412
+ if (pageText) {
1413
+ const lines = pageText.split("\n").filter((l) => l.trim());
1414
+ const lineHeight = 14;
1415
+ let yPos = height - 40;
1416
+ for (const line of lines) {
1417
+ const hasPlaceholder = PLACEHOLDER_REGEX.test(line);
1418
+ PLACEHOLDER_REGEX.lastIndex = 0;
1419
+ const element = {
1420
+ type: hasPlaceholder ? "placeholder" : "text",
1421
+ content: line.trim(),
1422
+ x: 40,
1423
+ y: yPos,
1424
+ font: defaultFont
1425
+ };
1426
+ if (hasPlaceholder) {
1427
+ const fieldName = extractFieldName(line.trim());
1428
+ if (fieldName) {
1429
+ element.fieldName = fieldName;
1430
+ }
1431
+ let match;
1432
+ PLACEHOLDER_REGEX.lastIndex = 0;
1433
+ while ((match = PLACEHOLDER_REGEX.exec(line)) !== null) {
1434
+ const name = match[1];
1435
+ if (!fieldsMap.has(name)) {
1436
+ fieldsMap.set(name, { pages: /* @__PURE__ */ new Set(), defaultValue: "" });
1437
+ }
1438
+ fieldsMap.get(name).pages.add(pageIndex + 1);
1439
+ }
1440
+ }
1441
+ elements.push(element);
1442
+ yPos -= lineHeight;
1443
+ }
1444
+ }
1445
+ return { width, height, elements };
1446
+ });
1447
+ const fields = [];
1448
+ for (const [name, info] of fieldsMap) {
1449
+ fields.push({
1450
+ name,
1451
+ defaultValue: info.defaultValue,
1452
+ pages: [...info.pages].sort((a, b) => a - b)
1453
+ });
1454
+ }
1455
+ return {
1456
+ version: "1.0",
1457
+ metadata: {
1458
+ name: options.name,
1459
+ description: options.description,
1460
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1461
+ sourcePageCount: pageCount
1462
+ },
1463
+ pages,
1464
+ fields,
1465
+ fonts,
1466
+ defaults: {
1467
+ font: defaultFont,
1468
+ color: { r: 0, g: 0, b: 0 },
1469
+ missingFieldBehavior: "leave_placeholder"
1470
+ }
1471
+ };
1472
+ }
1473
+ async function templateToPdf(template, data = {}, options = {}) {
1474
+ validateTemplate(template);
1475
+ const pdfDoc = await pdfLib.PDFDocument.create();
1476
+ const font = await pdfDoc.embedFont(pdfLib.StandardFonts.Helvetica);
1477
+ const boldFont = await pdfDoc.embedFont(pdfLib.StandardFonts.HelveticaBold);
1478
+ const missingFieldBehavior = options.missingFieldBehavior ?? template.defaults?.missingFieldBehavior ?? "leave_placeholder";
1479
+ const defaultColor = template.defaults?.color ?? { r: 0, g: 0, b: 0 };
1480
+ for (const templatePage of template.pages) {
1481
+ const page = pdfDoc.addPage([templatePage.width, templatePage.height]);
1482
+ for (const element of templatePage.elements) {
1483
+ const resolvedFont = resolveFont(element.font, template.defaults);
1484
+ const color = element.color ?? defaultColor;
1485
+ const pdfFont = resolvedFont.weight === "bold" ? boldFont : font;
1486
+ const fontSize = resolvedFont.size;
1487
+ const content = element.type === "placeholder" ? resolveContent(element.content, data, missingFieldBehavior, template.fields) : element.content;
1488
+ page.drawText(content, {
1489
+ x: element.x,
1490
+ y: element.y,
1491
+ size: fontSize,
1492
+ font: pdfFont,
1493
+ color: pdfLib.rgb(color.r, color.g, color.b)
1494
+ });
1495
+ }
1496
+ }
1497
+ return pdfDoc.save();
1498
+ }
1499
+ function validateTemplate(template) {
1500
+ if (!template) {
1501
+ throw new Error("Template is required");
1502
+ }
1503
+ if (template.version !== "1.0") {
1504
+ throw new Error(`Unsupported template version: ${template.version}`);
1505
+ }
1506
+ if (!Array.isArray(template.pages) || template.pages.length === 0) {
1507
+ throw new Error("Template must have at least one page");
1508
+ }
1509
+ if (!template.metadata) {
1510
+ throw new Error("Template metadata is required");
1511
+ }
1512
+ if (typeof template.metadata.sourcePageCount !== "number" || template.metadata.sourcePageCount < 1) {
1513
+ throw new Error("Template metadata.sourcePageCount must be a positive number");
1514
+ }
1515
+ if (!Array.isArray(template.fields)) {
1516
+ throw new Error("Template fields must be an array");
1517
+ }
1518
+ for (const page of template.pages) {
1519
+ if (typeof page.width !== "number" || typeof page.height !== "number") {
1520
+ throw new Error("Each page must have numeric width and height");
1521
+ }
1522
+ if (!Array.isArray(page.elements)) {
1523
+ throw new Error("Each page must have an elements array");
1524
+ }
1525
+ for (const element of page.elements) {
1526
+ if (element.type !== "text" && element.type !== "placeholder") {
1527
+ throw new Error(`Invalid element type: ${element.type}`);
1528
+ }
1529
+ if (typeof element.content !== "string") {
1530
+ throw new Error("Element content must be a string");
1531
+ }
1532
+ if (typeof element.x !== "number" || typeof element.y !== "number") {
1533
+ throw new Error("Element x and y must be numbers");
1534
+ }
1535
+ }
1536
+ }
1537
+ }
1538
+
1539
+ // src/xml/index.ts
1540
+ var xml_exports = {};
1541
+ __export(xml_exports, {
1542
+ convert: () => convert2,
1543
+ format: () => format2,
1544
+ getStats: () => getStats3,
1545
+ minify: () => minify2,
1546
+ parse: () => parse4,
1547
+ query: () => query2,
1548
+ validate: () => validate2
1549
+ });
1550
+ function parse4(input, options = {}) {
1551
+ const parser = new fastXmlParser.XMLParser({
1552
+ preserveOrder: options.preserveOrder ?? false,
1553
+ ignoreAttributes: options.ignoreAttributes ?? false,
1554
+ trimValues: options.trimValues ?? true,
1555
+ parseAttributeValue: true,
1556
+ parseTagValue: true
1557
+ });
1558
+ return parser.parse(input);
1559
+ }
1560
+ function format2(input, options = {}) {
1561
+ const indent = options.indent ?? 2;
1562
+ const parser = new fastXmlParser.XMLParser({
1563
+ preserveOrder: true,
1564
+ ignoreAttributes: false,
1565
+ trimValues: true,
1566
+ parseAttributeValue: true,
1567
+ parseTagValue: true
1568
+ });
1569
+ const parsed = parser.parse(input);
1570
+ const builder = new fastXmlParser.XMLBuilder({
1571
+ preserveOrder: true,
1572
+ ignoreAttributes: false,
1573
+ format: true,
1574
+ indentBy: " ".repeat(indent),
1575
+ suppressEmptyNode: false
1576
+ });
1577
+ return builder.build(parsed);
1578
+ }
1579
+ function minify2(input) {
1580
+ const parser = new fastXmlParser.XMLParser({
1581
+ preserveOrder: true,
1582
+ ignoreAttributes: false,
1583
+ trimValues: true,
1584
+ parseAttributeValue: true,
1585
+ parseTagValue: true
1586
+ });
1587
+ const parsed = parser.parse(input);
1588
+ const builder = new fastXmlParser.XMLBuilder({
1589
+ preserveOrder: true,
1590
+ ignoreAttributes: false,
1591
+ format: false,
1592
+ suppressEmptyNode: false
1593
+ });
1594
+ return builder.build(parsed);
1595
+ }
1596
+ function validate2(input) {
1597
+ const result = fastXmlParser.XMLValidator.validate(input, {
1598
+ allowBooleanAttributes: true
1599
+ });
1600
+ if (result === true) {
1601
+ return { valid: true, errors: [] };
1602
+ }
1603
+ return {
1604
+ valid: false,
1605
+ errors: [
1606
+ {
1607
+ line: result.err.line,
1608
+ message: result.err.msg
1609
+ }
1610
+ ]
1611
+ };
1612
+ }
1613
+ function query2(input, path) {
1614
+ const parser = new fastXmlParser.XMLParser({
1615
+ ignoreAttributes: false,
1616
+ trimValues: true,
1617
+ parseAttributeValue: true,
1618
+ parseTagValue: true
1619
+ });
1620
+ const parsed = parser.parse(input);
1621
+ const segments = path.replace(/^\/+/, "").split("/");
1622
+ const matches = resolvePath(parsed, segments);
1623
+ return {
1624
+ matches,
1625
+ count: matches.length
1626
+ };
1627
+ }
1628
+ function resolvePath(obj, segments) {
1629
+ if (segments.length === 0) {
1630
+ return obj !== void 0 ? [obj] : [];
1631
+ }
1632
+ if (obj === null || obj === void 0 || typeof obj !== "object") {
1633
+ return [];
1634
+ }
1635
+ const [current, ...rest] = segments;
1636
+ if (current === "*") {
1637
+ const results = [];
1638
+ for (const value of Object.values(obj)) {
1639
+ results.push(...resolvePath(value, rest));
1640
+ }
1641
+ return results;
1642
+ }
1643
+ const record = obj;
1644
+ if (current in record) {
1645
+ const value = record[current];
1646
+ if (Array.isArray(value)) {
1647
+ if (rest.length === 0) return value;
1648
+ const results = [];
1649
+ for (const item of value) {
1650
+ results.push(...resolvePath(item, rest));
1651
+ }
1652
+ return results;
1653
+ }
1654
+ return resolvePath(value, rest);
1655
+ }
1656
+ return [];
1657
+ }
1658
+ function convert2(input, from, to) {
1659
+ if (from === to) return input;
1660
+ if (from === "xml" && to === "json") {
1661
+ const parser = new fastXmlParser.XMLParser({
1662
+ ignoreAttributes: false,
1663
+ trimValues: true,
1664
+ parseAttributeValue: true,
1665
+ parseTagValue: true
1666
+ });
1667
+ return JSON.stringify(parser.parse(input), null, 2);
1668
+ }
1669
+ if (from === "json" && to === "xml") {
1670
+ const data = JSON.parse(input);
1671
+ const builder = new fastXmlParser.XMLBuilder({
1672
+ ignoreAttributes: false,
1673
+ format: true,
1674
+ indentBy: " ",
1675
+ suppressEmptyNode: false
1676
+ });
1677
+ return builder.build(data);
1678
+ }
1679
+ throw new Error(`Unsupported conversion: ${from} -> ${to}`);
1680
+ }
1681
+ function getStats3(input) {
1682
+ const parser = new fastXmlParser.XMLParser({
1683
+ ignoreAttributes: false,
1684
+ trimValues: true,
1685
+ parseAttributeValue: true,
1686
+ parseTagValue: true
1687
+ });
1688
+ const parsed = parser.parse(input);
1689
+ const stats = {
1690
+ elements: 0,
1691
+ attributes: 0,
1692
+ textNodes: 0,
1693
+ depth: 0,
1694
+ sizeBytes: Buffer.byteLength(input, "utf8")
1695
+ };
1696
+ countNodes(parsed, 0, stats);
1697
+ return stats;
1698
+ }
1699
+ function countNodes(obj, depth, stats) {
1700
+ if (obj === null || obj === void 0) return;
1701
+ if (typeof obj !== "object") {
1702
+ stats.textNodes++;
1703
+ return;
1704
+ }
1705
+ if (Array.isArray(obj)) {
1706
+ for (const item of obj) {
1707
+ countNodes(item, depth, stats);
1708
+ }
1709
+ return;
1710
+ }
1711
+ for (const [key, value] of Object.entries(obj)) {
1712
+ if (key.startsWith("@_")) {
1713
+ stats.attributes++;
1714
+ } else if (key === "#text") {
1715
+ stats.textNodes++;
1716
+ } else {
1717
+ stats.elements++;
1718
+ stats.depth = Math.max(stats.depth, depth + 1);
1719
+ countNodes(value, depth + 1, stats);
1720
+ }
1721
+ }
1722
+ }
1723
+
1724
+ // src/excel/index.ts
1725
+ var excel_exports = {};
1726
+ __export(excel_exports, {
1727
+ convert: () => convert3,
1728
+ createExcel: () => createExcel,
1729
+ getSheets: () => getSheets,
1730
+ getStats: () => getStats4,
1731
+ parse: () => parse5
1732
+ });
1733
+ async function parse5(file, options = {}) {
1734
+ const workbook = new ExcelJS__default.default.Workbook();
1735
+ await workbook.xlsx.load(Buffer.from(file));
1736
+ const sheets = [];
1737
+ workbook.eachSheet((ws, id) => {
1738
+ sheets.push({
1739
+ name: ws.name,
1740
+ index: id,
1741
+ rowCount: ws.rowCount,
1742
+ columnCount: ws.columnCount
1743
+ });
1744
+ });
1745
+ const targetSheet = typeof options.sheet === "number" ? workbook.worksheets[options.sheet] : typeof options.sheet === "string" ? workbook.getWorksheet(options.sheet) : workbook.worksheets[0];
1746
+ if (!targetSheet) {
1747
+ throw new Error("Sheet not found");
1748
+ }
1749
+ const useHeaders = options.header ?? true;
1750
+ const rows = [];
1751
+ let headers = [];
1752
+ targetSheet.eachRow((row, rowNumber) => {
1753
+ const values = row.values;
1754
+ const cells = values.slice(1);
1755
+ if (rowNumber === 1 && useHeaders) {
1756
+ headers = cells.map((c, i) => String(c ?? `Column${i + 1}`));
1757
+ return;
1758
+ }
1759
+ const record = {};
1760
+ const keys = useHeaders && headers.length > 0 ? headers : cells.map((_, i) => `Column${i + 1}`);
1761
+ if (!useHeaders && rowNumber === 1) {
1762
+ headers = keys;
1763
+ }
1764
+ keys.forEach((key, i) => {
1765
+ const val = cells[i];
1766
+ record[key] = val instanceof Date ? val.toISOString() : val ?? null;
1767
+ });
1768
+ rows.push(record);
1769
+ });
1770
+ return {
1771
+ sheets,
1772
+ data: rows,
1773
+ headers,
1774
+ rowCount: rows.length
1775
+ };
1776
+ }
1777
+ async function getSheets(file) {
1778
+ const workbook = new ExcelJS__default.default.Workbook();
1779
+ await workbook.xlsx.load(Buffer.from(file));
1780
+ const sheets = [];
1781
+ workbook.eachSheet((ws, id) => {
1782
+ sheets.push({
1783
+ name: ws.name,
1784
+ index: id,
1785
+ rowCount: ws.rowCount,
1786
+ columnCount: ws.columnCount
1787
+ });
1788
+ });
1789
+ return sheets;
1790
+ }
1791
+ async function convert3(file, format4, options = {}) {
1792
+ const workbook = new ExcelJS__default.default.Workbook();
1793
+ await workbook.xlsx.load(Buffer.from(file));
1794
+ const targetSheet = typeof options.sheet === "number" ? workbook.worksheets[options.sheet] : typeof options.sheet === "string" ? workbook.getWorksheet(options.sheet) : workbook.worksheets[0];
1795
+ if (!targetSheet) {
1796
+ throw new Error("Sheet not found");
1797
+ }
1798
+ const useHeaders = options.header ?? true;
1799
+ const allRows = [];
1800
+ targetSheet.eachRow((row) => {
1801
+ const values = row.values;
1802
+ allRows.push(values.slice(1).map((v) => v instanceof Date ? v.toISOString() : v));
1803
+ });
1804
+ if (allRows.length === 0) return "";
1805
+ const headers = useHeaders ? allRows[0].map((c, i) => String(c ?? `Column${i + 1}`)) : allRows[0].map((_, i) => `Column${i + 1}`);
1806
+ const dataRows = useHeaders ? allRows.slice(1) : allRows;
1807
+ switch (format4) {
1808
+ case "json": {
1809
+ const records = dataRows.map((row) => {
1810
+ const record = {};
1811
+ headers.forEach((h, i) => {
1812
+ record[h] = row[i] ?? null;
1813
+ });
1814
+ return record;
1815
+ });
1816
+ return JSON.stringify(records, null, 2);
1817
+ }
1818
+ case "csv":
1819
+ return toDSV(headers, dataRows, ",");
1820
+ case "tsv":
1821
+ return toDSV(headers, dataRows, " ");
1822
+ default:
1823
+ throw new Error(`Unsupported format: ${format4}`);
1824
+ }
1825
+ }
1826
+ function toDSV(headers, rows, delimiter) {
1827
+ const escape = (val) => {
1828
+ const str = String(val ?? "");
1829
+ if (str.includes(delimiter) || str.includes('"') || str.includes("\n")) {
1830
+ return `"${str.replace(/"/g, '""')}"`;
1831
+ }
1832
+ return str;
1833
+ };
1834
+ const lines = [headers.map(escape).join(delimiter)];
1835
+ for (const row of rows) {
1836
+ lines.push(headers.map((_, i) => escape(row[i])).join(delimiter));
1837
+ }
1838
+ return lines.join("\n");
1839
+ }
1840
+ async function createExcel(data, sheetName = "Sheet1") {
1841
+ const workbook = new ExcelJS__default.default.Workbook();
1842
+ const sheet = workbook.addWorksheet(sheetName);
1843
+ if (data.length === 0) {
1844
+ const buffer2 = await workbook.xlsx.writeBuffer();
1845
+ return new Uint8Array(buffer2);
1846
+ }
1847
+ const headers = Object.keys(data[0]);
1848
+ sheet.addRow(headers);
1849
+ for (const record of data) {
1850
+ sheet.addRow(headers.map((h) => record[h]));
1851
+ }
1852
+ const buffer = await workbook.xlsx.writeBuffer();
1853
+ return new Uint8Array(buffer);
1854
+ }
1855
+ async function getStats4(file) {
1856
+ const workbook = new ExcelJS__default.default.Workbook();
1857
+ await workbook.xlsx.load(Buffer.from(file));
1858
+ const sheetDetails = [];
1859
+ let totalRows = 0;
1860
+ let totalColumns = 0;
1861
+ workbook.eachSheet((ws, id) => {
1862
+ sheetDetails.push({
1863
+ name: ws.name,
1864
+ index: id,
1865
+ rowCount: ws.rowCount,
1866
+ columnCount: ws.columnCount
1867
+ });
1868
+ totalRows += ws.rowCount;
1869
+ totalColumns = Math.max(totalColumns, ws.columnCount);
1870
+ });
1871
+ return {
1872
+ sheets: sheetDetails.length,
1873
+ totalRows,
1874
+ totalColumns,
1875
+ sheetDetails,
1876
+ sizeBytes: file.length
1877
+ };
1878
+ }
1879
+
1880
+ // src/image/index.ts
1881
+ var image_exports = {};
1882
+ __export(image_exports, {
1883
+ blur: () => blur,
1884
+ compress: () => compress2,
1885
+ convert: () => convert4,
1886
+ crop: () => crop,
1887
+ flip: () => flip,
1888
+ flop: () => flop,
1889
+ getMetadata: () => getMetadata2,
1890
+ getStats: () => getStats5,
1891
+ grayscale: () => grayscale,
1892
+ resize: () => resize,
1893
+ rotate: () => rotate2
1894
+ });
1895
+ async function resize(file, options) {
1896
+ const result = await sharp2__default.default(Buffer.from(file)).resize({
1897
+ width: options.width,
1898
+ height: options.height,
1899
+ fit: options.fit ?? "inside",
1900
+ background: options.background ?? "#ffffff"
1901
+ }).toBuffer();
1902
+ return new Uint8Array(result);
1903
+ }
1904
+ async function crop(file, options) {
1905
+ const result = await sharp2__default.default(Buffer.from(file)).extract({
1906
+ left: options.left,
1907
+ top: options.top,
1908
+ width: options.width,
1909
+ height: options.height
1910
+ }).toBuffer();
1911
+ return new Uint8Array(result);
1912
+ }
1913
+ async function rotate2(file, options) {
1914
+ const result = await sharp2__default.default(Buffer.from(file)).rotate(options.degrees, {
1915
+ background: options.background ?? "#ffffff"
1916
+ }).toBuffer();
1917
+ return new Uint8Array(result);
1918
+ }
1919
+ async function flip(file) {
1920
+ const result = await sharp2__default.default(Buffer.from(file)).flip().toBuffer();
1921
+ return new Uint8Array(result);
1922
+ }
1923
+ async function flop(file) {
1924
+ const result = await sharp2__default.default(Buffer.from(file)).flop().toBuffer();
1925
+ return new Uint8Array(result);
1926
+ }
1927
+ async function grayscale(file) {
1928
+ const result = await sharp2__default.default(Buffer.from(file)).grayscale().toBuffer();
1929
+ return new Uint8Array(result);
1930
+ }
1931
+ async function blur(file, sigma = 3) {
1932
+ const result = await sharp2__default.default(Buffer.from(file)).blur(sigma).toBuffer();
1933
+ return new Uint8Array(result);
1934
+ }
1935
+ async function convert4(file, options) {
1936
+ let pipeline = sharp2__default.default(Buffer.from(file));
1937
+ switch (options.format) {
1938
+ case "png":
1939
+ pipeline = pipeline.png();
1940
+ break;
1941
+ case "jpeg":
1942
+ pipeline = pipeline.jpeg({ quality: options.quality ?? 80 });
1943
+ break;
1944
+ case "webp":
1945
+ pipeline = pipeline.webp({ quality: options.quality ?? 80 });
1946
+ break;
1947
+ case "gif":
1948
+ pipeline = pipeline.gif();
1949
+ break;
1950
+ case "tiff":
1951
+ pipeline = pipeline.tiff({ quality: options.quality ?? 80 });
1952
+ break;
1953
+ case "avif":
1954
+ pipeline = pipeline.avif({ quality: options.quality ?? 50 });
1955
+ break;
1956
+ default:
1957
+ throw new Error(`Unsupported format: ${options.format}`);
1958
+ }
1959
+ const result = await pipeline.toBuffer();
1960
+ return new Uint8Array(result);
1961
+ }
1962
+ async function compress2(file, options = {}) {
1963
+ const quality = options.quality ?? 70;
1964
+ const format4 = options.format ?? "jpeg";
1965
+ return convert4(file, { format: format4, quality });
1966
+ }
1967
+ async function getMetadata2(file) {
1968
+ const meta = await sharp2__default.default(Buffer.from(file)).metadata();
1969
+ return {
1970
+ width: meta.width ?? 0,
1971
+ height: meta.height ?? 0,
1972
+ format: meta.format ?? "unknown",
1973
+ channels: meta.channels ?? 0,
1974
+ space: meta.space ?? "unknown",
1975
+ depth: meta.depth ?? "unknown",
1976
+ density: meta.density,
1977
+ hasAlpha: meta.hasAlpha ?? false,
1978
+ sizeBytes: file.length
1979
+ };
1980
+ }
1981
+ async function getStats5(file) {
1982
+ const meta = await sharp2__default.default(Buffer.from(file)).metadata();
1983
+ const width = meta.width ?? 0;
1984
+ const height = meta.height ?? 0;
1985
+ return {
1986
+ width,
1987
+ height,
1988
+ format: meta.format ?? "unknown",
1989
+ channels: meta.channels ?? 0,
1990
+ hasAlpha: meta.hasAlpha ?? false,
1991
+ sizeBytes: file.length,
1992
+ megapixels: Math.round(width * height / 1e4) / 100
1993
+ };
1994
+ }
1995
+
1996
+ // src/markdown/index.ts
1997
+ var markdown_exports = {};
1998
+ __export(markdown_exports, {
1999
+ convert: () => convert5,
2000
+ extractFrontmatter: () => extractFrontmatter,
2001
+ extractLinks: () => extractLinks,
2002
+ generateToc: () => generateToc,
2003
+ getStats: () => getStats6,
2004
+ renderToc: () => renderToc,
2005
+ stripFrontmatter: () => stripFrontmatter
2006
+ });
2007
+ function convert5(input, options) {
2008
+ const { from, to } = options;
2009
+ if (from === to) return input;
2010
+ if (from === "markdown" && to === "html") {
2011
+ return markdownToHtml(input, options.gfm);
2012
+ }
2013
+ if (from === "html" && to === "markdown") {
2014
+ return htmlToMarkdown(input);
2015
+ }
2016
+ if (from === "markdown" && to === "text") {
2017
+ return markdownToText(input);
2018
+ }
2019
+ if (from === "html" && to === "text") {
2020
+ return htmlToText(input);
2021
+ }
2022
+ if (from === "text" && to === "markdown") {
2023
+ return input;
2024
+ }
2025
+ if (from === "text" && to === "html") {
2026
+ return `<p>${input.split("\n\n").join("</p><p>")}</p>`;
2027
+ }
2028
+ throw new Error(`Unsupported conversion: ${from} -> ${to}`);
2029
+ }
2030
+ function markdownToHtml(input, gfm = true) {
2031
+ marked.marked.setOptions({ gfm });
2032
+ return marked.marked.parse(input);
2033
+ }
2034
+ function htmlToMarkdown(input) {
2035
+ const turndown = new TurndownService__default.default({
2036
+ headingStyle: "atx",
2037
+ codeBlockStyle: "fenced",
2038
+ bulletListMarker: "-"
2039
+ });
2040
+ return turndown.turndown(input);
2041
+ }
2042
+ function markdownToText(input) {
2043
+ const html = markdownToHtml(input);
2044
+ return htmlToText(html);
2045
+ }
2046
+ function htmlToText(input) {
2047
+ return input.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, "").replace(/<style[^>]*>[\s\S]*?<\/style>/gi, "").replace(/<[^>]+>/g, "").replace(/&nbsp;/g, " ").replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/\n{3,}/g, "\n\n").trim();
2048
+ }
2049
+
2050
+ // src/markdown/toc.ts
2051
+ function generateToc(input) {
2052
+ const headingRegex = /^(#{1,6})\s+(.+)$/gm;
2053
+ const entries = [];
2054
+ let match;
2055
+ while ((match = headingRegex.exec(input)) !== null) {
2056
+ const level = match[1].length;
2057
+ const text = match[2].trim();
2058
+ const slug = text.toLowerCase().replace(/[^\w\s-]/g, "").replace(/\s+/g, "-").replace(/-+/g, "-");
2059
+ entries.push({ level, text, slug });
2060
+ }
2061
+ return entries;
2062
+ }
2063
+ function renderToc(entries) {
2064
+ if (entries.length === 0) return "";
2065
+ const minLevel = Math.min(...entries.map((e) => e.level));
2066
+ return entries.map((entry) => {
2067
+ const indent = " ".repeat(entry.level - minLevel);
2068
+ return `${indent}- [${entry.text}](#${entry.slug})`;
2069
+ }).join("\n");
2070
+ }
2071
+
2072
+ // src/markdown/extract.ts
2073
+ function extractLinks(input) {
2074
+ const links = [];
2075
+ const lines = input.split("\n");
2076
+ const linkRegex = /\[([^\]]*)\]\(([^)]+)\)/g;
2077
+ for (let i = 0; i < lines.length; i++) {
2078
+ let match;
2079
+ while ((match = linkRegex.exec(lines[i])) !== null) {
2080
+ links.push({
2081
+ text: match[1],
2082
+ href: match[2],
2083
+ line: i + 1
2084
+ });
2085
+ }
2086
+ }
2087
+ return links;
2088
+ }
2089
+ function extractFrontmatter(input) {
2090
+ const match = input.match(/^---\s*\n([\s\S]*?)\n---\s*\n/);
2091
+ if (!match) return null;
2092
+ const frontmatter = {};
2093
+ const lines = match[1].split("\n");
2094
+ for (const line of lines) {
2095
+ const colonIndex = line.indexOf(":");
2096
+ if (colonIndex === -1) continue;
2097
+ const key = line.substring(0, colonIndex).trim();
2098
+ let value = line.substring(colonIndex + 1).trim();
2099
+ if (value === "true") value = true;
2100
+ else if (value === "false") value = false;
2101
+ else if (!isNaN(Number(value)) && value !== "") value = Number(value);
2102
+ else if (typeof value === "string" && value.startsWith("[") && value.endsWith("]")) {
2103
+ value = value.slice(1, -1).split(",").map((s) => s.trim().replace(/^['"]|['"]$/g, ""));
2104
+ }
2105
+ frontmatter[key] = value;
2106
+ }
2107
+ return frontmatter;
2108
+ }
2109
+ function stripFrontmatter(input) {
2110
+ return input.replace(/^---\s*\n[\s\S]*?\n---\s*\n/, "");
2111
+ }
2112
+
2113
+ // src/markdown/stats.ts
2114
+ function getStats6(input) {
2115
+ const lines = input.split("\n");
2116
+ const text = input.replace(/```[\s\S]*?```/g, "").replace(/`[^`]+`/g, "");
2117
+ const headings = (text.match(/^#{1,6}\s+.+$/gm) || []).length;
2118
+ const links = (input.match(/\[([^\]]*)\]\(([^)]+)\)/g) || []).length;
2119
+ const images = (input.match(/!\[([^\]]*)\]\(([^)]+)\)/g) || []).length;
2120
+ const codeBlocks = (input.match(/```/g) || []).length / 2;
2121
+ const lists = (text.match(/^[\s]*[-*+]\s+|^[\s]*\d+\.\s+/gm) || []).length;
2122
+ const plainText = text.replace(/#{1,6}\s+/g, "").replace(/\[([^\]]*)\]\([^)]+\)/g, "$1").replace(/[*_~`]/g, "").trim();
2123
+ const words = plainText.split(/\s+/).filter((w) => w.length > 0).length;
2124
+ const paragraphs = input.split(/\n\s*\n/).filter((p) => p.trim().length > 0).length;
2125
+ return {
2126
+ words,
2127
+ characters: input.length,
2128
+ lines: lines.length,
2129
+ paragraphs,
2130
+ headings,
2131
+ links,
2132
+ images,
2133
+ codeBlocks: Math.floor(codeBlocks),
2134
+ lists,
2135
+ sizeBytes: Buffer.byteLength(input, "utf8")
2136
+ };
2137
+ }
2138
+
2139
+ // src/archive/index.ts
2140
+ var archive_exports = {};
2141
+ __export(archive_exports, {
2142
+ create: () => create,
2143
+ extract: () => extract,
2144
+ getStats: () => getStats7,
2145
+ list: () => list
2146
+ });
2147
+ async function create(files, options = {}) {
2148
+ const format4 = options.format ?? "zip";
2149
+ const level = options.compressionLevel ?? 6;
2150
+ return new Promise((resolve, reject) => {
2151
+ const chunks = [];
2152
+ const output = new stream.PassThrough();
2153
+ output.on("data", (chunk) => chunks.push(chunk));
2154
+ output.on("end", () => resolve(new Uint8Array(Buffer.concat(chunks))));
2155
+ output.on("error", reject);
2156
+ const archiverFormat = format4 === "tar.gz" ? "tar" : format4;
2157
+ const archiverOptions = format4 === "tar.gz" ? { gzip: true, gzipOptions: { level } } : format4 === "zip" ? { zlib: { level } } : {};
2158
+ const archive = archiver__default.default(archiverFormat, archiverOptions);
2159
+ archive.on("error", reject);
2160
+ archive.pipe(output);
2161
+ for (const file of files) {
2162
+ archive.append(file.content, { name: file.path });
2163
+ }
2164
+ archive.finalize();
2165
+ });
2166
+ }
2167
+ async function extract(file, options = {}) {
2168
+ const zip = new AdmZip__default.default(Buffer.from(file));
2169
+ const entries = zip.getEntries();
2170
+ const results = [];
2171
+ for (const entry of entries) {
2172
+ if (entry.isDirectory) continue;
2173
+ if (options.files && !options.files.includes(entry.entryName)) {
2174
+ continue;
2175
+ }
2176
+ results.push({
2177
+ path: entry.entryName,
2178
+ content: entry.getData()
2179
+ });
2180
+ }
2181
+ return results;
2182
+ }
2183
+ async function list(file) {
2184
+ const zip = new AdmZip__default.default(Buffer.from(file));
2185
+ const entries = zip.getEntries();
2186
+ return entries.map((entry) => ({
2187
+ path: entry.entryName,
2188
+ size: entry.header.size,
2189
+ compressedSize: entry.header.compressedSize,
2190
+ isDirectory: entry.isDirectory,
2191
+ modified: entry.header.time ? new Date(entry.header.time).toISOString() : void 0
2192
+ }));
2193
+ }
2194
+ async function getStats7(file) {
2195
+ const entries = await list(file);
2196
+ let totalSize = 0;
2197
+ let compressedSize = 0;
2198
+ let fileCount = 0;
2199
+ let directoryCount = 0;
2200
+ for (const entry of entries) {
2201
+ if (entry.isDirectory) {
2202
+ directoryCount++;
2203
+ } else {
2204
+ fileCount++;
2205
+ totalSize += entry.size;
2206
+ compressedSize += entry.compressedSize ?? entry.size;
2207
+ }
2208
+ }
2209
+ return {
2210
+ format: "zip",
2211
+ fileCount,
2212
+ directoryCount,
2213
+ totalSize,
2214
+ compressedSize,
2215
+ entries
2216
+ };
2217
+ }
2218
+
2219
+ // src/regex/index.ts
2220
+ var regex_exports = {};
2221
+ __export(regex_exports, {
2222
+ extract: () => extract2,
2223
+ replace: () => replace,
2224
+ test: () => test,
2225
+ validate: () => validate3
2226
+ });
2227
+
2228
+ // src/regex/utils.ts
2229
+ function buildFlags(options) {
2230
+ let flags = options.flags ?? "";
2231
+ if (options.global && !flags.includes("g")) flags += "g";
2232
+ if (options.caseInsensitive && !flags.includes("i")) flags += "i";
2233
+ if (options.multiline && !flags.includes("m")) flags += "m";
2234
+ return flags;
2235
+ }
2236
+
2237
+ // src/regex/test.ts
2238
+ function test(input, pattern, options = {}) {
2239
+ const flags = buildFlags(options);
2240
+ const regex = new RegExp(pattern, flags.includes("g") ? flags : flags + "g");
2241
+ const results = [];
2242
+ let match;
2243
+ while ((match = regex.exec(input)) !== null) {
2244
+ results.push({
2245
+ match: match[0],
2246
+ index: match.index,
2247
+ groups: match.groups ? { ...match.groups } : {}
2248
+ });
2249
+ if (!flags.includes("g")) break;
2250
+ }
2251
+ return {
2252
+ matches: results.length > 0,
2253
+ matchCount: results.length,
2254
+ results
2255
+ };
2256
+ }
2257
+
2258
+ // src/regex/replace.ts
2259
+ function replace(input, pattern, replacement, options = {}) {
2260
+ const flags = buildFlags({ ...options, global: options.global ?? true });
2261
+ const regex = new RegExp(pattern, flags);
2262
+ let replacements = 0;
2263
+ const output = input.replace(regex, (...args) => {
2264
+ replacements++;
2265
+ const groups = args[args.length - 1];
2266
+ let result = replacement;
2267
+ if (typeof groups === "object" && groups !== null) {
2268
+ for (const [key, value] of Object.entries(groups)) {
2269
+ result = result.replace(new RegExp(`\\$<${key}>`, "g"), String(value ?? ""));
2270
+ }
2271
+ }
2272
+ for (let i = 1; i < args.length - 2; i++) {
2273
+ result = result.replace(new RegExp(`\\$${i}`, "g"), args[i] ?? "");
2274
+ }
2275
+ return result;
2276
+ });
2277
+ return { output, replacements };
2278
+ }
2279
+
2280
+ // src/regex/extract.ts
2281
+ function extract2(input, pattern, options = {}) {
2282
+ const flags = buildFlags({ ...options, global: true });
2283
+ const regex = new RegExp(pattern, flags);
2284
+ const matches = [];
2285
+ const groups = [];
2286
+ let match;
2287
+ while ((match = regex.exec(input)) !== null) {
2288
+ matches.push(match[0]);
2289
+ if (match.groups) {
2290
+ groups.push({ ...match.groups });
2291
+ }
2292
+ }
2293
+ return {
2294
+ matches,
2295
+ groups,
2296
+ count: matches.length
2297
+ };
2298
+ }
2299
+
2300
+ // src/regex/validate.ts
2301
+ function validate3(pattern, flags) {
2302
+ try {
2303
+ new RegExp(pattern, flags);
2304
+ return { valid: true };
2305
+ } catch (e) {
2306
+ return {
2307
+ valid: false,
2308
+ error: e.message
2309
+ };
2310
+ }
2311
+ }
2312
+
2313
+ // src/diff/index.ts
2314
+ var diff_exports = {};
2315
+ __export(diff_exports, {
2316
+ apply: () => apply,
2317
+ compare: () => compare,
2318
+ createUnifiedPatch: () => createUnifiedPatch,
2319
+ parsePatchFile: () => parsePatchFile,
2320
+ unifiedDiff: () => unifiedDiff
2321
+ });
2322
+ function compare(a, b, options = {}) {
2323
+ const type = options.type ?? "line";
2324
+ let rawChanges;
2325
+ switch (type) {
2326
+ case "word":
2327
+ rawChanges = diff$1.diffWords(a, b, {
2328
+ ignoreWhitespace: options.ignoreWhitespace
2329
+ });
2330
+ break;
2331
+ case "char":
2332
+ rawChanges = diff$1.diffChars(a, b);
2333
+ break;
2334
+ case "line":
2335
+ default:
2336
+ rawChanges = diff$1.diffLines(a, b, {
2337
+ ignoreWhitespace: options.ignoreWhitespace
2338
+ });
2339
+ break;
2340
+ }
2341
+ const changes = rawChanges.map((c) => ({
2342
+ type: c.added ? "added" : c.removed ? "removed" : "unchanged",
2343
+ value: c.value,
2344
+ count: c.count ?? 0
2345
+ }));
2346
+ let additions = 0;
2347
+ let deletions = 0;
2348
+ let unchanged = 0;
2349
+ for (const change of changes) {
2350
+ switch (change.type) {
2351
+ case "added":
2352
+ additions += change.count;
2353
+ break;
2354
+ case "removed":
2355
+ deletions += change.count;
2356
+ break;
2357
+ case "unchanged":
2358
+ unchanged += change.count;
2359
+ break;
2360
+ }
2361
+ }
2362
+ return {
2363
+ identical: additions === 0 && deletions === 0,
2364
+ changes,
2365
+ stats: { additions, deletions, unchanged }
2366
+ };
2367
+ }
2368
+ function unifiedDiff(a, b, options = {}) {
2369
+ const fromFile = options.fromFile ?? "a";
2370
+ const toFile = options.toFile ?? "b";
2371
+ const context = options.context ?? 3;
2372
+ return diff$1.createTwoFilesPatch(fromFile, toFile, a, b, void 0, void 0, {
2373
+ context
2374
+ });
2375
+ }
2376
+ function createUnifiedPatch(fileName, original, modified, context = 3) {
2377
+ return diff$1.createPatch(fileName, original, modified, void 0, void 0, {
2378
+ context
2379
+ });
2380
+ }
2381
+ function apply(input, patch, options = {}) {
2382
+ const result = diff$1.applyPatch(input, patch, {
2383
+ fuzzFactor: options.fuzz ?? 0
2384
+ });
2385
+ if (result === false) {
2386
+ throw new Error("Failed to apply patch: patch does not match the input");
2387
+ }
2388
+ return result;
2389
+ }
2390
+ function parsePatchFile(patch) {
2391
+ return diff$1.parsePatch(patch);
2392
+ }
2393
+
2394
+ // src/sql/index.ts
2395
+ var sql_exports = {};
2396
+ __export(sql_exports, {
2397
+ convert: () => convert6,
2398
+ format: () => format3,
2399
+ getStats: () => getStats8,
2400
+ minify: () => minify3,
2401
+ parse: () => parse6,
2402
+ validate: () => validate4
2403
+ });
2404
+ var dialectMap = {
2405
+ mysql: "mysql",
2406
+ postgresql: "postgresql",
2407
+ sqlite: "sqlite",
2408
+ transactsql: "transactsql",
2409
+ bigquery: "bigquery"
2410
+ };
2411
+ function format3(input, options = {}) {
2412
+ const language = dialectMap[options.dialect ?? "postgresql"] ?? "postgresql";
2413
+ return sqlFormatter.format(input, {
2414
+ language,
2415
+ tabWidth: options.indent ?? 2,
2416
+ useTabs: false,
2417
+ keywordCase: options.uppercase !== false ? "upper" : "preserve",
2418
+ linesBetweenQueries: options.linesBetweenQueries ?? 2
2419
+ });
2420
+ }
2421
+ function minify3(input) {
2422
+ return input.replace(/--.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, "").replace(/\s+/g, " ").replace(/\s*([,;()=<>+\-*/])\s*/g, "$1").trim();
2423
+ }
2424
+ var parserDialectMap = {
2425
+ mysql: "MySQL",
2426
+ postgresql: "PostgresQL",
2427
+ sqlite: "SQLite",
2428
+ transactsql: "TransactSQL",
2429
+ bigquery: "BigQuery"
2430
+ };
2431
+ function parse6(input, dialect = "postgresql") {
2432
+ const parser = new nodeSqlParser.Parser();
2433
+ const dbType = parserDialectMap[dialect] ?? "PostgresQL";
2434
+ const ast = parser.astify(input, { database: dbType });
2435
+ const stmts = Array.isArray(ast) ? ast : [ast];
2436
+ const tables = /* @__PURE__ */ new Set();
2437
+ const columns = /* @__PURE__ */ new Set();
2438
+ for (const stmt of stmts) {
2439
+ extractTablesAndColumns(stmt, tables, columns);
2440
+ }
2441
+ return {
2442
+ type: stmts[0]?.type ?? "unknown",
2443
+ tables: Array.from(tables),
2444
+ columns: Array.from(columns),
2445
+ ast
2446
+ };
2447
+ }
2448
+ function validate4(input, dialect = "postgresql") {
2449
+ const parser = new nodeSqlParser.Parser();
2450
+ const dbType = parserDialectMap[dialect] ?? "PostgresQL";
2451
+ try {
2452
+ const ast = parser.astify(input, { database: dbType });
2453
+ return { valid: true, ast };
2454
+ } catch (e) {
2455
+ return {
2456
+ valid: false,
2457
+ error: e.message
2458
+ };
2459
+ }
2460
+ }
2461
+ function getStats8(input, dialect = "postgresql") {
2462
+ const parser = new nodeSqlParser.Parser();
2463
+ const dbType = parserDialectMap[dialect] ?? "PostgresQL";
2464
+ const ast = parser.astify(input, { database: dbType });
2465
+ const stmts = Array.isArray(ast) ? ast : [ast];
2466
+ const queryTypes = {};
2467
+ const tables = /* @__PURE__ */ new Set();
2468
+ let joins = 0;
2469
+ for (const stmt of stmts) {
2470
+ const type = (stmt.type ?? "unknown").toLowerCase();
2471
+ queryTypes[type] = (queryTypes[type] || 0) + 1;
2472
+ extractTablesAndColumns(stmt, tables, /* @__PURE__ */ new Set());
2473
+ const stmtStr = JSON.stringify(stmt);
2474
+ const joinMatches = stmtStr.match(/"join"/gi);
2475
+ if (joinMatches) joins += joinMatches.length;
2476
+ }
2477
+ const subqueryRegex = /\bSELECT\b/gi;
2478
+ const selectMatches = input.match(subqueryRegex);
2479
+ const subqueries = Math.max(0, (selectMatches?.length ?? 0) - stmts.filter((s) => s.type === "select").length);
2480
+ return {
2481
+ queryCount: stmts.length,
2482
+ queryTypes,
2483
+ tables: Array.from(tables),
2484
+ joins,
2485
+ subqueries
2486
+ };
2487
+ }
2488
+ function extractTablesAndColumns(node, tables, columns) {
2489
+ if (!node || typeof node !== "object") return;
2490
+ const obj = node;
2491
+ if (obj.table && typeof obj.table === "string") {
2492
+ tables.add(obj.table);
2493
+ }
2494
+ if (obj.from && Array.isArray(obj.from)) {
2495
+ for (const item of obj.from) {
2496
+ if (item && typeof item === "object" && "table" in item) {
2497
+ tables.add(String(item.table));
2498
+ }
2499
+ }
2500
+ }
2501
+ if (obj.columns && Array.isArray(obj.columns)) {
2502
+ for (const col of obj.columns) {
2503
+ if (col && typeof col === "object" && "expr" in col) {
2504
+ const expr = col.expr;
2505
+ if (expr.type === "column_ref" && typeof expr.column === "string") {
2506
+ columns.add(expr.column);
2507
+ }
2508
+ }
2509
+ }
2510
+ }
2511
+ for (const value of Object.values(obj)) {
2512
+ if (Array.isArray(value)) {
2513
+ for (const item of value) {
2514
+ extractTablesAndColumns(item, tables, columns);
2515
+ }
2516
+ } else if (typeof value === "object" && value !== null) {
2517
+ extractTablesAndColumns(value, tables, columns);
2518
+ }
2519
+ }
2520
+ }
2521
+ var parserDialectMap2 = {
2522
+ mysql: "MySQL",
2523
+ postgresql: "PostgresQL",
2524
+ sqlite: "SQLite",
2525
+ transactsql: "TransactSQL",
2526
+ bigquery: "BigQuery"
2527
+ };
2528
+ function convert6(input, options) {
2529
+ const fromDialect = parserDialectMap2[options.from ?? "postgresql"] ?? "PostgresQL";
2530
+ const toDialect = parserDialectMap2[options.to] ?? "PostgresQL";
2531
+ const parser = new nodeSqlParser.Parser();
2532
+ const ast = parser.astify(input, { database: fromDialect });
2533
+ return parser.sqlify(ast, { database: toDialect });
2534
+ }
2535
+
2536
+ // src/crypto/index.ts
2537
+ var crypto_exports = {};
2538
+ __export(crypto_exports, {
2539
+ checksum: () => checksum,
2540
+ decode: () => decode,
2541
+ decodeJwt: () => decodeJwt,
2542
+ encode: () => encode,
2543
+ generateUuid: () => generateUuid,
2544
+ hash: () => hash,
2545
+ hmac: () => hmac
2546
+ });
2547
+ function hash(input, algorithm = "sha256") {
2548
+ const h = crypto.createHash(algorithm).update(input).digest("hex");
2549
+ return {
2550
+ algorithm,
2551
+ hash: h,
2552
+ inputLength: input.length
2553
+ };
2554
+ }
2555
+ function hmac(input, key, options = {}) {
2556
+ const algorithm = options.algorithm ?? "sha256";
2557
+ const h = crypto.createHmac(algorithm, key).update(input).digest("hex");
2558
+ return {
2559
+ algorithm,
2560
+ hmac: h
2561
+ };
2562
+ }
2563
+ function checksum(data, algorithm = "sha256") {
2564
+ const buffer = typeof data === "string" ? Buffer.from(data) : Buffer.from(data);
2565
+ const h = crypto.createHash(algorithm).update(buffer).digest("hex");
2566
+ return {
2567
+ algorithm,
2568
+ checksum: h,
2569
+ sizeBytes: buffer.length
2570
+ };
2571
+ }
2572
+ function generateUuid() {
2573
+ let uuid;
2574
+ if (typeof globalThis.crypto?.randomUUID === "function") {
2575
+ uuid = globalThis.crypto.randomUUID();
2576
+ } else {
2577
+ uuid = crypto.randomUUID();
2578
+ }
2579
+ return {
2580
+ uuid,
2581
+ version: 4
2582
+ };
2583
+ }
2584
+
2585
+ // src/crypto/encode.ts
2586
+ function encode(input, format4) {
2587
+ switch (format4) {
2588
+ case "base64":
2589
+ return Buffer.from(input).toString("base64");
2590
+ case "hex":
2591
+ return Buffer.from(input).toString("hex");
2592
+ case "url":
2593
+ return encodeURIComponent(input);
2594
+ case "html":
2595
+ return input.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
2596
+ default:
2597
+ throw new Error(`Unsupported encoding format: ${format4}`);
2598
+ }
2599
+ }
2600
+ function decode(input, format4) {
2601
+ switch (format4) {
2602
+ case "base64":
2603
+ return Buffer.from(input, "base64").toString("utf8");
2604
+ case "hex":
2605
+ return Buffer.from(input, "hex").toString("utf8");
2606
+ case "url":
2607
+ return decodeURIComponent(input);
2608
+ case "html":
2609
+ return input.replace(/&#39;/g, "'").replace(/&quot;/g, '"').replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/&amp;/g, "&");
2610
+ default:
2611
+ throw new Error(`Unsupported encoding format: ${format4}`);
2612
+ }
2613
+ }
2614
+
2615
+ // src/crypto/jwt.ts
2616
+ function base64UrlDecode(str) {
2617
+ let base64 = str.replace(/-/g, "+").replace(/_/g, "/");
2618
+ const padding = base64.length % 4;
2619
+ if (padding) {
2620
+ base64 += "=".repeat(4 - padding);
2621
+ }
2622
+ if (typeof atob === "function") {
2623
+ return decodeURIComponent(
2624
+ atob(base64).split("").map((c) => "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2)).join("")
2625
+ );
2626
+ }
2627
+ return Buffer.from(base64, "base64").toString("utf8");
2628
+ }
2629
+ function decodeJwt(token) {
2630
+ const parts = token.split(".");
2631
+ if (parts.length !== 3) {
2632
+ throw new Error("Invalid JWT: must have 3 parts separated by dots");
2633
+ }
2634
+ const header = JSON.parse(base64UrlDecode(parts[0]));
2635
+ const payload = JSON.parse(base64UrlDecode(parts[1]));
2636
+ const result = {
2637
+ header,
2638
+ payload,
2639
+ signature: parts[2]
2640
+ };
2641
+ if (typeof payload.exp === "number") {
2642
+ const expDate = new Date(payload.exp * 1e3);
2643
+ result.expired = expDate < /* @__PURE__ */ new Date();
2644
+ result.expiresAt = expDate.toISOString();
2645
+ }
2646
+ return result;
2647
+ }
2648
+
2649
+ // src/datetime/index.ts
2650
+ var datetime_exports = {};
2651
+ __export(datetime_exports, {
2652
+ add: () => add,
2653
+ convertTimezone: () => convertTimezone,
2654
+ diff: () => diff2,
2655
+ formatDate: () => formatDate,
2656
+ listTimezones: () => listTimezones,
2657
+ now: () => now,
2658
+ parseCron: () => parseCron,
2659
+ parseDate: () => parseDate,
2660
+ subtract: () => subtract
2661
+ });
2662
+ function parseDate(input, timezone) {
2663
+ let dt;
2664
+ const unixNum = Number(input);
2665
+ if (!isNaN(unixNum) && String(unixNum) === input.trim()) {
2666
+ dt = unixNum > 1e12 ? luxon.DateTime.fromMillis(unixNum, { zone: timezone ?? "utc" }) : luxon.DateTime.fromSeconds(unixNum, { zone: timezone ?? "utc" });
2667
+ } else {
2668
+ dt = luxon.DateTime.fromISO(input, { zone: timezone ?? "utc" });
2669
+ if (!dt.isValid) {
2670
+ dt = luxon.DateTime.fromRFC2822(input, { zone: timezone ?? "utc" });
2671
+ }
2672
+ if (!dt.isValid) {
2673
+ dt = luxon.DateTime.fromSQL(input, { zone: timezone ?? "utc" });
2674
+ }
2675
+ }
2676
+ if (!dt.isValid) {
2677
+ throw new Error(`Unable to parse date: ${input} (${dt.invalidReason})`);
2678
+ }
2679
+ return {
2680
+ iso: dt.toISO(),
2681
+ unix: Math.floor(dt.toSeconds()),
2682
+ unixMs: dt.toMillis(),
2683
+ year: dt.year,
2684
+ month: dt.month,
2685
+ day: dt.day,
2686
+ hour: dt.hour,
2687
+ minute: dt.minute,
2688
+ second: dt.second,
2689
+ dayOfWeek: dt.weekdayLong,
2690
+ dayOfYear: dt.ordinal,
2691
+ weekNumber: dt.weekNumber,
2692
+ isLeapYear: dt.isInLeapYear,
2693
+ timezone: dt.zoneName,
2694
+ offset: dt.toFormat("ZZ")
2695
+ };
2696
+ }
2697
+ function formatDate(input, options = {}) {
2698
+ const tz = options.timezone ?? "utc";
2699
+ let dt = luxon.DateTime.fromISO(input, { zone: tz });
2700
+ if (!dt.isValid) {
2701
+ dt = luxon.DateTime.fromMillis(Number(input), { zone: tz });
2702
+ }
2703
+ if (!dt.isValid) {
2704
+ throw new Error(`Unable to parse date: ${input}`);
2705
+ }
2706
+ if (options.format) {
2707
+ return dt.toFormat(options.format);
2708
+ }
2709
+ return dt.toISO();
2710
+ }
2711
+ function now(timezone) {
2712
+ const dt = luxon.DateTime.now().setZone(timezone ?? "utc");
2713
+ return parseDate(dt.toISO(), timezone);
2714
+ }
2715
+ function add(input, amount, timezone) {
2716
+ const dt = luxon.DateTime.fromISO(input, { zone: timezone ?? "utc" });
2717
+ if (!dt.isValid) {
2718
+ throw new Error(`Unable to parse date: ${input}`);
2719
+ }
2720
+ const result = dt.plus(amount);
2721
+ return result.toISO();
2722
+ }
2723
+ function subtract(input, amount, timezone) {
2724
+ const dt = luxon.DateTime.fromISO(input, { zone: timezone ?? "utc" });
2725
+ if (!dt.isValid) {
2726
+ throw new Error(`Unable to parse date: ${input}`);
2727
+ }
2728
+ const result = dt.minus(amount);
2729
+ return result.toISO();
2730
+ }
2731
+ function diff2(a, b) {
2732
+ const dtA = luxon.DateTime.fromISO(a, { zone: "utc" });
2733
+ const dtB = luxon.DateTime.fromISO(b, { zone: "utc" });
2734
+ if (!dtA.isValid || !dtB.isValid) {
2735
+ throw new Error("Unable to parse one or both dates");
2736
+ }
2737
+ const duration = dtB.diff(dtA, [
2738
+ "years",
2739
+ "months",
2740
+ "days",
2741
+ "hours",
2742
+ "minutes",
2743
+ "seconds"
2744
+ ]);
2745
+ const totalMs = dtB.toMillis() - dtA.toMillis();
2746
+ return {
2747
+ years: Math.floor(duration.years),
2748
+ months: Math.floor(duration.months),
2749
+ days: Math.floor(duration.days),
2750
+ hours: Math.floor(duration.hours),
2751
+ minutes: Math.floor(duration.minutes),
2752
+ seconds: Math.floor(duration.seconds),
2753
+ totalDays: Math.floor(totalMs / 864e5),
2754
+ totalHours: Math.floor(totalMs / 36e5),
2755
+ totalMinutes: Math.floor(totalMs / 6e4),
2756
+ totalSeconds: Math.floor(totalMs / 1e3),
2757
+ totalMilliseconds: totalMs
2758
+ };
2759
+ }
2760
+ function convertTimezone(input, fromTimezone, toTimezone) {
2761
+ const dtFrom = luxon.DateTime.fromISO(input, { zone: fromTimezone });
2762
+ if (!dtFrom.isValid) {
2763
+ throw new Error(`Unable to parse date: ${input} in timezone ${fromTimezone}`);
2764
+ }
2765
+ const dtTo = dtFrom.setZone(toTimezone);
2766
+ if (!dtTo.isValid) {
2767
+ throw new Error(`Invalid target timezone: ${toTimezone}`);
2768
+ }
2769
+ const offsetFrom = dtFrom.offset;
2770
+ const offsetTo = dtTo.offset;
2771
+ const diffMinutes = offsetTo - offsetFrom;
2772
+ const sign = diffMinutes >= 0 ? "+" : "-";
2773
+ const absMinutes = Math.abs(diffMinutes);
2774
+ const hours = Math.floor(absMinutes / 60);
2775
+ const minutes = absMinutes % 60;
2776
+ return {
2777
+ input: dtFrom.toISO(),
2778
+ inputTimezone: fromTimezone,
2779
+ output: dtTo.toISO(),
2780
+ outputTimezone: toTimezone,
2781
+ offsetDifference: `${sign}${String(hours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}`
2782
+ };
2783
+ }
2784
+ function listTimezones() {
2785
+ return Intl.supportedValuesOf("timeZone");
2786
+ }
2787
+
2788
+ // src/datetime/cron.ts
2789
+ var MONTH_NAMES = ["", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
2790
+ var DAY_NAMES = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
2791
+ function parseCron(expression, count = 5) {
2792
+ const parts = expression.trim().split(/\s+/);
2793
+ if (parts.length !== 5) {
2794
+ return {
2795
+ valid: false,
2796
+ description: "",
2797
+ nextRuns: [],
2798
+ error: `Expected 5 fields, got ${parts.length}`
2799
+ };
2800
+ }
2801
+ try {
2802
+ const description = describeCron(parts);
2803
+ const nextRuns = getNextRuns(parts, count);
2804
+ return {
2805
+ valid: true,
2806
+ description,
2807
+ nextRuns: nextRuns.map((d) => d.toISOString())
2808
+ };
2809
+ } catch (e) {
2810
+ return {
2811
+ valid: false,
2812
+ description: "",
2813
+ nextRuns: [],
2814
+ error: e.message
2815
+ };
2816
+ }
2817
+ }
2818
+ function describeCron(parts) {
2819
+ const [min, hour, dom, month, dow] = parts;
2820
+ const segments = [];
2821
+ if (min === "*" && hour === "*" && dom === "*" && month === "*" && dow === "*") {
2822
+ return "Every minute";
2823
+ }
2824
+ if (min !== "*") segments.push(`at minute ${min}`);
2825
+ if (hour !== "*") segments.push(`at hour ${hour}`);
2826
+ if (dom !== "*") segments.push(`on day ${dom} of the month`);
2827
+ if (month !== "*") {
2828
+ const m = parseInt(month);
2829
+ segments.push(`in ${!isNaN(m) && m >= 1 && m <= 12 ? MONTH_NAMES[m] : month}`);
2830
+ }
2831
+ if (dow !== "*") {
2832
+ const d = parseInt(dow);
2833
+ segments.push(`on ${!isNaN(d) && d >= 0 && d <= 6 ? DAY_NAMES[d] : dow}`);
2834
+ }
2835
+ return segments.join(", ") || "Every minute";
2836
+ }
2837
+ function getNextRuns(parts, count) {
2838
+ const runs = [];
2839
+ const now2 = /* @__PURE__ */ new Date();
2840
+ const current = new Date(now2);
2841
+ current.setSeconds(0, 0);
2842
+ current.setMinutes(current.getMinutes() + 1);
2843
+ const maxIterations = 525600;
2844
+ let iterations = 0;
2845
+ while (runs.length < count && iterations < maxIterations) {
2846
+ if (matchesCron(current, parts)) {
2847
+ runs.push(new Date(current));
2848
+ }
2849
+ current.setMinutes(current.getMinutes() + 1);
2850
+ iterations++;
2851
+ }
2852
+ return runs;
2853
+ }
2854
+ function matchesCron(date, parts) {
2855
+ const [minExpr, hourExpr, domExpr, monthExpr, dowExpr] = parts;
2856
+ return matchesField(date.getMinutes(), minExpr, 0, 59) && matchesField(date.getHours(), hourExpr, 0, 23) && matchesField(date.getDate(), domExpr, 1, 31) && matchesField(date.getMonth() + 1, monthExpr, 1, 12) && matchesField(date.getDay(), dowExpr, 0, 6);
2857
+ }
2858
+ function matchesField(value, expr, min, max) {
2859
+ if (expr === "*") return true;
2860
+ for (const part of expr.split(",")) {
2861
+ if (part.includes("/")) {
2862
+ const [range, stepStr] = part.split("/");
2863
+ const step = parseInt(stepStr);
2864
+ const start = range === "*" ? min : parseInt(range);
2865
+ for (let i = start; i <= max; i += step) {
2866
+ if (i === value) return true;
2867
+ }
2868
+ } else if (part.includes("-")) {
2869
+ const [startStr, endStr] = part.split("-");
2870
+ const start = parseInt(startStr);
2871
+ const end = parseInt(endStr);
2872
+ if (value >= start && value <= end) return true;
2873
+ } else {
2874
+ if (parseInt(part) === value) return true;
2875
+ }
2876
+ }
2877
+ return false;
2878
+ }
2879
+
2880
+ // src/text/index.ts
2881
+ var text_exports = {};
2882
+ __export(text_exports, {
2883
+ convertCase: () => convertCase,
2884
+ generateLorem: () => generateLorem,
2885
+ getTextStats: () => getTextStats,
2886
+ interpolate: () => interpolate,
2887
+ similarity: () => similarity,
2888
+ slugify: () => slugify,
2889
+ truncate: () => truncate
2890
+ });
2891
+
2892
+ // src/text/case.ts
2893
+ function splitWords(input) {
2894
+ return input.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/[-_]/g, " ").split(/\s+/).filter((word) => word.length > 0);
2895
+ }
2896
+ function capitalize(word) {
2897
+ return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
2898
+ }
2899
+ function convertCase(input, to) {
2900
+ const words = splitWords(input);
2901
+ if (words.length === 0) {
2902
+ return "";
2903
+ }
2904
+ switch (to) {
2905
+ case "camel":
2906
+ return words.map((word, index) => index === 0 ? word.toLowerCase() : capitalize(word)).join("");
2907
+ case "pascal":
2908
+ return words.map((word) => capitalize(word)).join("");
2909
+ case "snake":
2910
+ return words.map((word) => word.toLowerCase()).join("_");
2911
+ case "kebab":
2912
+ return words.map((word) => word.toLowerCase()).join("-");
2913
+ case "constant":
2914
+ return words.map((word) => word.toUpperCase()).join("_");
2915
+ case "title":
2916
+ return words.map((word) => capitalize(word)).join(" ");
2917
+ case "sentence":
2918
+ return words.map((word, index) => index === 0 ? capitalize(word) : word.toLowerCase()).join(" ");
2919
+ case "upper":
2920
+ return words.map((word) => word.toUpperCase()).join(" ");
2921
+ case "lower":
2922
+ return words.map((word) => word.toLowerCase()).join(" ");
2923
+ }
2924
+ }
2925
+
2926
+ // src/text/slug.ts
2927
+ function slugify(input, separator = "-") {
2928
+ return input.toLowerCase().replace(/[^a-z0-9]+/g, separator).replace(new RegExp(`${escapeRegExp(separator)}+`, "g"), separator).replace(new RegExp(`^${escapeRegExp(separator)}|${escapeRegExp(separator)}$`, "g"), "");
2929
+ }
2930
+ function escapeRegExp(str) {
2931
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2932
+ }
2933
+
2934
+ // src/text/stats.ts
2935
+ function getTextStats(input) {
2936
+ const characters = input.length;
2937
+ const words = input.split(/\s+/).filter((word) => word.length > 0);
2938
+ const sentences = input.split(/[.!?](?:\s|$)/).filter((sentence) => sentence.trim().length > 0);
2939
+ const paragraphs = input.split(/\n\n+/).filter((paragraph) => paragraph.trim().length > 0);
2940
+ const lines = input.split(/\n/);
2941
+ const readingTimeMs = words.length / 200 * 60 * 1e3;
2942
+ return {
2943
+ characters,
2944
+ words: words.length,
2945
+ sentences: sentences.length,
2946
+ paragraphs: paragraphs.length,
2947
+ lines: lines.length,
2948
+ readingTimeMs
2949
+ };
2950
+ }
2951
+
2952
+ // src/text/truncate.ts
2953
+ function truncate(input, options) {
2954
+ const { length, boundary = "word", suffix = "..." } = options;
2955
+ if (input.length <= length) {
2956
+ return input;
2957
+ }
2958
+ const maxContentLength = length - suffix.length;
2959
+ if (maxContentLength <= 0) {
2960
+ return suffix.slice(0, length);
2961
+ }
2962
+ if (boundary === "character") {
2963
+ return input.slice(0, maxContentLength) + suffix;
2964
+ }
2965
+ const truncated = input.slice(0, maxContentLength);
2966
+ const lastSpaceIndex = truncated.lastIndexOf(" ");
2967
+ if (lastSpaceIndex === -1) {
2968
+ return truncated + suffix;
2969
+ }
2970
+ return input.slice(0, lastSpaceIndex) + suffix;
2971
+ }
2972
+
2973
+ // src/text/lorem.ts
2974
+ var LOREM_WORDS = [
2975
+ "lorem",
2976
+ "ipsum",
2977
+ "dolor",
2978
+ "sit",
2979
+ "amet",
2980
+ "consectetur",
2981
+ "adipiscing",
2982
+ "elit",
2983
+ "sed",
2984
+ "do",
2985
+ "eiusmod",
2986
+ "tempor",
2987
+ "incididunt",
2988
+ "ut",
2989
+ "labore",
2990
+ "et",
2991
+ "dolore",
2992
+ "magna",
2993
+ "aliqua",
2994
+ "enim",
2995
+ "ad",
2996
+ "minim",
2997
+ "veniam",
2998
+ "quis",
2999
+ "nostrud",
3000
+ "exercitation",
3001
+ "ullamco",
3002
+ "laboris",
3003
+ "nisi",
3004
+ "aliquip",
3005
+ "ex",
3006
+ "ea",
3007
+ "commodo",
3008
+ "consequat",
3009
+ "duis",
3010
+ "aute",
3011
+ "irure",
3012
+ "in",
3013
+ "reprehenderit",
3014
+ "voluptate",
3015
+ "velit",
3016
+ "esse",
3017
+ "cillum",
3018
+ "fugiat",
3019
+ "nulla",
3020
+ "pariatur",
3021
+ "excepteur",
3022
+ "sint",
3023
+ "occaecat",
3024
+ "cupidatat"
3025
+ ];
3026
+ function getWord(index) {
3027
+ return LOREM_WORDS[index % LOREM_WORDS.length];
3028
+ }
3029
+ function generateSentence(wordOffset) {
3030
+ const wordCount = 8 + wordOffset % 8;
3031
+ const words = [];
3032
+ for (let i = 0; i < wordCount; i++) {
3033
+ words.push(getWord(wordOffset + i));
3034
+ }
3035
+ words[0] = words[0].charAt(0).toUpperCase() + words[0].slice(1);
3036
+ return {
3037
+ sentence: words.join(" ") + ".",
3038
+ nextOffset: wordOffset + wordCount
3039
+ };
3040
+ }
3041
+ function generateLorem(count, unit = "words") {
3042
+ if (count <= 0) {
3043
+ return "";
3044
+ }
3045
+ if (unit === "words") {
3046
+ const words = [];
3047
+ for (let i = 0; i < count; i++) {
3048
+ words.push(getWord(i));
3049
+ }
3050
+ return words.join(" ");
3051
+ }
3052
+ if (unit === "sentences") {
3053
+ const sentences = [];
3054
+ let offset2 = 0;
3055
+ for (let i = 0; i < count; i++) {
3056
+ const { sentence, nextOffset } = generateSentence(offset2);
3057
+ sentences.push(sentence);
3058
+ offset2 = nextOffset;
3059
+ }
3060
+ return sentences.join(" ");
3061
+ }
3062
+ const paragraphs = [];
3063
+ let offset = 0;
3064
+ for (let i = 0; i < count; i++) {
3065
+ const sentenceCount = 3 + i % 4;
3066
+ const sentences = [];
3067
+ for (let j = 0; j < sentenceCount; j++) {
3068
+ const { sentence, nextOffset } = generateSentence(offset);
3069
+ sentences.push(sentence);
3070
+ offset = nextOffset;
3071
+ }
3072
+ paragraphs.push(sentences.join(" "));
3073
+ }
3074
+ return paragraphs.join("\n\n");
3075
+ }
3076
+
3077
+ // src/text/similarity.ts
3078
+ function similarity(a, b) {
3079
+ if (a === b) {
3080
+ return { distance: 0, similarity: 1 };
3081
+ }
3082
+ if (a.length === 0) {
3083
+ return { distance: b.length, similarity: 0 };
3084
+ }
3085
+ if (b.length === 0) {
3086
+ return { distance: a.length, similarity: 0 };
3087
+ }
3088
+ const m = a.length;
3089
+ const n = b.length;
3090
+ const dp = [];
3091
+ for (let i = 0; i <= m; i++) {
3092
+ dp[i] = new Array(n + 1);
3093
+ dp[i][0] = i;
3094
+ }
3095
+ for (let j = 0; j <= n; j++) {
3096
+ dp[0][j] = j;
3097
+ }
3098
+ for (let i = 1; i <= m; i++) {
3099
+ for (let j = 1; j <= n; j++) {
3100
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
3101
+ dp[i][j] = Math.min(
3102
+ dp[i - 1][j] + 1,
3103
+ // deletion
3104
+ dp[i][j - 1] + 1,
3105
+ // insertion
3106
+ dp[i - 1][j - 1] + cost
3107
+ // substitution
3108
+ );
3109
+ }
3110
+ }
3111
+ const distance = dp[m][n];
3112
+ const maxLength = Math.max(m, n);
3113
+ const sim = 1 - distance / maxLength;
3114
+ return { distance, similarity: sim };
3115
+ }
3116
+
3117
+ // src/text/template.ts
3118
+ function interpolate(template, variables) {
3119
+ const missingKeys = [];
3120
+ const result = template.replace(/\{\{\s*(\w+)\s*\}\}/g, (match, key) => {
3121
+ if (key in variables) {
3122
+ return variables[key];
3123
+ }
3124
+ missingKeys.push(key);
3125
+ return match;
3126
+ });
3127
+ const uniqueMissingKeys = [...new Set(missingKeys)];
3128
+ return { result, missingKeys: uniqueMissingKeys };
3129
+ }
3130
+
3131
+ // src/math/index.ts
3132
+ var math_exports = {};
3133
+ __export(math_exports, {
3134
+ calculateStats: () => calculateStats,
3135
+ convertBase: () => convertBase,
3136
+ convertUnit: () => convertUnit,
3137
+ formatNumber: () => formatNumber,
3138
+ percentage: () => percentage,
3139
+ percentageChange: () => percentageChange
3140
+ });
3141
+
3142
+ // src/math/convert.ts
3143
+ var lengthFactors = {
3144
+ mm: 1e-3,
3145
+ cm: 0.01,
3146
+ m: 1,
3147
+ km: 1e3,
3148
+ in: 0.0254,
3149
+ ft: 0.3048,
3150
+ yd: 0.9144,
3151
+ mi: 1609.344
3152
+ };
3153
+ var weightFactors = {
3154
+ mg: 1e-3,
3155
+ g: 1,
3156
+ kg: 1e3,
3157
+ oz: 28.3495,
3158
+ lb: 453.592,
3159
+ ton: 907185
3160
+ };
3161
+ var dataFactors = {
3162
+ b: 1,
3163
+ kb: 1024,
3164
+ mb: Math.pow(1024, 2),
3165
+ gb: Math.pow(1024, 3),
3166
+ tb: Math.pow(1024, 4)
3167
+ };
3168
+ var temperatureUnits = /* @__PURE__ */ new Set(["celsius", "fahrenheit", "kelvin"]);
3169
+ function convertTemperature(value, from, to) {
3170
+ if (from === to) return value;
3171
+ let celsius;
3172
+ switch (from) {
3173
+ case "celsius":
3174
+ celsius = value;
3175
+ break;
3176
+ case "fahrenheit":
3177
+ celsius = (value - 32) * 5 / 9;
3178
+ break;
3179
+ case "kelvin":
3180
+ celsius = value - 273.15;
3181
+ break;
3182
+ default:
3183
+ throw new Error(`Unknown temperature unit: ${from}`);
3184
+ }
3185
+ switch (to) {
3186
+ case "celsius":
3187
+ return celsius;
3188
+ case "fahrenheit":
3189
+ return celsius * 9 / 5 + 32;
3190
+ case "kelvin":
3191
+ return celsius + 273.15;
3192
+ default:
3193
+ throw new Error(`Unknown temperature unit: ${to}`);
3194
+ }
3195
+ }
3196
+ function getFactors(category) {
3197
+ switch (category) {
3198
+ case "length":
3199
+ return lengthFactors;
3200
+ case "weight":
3201
+ return weightFactors;
3202
+ case "data":
3203
+ return dataFactors;
3204
+ default:
3205
+ throw new Error(`No conversion factors for category: ${category}`);
3206
+ }
3207
+ }
3208
+ function convertUnit(value, from, to, category) {
3209
+ const fromLower = from.toLowerCase();
3210
+ const toLower = to.toLowerCase();
3211
+ if (category === "temperature") {
3212
+ if (!temperatureUnits.has(fromLower)) {
3213
+ throw new Error(`Unit '${from}' does not belong to category 'temperature'`);
3214
+ }
3215
+ if (!temperatureUnits.has(toLower)) {
3216
+ throw new Error(`Unit '${to}' does not belong to category 'temperature'`);
3217
+ }
3218
+ const result2 = convertTemperature(value, fromLower, toLower);
3219
+ return { value, from: fromLower, to: toLower, result: result2 };
3220
+ }
3221
+ const factors = getFactors(category);
3222
+ if (!(fromLower in factors)) {
3223
+ throw new Error(`Unit '${from}' does not belong to category '${category}'`);
3224
+ }
3225
+ if (!(toLower in factors)) {
3226
+ throw new Error(`Unit '${to}' does not belong to category '${category}'`);
3227
+ }
3228
+ const baseValue = value * factors[fromLower];
3229
+ const result = baseValue / factors[toLower];
3230
+ return { value, from: fromLower, to: toLower, result };
3231
+ }
3232
+
3233
+ // src/math/base.ts
3234
+ var radixMap = {
3235
+ binary: 2,
3236
+ octal: 8,
3237
+ decimal: 10,
3238
+ hex: 16
3239
+ };
3240
+ function convertBase(input, fromBase) {
3241
+ const radix = radixMap[fromBase];
3242
+ if (radix === void 0) {
3243
+ throw new Error(`Unknown base: ${fromBase}`);
3244
+ }
3245
+ let cleanInput = input.trim();
3246
+ if (fromBase === "binary" && cleanInput.startsWith("0b")) {
3247
+ cleanInput = cleanInput.slice(2);
3248
+ } else if (fromBase === "octal" && cleanInput.startsWith("0o")) {
3249
+ cleanInput = cleanInput.slice(2);
3250
+ } else if (fromBase === "hex" && cleanInput.startsWith("0x")) {
3251
+ cleanInput = cleanInput.slice(2);
3252
+ }
3253
+ const decimalValue = parseInt(cleanInput, radix);
3254
+ if (isNaN(decimalValue)) {
3255
+ throw new Error(`Invalid input '${input}' for base '${fromBase}'`);
3256
+ }
3257
+ return {
3258
+ input,
3259
+ fromBase,
3260
+ binary: "0b" + decimalValue.toString(2),
3261
+ octal: "0o" + decimalValue.toString(8),
3262
+ decimal: decimalValue.toString(10),
3263
+ hex: "0x" + decimalValue.toString(16)
3264
+ };
3265
+ }
3266
+
3267
+ // src/math/statistics.ts
3268
+ function getPercentile(sorted, p) {
3269
+ if (sorted.length === 1) return sorted[0];
3270
+ const index = p / 100 * (sorted.length - 1);
3271
+ const lower = Math.floor(index);
3272
+ const upper = Math.ceil(index);
3273
+ if (lower === upper) return sorted[lower];
3274
+ const fraction = index - lower;
3275
+ return sorted[lower] + fraction * (sorted[upper] - sorted[lower]);
3276
+ }
3277
+ function calculateStats(numbers) {
3278
+ if (numbers.length === 0) {
3279
+ throw new Error("Cannot calculate statistics for an empty array");
3280
+ }
3281
+ const count = numbers.length;
3282
+ const sum = numbers.reduce((acc, n) => acc + n, 0);
3283
+ const mean = sum / count;
3284
+ const sorted = [...numbers].sort((a, b) => a - b);
3285
+ let median;
3286
+ const mid = Math.floor(sorted.length / 2);
3287
+ if (sorted.length % 2 === 0) {
3288
+ median = (sorted[mid - 1] + sorted[mid]) / 2;
3289
+ } else {
3290
+ median = sorted[mid];
3291
+ }
3292
+ const frequencyMap = /* @__PURE__ */ new Map();
3293
+ for (const n of numbers) {
3294
+ frequencyMap.set(n, (frequencyMap.get(n) || 0) + 1);
3295
+ }
3296
+ let maxFrequency = 0;
3297
+ for (const freq of frequencyMap.values()) {
3298
+ if (freq > maxFrequency) maxFrequency = freq;
3299
+ }
3300
+ const mode = [];
3301
+ for (const [value, freq] of frequencyMap.entries()) {
3302
+ if (freq === maxFrequency) mode.push(value);
3303
+ }
3304
+ mode.sort((a, b) => a - b);
3305
+ const min = sorted[0];
3306
+ const max = sorted[sorted.length - 1];
3307
+ const range = max - min;
3308
+ const variance = numbers.reduce((acc, n) => acc + Math.pow(n - mean, 2), 0) / count;
3309
+ const standardDeviation = Math.sqrt(variance);
3310
+ const percentiles = {
3311
+ p25: getPercentile(sorted, 25),
3312
+ p50: getPercentile(sorted, 50),
3313
+ p75: getPercentile(sorted, 75),
3314
+ p90: getPercentile(sorted, 90),
3315
+ p99: getPercentile(sorted, 99)
3316
+ };
3317
+ return {
3318
+ count,
3319
+ sum,
3320
+ mean,
3321
+ median,
3322
+ mode,
3323
+ min,
3324
+ max,
3325
+ range,
3326
+ standardDeviation,
3327
+ variance,
3328
+ percentiles
3329
+ };
3330
+ }
3331
+
3332
+ // src/math/format.ts
3333
+ function formatNumber(value, options) {
3334
+ const locale = options?.locale ?? "en-US";
3335
+ const formatOptions = {};
3336
+ if (options?.style) {
3337
+ formatOptions.style = options.style;
3338
+ }
3339
+ if (options?.currency) {
3340
+ formatOptions.currency = options.currency;
3341
+ }
3342
+ if (options?.minimumFractionDigits !== void 0) {
3343
+ formatOptions.minimumFractionDigits = options.minimumFractionDigits;
3344
+ }
3345
+ if (options?.maximumFractionDigits !== void 0) {
3346
+ formatOptions.maximumFractionDigits = options.maximumFractionDigits;
3347
+ }
3348
+ return new Intl.NumberFormat(locale, formatOptions).format(value);
3349
+ }
3350
+
3351
+ // src/math/percentage.ts
3352
+ function percentage(value, total) {
3353
+ if (total === 0) {
3354
+ throw new Error("Total cannot be zero");
3355
+ }
3356
+ const pct = value / total * 100;
3357
+ return {
3358
+ value,
3359
+ total,
3360
+ percentage: pct,
3361
+ formatted: `${pct}%`
3362
+ };
3363
+ }
3364
+ function percentageChange(from, to) {
3365
+ if (from === 0) {
3366
+ throw new Error("Cannot calculate percentage change from zero");
3367
+ }
3368
+ const change = (to - from) / Math.abs(from) * 100;
3369
+ const sign = change >= 0 ? "+" : "";
3370
+ const formatted = `${sign}${change}%`;
3371
+ return {
3372
+ from,
3373
+ to,
3374
+ change,
3375
+ formatted
3376
+ };
3377
+ }
3378
+
3379
+ // src/color/index.ts
3380
+ var color_exports = {};
3381
+ __export(color_exports, {
3382
+ blendColors: () => blendColors,
3383
+ colorName: () => colorName,
3384
+ contrastRatio: () => contrastRatio,
3385
+ convertColor: () => convertColor,
3386
+ generatePalette: () => generatePalette,
3387
+ hexToRgb: () => hexToRgb,
3388
+ hslToRgb: () => hslToRgb,
3389
+ parseColor: () => parseColor,
3390
+ rgbToHex: () => rgbToHex,
3391
+ rgbToHsl: () => rgbToHsl
3392
+ });
3393
+
3394
+ // src/color/parse.ts
3395
+ function hexToRgb(hex) {
3396
+ let h = hex.replace(/^#/, "");
3397
+ if (h.length === 3) {
3398
+ h = h[0] + h[0] + h[1] + h[1] + h[2] + h[2];
3399
+ }
3400
+ if (h.length !== 6) {
3401
+ throw new Error(`Invalid hex color: ${hex}`);
3402
+ }
3403
+ const num = parseInt(h, 16);
3404
+ if (isNaN(num)) {
3405
+ throw new Error(`Invalid hex color: ${hex}`);
3406
+ }
3407
+ return {
3408
+ r: num >> 16 & 255,
3409
+ g: num >> 8 & 255,
3410
+ b: num & 255
3411
+ };
3412
+ }
3413
+ function hslToRgb(h, s, l) {
3414
+ const sNorm = s / 100;
3415
+ const lNorm = l / 100;
3416
+ const c = (1 - Math.abs(2 * lNorm - 1)) * sNorm;
3417
+ const hPrime = h / 60;
3418
+ const x = c * (1 - Math.abs(hPrime % 2 - 1));
3419
+ const m = lNorm - c / 2;
3420
+ let r1 = 0;
3421
+ let g1 = 0;
3422
+ let b1 = 0;
3423
+ if (hPrime >= 0 && hPrime < 1) {
3424
+ r1 = c;
3425
+ g1 = x;
3426
+ b1 = 0;
3427
+ } else if (hPrime >= 1 && hPrime < 2) {
3428
+ r1 = x;
3429
+ g1 = c;
3430
+ b1 = 0;
3431
+ } else if (hPrime >= 2 && hPrime < 3) {
3432
+ r1 = 0;
3433
+ g1 = c;
3434
+ b1 = x;
3435
+ } else if (hPrime >= 3 && hPrime < 4) {
3436
+ r1 = 0;
3437
+ g1 = x;
3438
+ b1 = c;
3439
+ } else if (hPrime >= 4 && hPrime < 5) {
3440
+ r1 = x;
3441
+ g1 = 0;
3442
+ b1 = c;
3443
+ } else if (hPrime >= 5 && hPrime < 6) {
3444
+ r1 = c;
3445
+ g1 = 0;
3446
+ b1 = x;
3447
+ }
3448
+ return {
3449
+ r: Math.round((r1 + m) * 255),
3450
+ g: Math.round((g1 + m) * 255),
3451
+ b: Math.round((b1 + m) * 255)
3452
+ };
3453
+ }
3454
+ function rgbToHsl(r, g, b) {
3455
+ const rNorm = r / 255;
3456
+ const gNorm = g / 255;
3457
+ const bNorm = b / 255;
3458
+ const max = Math.max(rNorm, gNorm, bNorm);
3459
+ const min = Math.min(rNorm, gNorm, bNorm);
3460
+ const delta = max - min;
3461
+ let h = 0;
3462
+ let s = 0;
3463
+ const l = (max + min) / 2;
3464
+ if (delta !== 0) {
3465
+ s = l > 0.5 ? delta / (2 - max - min) : delta / (max + min);
3466
+ if (max === rNorm) {
3467
+ h = ((gNorm - bNorm) / delta + (gNorm < bNorm ? 6 : 0)) * 60;
3468
+ } else if (max === gNorm) {
3469
+ h = ((bNorm - rNorm) / delta + 2) * 60;
3470
+ } else {
3471
+ h = ((rNorm - gNorm) / delta + 4) * 60;
3472
+ }
3473
+ }
3474
+ return {
3475
+ h: Math.round(h),
3476
+ s: Math.round(s * 100),
3477
+ l: Math.round(l * 100)
3478
+ };
3479
+ }
3480
+ function rgbToHex(r, g, b) {
3481
+ const toHex = (c) => {
3482
+ const hex = Math.max(0, Math.min(255, c)).toString(16);
3483
+ return hex.length === 1 ? "0" + hex : hex;
3484
+ };
3485
+ return "#" + toHex(r) + toHex(g) + toHex(b);
3486
+ }
3487
+ function parseColor(input) {
3488
+ const trimmed = input.trim().toLowerCase();
3489
+ let rgb3;
3490
+ const hexMatch = trimmed.match(/^#([0-9a-f]{3}|[0-9a-f]{6})$/);
3491
+ if (hexMatch) {
3492
+ rgb3 = hexToRgb(trimmed);
3493
+ } else {
3494
+ const rgbMatch = trimmed.match(/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/);
3495
+ if (rgbMatch) {
3496
+ rgb3 = {
3497
+ r: Math.min(255, parseInt(rgbMatch[1], 10)),
3498
+ g: Math.min(255, parseInt(rgbMatch[2], 10)),
3499
+ b: Math.min(255, parseInt(rgbMatch[3], 10))
3500
+ };
3501
+ } else {
3502
+ const hslMatch = trimmed.match(/^hsl\(\s*(\d{1,3})\s*,\s*(\d{1,3})%\s*,\s*(\d{1,3})%\s*\)$/);
3503
+ if (hslMatch) {
3504
+ const h = Math.min(360, parseInt(hslMatch[1], 10));
3505
+ const s = Math.min(100, parseInt(hslMatch[2], 10));
3506
+ const l = Math.min(100, parseInt(hslMatch[3], 10));
3507
+ rgb3 = hslToRgb(h, s, l);
3508
+ } else {
3509
+ throw new Error(`Unsupported color format: ${input}`);
3510
+ }
3511
+ }
3512
+ }
3513
+ const hsl = rgbToHsl(rgb3.r, rgb3.g, rgb3.b);
3514
+ const hex = rgbToHex(rgb3.r, rgb3.g, rgb3.b);
3515
+ return {
3516
+ hex,
3517
+ rgb: `rgb(${rgb3.r}, ${rgb3.g}, ${rgb3.b})`,
3518
+ hsl: `hsl(${hsl.h}, ${hsl.s}%, ${hsl.l}%)`,
3519
+ values: {
3520
+ rgb: rgb3,
3521
+ hsl
3522
+ }
3523
+ };
3524
+ }
3525
+
3526
+ // src/color/convert.ts
3527
+ function convertColor(input, to) {
3528
+ const result = parseColor(input);
3529
+ switch (to) {
3530
+ case "hex":
3531
+ return result.hex;
3532
+ case "rgb":
3533
+ return result.rgb;
3534
+ case "hsl":
3535
+ return result.hsl;
3536
+ default:
3537
+ throw new Error(`Unsupported target format: ${to}`);
3538
+ }
3539
+ }
3540
+
3541
+ // src/color/contrast.ts
3542
+ function srgbChannel(c) {
3543
+ const normalized = c / 255;
3544
+ return normalized <= 0.03928 ? normalized / 12.92 : Math.pow((normalized + 0.055) / 1.055, 2.4);
3545
+ }
3546
+ function relativeLuminance(r, g, b) {
3547
+ return 0.2126 * srgbChannel(r) + 0.7152 * srgbChannel(g) + 0.0722 * srgbChannel(b);
3548
+ }
3549
+ function contrastRatio(color1, color2) {
3550
+ const c1 = parseColor(color1);
3551
+ const c2 = parseColor(color2);
3552
+ const l1 = relativeLuminance(c1.values.rgb.r, c1.values.rgb.g, c1.values.rgb.b);
3553
+ const l2 = relativeLuminance(c2.values.rgb.r, c2.values.rgb.g, c2.values.rgb.b);
3554
+ const lighter = Math.max(l1, l2);
3555
+ const darker = Math.min(l1, l2);
3556
+ const ratio = (lighter + 0.05) / (darker + 0.05);
3557
+ const roundedRatio = Math.round(ratio * 100) / 100;
3558
+ return {
3559
+ ratio: roundedRatio,
3560
+ formatted: `${roundedRatio.toFixed(2)}:1`,
3561
+ aa: {
3562
+ normal: roundedRatio >= 4.5,
3563
+ large: roundedRatio >= 3
3564
+ },
3565
+ aaa: {
3566
+ normal: roundedRatio >= 7,
3567
+ large: roundedRatio >= 4.5
3568
+ }
3569
+ };
3570
+ }
3571
+
3572
+ // src/color/palette.ts
3573
+ function hslToConversionResult(h, s, l) {
3574
+ const normalizedH = (h % 360 + 360) % 360;
3575
+ const rgb3 = hslToRgb(normalizedH, s, l);
3576
+ const hex = rgbToHex(rgb3.r, rgb3.g, rgb3.b);
3577
+ const hslRecalc = rgbToHsl(rgb3.r, rgb3.g, rgb3.b);
3578
+ return {
3579
+ hex,
3580
+ rgb: `rgb(${rgb3.r}, ${rgb3.g}, ${rgb3.b})`,
3581
+ hsl: `hsl(${hslRecalc.h}, ${hslRecalc.s}%, ${hslRecalc.l}%)`,
3582
+ values: {
3583
+ rgb: rgb3,
3584
+ hsl: hslRecalc
3585
+ }
3586
+ };
3587
+ }
3588
+ function generatePalette(base, options) {
3589
+ const parsed = parseColor(base);
3590
+ const { h, s, l } = parsed.values.hsl;
3591
+ const count = options.count ?? 5;
3592
+ switch (options.type) {
3593
+ case "complementary": {
3594
+ return [
3595
+ hslToConversionResult(h, s, l),
3596
+ hslToConversionResult(h + 180, s, l)
3597
+ ];
3598
+ }
3599
+ case "analogous": {
3600
+ const results = [];
3601
+ const spread = 30;
3602
+ const step = spread * 2 / (count - 1);
3603
+ for (let i = 0; i < count; i++) {
3604
+ const hue = h - spread + step * i;
3605
+ results.push(hslToConversionResult(hue, s, l));
3606
+ }
3607
+ return results;
3608
+ }
3609
+ case "triadic": {
3610
+ return [
3611
+ hslToConversionResult(h, s, l),
3612
+ hslToConversionResult(h + 120, s, l),
3613
+ hslToConversionResult(h + 240, s, l)
3614
+ ];
3615
+ }
3616
+ case "shades": {
3617
+ const results = [];
3618
+ const minL = 10;
3619
+ const step = (l - minL) / (count - 1);
3620
+ for (let i = 0; i < count; i++) {
3621
+ const lightness = Math.round(l - step * i);
3622
+ results.push(hslToConversionResult(h, s, lightness));
3623
+ }
3624
+ return results;
3625
+ }
3626
+ case "tints": {
3627
+ const results = [];
3628
+ const maxL = 95;
3629
+ const step = (maxL - l) / (count - 1);
3630
+ for (let i = 0; i < count; i++) {
3631
+ const lightness = Math.round(l + step * i);
3632
+ results.push(hslToConversionResult(h, s, lightness));
3633
+ }
3634
+ return results;
3635
+ }
3636
+ default:
3637
+ throw new Error(`Unsupported palette type: ${options.type}`);
3638
+ }
3639
+ }
3640
+
3641
+ // src/color/blend.ts
3642
+ function blendColors(color1, color2, ratio = 0.5) {
3643
+ if (ratio < 0 || ratio > 1) {
3644
+ throw new Error(`Ratio must be between 0 and 1, got: ${ratio}`);
3645
+ }
3646
+ const c1 = parseColor(color1);
3647
+ const c2 = parseColor(color2);
3648
+ const r = Math.round(c1.values.rgb.r * (1 - ratio) + c2.values.rgb.r * ratio);
3649
+ const g = Math.round(c1.values.rgb.g * (1 - ratio) + c2.values.rgb.g * ratio);
3650
+ const b = Math.round(c1.values.rgb.b * (1 - ratio) + c2.values.rgb.b * ratio);
3651
+ const hex = rgbToHex(r, g, b);
3652
+ const hsl = rgbToHsl(r, g, b);
3653
+ return {
3654
+ color: {
3655
+ hex,
3656
+ rgb: `rgb(${r}, ${g}, ${b})`,
3657
+ hsl: `hsl(${hsl.h}, ${hsl.s}%, ${hsl.l}%)`,
3658
+ values: {
3659
+ rgb: { r, g, b },
3660
+ hsl
3661
+ }
3662
+ },
3663
+ ratio
3664
+ };
3665
+ }
3666
+
3667
+ // src/color/name.ts
3668
+ var NAMED_COLORS = {
3669
+ black: "#000000",
3670
+ white: "#FFFFFF",
3671
+ red: "#FF0000",
3672
+ green: "#008000",
3673
+ blue: "#0000FF",
3674
+ yellow: "#FFFF00",
3675
+ cyan: "#00FFFF",
3676
+ magenta: "#FF00FF",
3677
+ orange: "#FFA500",
3678
+ purple: "#800080",
3679
+ pink: "#FFC0CB",
3680
+ brown: "#A52A2A",
3681
+ gray: "#808080",
3682
+ silver: "#C0C0C0",
3683
+ maroon: "#800000",
3684
+ navy: "#000080",
3685
+ teal: "#008080",
3686
+ olive: "#808000",
3687
+ lime: "#00FF00",
3688
+ aqua: "#00FFFF",
3689
+ coral: "#FF7F50",
3690
+ salmon: "#FA8072",
3691
+ gold: "#FFD700",
3692
+ khaki: "#F0E68C",
3693
+ plum: "#DDA0DD",
3694
+ violet: "#EE82EE",
3695
+ indigo: "#4B0082",
3696
+ beige: "#F5F5DC",
3697
+ ivory: "#FFFFF0",
3698
+ lavender: "#E6E6FA"
3699
+ };
3700
+ function euclideanDistance(r1, g1, b1, r2, g2, b2) {
3701
+ return Math.sqrt(
3702
+ Math.pow(r1 - r2, 2) + Math.pow(g1 - g2, 2) + Math.pow(b1 - b2, 2)
3703
+ );
3704
+ }
3705
+ function colorName(input) {
3706
+ const parsed = parseColor(input);
3707
+ const { r, g, b } = parsed.values.rgb;
3708
+ let closestName = "";
3709
+ let closestHex = "";
3710
+ let closestDistance = Infinity;
3711
+ for (const [name, hex] of Object.entries(NAMED_COLORS)) {
3712
+ const namedRgb = hexToRgb(hex);
3713
+ const distance = euclideanDistance(r, g, b, namedRgb.r, namedRgb.g, namedRgb.b);
3714
+ if (distance < closestDistance) {
3715
+ closestDistance = distance;
3716
+ closestName = name;
3717
+ closestHex = hex.toLowerCase();
3718
+ }
3719
+ }
3720
+ return {
3721
+ name: closestName,
3722
+ exact: closestDistance === 0,
3723
+ hex: closestHex
3724
+ };
3725
+ }
3726
+
3727
+ exports.archive = archive_exports;
3728
+ exports.color = color_exports;
3729
+ exports.crypto = crypto_exports;
3730
+ exports.csv = csv_exports;
3731
+ exports.datetime = datetime_exports;
3732
+ exports.diff = diff_exports;
3733
+ exports.excel = excel_exports;
3734
+ exports.image = image_exports;
3735
+ exports.json = json_exports;
3736
+ exports.markdown = markdown_exports;
3737
+ exports.math = math_exports;
3738
+ exports.pdf = pdf_exports;
3739
+ exports.regex = regex_exports;
3740
+ exports.sql = sql_exports;
3741
+ exports.text = text_exports;
3742
+ exports.xml = xml_exports;
3743
+ //# sourceMappingURL=index.js.map
3744
+ //# sourceMappingURL=index.js.map