File: watch-cli.ts

package info (click to toggle)
node-rollup 2.38.4-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 42,968 kB
  • sloc: javascript: 88,384; makefile: 10
file content (158 lines) | stat: -rw-r--r-- 4,283 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
const chokidar = require('chokidar');
import { bold, cyan, green, underline } from 'colorette';
const dateTime = require ('date-time');
import fs from 'fs';
const ms = require('pretty-ms');
const onExit = require('signal-exit');
import * as rollup from '../../src/node-entry';
import { MergedRollupOptions, RollupWatcher } from '../../src/rollup/types';
import relativeId from '../../src/utils/relativeId';
import { handleError, stderr } from '../logging';
import { BatchWarnings } from './batchWarnings';
import { getConfigPath } from './getConfigPath';
import loadAndParseConfigFile from './loadConfigFile';
import loadConfigFromCommand from './loadConfigFromCommand';
import { getResetScreen } from './resetScreen';
import { printTimings } from './timings';

export async function watch(command: any) {
	process.env.ROLLUP_WATCH = 'true';
	const isTTY = process.stderr.isTTY;
	const silent = command.silent;
	let configs: MergedRollupOptions[];
	let warnings: BatchWarnings;
	let watcher: RollupWatcher;
	let configWatcher: fs.FSWatcher;
	const configFile = command.config ? getConfigPath(command.config) : null;

	onExit(close);
	process.on('uncaughtException' as any, close);
	if (!process.stdin.isTTY) {
		process.stdin.on('end', close);
		process.stdin.resume();
	}

	if (configFile) {
		let reloadingConfig = false;
		let aborted = false;
		let configFileData: string | null = null;

		configWatcher = chokidar.watch(configFile).on('change', () => reloadConfigFile());
		await reloadConfigFile();

		async function reloadConfigFile() {
			try {
				const newConfigFileData = fs.readFileSync(configFile!, 'utf-8');
				if (newConfigFileData === configFileData) {
					return;
				}
				if (reloadingConfig) {
					aborted = true;
					return;
				}
				if (configFileData) {
					stderr(`\nReloading updated config...`);
				}
				configFileData = newConfigFileData;
				reloadingConfig = true;
				({ options: configs, warnings } = await loadAndParseConfigFile(configFile!, command));
				reloadingConfig = false;
				if (aborted) {
					aborted = false;
					reloadConfigFile();
				} else {
					if (watcher) {
						watcher.close();
					}
					start(configs);
				}
			} catch (err) {
				configs = [];
				reloadingConfig = false;
				handleError(err, true);
			}
		}
	} else {
		({ options: configs, warnings } = await loadConfigFromCommand(command));
		start(configs);
	}

	// tslint:disable-next-line:no-unnecessary-type-assertion
	const resetScreen = getResetScreen(configs!, isTTY);

	function start(configs: MergedRollupOptions[]) {
		try {
			watcher = rollup.watch(configs as any);
		} catch (err) {
			return handleError(err);
		}

		watcher.on('event', event => {
			switch (event.code) {
				case 'ERROR':
					warnings.flush();
					handleError(event.error, true);
					break;

				case 'START':
					if (!silent) {
						resetScreen(underline(`rollup v${rollup.VERSION}`));
					}
					break;

				case 'BUNDLE_START':
					if (!silent) {
						let input = event.input;
						if (typeof input !== 'string') {
							input = Array.isArray(input)
								? input.join(', ')
								: Object.keys(input as Record<string, string>)
										.map(key => (input as Record<string, string>)[key])
										.join(', ');
						}
						stderr(
							cyan(`bundles ${bold(input)} → ${bold(event.output.map(relativeId).join(', '))}...`)
						);
					}
					break;

				case 'BUNDLE_END':
					warnings.flush();
					if (!silent)
						stderr(
							green(
								`created ${bold(event.output.map(relativeId).join(', '))} in ${bold(
									ms(event.duration)
								)}`
							)
						);
					if (event.result && event.result.getTimings) {
						printTimings(event.result.getTimings());
					}
					break;

				case 'END':
					if (!silent && isTTY) {
						stderr(`\n[${dateTime()}] waiting for changes...`);
					}
			}

			if ('result' in event && event.result) {
				event.result.close().catch(error => handleError(error, true));
			}
		});
	}

	function close(code: number | null) {
		process.removeListener('uncaughtException', close);
		// removing a non-existent listener is a no-op
		process.stdin.removeListener('end', close);

		if (watcher) watcher.close();
		if (configWatcher) configWatcher.close();

		if (code) {
			process.exit(code);
		}
	}
}