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,194 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Простой пример использования новых возможностей JTCSV 2.1.0
5
+ * Демонстрация Fast-Path Engine, NDJSON и Plugin System
6
+ *
7
+ * @version 1.0.0
8
+ * @date 2026-01-22
9
+ */
10
+
11
+ // Используем require для совместимости с текущей структурой проекта
12
+ const { jsonToCsv, csvToJson } = require('jtcsv');
13
+ import type { JsonToCsvOptions, CsvToJsonOptions } from '../src/types';
14
+
15
+ (async () => {
16
+ console.log('🚀 JTCSV 2.1.0 - Демонстрация новых возможностей\n');
17
+
18
+ // ============================================================================
19
+ // 1. Базовое использование (обратная совместимость)
20
+ // ============================================================================
21
+
22
+ console.log('1. 📦 Базовое использование (обратная совместимость)');
23
+ console.log('='.repeat(60));
24
+
25
+ const sampleData = [
26
+ { id: 1, name: 'John Doe', age: 30, city: 'New York' },
27
+ { id: 2, name: 'Jane Smith', age: 25, city: 'London' },
28
+ { id: 3, name: 'Bob Johnson', age: 35, city: 'Tokyo' }
29
+ ];
30
+
31
+ // Конвертация JSON → CSV
32
+ const csv = jsonToCsv(sampleData, { delimiter: ',' });
33
+ console.log('📄 CSV результат:');
34
+ console.log(csv);
35
+ console.log();
36
+
37
+ // Конвертация CSV → JSON
38
+ const json = csvToJson(csv, { delimiter: ',' });
39
+ console.log('📊 JSON результат:');
40
+ console.log(JSON.stringify(json, null, 2));
41
+ console.log();
42
+
43
+ // ============================================================================
44
+ // 2. Fast-Path Engine (оптимизированный парсинг)
45
+ // ============================================================================
46
+
47
+ console.log('\n2. ⚡ Fast-Path Engine (оптимизированный парсинг)');
48
+ console.log('='.repeat(60));
49
+
50
+ const FastPathEngine = require('../src/engines/fast-path-engine');
51
+ const engine = new FastPathEngine();
52
+
53
+ const largeCsv = `id,name,age,city
54
+ 1,John Doe,30,New York
55
+ 2,Jane Smith,25,London
56
+ 3,Bob Johnson,35,Tokyo
57
+ 4,Alice Brown,28,Paris
58
+ 5,Charlie Wilson,42,Berlin`;
59
+
60
+ console.log('📊 Парсинг CSV с Fast-Path Engine:');
61
+ const fastPathResult = engine.parse(largeCsv, { delimiter: ',' });
62
+ console.log(JSON.stringify(fastPathResult, null, 2));
63
+ console.log();
64
+
65
+ // ============================================================================
66
+ // 3. NDJSON поддержка (Newline Delimited JSON)
67
+ // ============================================================================
68
+
69
+ console.log('\n3. 📝 NDJSON поддержка (Newline Delimited JSON)');
70
+ console.log('='.repeat(60));
71
+
72
+ const { jsonToNdjson, ndjsonToJson } = require('jtcsv');
73
+
74
+ const ndjsonData = [
75
+ { id: 1, name: 'John', active: true },
76
+ { id: 2, name: 'Jane', active: false },
77
+ { id: 3, name: 'Bob', active: true }
78
+ ];
79
+
80
+ // Конвертация в NDJSON
81
+ const ndjson = jsonToNdjson(ndjsonData);
82
+ console.log('📄 NDJSON результат:');
83
+ console.log(ndjson);
84
+ console.log();
85
+
86
+ // Обратная конвертация
87
+ const fromNdjson = ndjsonToJson(ndjson);
88
+ console.log('📊 JSON из NDJSON:');
89
+ console.log(JSON.stringify(fromNdjson, null, 2));
90
+ console.log();
91
+
92
+ // ============================================================================
93
+ // 4. Потоковая обработка
94
+ // ============================================================================
95
+
96
+ console.log('\n4. 🌊 Потоковая обработка');
97
+ console.log('='.repeat(60));
98
+
99
+ const { streamCsvToJson, streamJsonToCsv } = require('jtcsv');
100
+
101
+ console.log('📊 Пример потоковой обработки CSV:');
102
+
103
+ // Создание потока CSV данных
104
+ const csvStream = `id,name,age
105
+ 1,John,30
106
+ 2,Jane,25
107
+ 3,Bob,35`;
108
+
109
+ const jsonStream = streamCsvToJson(csvStream, { delimiter: ',' });
110
+
111
+ // В реальном приложении здесь была бы обработка потока
112
+ console.log('✅ Поток создан успешно');
113
+ console.log();
114
+
115
+ // ============================================================================
116
+ // 5. Асинхронные функции
117
+ // ============================================================================
118
+
119
+ console.log('\n5. ⏱️ Асинхронные функции');
120
+ console.log('='.repeat(60));
121
+
122
+ try {
123
+ // Использование асинхронных версий функций
124
+ const asyncCsv = await jsonToCsv(sampleData, { delimiter: ';' });
125
+ console.log('📄 Асинхронный CSV результат:');
126
+ console.log(asyncCsv.substring(0, 100) + '...');
127
+ console.log();
128
+ } catch (error: any) {
129
+ console.error('❌ Ошибка при асинхронной конвертации:', error.message);
130
+ }
131
+
132
+ // ============================================================================
133
+ // 6. Многопоточная обработка
134
+ // ============================================================================
135
+
136
+ console.log('\n6. 🚀 Многопоточная обработка');
137
+ console.log('='.repeat(60));
138
+
139
+ try {
140
+ const { processCsvMultithreaded } = require('../src/workers/csv-multithreaded');
141
+
142
+ console.log('📊 Запуск многопоточной обработки...');
143
+
144
+ // В реальном приложении здесь была бы обработка больших данных
145
+ console.log('✅ Многопоточная система готова к использованию');
146
+ console.log();
147
+ } catch (error) {
148
+ console.log('ℹ️ Многопоточная обработка доступна только в Node.js');
149
+ console.log();
150
+ }
151
+
152
+ // ============================================================================
153
+ // 7. TypeScript типы
154
+ // ============================================================================
155
+
156
+ console.log('\n7. 📘 TypeScript типы');
157
+ console.log('='.repeat(60));
158
+
159
+ // Демонстрация TypeScript типов
160
+ const typedOptions: JsonToCsvOptions = {
161
+ delimiter: ',',
162
+ includeHeaders: true,
163
+ maxRecords: 100,
164
+ preventCsvInjection: true,
165
+ rfc4180Compliant: true
166
+ };
167
+
168
+ console.log('✅ TypeScript типы корректно работают');
169
+ console.log('📋 Пример опций:', JSON.stringify(typedOptions, null, 2));
170
+ console.log();
171
+
172
+ // ============================================================================
173
+ // Заключение
174
+ // ============================================================================
175
+
176
+ console.log('\n🎉 Демонстрация завершена!');
177
+ console.log('='.repeat(60));
178
+ console.log('\n📚 Основные возможности JTCSV 2.1.0:');
179
+ console.log(' • ⚡ Fast-Path Engine для оптимизированного парсинга');
180
+ console.log(' • 📝 Поддержка NDJSON (Newline Delimited JSON)');
181
+ console.log(' • 🌊 Потоковая обработка больших данных');
182
+ console.log(' • ⏱️ Асинхронные и многопоточные функции');
183
+ console.log(' • 📘 Полная поддержка TypeScript');
184
+ console.log(' • 🔌 Расширяемая плагинная система');
185
+ console.log(' • 🛡️ Защита от CSV инъекций');
186
+ console.log(' • 📊 Поддержка различных форматов (CSV, TSV, NDJSON)');
187
+ console.log('\n🚀 Готово к использованию в production!');
188
+ })();
189
+
190
+ // Обработка ошибок
191
+ process.on('unhandledRejection', (error) => {
192
+ console.error('❌ Необработанная ошибка:', error);
193
+ process.exit(1);
194
+ });
@@ -7,10 +7,10 @@
7
7
  * and real-time progress monitoring.
