blob: 5cd116d4cfb17997d788f28d03e5de729eef6666 (
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
|
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';
export function watchContentDependencies() {
const events = new EventEmitter();
const contentDependencies = {};
Object.assign(events, {
contentDependencies,
});
// 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);
})
return events;
function getFunctionName(filePath) {
const shortPath = path.basename(filePath);
const functionName = shortPath.slice(0, -path.extname(shortPath).length);
return functionName;
}
async function handlePathRemoved(filePath) {
const functionName = getFunctionName(filePath);
delete contentDependencies[functionName];
}
async function handlePathUpdated(filePath) {
const functionName = getFunctionName(filePath);
let error = null;
main: {
let spec;
try {
spec = (await import(`${filePath}?${Date.now()}`)).default;
} catch (caughtError) {
error = caughtError;
error.message = `Error importing: ${error.message}`;
break main;
}
try {
if (typeof spec.data === 'function') {
annotateFunction(spec.data, {name: functionName, description: 'data'});
}
if (typeof spec.generate === 'function') {
annotateFunction(spec.generate, {name: functionName});
}
} catch (caughtError) {
error = caughtError;
error.message = `Error annotating functions: ${error.message}`;
break main;
}
let fn;
try {
fn = contentFunction(spec);
} catch (caughtError) {
error = caughtError;
error.message = `Error loading spec: ${error.message}`;
break main;
}
contentDependencies[functionName] = fn;
}
if (!error) {
return true;
}
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;
}
}
|