jtcsv 2.2.8 → 3.1.0

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