jtcsv 2.2.7 → 3.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 (140) hide show
  1. package/README.md +31 -1
  2. package/bin/jtcsv.js +891 -821
  3. package/bin/jtcsv.ts +2534 -0
  4. package/csv-to-json.js +168 -145
  5. package/dist/jtcsv-core.cjs.js +1407 -0
  6. package/dist/jtcsv-core.cjs.js.map +1 -0
  7. package/dist/jtcsv-core.esm.js +1379 -0
  8. package/dist/jtcsv-core.esm.js.map +1 -0
  9. package/dist/jtcsv-core.umd.js +1413 -0
  10. package/dist/jtcsv-core.umd.js.map +1 -0
  11. package/dist/jtcsv-full.cjs.js +1912 -0
  12. package/dist/jtcsv-full.cjs.js.map +1 -0
  13. package/dist/jtcsv-full.esm.js +1880 -0
  14. package/dist/jtcsv-full.esm.js.map +1 -0
  15. package/dist/jtcsv-full.umd.js +1918 -0
  16. package/dist/jtcsv-full.umd.js.map +1 -0
  17. package/dist/jtcsv-workers.esm.js +759 -0
  18. package/dist/jtcsv-workers.esm.js.map +1 -0
  19. package/dist/jtcsv-workers.umd.js +773 -0
  20. package/dist/jtcsv-workers.umd.js.map +1 -0
  21. package/dist/jtcsv.cjs.js +61 -19
  22. package/dist/jtcsv.cjs.js.map +1 -1
  23. package/dist/jtcsv.esm.js +61 -19
  24. package/dist/jtcsv.esm.js.map +1 -1
  25. package/dist/jtcsv.umd.js +61 -19
  26. package/dist/jtcsv.umd.js.map +1 -1
  27. package/errors.js +188 -2
  28. package/examples/advanced/conditional-transformations.js +446 -0
  29. package/examples/advanced/conditional-transformations.ts +446 -0
  30. package/examples/advanced/csv-parser.worker.js +89 -0
  31. package/examples/advanced/csv-parser.worker.ts +89 -0
  32. package/examples/advanced/nested-objects-example.js +306 -0
  33. package/examples/advanced/nested-objects-example.ts +306 -0
  34. package/examples/advanced/performance-optimization.js +504 -0
  35. package/examples/advanced/performance-optimization.ts +504 -0
  36. package/examples/advanced/run-demo-server.js +116 -0
  37. package/examples/advanced/run-demo-server.ts +116 -0
  38. package/examples/advanced/web-worker-usage.html +874 -0
  39. package/examples/async-multithreaded-example.ts +335 -0
  40. package/examples/cli-advanced-usage.md +288 -0
  41. package/examples/cli-batch-processing.ts +38 -0
  42. package/examples/cli-tool.js +0 -3
  43. package/examples/cli-tool.ts +183 -0
  44. package/examples/error-handling.js +21 -7
  45. package/examples/error-handling.ts +356 -0
  46. package/examples/express-api.js +0 -3
  47. package/examples/express-api.ts +164 -0
  48. package/examples/large-dataset-example.js +0 -3
  49. package/examples/large-dataset-example.ts +204 -0
  50. package/examples/ndjson-processing.js +1 -1
  51. package/examples/ndjson-processing.ts +456 -0
  52. package/examples/plugin-excel-exporter.js +3 -4
  53. package/examples/plugin-excel-exporter.ts +406 -0
  54. package/examples/react-integration.tsx +637 -0
  55. package/examples/schema-validation.ts +640 -0
  56. package/examples/simple-usage.js +254 -254
  57. package/examples/simple-usage.ts +194 -0
  58. package/examples/streaming-example.js +4 -5
  59. package/examples/streaming-example.ts +419 -0
  60. package/examples/web-workers-advanced.ts +28 -0
  61. package/index.d.ts +1 -3
  62. package/index.js +15 -1
  63. package/json-save.js +9 -3
  64. package/json-to-csv.js +168 -21
  65. package/package.json +69 -10
  66. package/plugins/express-middleware/README.md +21 -2
  67. package/plugins/express-middleware/example.js +3 -4
  68. package/plugins/express-middleware/example.ts +135 -0
  69. package/plugins/express-middleware/index.d.ts +1 -1
  70. package/plugins/express-middleware/index.js +270 -118
  71. package/plugins/express-middleware/index.ts +557 -0
  72. package/plugins/fastify-plugin/index.js +2 -4
  73. package/plugins/fastify-plugin/index.ts +443 -0
  74. package/plugins/hono/index.ts +226 -0
  75. package/plugins/nestjs/index.ts +201 -0
  76. package/plugins/nextjs-api/examples/ConverterComponent.tsx +386 -0
  77. package/plugins/nextjs-api/examples/api-convert.js +0 -2
  78. package/plugins/nextjs-api/examples/api-convert.ts +67 -0
  79. package/plugins/nextjs-api/index.tsx +339 -0
  80. package/plugins/nextjs-api/route.js +2 -3
  81. package/plugins/nextjs-api/route.ts +370 -0
  82. package/plugins/nuxt/index.ts +94 -0
  83. package/plugins/nuxt/runtime/composables/useJtcsv.ts +100 -0
  84. package/plugins/nuxt/runtime/plugin.ts +71 -0
  85. package/plugins/remix/index.js +1 -1
  86. package/plugins/remix/index.ts +260 -0
  87. package/plugins/sveltekit/index.js +1 -1
  88. package/plugins/sveltekit/index.ts +301 -0
  89. package/plugins/trpc/index.ts +267 -0
  90. package/src/browser/browser-functions.ts +402 -0
  91. package/src/browser/core.js +92 -0
  92. package/src/browser/core.ts +152 -0
  93. package/src/browser/csv-to-json-browser.d.ts +3 -0
  94. package/src/browser/csv-to-json-browser.js +36 -14
  95. package/src/browser/csv-to-json-browser.ts +264 -0
  96. package/src/browser/errors-browser.ts +303 -0
  97. package/src/browser/extensions/plugins.js +92 -0
  98. package/src/browser/extensions/plugins.ts +93 -0
  99. package/src/browser/extensions/workers.js +39 -0
  100. package/src/browser/extensions/workers.ts +39 -0
  101. package/src/browser/globals.d.ts +5 -0
  102. package/src/browser/index.ts +192 -0
  103. package/src/browser/json-to-csv-browser.d.ts +3 -0
  104. package/src/browser/json-to-csv-browser.js +13 -3
  105. package/src/browser/json-to-csv-browser.ts +262 -0
  106. package/src/browser/streams.js +12 -2
  107. package/src/browser/streams.ts +336 -0
  108. package/src/browser/workers/csv-parser.worker.ts +377 -0
  109. package/src/browser/workers/worker-pool.ts +548 -0
  110. package/src/core/delimiter-cache.js +22 -8
  111. package/src/core/delimiter-cache.ts +310 -0
  112. package/src/core/node-optimizations.ts +449 -0
  113. package/src/core/plugin-system.js +29 -11
  114. package/src/core/plugin-system.ts +400 -0
  115. package/src/core/transform-hooks.ts +558 -0
  116. package/src/engines/fast-path-engine-new.ts +347 -0
  117. package/src/engines/fast-path-engine.ts +854 -0
  118. package/src/errors.ts +72 -0
  119. package/src/formats/ndjson-parser.ts +469 -0
  120. package/src/formats/tsv-parser.ts +334 -0
  121. package/src/index-with-plugins.js +16 -9
  122. package/src/index-with-plugins.ts +395 -0
  123. package/src/types/index.ts +255 -0
  124. package/src/utils/bom-utils.js +259 -0
  125. package/src/utils/bom-utils.ts +373 -0
  126. package/src/utils/encoding-support.js +124 -0
  127. package/src/utils/encoding-support.ts +155 -0
  128. package/src/utils/schema-validator.js +19 -19
  129. package/src/utils/schema-validator.ts +819 -0
  130. package/src/utils/transform-loader.js +1 -1
  131. package/src/utils/transform-loader.ts +389 -0
  132. package/src/utils/zod-adapter.js +170 -0
  133. package/src/utils/zod-adapter.ts +280 -0
  134. package/src/web-server/index.js +10 -10
  135. package/src/web-server/index.ts +683 -0
  136. package/src/workers/csv-multithreaded.ts +310 -0
  137. package/src/workers/csv-parser.worker.ts +227 -0
  138. package/src/workers/worker-pool.ts +409 -0
  139. package/stream-csv-to-json.js +26 -8
  140. package/stream-json-to-csv.js +1 -0