8
8
  */
9
9
 
10
- const fs = require('fs');
11
- const path = require('path');
12
- const { pipeline } = require('stream/promises');
13
- const jtcsv = require('../index.js');
10
+ import fs from "fs";
11
+ import path from "path";
12
+ const { pipeline } = await import("stream/promises");
13
+ import jtcsv from "jtcsv";
14
14
 
15
15
  async function generateLargeJsonFile(filePath, recordCount) {
16
16
  console.log(`Generating ${recordCount} records...`);
@@ -83,7 +83,8 @@ async function exampleJsonToCsvStreaming() {
83
83
  let buffer = '';
84
84
  let recordCount = 0;
85
85
 
86
- const jsonStream = new (require('stream').Transform)({
86
+ const streamModule = require("stream");
87
+ const jsonStream = new streamModule.Transform({
87
88
  objectMode: true,
88
89
  transform(chunk, encoding, callback) {
89
90
  buffer += chunk;
@@ -223,7 +224,7 @@ async function exampleCsvToJsonStreaming() {
223
224
  let firstRecord = true;
224
225
 
225
226
  // Custom transform to format JSON array
226
- const arrayFormatter = new (require('stream').Transform)({
227
+ const arrayFormatter = (require("stream").Transform)({
227
228
  objectMode: true,
228
229
  transform(chunk, encoding, callback) {
229
230
  const jsonRecord = JSON.stringify(chunk);
@@ -364,7 +365,9 @@ async function exampleBidirectionalStreaming() {
364
365
  // Cleanup on error
365
366
  try {
366
367
  await fs.promises.unlink(tempFile);
367
- } catch (e) {}
368
+ } catch (_e) {
369
+ // Ignore cleanup errors
370
+ }
368
371
  }
369
372
  }
370
373
 
@@ -408,12 +411,9 @@ if (require.main === module) {
408
411
  });
409
412
  }
410
413
 
411
- module.exports = {
414
+ export default {
412
415
  generateLargeJsonFile,
413
416
  exampleJsonToCsvStreaming,
414
417
  exampleCsvToJsonStreaming,
415
418
  exampleBidirectionalStreaming
416
- };
417
-
418
-
419
-
419
+ };
package/index.d.ts CHANGED
@@ -1,5 +1,4 @@
1
- declare module 'jtcsv' {
2
- import { Readable, Writable, Transform } from 'stream';
1
+ import { Readable, Writable, Transform } from 'stream';
3
2
 
4
3
  // JSON to CSV interfaces
5
4
  export interface JsonToCsvOptions {
@@ -13,12 +12,18 @@ declare module 'jtcsv' {
13
12
  template?: Record<string, any>;
14
13
  /** Maximum number of records to process (optional, no limit by default) */
15
14
  maxRecords?: number;
16
- /** Prevent CSV injection attacks by escaping formulas (default: true) */
17
- preventCsvInjection?: boolean;
18
- /** Ensure RFC 4180 compliance (proper quoting, line endings) (default: true) */
19
- rfc4180Compliant?: boolean;
20
- /** JSON schema for data validation and formatting */
21
- schema?: Record<string, any>;
15
+ /** Prevent CSV injection attacks by escaping formulas (default: true) */
16
+ preventCsvInjection?: boolean;
17
+ /** Ensure RFC 4180 compliance (proper quoting, line endings) (default: true) */
18
+ rfc4180Compliant?: boolean;
19
+ /** Normalize excessive quotes in JSON string values before CSV export (default: true) */
20
+ normalizeQuotes?: boolean;
21
+ /** JSON schema for data validation and formatting */
22
+ schema?: Record<string, any>;
23
+ /** Warn when record count exceeds this threshold (default: 1000000) */
24
+ memoryWarningThreshold?: number;
25
+ /** Safety limit for in-memory conversion (default: 5000000). Set to Infinity to disable. */
26
+ memoryLimit?: number;
22
27
  }
23
28
 
24
29
  export interface SaveAsCsvOptions extends JsonToCsvOptions {
@@ -50,6 +55,18 @@ declare module 'jtcsv' {
50
55
  useFastPath?: boolean;
51
56
  /** Fast-path output mode (default: 'objects') */
52
57
  fastPathMode?: 'objects' | 'compact' | 'stream';
58
+ /** Error recovery strategy for row-level errors (default: 'throw') */
59
+ onError?: 'skip' | 'warn' | 'throw';
60
+ /** Custom error handler for row-level errors */
61
+ errorHandler?: (error: Error, line: string, lineNumber: number) => void;
62
+ /** Attempt to repair shifted rows with trailing empty fields (default: true) */
63
+ repairRowShifts?: boolean;
64
+ /** Normalize excessive quotes in parsed fields (default: true) */
65
+ normalizeQuotes?: boolean;
66
+ /** Warn when row count exceeds this threshold (default: 1000000) */
67
+ memoryWarningThreshold?: number;
68
+ /** Safety limit for in-memory conversion (default: 5000000). Set to Infinity to disable. */
69
+ memoryLimit?: number;
53
70
  }
54
71
 
55
72
  // JSON save interfaces
@@ -171,41 +188,117 @@ declare module 'jtcsv' {
171
188
  }
172
189
 
173
190
  // Error classes
191
+ export type ErrorContextValue = Record<string, any> | string | null;
192
+
193
+ export interface ErrorMeta {
194
+ hint?: string;
195
+ docs?: string;
196
+ context?: ErrorContextValue;
197
+ originalError?: Error;
198
+ }
199
+
174
200
  export class JtcsvError extends Error {
175
201
  code: string;
176
- constructor(message: string, code?: string);
202
+ hint?: string;
203
+ docs?: string;
204
+ context?: ErrorContextValue;
205
+ originalError?: Error;
206
+ constructor(message: string, code?: string, meta?: ErrorMeta);
177
207
  }
178
208
 
179
209
  export class ValidationError extends JtcsvError {
180
- constructor(message: string);
210
+ constructor(message: string, meta?: ErrorMeta);
181
211
  }
182
212
 
183
213
  export class SecurityError extends JtcsvError {
184
- constructor(message: string);
214
+ constructor(message: string, meta?: ErrorMeta);
185
215
  }
186
216
 
187
217
  export class FileSystemError extends JtcsvError {
188
218
  originalError?: Error;
189
- constructor(message: string, originalError?: Error);
219
+ constructor(message: string, originalError?: Error | null, meta?: ErrorMeta);
190
220
  }
191
221
 
192
222
  export class ParsingError extends JtcsvError {
193
223
  lineNumber?: number;
194
224
  column?: number;
195
- constructor(message: string, lineNumber?: number, column?: number);
225
+ context?: ErrorContextValue;
226
+ expected?: string | null;
227
+ actual?: string | null;
228
+ originalMessage?: string;
229
+ constructor(
230
+ message: string,
231
+ lineNumber?: number | null,
232
+ column?: number | null,
233
+ context?: string | null,
234
+ expected?: string | null,
235
+ actual?: string | null,
236
+ meta?: ErrorMeta
237
+ );
196
238
  }
197
239
 
198
240
  export class LimitError extends JtcsvError {
199
- limit: number;
200
- actual: number;
201
- constructor(message: string, limit: number, actual: number);
241
+ limit: any;
242
+ actual: any;
243
+ constructor(message: string, limit: any, actual: any, meta?: ErrorMeta);
202
244
  }
203
245
 
204
246
  export class ConfigurationError extends JtcsvError {
205
- constructor(message: string);
247
+ constructor(message: string, meta?: ErrorMeta);
206
248
  }
207
249
 
250
+ export const ERROR_CODES: {
251
+ JTCSV_ERROR: string;
252
+ VALIDATION_ERROR: string;
253
+ SECURITY_ERROR: string;
254
+ FILE_SYSTEM_ERROR: string;
255
+ PARSING_ERROR: string;
256
+ LIMIT_ERROR: string;
257
+ CONFIGURATION_ERROR: string;
258
+ INVALID_INPUT: string;
259
+ SECURITY_VIOLATION: string;
260
+ FILE_NOT_FOUND: string;
261
+ PARSE_FAILED: string;
262
+ SIZE_LIMIT: string;
263
+ INVALID_CONFIG: string;
264
+ UNKNOWN_ERROR: string;
265
+ STREAM_CREATION_ERROR: string;
266
+ STREAM_PROCESSING_ERROR: string;
267
+ };
268
+
269
+ export type ErrorCode = typeof ERROR_CODES[keyof typeof ERROR_CODES];
270
+
208
271
  // Utility functions
272
+ export function createDetailedErrorMessage(
273
+ baseMessage: string,
274
+ details?: {
275
+ lineNumber?: number;
276
+ column?: number;
277
+ context?: string;
278
+ expected?: string;
279
+ actual?: string;
280
+ suggestion?: string;
281
+ codeSnippet?: string;
282
+ hint?: string;
283
+ docs?: string;
284
+ }
285
+ ): string;
286
+
287
+ export class ErrorContext {
288
+ lineNumber(line: number): this;
289
+ column(col: number): this;
290
+ context(ctx: string): this;
291
+ expected(exp: string): this;
292
+ actual(act: string): this;
293
+ suggestion(sugg: string): this;
294
+ codeSnippet(snippet: string): this;
295
+ hint(text: string): this;
296
+ docs(link: string): this;
297
+ buildMessage(baseMessage: string): string;
298
+ throwParsingError(baseMessage: string): never;
299
+ throwValidationError(baseMessage: string): never;
300
+ }
301
+
209
302
  export function createErrorMessage(type: string, details: string): string;
210
303
  export function handleError(error: Error, context?: Record<string, any>): void;
211
304
  export function safeExecute<T>(
@@ -218,6 +311,16 @@ declare module 'jtcsv' {
218
311
  errorType: string,
219
312
  context?: Record<string, any>
220
313
  ): T;
314
+ export function safeExecuteSync<T>(
315
+ fn: () => T,
316
+ errorType: string,
317
+ context?: Record<string, any>
318
+ ): T;
319
+ export function safeExecuteAsync<T>(
320
+ fn: () => Promise<T>,
321
+ errorType: string,
322
+ context?: Record<string, any>
323
+ ): Promise<T>;
221
324
 
222
325
  /**
223
326
  * Convert JSON array to CSV string
@@ -320,6 +423,17 @@ declare module 'jtcsv' {
320
423
  options?: CsvToJsonOptions
321
424
  ): Promise<Record<string, any>[]>;
322
425
 
426
+ /**
427
+ * Read CSV file and convert it to JSON array (normalized naming alias)
428
+ * @param filePath Path to CSV file
429
+ * @param options Conversion options
430
+ * @returns Promise that resolves to JSON array
431
+ */
432
+ export function csvToJsonFile(
433
+ filePath: string,
434
+ options?: CsvToJsonOptions
435
+ ): Promise<Record<string, any>[]>;
436
+
323
437
  /**
324
438
  * Synchronously read CSV file and convert it to JSON array
325
439
  * @param filePath Path to CSV file
@@ -334,6 +448,17 @@ declare module 'jtcsv' {
334
448
  options?: CsvToJsonOptions
335
449
  ): Record<string, any>[];
336
450
 
451
+ /**
452
+ * Synchronously read CSV file and convert it to JSON array (normalized naming alias)
453
+ * @param filePath Path to CSV file
454
+ * @param options Conversion options
455
+ * @returns JSON array
456
+ */
457
+ export function csvToJsonFileSync(
458
+ filePath: string,
459
+ options?: CsvToJsonOptions
460
+ ): Record<string, any>[];
461
+
337
462
  /**
338
463
  * Auto-detect CSV delimiter from content
339
464
  * @param csv CSV content string
@@ -451,6 +576,15 @@ declare module 'jtcsv' {
451
576
  options?: CsvToJsonStreamOptions
452
577
  ): Transform;
453
578
 
579
+ /**
580
+ * Creates a transform stream that converts CSV chunks to JSON objects (normalized naming alias)
581
+ * @param options Configuration options
582
+ * @returns Transform stream
583
+ */
584
+ export function csvToJsonStream(
585
+ options?: CsvToJsonStreamOptions
586
+ ): Transform;
587
+
454
588
  /**
455
589
  * Converts a readable stream of CSV text to JSON objects
456
590
  * @param inputStream Readable stream of CSV text
@@ -475,6 +609,17 @@ declare module 'jtcsv' {
475
609
  options?: CsvToJsonStreamOptions
476
610
  ): Promise<Readable>;
477
611
 
612
+ /**
613
+ * Reads CSV file and converts it to JSON using streaming (normalized naming alias)
614
+ * @param filePath Path to CSV file
615
+ * @param options Configuration options
616
+ * @returns Readable stream of JSON objects
617
+ */
618
+ export function csvFileToJsonStream(
619
+ filePath: string,
620
+ options?: CsvToJsonStreamOptions
621
+ ): Promise<Readable>;
622
+
478
623
  /**
479
624
  * Creates a writable stream that collects JSON objects into an array
480
625
  * @returns Writable stream that collects data
@@ -649,4 +794,28 @@ declare module 'jtcsv' {
649
794
  export function createTsvToJsonStream(
650
795
  options?: TsvOptions
651
796
  ): TransformStream;
652
- }
797
+
798
+ // Built-in validators
799
+ export function isEmail(value: string): boolean;
800
+ export function isUrl(value: string): boolean;
801
+ export function isDate(value: string | Date): boolean;
802
+ export const validators: {
803
+ isEmail: typeof isEmail;
804
+ isUrl: typeof isUrl;
805
+ isDate: typeof isDate;
806
+ };
807
+
808
+ // Batch helpers (Node.js)
809
+ export function createBatchProcessor<T, R>(
810
+ processor: (batch: T[]) => Promise<R[]> | R[],
811
+ options?: { batchSize?: number; parallelism?: number }
812
+ ): (items: T[]) => AsyncGenerator<R>;
813
+
814
+ export const asyncIterUtils: {
815
+ mapConcurrent<T, R>(
816
+ iterator: AsyncIterable<T>,
817
+ mapper: (item: T) => Promise<R> | R,
818
+ concurrency?: number
819
+ ): AsyncGenerator<R>;
820
+ batch<T>(iterator: AsyncIterable<T>, size?: number): AsyncGenerator<T[]>;
821
+ };