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.
- package/README.md +204 -115
- package/bin/jtcsv.ts +2612 -0
- package/browser.d.ts +142 -0
- package/dist/benchmark.js +446 -0
- package/dist/benchmark.js.map +1 -0
- package/dist/bin/jtcsv.js +1940 -0
- package/dist/bin/jtcsv.js.map +1 -0
- package/dist/csv-to-json.js +1262 -0
- package/dist/csv-to-json.js.map +1 -0
- package/dist/errors.js +291 -0
- package/dist/errors.js.map +1 -0
- package/dist/eslint.config.js +147 -0
- package/dist/eslint.config.js.map +1 -0
- package/dist/index-core.js +95 -0
- package/dist/index-core.js.map +1 -0
- package/dist/index.js +93 -0
- package/dist/index.js.map +1 -0
- package/dist/json-save.js +229 -0
- package/dist/json-save.js.map +1 -0
- package/dist/json-to-csv.js +576 -0
- package/dist/json-to-csv.js.map +1 -0
- package/dist/jtcsv-core.cjs.js +1736 -0
- package/dist/jtcsv-core.cjs.js.map +1 -0
- package/dist/jtcsv-core.esm.js +1708 -0
- package/dist/jtcsv-core.esm.js.map +1 -0
- package/dist/jtcsv-core.umd.js +1742 -0
- package/dist/jtcsv-core.umd.js.map +1 -0
- package/dist/jtcsv-full.cjs.js +2241 -0
- package/dist/jtcsv-full.cjs.js.map +1 -0
- package/dist/jtcsv-full.esm.js +2209 -0
- package/dist/jtcsv-full.esm.js.map +1 -0
- package/dist/jtcsv-full.umd.js +2247 -0
- package/dist/jtcsv-full.umd.js.map +1 -0
- package/dist/jtcsv-workers.esm.js +768 -0
- package/dist/jtcsv-workers.esm.js.map +1 -0
- package/dist/jtcsv-workers.umd.js +782 -0
- package/dist/jtcsv-workers.umd.js.map +1 -0
- package/dist/jtcsv.cjs.js +1996 -2048
- package/dist/jtcsv.cjs.js.map +1 -1
- package/dist/jtcsv.esm.js +1992 -2048
- package/dist/jtcsv.esm.js.map +1 -1
- package/dist/jtcsv.umd.js +2157 -2209
- package/dist/jtcsv.umd.js.map +1 -1
- package/dist/plugins/express-middleware/index.js +350 -0
- package/dist/plugins/express-middleware/index.js.map +1 -0
- package/dist/plugins/fastify-plugin/index.js +315 -0
- package/dist/plugins/fastify-plugin/index.js.map +1 -0
- package/dist/plugins/hono/index.js +111 -0
- package/dist/plugins/hono/index.js.map +1 -0
- package/dist/plugins/nestjs/index.js +112 -0
- package/dist/plugins/nestjs/index.js.map +1 -0
- package/dist/plugins/nuxt/index.js +53 -0
- package/dist/plugins/nuxt/index.js.map +1 -0
- package/dist/plugins/remix/index.js +133 -0
- package/dist/plugins/remix/index.js.map +1 -0
- package/dist/plugins/sveltekit/index.js +155 -0
- package/dist/plugins/sveltekit/index.js.map +1 -0
- package/dist/plugins/trpc/index.js +136 -0
- package/dist/plugins/trpc/index.js.map +1 -0
- package/dist/run-demo.js +49 -0
- package/dist/run-demo.js.map +1 -0
- package/dist/src/browser/browser-functions.js +193 -0
- package/dist/src/browser/browser-functions.js.map +1 -0
- package/dist/src/browser/core.js +123 -0
- package/dist/src/browser/core.js.map +1 -0
- package/dist/src/browser/csv-to-json-browser.js +353 -0
- package/dist/src/browser/csv-to-json-browser.js.map +1 -0
- package/dist/src/browser/errors-browser.js +219 -0
- package/dist/src/browser/errors-browser.js.map +1 -0
- package/dist/src/browser/extensions/plugins.js +106 -0
- package/dist/src/browser/extensions/plugins.js.map +1 -0
- package/dist/src/browser/extensions/workers.js +66 -0
- package/dist/src/browser/extensions/workers.js.map +1 -0
- package/dist/src/browser/index.js +140 -0
- package/dist/src/browser/index.js.map +1 -0
- package/dist/src/browser/json-to-csv-browser.js +225 -0
- package/dist/src/browser/json-to-csv-browser.js.map +1 -0
- package/dist/src/browser/streams.js +340 -0
- package/dist/src/browser/streams.js.map +1 -0
- package/dist/src/browser/workers/csv-parser.worker.js +264 -0
- package/dist/src/browser/workers/csv-parser.worker.js.map +1 -0
- package/dist/src/browser/workers/worker-pool.js +338 -0
- package/dist/src/browser/workers/worker-pool.js.map +1 -0
- package/dist/src/core/delimiter-cache.js +196 -0
- package/dist/src/core/delimiter-cache.js.map +1 -0
- package/dist/src/core/node-optimizations.js +279 -0
- package/dist/src/core/node-optimizations.js.map +1 -0
- package/dist/src/core/plugin-system.js +399 -0
- package/dist/src/core/plugin-system.js.map +1 -0
- package/dist/src/core/transform-hooks.js +348 -0
- package/dist/src/core/transform-hooks.js.map +1 -0
- package/dist/src/engines/fast-path-engine-new.js +262 -0
- package/dist/src/engines/fast-path-engine-new.js.map +1 -0
- package/dist/src/engines/fast-path-engine.js +671 -0
- package/dist/src/engines/fast-path-engine.js.map +1 -0
- package/dist/src/errors.js +18 -0
- package/dist/src/errors.js.map +1 -0
- package/dist/src/formats/ndjson-parser.js +332 -0
- package/dist/src/formats/ndjson-parser.js.map +1 -0
- package/dist/src/formats/tsv-parser.js +230 -0
- package/dist/src/formats/tsv-parser.js.map +1 -0
- package/dist/src/index-with-plugins.js +259 -0
- package/dist/src/index-with-plugins.js.map +1 -0
- package/dist/src/types/index.js +3 -0
- package/dist/src/types/index.js.map +1 -0
- package/dist/src/utils/bom-utils.js +267 -0
- package/dist/src/utils/bom-utils.js.map +1 -0
- package/dist/src/utils/encoding-support.js +77 -0
- package/dist/src/utils/encoding-support.js.map +1 -0
- package/dist/src/utils/schema-validator.js +609 -0
- package/dist/src/utils/schema-validator.js.map +1 -0
- package/dist/src/utils/transform-loader.js +281 -0
- package/dist/src/utils/transform-loader.js.map +1 -0
- package/dist/src/utils/validators.js +40 -0
- package/dist/src/utils/validators.js.map +1 -0
- package/dist/src/utils/zod-adapter.js +144 -0
- package/dist/src/utils/zod-adapter.js.map +1 -0
- package/dist/src/web-server/index.js +648 -0
- package/dist/src/web-server/index.js.map +1 -0
- package/dist/src/workers/csv-multithreaded.js +211 -0
- package/dist/src/workers/csv-multithreaded.js.map +1 -0
- package/dist/src/workers/csv-parser.worker.js +179 -0
- package/dist/src/workers/csv-parser.worker.js.map +1 -0
- package/dist/src/workers/worker-pool.js +228 -0
- package/dist/src/workers/worker-pool.js.map +1 -0
- package/dist/stream-csv-to-json.js +665 -0
- package/dist/stream-csv-to-json.js.map +1 -0
- package/dist/stream-json-to-csv.js +389 -0
- package/dist/stream-json-to-csv.js.map +1 -0
- package/examples/advanced/conditional-transformations.ts +446 -0
- package/examples/advanced/csv-parser.worker.ts +89 -0
- package/examples/advanced/nested-objects-example.ts +306 -0
- package/examples/advanced/performance-optimization.ts +504 -0
- package/examples/advanced/run-demo-server.ts +116 -0
- package/examples/advanced/web-worker-usage.html +874 -0
- package/examples/async-multithreaded-example.ts +335 -0
- package/examples/cli-advanced-usage.md +290 -0
- package/examples/{cli-batch-processing.js → cli-batch-processing.ts} +38 -38
- package/examples/{cli-tool.js → cli-tool.ts} +5 -8
- package/examples/{error-handling.js → error-handling.ts} +356 -324
- package/examples/{express-api.js → express-api.ts} +161 -164
- package/examples/{large-dataset-example.js → large-dataset-example.ts} +201 -182
- package/examples/{ndjson-processing.js → ndjson-processing.ts} +456 -434
- package/examples/{plugin-excel-exporter.js → plugin-excel-exporter.ts} +6 -7
- package/examples/react-integration.tsx +637 -0
- package/examples/{schema-validation.js → schema-validation.ts} +2 -2
- package/examples/simple-usage.ts +194 -0
- package/examples/{streaming-example.js → streaming-example.ts} +12 -12
- package/index.d.ts +187 -18
- package/package.json +75 -81
- package/plugins.d.ts +37 -0
- package/schema.d.ts +103 -0
- package/src/browser/browser-functions.ts +402 -0
- package/src/browser/core.ts +152 -0
- package/src/browser/csv-to-json-browser.d.ts +3 -0
- package/src/browser/csv-to-json-browser.ts +494 -0
- package/src/browser/{errors-browser.js → errors-browser.ts} +305 -197
- package/src/browser/extensions/plugins.ts +93 -0
- package/src/browser/extensions/workers.ts +39 -0
- package/src/browser/globals.d.ts +5 -0
- package/src/browser/index.ts +192 -0
- package/src/browser/json-to-csv-browser.d.ts +3 -0
- package/src/browser/json-to-csv-browser.ts +338 -0
- package/src/browser/streams.ts +403 -0
- package/src/browser/workers/{csv-parser.worker.js → csv-parser.worker.ts} +3 -3
- package/src/browser/workers/{worker-pool.js → worker-pool.ts} +51 -30
- package/src/core/delimiter-cache.ts +320 -0
- package/src/core/{node-optimizations.js → node-optimizations.ts} +448 -407
- package/src/core/plugin-system.ts +588 -0
- package/src/core/transform-hooks.ts +566 -0
- package/src/engines/{fast-path-engine-new.js → fast-path-engine-new.ts} +11 -2
- package/src/engines/{fast-path-engine.js → fast-path-engine.ts} +79 -53
- package/src/errors.ts +1 -0
- package/src/formats/{ndjson-parser.js → ndjson-parser.ts} +24 -16
- package/src/formats/{tsv-parser.js → tsv-parser.ts} +18 -17
- package/src/{index-with-plugins.js → index-with-plugins.ts} +381 -357
- package/src/types/index.ts +275 -0
- package/src/utils/bom-utils.ts +373 -0
- package/src/utils/encoding-support.ts +155 -0
- package/src/utils/{schema-validator.js → schema-validator.ts} +814 -589
- package/src/utils/transform-loader.ts +389 -0
- package/src/utils/validators.ts +35 -0
- package/src/utils/zod-adapter.ts +280 -0
- package/src/web-server/{index.js → index.ts} +19 -19
- package/src/workers/csv-multithreaded.ts +310 -0
- package/src/workers/csv-parser.worker.ts +227 -0
- package/src/workers/worker-pool.ts +409 -0
- package/bin/jtcsv.js +0 -2462
- package/csv-to-json.js +0 -688
- package/errors.js +0 -208
- package/examples/simple-usage.js +0 -282
- package/index.js +0 -68
- package/json-save.js +0 -254
- package/json-to-csv.js +0 -526
- package/plugins/README.md +0 -91
- package/plugins/express-middleware/README.md +0 -64
- package/plugins/express-middleware/example.js +0 -136
- package/plugins/express-middleware/index.d.ts +0 -114
- package/plugins/express-middleware/index.js +0 -360
- package/plugins/express-middleware/package.json +0 -52
- package/plugins/fastify-plugin/index.js +0 -406
- package/plugins/fastify-plugin/package.json +0 -55
- package/plugins/hono/README.md +0 -28
- package/plugins/hono/index.d.ts +0 -12
- package/plugins/hono/index.js +0 -36
- package/plugins/hono/package.json +0 -35
- package/plugins/nestjs/README.md +0 -35
- package/plugins/nestjs/index.d.ts +0 -25
- package/plugins/nestjs/index.js +0 -77
- package/plugins/nestjs/package.json +0 -37
- package/plugins/nextjs-api/README.md +0 -57
- package/plugins/nextjs-api/examples/ConverterComponent.jsx +0 -386
- package/plugins/nextjs-api/examples/api-convert.js +0 -69
- package/plugins/nextjs-api/index.js +0 -387
- package/plugins/nextjs-api/package.json +0 -63
- package/plugins/nextjs-api/route.js +0 -371
- package/plugins/nuxt/README.md +0 -24
- package/plugins/nuxt/index.js +0 -21
- package/plugins/nuxt/package.json +0 -35
- package/plugins/nuxt/runtime/composables/useJtcsv.js +0 -6
- package/plugins/nuxt/runtime/plugin.js +0 -6
- package/plugins/remix/README.md +0 -26
- package/plugins/remix/index.d.ts +0 -16
- package/plugins/remix/index.js +0 -62
- package/plugins/remix/package.json +0 -35
- package/plugins/sveltekit/README.md +0 -28
- package/plugins/sveltekit/index.d.ts +0 -17
- package/plugins/sveltekit/index.js +0 -54
- package/plugins/sveltekit/package.json +0 -33
- package/plugins/trpc/README.md +0 -25
- package/plugins/trpc/index.d.ts +0 -7
- package/plugins/trpc/index.js +0 -32
- package/plugins/trpc/package.json +0 -34
- package/src/browser/browser-functions.js +0 -219
- package/src/browser/csv-to-json-browser.js +0 -700
- package/src/browser/index.js +0 -113
- package/src/browser/json-to-csv-browser.js +0 -309
- package/src/browser/streams.js +0 -393
- package/src/core/delimiter-cache.js +0 -186
- package/src/core/plugin-system.js +0 -476
- package/src/core/transform-hooks.js +0 -350
- package/src/errors.js +0 -26
- package/src/utils/transform-loader.js +0 -205
- package/stream-csv-to-json.js +0 -542
- package/stream-json-to-csv.js +0 -464
- /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
|
-
|
|
11
|
-
|
|
12
|
-
const {
|
|
13
|
-
|
|
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
|
|
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 =
|
|
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 (
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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:
|
|
200
|
-
actual:
|
|
201
|
-
constructor(message: string, limit:
|
|
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
|
+
};
|