1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | exports.transformMap = exports.notNullishPredicate = void 0;
|
4 | const js_lib_1 = require("@naturalcycles/js-lib");
|
5 | const through2Concurrent = require("through2-concurrent");
|
6 | const colors_1 = require("../../colors");
|
7 | function notNullishPredicate(item) {
|
8 | return item !== undefined && item !== null;
|
9 | }
|
10 | exports.notNullishPredicate = notNullishPredicate;
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 | function transformMap(mapper, opt = {}) {
|
24 | const { concurrency = 16, predicate = notNullishPredicate, errorMode = js_lib_1.ErrorMode.THROW_IMMEDIATELY, flattenArrayOutput, onError, beforeFinal, metric = 'stream', } = opt;
|
25 | let index = -1;
|
26 | let isRejected = false;
|
27 | let errors = 0;
|
28 | const collectedErrors = [];
|
29 | return through2Concurrent.obj({
|
30 | maxConcurrency: concurrency,
|
31 |
|
32 | async final(cb) {
|
33 |
|
34 | logErrorStats(true);
|
35 | await beforeFinal?.();
|
36 | if (collectedErrors.length) {
|
37 |
|
38 | cb(new js_lib_1.AggregatedError(collectedErrors));
|
39 | }
|
40 | else {
|
41 |
|
42 | cb();
|
43 | }
|
44 | },
|
45 | }, async function transformMapFn(chunk, _encoding, cb) {
|
46 | index++;
|
47 |
|
48 |
|
49 | if (isRejected && errorMode === js_lib_1.ErrorMode.THROW_IMMEDIATELY)
|
50 | return cb();
|
51 | try {
|
52 | const currentIndex = index;
|
53 | const res = await mapper(chunk, currentIndex);
|
54 | const passedResults = await (0, js_lib_1.pFilter)(flattenArrayOutput && Array.isArray(res) ? res : [res], async (r) => await predicate(r, currentIndex));
|
55 | if (passedResults.length === 0) {
|
56 | cb();
|
57 | }
|
58 | else {
|
59 | passedResults.forEach(r => {
|
60 | this.push(r);
|
61 |
|
62 | });
|
63 | cb();
|
64 | }
|
65 | }
|
66 | catch (err) {
|
67 | console.error(err);
|
68 | errors++;
|
69 | logErrorStats();
|
70 | if (onError) {
|
71 | try {
|
72 | onError(err, chunk);
|
73 | }
|
74 | catch { }
|
75 | }
|
76 | if (errorMode === js_lib_1.ErrorMode.THROW_IMMEDIATELY) {
|
77 | isRejected = true;
|
78 |
|
79 | return cb(err);
|
80 | }
|
81 | if (errorMode === js_lib_1.ErrorMode.THROW_AGGREGATED) {
|
82 | collectedErrors.push(err);
|
83 | }
|
84 |
|
85 | cb();
|
86 | }
|
87 | });
|
88 | function logErrorStats(final = false) {
|
89 | if (!errors)
|
90 | return;
|
91 | console.log(`${metric} ${final ? 'final ' : ''}errors: ${(0, colors_1.yellow)(errors)}`);
|
92 | }
|
93 | }
|
94 | exports.transformMap = transformMap;
|