-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext.js
executable file
·340 lines (313 loc) · 11.7 KB
/
context.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
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
const EventEmitter = require('events');
const {featuresForContext} = require('./features');
const {modulesForContext} = require('./module');
const {watchDirAt, filePathReader, filePathWriter} = require('./fsWatcher');
const {createLogger, rootLogger} = require("./logger");
const {createModule} = require("./moduleFactory");
const contexts = {};
const contextsOptions = [];
const pathToId = path => {
let result = "";
for (const c of path) {
if (c === '/') {
if (result) result += '_';
} else if (c !== '.' || result) {
result += c;
}
}
return result || '_';
};
let saveAllOptions;
const saver = save => {
saveAllOptions = save;
saveOptions();
};
const saveOptions = (options) => saveAllOptions && saveAllOptions([...contextsOptions], options).catch(e => rootLogger.error(`can not save context: ${e}`, e));
const newContext = (options, allowAdministration = false) => {
const emitter = new EventEmitter();
const {path, session = {}, email = {}} = options;
const id = allowAdministration ? 'administrationApi' : pathToId(path);
const context = {id, path, session, email, allowAdministration};
context.register = () => {
const old = contexts[context.path];
if (old) {
if (!old.allowAdministration) {
old.unregister();
} else {
throw new Error(`Administration context can not be unregistered`);
}
}
rootLogger.info(`creating context '${id}' at '${path}'`);
if (!allowAdministration) {
contextsOptions.push(options);
}
saveOptions(options);
emitter.emit('register', options);
contexts[context.path] = context;
};
context.unregister = () => {
if (contexts[context.path] === context) {
rootLogger.info(`removing context '${id}' at '${path}'`);
emitter.emit('unregister');
if (!allowAdministration) {
const i = contextsOptions.indexOf(options);
if (i >= 0) {
contextsOptions.splice(i, 1);
saveOptions(options);
}
}
delete contexts[context.path];
return true;
}
return false
};
context.getOptions = () => options;
context.on = (name, listener) => emitter.on(name, listener);
context.emit = (name, data) => emitter.emit(name, data);
return context;
};
const contextParams = "session,email".split(',');
const optionsParams = [...contextParams, ..."headers,url".split(',')];
const modifyContext = (contextId, options = {}) => {
const context = Object.values(contexts).find(({id})=> id === contextId);
if (!context) {
return {contextId};
}
const actualOptions = context.getOptions();
const oldValues = {};
const changedFields = optionsParams.filter(field => {
const opt = options[field];
if (opt !== undefined) {
const value = actualOptions[field];
if (opt !== value) {
oldValues[field] = value;
if (opt == null) {
delete actualOptions[field];
} else {
actualOptions[field] = opt;
}
if (contextParams.includes(field)) {
context[field] = opt == null ? {} : opt;
}
return true;
}
}
return false;
});
if (changedFields.includes('headers') || changedFields.includes('url')) {
unregisterPath(actualOptions.path);
registerPath(actualOptions);
}
if (changedFields.length) {
saveOptions(actualOptions);
context.emit('modify', changedFields);
}
return {contextId, options: actualOptions};
};
const contextFor = contextId => Object.values(contexts).find(({id})=> id === contextId);
const contextForPath = (path) => contexts[path];
const getContexts = () => Object.values(contexts).map(({id})=> ({id}));
const toRemove = ["index.html", "index.htm"];
const pageTypes = Object.entries({
".ejs": "ejs",
".pug": "pug",
});
function getFileType(file) {
let isJsModule = false;
let pageType = null;
let path = file;
const paths = [];
if (path.endsWith('mod.js')) {
const lastModuleCharIndex = path.length - 7;
const lastChar = path.charAt(lastModuleCharIndex);
const rootModule = lastChar === '/';
if (rootModule || lastChar === '.') {
isJsModule = true;
path = path.substr(0, rootModule ? lastModuleCharIndex + 1 : lastModuleCharIndex)
}
} else {
const [ext, name] = pageTypes.find(([ext]) => path.endsWith(ext)) || [];
if (name) {
const withoutExtension = path.substr(0, path.length - ext.length);
paths.push(withoutExtension);
pageType = name;
path = `${withoutExtension}.html`
} else if (path.endsWith('.html')) {
pageType = 'html';
const withoutExtension = path.substr(0, path.length - 5);
paths.push(withoutExtension);
}
}
paths.push(path);
toRemove.map(end => path.endsWith(end) && paths.push(path.substr(0, path.length - end.length)));
return {paths, isJsModule, pageType};
}
let defaultPath;
let resolvers;
const addPathResolver = (path, resolve) => {
if (!resolvers) resolvers = [];
resolve.path = path;
resolvers.push(resolve);
};
const resolveBy = req => {
if (!resolvers) return defaultPath;
const item = resolvers.find(resolve => resolve(req));
return item ? item.path : defaultPath;
};
function remove(module) {
const onUnLoad = module && module.onUnLoad;
try {
onUnLoad && onUnLoad();
} catch (e) {
}
}
const unregisterPath = (path) => {
if (resolvers) {
let {length} = resolvers;
while (length-- > 0) if (resolvers[length].path === path) resolvers.splice(length, 1);
if (resolvers.length === 0) resolvers = null;
}
};
const urlStartsWith = (fullUrl, url) => fullUrl.startsWith(url+'/');
const registerPath = ({path, headers, url = ""}) => {
let pathResolver;
if (headers) {
const entries = Object.entries(headers);
const {length, 0: first} = entries;
if (length === 1) {
const [name, value] = first;
if (url) {
if (Array.isArray(value)) {
pathResolver = ({headers, originalUrl}) => urlStartsWith(originalUrl, url) && value.includes(headers[name]);
} else {
pathResolver = ({headers, originalUrl}) => urlStartsWith(originalUrl, url) && value === headers[name];
}
} else {
if (Array.isArray(value)) {
pathResolver = ({headers}) => value.includes(headers[name]);
} else {
pathResolver = ({headers}) => value === headers[name];
}
}
} else {
const ignore = entries.map(([name, value]) => {
if (Array.isArray(value)) {
return headers => !value.includes(headers[name]);
}
return headers => headers[name] !== value;
});
if (url) {
pathResolver = ({headers, originalUrl}) => urlStartsWith(originalUrl, url) && !ignore.find(i => i(headers));
} else {
pathResolver = ({headers}) => !ignore.find(i => i(headers));
}
}
} else if (url) {
pathResolver = ({originalUrl}) => urlStartsWith(originalUrl, url);
} else {
defaultPath = path;
}
if (pathResolver) {
addPathResolver(path, pathResolver);
}
};
const fileListeners = [];
const addFileListener = listener => fileListeners.push(listener);
const removeFileListener = listener => fileListeners.splice(fileListeners.indexOf(listener), 1);
let serveStatic;
const getServerStatic = () => {
if (!serveStatic) serveStatic = require('serve-static');
return serveStatic;
};
const registerContext = async (options, {allowAdministration} = {}) => {
if (!options) return;
const {path} = options;
if (!path) return;
const context = newContext(options, allowAdministration);
const {id} = context;
context.createLogger = filePath => createLogger(id, filePath);
context.logger = createLogger(id, '');
context.on('unregister', () => {
if (!context.unregistered) {
unregisterPath(path);
context.files['/']();
context.unregistered = true;
}
});
context.on('register', () => {
if (!context.registered) {
registerPath(options);
context.registered = true;
}
});
context.contentOf = filePathReader(path);
context.storeContent = filePathWriter(path);
const {featuresFor} = featuresForContext(context);
const {module, removeModule} = modulesForContext(context);
let staticRequest;
const getStaticRequest = () => {
if (!staticRequest) {
const serverStatic = getServerStatic()(path);
staticRequest = (req, res, next) => {
const length = options.url ? options.url.length : 0;
if (length) {
const url = req.url.substr(length);
serverStatic({...req, url}, res, next);
} else {
serverStatic(req, res, next);
}
};
}
return staticRequest;
};
context.on('modify', (changedFields) => {
if (changedFields.includes('url')) {
createContextModuleFinder(context, module, options);
}
});
context.files = await watchDirAt(path, data => {
const {newFiles, removedFiles} = data;
for (const filePath of removedFiles) {
const {paths} = getFileType(filePath);
for (const urlPath of paths) {
remove(removeModule(urlPath));
}
}
for (const filePath of newFiles) {
const fileType = getFileType(filePath);
const {paths} = fileType;
const registerModule = (logger, result, info) => {
for (const urlPath of paths) {
const existing = module(urlPath);
if (existing) {
logger.log(`re-registering module '${filePath}' at '${urlPath}'${info ? ', '+info : ''}`);
for (const key of Object.keys(existing)) {
delete existing[key];
}
Object.assign(existing, result);
} else {
logger.log(`registering module '${filePath}' at '${urlPath}'${info ? ', '+info : ''}`);
module(urlPath, result);
}
}
};
createModule(context, getStaticRequest, filePath, featuresFor, fileType, registerModule).catch(e => {
context.logger.error(`can not create module '${filePath}': ${e}`);
});
}
if (fileListeners.length) fileListeners.map(listener => listener({id, newFiles, removedFiles}));
});
createContextModuleFinder(context, module, options);
context.register();
return context;
};
const createContextModuleFinder = (context, module, options) => {
const {url} = options;
if (url) {
const {length} = url;
context.moduleAt = urlPath => module(urlPath.substr(length));
} else {
context.moduleAt = urlPath => module(urlPath);
}
};
module.exports = {getServerStatic, newContext, modifyContext, contextFor, contextForPath, getContexts, registerContext, resolveBy, addFileListener, removeFileListener, saver};