tty-table 5.0.0 → 6.0.1

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/dist/cli.js ADDED
@@ -0,0 +1,1052 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __commonJS = (cb, mod) => function __require() {
10
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+
29
+ // node_modules/clone/clone.js
30
+ var require_clone = __commonJS({
31
+ "node_modules/clone/clone.js"(exports2, module2) {
32
+ "use strict";
33
+ var clone = (function() {
34
+ "use strict";
35
+ function clone2(parent, circular, depth, prototype) {
36
+ var filter;
37
+ if (typeof circular === "object") {
38
+ depth = circular.depth;
39
+ prototype = circular.prototype;
40
+ filter = circular.filter;
41
+ circular = circular.circular;
42
+ }
43
+ var allParents = [];
44
+ var allChildren = [];
45
+ var useBuffer = typeof Buffer != "undefined";
46
+ if (typeof circular == "undefined")
47
+ circular = true;
48
+ if (typeof depth == "undefined")
49
+ depth = Infinity;
50
+ function _clone(parent2, depth2) {
51
+ if (parent2 === null)
52
+ return null;
53
+ if (depth2 == 0)
54
+ return parent2;
55
+ var child;
56
+ var proto;
57
+ if (typeof parent2 != "object") {
58
+ return parent2;
59
+ }
60
+ if (clone2.__isArray(parent2)) {
61
+ child = [];
62
+ } else if (clone2.__isRegExp(parent2)) {
63
+ child = new RegExp(parent2.source, __getRegExpFlags(parent2));
64
+ if (parent2.lastIndex) child.lastIndex = parent2.lastIndex;
65
+ } else if (clone2.__isDate(parent2)) {
66
+ child = new Date(parent2.getTime());
67
+ } else if (useBuffer && Buffer.isBuffer(parent2)) {
68
+ if (Buffer.allocUnsafe) {
69
+ child = Buffer.allocUnsafe(parent2.length);
70
+ } else {
71
+ child = new Buffer(parent2.length);
72
+ }
73
+ parent2.copy(child);
74
+ return child;
75
+ } else {
76
+ if (typeof prototype == "undefined") {
77
+ proto = Object.getPrototypeOf(parent2);
78
+ child = Object.create(proto);
79
+ } else {
80
+ child = Object.create(prototype);
81
+ proto = prototype;
82
+ }
83
+ }
84
+ if (circular) {
85
+ var index = allParents.indexOf(parent2);
86
+ if (index != -1) {
87
+ return allChildren[index];
88
+ }
89
+ allParents.push(parent2);
90
+ allChildren.push(child);
91
+ }
92
+ for (var i in parent2) {
93
+ var attrs;
94
+ if (proto) {
95
+ attrs = Object.getOwnPropertyDescriptor(proto, i);
96
+ }
97
+ if (attrs && attrs.set == null) {
98
+ continue;
99
+ }
100
+ child[i] = _clone(parent2[i], depth2 - 1);
101
+ }
102
+ return child;
103
+ }
104
+ return _clone(parent, depth);
105
+ }
106
+ clone2.clonePrototype = function clonePrototype(parent) {
107
+ if (parent === null)
108
+ return null;
109
+ var c = function() {
110
+ };
111
+ c.prototype = parent;
112
+ return new c();
113
+ };
114
+ function __objToStr(o) {
115
+ return Object.prototype.toString.call(o);
116
+ }
117
+ ;
118
+ clone2.__objToStr = __objToStr;
119
+ function __isDate(o) {
120
+ return typeof o === "object" && __objToStr(o) === "[object Date]";
121
+ }
122
+ ;
123
+ clone2.__isDate = __isDate;
124
+ function __isArray(o) {
125
+ return typeof o === "object" && __objToStr(o) === "[object Array]";
126
+ }
127
+ ;
128
+ clone2.__isArray = __isArray;
129
+ function __isRegExp(o) {
130
+ return typeof o === "object" && __objToStr(o) === "[object RegExp]";
131
+ }
132
+ ;
133
+ clone2.__isRegExp = __isRegExp;
134
+ function __getRegExpFlags(re) {
135
+ var flags = "";
136
+ if (re.global) flags += "g";
137
+ if (re.ignoreCase) flags += "i";
138
+ if (re.multiline) flags += "m";
139
+ return flags;
140
+ }
141
+ ;
142
+ clone2.__getRegExpFlags = __getRegExpFlags;
143
+ return clone2;
144
+ })();
145
+ if (typeof module2 === "object" && module2.exports) {
146
+ module2.exports = clone;
147
+ }
148
+ }
149
+ });
150
+
151
+ // node_modules/defaults/index.js
152
+ var require_defaults = __commonJS({
153
+ "node_modules/defaults/index.js"(exports2, module2) {
154
+ "use strict";
155
+ var clone = require_clone();
156
+ module2.exports = function(options, defaults2) {
157
+ options = options || {};
158
+ Object.keys(defaults2).forEach(function(key) {
159
+ if (typeof options[key] === "undefined") {
160
+ options[key] = clone(defaults2[key]);
161
+ }
162
+ });
163
+ return options;
164
+ };
165
+ }
166
+ });
167
+
168
+ // node_modules/wcwidth/combining.js
169
+ var require_combining = __commonJS({
170
+ "node_modules/wcwidth/combining.js"(exports2, module2) {
171
+ "use strict";
172
+ module2.exports = [
173
+ [768, 879],
174
+ [1155, 1158],
175
+ [1160, 1161],
176
+ [1425, 1469],
177
+ [1471, 1471],
178
+ [1473, 1474],
179
+ [1476, 1477],
180
+ [1479, 1479],
181
+ [1536, 1539],
182
+ [1552, 1557],
183
+ [1611, 1630],
184
+ [1648, 1648],
185
+ [1750, 1764],
186
+ [1767, 1768],
187
+ [1770, 1773],
188
+ [1807, 1807],
189
+ [1809, 1809],
190
+ [1840, 1866],
191
+ [1958, 1968],
192
+ [2027, 2035],
193
+ [2305, 2306],
194
+ [2364, 2364],
195
+ [2369, 2376],
196
+ [2381, 2381],
197
+ [2385, 2388],
198
+ [2402, 2403],
199
+ [2433, 2433],
200
+ [2492, 2492],
201
+ [2497, 2500],
202
+ [2509, 2509],
203
+ [2530, 2531],
204
+ [2561, 2562],
205
+ [2620, 2620],
206
+ [2625, 2626],
207
+ [2631, 2632],
208
+ [2635, 2637],
209
+ [2672, 2673],
210
+ [2689, 2690],
211
+ [2748, 2748],
212
+ [2753, 2757],
213
+ [2759, 2760],
214
+ [2765, 2765],
215
+ [2786, 2787],
216
+ [2817, 2817],
217
+ [2876, 2876],
218
+ [2879, 2879],
219
+ [2881, 2883],
220
+ [2893, 2893],
221
+ [2902, 2902],
222
+ [2946, 2946],
223
+ [3008, 3008],
224
+ [3021, 3021],
225
+ [3134, 3136],
226
+ [3142, 3144],
227
+ [3146, 3149],
228
+ [3157, 3158],
229
+ [3260, 3260],
230
+ [3263, 3263],
231
+ [3270, 3270],
232
+ [3276, 3277],
233
+ [3298, 3299],
234
+ [3393, 3395],
235
+ [3405, 3405],
236
+ [3530, 3530],
237
+ [3538, 3540],
238
+ [3542, 3542],
239
+ [3633, 3633],
240
+ [3636, 3642],
241
+ [3655, 3662],
242
+ [3761, 3761],
243
+ [3764, 3769],
244
+ [3771, 3772],
245
+ [3784, 3789],
246
+ [3864, 3865],
247
+ [3893, 3893],
248
+ [3895, 3895],
249
+ [3897, 3897],
250
+ [3953, 3966],
251
+ [3968, 3972],
252
+ [3974, 3975],
253
+ [3984, 3991],
254
+ [3993, 4028],
255
+ [4038, 4038],
256
+ [4141, 4144],
257
+ [4146, 4146],
258
+ [4150, 4151],
259
+ [4153, 4153],
260
+ [4184, 4185],
261
+ [4448, 4607],
262
+ [4959, 4959],
263
+ [5906, 5908],
264
+ [5938, 5940],
265
+ [5970, 5971],
266
+ [6002, 6003],
267
+ [6068, 6069],
268
+ [6071, 6077],
269
+ [6086, 6086],
270
+ [6089, 6099],
271
+ [6109, 6109],
272
+ [6155, 6157],
273
+ [6313, 6313],
274
+ [6432, 6434],
275
+ [6439, 6440],
276
+ [6450, 6450],
277
+ [6457, 6459],
278
+ [6679, 6680],
279
+ [6912, 6915],
280
+ [6964, 6964],
281
+ [6966, 6970],
282
+ [6972, 6972],
283
+ [6978, 6978],
284
+ [7019, 7027],
285
+ [7616, 7626],
286
+ [7678, 7679],
287
+ [8203, 8207],
288
+ [8234, 8238],
289
+ [8288, 8291],
290
+ [8298, 8303],
291
+ [8400, 8431],
292
+ [12330, 12335],
293
+ [12441, 12442],
294
+ [43014, 43014],
295
+ [43019, 43019],
296
+ [43045, 43046],
297
+ [64286, 64286],
298
+ [65024, 65039],
299
+ [65056, 65059],
300
+ [65279, 65279],
301
+ [65529, 65531],
302
+ [68097, 68099],
303
+ [68101, 68102],
304
+ [68108, 68111],
305
+ [68152, 68154],
306
+ [68159, 68159],
307
+ [119143, 119145],
308
+ [119155, 119170],
309
+ [119173, 119179],
310
+ [119210, 119213],
311
+ [119362, 119364],
312
+ [917505, 917505],
313
+ [917536, 917631],
314
+ [917760, 917999]
315
+ ];
316
+ }
317
+ });
318
+
319
+ // node_modules/wcwidth/index.js
320
+ var require_wcwidth = __commonJS({
321
+ "node_modules/wcwidth/index.js"(exports2, module2) {
322
+ "use strict";
323
+ var defaults2 = require_defaults();
324
+ var combining = require_combining();
325
+ var DEFAULTS = {
326
+ nul: 0,
327
+ control: 0
328
+ };
329
+ module2.exports = function wcwidth3(str) {
330
+ return wcswidth(str, DEFAULTS);
331
+ };
332
+ module2.exports.config = function(opts) {
333
+ opts = defaults2(opts || {}, DEFAULTS);
334
+ return function wcwidth3(str) {
335
+ return wcswidth(str, opts);
336
+ };
337
+ };
338
+ function wcswidth(str, opts) {
339
+ if (typeof str !== "string") return wcwidth2(str, opts);
340
+ var s = 0;
341
+ for (var i = 0; i < str.length; i++) {
342
+ var n = wcwidth2(str.charCodeAt(i), opts);
343
+ if (n < 0) return -1;
344
+ s += n;
345
+ }
346
+ return s;
347
+ }
348
+ function wcwidth2(ucs, opts) {
349
+ if (ucs === 0) return opts.nul;
350
+ if (ucs < 32 || ucs >= 127 && ucs < 160) return opts.control;
351
+ if (bisearch(ucs)) return 0;
352
+ return 1 + (ucs >= 4352 && (ucs <= 4447 || // Hangul Jamo init. consonants
353
+ ucs == 9001 || ucs == 9002 || ucs >= 11904 && ucs <= 42191 && ucs != 12351 || // CJK ... Yi
354
+ ucs >= 44032 && ucs <= 55203 || // Hangul Syllables
355
+ ucs >= 63744 && ucs <= 64255 || // CJK Compatibility Ideographs
356
+ ucs >= 65040 && ucs <= 65049 || // Vertical forms
357
+ ucs >= 65072 && ucs <= 65135 || // CJK Compatibility Forms
358
+ ucs >= 65280 && ucs <= 65376 || // Fullwidth Forms
359
+ ucs >= 65504 && ucs <= 65510 || ucs >= 131072 && ucs <= 196605 || ucs >= 196608 && ucs <= 262141));
360
+ }
361
+ function bisearch(ucs) {
362
+ var min = 0;
363
+ var max = combining.length - 1;
364
+ var mid;
365
+ if (ucs < combining[0][0] || ucs > combining[max][1]) return false;
366
+ while (max >= min) {
367
+ mid = Math.floor((min + max) / 2);
368
+ if (ucs > combining[mid][1]) min = mid + 1;
369
+ else if (ucs < combining[mid][0]) max = mid - 1;
370
+ else return true;
371
+ }
372
+ return false;
373
+ }
374
+ }
375
+ });
376
+
377
+ // src/cli.ts
378
+ var import_node_fs = __toESM(require("fs"));
379
+ var import_node_path = __toESM(require("path"));
380
+ var import_csv = require("csv");
381
+ var import_yargs = __toESM(require("yargs"));
382
+ var import_helpers = require("yargs/helpers");
383
+
384
+ // src/defaults.ts
385
+ var defaults = {
386
+ borderCharacters: {
387
+ invisible: [
388
+ { v: " ", l: " ", j: " ", h: " ", r: " " },
389
+ { v: " ", l: " ", j: " ", h: " ", r: " " },
390
+ { v: " ", l: " ", j: " ", h: " ", r: " " }
391
+ ],
392
+ solid: [
393
+ { v: "\u2502", l: "\u250C", j: "\u252C", h: "\u2500", r: "\u2510" },
394
+ { v: "\u2502", l: "\u251C", j: "\u253C", h: "\u2500", r: "\u2524" },
395
+ { v: "\u2502", l: "\u2514", j: "\u2534", h: "\u2500", r: "\u2518" }
396
+ ],
397
+ dashed: [
398
+ { v: "|", l: "+", j: "+", h: "-", r: "+" },
399
+ { v: "|", l: "+", j: "+", h: "-", r: "+" },
400
+ { v: "|", l: "+", j: "+", h: "-", r: "+" }
401
+ ],
402
+ none: [
403
+ { v: "", l: "", j: "", h: "", r: "" },
404
+ { v: "", l: "", j: "", h: "", r: "" },
405
+ { v: "", l: "", j: "", h: "", r: "" }
406
+ ]
407
+ },
408
+ align: "center",
409
+ borderColor: null,
410
+ borderStyle: "solid",
411
+ color: false,
412
+ COLUMNS: 80,
413
+ // if !process.stdout.columns assume redirecting to write stream 80 columns is VT200 standard
414
+ compact: false,
415
+ defaultErrorValue: "\uFFFD",
416
+ defaultValue: "",
417
+ errorOnNull: false,
418
+ FIXED_WIDTH: false,
419
+ footerAlign: "center",
420
+ footerColor: false,
421
+ formatter: null,
422
+ headerAlign: "center",
423
+ headerColor: "yellow",
424
+ isNull: false,
425
+ // undocumented cell setting
426
+ marginLeft: 2,
427
+ marginTop: 1,
428
+ paddingBottom: 0,
429
+ paddingLeft: 1,
430
+ paddingRight: 1,
431
+ paddingTop: 0,
432
+ showHeader: null,
433
+ // undocumented
434
+ truncate: false,
435
+ width: "100%",
436
+ GUTTER: 1,
437
+ // undocumented
438
+ columnSettings: [],
439
+ // save so cell options can be merged into column options
440
+ table: {
441
+ body: "",
442
+ columnInnerWidths: [],
443
+ columnWidths: [],
444
+ columns: [],
445
+ footer: "",
446
+ header: "",
447
+ // post-rendered strings.
448
+ height: 0,
449
+ typeLocked: false
450
+ // once a table type is selected can't switch
451
+ }
452
+ };
453
+ defaults.borderCharacters["0"] = defaults.borderCharacters.none;
454
+ defaults.borderCharacters["1"] = defaults.borderCharacters.solid;
455
+ defaults.borderCharacters["2"] = defaults.borderCharacters.dashed;
456
+ var defaults_default = defaults;
457
+
458
+ // src/style.ts
459
+ var import_chalk = __toESM(require("chalk"));
460
+ var import_kleur = __toESM(require("kleur"));
461
+ var import_strip_ansi = __toESM(require("strip-ansi"));
462
+ var colorLib = process && process.stdout ? import_chalk.default : import_kleur.default;
463
+ var style = (str, ...colors) => {
464
+ const out = colors.reduce(function(input, color) {
465
+ return colorLib[color](input);
466
+ }, str);
467
+ return out;
468
+ };
469
+ var styleEachChar = (str, ...colors) => {
470
+ const chars = [...(0, import_strip_ansi.default)(str)];
471
+ const out = chars.reduce((prev, current) => {
472
+ const coded = colors.reduce((input, color) => {
473
+ return colorLib[color](input);
474
+ }, current);
475
+ return prev + coded;
476
+ }, "");
477
+ return out;
478
+ };
479
+ var resetStyle = function(str) {
480
+ this.configure({ reset: true });
481
+ return (0, import_strip_ansi.default)(str);
482
+ };
483
+ var colorizeCell = (str, cellOptions, rowType) => {
484
+ let color = false;
485
+ switch (true) {
486
+ case rowType === "body":
487
+ color = cellOptions.color || color;
488
+ break;
489
+ case rowType === "header":
490
+ color = cellOptions.headerColor || color;
491
+ break;
492
+ default:
493
+ color = cellOptions.footerColor || color;
494
+ }
495
+ if (color) {
496
+ str = style(str, color);
497
+ }
498
+ return str;
499
+ };
500
+ var isColorEnabled = () => {
501
+ return process && process.stdout ? colorLib.level > 0 : colorLib.enabled;
502
+ };
503
+
504
+ // src/format.ts
505
+ var import_strip_ansi2 = __toESM(require("strip-ansi"));
506
+ var import_smartwrap = __toESM(require("smartwrap"));
507
+ var import_wcwidth = __toESM(require_wcwidth());
508
+ var addPadding = (config, width) => {
509
+ return width + config.paddingLeft + config.paddingRight;
510
+ };
511
+ var getDisplayWidth = (value) => {
512
+ const lines = (0, import_strip_ansi2.default)(value.toString()).split(/[\n\r]/);
513
+ let widest = 0;
514
+ for (const line of lines) {
515
+ const width = (0, import_wcwidth.default)(line);
516
+ if (width > widest) widest = width;
517
+ }
518
+ return widest;
519
+ };
520
+ var getMaxLength = (columnOptions, rows, columnIndex) => {
521
+ let widest = 0;
522
+ if (columnOptions && (columnOptions.value || columnOptions.alias)) {
523
+ const value = columnOptions.alias || columnOptions.value;
524
+ widest = getDisplayWidth(value);
525
+ }
526
+ for (const row of rows) {
527
+ if (row[columnIndex]) {
528
+ const value = row[columnIndex].value ? row[columnIndex].value : row[columnIndex];
529
+ const width = getDisplayWidth(value);
530
+ if (width > widest) widest = width;
531
+ }
532
+ }
533
+ return widest;
534
+ };
535
+ var getAvailableWidth = (config) => {
536
+ if (process && (process.stdout && process.stdout.columns || process.env && process.env.COLUMNS)) {
537
+ let viewport = process.stdout && process.stdout.columns ? process.stdout.columns : process.env.COLUMNS;
538
+ viewport = viewport - config.marginLeft;
539
+ if (config.width !== "auto" && /^\d+%$/.test(config.width)) {
540
+ return Math.min(1, config.width.slice(0, -1) * 0.01) * viewport;
541
+ }
542
+ if (config.width !== "auto" && /^\d+$/.test(config.width)) {
543
+ config.FIXED_WIDTH = true;
544
+ return config.width;
545
+ }
546
+ return viewport;
547
+ }
548
+ if (typeof globalThis.window !== "undefined") return globalThis.window.innerWidth;
549
+ return config.COLUMNS - config.marginLeft;
550
+ };
551
+ var getStringLength = (str) => {
552
+ return (0, import_wcwidth.default)((0, import_strip_ansi2.default)(str));
553
+ };
554
+ var wrapCellText = (config, cellValue, columnIndex, cellOptions, rowType) => {
555
+ const startAnsiRegexp = /^(\x1b\[[0-9;]*m)+/;
556
+ const endAnsiRegexp = /(\x1b\[[0-9;]*m)+$/;
557
+ let str = cellValue.toString();
558
+ const startMatches = str.match(startAnsiRegexp) || [""];
559
+ str = str.replace(startAnsiRegexp, "");
560
+ const endMatches = str.match(endAnsiRegexp) || [""];
561
+ str = str.replace(endAnsiRegexp, "");
562
+ let alignTgt;
563
+ switch (rowType) {
564
+ case "header":
565
+ alignTgt = "headerAlign";
566
+ break;
567
+ case "body":
568
+ alignTgt = "align";
569
+ break;
570
+ default:
571
+ alignTgt = "footerAlign";
572
+ }
573
+ if (cellOptions[alignTgt] === "center") {
574
+ cellOptions.paddingLeft = cellOptions.paddingRight = Math.max(
575
+ cellOptions.paddingRight,
576
+ cellOptions.paddingLeft,
577
+ 0
578
+ );
579
+ }
580
+ const columnWidth = config.table.columnWidths[columnIndex];
581
+ const innerWidth = columnWidth - cellOptions.paddingLeft - cellOptions.paddingRight - config.GUTTER;
582
+ if (typeof config.truncate === "string") {
583
+ str = truncate(str, cellOptions, innerWidth);
584
+ } else {
585
+ str = wrap(str, cellOptions, innerWidth);
586
+ }
587
+ const cell = str.split("\n").map((line) => {
588
+ line = line.trim();
589
+ const lineLength = getStringLength(line);
590
+ if (lineLength < columnWidth) {
591
+ let emptySpace = columnWidth - lineLength;
592
+ switch (true) {
593
+ case cellOptions[alignTgt] === "center":
594
+ emptySpace--;
595
+ const padBoth = Math.floor(emptySpace / 2);
596
+ const padRemainder = emptySpace % 2;
597
+ line = " ".repeat(padBoth) + line + " ".repeat(padBoth + padRemainder);
598
+ break;
599
+ case cellOptions[alignTgt] === "right":
600
+ line = " ".repeat(emptySpace - cellOptions.paddingRight - 1) + line + " ".repeat(cellOptions.paddingRight);
601
+ break;
602
+ default:
603
+ line = " ".repeat(cellOptions.paddingLeft) + line + " ".repeat(emptySpace - cellOptions.paddingLeft - 1);
604
+ }
605
+ }
606
+ return startMatches[0] + line + endMatches[0];
607
+ });
608
+ return { cell, innerWidth };
609
+ };
610
+ var truncate = (str, cellOptions, maxWidth) => {
611
+ const stringWidth = (0, import_wcwidth.default)(str);
612
+ if (maxWidth < stringWidth) {
613
+ str = (0, import_smartwrap.default)(str, {
614
+ width: maxWidth - cellOptions.truncate.length,
615
+ breakword: true
616
+ }).split("\n")[0];
617
+ str = str + cellOptions.truncate;
618
+ }
619
+ return str;
620
+ };
621
+ var wrap = (str, cellOptions, innerWidth) => {
622
+ const outstring = (0, import_smartwrap.default)(str, {
623
+ errorChar: cellOptions.defaultErrorValue,
624
+ minWidth: 1,
625
+ trim: true,
626
+ width: innerWidth
627
+ });
628
+ return outstring;
629
+ };
630
+ var getColumnWidths = (config, rows) => {
631
+ const availableWidth = getAvailableWidth(config);
632
+ const iterable = config.table.header[0] && config.table.header[0].length > 0 ? config.table.header[0] : rows[0];
633
+ let widths = iterable.map((column, columnIndex) => {
634
+ let result;
635
+ switch (true) {
636
+ // column width is a percentage of table width specified in column header
637
+ case (typeof column === "object" && /^\d+%$/.test(column.width)):
638
+ result = column.width.slice(0, -1) * 0.01 * availableWidth;
639
+ result = addPadding(config, result);
640
+ break;
641
+ // column width is specified in column header
642
+ case (typeof column === "object" && /^\d+$/.test(column.width)):
643
+ result = column.width;
644
+ break;
645
+ // 'auto' sets column width to its longest value in the initial data set
646
+ default: {
647
+ const columnOptions = config.table.header[0][columnIndex] ? config.table.header[0][columnIndex] : {};
648
+ const measurableRows = rows.length ? rows : config.table.header[0];
649
+ result = getMaxLength(columnOptions, measurableRows, columnIndex);
650
+ result = addPadding(config, result);
651
+ }
652
+ }
653
+ result = result + config.GUTTER;
654
+ return result;
655
+ });
656
+ const totalWidth = widths.reduce((prev, current) => prev + current);
657
+ if (totalWidth > availableWidth || config.FIXED_WIDTH) {
658
+ const proportion = (availableWidth / totalWidth).toFixed(2) - 0.01;
659
+ const relativeWidths = widths.map((value) => Math.max(2, Math.floor(proportion * value)));
660
+ if (config.FIXED_WIDTH) return relativeWidths;
661
+ if (proportion > 0) {
662
+ const totalRelativeWidths = relativeWidths.reduce((prev, current) => prev + current);
663
+ widths = totalRelativeWidths < totalWidth ? relativeWidths : widths;
664
+ }
665
+ } else {
666
+ widths = widths.map(Math.floor);
667
+ }
668
+ return widths;
669
+ };
670
+
671
+ // src/render.ts
672
+ var import_strip_ansi3 = __toESM(require("strip-ansi"));
673
+ var stringifyData = (config, inputData) => {
674
+ const sections = { header: [], body: [], footer: [] };
675
+ const marginLeft = " ".repeat(config.marginLeft);
676
+ const borderStyle = config.borderCharacters[config.borderStyle];
677
+ const borders = [];
678
+ const constructorType = getConstructorGeometry(inputData[0] || [], config);
679
+ const rows = coerceConstructorGeometry(config, inputData, constructorType);
680
+ if (!global.columnWidths) global.columnWidths = {};
681
+ if (global.columnWidths[config.tableId]) {
682
+ config.table.columnWidths = global.columnWidths[config.tableId];
683
+ } else {
684
+ const formattedRows = rows.map((row, rowIndex) => {
685
+ return row.map((cell, cellIndex) => buildCell(config, cell, cellIndex, "body", rowIndex, rows, inputData, true));
686
+ });
687
+ global.columnWidths[config.tableId] = config.table.columnWidths = getColumnWidths(config, formattedRows);
688
+ }
689
+ switch (true) {
690
+ case (config.showHeader !== null && !config.showHeader):
691
+ sections.header = [];
692
+ break;
693
+ case config.showHeader === true:
694
+ case !!config.table.header[0].find((obj) => obj.value || obj.alias):
695
+ sections.header = config.table.header.map((row) => buildRow(config, row, "header", null, rows, inputData));
696
+ break;
697
+ default:
698
+ sections.header = [];
699
+ }
700
+ sections.body = rows.map((row, rowIndex) => buildRow(config, row, "body", rowIndex, rows, inputData));
701
+ sections.footer = config.table.footer instanceof Array && config.table.footer.length > 0 ? [config.table.footer] : [];
702
+ sections.footer = sections.footer.map((row) => buildRow(config, row, "footer", null, rows, inputData));
703
+ for (let a = 0; a < 3; a++) {
704
+ borders[a] = borderStyle[a].l;
705
+ config.table.columnWidths.forEach((columnWidth, index, arr) => {
706
+ borders[a] += borderStyle[a].h.repeat(Math.max(columnWidth, 2) - 1);
707
+ borders[a] += index + 1 < arr.length ? borderStyle[a].j : "";
708
+ });
709
+ borders[a] += borderStyle[a].r;
710
+ borders[a] = a < 2 ? `${marginLeft + borders[a]}
711
+ ` : marginLeft + borders[a];
712
+ }
713
+ const output = [borders[0]];
714
+ for (const [sectionIndex, sectionName] of Object.keys(sections).entries()) {
715
+ const section = sections[sectionName];
716
+ for (let rowIndex = 0; rowIndex < section.length; rowIndex++) {
717
+ const row = section[rowIndex];
718
+ row.forEach((line) => {
719
+ output.push(marginLeft + borderStyle[1].v + line.join(borderStyle[1].v) + borderStyle[1].v + "\n");
720
+ });
721
+ switch (true) {
722
+ case (rowIndex === section.length - 1 && sectionIndex === 1 && sections.footer.length === 0):
723
+ break;
724
+ case (rowIndex === section.length - 1 && sectionIndex === 2):
725
+ break;
726
+ case (config.compact && sectionName === "body" && !row.empty):
727
+ break;
728
+ case (config.borderStyle === "none" && config.compact):
729
+ break;
730
+ default:
731
+ output.push(borders[1]);
732
+ }
733
+ }
734
+ }
735
+ output.push(borders[2]);
736
+ const finalOutput = "\n".repeat(config.marginTop) + output.join("");
737
+ config.height = finalOutput.split(/\r\n|\r|\n/).length;
738
+ return finalOutput;
739
+ };
740
+ var buildRow = (config, row, rowType, rowIndex, rowData, inputData) => {
741
+ let minRowHeight = 0;
742
+ if (row.length === 0 && config.compact) {
743
+ row.empty = true;
744
+ return row;
745
+ }
746
+ const lengthDifference = config.table.columnWidths.length - row.length;
747
+ if (lengthDifference > 0) row = row.concat(Array.apply(null, new Array(lengthDifference)).map(() => null));
748
+ else if (lengthDifference < 0) row.length = config.table.columnWidths.length;
749
+ row = row.map((elem, elemIndex) => {
750
+ const cell = buildCell(config, elem, elemIndex, rowType, rowIndex, rowData, inputData);
751
+ minRowHeight = minRowHeight < cell.length ? cell.length : minRowHeight;
752
+ return cell;
753
+ });
754
+ minRowHeight = rowType === "header" ? minRowHeight : minRowHeight + (config.paddingBottom + config.paddingTop);
755
+ const linedRow = Array.apply(null, { length: minRowHeight }).map(Function.call, () => []);
756
+ row.forEach(function(cell, a) {
757
+ const whitespace = " ".repeat(Math.max(config.table.columnWidths[a] - 1, 0));
758
+ if (rowType === "body") {
759
+ for (let i = 0; i < config.paddingTop; i++) cell.unshift(whitespace);
760
+ for (let i = 0; i < config.paddingBottom; i++) cell.push(whitespace);
761
+ }
762
+ for (let i = 0; i < minRowHeight; i++) linedRow[i].push(typeof cell[i] !== "undefined" ? cell[i] : whitespace);
763
+ });
764
+ return linedRow;
765
+ };
766
+ var buildCell = (config, elem, columnIndex, rowType, rowIndex, rowData, inputData, dryRun = false) => {
767
+ let cellValue = null;
768
+ const cellOptions = Object.assign(
769
+ { reset: false },
770
+ config,
771
+ rowType !== "header" ? config.columnSettings[columnIndex] : {},
772
+ typeof elem === "object" ? elem : {}
773
+ );
774
+ if (rowType === "header") {
775
+ config.table.columns.push(cellOptions);
776
+ cellValue = cellOptions.alias || cellOptions.value || "";
777
+ } else {
778
+ switch (true) {
779
+ case (typeof elem === "undefined" || elem === null):
780
+ cellValue = config.errorOnNull ? config.defaultErrorValue : config.defaultValue;
781
+ if (!isColorEnabled()) cellValue = (0, import_strip_ansi3.default)(cellValue);
782
+ cellOptions.isNull = true;
783
+ break;
784
+ case (typeof elem === "object" && elem !== null && typeof elem.value !== "undefined"):
785
+ cellValue = elem.value;
786
+ break;
787
+ case typeof elem === "function":
788
+ cellValue = elem.bind({
789
+ configure: function(object) {
790
+ return Object.assign(cellOptions, object);
791
+ },
792
+ style,
793
+ resetStyle
794
+ })(cellValue, columnIndex, rowIndex, rowData, inputData);
795
+ break;
796
+ default:
797
+ cellValue = elem;
798
+ }
799
+ if (rowType === "body" && typeof cellOptions.formatter === "function") {
800
+ cellValue = cellOptions.formatter.bind({
801
+ configure: function(object) {
802
+ return Object.assign(cellOptions, object);
803
+ },
804
+ style,
805
+ resetStyle
806
+ })(cellValue, columnIndex, rowIndex, rowData, inputData);
807
+ }
808
+ if (dryRun) return cellValue;
809
+ }
810
+ if (!cellOptions.reset) cellValue = colorizeCell(cellValue, cellOptions, rowType);
811
+ const { cell, innerWidth } = wrapCellText(cellOptions, cellValue, columnIndex, cellOptions, rowType);
812
+ if (rowType === "header") config.table.columnInnerWidths.push(innerWidth);
813
+ return cell;
814
+ };
815
+ var getConstructorGeometry = (row, config) => {
816
+ let type;
817
+ if (typeof row === "object" && !(row instanceof Array)) {
818
+ const keys = Object.keys(row);
819
+ if (config.adapter === "automattic") {
820
+ const key = keys[0];
821
+ type = row[key] instanceof Array ? "automattic-cross" : "automattic-vertical";
822
+ } else type = "o-horizontal";
823
+ } else type = "a-horizontal";
824
+ return type;
825
+ };
826
+ var coerceConstructorGeometry = (config, rows, constructorType) => {
827
+ let output = [];
828
+ switch (constructorType) {
829
+ case "automattic-cross":
830
+ config.columnSettings[0] = config.columnSettings[0] || {};
831
+ config.columnSettings[0].color = config.headerColor;
832
+ output = rows.map((obj) => {
833
+ const key = Object.keys(obj)[0];
834
+ return [key].concat(obj[key]);
835
+ });
836
+ break;
837
+ case "automattic-vertical":
838
+ config.columnSettings[0] = config.columnSettings[0] || {};
839
+ config.columnSettings[0].color = config.headerColor;
840
+ output = rows.map((value) => {
841
+ const key = Object.keys(value)[0];
842
+ return [key, value[key]];
843
+ });
844
+ break;
845
+ case "o-horizontal":
846
+ if (config.table.header[0].length && config.table.header[0].every((obj) => obj.value)) {
847
+ output = rows.map((row) => config.table.header[0].map((obj) => row[obj.value]));
848
+ } else output = rows.map((obj) => Object.values(obj));
849
+ break;
850
+ case "a-horizontal":
851
+ output = rows;
852
+ break;
853
+ }
854
+ return output;
855
+ };
856
+
857
+ // src/factory.ts
858
+ var counter = 0;
859
+ var Factory = function(paramsArr) {
860
+ const _configKey = Symbol.config;
861
+ let header = [];
862
+ const body = [];
863
+ let footer = [];
864
+ let options = {};
865
+ switch (true) {
866
+ // header, rows, footer, and options
867
+ case paramsArr.length === 4:
868
+ header = paramsArr[0];
869
+ body.push(...paramsArr[1]);
870
+ footer = paramsArr[2];
871
+ options = paramsArr[3];
872
+ break;
873
+ // header, rows, footer
874
+ case (paramsArr.length === 3 && paramsArr[2] instanceof Array):
875
+ header = paramsArr[0];
876
+ body.push(...paramsArr[1]);
877
+ footer = paramsArr[2];
878
+ break;
879
+ // header, rows, options
880
+ case (paramsArr.length === 3 && typeof paramsArr[2] === "object"):
881
+ header = paramsArr[0];
882
+ body.push(...paramsArr[1]);
883
+ options = paramsArr[2];
884
+ break;
885
+ // header, rows (rows, footer is not an option)
886
+ case (paramsArr.length === 2 && paramsArr[1] instanceof Array):
887
+ header = paramsArr[0];
888
+ body.push(...paramsArr[1]);
889
+ break;
890
+ // rows, options
891
+ case (paramsArr.length === 2 && typeof paramsArr[1] === "object"):
892
+ body.push(...paramsArr[0]);
893
+ options = paramsArr[1];
894
+ break;
895
+ // rows
896
+ case (paramsArr.length === 1 && paramsArr[0] instanceof Array):
897
+ body.push(...paramsArr[0]);
898
+ break;
899
+ // adapter called: i.e. `require('tty-table')('automattic-cli-table')`
900
+ case (paramsArr.length === 1 && typeof paramsArr[0] === "string"): {
901
+ const adapters = {
902
+ "automattic-cli-table": () => require("../adapters/automattic-cli-table.js"),
903
+ "default-adapter": () => require("../adapters/default-adapter.js"),
904
+ "terminal-adapter": () => require("../adapters/terminal-adapter.js")
905
+ };
906
+ const load = adapters[paramsArr[0]];
907
+ if (!load) throw new Error(`Unknown adapter: "${paramsArr[0]}". Available adapters: ${Object.keys(adapters).join(", ")}`);
908
+ return load();
909
+ }
910
+ /* istanbul ignore next */
911
+ default:
912
+ console.log("Error: Bad params. \nSee docs at github.com/tecfu/tty-table");
913
+ process.exit();
914
+ }
915
+ const cloneddefaults = JSON.parse(JSON.stringify(defaults_default));
916
+ const config = Object.assign({}, cloneddefaults, options);
917
+ config.align = config.alignment || config.align;
918
+ config.headerAlign = config.headerAlignment || config.headerAlign;
919
+ if (config.truncate === true) config.truncate = "";
920
+ if (config.borderColor) {
921
+ config.borderCharacters[config.borderStyle] = config.borderCharacters[config.borderStyle].map(function(obj) {
922
+ Object.keys(obj).forEach(function(key) {
923
+ obj[key] = style(obj[key], config.borderColor);
924
+ });
925
+ return obj;
926
+ });
927
+ }
928
+ config.columnSettings = header.slice(0);
929
+ config.table.header = header;
930
+ config.table.header = [config.table.header];
931
+ config.table.footer = footer;
932
+ if (config.terminalAdapter !== true) {
933
+ counter++;
934
+ }
935
+ config.tableId = counter;
936
+ const tableObject = Object.create(body);
937
+ tableObject[_configKey] = config;
938
+ tableObject.render = function() {
939
+ const output = stringifyData(this[_configKey], this.slice(0));
940
+ tableObject.height = this[_configKey].height;
941
+ return output;
942
+ };
943
+ return tableObject;
944
+ };
945
+ var Table = function(...params) {
946
+ return Factory(params);
947
+ };
948
+ Table.resetStyle = resetStyle;
949
+ Table.style = styleEachChar;
950
+ var factory_default = Table;
951
+
952
+ // src/index.ts
953
+ var src_default = factory_default;
954
+
955
+ // src/ansi.ts
956
+ var codes = {
957
+ reset: "0",
958
+ bold: "1",
959
+ dim: "2",
960
+ italic: "3",
961
+ underline: "4",
962
+ inverse: "7",
963
+ hidden: "8",
964
+ strikethrough: "9",
965
+ black: "30",
966
+ red: "31",
967
+ green: "32",
968
+ yellow: "33",
969
+ blue: "34",
970
+ magenta: "35",
971
+ cyan: "36",
972
+ white: "37",
973
+ gray: "90",
974
+ grey: "90",
975
+ bgBlack: "40",
976
+ bgRed: "41",
977
+ bgGreen: "42",
978
+ bgYellow: "43",
979
+ bgBlue: "44",
980
+ bgMagenta: "45",
981
+ bgCyan: "46",
982
+ bgWhite: "47"
983
+ };
984
+ var style2 = (value, ...styles) => {
985
+ const active = styles.map((s) => codes[s]).filter(Boolean);
986
+ return active.length ? `\x1B[${active.join(";")}m${value}\x1B[0m` : value;
987
+ };
988
+
989
+ // src/cli.ts
990
+ var main = async () => {
991
+ const argv = await (0, import_yargs.default)((0, import_helpers.hideBin)(process.argv)).options({
992
+ config: { type: "string" },
993
+ format: { choices: ["json", "csv"], default: "csv" },
994
+ "csv-delimiter": { type: "string", default: "," },
995
+ "csv-escape": { type: "string" },
996
+ "csv-rowDelimiter": { type: "string", default: "\n" }
997
+ }).parse();
998
+ const options = {};
999
+ for (const [key, value] of Object.entries(argv)) if (key.startsWith("options-")) options[key.slice(8)] = value;
1000
+ let header = [];
1001
+ if (argv.config) {
1002
+ const parsedHeader = JSON.parse(import_node_fs.default.readFileSync(import_node_path.default.resolve(argv.config), "utf8"));
1003
+ if (!Array.isArray(parsedHeader)) fail("Configuration error", "The header configuration must be a JSON array.");
1004
+ header = parsedHeader;
1005
+ }
1006
+ const stdin = await new Promise((resolve) => {
1007
+ let data = "";
1008
+ process.stdin.setEncoding("utf8");
1009
+ process.stdin.on("data", (chunk) => {
1010
+ data += chunk;
1011
+ });
1012
+ process.stdin.on("end", () => resolve(data));
1013
+ });
1014
+ function fail(title, detail) {
1015
+ console.error(`
1016
+ ${style2(title, "white", "bgRed")}
1017
+
1018
+ ${detail}`);
1019
+ process.exit(1);
1020
+ }
1021
+ let rows;
1022
+ if (argv.format === "json") {
1023
+ try {
1024
+ const parsed = JSON.parse(stdin);
1025
+ rows = Array.isArray(parsed) ? parsed : fail("JSON parse error", "Please provide a JSON array or use --format csv.");
1026
+ } catch {
1027
+ fail("JSON parse error", "Please provide valid JSON or use --format csv.");
1028
+ }
1029
+ } else {
1030
+ try {
1031
+ rows = await new Promise((resolve, reject) => {
1032
+ const csvOptions = {
1033
+ delimiter: argv["csv-delimiter"],
1034
+ record_delimiter: argv["csv-rowDelimiter"]
1035
+ };
1036
+ const escape = argv["csv-escape"];
1037
+ if (escape !== void 0) csvOptions.escape = escape;
1038
+ (0, import_csv.parse)(stdin, csvOptions, (error, records) => {
1039
+ if (error) reject(error);
1040
+ else resolve(records);
1041
+ });
1042
+ });
1043
+ } catch {
1044
+ fail("CSV parse error", "Please provide valid comma-separated values or use --format json.");
1045
+ }
1046
+ }
1047
+ const table = src_default(header, rows, options);
1048
+ process.stdout.write(table.render() + "\n");
1049
+ };
1050
+ void main();
1051
+ ;if (typeof module !== "undefined" && typeof module.exports?.default === "function") { module.exports = Object.assign(module.exports.default, module.exports) }
1052
+ //# sourceMappingURL=cli.js.map