forked from SAP-archive/karma-ui5
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathframework.js
More file actions
496 lines (430 loc) · 15 KB
/
Copy pathframework.js
File metadata and controls
496 lines (430 loc) · 15 KB
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
const normalizer = require("@ui5/project").normalizer;
const ui5Fs = require("@ui5/fs");
const resourceFactory = ui5Fs.resourceFactory;
const ReaderCollectionPrioritized = ui5Fs.ReaderCollectionPrioritized;
const httpProxy = require("http-proxy");
const fs = require("fs");
const path = require("path");
const yaml = require("js-yaml");
const stat = fs.statSync;
const {ErrorMessage} = require("./errors");
class Framework {
constructor() {
this.isPaused = true;
this.queue = [];
this._serveResources = null;
this._serveThemes = null;
this.config = {};
}
createPluginFilesPattern(pattern) {
return {pattern, included: true, served: true, watched: false};
}
createProjectFilesPattern(pattern) {
return {pattern, included: false, served: true, watched: true};
}
/**
* Checks if a list of paths exists
*
* @private
* @param {Array} paths List of paths to check
*
* @returns {boolean[]} array if path exist
*/
pathsExist(paths) {
return paths.map((folderName) => this.exists(path.join(this.config.basePath, folderName)));
}
/**
* Checks if a file or path exists
*
* @private
* @param {string} filePath Path to check
* @returns {boolean} true if the file or path exists
*/
exists(filePath) {
try {
return stat(filePath).isDirectory();
} catch (err) {
// "File or directory does not exist"
if (err.code === "ENOENT") {
return false;
} else {
throw err;
}
}
}
/**
* Mutates config and auto set type if not defined
*/
detectTypeFromFolder() {
const webappFolder = this.config.ui5.paths.webapp;
const srcFolder = this.config.ui5.paths.src;
const testFolder = this.config.ui5.paths.test;
const [hasWebapp, hasSrc, hasTest] = this.pathsExist([webappFolder, srcFolder, testFolder]);
if (hasWebapp) return "application";
if (hasSrc && hasTest) return "library";
}
replaceLast(path, replacement) {
return path.split("/").slice(0, -1).concat(replacement).join("/");
}
checkLegacy(config) {
if (config.openui5 || config.client.openui5) {
this.logger.log("error", ErrorMessage.migrateConfig());
throw new Error(ErrorMessage.failure());
}
}
initScriptMode(config) {
let url;
if (config.ui5.url) {
url = config.ui5.url + "/resources/sap-ui-core.js";
} else {
// Uses middleware if no url has been specified
// Need to use an absolute URL as the file doesn't exist physically but will be
// resolved via our middleware
url = `${config.protocol}//${config.hostname}:${config.port}/base/`;
if (config.ui5.type === "application") {
url += `${config.ui5.paths.webapp}/resources/sap-ui-core.js`;
} else if (config.ui5.type === "library") {
url += `${this.replaceLast(config.ui5.paths.src, "resources")}/sap-ui-core.js`;
}
}
config.client.ui5.config = config.ui5.config;
config.client.ui5.tests = config.ui5.tests;
if (config.ui5.tests) {
config.files.unshift(this.createPluginFilesPattern(`${__dirname}/client/autorun.js`));
}
config.files.unshift(this.createPluginFilesPattern(url));
config.files.unshift(this.createPluginFilesPattern(`${__dirname}/client/sap-ui-config.js`));
}
async init({config, logger}) {
this.config = config;
this.logger = logger.create("ui5.framework");
this.config.basePath = config.basePath || "";
this.config.client = config.client || {};
this.config.client.clearContext = false;
// Always override client ui5 config. It should not be used by consumers.
// Relevant options (e.g. testpage, config, tests) will be written to the client section.
this.config.client.ui5 = {};
this.config.client.ui5.useIframe = true; // for now only allow using iframes in HTML mode
this.config.client.ui5.logAssertions = config.ui5 && config.ui5.logAssertions || false;
this.config.ui5 = config.ui5 || {};
this.config.proxies = config.proxies || {};
this.config.middleware = config.middleware || [];
this.config.files = config.files || [];
this.config.beforeMiddleware = config.beforeMiddleware || [];
if (!this.config.ui5.mode) {
this.config.ui5.mode = "html";
}
this.checkLegacy(config);
if (this.config.ui5.mode && ["script", "html"].indexOf(this.config.ui5.mode) === -1) {
this.logger.log("error", ErrorMessage.invalidMode(this.config.ui5.mode));
throw new Error(ErrorMessage.failure());
}
const blacklistedFrameworks = ["qunit", "sinon"];
const hasBlacklistedFrameworks = (frameworks) => frameworks.some((fwk) => blacklistedFrameworks.includes(fwk));
if (this.config.ui5.mode === "html" && hasBlacklistedFrameworks(this.config.frameworks || [])) {
this.logger.log("error", ErrorMessage.blacklistedFrameworks(this.config.frameworks) );
throw new Error(ErrorMessage.failure());
}
if (this.config.ui5.mode === "html" && this.config.files.length > 0) {
this.logger.log("error", ErrorMessage.containsFilesDefinition() );
throw new Error(ErrorMessage.failure());
}
if (this.config.ui5.paths && !this.config.ui5.type) {
this.logger.log("error", ErrorMessage.customPathWithoutType() );
throw new Error(ErrorMessage.failure());
}
if (this.config.ui5.mode !== "html" && this.config.ui5.urlParameters) {
this.logger.log("error", ErrorMessage.urlParametersConfigInNonHtmlMode(this.config.ui5.mode,
this.config.ui5.urlParameters));
throw new Error(ErrorMessage.failure());
}
if (this.config.ui5.urlParameters !== undefined && !Array.isArray(this.config.ui5.urlParameters)) {
this.logger.log("error", ErrorMessage.urlParametersNotAnArray(this.config.ui5.urlParameters));
throw new Error(ErrorMessage.failure());
}
if (this.config.ui5.urlParameters) {
this.config.ui5.urlParameters.forEach((urlParameter) => {
if (typeof urlParameter !== "object") {
this.logger.log("error", ErrorMessage.urlParameterNotObject(urlParameter));
throw new Error(ErrorMessage.failure());
}
if (urlParameter.key === undefined || urlParameter.value === undefined) {
this.logger.log("error", ErrorMessage.urlParameterMissingKeyOrValue(urlParameter));
throw new Error(ErrorMessage.failure());
}
});
}
this.config.ui5.paths = this.config.ui5.paths || {
webapp: "webapp",
src: "src",
test: "test"
};
["webapp", "src", "test"].forEach((pathName) => {
let pathValue = this.config.ui5.paths[pathName];
if (!pathValue) {
return;
}
let absolutePathValue;
const absoluteBasePath = path.resolve(this.config.basePath);
// Make sure paths are relative to the basePath
if (path.isAbsolute(pathValue)) {
absolutePathValue = pathValue;
pathValue = path.relative(this.config.basePath, pathValue);
} else {
absolutePathValue = path.resolve(this.config.basePath, pathValue);
}
// Paths must be within basePath
if (!absolutePathValue.startsWith(absoluteBasePath)) {
this.logger.log("error", ErrorMessage.pathNotWithinBasePath({
pathName,
pathValue: this.config.ui5.paths[pathName], // use value given in config here
absolutePathValue,
basePath: absoluteBasePath
}));
throw new Error(ErrorMessage.failure());
}
this.config.ui5.paths[pathName] = pathValue;
});
this.autoDetectType();
if (this.config.ui5.mode === "script") {
this.initScriptMode(config);
} else {
// Add browser bundle including third-party dependencies
this.config.files.unshift(this.createPluginFilesPattern(__dirname + "/../dist/browser-bundle.js"));
}
// Make testpage url available to the client
this.config.client.ui5.testpage = this.config.ui5.testpage;
// Pass configured urlParameters to client
this.config.client.ui5.urlParameters = this.config.ui5.urlParameters;
if (this.config.ui5.type === "application") {
const webappFolder = this.config.ui5.paths.webapp;
if (!this.exists(path.join(this.config.basePath, webappFolder))) {
this.logger.log("error", ErrorMessage.applicationFolderNotFound(webappFolder));
throw new Error(ErrorMessage.failure());
}
// Match all files (including dotfiles)
this.config.files.push(
this.createProjectFilesPattern(config.basePath + `/{${webappFolder}/**,${webappFolder}/**/.*}`)
);
// No proxy required here, local files will be loaded via karma first
} else if (config.ui5.type === "library") {
const srcFolder = this.config.ui5.paths.src;
const testFolder = this.config.ui5.paths.test;
const [hasSrc, hasTest] = this.pathsExist([srcFolder, testFolder]);
if (!hasSrc || !hasTest) {
this.logger.log("error", ErrorMessage.libraryFolderNotFound({
srcFolder, testFolder, hasSrc, hasTest
}));
throw new Error(ErrorMessage.failure());
}
this.config.files.push(
// Match all files (including dotfiles)
this.createProjectFilesPattern(`${config.basePath}/{${srcFolder}/**,${srcFolder}/**/.*}`),
this.createProjectFilesPattern(`${config.basePath}/{${testFolder}/**,${testFolder}/**/.*}`),
);
// Configure proxies to first load files from karma server (e.g. library under test)
// Otherwise the coverage reporting won't work
this.config.proxies[`/base/${this.replaceLast(srcFolder, "resources")}/`] = `/base/${srcFolder}/`;
this.config.proxies[`/base/${this.replaceLast(srcFolder, "test-resources")}/`] = `/base/${testFolder}/`;
this.config.proxies[`/base/${this.replaceLast(testFolder, "resources")}/`] = `/base/${srcFolder}/`;
this.config.proxies[`/base/${this.replaceLast(testFolder, "test-resources")}/`] = `/base/${testFolder}/`;
} else {
this.logger.log("error", ErrorMessage.invalidProjectType(config.ui5.type) );
throw new Error(ErrorMessage.failure());
}
// this.addPreprocessor();
await this.setupMiddleware();
return this;
}
autoDetectType() {
if (this.config.ui5.type) {
return;
}
const filePath = path.join(this.config.basePath, "ui5.yaml");
let fileContent;
try {
fileContent = fs.readFileSync(filePath);
} catch (err) {
if (err.code !== "ENOENT") {
throw err;
}
}
if (fileContent) {
let configs;
try {
configs = yaml.safeLoadAll(fileContent, {
filename: filePath
});
} catch (err) {
if (err.name === "YAMLException") {
this.logger.log("error", ErrorMessage.invalidUI5Yaml({
filePath, yamlException: err
}));
throw Error(ErrorMessage.failure());
} else {
throw err;
}
}
if (!configs[0] || !configs[0].type) {
this.logger.log("error", ErrorMessage.missingTypeInYaml());
throw Error(ErrorMessage.failure());
}
this.config.ui5.type = configs[0].type;
} else {
this.config.ui5.type = this.detectTypeFromFolder();
}
if (!this.config.ui5.type) {
let errorText = "";
if (this.config.basePath.endsWith("/webapp")) {
errorText = ErrorMessage.invalidBasePath();
} else {
errorText = ErrorMessage.invalidFolderStructure();
}
this.logger.log("error", errorText);
throw new Error(ErrorMessage.failure());
}
}
// Adding coverage preprocessor is currently not supported
// /**
// * Adds preprocessors dynamically in case if no preprocessors have been defined in the config
// */
// addPreprocessor() {
// const type = this.config.ui5.type,
// cwd = process.cwd(),
// srcFolder = this.config.ui5.paths.src,
// webappFolder = this.config.ui5.paths.webapp;
// if (this.config.preprocessors && type && Object.keys(this.config.preprocessors).length === 0) {
// if (type === "library") {
// this.config.preprocessors[`${cwd}/${srcFolder}/**/*.js`] = ['coverage'];
// } else if (type === "application") {
// this.config.preprocessors[`${cwd}/{${webappFolder},${webappFolder}/!(test)}/*.js`] = ['coverage'];
// }
// }
// }
rewriteUrl(url) {
const type = this.config.ui5.type;
const webappFolder = this.config.ui5.paths.webapp;
const srcFolder = this.config.ui5.paths.src;
const testFolder = this.config.ui5.paths.test;
if (!type) {
// TODO: do we want no type to be allowed?
return url;
} else if (type === "application") {
const webappPattern = new RegExp(`^/base/${webappFolder}/`);
if (webappPattern.test(url)) {
return url.replace(webappPattern, "/");
}
} else if (type === "library") {
const srcPattern = new RegExp(`^/base/${srcFolder}/`);
const testPattern = new RegExp(`^/base/${testFolder}/`);
// const basePattern = /^\/base\//; // TODO: is this expected?
if (srcPattern.test(url)) {
return url.replace(srcPattern, "/resources/");
} else if (testPattern.test(url)) {
return url.replace(testPattern, "/test-resources/");
} /* else if (basePattern.test(url)) {
return url.replace(basePattern, "/");
}*/
} else {
this.logger.log("error", ErrorMessage.urlRewriteFailed(type));
return;
}
return url;
}
processRequests() {
this.isPaused = false;
this.queue.forEach(function(next) {
next();
});
this.queue = [];
}
pauseRequests() {
return (req, res, next) => {
if (this.isPaused) {
this.queue.push(next);
} else {
next();
}
};
}
async setupUI5Server({basePath, configPath}) {
const normalizerOptions = {
cwd: basePath
};
if (configPath) {
normalizerOptions.configPath = path.resolve(basePath, configPath);
}
const tree = await normalizer.generateProjectTree(normalizerOptions);
const projectResourceCollections = resourceFactory.createCollectionsForTree(tree);
const workspace = resourceFactory.createWorkspace({
reader: projectResourceCollections.source,
name: tree.metadata.name
});
const all = new ReaderCollectionPrioritized({
name: "server - prioritize workspace over dependencies",
readers: [workspace, projectResourceCollections.dependencies]
});
const resources = {
rootProject: projectResourceCollections.source,
dependencies: projectResourceCollections.dependencies,
all
};
// eslint-disable-next-line new-cap
const router = require("express").Router();
// TODO: rework ui5-server API and make public
const MiddlewareManager = require("@ui5/server/lib/middleware/MiddlewareManager");
const middlewareManager = new MiddlewareManager({
tree,
resources
});
await middlewareManager.applyMiddleware(router);
return {
serveResources: router
};
}
setupProxy({url}) {
const proxy = httpProxy.createProxyServer({
target: url,
changeOrigin: true
});
return {
serveResources: (req, res, next) => proxy.web(req, res, next),
serveThemes: undefined
};
}
async setupMiddleware() {
const config = this.config;
let server = {
serveResources: undefined,
serveThemes: undefined
};
if (config.ui5.url) {
config.middleware.push("ui5--serveResources");
server = await this.setupProxy(config.ui5);
} else if (config.ui5.useMiddleware !== false) {
config.beforeMiddleware.push("ui5--pauseRequests");
config.middleware.push("ui5--serveResources");
// config.middleware.push("ui5--serveThemes");
server = await this.setupUI5Server({
basePath: config.basePath,
configPath: config.ui5.configPath
});
}
this._serveResources = server.serveResources;
this._serveThemes = server.serveThemes;
this.processRequests();
return this;
}
serveResources() {
return (req, res, next) => {
req.url = this.rewriteUrl(req.url);
this._serveResources(req, res, next);
};
}
serveThemes() {
return (req, res, next) => {
this._serveThemes(req, res, next);
};
}
}
module.exports = Framework;