-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
executable file
·189 lines (161 loc) · 6.05 KB
/
index.js
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
#!/usr/bin/env node
/* this file is the entry point when launching `study` from the CLI */
const fs = require('fs');
const path = require('path');
const open = require('open');
process.env['NODE_CONFIG_DIR'] = path.join(__dirname, '..', 'config');
const config = require('config');
const { copyDir } = require('../server/lib/copyDir');
const { emptyDir } = require('../server/lib/emptyDir');
let rootStudyConfig = {};
// hack: prefer lenses.json
try {
rootStudyConfig = require(path.join(process.cwd(), 'study.json'));
} catch (o_0) {}
try {
rootStudyConfig = require(path.join(process.cwd(), 'lenses.json'));
} catch (o_0) {}
/* The user can optionally launch a sub-path from the directory they are in
if they do this, localhost will still serve from the root of the directory
the browser will just open to the selected sub-path
when global configuration is set, there will be default plugin options for different mime types
then the browser will open to that sub-path with the appropriate queries
-> localhost:xxxx/user/defined/path?default-plugins-for-mime-type
*/
const userArgs = process.argv.slice(2);
// use the first arg that doesn't match a port config
config.demo = null;
// is this a demo run?
const demoOption = '-demo-reset';
const isDemo =
userArgs.find((entry) => entry.includes(demoOption))?.split('=') ||
Object.entries(rootStudyConfig).find((entry) =>
entry[0].includes(demoOption),
);
if (isDemo) {
config.demo = {};
const defaultDelay = 300000;
const userDelay = isDemo.length > 1 ? Number(isDemo[1]) : defaultDelay;
config.demo.resetDelay = !Number.isNaN(userDelay) ? userDelay : defaultDelay;
config.demo.resetIgnore =
userArgs
.find((entry) => entry.includes('-reset-ignore'))
?.split('=')?.[1]
.split(',') ||
Object.entries(rootStudyConfig).find((entry) =>
entry[0].includes('-reset-ignore'),
)?.[1];
config.demo.path = path.join(__dirname, '..', '.temp-demo-content');
// clear any old demos
console.log('--- emptying backup directory ---');
emptyDir(config.demo.path);
console.log('--- backing up demo content ---');
copyDir(process.cwd(), config.demo.path, config.demo.resetIgnore);
// https://stackoverflow.com/a/14032965
function clearBackup() {
console.log('\n========= clearing demo backup =========');
emptyDir(config.demo.path);
}
//do something when app is closing
process.on('exit', clearBackup.bind(null, { cleanup: true }));
//catches ctrl+c event
// process.on('SIGINT', clearBackup.bind(null, { exit: true }));
// catches "kill pid" (for example: nodemon restart)
process.on('SIGUSR1', clearBackup.bind(null, { exit: true }));
process.on('SIGUSR2', clearBackup.bind(null, { exit: true }));
}
const pathToStudy =
userArgs.find((entry) => entry[0] !== '-' && entry[1] !== '-') || '';
// todo
// search process.argv for "-h"
// log a little guide to the console
// allow users to pass a port
// subsequent arguments can be interpreted as plugins to apply, overriding the default
// $ study ./path/file.js format highlight
// futurer things might be like:
// $ study ./path/file.js format highlight -o new-file.js
const absPathToStudy = path.join(process.cwd(), pathToStudy);
// const absPathToStudy = userArgs.includes("--sandbox")
// ? path.join(__dirname, "..", "sandbox")
// : path.join(process.cwd(), pathToStudy);
// // should you be allowed to open to a 404 path?
// // it won't hurt anything, it'll just be a 404 page
// const isValidPath = fs.existsSync(absPathToStudy);
// if (!isValidPath) {
// throw new Error(pathToStudy + ': is not a valid path');
// };
const defaultLenses = config.locals['--defaults'];
const defaultLense =
fs.existsSync(absPathToStudy) && fs.lstatSync(absPathToStudy).isDirectory()
? defaultLenses.directory
: defaultLenses[path.extname(pathToStudy)];
// user can define a port number to study
const cliPortSearch = process.argv.find((entry) => {
if (/--port=[\d]*/i.test(entry)) {
const portString = entry.split('=')[1];
const portNumber = Number(portString);
if (!Number.isNaN(portNumber) && portNumber >= 3000 && portNumber < 9000) {
return true;
}
process.argv;
}
return false;
});
const cliPort =
cliPortSearch !== undefined ? cliPortSearch.split('=')[1] : undefined;
const cliLensSearch = process.argv.find((entry) => /--lens=[\d]*/i.test(entry));
const cliLens =
cliLensSearch !== undefined ? cliLensSearch.split('=')[1] : undefined;
/**
* @param {Object} object
* @param {string} key
* @return {any} value
* https://stackoverflow.com/a/47538066
*/
const getParameterCaseInsensitive = (object, key) => {
return object[
Object.keys(object).find((k) => k.toLowerCase() === key.toLowerCase())
];
};
const rootStudyConfigPort = getParameterCaseInsensitive(
rootStudyConfig,
'--port',
);
const rootStudyConfigPortValidated =
!Number.isNaN(rootStudyConfigPort) &&
rootStudyConfigPort >= 3000 &&
rootStudyConfigPort < 9000
? rootStudyConfigPort
: undefined;
const port =
process.env.PORT || cliPort || rootStudyConfigPortValidated || config.PORT;
const queryMarker = defaultLense ? '?' : '';
// -- the following lines will need to be rewritten when config works --
// construct a url using global configurations and the user-provided sub-path
// should this not normalize? might it make url paths in windows backslashes?
const pathToOpen = path.normalize(pathToStudy);
// const url = `http://localhost:${port}/${pathToOpen}${queryMarker}${defaultLense}`;
const url = `http://localhost:${port}/${pathToOpen}${queryMarker}${
cliLens || '--defaults'
}`;
const helpUrl = `http://localhost:${port}?--help`;
// launch the server
require('../server/index.js')(port).then((_) => {
console.log('studying: ', url);
if (
!(
userArgs.find((entry) => entry.includes('-no-open')) ||
Object.keys(rootStudyConfig).find((configName) =>
configName.includes('-no-open'),
)
)
) {
open(url);
}
// if (config.locals["--help"]) {
// setTimeout(() => open(helpUrl), 200);
// }
});
/*
go to ../server/index.js for the next step in your journey
*/