« get me outta code hell

index.js « dependencies « content « src - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/content/dependencies/index.js
blob: c2d88f643c40a0f99a648a8844ce161cf6bf74fd (plain)
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
import chokidar from 'chokidar';
import EventEmitter from 'events';
import * as path from 'path';
import {fileURLToPath} from 'url';

import contentFunction from '../../content-function.js';
import {color, logWarn} from '../../util/cli.js';
import {annotateFunction} from '../../util/sugar.js';

function cachebust(filePath) {
  if (filePath in cachebust.cache) {
    cachebust.cache[filePath] += 1;
    return `${filePath}?cachebust${cachebust.cache[filePath]}`;
  } else {
    cachebust.cache[filePath] = 0;
    return filePath;
  }
}

cachebust.cache = Object.create(null);

export function watchContentDependencies({
  mock = null,
  logging = true,
} = {}) {
  const events = new EventEmitter();
  const contentDependencies = {};

  let emittedReady = false;
  let initialScanComplete = false;
  let allDependenciesFulfilled = false;

  Object.assign(events, {
    contentDependencies,
    close,
  });

  // Watch adjacent files
  const metaPath = fileURLToPath(import.meta.url);
  const metaDirname = path.dirname(metaPath);
  const watcher = chokidar.watch(metaDirname);

  watcher.on('all', (event, filePath) => {
    if (!['add', 'change'].includes(event)) return;
    if (filePath === metaPath) return;
    handlePathUpdated(filePath);
  });

  watcher.on('unlink', (filePath) => {
    if (filePath === metaPath) {
      console.error(`Yeowzers content dependencies just got nuked.`);
      return;
    }
    handlePathRemoved(filePath);
  });

  watcher.on('ready', () => {
    initialScanComplete = true;
    checkReadyConditions();
  });

  if (mock) {
    const errors = [];
    for (const [functionName, spec] of Object.entries(mock)) {
      try {
        const fn = processFunctionSpec(functionName, spec);
        contentDependencies[functionName] = fn;
      } catch (error) {
        error.message = `(${functionName}) ${error.message}`;
        errors.push(error);
      }
    }
    if (errors.length) {
      throw new AggregateError(errors, `Errors processing mocked content functions`);
    }
    checkReadyConditions();
  }

  return events;

  async function close() {
    return watcher.close();
  }

  function checkReadyConditions() {
    if (emittedReady) {
      return;
    }

    if (!initialScanComplete) {
      return;
    }

    checkAllDependenciesFulfilled();

    if (!allDependenciesFulfilled) {
      return;
    }

    events.emit('ready');
    emittedReady = true;
  }

  function checkAllDependenciesFulfilled() {
    allDependenciesFulfilled = !Object.values(contentDependencies).includes(null);
  }

  function getFunctionName(filePath) {
    const shortPath = path.basename(filePath);
    const functionName = shortPath.slice(0, -path.extname(shortPath).length);
    return functionName;
  }

  function isMocked(functionName) {
    return !!mock && Object.keys(mock).includes(functionName);
  }

  async function handlePathRemoved(filePath) {
    const functionName = getFunctionName(filePath);
    if (isMocked(functionName)) return;

    delete contentDependencies[functionName];
  }

  async function handlePathUpdated(filePath) {
    const functionName = getFunctionName(filePath);
    if (isMocked(functionName)) return;

    let error = null;

    main: {
      let spec;
      try {
        spec = (await import(cachebust(filePath))).default;
      } catch (caughtError) {
        error = caughtError;
        error.message = `Error importing: ${error.message}`;
        break main;
      }

      let fn;
      try {
        fn = processFunctionSpec(functionName, spec);
      } catch (caughtError) {
        error = caughtError;
        break main;
      }

      contentDependencies[functionName] = fn;

      events.emit('update', functionName);
      checkReadyConditions();
    }

    if (!error) {
      return true;
    }

    if (!(functionName in contentDependencies)) {
      contentDependencies[functionName] = null;
    }

    events.emit('error', functionName, error);

    if (logging) {
      if (contentDependencies[functionName]) {
        logWarn`Failed to import ${functionName} - using existing version`;
      } else {
        logWarn`Failed to import ${functionName} - no prior version loaded`;
      }

      if (typeof error === 'string') {
        console.error(color.yellow(error));
      } else {
        console.error(error);
      }
    }

    return false;
  }

  function processFunctionSpec(functionName, spec) {
    if (typeof spec.data === 'function') {
      annotateFunction(spec.data, {name: functionName, description: 'data'});
    }

    if (typeof spec.generate === 'function') {
      annotateFunction(spec.generate, {name: functionName});
    }

    let fn;
    try {
      fn = contentFunction(spec);
    } catch (error) {
      error.message = `Error loading spec: ${error.message}`;
      throw error;
    }

    return fn;
  }
}

export function quickLoadContentDependencies(opts) {
  return new Promise((resolve, reject) => {
    const watcher = watchContentDependencies(opts);

    watcher.on('error', (name, error) => {
      watcher.close().then(() => {
        error.message = `Error loading dependency ${name}: ${error}`;
        reject(error);
      });
    });

    watcher.on('ready', () => {
      watcher.close().then(() => {
        resolve(watcher.contentDependencies);
      });
    });
  });
}