@atlaspack/reporter-cli 2.12.1-canary.3354

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/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "@atlaspack/reporter-cli",
3
+ "version": "2.12.1-canary.3354+7bb54d46a",
4
+ "license": "MIT",
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/atlassian-labs/atlaspack.git"
11
+ },
12
+ "main": "lib/CLIReporter.js",
13
+ "source": "src/CLIReporter.js",
14
+ "engines": {
15
+ "node": ">= 16.0.0",
16
+ "atlaspack": "2.12.1-canary.3354+7bb54d46a"
17
+ },
18
+ "targets": {
19
+ "main": {
20
+ "includeNodeModules": {
21
+ "@atlaspack/plugin": false,
22
+ "@atlaspack/types": false,
23
+ "@atlaspack/utils": false,
24
+ "chalk": false,
25
+ "term-size": false
26
+ }
27
+ }
28
+ },
29
+ "dependencies": {
30
+ "@atlaspack/plugin": "2.12.1-canary.3354+7bb54d46a",
31
+ "@atlaspack/types": "2.12.1-canary.3354+7bb54d46a",
32
+ "@atlaspack/utils": "2.12.1-canary.3354+7bb54d46a",
33
+ "chalk": "^4.1.0",
34
+ "term-size": "^2.2.1"
35
+ },
36
+ "devDependencies": {
37
+ "@atlaspack/feature-flags": "2.12.1-canary.3354+7bb54d46a",
38
+ "filesize": "^6.1.0",
39
+ "nullthrows": "^1.1.1",
40
+ "ora": "^5.2.0",
41
+ "string-width": "^4.2.0",
42
+ "wrap-ansi": "^7.0.0"
43
+ },
44
+ "gitHead": "7bb54d46a00c5ba9cdbc2ee426dcbe82c8d79a3e"
45
+ }
@@ -0,0 +1,298 @@
1
+ // @flow
2
+ import type {ReporterEvent, PluginOptions} from '@atlaspack/types';
3
+ import type {Diagnostic} from '@atlaspack/diagnostic';
4
+ import type {Color} from 'chalk';
5
+
6
+ import {Reporter} from '@atlaspack/plugin';
7
+ import {
8
+ getProgressMessage,
9
+ prettifyTime,
10
+ prettyDiagnostic,
11
+ throttle,
12
+ } from '@atlaspack/utils';
13
+ import chalk from 'chalk';
14
+
15
+ import {getTerminalWidth} from './utils';
16
+ import logLevels from './logLevels';
17
+ import bundleReport from './bundleReport';
18
+ import phaseReport from './phaseReport';
19
+ import {
20
+ writeOut,
21
+ updateSpinner,
22
+ persistSpinner,
23
+ isTTY,
24
+ resetWindow,
25
+ persistMessage,
26
+ } from './render';
27
+ import * as emoji from './emoji';
28
+ import wrapAnsi from 'wrap-ansi';
29
+
30
+ const THROTTLE_DELAY = 100;
31
+ const seenWarnings = new Set();
32
+ const seenPhases = new Set();
33
+ const seenPhasesGen = new Set();
34
+
35
+ let phaseStartTimes = {};
36
+ let pendingIncrementalBuild = false;
37
+
38
+ let statusThrottle = throttle((message: string) => {
39
+ updateSpinner(message);
40
+ }, THROTTLE_DELAY);
41
+
42
+ // Exported only for test
43
+ export async function _report(
44
+ event: ReporterEvent,
45
+ options: PluginOptions,
46
+ ): Promise<void> {
47
+ let logLevelFilter = logLevels[options.logLevel || 'info'];
48
+
49
+ switch (event.type) {
50
+ case 'buildStart': {
51
+ seenWarnings.clear();
52
+ seenPhases.clear();
53
+ if (logLevelFilter < logLevels.info) {
54
+ break;
55
+ }
56
+
57
+ // Clear any previous output
58
+ resetWindow();
59
+
60
+ if (options.serveOptions) {
61
+ persistMessage(
62
+ chalk.blue.bold(
63
+ `Server running at ${
64
+ options.serveOptions.https ? 'https' : 'http'
65
+ }://${options.serveOptions.host ?? 'localhost'}:${
66
+ options.serveOptions.port
67
+ }`,
68
+ ),
69
+ );
70
+ }
71
+
72
+ break;
73
+ }
74
+ case 'buildProgress': {
75
+ if (logLevelFilter < logLevels.info) {
76
+ break;
77
+ }
78
+
79
+ if (pendingIncrementalBuild) {
80
+ pendingIncrementalBuild = false;
81
+ phaseStartTimes = {};
82
+ seenPhasesGen.clear();
83
+ seenPhases.clear();
84
+ }
85
+
86
+ if (!seenPhasesGen.has(event.phase)) {
87
+ phaseStartTimes[event.phase] = Date.now();
88
+ seenPhasesGen.add(event.phase);
89
+ }
90
+
91
+ if (!isTTY && logLevelFilter != logLevels.verbose) {
92
+ if (event.phase == 'transforming' && !seenPhases.has('transforming')) {
93
+ updateSpinner('Building...');
94
+ } else if (event.phase == 'bundling' && !seenPhases.has('bundling')) {
95
+ updateSpinner('Bundling...');
96
+ } else if (
97
+ (event.phase == 'packaging' || event.phase == 'optimizing') &&
98
+ !seenPhases.has('packaging') &&
99
+ !seenPhases.has('optimizing')
100
+ ) {
101
+ updateSpinner('Packaging & Optimizing...');
102
+ }
103
+ seenPhases.add(event.phase);
104
+ break;
105
+ }
106
+
107
+ let message = getProgressMessage(event);
108
+ if (message != null) {
109
+ if (isTTY) {
110
+ statusThrottle(chalk.gray.bold(message));
111
+ } else {
112
+ updateSpinner(message);
113
+ }
114
+ }
115
+ break;
116
+ }
117
+ case 'buildSuccess':
118
+ if (logLevelFilter < logLevels.info) {
119
+ break;
120
+ }
121
+
122
+ phaseStartTimes['buildSuccess'] = Date.now();
123
+
124
+ persistSpinner(
125
+ 'buildProgress',
126
+ 'success',
127
+ chalk.green.bold(`Built in ${prettifyTime(event.buildTime)}`),
128
+ );
129
+
130
+ if (options.mode === 'production') {
131
+ await bundleReport(
132
+ event.bundleGraph,
133
+ options.outputFS,
134
+ options.projectRoot,
135
+ options.detailedReport?.assetsPerBundle,
136
+ );
137
+ } else {
138
+ pendingIncrementalBuild = true;
139
+ }
140
+
141
+ if (process.env.ATLASPACK_SHOW_PHASE_TIMES) {
142
+ phaseReport(phaseStartTimes);
143
+ }
144
+ break;
145
+ case 'buildFailure':
146
+ if (logLevelFilter < logLevels.error) {
147
+ break;
148
+ }
149
+
150
+ resetWindow();
151
+
152
+ persistSpinner('buildProgress', 'error', chalk.red.bold('Build failed.'));
153
+
154
+ await writeDiagnostic(options, event.diagnostics, 'red', true);
155
+ break;
156
+ case 'cache':
157
+ if (event.size > 500000) {
158
+ switch (event.phase) {
159
+ case 'start':
160
+ updateSpinner('Writing cache to disk');
161
+ break;
162
+ case 'end':
163
+ persistSpinner(
164
+ 'cache',
165
+ 'success',
166
+ chalk.grey.bold(`Cache written to disk`),
167
+ );
168
+ break;
169
+ }
170
+ }
171
+ break;
172
+ case 'log': {
173
+ if (logLevelFilter < logLevels[event.level]) {
174
+ break;
175
+ }
176
+
177
+ switch (event.level) {
178
+ case 'success':
179
+ writeOut(chalk.green(event.message));
180
+ break;
181
+ case 'progress':
182
+ writeOut(event.message);
183
+ break;
184
+ case 'verbose':
185
+ case 'info':
186
+ await writeDiagnostic(options, event.diagnostics, 'blue');
187
+ break;
188
+ case 'warn':
189
+ if (
190
+ event.diagnostics.some(
191
+ diagnostic => !seenWarnings.has(diagnostic.message),
192
+ )
193
+ ) {
194
+ await writeDiagnostic(options, event.diagnostics, 'yellow', true);
195
+ for (let diagnostic of event.diagnostics) {
196
+ seenWarnings.add(diagnostic.message);
197
+ }
198
+ }
199
+ break;
200
+ case 'error':
201
+ await writeDiagnostic(options, event.diagnostics, 'red', true);
202
+ break;
203
+ default:
204
+ throw new Error('Unknown log level ' + event.level);
205
+ }
206
+ }
207
+ }
208
+ }
209
+
210
+ async function writeDiagnostic(
211
+ options: PluginOptions,
212
+ diagnostics: Array<Diagnostic>,
213
+ color: Color,
214
+ isError: boolean = false,
215
+ ) {
216
+ let columns = getTerminalWidth().columns;
217
+ let indent = 2;
218
+ let spaceAfter = isError;
219
+ for (let diagnostic of diagnostics) {
220
+ let {message, stack, codeframe, hints, documentation} =
221
+ await prettyDiagnostic(diagnostic, options, columns - indent);
222
+ // $FlowFixMe[incompatible-use]
223
+ message = chalk[color](message);
224
+
225
+ if (spaceAfter) {
226
+ writeOut('');
227
+ }
228
+
229
+ if (message) {
230
+ writeOut(wrapWithIndent(message), isError);
231
+ }
232
+
233
+ if (stack || codeframe) {
234
+ writeOut('');
235
+ }
236
+
237
+ if (stack) {
238
+ writeOut(chalk.gray(wrapWithIndent(stack, indent)), isError);
239
+ }
240
+
241
+ if (codeframe) {
242
+ writeOut(indentString(codeframe, indent), isError);
243
+ }
244
+
245
+ if ((stack || codeframe) && (hints.length > 0 || documentation)) {
246
+ writeOut('');
247
+ }
248
+
249
+ // Write hints
250
+ let hintIndent = stack || codeframe ? indent : 0;
251
+ for (let hint of hints) {
252
+ writeOut(
253
+ wrapWithIndent(
254
+ `${emoji.hint} ${chalk.blue.bold(hint)}`,
255
+ hintIndent + 3,
256
+ hintIndent,
257
+ ),
258
+ );
259
+ }
260
+
261
+ if (documentation) {
262
+ writeOut(
263
+ wrapWithIndent(
264
+ `${emoji.docs} ${chalk.magenta.bold(documentation)}`,
265
+ hintIndent + 3,
266
+ hintIndent,
267
+ ),
268
+ );
269
+ }
270
+
271
+ spaceAfter = stack || codeframe || hints.length > 0 || documentation;
272
+ }
273
+
274
+ if (spaceAfter) {
275
+ writeOut('');
276
+ }
277
+ }
278
+
279
+ function wrapWithIndent(string, indent = 0, initialIndent = indent) {
280
+ let width = getTerminalWidth().columns;
281
+ return indentString(
282
+ wrapAnsi(string.trimEnd(), width - indent, {trim: false}),
283
+ indent,
284
+ initialIndent,
285
+ );
286
+ }
287
+
288
+ function indentString(string, indent = 0, initialIndent = indent) {
289
+ return (
290
+ ' '.repeat(initialIndent) + string.replace(/\n/g, '\n' + ' '.repeat(indent))
291
+ );
292
+ }
293
+
294
+ export default (new Reporter({
295
+ report({event, options}) {
296
+ return _report(event, options);
297
+ },
298
+ }): Reporter);
@@ -0,0 +1,99 @@
1
+ // @flow
2
+ import type {BundleGraph, FilePath, PackagedBundle} from '@atlaspack/types';
3
+ import type {FileSystem} from '@atlaspack/fs';
4
+
5
+ import {generateBuildMetrics, prettifyTime} from '@atlaspack/utils';
6
+ import filesize from 'filesize';
7
+ import chalk from 'chalk';
8
+ import nullthrows from 'nullthrows';
9
+
10
+ import * as emoji from './emoji';
11
+ import {writeOut, table} from './render';
12
+ import {formatFilename} from './utils';
13
+
14
+ const LARGE_BUNDLE_SIZE = 1024 * 1024;
15
+ const COLUMNS = [
16
+ {align: 'left'}, // name
17
+ {align: 'right'}, // size
18
+ {align: 'right'}, // time
19
+ ];
20
+
21
+ export default async function bundleReport(
22
+ bundleGraph: BundleGraph<PackagedBundle>,
23
+ fs: FileSystem,
24
+ projectRoot: FilePath,
25
+ assetCount: number = 0,
26
+ ) {
27
+ let bundleList = bundleGraph.getBundles();
28
+
29
+ // Get a list of bundles sorted by size
30
+ let {bundles} =
31
+ assetCount > 0
32
+ ? await generateBuildMetrics(bundleList, fs, projectRoot)
33
+ : {
34
+ bundles: bundleList.map(b => {
35
+ return {
36
+ filePath: nullthrows(b.filePath),
37
+ size: b.stats.size,
38
+ time: b.stats.time,
39
+ assets: [],
40
+ };
41
+ }),
42
+ };
43
+ let rows = [];
44
+
45
+ for (let bundle of bundles) {
46
+ // Add a row for the bundle
47
+ rows.push([
48
+ formatFilename(bundle.filePath || '', chalk.cyan.bold),
49
+ chalk.bold(prettifySize(bundle.size, bundle.size > LARGE_BUNDLE_SIZE)),
50
+ chalk.green.bold(prettifyTime(bundle.time)),
51
+ ]);
52
+
53
+ if (assetCount > 0) {
54
+ let largestAssets = bundle.assets.slice(0, assetCount);
55
+ for (let asset of largestAssets) {
56
+ let columns: Array<string> = [
57
+ asset == largestAssets[largestAssets.length - 1] ? '└── ' : '├── ',
58
+ chalk.dim(prettifySize(asset.size)),
59
+ chalk.dim(chalk.green(prettifyTime(asset.time))),
60
+ ];
61
+
62
+ if (asset.filePath !== '') {
63
+ columns[0] += formatFilename(asset.filePath, chalk.reset);
64
+ } else {
65
+ columns[0] += 'Code from unknown sourcefiles';
66
+ }
67
+
68
+ // Add a row for the asset.
69
+ rows.push(columns);
70
+ }
71
+
72
+ if (bundle.assets.length > largestAssets.length) {
73
+ rows.push([
74
+ '└── ' +
75
+ chalk.dim(
76
+ `+ ${bundle.assets.length - largestAssets.length} more assets`,
77
+ ),
78
+ ]);
79
+ }
80
+
81
+ // If this isn't the last bundle, add an empty row before the next one
82
+ if (bundle !== bundles[bundles.length - 1]) {
83
+ rows.push([]);
84
+ }
85
+ }
86
+ }
87
+
88
+ // Render table
89
+ writeOut('');
90
+ table(COLUMNS, rows);
91
+ }
92
+
93
+ function prettifySize(size, isLarge) {
94
+ let res = filesize(size);
95
+ if (isLarge) {
96
+ return chalk.yellow(emoji.warning + ' ' + res);
97
+ }
98
+ return chalk.magenta(res);
99
+ }
package/src/emoji.js ADDED
@@ -0,0 +1,29 @@
1
+ // @flow strict-local
2
+
3
+ // From https://github.com/sindresorhus/is-unicode-supported/blob/8f123916d5c25a87c4f966dcc248b7ca5df2b4ca/index.js
4
+ // This package is ESM-only so it has to be vendored
5
+ function isUnicodeSupported() {
6
+ if (process.platform !== 'win32') {
7
+ return process.env.TERM !== 'linux'; // Linux console (kernel)
8
+ }
9
+
10
+ return (
11
+ Boolean(process.env.CI) ||
12
+ Boolean(process.env.WT_SESSION) || // Windows Terminal
13
+ process.env.ConEmuTask === '{cmd::Cmder}' || // ConEmu and cmder
14
+ process.env.TERM_PROGRAM === 'vscode' ||
15
+ process.env.TERM === 'xterm-256color' ||
16
+ process.env.TERM === 'alacritty'
17
+ );
18
+ }
19
+
20
+ const supportsEmoji = isUnicodeSupported();
21
+
22
+ // Fallback symbols for Windows from https://en.wikipedia.org/wiki/Code_page_437
23
+ export const progress: string = supportsEmoji ? '⏳' : '∞';
24
+ export const success: string = supportsEmoji ? '✨' : '√';
25
+ export const error: string = supportsEmoji ? '🚨' : '×';
26
+ export const warning: string = supportsEmoji ? '⚠️' : '‼';
27
+ export const info: string = supportsEmoji ? 'ℹ️' : 'ℹ';
28
+ export const hint: string = supportsEmoji ? '💡' : 'ℹ';
29
+ export const docs: string = supportsEmoji ? '📝' : 'ℹ';
@@ -0,0 +1,13 @@
1
+ // @flow strict-local
2
+
3
+ const logLevels = {
4
+ none: 0,
5
+ error: 1,
6
+ warn: 2,
7
+ info: 3,
8
+ progress: 3,
9
+ success: 3,
10
+ verbose: 4,
11
+ };
12
+
13
+ export default logLevels;
@@ -0,0 +1,33 @@
1
+ // @flow
2
+ import {prettifyTime} from '@atlaspack/utils';
3
+ import chalk from 'chalk';
4
+ import {writeOut} from './render';
5
+ import invariant from 'assert';
6
+
7
+ export default function phaseReport(phaseStartTimes: {[string]: number}) {
8
+ let phaseTimes = {};
9
+ if (phaseStartTimes['transforming'] && phaseStartTimes['bundling']) {
10
+ phaseTimes['Transforming'] =
11
+ phaseStartTimes['bundling'] - phaseStartTimes['transforming'];
12
+ }
13
+
14
+ let packagingAndOptimizing =
15
+ phaseStartTimes['packaging'] && phaseStartTimes['optimizing']
16
+ ? Math.min(phaseStartTimes['packaging'], phaseStartTimes['optimizing'])
17
+ : phaseStartTimes['packaging'] || phaseStartTimes['optimizing'];
18
+
19
+ if (phaseStartTimes['bundling'] && packagingAndOptimizing) {
20
+ phaseTimes['Bundling'] =
21
+ packagingAndOptimizing - phaseStartTimes['bundling'];
22
+ }
23
+
24
+ if (packagingAndOptimizing && phaseStartTimes['buildSuccess']) {
25
+ phaseTimes['Packaging & Optimizing'] =
26
+ phaseStartTimes['buildSuccess'] - packagingAndOptimizing;
27
+ }
28
+
29
+ for (let [phase, time] of Object.entries(phaseTimes)) {
30
+ invariant(typeof time === 'number');
31
+ writeOut(chalk.green.bold(`${phase} finished in ${prettifyTime(time)}`));
32
+ }
33
+ }
package/src/render.js ADDED
@@ -0,0 +1,149 @@
1
+ // @flow
2
+ import type {Writable} from 'stream';
3
+
4
+ import readline from 'readline';
5
+ import ora from 'ora';
6
+ import stringWidth from 'string-width';
7
+
8
+ import type {PadAlign} from './utils';
9
+ import {pad, countLines} from './utils';
10
+ import * as emoji from './emoji';
11
+
12
+ type ColumnType = {|
13
+ align: PadAlign,
14
+ |};
15
+
16
+ export const isTTY: any | boolean | true =
17
+ // $FlowFixMe
18
+ process.env.NODE_ENV !== 'test' && process.stdout.isTTY;
19
+
20
+ let stdout = process.stdout;
21
+ let stderr = process.stderr;
22
+
23
+ // Some state so we clear the output properly
24
+ let lineCount = 0;
25
+ let errorLineCount = 0;
26
+ let statusPersisted = false;
27
+
28
+ export function _setStdio(stdoutLike: Writable, stderrLike: Writable) {
29
+ stdout = stdoutLike;
30
+ stderr = stderrLike;
31
+ }
32
+
33
+ let spinner = ora({
34
+ color: 'green',
35
+ stream: stdout,
36
+ discardStdin: false,
37
+ });
38
+ let persistedMessages = [];
39
+
40
+ export function writeOut(message: string, isError: boolean = false) {
41
+ let processedMessage = message + '\n';
42
+ let hasSpinner = spinner.isSpinning;
43
+
44
+ // Stop spinner so we don't duplicate it
45
+ if (hasSpinner) {
46
+ spinner.stop();
47
+ }
48
+
49
+ let lines = countLines(message);
50
+ if (isError) {
51
+ stderr.write(processedMessage);
52
+ errorLineCount += lines;
53
+ } else {
54
+ stdout.write(processedMessage);
55
+ lineCount += lines;
56
+ }
57
+
58
+ // Restart the spinner
59
+ if (hasSpinner) {
60
+ spinner.start();
61
+ }
62
+ }
63
+
64
+ export function persistMessage(message: string) {
65
+ if (persistedMessages.includes(message)) return;
66
+
67
+ persistedMessages.push(message);
68
+ writeOut(message);
69
+ }
70
+
71
+ export function updateSpinner(message: string) {
72
+ // This helps the spinner play well with the tests
73
+ if (!isTTY) {
74
+ writeOut(message);
75
+ return;
76
+ }
77
+
78
+ spinner.text = message + '\n';
79
+ if (!spinner.isSpinning) {
80
+ spinner.start();
81
+ }
82
+ }
83
+
84
+ export function persistSpinner(
85
+ name: string,
86
+ status: 'success' | 'error',
87
+ message: string,
88
+ ) {
89
+ spinner.stopAndPersist({
90
+ symbol: emoji[status],
91
+ text: message,
92
+ });
93
+
94
+ statusPersisted = true;
95
+ }
96
+
97
+ function clearStream(stream: Writable, lines: number) {
98
+ if (!isTTY) return;
99
+
100
+ readline.moveCursor(stream, 0, -lines);
101
+ readline.clearScreenDown(stream);
102
+ }
103
+
104
+ // Reset the window's state
105
+ export function resetWindow() {
106
+ if (!isTTY) return;
107
+
108
+ // If status has been persisted we add a line
109
+ // Otherwise final states would remain in the terminal for rebuilds
110
+ if (statusPersisted) {
111
+ lineCount++;
112
+ statusPersisted = false;
113
+ }
114
+
115
+ clearStream(stderr, errorLineCount);
116
+ errorLineCount = 0;
117
+
118
+ clearStream(stdout, lineCount);
119
+ lineCount = 0;
120
+
121
+ for (let m of persistedMessages) {
122
+ writeOut(m);
123
+ }
124
+ }
125
+
126
+ export function table(columns: Array<ColumnType>, table: Array<Array<string>>) {
127
+ // Measure column widths
128
+ let colWidths = [];
129
+ for (let row of table) {
130
+ let i = 0;
131
+ for (let item of row) {
132
+ colWidths[i] = Math.max(colWidths[i] || 0, stringWidth(item));
133
+ i++;
134
+ }
135
+ }
136
+
137
+ // Render rows
138
+ for (let row of table) {
139
+ let items = row.map((item, i) => {
140
+ // Add padding between columns unless the alignment is the opposite to the
141
+ // next column and pad to the column width.
142
+ let padding =
143
+ !columns[i + 1] || columns[i + 1].align === columns[i].align ? 4 : 0;
144
+ return pad(item, colWidths[i] + padding, columns[i].align);
145
+ });
146
+
147
+ writeOut(items.join(''));
148
+ }
149
+ }