-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
856 lines (792 loc) · 30.7 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
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
/**
*
* OpenUI5 Library Utilities
* Copyright 2017 PulseShift GmbH. All rights reserved.
*
* Licensed under the MIT License.
*
*/
const gulp = require("gulp");
const gulpif = require("gulp-if");
const rename = require("gulp-rename");
const tap = require("gulp-tap");
const terser = require("gulp-terser");
const cleanCSS = require("gulp-clean-css");
const ui5preload = require("gulp-ui5-preload");
const lessOpenUI5 = require("less-openui5");
const request = require("request");
const progress = require("request-progress");
const Zip = require("adm-zip");
const fs = require("fs");
const path = require("path");
var getDirName = require('path').dirname;
// create a builder instance
const builder = new lessOpenUI5.Builder();
// export functions
module.exports = { ui5Download, ui5Build, ui5CompileLessLib };
/**
* Download OpenUI5 repository from external URL and unzip.
*
* @param {string} [sDownloadURL] Download URL of required archive.
* @param {string} [sDownloadPath] Destination path for the download archive and extracted files.
* @param {string} [sUI5Version] Version number of UI5 to create at <code>sDownloadPath</code> a subdirectory named <code>/{{sUI5Version}}</code>.
* @param {Object} [oOptions] Download options.
* @param {function(number,number,{ name: string, progress: number|null}):void} [oOptions.onProgress] Callback function to track download progress taking as params: current step number, total step number and if available, step details (object with name and progress in percent).
* @returns {Promise.string} Promise which resolves to a success or error message.
*/
function ui5Download(sDownloadURL, sDownloadPath, sUI5Version, oOptions = {}) {
// check params
if (!sDownloadURL) {
return Promise.reject("No download URL provided");
}
if (!sDownloadPath) {
return Promise.reject("No download path provided");
}
if (!sUI5Version) {
return Promise.reject("No UI5 version provided");
}
const oSteps = {
download: {
number: 1,
details: { name: "download" },
},
unzip: {
number: 2,
details: { name: "unzip" },
},
};
const iTotalSteps = Object.keys(oSteps).length;
const sTargetPath = path.join(sDownloadPath, sUI5Version);
const sSuccessMessage = `UI5 download (${sUI5Version}) already exist at ${sTargetPath}`;
const fnProgressCallback =
typeof oOptions.onProgress === "function" ? oOptions.onProgress : () => {};
// check if ui5 library was already downloaded and ectracted
return fs.existsSync(sTargetPath)
? // download is already available
Promise.resolve(sSuccessMessage)
: // download and unzip sources
new Promise((resolve, reject) => {
progress(
request.get(
sDownloadURL,
{ encoding: null },
(oError, oResponse, oData) => {
if (oError) {
// reject promise
return reject(oError);
}
// update progress information (start step 2)
const oStep = oSteps["unzip"];
fnProgressCallback(oStep.number, iTotalSteps, oStep.details);
// Do something after request finishes
const oBuffer = Buffer.from(oData, "binary");
const zip = new Zip(oBuffer);
const overwrite = true;
// extracts everything
zip.extractAllTo(sTargetPath, overwrite);
// if sap-ui-core.js is not located in extracted root,
// we will rename the download directory to 'resources'
if (!fs.existsSync(path.join(sTargetPath, "sap-ui-core.js"))) {
// read all extracted files in current directory
const aFiles = fs.readdirSync(sTargetPath);
aFiles.forEach((sFileName) => {
if (
fs.statSync(path.join(sTargetPath, sFileName)).isDirectory()
) {
// rename download folder in root
try {
fs.renameSync(
path.join(sTargetPath, sFileName),
path.join(sTargetPath, "resources")
);
} catch (e) {
// skip renaming
console.error(
`Renaming directory "${path.join(
sTargetPath,
sFileName
)}" failed: `,
e
);
}
}
});
}
// resolve promise
return resolve(`UI5 download successful: ${sTargetPath}`);
}
)
).on("progress", (oProgressDetails) => {
// update progress information
const oStep = oSteps["download"];
fnProgressCallback(
oStep.number,
iTotalSteps,
Object.assign({}, oStep.details, {
progress: oProgressDetails.percent * 100,
})
);
});
});
}
/**
* Use PulseShifts own build tools to build OpenUI5 library.
*
* @param {string} [sUI5SrcPath] Source path of the OpenUI5 source code..
* @param {string} [sUI5TargetPath] Destination path for the build library.
* @param {string} [sUI5Version] Version number of UI5 to create at <code>sUI5TargetPath</code> a subdirectory named <code>/{{sUI5Version}}</code>.
* @param {Object} [oOptions] Build options.
* @param {function(number,number,{ name: string, progress: number|null}):void} [oOptions.onProgress] Callback function to track build progress taking as params: current step number, total step number and if available, step details (object with name and progress in percent).
* @returns {Promise.string} Promise which resolves to a success or error message.
*/
function ui5Build(sUI5SrcPath, sUI5TargetPath, sUI5Version, oOptions = {}) {
// check params
if (!sUI5SrcPath) {
return Promise.reject("No UI5 source path provided");
}
if (!fs.existsSync(sUI5SrcPath)) {
return Promise.reject(`UI5 source path ${sUI5SrcPath} does not eist`);
}
if (!sUI5TargetPath) {
return Promise.reject("No UI5 target path provided");
}
if (!sUI5Version) {
return Promise.reject("No UI5 version provided");
}
// if ui5 target location already exist, cancel to prevent unwanted overrides
if (fs.existsSync(sUI5TargetPath)) {
return Promise.resolve(
`UI5 target directory ${sUI5TargetPath} already exist. Please clean target location for rebuild (directory will be created automatically).`
);
}
const isSrcInDownloadRoot = fs.existsSync(`${sUI5SrcPath}/src`);
const isSrcInDownloadSubDir = fs
.readdirSync(sUI5SrcPath)
.some((sPath) => fs.existsSync(`${path.join(sUI5SrcPath, sPath)}/src`));
const fnProgressCallback =
typeof oOptions.onProgress === "function" ? oOptions.onProgress : () => {};
// cancel if UI5 source code location ('/src' directory) could not be found
if (!isSrcInDownloadRoot && !isSrcInDownloadSubDir) {
return Promise.reject(
`UI5 source code not found in given directory ${sUI5SrcPath}, please check if the given path contains the correct OpenUI5 source code structure.`
);
}
// update UI5 source path if '/src' directory was found in a sub directory
if (isSrcInDownloadSubDir) {
sUI5SrcPath = fs
.readdirSync(sUI5SrcPath)
.reduce(
(sFinalPath, sPath) =>
fs.existsSync(`${path.join(sUI5SrcPath, sPath)}/src`)
? path.join(sUI5SrcPath, sPath)
: sFinalPath,
sUI5SrcPath
);
}
// define steps for progress information
const oSteps = {
"read modules": { number: 1, details: { name: "read modules" } },
"copy debug resources": {
number: 2,
details: { name: "copy debug scripts" },
},
"copy minified scripts and other resources": {
number: 3,
details: { name: "minify scripts and copy resources" },
},
"compose sap-ui-*.js resources": {
number: 4,
details: { name: "compose sap-ui-*.js resources" },
},
"bundle modules": {
number: 5,
details: { name: "bundle modules" },
},
"copy themes": {
number: 6,
details: { name: "copy themes" },
},
"compile themes": {
number: 7,
details: { name: "compile themes" },
},
"post-process CSS": {
number: 8,
details: { name: "minify CSS" },
},
"compose sap-ui-version.json": {
number: 9,
details: { name: "compose sap-ui-version.json" },
},
};
const iTotalSteps = Object.keys(oSteps).length;
// initialize build time
const NOW = new Date();
const sBuildTime = NOW.toLocaleDateString("en-GB", {
weekday: "short",
year: "numeric",
month: "short",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
second: "numeric",
});
const sCopyrightBanner = `UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2017 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
* Build by PulseShift GmbH, OpenUI5 Version ${sUI5Version}, Buildtime ${sBuildTime}.`;
/*
* These modules (if defined) will be predelivered with sap-ui-core.js.
*/
const aSAPUiCorePreloadModules = [];
// modules referenced in raw sap-ui-*.js directly
let aSAPUiCoreAutoIncludedModules = [];
// found UI5 modules
let aUI5Modules = [];
// found UI5 themes
let aUI5Themes = [];
// 1. collect all module and theme paths of OpenUI5 project
const oBuildPromiseChain = new Promise((resolve, reject) => {
// update progress information
const oStep = oSteps["read modules"];
fnProgressCallback(oStep.number, iTotalSteps, oStep.details);
// read all directories in 'src'
return fs.readdir(
`${sUI5SrcPath}/src/`,
// TODO: add error message
(oError, aPaths) => (oError ? reject() : resolve(aPaths))
);
})
.then((aPaths = []) => {
// extract modules
aUI5Modules = aPaths
.filter((sSrc) => {
// filter for directories only that starts with 'sap.'
return (
fs.statSync(path.join(`${sUI5SrcPath}/src/`, sSrc)).isDirectory() &&
sSrc.startsWith("sap.")
);
})
.map((sDir) => {
// map to complete paths
return {
path: `${sUI5SrcPath}/src/${sDir}`,
targetPath: `${sUI5TargetPath}/${sDir.split(".").join("/")}`,
name: sDir,
};
});
// extract themes
aUI5Themes = aPaths
.filter((sSrc) => {
// filter for directories that only starts with 'themelib'
return (
fs.statSync(path.join(`${sUI5SrcPath}/src/`, sSrc)).isDirectory() &&
sSrc.startsWith("themelib")
);
})
.map((sDir) => `${sUI5SrcPath}/src/${sDir}`);
})
// 2. create debug resources first (rename all javascript files and copy them as debug resources)
.then(
() =>
new Promise((resolve, reject) => {
// update progress information
const oStep = oSteps["copy debug resources"];
fnProgressCallback(oStep.number, iTotalSteps, oStep.details);
return (
gulp
.src([
...aUI5Modules.map((oModule) => `${oModule.path}/src/**/*.js`),
])
// A) add -dbg suffix
.pipe(rename({ suffix: "-dbg" }))
// B) update copyright of debug resources
.pipe(
tap((oFile) =>
replaceFilePlaceholders(oFile, [
{ identifier: "${copyright}", content: sCopyrightBanner },
])
)
)
// save at target location
.pipe(gulp.dest(sUI5TargetPath))
.on("end", resolve)
.on("error", reject)
);
})
)
// 3. copy all other resources of modules in target directory and this time minify JS
.then(
() =>
new Promise((resolve, reject) => {
// update progress information
const oStep = oSteps["copy minified scripts and other resources"];
fnProgressCallback(oStep.number, iTotalSteps, oStep.details);
return (
gulp
.src([
`${sUI5SrcPath}/LICENSE.txt`,
`${sUI5SrcPath}/NOTICE.txt`,
`${sUI5SrcPath}/README.md`,
// module files
...aUI5Modules.map((oModule) => `${oModule.path}/src/**/*`),
])
// minify all JS resources
.pipe(gulpif("**/*.js", terser()))
// update copyright of library less sources
.pipe(
gulpif(
["**/library.source.less"],
tap((oFile) =>
replaceFilePlaceholders(oFile, [
{ identifier: "${copyright}", content: sCopyrightBanner },
])
)
)
)
// save at target location
.pipe(gulp.dest(sUI5TargetPath))
.on("end", resolve)
.on("error", reject)
);
})
)
// 4. build and concat sap-ui-*.js resources in target location
.then(
() =>
new Promise((resolve, reject) => {
// update progress information
const oStep = oSteps["compose sap-ui-*.js resources"];
fnProgressCallback(oStep.number, iTotalSteps, oStep.details);
return (
gulp
.src([
`${sUI5TargetPath}/sap-ui-core.js`,
`${sUI5TargetPath}/sap-ui-core-nojQuery.js`,
`${sUI5TargetPath}/sap-ui-core-dbg.js`,
`${sUI5TargetPath}/sap-ui-core-nojQuery-dbg.js`,
])
.pipe(
tap((oFile) => {
// parse scripts to include
const aRawScriptIncludes = oFile.contents
.toString("utf8")
.match(/raw:([\w\.\/_-]*)/gm);
// continue without change if no import scripts have been found
if (!aRawScriptIncludes) return oFile;
const aScriptIncludes = aRawScriptIncludes
.map((f) => f.replace("raw:", ""))
.filter((f) => f !== "");
// memorize included modules, so that we can exclude them when building library-preload for sap.ui.core
if (oFile.path.endsWith("sap-ui-core.js")) {
aSAPUiCoreAutoIncludedModules = aScriptIncludes;
}
// create include scripts content
const sIncludedRawScripts = aScriptIncludes
// add preload modules for sap-ui-core.js
.concat(aSAPUiCorePreloadModules)
// request debug resources, if sap-ui-*-dbg is called
.map((f) =>
oFile.path.endsWith("-dbg.js")
? f.replace(".js", "-dbg.js")
: f
)
// read file
.map((sScriptPath) =>
fs.readFileSync(
`${sUI5TargetPath}/${sScriptPath}`,
"utf8"
)
)
// replace banner
.map((sScriptContent) =>
sScriptContent.replace("${copyright}", sCopyrightBanner)
)
// join to single file content
.join("");
// HINT: sap-ui-core.js and sap-ui-core-nojQuery.js and there equivalent debug variants, will be postprocessed in target location, again
// write concatenated scripts into file
oFile.contents = Buffer.from(sIncludedRawScripts);
return oFile;
})
)
// inject file by JS footer and header
.pipe(tap((oFile) => composeSAPUiCore(oFile)))
// save at target location
.pipe(gulp.dest(sUI5TargetPath))
.on("end", resolve)
.on("error", reject)
);
})
)
// 5. create preload bundle files for all modules (except sap.ui.core, because guess why: it has special requirements) and save them at target directory
.then(() => {
// update progress information
const oStep = oSteps["bundle modules"];
fnProgressCallback(oStep.number, iTotalSteps, oStep.details);
return Promise.all(
aUI5Modules
.filter((oModule) => oModule.name !== "sap.ui.core")
.map(
(oModule) =>
new Promise((resolve, reject) =>
gulp
.src([
`${oModule.targetPath}/**/*.js`,
`!${oModule.targetPath}/**/library-preload.js`,
// don't bundle debug resources
`!${oModule.targetPath}/**/*-dbg.js`,
// exclude modules that are already bundled in sap-ui-core.js
...aSAPUiCoreAutoIncludedModules
.concat(aSAPUiCorePreloadModules)
.map((sModule) => `!${sUI5TargetPath}/${sModule}.js`),
])
// TODO: tap into library.js files to customize ui5 bundle
// create library-preload.json
.pipe(
ui5preload({
base: oModule.targetPath,
namespace: oModule.name,
isLibrary: true, // if set to true a library-preload.json file is emitted instead of a Component-preload.js file (default)
})
)
// transform all library-preload.json files to transform all library-preload.js (mandatory since OpenUI5 1.40)
.pipe(
gulpif(
"**/library-preload.json",
tap((oFile) => transformPreloadJSON(oFile))
)
)
.pipe(
gulpif(
"**/library-preload.json",
rename({ extname: ".js" })
)
)
// save directly in target location
.pipe(gulp.dest(oModule.targetPath))
.on("end", resolve)
.on("error", reject)
) // end Promise
)
);
}) // end Promise.all
// 6. now create preload bundle files sap.ui.core, too
.then(
() =>
new Promise((resolve, reject) =>
gulp
.src([
`${sUI5TargetPath}/jquery.sap.*.js`,
`${sUI5TargetPath}/sap/ui/Global.js`,
`${sUI5TargetPath}/sap/ui/base/**/*.js`,
`${sUI5TargetPath}/sap/ui/core/**/*.js`,
`${sUI5TargetPath}/sap/ui/model/**/*.js`,
`!${sUI5TargetPath}/**/library-preload.js`,
// don't bundle debug resources
`!${sUI5TargetPath}/**/*-dbg.js`,
// exclude modules that are already bundled in sap-ui-core.js
...aSAPUiCoreAutoIncludedModules
.concat(aSAPUiCorePreloadModules)
.map((sModule) => `!${sUI5TargetPath}/${sModule}.js`),
])
// TODO: tap into library.js files to customize ui5 bundle
// create library-preload.json
.pipe(
ui5preload({
base: sUI5TargetPath,
namespace: "",
isLibrary: true, // if set to true a library-preload.json file is emitted instead of a Component-preload.js file (default)
})
)
// transform all library-preload.json files to transform all library-preload.js (mandatory since OpenUI5 1.40)
.pipe(
gulpif(
"**/library-preload.json",
tap((oFile) => transformPreloadJSON(oFile))
)
)
.pipe(gulpif("**/library-preload.json", rename({ extname: ".js" })))
// save directly in target location
.pipe(gulp.dest(`${sUI5TargetPath}/sap/ui/core`))
.on("end", resolve)
.on("error", reject)
)
)
// NOW WE START TO UPDATE ALL THEME RESOURCES
// 7. copy all themes into theme target path
.then(
() =>
new Promise((resolve, reject) => {
// update progress information
const oStep = oSteps["copy themes"];
fnProgressCallback(oStep.number, iTotalSteps, oStep.details);
return (
gulp
.src([
// copy UI5 theme libraries (e.g. sap_belize, sap_bluecrystal, etc.)
...aUI5Themes.map((sThemePath) => `${sThemePath}/src/**/*`),
// copy UI5 base and high contrast theme from module paths
...aUI5Modules.map(
(oModule) => `${oModule.path}/src/**/themes/**/*`
),
])
// update path of base and high contrast theme
.pipe(
rename((path) => {
// normal path: sap/m/themes/sap_belize
// update path: sap.m/src/sap/m/themes/base => sap/m/themes/base
const aPathChain = path.dirname.split(path.sep);
path.dirname =
aPathChain.length > 1 && aPathChain[1] === "src"
? aPathChain.slice(2, aPathChain.length - 1).join("/")
: path.dirname;
})
)
// update copyright of library less sources
.pipe(
gulpif(
"**/library.source.less",
tap((oFile) =>
replaceFilePlaceholders(oFile, [
{ identifier: "${copyright}", content: sCopyrightBanner },
])
)
)
)
// save at target location
.pipe(gulp.dest(sUI5TargetPath))
.on("end", resolve)
.on("error", reject)
);
})
)
// 8. build css libraries for all themes of all modules
.then(
() =>
new Promise((resolve, reject) => {
// update progress information
const oStep = oSteps["compile themes"];
fnProgressCallback(oStep.number, iTotalSteps, oStep.details);
return (
gulp
.src([`${sUI5TargetPath}/**/themes/**/library.source.less`])
// create library.css
.pipe(
tap((oFile) => {
// TODO: tap into library.source.less files to customize ui5 bundle
ui5CompileLessLib(oFile);
})
)
// save at target location
.pipe(gulp.dest(sUI5TargetPath))
.on("end", resolve)
.on("error", reject)
);
})
)
// 9. minify and clean up css resources
.then(
() =>
new Promise((resolve, reject) => {
// update progress information
const oStep = oSteps["post-process CSS"];
fnProgressCallback(oStep.number, iTotalSteps, oStep.details);
return (
gulp
.src([`${sUI5TargetPath}/**/*.css`])
// minify CSS as much as possible
.pipe(
cleanCSS({
inline: ["none"],
level: 2,
})
)
// save at target location
.pipe(gulp.dest(sUI5TargetPath))
.on("end", resolve)
.on("error", reject)
);
})
)
// 10. [FINAL STEP] last but not least: write sap-ui-version.json
.then(
() =>
new Promise((resolve, reject) => {
// update progress information
const oStep = oSteps["compose sap-ui-version.json"];
fnProgressCallback(oStep.number, iTotalSteps, oStep.details);
const oVersionJSON = {
buildTimestamp: sBuildTime,
name: "openui5-sdk-dist-pulseshift-custom",
version: sUI5Version,
librares: aUI5Modules.map((oModule) => ({
buildTimestamp: sBuildTime,
name: oModule.name,
version: sUI5Version,
})),
};
const sVersionJSONString = JSON.stringify(oVersionJSON, null, 2);
const sSuccessMessage = `UI5 build successful: ${sUI5Version}`;
// write JSON file
fs.writeFile(
`${sUI5TargetPath}/sap-ui-version.json`,
sVersionJSONString,
(oError) => (oError ? reject() : resolve(sSuccessMessage))
);
})
);
// return promise
return oBuildPromiseChain;
}
/**
* Compile library.source.less and dependencies to library.css.
*
* @param {Vinyl} [oFile] Vinyl file object of library.source.less.
* @returns {Promise} Promise.
*/
function ui5CompileLessLib(oFile) {
const sDestDir = path.dirname(oFile.path);
const sFileName = oFile.path.split(path.sep).pop();
const sLessFileContent = oFile.contents.toString("utf8");
// options for less-openui5
const oOptions = {
lessInput: sLessFileContent,
rootPaths: [sDestDir],
rtl: true,
parser: {
filename: sFileName,
paths: [sDestDir],
},
compiler: { compress: false },
};
// build a theme
const oBuildThemePromise = builder
.build(oOptions)
.catch((oError) => {
// CSS build fails in 99% of all cases, because of a missing .less file
// create empty LESS file and try again if build failed
// try to parse error message to find out which missing LESS file caused the failed build
// console.log('-----')
// console.log('oError.message', oError.message)
const sMissingFileName = (oError.message.match(
/((\.*?\/?)*\w.*\.\w+)/g
) || [""])[0];
const sSourceFileName = oError.filename;
const sMissingFilePath = path.resolve(
sDestDir,
sSourceFileName.replace("library.source.less", ""),
sMissingFileName
);
// console.log('sMissingFileName', sMissingFileName)
// console.log('sMissingFilePath', sMissingFilePath)
let isIssueFixed = false;
// create missing .less file (with empty content), else the library.css can't be created
if (!fs.existsSync(sMissingFilePath)) {
try {
if(!fs.existsSync(getDirName(sMissingFilePath))) {
fs.mkdirSync(getDirName(sMissingFilePath), { recursive: true})
}
fs.writeFileSync(sMissingFilePath, "");
isIssueFixed = true;
} catch (e) {
// console.log('Error writng missing file: ', e)
isIssueFixed = false;
}
}
// console.log('isIssueFixed', isIssueFixed)
// console.log('-----')
if (!isIssueFixed) {
// if this error message raises up, the build failed due to the other 1% cases
return Promise.reject("Compile UI5 less lib: " + (oError.message || oError));
}
// if missing file could be created, try theme build again
return isIssueFixed ? ui5CompileLessLib(oFile) : Promise.reject();
})
.then((oResult) => {
// build css content was successful >> save result
const aTargetFiles = [
{
path: `${sDestDir}/library.css`,
content: oResult.css,
},
{
path: `${sDestDir}/library-RTL.css`,
content: oResult.cssRtl,
},
{
path: `${sDestDir}/library-parameters.json`,
content:
JSON.stringify(
oResult.variables,
null,
oOptions.compiler.compress ? 0 : 4
) || "",
},
];
const aWriteFilesPromises = aTargetFiles.map((oFile) => {
return new Promise((resolve, reject) =>
fs.writeFile(oFile.path, oFile.content, (oError) =>
oError ? reject() : resolve()
)
);
});
// return promise
return Promise.all(aWriteFilesPromises);
})
.then(() => {
// clear builder cache when finished to cleanup memory
builder.clearCache();
return Promise.resolve();
});
return oBuildThemePromise;
}
/**
* Transform library-preload.json content.
*
* @param {Vinyl} [oFile] Vinyl file object of library-preload.json.
* @returns {Vinyl} Transformed library-preload.json.
*/
function transformPreloadJSON(oFile) {
const oJSONRaw = oFile.contents.toString("utf8");
const sPrelaodJSON = `jQuery.sap.registerPreloadedModules(${oJSONRaw});`;
oFile.contents = Buffer.from(sPrelaodJSON);
return oFile;
}
// replace a list of placeholders with a list of string contents
function replaceFilePlaceholders(oFile, aReplacementRules) {
// parse file
const sRaw = oFile.contents.toString("utf8");
const sUpdatedFile = aReplacementRules.reduce((oResult, oRule) => {
return oResult.replace(oRule.identifier, oRule.content);
}, sRaw);
// update new raw content
oFile.contents = Buffer.from(sUpdatedFile);
// return updated file
return oFile;
}
/**
* Compose sap-ui-*.js files.
*
* @param {Vinyl} [oFile] Vinyl file object sap-ui-*.js.
* @returns {Vinyl} Composed sap-ui-*.js file.
*/
function composeSAPUiCore(oFile) {
// parse sap-ui-*.js file
const sRaw = oFile.contents.toString("utf8");
// footer used in original OpenUI5 builds
const sComposedCore = oFile.path.endsWith("-dbg.js")
? `${sRaw}
if (!window["sap-ui-debug"]) { sap.ui.requireSync("sap/ui/core/library-preload"); }
sap.ui.requireSync("sap/ui/core/Core");
sap.ui.getCore().boot && sap.ui.getCore().boot();`
: `window["sap-ui-optimized"] = true;
${sRaw}
if (!window["sap-ui-debug"]) { sap.ui.requireSync("sap/ui/core/library-preload"); }
sap.ui.requireSync("sap/ui/core/Core");
sap.ui.getCore().boot && sap.ui.getCore().boot();`;
// update new raw content
oFile.contents = Buffer.from(sComposedCore);
// return updated file
return oFile;
}