UNPKG

2.96 kBJavaScriptView Raw
1// @flow strict-local
2
3import type {ReporterEvent} from '@parcel/types';
4import type {WorkerApi} from '@parcel/workers';
5import type {ParcelOptions} from './types';
6
7import invariant from 'assert';
8import {
9 bundleToInternalBundle,
10 bundleToInternalBundleGraph,
11 NamedBundle,
12} from './public/Bundle';
13import WorkerFarm, {bus} from '@parcel/workers';
14import ParcelConfig from './ParcelConfig';
15import logger, {
16 patchConsole,
17 unpatchConsole,
18 PluginLogger,
19 INTERNAL_ORIGINAL_CONSOLE,
20} from '@parcel/logger';
21import PluginOptions from './public/PluginOptions';
22import BundleGraph from './BundleGraph';
23
24type Opts = {|
25 config: ParcelConfig,
26 options: ParcelOptions,
27 workerFarm: WorkerFarm,
28|};
29
30export default class ReporterRunner {
31 config: ParcelConfig;
32 options: ParcelOptions;
33 pluginOptions: PluginOptions;
34
35 constructor(opts: Opts) {
36 this.config = opts.config;
37 this.options = opts.options;
38 this.pluginOptions = new PluginOptions(this.options);
39
40 logger.onLog(event => this.report(event));
41
42 bus.on('reporterEvent', event => {
43 if (
44 event.type === 'buildProgress' &&
45 (event.phase === 'optimizing' || event.phase === 'packaging') &&
46 !(event.bundle instanceof NamedBundle)
47 ) {
48 // Convert any internal bundles back to their public equivalents as reporting
49 // is public api
50 let bundleGraph = opts.workerFarm.workerApi.getSharedReference(
51 event.bundleGraphRef,
52 );
53 invariant(bundleGraph instanceof BundleGraph);
54 this.report({
55 ...event,
56 bundle: new NamedBundle(event.bundle, bundleGraph, this.options),
57 });
58 return;
59 }
60
61 this.report(event);
62 });
63
64 if (this.options.patchConsole) {
65 patchConsole();
66 } else {
67 unpatchConsole();
68 }
69 }
70
71 async report(event: ReporterEvent) {
72 let reporters = await this.config.getReporters();
73
74 for (let reporter of reporters) {
75 try {
76 await reporter.plugin.report({
77 event,
78 options: this.pluginOptions,
79 logger: new PluginLogger({origin: reporter.name}),
80 });
81 } catch (e) {
82 // We shouldn't emit a report event here as we will cause infinite loops...
83 INTERNAL_ORIGINAL_CONSOLE.error(e);
84 }
85 }
86 }
87}
88
89export function reportWorker(workerApi: WorkerApi, event: ReporterEvent) {
90 if (
91 event.type === 'buildProgress' &&
92 (event.phase === 'optimizing' || event.phase === 'packaging')
93 ) {
94 // Convert any public api bundles to their internal equivalents for
95 // easy serialization
96 bus.emit('reporterEvent', {
97 ...event,
98 bundle: bundleToInternalBundle(event.bundle),
99 bundleGraphRef: workerApi.resolveSharedReference(
100 bundleToInternalBundleGraph(event.bundle),
101 ),
102 });
103 return;
104 }
105
106 bus.emit('reporterEvent', event);
107}
108
109export function report(event: ReporterEvent) {
110 bus.emit('reporterEvent', event);
111}