1 | import npath from 'path';
|
2 |
|
3 | import _ from 'underscore';
|
4 | import watchy from 'watchy';
|
5 |
|
6 | import buildConfig from './build-config.js';
|
7 | import bustCache from './bust-cache.js';
|
8 | import getConfig from './get-config.js';
|
9 |
|
10 | export default async ({
|
11 | configPath = 'cogs.js',
|
12 | debounce = 0.1,
|
13 | onError = _.noop,
|
14 | onEnd = _.noop,
|
15 | onResult = _.noop,
|
16 | onStart = _.noop,
|
17 | usePolling = false,
|
18 | watchPaths = []
|
19 | }) => {
|
20 | let building = false;
|
21 | let changedPaths = new Set();
|
22 | let config;
|
23 | let timeoutId;
|
24 |
|
25 | const build = async () => {
|
26 | if (building) return;
|
27 |
|
28 | building = true;
|
29 |
|
30 | const paths = changedPaths;
|
31 | changedPaths = new Set();
|
32 | if (paths.has(configPath)) {
|
33 | config = null;
|
34 | } else if (config) {
|
35 | await Promise.all(
|
36 | _.map(Array.from(paths), path => bustCache({ config, path }))
|
37 | );
|
38 | }
|
39 |
|
40 | if (!config) config = await getConfig(configPath);
|
41 | await onStart();
|
42 | await buildConfig({
|
43 | config,
|
44 | onResult: async result => {
|
45 | const { didChange, targetPath } = result;
|
46 | if (didChange) await bustCache({ config, path: targetPath });
|
47 | return onResult(result);
|
48 | }
|
49 | });
|
50 | await onEnd();
|
51 |
|
52 | building = false;
|
53 |
|
54 | if (changedPaths.size) await build();
|
55 | };
|
56 |
|
57 | if (!watchPaths.length) return build();
|
58 |
|
59 | const tryBuild = async () => {
|
60 | try {
|
61 | await build();
|
62 | } catch (er) {
|
63 | await onError(er);
|
64 | }
|
65 | };
|
66 |
|
67 | const handleChangedPath = ({ path }) => {
|
68 | changedPaths.add(npath.relative('.', path));
|
69 | if (!debounce) return tryBuild();
|
70 |
|
71 | clearTimeout(timeoutId);
|
72 | timeoutId = setTimeout(tryBuild, debounce * 1000);
|
73 | };
|
74 |
|
75 | const watcher = await watchy({
|
76 | onError,
|
77 | onChange: handleChangedPath,
|
78 | patterns: [].concat(configPath, watchPaths),
|
79 | usePolling
|
80 | });
|
81 |
|
82 | await tryBuild();
|
83 |
|
84 | return watcher;
|
85 | };
|