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