@@ -0,0 +1,1912 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ // Система ошибок для браузерной версии jtcsv
6
+ // Адаптирована для работы без Node.js специфичных API
7
+ /**
8
+ * Базовый класс ошибки jtcsv
9
+ */
10
+ class JTCSVError extends Error {
11
+ constructor(message, code = 'JTCSV_ERROR', details = {}) {
12
+ super(message);
13
+ this.name = 'JTCSVError';
14
+ this.code = code;
15
+ this.details = details;
16
+ // Сохранение stack trace
17
+ if (Error.captureStackTrace) {
18
+ Error.captureStackTrace(this, JTCSVError);
19
+ }
20
+ }
21
+ }
22
+ /**
23
+ * Ошибка валидации
24
+ */
25
+ class ValidationError extends JTCSVError {
26
+ constructor(message, details = {}) {
27
+ super(message, 'VALIDATION_ERROR', details);
28
+ this.name = 'ValidationError';
29
+ }
30
+ }
31
+ /**
32
+ * Ошибка безопасности
33
+ */
34
+ class SecurityError extends JTCSVError {
35
+ constructor(message, details = {}) {
36
+ super(message, 'SECURITY_ERROR', details);
37
+ this.name = 'SecurityError';
38
+ }
39
+ }
40
+ /**
41
+ * Ошибка файловой системы (адаптирована для браузера)
42
+ */
43
+ class FileSystemError extends JTCSVError {
44
+ constructor(message, originalError, details = {}) {
45
+ super(message, 'FILE_SYSTEM_ERROR', { ...details, originalError });
46
+ this.name = 'FileSystemError';
47
+ if (originalError && originalError.code) {
48
+ this.code = originalError.code;
49
+ }
50
+ }
51
+ }
52
+ /**
53
+ * Ошибка парсинга
54
+ */
55
+ class ParsingError extends JTCSVError {
56
+ constructor(message, lineNumber, details = {}) {
57
+ super(message, 'PARSING_ERROR', { ...details, lineNumber });
58
+ this.name = 'ParsingError';
59
+ this.lineNumber = lineNumber;
60
+ }
61
+ }
62
+ /**
63
+ * Ошибка превышения лимита
64
+ */
65
+ class LimitError extends JTCSVError {
66
+ constructor(message, limit, actual, details = {}) {
67
+ super(message, 'LIMIT_ERROR', { ...details, limit, actual });
68
+ this.name = 'LimitError';
69
+ this.limit = limit;
70
+ this.actual = actual;
71
+ }
72
+ }
73
+ /**
74
+ * Ошибка конфигурации
75
+ */
76
+ class ConfigurationError extends JTCSVError {
77
+ constructor(message, details = {}) {
78
+ super(message, 'CONFIGURATION_ERROR', details);
79
+ this.name = 'ConfigurationError';
80
+ }
81
+ }
82
+ /**
83
+ * Коды ошибок
84
+ */
85
+ const ERROR_CODES = {
86
+ JTCSV_ERROR: 'JTCSV_ERROR',
87
+ VALIDATION_ERROR: 'VALIDATION_ERROR',
88
+ SECURITY_ERROR: 'SECURITY_ERROR',
89
+ FILE_SYSTEM_ERROR: 'FILE_SYSTEM_ERROR',
90
+ PARSING_ERROR: 'PARSING_ERROR',
91
+ LIMIT_ERROR: 'LIMIT_ERROR',
92
+ CONFIGURATION_ERROR: 'CONFIGURATION_ERROR',
93
+ INVALID_INPUT: 'INVALID_INPUT',
94
+ SECURITY_VIOLATION: 'SECURITY_VIOLATION',
95
+ FILE_NOT_FOUND: 'FILE_NOT_FOUND',
96
+ PARSE_FAILED: 'PARSE_FAILED',
97
+ SIZE_LIMIT: 'SIZE_LIMIT',
98
+ INVALID_CONFIG: 'INVALID_CONFIG',
99
+ UNKNOWN_ERROR: 'UNKNOWN_ERROR'
100
+ };
101
+ /**
102
+ * Безопасное выполнение функции с обработкой ошибок
103
+ *
104
+ * @param fn - Функция для выполнения
105
+ * @param errorCode - Код ошибки по умолчанию
106
+ * @param errorDetails - Детали ошибки
107
+ * @returns Результат выполнения функции
108
+ */
109
+ function safeExecute(fn, errorCode = 'UNKNOWN_ERROR', errorDetails = {}) {
110
+ try {
111
+ if (typeof fn === 'function') {
112
+ return fn();
113
+ }
114
+ throw new ValidationError('Function expected');
115
+ }
116
+ catch (error) {
117
+ // Если ошибка уже является JTCSVError, перебросить её
118
+ if (error instanceof JTCSVError) {
119
+ throw error;
120
+ }
121
+ // Определить тип ошибки на основе сообщения или кода
122
+ let enhancedError;
123
+ const errorMessage = error.message || String(error);
124
+ if (errorMessage.includes('validation') || errorMessage.includes('Validation')) {
125
+ enhancedError = new ValidationError(errorMessage, { ...errorDetails, originalError: error });
126
+ }
127
+ else if (errorMessage.includes('security') || errorMessage.includes('Security')) {
128
+ enhancedError = new SecurityError(errorMessage, { ...errorDetails, originalError: error });
129
+ }
130
+ else if (errorMessage.includes('parsing') || errorMessage.includes('Parsing')) {
131
+ enhancedError = new ParsingError(errorMessage, undefined, { ...errorDetails, originalError: error });
132
+ }
133
+ else if (errorMessage.includes('limit') || errorMessage.includes('Limit')) {
134
+ enhancedError = new LimitError(errorMessage, null, null, { ...errorDetails, originalError: error });
135
+ }
136
+ else if (errorMessage.includes('configuration') || errorMessage.includes('Configuration')) {
137
+ enhancedError = new ConfigurationError(errorMessage, { ...errorDetails, originalError: error });
138
+ }
139
+ else if (errorMessage.includes('file') || errorMessage.includes('File')) {
140
+ enhancedError = new FileSystemError(errorMessage, error, errorDetails);
141
+ }
142
+ else {
143
+ // Общая ошибка
144
+ enhancedError = new JTCSVError(errorMessage, errorCode, { ...errorDetails, originalError: error });
145
+ }
146
+ // Сохранить оригинальный stack trace если возможно
147
+ if (error.stack) {
148
+ enhancedError.stack = error.stack;
149
+ }
150
+ throw enhancedError;
151
+ }
152
+ }
153
+ /**
154
+ * Асинхронная версия safeExecute
155
+ */
156
+ async function safeExecuteAsync(fn, errorCode = 'UNKNOWN_ERROR', errorDetails = {}) {
157
+ try {
158
+ if (typeof fn === 'function') {
159
+ return await fn();
160
+ }
161
+ throw new ValidationError('Function expected');
162
+ }
163
+ catch (error) {
164
+ // Если ошибка уже является JTCSVError, перебросить её
165
+ if (error instanceof JTCSVError) {
166
+ throw error;
167
+ }
168
+ // Определить тип ошибки
169
+ let enhancedError;
170
+ const errorMessage = error.message || String(error);
171
+ if (errorMessage.includes('validation') || errorMessage.includes('Validation')) {
172
+ enhancedError = new ValidationError(errorMessage, { ...errorDetails, originalError: error });
173
+ }
174
+ else if (errorMessage.includes('security') || errorMessage.includes('Security')) {
175
+ enhancedError = new SecurityError(errorMessage, { ...errorDetails, originalError: error });
176
+ }
177
+ else if (errorMessage.includes('parsing') || errorMessage.includes('Parsing')) {
178
+ enhancedError = new ParsingError(errorMessage, undefined, { ...errorDetails, originalError: error });
179
+ }
180
+ else if (errorMessage.includes('limit') || errorMessage.includes('Limit')) {
181
+ enhancedError = new LimitError(errorMessage, null, null, { ...errorDetails, originalError: error });
182
+ }
183
+ else if (errorMessage.includes('configuration') || errorMessage.includes('Configuration')) {
184
+ enhancedError = new ConfigurationError(errorMessage, { ...errorDetails, originalError: error });
185
+ }
186
+ else if (errorMessage.includes('file') || errorMessage.includes('File')) {
187
+ enhancedError = new FileSystemError(errorMessage, error, errorDetails);
188
+ }
189
+ else {
190
+ enhancedError = new JTCSVError(errorMessage, errorCode, { ...errorDetails, originalError: error });
191
+ }
192
+ if (error.stack) {
193
+ enhancedError.stack = error.stack;
194
+ }
195
+ throw enhancedError;
196
+ }
197
+ }
198
+ /**
199
+ * Создать сообщение об ошибке
200
+ */
201
+ function createErrorMessage(error, includeStack = false) {
202
+ let message = error.message || 'Unknown error';
203
+ if (error instanceof JTCSVError) {
204
+ message = `[${error.code}] ${message}`;
205
+ if (error instanceof ParsingError && error.lineNumber) {
206
+ message += ` (line ${error.lineNumber})`;
207
+ }
208
+ if (error instanceof LimitError && error.limit && error.actual) {
209
+ message += ` (limit: ${error.limit}, actual: ${error.actual})`;
210
+ }
211
+ }
212
+ if (includeStack && error.stack) {
213
+ message += `\n${error.stack}`;
214
+ }
215
+ return message;
216
+ }
217
+ /**
218
+ * Обработка ошибки
219
+ */
220
+ function handleError(error, options = {}) {
221
+ const { log = true, throw: shouldThrow = false, format = true } = options;
222
+ const message = format ? createErrorMessage(error) : error.message;
223
+ if (log) {
224
+ console.error(`[jtcsv] ${message}`);
225
+ if (error instanceof JTCSVError && error.details) {
226
+ console.error('Error details:', error.details);
227
+ }
228
+ }
229
+ if (shouldThrow) {
230
+ throw error;
231
+ }
232
+ return message;
233
+ }
234
+ // Экспорт для Node.js совместимости
235
+ if (typeof module !== 'undefined' && module.exports) {
236
+ module.exports = {
237
+ JTCSVError,
238
+ ValidationError,
239
+ SecurityError,
240
+ FileSystemError,
241
+ ParsingError,
242
+ LimitError,
243
+ ConfigurationError,
244
+ ERROR_CODES,
245
+ safeExecute,
246
+ safeExecuteAsync,
247
+ createErrorMessage,
248
+ handleError
249
+ };
250
+ }
251
+
252
+ // Браузерная версия JSON to CSV конвертера
253
+ // Адаптирована для работы в браузере без Node.js API
254
+ /**
255
+ * Валидация входных данных и опций
256
+ * @private
257
+ */
258
+ function validateInput(data, options) {
259
+ // Validate data
260
+ if (!Array.isArray(data)) {
261
+ throw new ValidationError('Input data must be an array');
262
+ }
263
+ // Validate options
264
+ if (options && typeof options !== 'object') {
265
+ throw new ConfigurationError('Options must be an object');
266
+ }
267
+ // Validate delimiter
268
+ if (options?.delimiter && typeof options.delimiter !== 'string') {
269
+ throw new ConfigurationError('Delimiter must be a string');
270
+ }
271
+ if (options?.delimiter && options.delimiter.length !== 1) {
272
+ throw new ConfigurationError('Delimiter must be a single character');
273
+ }
274
+ // Validate renameMap
275
+ if (options?.renameMap && typeof options.renameMap !== 'object') {
276
+ throw new ConfigurationError('renameMap must be an object');
277
+ }
278
+ // Validate maxRecords
279
+ if (options && options.maxRecords !== undefined) {
280
+ if (typeof options.maxRecords !== 'number' || options.maxRecords <= 0) {
281
+ throw new ConfigurationError('maxRecords must be a positive number');
282
+ }
283
+ }
284
+ // Validate preventCsvInjection
285
+ if (options?.preventCsvInjection !== undefined && typeof options.preventCsvInjection !== 'boolean') {
286
+ throw new ConfigurationError('preventCsvInjection must be a boolean');
287
+ }
288
+ // Validate rfc4180Compliant
289
+ if (options?.rfc4180Compliant !== undefined && typeof options.rfc4180Compliant !== 'boolean') {
290
+ throw new ConfigurationError('rfc4180Compliant must be a boolean');
291
+ }
292
+ return true;
293
+ }
294
+ /**
295
+ * Экранирование CSV значений для предотвращения инъекций
296
+ * @private
297
+ */
298
+ function escapeCsvValue(value, preventInjection = true) {
299
+ if (value === null || value === undefined) {
300
+ return '';
301
+ }
302
+ const str = String(value);
303
+ // Экранирование формул для предотвращения CSV инъекций
304
+ if (preventInjection && /^[=+\-@]/.test(str)) {
305
+ return "'" + str;
306
+ }
307
+ // Экранирование кавычек и переносов строк
308
+ if (str.includes('"') || str.includes('\n') || str.includes('\r') || str.includes(',')) {
309
+ return '"' + str.replace(/"/g, '""') + '"';
310
+ }
311
+ return str;
312
+ }
313
+ /**
314
+ * Извлечение всех уникальных ключей из массива объектов
315
+ * @private
316
+ */
317
+ function extractAllKeys(data) {
318
+ const keys = new Set();
319
+ for (const item of data) {
320
+ if (item && typeof item === 'object') {
321
+ Object.keys(item).forEach(key => keys.add(key));
322
+ }
323
+ }
324
+ return Array.from(keys);
325
+ }
326
+ /**
327
+ * Конвертация массива объектов в CSV строку
328
+ *
329
+ * @param data - Массив объектов для конвертации
330
+ * @param options - Опции конвертации
331
+ * @returns CSV строка
332
+ */
333
+ function jsonToCsv$1(data, options = {}) {
334
+ return safeExecute(() => {
335
+ validateInput(data, options);
336
+ if (data.length === 0) {
337
+ return '';
338
+ }
339
+ // Настройки по умолчанию
340
+ const delimiter = options.delimiter || ';';
341
+ const includeHeaders = options.includeHeaders !== false;
342
+ const maxRecords = options.maxRecords || data.length;
343
+ const preventInjection = options.preventCsvInjection !== false;
344
+ const rfc4180Compliant = options.rfc4180Compliant !== false;
345
+ // Ограничение количества записей
346
+ const limitedData = data.slice(0, maxRecords);
347
+ // Извлечение всех ключей
348
+ const allKeys = extractAllKeys(limitedData);
349
+ // Применение renameMap если есть
350
+ const renameMap = options.renameMap || {};
351
+ const finalKeys = allKeys.map(key => renameMap[key] || key);
352
+ // Создание CSV строки
353
+ const lines = [];
354
+ // Заголовки
355
+ if (includeHeaders) {
356
+ const headerLine = finalKeys.map(key => escapeCsvValue(key, preventInjection)).join(delimiter);
357
+ lines.push(headerLine);
358
+ }
359
+ // Данные
360
+ for (const item of limitedData) {
361
+ const rowValues = allKeys.map(key => {
362
+ const value = item?.[key];
363
+ return escapeCsvValue(value, preventInjection);
364
+ });
365
+ lines.push(rowValues.join(delimiter));
366
+ }
367
+ // RFC 4180 compliance: CRLF line endings
368
+ if (rfc4180Compliant) {
369
+ return lines.join('\r\n');
370
+ }
371
+ return lines.join('\n');
372
+ });
373
+ }
374
+ /**
375
+ * Асинхронная версия jsonToCsv
376
+ */
377
+ async function jsonToCsvAsync$1(data, options = {}) {
378
+ return jsonToCsv$1(data, options);
379
+ }
380
+ /**
381
+ * Создает итератор для потоковой конвертации JSON в CSV
382
+ *
383
+ * @param data - Массив объектов или async итератор
384
+ * @param options - Опции конвертации
385
+ * @returns AsyncIterator с CSV чанками
386
+ */
387
+ async function* jsonToCsvIterator(data, options = {}) {
388
+ validateInput(Array.isArray(data) ? data : [], options);
389
+ const delimiter = options.delimiter || ';';
390
+ const includeHeaders = options.includeHeaders !== false;
391
+ const preventInjection = options.preventCsvInjection !== false;
392
+ const rfc4180Compliant = options.rfc4180Compliant !== false;
393
+ let allKeys = [];
394
+ let renameMap = {};
395
+ // Если данные - массив, обрабатываем как массив
396
+ if (Array.isArray(data)) {
397
+ if (data.length === 0) {
398
+ return;
399
+ }
400
+ allKeys = extractAllKeys(data);
401
+ renameMap = options.renameMap || {};
402
+ const finalKeys = allKeys.map(key => renameMap[key] || key);
403
+ // Заголовки
404
+ if (includeHeaders) {
405
+ const headerLine = finalKeys.map(key => escapeCsvValue(key, preventInjection)).join(delimiter);
406
+ yield headerLine + (rfc4180Compliant ? '\r\n' : '\n');
407
+ }
408
+ // Данные
409
+ for (const item of data) {
410
+ const rowValues = allKeys.map(key => {
411
+ const value = item?.[key];
412
+ return escapeCsvValue(value, preventInjection);
413
+ });
414
+ yield rowValues.join(delimiter) + (rfc4180Compliant ? '\r\n' : '\n');
415
+ }
416
+ }
417
+ else {
418
+ // Для async итератора нужна другая логика
419
+ throw new ValidationError('Async iterators not yet implemented in browser version');
420
+ }
421
+ }
422
+ /**
423
+ * Асинхронная версия jsonToCsvIterator (псевдоним)
424
+ */
425
+ const jsonToCsvIteratorAsync = jsonToCsvIterator;
426
+ /**
427
+ * Безопасная конвертация с обработкой ошибок
428
+ *
429
+ * @param data - Массив объектов
430
+ * @param options - Опции конвертации
431
+ * @returns CSV строка или null при ошибке
432
+ */
433
+ function jsonToCsvSafe(data, options = {}) {
434
+ try {
435
+ return jsonToCsv$1(data, options);
436
+ }
437
+ catch (error) {
438
+ console.error('JSON to CSV conversion error:', error);
439
+ return null;
440
+ }
441
+ }
442
+ /**
443
+ * Асинхронная версия jsonToCsvSafe
444
+ */
445
+ async function jsonToCsvSafeAsync(data, options = {}) {
446
+ try {
447
+ return await jsonToCsvAsync$1(data, options);
448
+ }
449
+ catch (error) {
450
+ console.error('JSON to CSV conversion error:', error);
451
+ return null;
452
+ }
453
+ }
454
+ // Экспорт для Node.js совместимости
455
+ if (typeof module !== 'undefined' && module.exports) {
456
+ module.exports = {
457
+ jsonToCsv: jsonToCsv$1,
458
+ jsonToCsvAsync: jsonToCsvAsync$1,
459
+ jsonToCsvIterator,
460
+ jsonToCsvIteratorAsync,
461
+ jsonToCsvSafe,
462
+ jsonToCsvSafeAsync
463
+ };
464
+ }
465
+
466
+ var jsonToCsvBrowser = /*#__PURE__*/Object.freeze({
467
+ __proto__: null,
468
+ jsonToCsv: jsonToCsv$1,
469
+ jsonToCsvAsync: jsonToCsvAsync$1,
470
+ jsonToCsvIterator: jsonToCsvIterator,
471
+ jsonToCsvIteratorAsync: jsonToCsvIteratorAsync,
472
+ jsonToCsvSafe: jsonToCsvSafe,
473
+ jsonToCsvSafeAsync: jsonToCsvSafeAsync
474
+ });
475
+
476
+ // Браузерная версия CSV to JSON конвертера
477
+ // Адаптирована для работы в браузере без Node.js API
478
+ /**
479
+ * Валидация опций парсинга
480
+ * @private
481
+ */
482
+ function validateCsvOptions(options) {
483
+ // Validate options
484
+ if (options && typeof options !== 'object') {
485
+ throw new ConfigurationError('Options must be an object');
486
+ }
487
+ // Validate delimiter
488
+ if (options?.delimiter && typeof options.delimiter !== 'string') {
489
+ throw new ConfigurationError('Delimiter must be a string');
490
+ }
491
+ if (options?.delimiter && options.delimiter.length !== 1) {
492
+ throw new ConfigurationError('Delimiter must be a single character');
493
+ }
494
+ // Validate autoDetect
495
+ if (options?.autoDetect !== undefined && typeof options.autoDetect !== 'boolean') {
496
+ throw new ConfigurationError('autoDetect must be a boolean');
497
+ }
498
+ // Validate candidates
499
+ if (options?.candidates && !Array.isArray(options.candidates)) {
500
+ throw new ConfigurationError('candidates must be an array');
501
+ }
502
+ // Validate maxRows
503
+ if (options?.maxRows !== undefined && (typeof options.maxRows !== 'number' || options.maxRows <= 0)) {
504
+ throw new ConfigurationError('maxRows must be a positive number');
505
+ }
506
+ if (options?.warnExtraFields !== undefined && typeof options.warnExtraFields !== 'boolean') {
507
+ throw new ConfigurationError('warnExtraFields must be a boolean');
508
+ }
509
+ return true;
510
+ }
511
+ /**
512
+ * Автоматическое определение разделителя
513
+ * @private
514
+ */
515
+ function autoDetectDelimiter$1(text, candidates = [',', ';', '\t', '|']) {
516
+ if (!text || typeof text !== 'string') {
517
+ return ',';
518
+ }
519
+ const firstLine = text.split('\n')[0];
520
+ if (!firstLine) {
521
+ return ',';
522
+ }
523
+ let bestCandidate = ',';
524
+ let bestCount = 0;
525
+ for (const candidate of candidates) {
526
+ const count = (firstLine.match(new RegExp(candidate.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g')) || []).length;
527
+ if (count > bestCount) {
528
+ bestCount = count;
529
+ bestCandidate = candidate;
530
+ }
531
+ }
532
+ return bestCandidate;
533
+ }
534
+ /**
535
+ * Парсинг CSV строки в массив объектов
536
+ *
537
+ * @param csvText - CSV текст для парсинга
538
+ * @param options - Опции парсинга
539
+ * @returns Массив объектов
540
+ */
541
+ function csvToJson$1(csvText, options = {}) {
542
+ return safeExecute(() => {
543
+ validateCsvOptions(options);
544
+ if (typeof csvText !== 'string') {
545
+ throw new ValidationError('CSV text must be a string');
546
+ }
547
+ if (csvText.trim() === '') {
548
+ return [];
549
+ }
550
+ // Определение разделителя
551
+ const delimiter = options.delimiter ||
552
+ (options.autoDetect !== false ? autoDetectDelimiter$1(csvText, options.candidates) : ',');
553
+ // Разделение на строки
554
+ const lines = csvText.split('\n').filter(line => line.trim() !== '');
555
+ if (lines.length === 0) {
556
+ return [];
557
+ }
558
+ // Парсинг заголовков
559
+ const headers = lines[0].split(delimiter).map(h => h.trim());
560
+ // Ограничение количества строк
561
+ const maxRows = options.maxRows || Infinity;
562
+ const dataRows = lines.slice(1, Math.min(lines.length, maxRows + 1));
563
+ // Парсинг данных
564
+ const result = [];
565
+ for (let i = 0; i < dataRows.length; i++) {
566
+ const line = dataRows[i];
567
+ const values = line.split(delimiter);
568
+ const row = {};
569
+ for (let j = 0; j < headers.length; j++) {
570
+ const header = headers[j];
571
+ const value = j < values.length ? values[j].trim() : '';
572
+ // Попытка парсинга чисел
573
+ if (/^-?\d+(\.\d+)?$/.test(value)) {
574
+ row[header] = parseFloat(value);
575
+ }
576
+ else if (value.toLowerCase() === 'true' || value.toLowerCase() === 'false') {
577
+ row[header] = value.toLowerCase() === 'true';
578
+ }
579
+ else {
580
+ row[header] = value;
581
+ }
582
+ }
583
+ result.push(row);
584
+ }
585
+ return result;
586
+ });
587
+ }
588
+ /**
589
+ * Асинхронная версия csvToJson
590
+ */
591
+ async function csvToJsonAsync$1(csvText, options = {}) {
592
+ return csvToJson$1(csvText, options);
593
+ }
594
+ /**
595
+ * Создает итератор для потокового парсинга CSV
596
+ *
597
+ * @param input - CSV текст, File или Blob
598
+ * @param options - Опции парсинга
599
+ * @returns AsyncGenerator
600
+ */
601
+ async function* csvToJsonIterator$1(input, options = {}) {
602
+ validateCsvOptions(options);
603
+ let csvText;
604
+ if (typeof input === 'string') {
605
+ csvText = input;
606
+ }
607
+ else if (input instanceof File || input instanceof Blob) {
608
+ csvText = await input.text();
609
+ }
610
+ else {
611
+ throw new ValidationError('Input must be string, File or Blob');
612
+ }
613
+ if (csvText.trim() === '') {
614
+ return;
615
+ }
616
+ // Определение разделителя
617
+ const delimiter = options.delimiter ||
618
+ (options.autoDetect !== false ? autoDetectDelimiter$1(csvText, options.candidates) : ',');
619
+ // Разделение на строки
620
+ const lines = csvText.split('\n').filter(line => line.trim() !== '');
621
+ if (lines.length === 0) {
622
+ return;
623
+ }
624
+ // Парсинг заголовков
625
+ const headers = lines[0].split(delimiter).map(h => h.trim());
626
+ // Ограничение количества строк
627
+ const maxRows = options.maxRows || Infinity;
628
+ const dataRows = lines.slice(1, Math.min(lines.length, maxRows + 1));
629
+ // Возврат данных по одной строке
630
+ for (let i = 0; i < dataRows.length; i++) {
631
+ const line = dataRows[i];
632
+ const values = line.split(delimiter);
633
+ const row = {};
634
+ for (let j = 0; j < headers.length; j++) {
635
+ const header = headers[j];
636
+ const value = j < values.length ? values[j].trim() : '';
637
+ // Попытка парсинга чисел
638
+ if (/^-?\d+(\.\d+)?$/.test(value)) {
639
+ row[header] = parseFloat(value);
640
+ }
641
+ else if (value.toLowerCase() === 'true' || value.toLowerCase() === 'false') {
642
+ row[header] = value.toLowerCase() === 'true';
643
+ }
644
+ else {
645
+ row[header] = value;
646
+ }
647
+ }
648
+ yield row;
649
+ }
650
+ }
651
+ /**
652
+ * Асинхронная версия csvToJsonIterator (псевдоним)
653
+ */
654
+ const csvToJsonIteratorAsync = csvToJsonIterator$1;
655
+ /**
656
+ * Парсинг CSV с обработкой ошибок
657
+ *
658
+ * @param csvText - CSV текст
659
+ * @param options - Опции парсинга
660
+ * @returns Результат парсинга или null при ошибке
661
+ */
662
+ function parseCsvSafe(csvText, options = {}) {
663
+ try {
664
+ return csvToJson$1(csvText, options);
665
+ }
666
+ catch (error) {
667
+ console.error('CSV parsing error:', error);
668
+ return null;
669
+ }
670
+ }
671
+ /**
672
+ * Асинхронная версия parseCsvSafe
673
+ */
674
+ async function parseCsvSafeAsync(csvText, options = {}) {
675
+ try {
676
+ return await csvToJsonAsync$1(csvText, options);
677
+ }
678
+ catch (error) {
679
+ console.error('CSV parsing error:', error);
680
+ return null;
681
+ }
682
+ }
683
+ // Экспорт для Node.js совместимости
684
+ if (typeof module !== 'undefined' && module.exports) {
685
+ module.exports = {
686
+ csvToJson: csvToJson$1,
687
+ csvToJsonAsync: csvToJsonAsync$1,
688
+ csvToJsonIterator: csvToJsonIterator$1,
689
+ csvToJsonIteratorAsync,
690
+ parseCsvSafe,
691
+ parseCsvSafeAsync,
692
+ autoDetectDelimiter: autoDetectDelimiter$1
693
+ };
694
+ }
695
+
696
+ var csvToJsonBrowser = /*#__PURE__*/Object.freeze({
697
+ __proto__: null,
698
+ csvToJson: csvToJson$1,
699
+ csvToJsonAsync: csvToJsonAsync$1,
700
+ csvToJsonIterator: csvToJsonIterator$1,
701
+ csvToJsonIteratorAsync: csvToJsonIteratorAsync,
702
+ parseCsvSafe: parseCsvSafe,
703
+ parseCsvSafeAsync: parseCsvSafeAsync
704
+ });
705
+
706
+ function isReadableStream(value) {
707
+ return value && typeof value.getReader === 'function';
708
+ }
709
+ function isAsyncIterable(value) {
710
+ return value && typeof value[Symbol.asyncIterator] === 'function';
711
+ }
712
+ function isIterable(value) {
713
+ return value && typeof value[Symbol.iterator] === 'function';
714
+ }
715
+ function createReadableStreamFromIterator(iterator) {
716
+ return new ReadableStream({
717
+ async pull(controller) {
718
+ try {
719
+ const { value, done } = await iterator.next();
720
+ if (done) {
721
+ controller.close();
722
+ return;
723
+ }
724
+ controller.enqueue(value);
725
+ }
726
+ catch (error) {
727
+ controller.error(error);
728
+ }
729
+ },
730
+ cancel() {
731
+ if (iterator.return) {
732
+ iterator.return();
733
+ }
734
+ }
735
+ });
736
+ }
737
+ function detectInputFormat(input, options) {
738
+ if (options && options.inputFormat) {
739
+ return options.inputFormat;
740
+ }
741
+ if (typeof input === 'string') {
742
+ const trimmed = input.trim();
743
+ if (trimmed === '') {
744
+ return 'unknown';
745
+ }
746
+ // Проверка на NDJSON (каждая строка - валидный JSON)
747
+ if (trimmed.includes('\n')) {
748
+ const lines = trimmed.split('\n').filter(line => line.trim() !== '');
749
+ if (lines.length > 0) {
750
+ try {
751
+ JSON.parse(lines[0]);
752
+ return 'ndjson';
753
+ }
754
+ catch {
755
+ // Не NDJSON
756
+ }
757
+ }
758
+ }
759
+ // Проверка на JSON
760
+ try {
761
+ const parsed = JSON.parse(trimmed);
762
+ if (Array.isArray(parsed) || (parsed && typeof parsed === 'object')) {
763
+ return 'json';
764
+ }
765
+ }
766
+ catch {
767
+ // Не JSON
768
+ }
769
+ // Проверка на CSV
770
+ if (trimmed.includes(',') || trimmed.includes(';') || trimmed.includes('\t')) {
771
+ return 'csv';
772
+ }
773
+ }
774
+ return 'unknown';
775
+ }
776
+ async function* jsonToCsvChunkIterator(input, options = {}) {
777
+ const format = detectInputFormat(input, options);
778
+ if (format === 'csv') {
779
+ throw new ValidationError('Input appears to be CSV, not JSON');
780
+ }
781
+ // Вспомогательная функция для создания асинхронного итератора
782
+ function toAsyncIterator(iterable) {
783
+ if (isAsyncIterable(iterable)) {
784
+ return iterable[Symbol.asyncIterator]();
785
+ }
786
+ if (isIterable(iterable)) {
787
+ const syncIterator = iterable[Symbol.iterator]();
788
+ return {
789
+ next: () => Promise.resolve(syncIterator.next()),
790
+ return: syncIterator.return ? () => Promise.resolve(syncIterator.return()) : undefined,
791
+ throw: syncIterator.throw ? (error) => Promise.resolve(syncIterator.throw(error)) : undefined
792
+ };
793
+ }
794
+ throw new ValidationError('Input is not iterable');
795
+ }
796
+ let iterator;
797
+ if (isAsyncIterable(input) || isIterable(input)) {
798
+ iterator = toAsyncIterator(input);
799
+ }
800
+ else if (typeof input === 'string') {
801
+ const parsed = JSON.parse(input);
802
+ if (Array.isArray(parsed)) {
803
+ iterator = toAsyncIterator(parsed);
804
+ }
805
+ else {
806
+ iterator = toAsyncIterator([parsed]);
807
+ }
808
+ }
809
+ else if (Array.isArray(input)) {
810
+ iterator = toAsyncIterator(input);
811
+ }
812
+ else {
813
+ iterator = toAsyncIterator([input]);
814
+ }
815
+ const delimiter = options.delimiter || ';';
816
+ const includeHeaders = options.includeHeaders !== false;
817
+ const preventInjection = options.preventCsvInjection !== false;
818
+ let isFirstChunk = true;
819
+ let headers = [];
820
+ while (true) {
821
+ const { value, done } = await iterator.next();
822
+ if (done)
823
+ break;
824
+ const item = value;
825
+ if (isFirstChunk) {
826
+ // Извлечение заголовков из первого элемента
827
+ headers = Object.keys(item);
828
+ if (includeHeaders) {
829
+ const headerLine = headers.map(header => {
830
+ const escaped = header.includes('"') ? `"${header.replace(/"/g, '""')}"` : header;
831
+ return preventInjection && /^[=+\-@]/.test(escaped) ? `'${escaped}` : escaped;
832
+ }).join(delimiter);
833
+ yield headerLine + '\n';
834
+ }
835
+ isFirstChunk = false;
836
+ }
837
+ const row = headers.map(header => {
838
+ const value = item[header];
839
+ const strValue = value === null || value === undefined ? '' : String(value);
840
+ if (strValue.includes('"') || strValue.includes('\n') || strValue.includes('\r') || strValue.includes(delimiter)) {
841
+ return `"${strValue.replace(/"/g, '""')}"`;
842
+ }
843
+ if (preventInjection && /^[=+\-@]/.test(strValue)) {
844
+ return `'${strValue}`;
845
+ }
846
+ return strValue;
847
+ }).join(delimiter);
848
+ yield row + '\n';
849
+ }
850
+ }
851
+ async function* jsonToNdjsonChunkIterator(input, options = {}) {
852
+ const format = detectInputFormat(input, options);
853
+ // Вспомогательная функция для создания асинхронного итератора
854
+ function toAsyncIterator(iterable) {
855
+ if (isAsyncIterable(iterable)) {
856
+ return iterable[Symbol.asyncIterator]();
857
+ }
858
+ if (isIterable(iterable)) {
859
+ const syncIterator = iterable[Symbol.iterator]();
860
+ return {
861
+ next: () => Promise.resolve(syncIterator.next()),
862
+ return: syncIterator.return ? () => Promise.resolve(syncIterator.return()) : undefined,
863
+ throw: syncIterator.throw ? (error) => Promise.resolve(syncIterator.throw(error)) : undefined
864
+ };
865
+ }
866
+ throw new ValidationError('Input is not iterable');
867
+ }
868
+ let iterator;
869
+ if (isAsyncIterable(input) || isIterable(input)) {
870
+ iterator = toAsyncIterator(input);
871
+ }
872
+ else if (typeof input === 'string') {
873
+ if (format === 'ndjson') {
874
+ const lines = input.split('\n').filter(line => line.trim() !== '');
875
+ iterator = toAsyncIterator(lines);
876
+ }
877
+ else {
878
+ const parsed = JSON.parse(input);
879
+ if (Array.isArray(parsed)) {
880
+ iterator = toAsyncIterator(parsed);
881
+ }
882
+ else {
883
+ iterator = toAsyncIterator([parsed]);
884
+ }
885
+ }
886
+ }
887
+ else if (Array.isArray(input)) {
888
+ iterator = toAsyncIterator(input);
889
+ }
890
+ else {
891
+ iterator = toAsyncIterator([input]);
892
+ }
893
+ while (true) {
894
+ const { value, done } = await iterator.next();
895
+ if (done)
896
+ break;
897
+ let jsonStr;
898
+ if (typeof value === 'string') {
899
+ try {
900
+ // Проверяем, является ли строка валидным JSON
901
+ JSON.parse(value);
902
+ jsonStr = value;
903
+ }
904
+ catch {
905
+ // Если нет, сериализуем как JSON
906
+ jsonStr = JSON.stringify(value);
907
+ }
908
+ }
909
+ else {
910
+ jsonStr = JSON.stringify(value);
911
+ }
912
+ yield jsonStr + '\n';
913
+ }
914
+ }
915
+ async function* csvToJsonChunkIterator(input, options = {}) {
916
+ if (typeof input === 'string') {
917
+ // Используем csvToJsonIterator из csv-to-json-browser
918
+ yield* csvToJsonIterator$1(input, options);
919
+ }
920
+ else if (input instanceof File || input instanceof Blob) {
921
+ const text = await input.text();
922
+ yield* csvToJsonIterator$1(text, options);
923
+ }
924
+ else if (isReadableStream(input)) {
925
+ const reader = input.getReader();
926
+ const decoder = new TextDecoder();
927
+ let buffer = '';
928
+ try {
929
+ while (true) {
930
+ const { value, done } = await reader.read();
931
+ if (done)
932
+ break;
933
+ buffer += decoder.decode(value, { stream: true });
934
+ // Обработка буфера по строкам
935
+ const lines = buffer.split('\n');
936
+ buffer = lines.pop() || '';
937
+ // TODO: Реализовать парсинг CSV из чанков
938
+ // Пока просто возвращаем сырые строки
939
+ for (const line of lines) {
940
+ if (line.trim()) {
941
+ yield { raw: line };
942
+ }
943
+ }
944
+ }
945
+ // Обработка остатка буфера
946
+ if (buffer.trim()) {
947
+ yield { raw: buffer };
948
+ }
949
+ }
950
+ finally {
951
+ reader.releaseLock();
952
+ }
953
+ }
954
+ else {
955
+ throw new ValidationError('Unsupported input type for CSV streaming');
956
+ }
957
+ }
958
+ function jsonToCsvStream$1(input, options = {}) {
959
+ const iterator = jsonToCsvChunkIterator(input, options);
960
+ return createReadableStreamFromIterator(iterator);
961
+ }
962
+ function jsonToNdjsonStream$1(input, options = {}) {
963
+ const iterator = jsonToNdjsonChunkIterator(input, options);
964
+ return createReadableStreamFromIterator(iterator);
965
+ }
966
+ function csvToJsonStream$1(input, options = {}) {
967
+ const iterator = csvToJsonChunkIterator(input, options);
968
+ return createReadableStreamFromIterator(iterator);
969
+ }
970
+ /**
971
+ * Асинхронная версия jsonToCsvStream
972
+ */
973
+ async function jsonToCsvStreamAsync(input, options = {}) {
974
+ return jsonToCsvStream$1(input, options);
975
+ }
976
+ /**
977
+ * Асинхронная версия jsonToNdjsonStream
978
+ */
979
+ async function jsonToNdjsonStreamAsync(input, options = {}) {
980
+ return jsonToNdjsonStream$1(input, options);
981
+ }
982
+ /**
983
+ * Асинхронная версия csvToJsonStream
984
+ */
985
+ async function csvToJsonStreamAsync(input, options = {}) {
986
+ return csvToJsonStream$1(input, options);
987
+ }
988
+ // Экспорт для Node.js совместимости
989
+ if (typeof module !== 'undefined' && module.exports) {
990
+ module.exports = {
991
+ jsonToCsvStream: jsonToCsvStream$1,
992
+ jsonToCsvStreamAsync,
993
+ jsonToNdjsonStream: jsonToNdjsonStream$1,
994
+ jsonToNdjsonStreamAsync,
995
+ csvToJsonStream: csvToJsonStream$1,
996
+ csvToJsonStreamAsync,
997
+ createReadableStreamFromIterator
998
+ };
999
+ }
1000
+
1001
+ // Браузерные специфичные функции для jtcsv
1002
+ // Функции, которые работают только в браузере
1003
+ /**
1004
+ * Скачивает JSON данные как CSV файл
1005
+ *
1006
+ * @param data - Массив объектов для конвертации
1007
+ * @param filename - Имя файла для скачивания (по умолчанию 'data.csv')
1008
+ * @param options - Опции для jsonToCsv
1009
+ *
1010
+ * @example
1011
+ * const data = [
1012
+ * { id: 1, name: 'John' },
1013
+ * { id: 2, name: 'Jane' }
1014
+ * ];
1015
+ * downloadAsCsv(data, 'users.csv', { delimiter: ',' });
1016
+ */
1017
+ function downloadAsCsv(data, filename = 'data.csv', options = {}) {
1018
+ // Проверка что мы в браузере
1019
+ if (typeof window === 'undefined') {
1020
+ throw new ValidationError('downloadAsCsv() работает только в браузере. Используйте saveAsCsv() в Node.js');
1021
+ }
1022
+ // Валидация имени файла
1023
+ if (typeof filename !== 'string' || filename.trim() === '') {
1024
+ throw new ValidationError('Filename must be a non-empty string');
1025
+ }
1026
+ // Добавление расширения .csv если его нет
1027
+ if (!filename.toLowerCase().endsWith('.csv')) {
1028
+ filename += '.csv';
1029
+ }
1030
+ // Конвертация в CSV
1031
+ const csv = jsonToCsv$1(data, options);
1032
+ // Создание Blob
1033
+ const blob = new Blob([csv], {
1034
+ type: 'text/csv;charset=utf-8;'
1035
+ });
1036
+ // Создание ссылки для скачивания
1037
+ const link = document.createElement('a');
1038
+ const url = URL.createObjectURL(blob);
1039
+ link.setAttribute('href', url);
1040
+ link.setAttribute('download', filename);
1041
+ link.style.visibility = 'hidden';
1042
+ document.body.appendChild(link);
1043
+ link.click();
1044
+ document.body.removeChild(link);
1045
+ // Освобождение URL
1046
+ setTimeout(() => URL.revokeObjectURL(url), 100);
1047
+ }
1048
+ /**
1049
+ * Асинхронная версия downloadAsCsv
1050
+ */
1051
+ async function downloadAsCsvAsync$1(data, filename = 'data.csv', options = {}) {
1052
+ return downloadAsCsv(data, filename, options);
1053
+ }
1054
+ /**
1055
+ * Парсит CSV файл из input[type="file"]
1056
+ *
1057
+ * @param file - File объект из input
1058
+ * @param options - Опции для csvToJson
1059
+ * @returns Promise с распарсенными данными
1060
+ */
1061
+ async function parseCsvFile(file, options = {}) {
1062
+ if (!(file instanceof File)) {
1063
+ throw new ValidationError('parseCsvFile() ожидает объект File');
1064
+ }
1065
+ // Чтение файла как текст
1066
+ const text = await file.text();
1067
+ // Парсинг CSV
1068
+ return csvToJson$1(text, options);
1069
+ }
1070
+ /**
1071
+ * Парсит CSV файл потоково
1072
+ *
1073
+ * @param file - File объект
1074
+ * @param options - Опции для потокового парсинга
1075
+ * @returns AsyncIterator с данными
1076
+ */
1077
+ function parseCsvFileStream(file, options = {}) {
1078
+ if (!(file instanceof File)) {
1079
+ throw new ValidationError('parseCsvFileStream() ожидает объект File');
1080
+ }
1081
+ // Используем csvToJsonIterator из импортированного модуля
1082
+ return csvToJsonIterator$1(file, options);
1083
+ }
1084
+ /**
1085
+ * Создает поток для конвертации JSON в CSV
1086
+ *
1087
+ * @param options - Опции для jsonToCsv
1088
+ * @returns ReadableStream
1089
+ */
1090
+ function jsonToCsvStream(options = {}) {
1091
+ return jsonToCsvStream$1(options);
1092
+ }
1093
+ /**
1094
+ * Создает поток для конвертации JSON в NDJSON
1095
+ *
1096
+ * @param options - Опции для конвертации
1097
+ * @returns ReadableStream
1098
+ */
1099
+ function jsonToNdjsonStream(options = {}) {
1100
+ return jsonToNdjsonStream$1(options);
1101
+ }
1102
+ /**
1103
+ * Создает поток для парсинга CSV в JSON
1104
+ *
1105
+ * @param options - Опции для csvToJson
1106
+ * @returns ReadableStream
1107
+ */
1108
+ function csvToJsonStream(options = {}) {
1109
+ return csvToJsonStream$1(options);
1110
+ }
1111
+ /**
1112
+ * Загружает CSV файл по URL
1113
+ *
1114
+ * @param url - URL CSV файла
1115
+ * @param options - Опции для csvToJson
1116
+ * @returns Promise с распарсенными данными
1117
+ */
1118
+ async function loadCsvFromUrl(url, options = {}) {
1119
+ if (typeof window === 'undefined') {
1120
+ throw new ValidationError('loadCsvFromUrl() работает только в браузере');
1121
+ }
1122
+ const response = await fetch(url);
1123
+ if (!response.ok) {
1124
+ throw new ValidationError(`Failed to load CSV from URL: ${response.status} ${response.statusText}`);
1125
+ }
1126
+ const text = await response.text();
1127
+ return csvToJson$1(text, options);
1128
+ }
1129
+ /**
1130
+ * Асинхронная версия loadCsvFromUrl
1131
+ */
1132
+ async function loadCsvFromUrlAsync(url, options = {}) {
1133
+ return loadCsvFromUrl(url, options);
1134
+ }
1135
+ /**
1136
+ * Экспортирует данные в CSV и открывает в новой вкладке
1137
+ *
1138
+ * @param data - Данные для экспорта
1139
+ * @param options - Опции для jsonToCsv
1140
+ */
1141
+ function openCsvInNewTab(data, options = {}) {
1142
+ if (typeof window === 'undefined') {
1143
+ throw new ValidationError('openCsvInNewTab() работает только в браузере');
1144
+ }
1145
+ const csv = jsonToCsv$1(data, options);
1146
+ const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' });
1147
+ const url = URL.createObjectURL(blob);
1148
+ window.open(url, '_blank');
1149
+ // Освобождение URL через некоторое время
1150
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
1151
+ }
1152
+ /**
1153
+ * Асинхронная версия openCsvInNewTab
1154
+ */
1155
+ async function openCsvInNewTabAsync(data, options = {}) {
1156
+ return openCsvInNewTab(data, options);
1157
+ }
1158
+ /**
1159
+ * Копирует CSV в буфер обмена
1160
+ *
1161
+ * @param data - Данные для копирования
1162
+ * @param options - Опции для jsonToCsv
1163
+ * @returns Promise с результатом копирования
1164
+ */
1165
+ async function copyCsvToClipboard(data, options = {}) {
1166
+ if (typeof window === 'undefined' || !navigator.clipboard) {
1167
+ throw new ValidationError('copyCsvToClipboard() требует поддержки Clipboard API');
1168
+ }
1169
+ const csv = jsonToCsv$1(data, options);
1170
+ try {
1171
+ await navigator.clipboard.writeText(csv);
1172
+ return true;
1173
+ }
1174
+ catch (error) {
1175
+ console.error('Failed to copy to clipboard:', error);
1176
+ return false;
1177
+ }
1178
+ }
1179
+ /**
1180
+ * Сохраняет CSV в localStorage
1181
+ *
1182
+ * @param key - Ключ для сохранения
1183
+ * @param data - Данные для сохранения
1184
+ * @param options - Опции для jsonToCsv
1185
+ */
1186
+ function saveCsvToLocalStorage(key, data, options = {}) {
1187
+ if (typeof window === 'undefined' || !localStorage) {
1188
+ throw new ValidationError('saveCsvToLocalStorage() требует localStorage');
1189
+ }
1190
+ const csv = jsonToCsv$1(data, options);
1191
+ localStorage.setItem(key, csv);
1192
+ }
1193
+ /**
1194
+ * Загружает CSV из localStorage
1195
+ *
1196
+ * @param key - Ключ для загрузки
1197
+ * @param options - Опции для csvToJson
1198
+ * @returns Распарсенные данные или null
1199
+ */
1200
+ function loadCsvFromLocalStorage(key, options = {}) {
1201
+ if (typeof window === 'undefined' || !localStorage) {
1202
+ throw new ValidationError('loadCsvFromLocalStorage() требует localStorage');
1203
+ }
1204
+ const csv = localStorage.getItem(key);
1205
+ if (!csv) {
1206
+ return null;
1207
+ }
1208
+ return csvToJson$1(csv, options);
1209
+ }
1210
+ /**
1211
+ * Асинхронная версия loadCsvFromLocalStorage
1212
+ */
1213
+ async function loadCsvFromLocalStorageAsync(key, options = {}) {
1214
+ return loadCsvFromLocalStorage(key, options);
1215
+ }
1216
+ /**
1217
+ * Создает CSV файл из JSON данных (альтернатива downloadAsCsv)
1218
+ * Возвращает Blob вместо автоматического скачивания
1219
+ *
1220
+ * @param data - Массив объектов
1221
+ * @param options - Опции для jsonToCsv
1222
+ * @returns CSV Blob
1223
+ */
1224
+ function createCsvBlob(data, options = {}) {
1225
+ const csv = jsonToCsv$1(data, options);
1226
+ return new Blob([csv], {
1227
+ type: 'text/csv;charset=utf-8;'
1228
+ });
1229
+ }
1230
+ /**
1231
+ * Асинхронная версия createCsvBlob
1232
+ */
1233
+ async function createCsvBlobAsync(data, options = {}) {
1234
+ return createCsvBlob(data, options);
1235
+ }
1236
+ /**
1237
+ * Парсит CSV строку из Blob
1238
+ *
1239
+ * @param blob - CSV Blob
1240
+ * @param options - Опции для csvToJson
1241
+ * @returns Promise с JSON данными
1242
+ */
1243
+ async function parseCsvBlob(blob, options = {}) {
1244
+ if (!(blob instanceof Blob)) {
1245
+ throw new ValidationError('Input must be a Blob object');
1246
+ }
1247
+ return new Promise((resolve, reject) => {
1248
+ const reader = new FileReader();
1249
+ reader.onload = function (event) {
1250
+ try {
1251
+ const csvText = event.target?.result;
1252
+ const json = csvToJson$1(csvText, options);
1253
+ resolve(json);
1254
+ }
1255
+ catch (error) {
1256
+ reject(error);
1257
+ }
1258
+ };
1259
+ reader.onerror = function () {
1260
+ reject(new ValidationError('Ошибка чтения Blob'));
1261
+ };
1262
+ reader.readAsText(blob, 'UTF-8');
1263
+ });
1264
+ }
1265
+ /**
1266
+ * Асинхронная версия parseCsvBlob
1267
+ */
1268
+ async function parseCsvBlobAsync(blob, options = {}) {
1269
+ return parseCsvBlob(blob, options);
1270
+ }
1271
+ // Экспорт для Node.js совместимости
1272
+ if (typeof module !== 'undefined' && module.exports) {
1273
+ module.exports = {
1274
+ downloadAsCsv,
1275
+ downloadAsCsvAsync: downloadAsCsvAsync$1,
1276
+ parseCsvFile,
1277
+ parseCsvFileStream,
1278
+ createCsvBlob,
1279
+ createCsvBlobAsync,
1280
+ parseCsvBlob,
1281
+ parseCsvBlobAsync,
1282
+ jsonToCsvStream,
1283
+ jsonToNdjsonStream,
1284
+ csvToJsonStream,
1285
+ loadCsvFromUrl,
1286
+ loadCsvFromUrlAsync,
1287
+ openCsvInNewTab,
1288
+ openCsvInNewTabAsync,
1289
+ copyCsvToClipboard,
1290
+ saveCsvToLocalStorage,
1291
+ loadCsvFromLocalStorage,
1292
+ loadCsvFromLocalStorageAsync
1293
+ };
1294
+ }
1295
+
1296
+ // Worker Pool для параллельной обработки CSV
1297
+ // Использует Comlink для простой коммуникации с Web Workers
1298
+ // Проверка поддержки Web Workers
1299
+ const WORKERS_SUPPORTED = typeof Worker !== 'undefined';
1300
+ function isTransferableBuffer(value) {
1301
+ if (!(value instanceof ArrayBuffer)) {
1302
+ return false;
1303
+ }
1304
+ if (typeof SharedArrayBuffer !== 'undefined' && value instanceof SharedArrayBuffer) {
1305
+ return false;
1306
+ }
1307
+ return true;
1308
+ }
1309
+ function collectTransferables(args) {
1310
+ const transferables = [];
1311
+ const collectFromValue = (value) => {
1312
+ if (!value) {
1313
+ return;
1314
+ }
1315
+ if (isTransferableBuffer(value)) {
1316
+ transferables.push(value);
1317
+ return;
1318
+ }
1319
+ if (ArrayBuffer.isView(value) && isTransferableBuffer(value.buffer)) {
1320
+ transferables.push(value.buffer);
1321
+ return;
1322
+ }
1323
+ if (Array.isArray(value)) {
1324
+ value.forEach(collectFromValue);
1325
+ }
1326
+ };
1327
+ args.forEach(collectFromValue);
1328
+ return transferables.length ? transferables : null;
1329
+ }
1330
+ /**
1331
+ * Опции для Worker Pool
1332
+ * @typedef {Object} WorkerPoolOptions
1333
+ * @property {number} [workerCount=4] - Количество workers в pool
1334
+ * @property {number} [maxQueueSize=100] - Максимальный размер очереди задач
1335
+ * @property {boolean} [autoScale=true] - Автоматическое масштабирование pool
1336
+ * @property {number} [idleTimeout=60000] - Таймаут простоя worker (мс)
1337
+ */
1338
+ /**
1339
+ * Статистика Worker Pool
1340
+ * @typedef {Object} WorkerPoolStats
1341
+ * @property {number} totalWorkers - Всего workers
1342
+ * @property {number} activeWorkers - Активные workers
1343
+ * @property {number} idleWorkers - Простаивающие workers
1344
+ * @property {number} queueSize - Размер очереди
1345
+ * @property {number} tasksCompleted - Завершенные задачи
1346
+ * @property {number} tasksFailed - Неудачные задачи
1347
+ */
1348
+ /**
1349
+ * Прогресс обработки задачи
1350
+ * @typedef {Object} TaskProgress
1351
+ * @property {number} processed - Обработано элементов
1352
+ * @property {number} total - Всего элементов
1353
+ * @property {number} percentage - Процент выполнения
1354
+ * @property {number} speed - Скорость обработки (элементов/сек)
1355
+ */
1356
+ /**
1357
+ * Worker Pool для параллельной обработки CSV
1358
+ */
1359
+ class WorkerPool {
1360
+ /**
1361
+ * Создает новый Worker Pool
1362
+ * @param {string} workerScript - URL скрипта worker
1363
+ * @param {WorkerPoolOptions} [options] - Опции pool
1364
+ */
1365
+ constructor(workerScript, options = {}) {
1366
+ if (!WORKERS_SUPPORTED) {
1367
+ throw new ValidationError('Web Workers не поддерживаются в этом браузере');
1368
+ }
1369
+ this.workerScript = workerScript;
1370
+ this.options = {
1371
+ workerCount: 4,
1372
+ maxQueueSize: 100,
1373
+ autoScale: true,
1374
+ idleTimeout: 60000,
1375
+ ...options
1376
+ };
1377
+ this.workers = [];
1378
+ this.taskQueue = [];
1379
+ this.activeTasks = new Map();
1380
+ this.stats = {
1381
+ totalWorkers: 0,
1382
+ activeWorkers: 0,
1383
+ idleWorkers: 0,
1384
+ queueSize: 0,
1385
+ tasksCompleted: 0,
1386
+ tasksFailed: 0
1387
+ };
1388
+ this.initializeWorkers();
1389
+ }
1390
+ /**
1391
+ * Инициализация workers
1392
+ * @private
1393
+ */
1394
+ initializeWorkers() {
1395
+ const { workerCount } = this.options;
1396
+ for (let i = 0; i < workerCount; i++) {
1397
+ this.createWorker();
1398
+ }
1399
+ this.updateStats();
1400
+ }
1401
+ /**
1402
+ * Создает нового worker
1403
+ * @private
1404
+ */
1405
+ createWorker() {
1406
+ try {
1407
+ const worker = new Worker(this.workerScript, { type: 'module' });
1408
+ worker.id = `worker-${this.workers.length}`;
1409
+ worker.status = 'idle';
1410
+ worker.lastUsed = Date.now();
1411
+ worker.taskId = null;
1412
+ // Обработчики событий
1413
+ worker.onmessage = (event) => this.handleWorkerMessage(worker, event);
1414
+ worker.onerror = (error) => this.handleWorkerError(worker, error);
1415
+ worker.onmessageerror = (error) => this.handleWorkerMessageError(worker, error);
1416
+ this.workers.push(worker);
1417
+ this.stats.totalWorkers++;
1418
+ this.stats.idleWorkers++;
1419
+ return worker;
1420
+ }
1421
+ catch (error) {
1422
+ throw new ConfigurationError(`Не удалось создать worker: ${error.message}`);
1423
+ }
1424
+ }
1425
+ /**
1426
+ * Обработка сообщений от worker
1427
+ * @private
1428
+ */
1429
+ handleWorkerMessage(worker, event) {
1430
+ const { data } = event;
1431
+ if (data.type === 'PROGRESS') {
1432
+ this.handleProgress(worker, data);
1433
+ }
1434
+ else if (data.type === 'RESULT') {
1435
+ this.handleResult(worker, data);
1436
+ }
1437
+ else if (data.type === 'ERROR') {
1438
+ this.handleWorkerTaskError(worker, data);
1439
+ }
1440
+ }
1441
+ /**
1442
+ * Обработка прогресса задачи
1443
+ * @private
1444
+ */
1445
+ handleProgress(worker, progressData) {
1446
+ const taskId = worker.taskId;
1447
+ if (taskId && this.activeTasks.has(taskId)) {
1448
+ const task = this.activeTasks.get(taskId);
1449
+ if (task.onProgress) {
1450
+ task.onProgress({
1451
+ processed: progressData.processed,
1452
+ total: progressData.total,
1453
+ percentage: (progressData.processed / progressData.total) * 100,
1454
+ speed: progressData.speed || 0
1455
+ });
1456
+ }
1457
+ }
1458
+ }
1459
+ /**
1460
+ * Обработка результата задачи
1461
+ * @private
1462
+ */
1463
+ handleResult(worker, resultData) {
1464
+ const taskId = worker.taskId;
1465
+ if (taskId && this.activeTasks.has(taskId)) {
1466
+ const task = this.activeTasks.get(taskId);
1467
+ // Освобождение worker
1468
+ worker.status = 'idle';
1469
+ worker.lastUsed = Date.now();
1470
+ worker.taskId = null;
1471
+ this.stats.activeWorkers--;
1472
+ this.stats.idleWorkers++;
1473
+ // Завершение задачи
1474
+ task.resolve(resultData.data);
1475
+ this.activeTasks.delete(taskId);
1476
+ this.stats.tasksCompleted++;
1477
+ // Обработка следующей задачи в очереди
1478
+ this.processQueue();
1479
+ this.updateStats();
1480
+ }
1481
+ }
1482
+ /**
1483
+ * Обработка ошибки задачи
1484
+ * @private
1485
+ */
1486
+ handleWorkerTaskError(worker, errorData) {
1487
+ const taskId = worker.taskId;
1488
+ if (taskId && this.activeTasks.has(taskId)) {
1489
+ const task = this.activeTasks.get(taskId);
1490
+ // Освобождение worker
1491
+ worker.status = 'idle';
1492
+ worker.lastUsed = Date.now();
1493
+ worker.taskId = null;
1494
+ this.stats.activeWorkers--;
1495
+ this.stats.idleWorkers++;
1496
+ // Завершение с ошибкой
1497
+ const workerError = new Error(errorData.message || 'Ошибка в worker');
1498
+ if (errorData.code) {
1499
+ workerError.code = errorData.code;
1500
+ }
1501
+ if (errorData.details) {
1502
+ workerError.details = errorData.details;
1503
+ }
1504
+ task.reject(workerError);
1505
+ this.activeTasks.delete(taskId);
1506
+ this.stats.tasksFailed++;
1507
+ // Обработка следующей задачи
1508
+ this.processQueue();
1509
+ this.updateStats();
1510
+ }
1511
+ }
1512
+ /**
1513
+ * Обработка ошибок worker
1514
+ * @private
1515
+ */
1516
+ handleWorkerError(worker, error) {
1517
+ console.error(`Worker ${worker.id} error:`, error);
1518
+ // Перезапуск worker
1519
+ this.restartWorker(worker);
1520
+ }
1521
+ /**
1522
+ * Обработка ошибок сообщений
1523
+ * @private
1524
+ */
1525
+ handleWorkerMessageError(worker, error) {
1526
+ console.error(`Worker ${worker.id} message error:`, error);
1527
+ }
1528
+ /**
1529
+ * Перезапуск worker
1530
+ * @private
1531
+ */
1532
+ restartWorker(worker) {
1533
+ const index = this.workers.indexOf(worker);
1534
+ if (index !== -1) {
1535
+ // Завершение старого worker
1536
+ worker.terminate();
1537
+ // Удаление из статистики
1538
+ if (worker.status === 'active') {
1539
+ this.stats.activeWorkers--;
1540
+ }
1541
+ else {
1542
+ this.stats.idleWorkers--;
1543
+ }
1544
+ this.stats.totalWorkers--;
1545
+ // Создание нового worker
1546
+ const newWorker = this.createWorker();
1547
+ this.workers[index] = newWorker;
1548
+ // Перезапуск задачи если была активна
1549
+ if (worker.taskId && this.activeTasks.has(worker.taskId)) {
1550
+ const task = this.activeTasks.get(worker.taskId);
1551
+ this.executeTask(newWorker, task);
1552
+ }
1553
+ }
1554
+ }
1555
+ /**
1556
+ * Выполнение задачи на worker
1557
+ * @private
1558
+ */
1559
+ executeTask(worker, task) {
1560
+ worker.status = 'active';
1561
+ worker.lastUsed = Date.now();
1562
+ worker.taskId = task.id;
1563
+ this.stats.idleWorkers--;
1564
+ this.stats.activeWorkers++;
1565
+ // Отправка задачи в worker
1566
+ const payload = {
1567
+ type: 'EXECUTE',
1568
+ taskId: task.id,
1569
+ method: task.method,
1570
+ args: task.args,
1571
+ options: task.options
1572
+ };
1573
+ if (task.transferList && task.transferList.length) {
1574
+ worker.postMessage(payload, task.transferList);
1575
+ }
1576
+ else {
1577
+ worker.postMessage(payload);
1578
+ }
1579
+ }
1580
+ /**
1581
+ * Обработка очереди задач
1582
+ * @private
1583
+ */
1584
+ processQueue() {
1585
+ if (this.taskQueue.length === 0) {
1586
+ return;
1587
+ }
1588
+ while (this.taskQueue.length > 0) {
1589
+ const idleWorker = this.workers.find(w => w.status === 'idle');
1590
+ if (!idleWorker) {
1591
+ if (this.options.autoScale && this.workers.length < this.options.maxQueueSize) {
1592
+ this.createWorker();
1593
+ continue;
1594
+ }
1595
+ break;
1596
+ }
1597
+ const task = this.taskQueue.shift();
1598
+ this.stats.queueSize--;
1599
+ this.executeTask(idleWorker, task);
1600
+ }
1601
+ this.updateStats();
1602
+ }
1603
+ /**
1604
+ * Обновление статистики
1605
+ * @private
1606
+ */
1607
+ updateStats() {
1608
+ this.stats.queueSize = this.taskQueue.length;
1609
+ }
1610
+ /**
1611
+ * Выполнение задачи через pool
1612
+ * @param {string} method - Метод для вызова в worker
1613
+ * @param {Array} args - Аргументы метода
1614
+ * @param {Object} [options] - Опции задачи
1615
+ * @param {Function} [onProgress] - Callback прогресса
1616
+ * @returns {Promise<unknown>} Результат выполнения
1617
+ */
1618
+ async exec(method, args = [], options = {}, onProgress = null) {
1619
+ return new Promise((resolve, reject) => {
1620
+ // Проверка размера очереди
1621
+ if (this.taskQueue.length >= this.options.maxQueueSize) {
1622
+ reject(new Error('Очередь задач переполнена'));
1623
+ return;
1624
+ }
1625
+ // Создание задачи
1626
+ const taskId = `task-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
1627
+ const { transfer, ...taskOptions } = options || {};
1628
+ const transferList = transfer || collectTransferables(args);
1629
+ const task = {
1630
+ id: taskId,
1631
+ method,
1632
+ args,
1633
+ options: taskOptions,
1634
+ transferList,
1635
+ onProgress,
1636
+ resolve,
1637
+ reject,
1638
+ createdAt: Date.now()
1639
+ };
1640
+ // Добавление в очередь
1641
+ this.taskQueue.push(task);
1642
+ this.stats.queueSize++;
1643
+ // Запуск обработки очереди
1644
+ this.processQueue();
1645
+ this.updateStats();
1646
+ });
1647
+ }
1648
+ /**
1649
+ * Получение статистики pool
1650
+ * @returns {WorkerPoolStats} Статистика
1651
+ */
1652
+ getStats() {
1653
+ return { ...this.stats };
1654
+ }
1655
+ /**
1656
+ * Очистка простаивающих workers
1657
+ */
1658
+ cleanupIdleWorkers() {
1659
+ const now = Date.now();
1660
+ const { idleTimeout } = this.options;
1661
+ for (let i = this.workers.length - 1; i >= 0; i--) {
1662
+ const worker = this.workers[i];
1663
+ if (worker.status === 'idle' && (now - worker.lastUsed) > idleTimeout) {
1664
+ // Сохранение минимального количества workers
1665
+ if (this.workers.length > 1) {
1666
+ worker.terminate();
1667
+ this.workers.splice(i, 1);
1668
+ this.stats.totalWorkers--;
1669
+ this.stats.idleWorkers--;
1670
+ }
1671
+ }
1672
+ }
1673
+ }
1674
+ /**
1675
+ * Завершение всех workers
1676
+ */
1677
+ terminate() {
1678
+ this.workers.forEach(worker => {
1679
+ worker.terminate();
1680
+ });
1681
+ this.workers = [];
1682
+ this.taskQueue = [];
1683
+ this.activeTasks.clear();
1684
+ // Сброс статистики
1685
+ this.stats = {
1686
+ totalWorkers: 0,
1687
+ activeWorkers: 0,
1688
+ idleWorkers: 0,
1689
+ queueSize: 0,
1690
+ tasksCompleted: 0,
1691
+ tasksFailed: 0
1692
+ };
1693
+ }
1694
+ }
1695
+ /**
1696
+ * Создает Worker Pool для обработки CSV
1697
+ * @param {WorkerPoolOptions} [options] - Опции pool
1698
+ * @returns {WorkerPool} Worker Pool
1699
+ */
1700
+ function createWorkerPool(options = {}) {
1701
+ // Используем встроенный worker скрипт
1702
+ const baseUrl = typeof document !== 'undefined'
1703
+ ? document.baseURI
1704
+ : (typeof self !== 'undefined' && self.location
1705
+ ? self.location.href
1706
+ : '');
1707
+ const workerScript = new URL('./csv-parser.worker.js', baseUrl).href;
1708
+ return new WorkerPool(workerScript, options);
1709
+ }
1710
+ /**
1711
+ * Парсит CSV с использованием Web Workers
1712
+ * @param {string|File} csvInput - CSV строка или File объект
1713
+ * @param {Object} [options] - Опции парсинга
1714
+ * @param {Function} [onProgress] - Callback прогресса
1715
+ * @returns {Promise<Array<Object>>} JSON данные
1716
+ */
1717
+ async function parseCSVWithWorker(csvInput, options = {}, onProgress = null) {
1718
+ // Создание pool если нужно
1719
+ const poolHolder = parseCSVWithWorker;
1720
+ if (!poolHolder.pool) {
1721
+ poolHolder.pool = createWorkerPool();
1722
+ }
1723
+ const pool = poolHolder.pool;
1724
+ // Подготовка CSV строки
1725
+ // ?????????? CSV ??????
1726
+ let csvPayload = csvInput;
1727
+ let transfer = null;
1728
+ if (csvInput instanceof File) {
1729
+ const buffer = await readFileAsArrayBuffer(csvInput);
1730
+ csvPayload = new Uint8Array(buffer);
1731
+ transfer = [buffer];
1732
+ }
1733
+ else if (csvInput instanceof ArrayBuffer) {
1734
+ csvPayload = csvInput;
1735
+ transfer = [csvInput];
1736
+ }
1737
+ else if (ArrayBuffer.isView(csvInput)) {
1738
+ csvPayload = csvInput;
1739
+ if (csvInput.buffer instanceof ArrayBuffer) {
1740
+ transfer = [csvInput.buffer];
1741
+ }
1742
+ }
1743
+ else if (typeof csvInput !== 'string') {
1744
+ throw new ValidationError('Input must be a CSV string, File, or ArrayBuffer');
1745
+ }
1746
+ // ????????? ?????? ????? pool
1747
+ const execOptions = transfer ? { transfer } : {};
1748
+ return pool.exec('parseCSV', [csvPayload, options], execOptions, onProgress);
1749
+ }
1750
+ /**
1751
+ * Чтение файла как текст
1752
+ * @private
1753
+ */
1754
+ async function readFileAsArrayBuffer(file) {
1755
+ return new Promise((resolve, reject) => {
1756
+ const reader = new FileReader();
1757
+ reader.onload = (event) => resolve(event.target.result);
1758
+ reader.onerror = (error) => reject(error);
1759
+ reader.readAsArrayBuffer(file);
1760
+ });
1761
+ }
1762
+ // Экспорт для Node.js совместимости
1763
+ if (typeof module !== 'undefined' && module.exports) {
1764
+ module.exports = {
1765
+ WorkerPool,
1766
+ createWorkerPool,
1767
+ parseCSVWithWorker
1768
+ };
1769
+ }
1770
+
1771
+ var workerPool = /*#__PURE__*/Object.freeze({
1772
+ __proto__: null,
1773
+ WorkerPool: WorkerPool,
1774
+ createWorkerPool: createWorkerPool,
1775
+ parseCSVWithWorker: parseCSVWithWorker
1776
+ });
1777
+
1778
+ // Браузерный entry point для jtcsv
1779
+ // Экспортирует все функции с поддержкой браузера
1780
+ const { jsonToCsv, preprocessData, deepUnwrap } = jsonToCsvBrowser;
1781
+ const { csvToJson, csvToJsonIterator, autoDetectDelimiter } = csvToJsonBrowser;
1782
+ /**
1783
+ * Ленивая инициализация Worker Pool
1784
+ */
1785
+ async function createWorkerPoolLazy(options = {}) {
1786
+ const mod = await Promise.resolve().then(function () { return workerPool; });
1787
+ return mod.createWorkerPool(options);
1788
+ }
1789
+ /**
1790
+ * Ленивый парсинг CSV с использованием Worker
1791
+ */
1792
+ async function parseCSVWithWorkerLazy(csvInput, options = {}, onProgress) {
1793
+ const mod = await Promise.resolve().then(function () { return workerPool; });
1794
+ return mod.parseCSVWithWorker(csvInput, options, onProgress);
1795
+ }
1796
+ /**
1797
+ * Асинхронная версия jsonToCsv
1798
+ */
1799
+ async function jsonToCsvAsync(data, options = {}) {
1800
+ return jsonToCsv(data, options);
1801
+ }
1802
+ /**
1803
+ * Асинхронная версия csvToJson
1804
+ */
1805
+ async function csvToJsonAsync(csv, options = {}) {
1806
+ return csvToJson(csv, options);
1807
+ }
1808
+ /**
1809
+ * Асинхронная версия parseCsvFile
1810
+ */
1811
+ async function parseCsvFileAsync(file, options = {}) {
1812
+ return parseCsvFile(file, options);
1813
+ }
1814
+ /**
1815
+ * Асинхронная версия autoDetectDelimiter
1816
+ */
1817
+ async function autoDetectDelimiterAsync(csv) {
1818
+ return autoDetectDelimiter(csv);
1819
+ }
1820
+ /**
1821
+ * Асинхронная версия downloadAsCsv
1822
+ */
1823
+ async function downloadAsCsvAsync(data, filename = 'export.csv', options = {}) {
1824
+ return downloadAsCsv(data, filename, options);
1825
+ }
1826
+ // Основной экспорт
1827
+ const jtcsv = {
1828
+ // JSON to CSV функции
1829
+ jsonToCsv,
1830
+ preprocessData,
1831
+ downloadAsCsv,
1832
+ deepUnwrap,
1833
+ // CSV to JSON функции
1834
+ csvToJson,
1835
+ csvToJsonIterator,
1836
+ parseCsvFile,
1837
+ parseCsvFileStream,
1838
+ jsonToCsvStream,
1839
+ jsonToNdjsonStream,
1840
+ csvToJsonStream,
1841
+ autoDetectDelimiter,
1842
+ // Web Workers функции
1843
+ createWorkerPool,
1844
+ parseCSVWithWorker,
1845
+ createWorkerPoolLazy,
1846
+ parseCSVWithWorkerLazy,
1847
+ // Асинхронные функции
1848
+ jsonToCsvAsync,
1849
+ csvToJsonAsync,
1850
+ parseCsvFileAsync,
1851
+ autoDetectDelimiterAsync,
1852
+ downloadAsCsvAsync,
1853
+ // Error classes
1854
+ ValidationError,
1855
+ SecurityError,
1856
+ FileSystemError,
1857
+ ParsingError,
1858
+ LimitError,
1859
+ ConfigurationError,
1860
+ ERROR_CODES,
1861
+ // Удобные алиасы
1862
+ parse: csvToJson,
1863
+ unparse: jsonToCsv,
1864
+ parseAsync: csvToJsonAsync,
1865
+ unparseAsync: jsonToCsvAsync,
1866
+ // Версия
1867
+ version: '2.0.0-browser'
1868
+ };
1869
+ // Экспорт для разных сред
1870
+ if (typeof module !== 'undefined' && module.exports) {
1871
+ // Node.js CommonJS
1872
+ module.exports = jtcsv;
1873
+ }
1874
+ else if (typeof define === 'function' && define.amd) {
1875
+ // AMD
1876
+ define([], () => jtcsv);
1877
+ }
1878
+ else if (typeof window !== 'undefined') {
1879
+ // Браузер (глобальная переменная)
1880
+ window.jtcsv = jtcsv;
1881
+ }
1882
+
1883
+ exports.ConfigurationError = ConfigurationError;
1884
+ exports.ERROR_CODES = ERROR_CODES;
1885
+ exports.FileSystemError = FileSystemError;
1886
+ exports.LimitError = LimitError;
1887
+ exports.ParsingError = ParsingError;
1888
+ exports.SecurityError = SecurityError;
1889
+ exports.ValidationError = ValidationError;
1890
+ exports.autoDetectDelimiter = autoDetectDelimiter;
1891
+ exports.autoDetectDelimiterAsync = autoDetectDelimiterAsync;
1892
+ exports.createWorkerPool = createWorkerPool;
1893
+ exports.createWorkerPoolLazy = createWorkerPoolLazy;
1894
+ exports.csvToJson = csvToJson;
1895
+ exports.csvToJsonAsync = csvToJsonAsync;
1896
+ exports.csvToJsonIterator = csvToJsonIterator;
1897
+ exports.csvToJsonStream = csvToJsonStream;
1898
+ exports.deepUnwrap = deepUnwrap;
1899
+ exports.default = jtcsv;
1900
+ exports.downloadAsCsv = downloadAsCsv;
1901
+ exports.downloadAsCsvAsync = downloadAsCsvAsync;
1902
+ exports.jsonToCsv = jsonToCsv;
1903
+ exports.jsonToCsvAsync = jsonToCsvAsync;
1904
+ exports.jsonToCsvStream = jsonToCsvStream;
1905
+ exports.jsonToNdjsonStream = jsonToNdjsonStream;
1906
+ exports.parseCSVWithWorker = parseCSVWithWorker;
1907
+ exports.parseCSVWithWorkerLazy = parseCSVWithWorkerLazy;
1908
+ exports.parseCsvFile = parseCsvFile;
1909
+ exports.parseCsvFileAsync = parseCsvFileAsync;
1910
+ exports.parseCsvFileStream = parseCsvFileStream;
1911
+ exports.preprocessData = preprocessData;
1912
+ //# sourceMappingURL=jtcsv-full.cjs.js.map