-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgulpfile.babel.js
2212 lines (2042 loc) · 64.5 KB
/
gulpfile.babel.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
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* @flow */
/* eslint-env node */
/**
*
* Copyright 2017 PulseShift GmbH. All rights reserved.
*
* Licensed under the MIT License.
*
* This file makes use of new JavaScript features.
* Babel handles this without us having to do anything. It just works.
* You can read more about the new JavaScript features here:
* https://babeljs.io/docs/learn-es2015/
*
*/
import pkg from './package.json'
import gulp from 'gulp'
import gutil from 'gulp-util'
import gulpif from 'gulp-if'
import rename from 'gulp-rename'
import plumber from 'gulp-plumber'
import babel from 'gulp-babel'
import uglify from 'gulp-uglify'
import htmlmin from 'gulp-htmlmin'
import prettydata from 'gulp-pretty-data'
import imagemin from 'gulp-imagemin'
import cleanCSS from 'gulp-clean-css'
import less from 'gulp-less'
import tap from 'gulp-tap'
import order from 'gulp-order'
import touch from 'gulp-touch-cmd'
import sourcemaps from 'gulp-sourcemaps'
import ui5preload from 'gulp-ui5-preload'
import mainNpmFiles from 'gulp-main-npm-files'
import ui5Bust from 'ui5-cache-buster'
import {ui5Build, ui5CompileLessLib} from 'ui5-lib-util'
import browserify from 'browserify'
import source from 'vinyl-source-stream'
import buffer from 'vinyl-buffer'
import babelify from 'babelify'
import LessAutoprefix from 'less-plugin-autoprefix'
import ora from 'ora'
import del from 'del'
import path from 'path'
import fs from 'fs'
import handlebars from 'handlebars'
import gulpHandlebars from 'gulp-handlebars-html'
// import favicons from 'gulp-favicons'
import gzip from 'gulp-gzip'
import brotli from 'gulp-brotli'
import yargs from 'yargs'
import {hideBin} from 'yargs/helpers'
/*
* SETUP SCRIPT RUNTIME ENVIRONMENT
*/
// parse program commands
const options = yargs(hideBin(process.argv))
.option('silent', {
type: 'boolean',
default: true,
description: 'Run w/ reduced logging',
})
.option('local', {
type: 'boolean',
default: true,
description: 'Start an own HTTP server, serving the build output',
}).argv
const hdlbars = gulpHandlebars(handlebars)
const spinner = ora()
// register handlebars helper function
handlebars.registerHelper('secure', function(str) {
return new handlebars.SafeString(str)
})
// switch between gulp log and custom log
spinner.enabled = options.silent
spinner.print = sText =>
spinner.stopAndPersist({
text: sText
})
/*
* CONFIGURATION
*/
const IS_DEV_MODE = process.env.NODE_ENV === 'development'
// path to source directory
const SRC = 'src'
// path to development directory
const DEV = 'dev'
// path to ditribution direcory
const DIST = 'dist'
// path to ui5 repository
const UI5 = IS_DEV_MODE ? 'ui5' : `${DIST}/ui5`
// create unique hash for current favicon image
// const isFaviconDefined =
// pkg.favicon && pkg.favicon.src.length > 0 && fs.existsSync(pkg.favicon.src)
// const FAVICON_HASH = isFaviconDefined //TODO:get rid? Favicons NOT in root seesm to be an anit pattern? https://stackoverflow.com/questions/5273103/any-problems-with-favicons-in-a-subfolder
// ? require('loader-utils')
// .getHashDigest(
// Buffer.concat([fs.readFileSync(pkg.favicon.src)]),
// 'sha512',
// 'base62',
// 8
// )
// .toLowerCase()
// : ''
// read build settings
const BUILD = {
cacheBuster: pkg.ui5.build && pkg.ui5.build.cacheBuster === true,
compression: pkg.ui5.build && pkg.ui5.build.compression !== false,
compressionGzip:
pkg.ui5.build &&
(pkg.ui5.build.compression === true ||
[].concat(pkg.ui5.build.compression).includes('gzip')),
compressionBrotli:
pkg.ui5.build &&
(pkg.ui5.build.compression === true ||
[].concat(pkg.ui5.build.compression).includes('brotli'))
}
// helper array function
const noPrebuild = oModule => oModule.prebuild !== true
const mapExternalModulePath = oModule => ({
...oModule,
path: oModule.path.replace(/^\/?node_modules/, `${SRC}/node_modules`)
})
// read modules
const UI5_APPS = (pkg.ui5.apps || []).map(mapExternalModulePath)
const UI5_LIBS = (pkg.ui5.libraries || []).map(mapExternalModulePath)
const UI5_THEMES = (pkg.ui5.themes || []).map(mapExternalModulePath)
const NON_UI5_ASSETS = (pkg.ui5.assets || []).map(mapExternalModulePath)
const UI5_ROOTS = []
.concat(UI5_APPS)
.concat(UI5_THEMES)
.concat(UI5_LIBS)
.concat(NON_UI5_ASSETS)
// target directory of plain npm dependencies
const NPM_MODULES_TARGET = pkg.ui5.vendor || {
name: '',
path: ''
}
// identify ui5 modules loaded as devDependency
const NPM_UI5_LIBS = (pkg.ui5.libraries || []).filter(oModule =>
oModule.path.startsWith('node_modules')
)
const NPM_UI5_MODULES = []
.concat(pkg.ui5.apps || [])
.concat(pkg.ui5.themes || [])
.concat(pkg.ui5.libraries || [])
.concat(pkg.ui5.assets || [])
.filter(oModule => oModule.path.startsWith('node_modules'))
const THEMES = [
'base',
'psmaterial',
'sap_belize',
'sap_belize_hcb',
'sap_belize_hcw',
'sap_belize_plus',
'sap_bluecrystal',
'sap_goldreflection',
'sap_hcb'
]
const TARGET_THEME = pkg.ui5.theme || 'sap_belize'
// paths used in our app
const paths = {
entry: {
src: [pkg.main]
},
assets: {
src: UI5_ROOTS.filter(noPrebuild)
.reduce(
(aSrc, oModule) =>
aSrc.concat([
`${oModule.path}/**/*.properties`,
`${oModule.path}/**/*.json`,
`${oModule.path}/**/*.{xml,html}`,
`${oModule.path}/**/*.css`,
`${oModule.path}/**/*.{jpg,jpeg,png,svg,ico}`,
`${oModule.path}/**/*.{woff,woff2,eot,ttf}`
]),
[]
)
// take into account .js files only for asset roots
.concat(NON_UI5_ASSETS.map(oAsset => `${oAsset.path}/**/*.js`))
},
scripts: {
src: UI5_APPS.filter(noPrebuild)
.concat(UI5_LIBS)
.map(oModule => `${oModule.path}/**/*.js`)
},
appStyles: {
src: UI5_APPS.concat(NON_UI5_ASSETS).map(
oModule => `${oModule.path}/**/*.less`
)
},
libStyles: {
src: UI5_LIBS.filter(noPrebuild).map(
oLibrary => `${oLibrary.path}/**/*.less`
)
},
themeStyles: {
src: UI5_THEMES.filter(noPrebuild).map(oTheme => `${oTheme.path}/**/*.less`)
},
htmlEntries: {
// this should be the result file of task 'entryDist'
src: [`${DIST}/index.html`]
}
}
/**
* Gulp 'start' task (development mode).
* @description Call update and start file watcher.
* @public
*/
const start = gulp.series(
logStart,
cleanDev,
// favicon,
gulp.parallel(prepareOpenUI5, loadDependencies),
gulp.parallel(copyUi5Theme, copyUi5LibraryThemes),
gulp.parallel(
entry,
assets,
scripts,
ui5AppStyles,
ui5LibStyles,
ui5ThemeStyles
),
gulp.parallel(logStats, updateVersion),
watch
)
// log start message and start spinner
function logStart(done) {
spinner.print(' ')
spinner.start('Start development server...')
done()
}
// log common statistics
function logStatsCommons() {
// const sSourceID = pkg.ui5.src
// const oSource = pkg.ui5.srcLinks[sSourceID]
const sUI5Version = getUI5Version()
// const sOnlineUI5State =
// !oSource.isArchive && oSource.isPrebuild ? '(remote)' : ''
// const sUI5Details = !oSource.isPrebuild ? '(custom build)' : sOnlineUI5State
const iApps = UI5_APPS.length
const iThemes = UI5_THEMES.length
const iLibs = UI5_LIBS.length
const sVendorLibsPath = NPM_MODULES_TARGET.path
const aVendorLibs = allExplicitDependencies()
if (aVendorLibs.length > 0) {
spinner.print(' ')
spinner.succeed(
`Dependencies (vendor libraries) loaded into: ${sVendorLibsPath}`
)
aVendorLibs.forEach(sEntry => {
const sModuleName = sEntry.split('/node_modules/')[1].split('/')[0]
spinner.print(`• ${sModuleName} as ${getExposedModuleName(sModuleName)}`)
})
}
// print success message
spinner.print(' ')
spinner.succeed(`UI5 Version: ${sUI5Version}`).print(' ')
spinner
.succeed('UI5 assets created:')
.print(`• ${iApps} app${iApps !== 1 ? 's' : ''}`)
.print(`• ${iThemes} theme${iThemes !== 1 ? 's' : ''}`)
.print(`• ${iLibs} librar${iLibs !== 1 ? 'ies' : 'y'}`)
.print(' ')
}
// log start statistics and stop spinner
function logStats(done) {
// print success message
spinner.succeed(
'Development server started, use Ctrl+C to stop and go back to the console...'
)
logStatsCommons()
done()
}
export default start
/**
* Gulp 'build' task (distribution mode).
* @description Build the complete app to run in production environment.
* @public
*/
const build = gulp.series(
logStartDist,
cleanDist,
// favicon,
gulp.parallel(
//gulp.series(prepareOpenUI5, buildOpenUI5),
gulp.series(prepareOpenUI5),
loadDependenciesDist
),
gulp.parallel(copyUi5Theme, copyUi5LibraryThemes),
gulp.parallel(
entryDist,
assetsDist,
scriptsDist,
ui5AppStylesDist,
ui5LibStylesDist,
ui5ThemeStylesDist
),
gulp.parallel(ui5preloads, ui5LibPreloads),
gulp.parallel(ui5cacheBust),
gulp.parallel(preCompressionGzip, preCompressionBrotli),
logStatsDist
)
const buildErrorHandler = {
errorHandler: error => {
// print error
spinner.fail(error)
// exit gulp
throw error
}
}
// log start build message and start spinner
function logStartDist(done) {
spinner.print(' ')
spinner.start('Build start...')
done()
}
// log build statistics and stop spinner
function logStatsDist(done) {
// print success message
spinner
.succeed('Build successfull.')
.print(' ')
.print(`Build entry: ${pkg.main}`)
.print(`Build output: ${path.resolve(__dirname, DIST)}`)
logStatsCommons()
done()
}
export {build}
/* ----------------------------------------------------------- *
* watch files for changes
* ----------------------------------------------------------- */
// [development build]
function watch() {
// start watchers
gulp.watch(paths.entry.src, gulp.series(startWatchTask, entry, reload))
gulp.watch(paths.assets.src, gulp.series(startWatchTask, assets, reload))
gulp.watch(paths.scripts.src, gulp.series(startWatchTask, scripts, reload))
gulp.watch(
paths.appStyles.src,
gulp.series(startWatchTask, ui5AppStyles, reload)
)
gulp.watch(
paths.libStyles.src,
gulp.series(startWatchTask, ui5LibStyles, reload)
)
gulp.watch(
paths.themeStyles.src,
gulp.series(startWatchTask, ui5ThemeStyles, reload)
)
// start HTTP server
if (options.local) {
startHttpServer()
}
}
// [production build]
export function startHttpServer() {
const sSuccessMessage =
'\u{1F64C} (Server started, use Ctrl+C to stop and go back to the console...)'
// start web server
const port = parseInt(process.env.DEV_PORT || 3000, 10)
const express = require('express')
const proxy = require('http-proxy-middleware')
// proxy middleware options
const proxyOptions = {
target: process.env.DEV_API_PROXY,
secure: false,
xfwd: true,
// autoRewrite: true,
// changeOrigin: true,
headers: {
host: `localhost:${port}`,
origin: `http://localhost:${port}`
},
cookieDomainRewrite: {
'*': `localhost:${port}`
}
}
// create the proxy (without context)
const apiProxy = process.env.DEV_API_PROXY ? proxy(proxyOptions) : null
// mount web server
const webServer = express()
// config and start web server
if (process.env.DEV_API_PROXY) {
webServer.use('/api', apiProxy)
}
webServer.use(express.static(IS_DEV_MODE ? `./${DEV}` : `./${DIST}`))
webServer.use('/app', express.static(IS_DEV_MODE ? `./${DEV}` : `./${DIST}`))
webServer.use('/ui5', express.static(`./${UI5}`))
webServer.use('/.maps', express.static(`./.maps`))
// if (!IS_DEV_MODE) {
// // TODO: get gzip middleware working again with express
// // gzip/brotli static middleware - serves compressed files if they exist
// const gzipStaticMiddleware = require('connect-gzip-static')
// const oneDay = 86400000
// webServer.use('/app', gzipStaticMiddleware(`./${DIST}`), {maxAge: oneDay})
// }
webServer.listen(port)
// log success message
gutil.log(gutil.colors.green(sSuccessMessage))
}
/* ----------------------------------------------------------- *
* reload browser
* ----------------------------------------------------------- */
/**
* Helper to print the current time formatted
* @return {string}
*/
function currentTime() {
const now = new Date()
const h = str_pad(now.getHours())
const m = str_pad(now.getMinutes())
const s = str_pad(now.getSeconds())
return h + ':' + m + ':' + s
}
function str_pad(n) {
return String('0' + n).slice(-2)
}
// [development build]
function reload(done) {
if (options.silent) {
spinner.print(
`\u{1F435} Update completed, ready for reload... - ${currentTime()}`
)
} else {
gutil.log(`Update completed, ready for reload... - ${currentTime()}`)
}
done()
}
function startWatchTask(done) {
if (options.silent) {
spinner.print(`\u{1F440} Watch task started ... - ${currentTime()}`)
} else {
gutil.log(`Watch task started ... - ${currentTime()}`)
}
done()
}
/* ----------------------------------------------------------- *
* if required: download and build OpenUI5 library
* ----------------------------------------------------------- */
// [development & production build]
// export function downloadOpenUI5() {
// try {
// const sSourceID = pkg.ui5.src
// const oSource = pkg.ui5.srcLinks[sSourceID]
// const sUI5Version = oSource.version
// const sCompiledURL = handlebars.compile(oSource.url)(oSource)
// const isRemoteLink = sCompiledURL.startsWith('http')
// // if UI5 download link is marked as prebuild,
// // we can extract it directly into '/ui5' target directory
// const sDownloadPath = !oSource.isPrebuild
// ? path.resolve(__dirname, './.download')
// : path.resolve(__dirname, `./${UI5}`)
// const isDownloadRequired =
// oSource.isArchive &&
// isRemoteLink &&
// !fs.existsSync(path.join(sDownloadPath, sUI5Version))
// const oDownloadOptions = {
// onProgress(iStep, iTotalSteps, oStepDetails) {
// // update spinner state
// spinner.text = `Downloading UI5... [${iStep}/${iTotalSteps}] ${Math.round(
// oStepDetails.progress || 0
// )}% (${oStepDetails.name})`
// }
// }
// // ensure ui5 download oath exists
// if (!fs.existsSync(sDownloadPath)) {
// fs.mkdirSync(sDownloadPath)
// }
// if (isDownloadRequired) {
// gutil.log('Download UI5 form: ' + sCompiledURL)
// // update spinner state
// spinner.text =
// 'Downloading UI5... (this task can take several minutes, please be patient)'
// }
// // return promise
// return isDownloadRequired
// ? ui5Download(sCompiledURL, sDownloadPath, sUI5Version, oDownloadOptions)
// .then(sSuccessMessage => {
// spinner.succeed(sSuccessMessage)
// spinner.start('')
// })
// .catch(sErrorMessage => {
// spinner.fail(sErrorMessage)
// spinner.start('')
// throw sErrorMessage
// })
// : Promise.resolve()
// } catch (error) {
// spinner.fail(error)
// }
// }
/**
* Reads UI5 version from depencies
*/
function getUI5Version() {
//Make sure to return actual semantic version number only, as this will be used in URLs
return pkg.dependencies['@openui5/sap.ui.core'].replace(/[^0123456789.]/g, '')
}
export function prepareOpenUI5() {
let sUI5Version = getUI5Version()
let sUI5Path = path.resolve(__dirname, `./${UI5}`)
const isAlreadyPresent = fs.existsSync(path.join(sUI5Path, sUI5Version))
if (!isAlreadyPresent) {
gutil.log(
'Missing UI5 runtime, start building for version: ' +
gutil.colors.bold(sUI5Version)
)
require('child_process').execSync(
`yarn ui5 build --all --dest=./${UI5}/${sUI5Version} --clean-dest=true`,
{stdio: 'inherit'}
)
//Build sap-ui-version.json file (e.g. to make UI5 inspector happy)
// initialize build time
const NOW = new Date()
// build time stamp in format yyyyMMddhhmm
const sBuildTime = NOW.toISOString()
.slice(0, 16)
.replace(/[-T:]/g, '')
const oVersionJSON = {
buildTimestamp: sBuildTime,
name: 'openui5-sdk-dist-pulseshift-custom',
version: sUI5Version,
libraries: [] //TODO:Check if needed: Could be read from yarn/npm dependencies
}
const sVersionJSONString = JSON.stringify(oVersionJSON, null, 2)
// write JSON file
fs.writeFileSync(
`./${UI5}/${sUI5Version}/resources/sap-ui-version.json`,
sVersionJSONString
)
} else {
gutil.log(
'Found UI5 runtime, nothing to do - version: ' +
gutil.colors.bold(sUI5Version)
)
}
return Promise.resolve()
}
// [development & production build]
//TODO: Is this still needed?
export function buildOpenUI5() {
//const sSourceID = pkg.ui5.src
//const oSource = pkg.ui5.srcLinks[sSourceID]
//const sUI5Version = oSource.version
let sUI5Version = getUI5Version()
//const sDownloadPath = path.resolve(__dirname, './ui5_tmp')
const sDownloadPath = path.resolve(__dirname, `./${UI5}/${sUI5Version}`)
const sUI5TargetPath = path.resolve(__dirname, `./${UI5}/${sUI5Version}`)
const isBuildRequired = !fs.existsSync(sUI5TargetPath)
const oBuildOptions = {
onProgress(iStep, iTotalSteps, oStepDetails) {
// update spinner state
spinner.text = `Build UI5... [${iStep}/${iTotalSteps}] (${oStepDetails.name})`
}
}
if (isBuildRequired) {
// update spinner state
spinner.text =
'Build UI5... (this task can take several minutes, please be patient)'
}
// define build Promise
return isBuildRequired
? ui5Build(
`${sDownloadPath}/${sUI5Version}`,
sUI5TargetPath,
sUI5Version,
oBuildOptions
)
.then(sSuccessMessage => {
spinner.succeed(sSuccessMessage)
spinner.start('')
})
.catch(sErrorMessage => {
spinner.fail(sErrorMessage)
spinner.start('')
})
: Promise.resolve()
}
/* ----------------------------------------------------------- *
* clean development directory
* ----------------------------------------------------------- */
// [development build]
function cleanDev() {
const VENDOR_SRC = pkg.ui5.vendor ? `${pkg.ui5.vendor.path}/**/*` : ''
return del(
[`${DEV}/**/*`, `!${UI5}/**/*`].concat(
VENDOR_SRC
)
)
}
// [production build]
function cleanDist() {
const VENDOR_SRC = pkg.ui5.vendor ? `${pkg.ui5.vendor.path}/**/*` : ''
return del(
[`${DIST}/**/*`, `!${UI5}/**/*`].concat(
VENDOR_SRC
)
)
}
// [helper function]
export function clean() {
const VENDOR_SRC = pkg.ui5.vendor ? `${pkg.ui5.vendor.path}/**/*` : ''
return del(
[
DEV,
DIST,
UI5,
'.maps',
'.download',
'test/screenshots/**/*',
`${SRC}/**/*.help.properties`,
`${SRC}/**/i18n_*.properties`,
`${SRC}/**/messagebundle_*.properties`
]
.concat(
THEMES.filter(theme => theme !== TARGET_THEME).map(
theme => `${SRC}/resources/ui5-themes/UI5/sap/**/themes/${theme}`
)
)
.concat(VENDOR_SRC)
)
}
/* ----------------------------------------------------------- *
* generate favicons (long runner ~ 100-200 sec)
* ----------------------------------------------------------- */
// [production & development build]
// function favicon() {
// const targetPath = IS_DEV_MODE ? DEV : DIST
// const isFaviconsDirCached = fs.existsSync(
// `${targetPath}/favicons_results.html`
// )
// // use content hash of master image as directory name and cashe assets in dev mode
// return isFaviconsDirCached || !isFaviconDefined
// ? Promise.resolve()
// : gulp
// .src(pkg.favicon.src)
// .pipe(plumber(buildErrorHandler))
// .pipe(
// favicons({
// appName: pkg.ui5.indexTitle,
// appDescription: pkg.description,
// developerName: pkg.author,
// version: pkg.version,
// background: '#fefefe',
// theme_color: '#fefefe',
// path: ``,
// html: 'favicons_results.html',
// online: false,
// preferOnline: false,
// pipeHTML: true
// })
// )
// .pipe(gulp.dest(`${targetPath}`))
// }
/* ----------------------------------------------------------- *
* optimize and compile app entry (src/index.handlebars)
* ----------------------------------------------------------- */
// [helper function]
function getHandlebarsProps(sEntryHTMLPath) {
const aResourceRootsSrc = []
.concat(UI5_APPS)
.concat(UI5_LIBS)
.concat(NON_UI5_ASSETS)
.concat([NPM_MODULES_TARGET])
return {
indexTitle: pkg.ui5.indexTitle,
src: getRelativeUI5SrcURL(sEntryHTMLPath),
scriptAttributes: IS_DEV_MODE ? '' : 'defer', //Add defer only in prod build as currently sap-ui-debug does not work in deferred mode
theme: TARGET_THEME,
// create resource roots string
resourceroots: JSON.stringify(
aResourceRootsSrc.reduce((oResult, oModule) => {
const sModulePath = oModule.path.replace(
new RegExp(`^${SRC}`),
IS_DEV_MODE ? DEV : DIST
)
// create path to theme relative to entry HTML
let sRelativePath = path.relative(
path.parse(sEntryHTMLPath).dir,
sModulePath
)
// on windows, the sRelativePath will contain backslashes. as the browser cannot handle
// the relative path included in the script tag containing backslashes, we have to replace
// them with normal slashes
sRelativePath = sRelativePath.includes('\\')
? sRelativePath.replace(/\\/g, '/')
: sRelativePath
return Object.assign(oResult, {
[oModule.name]: sRelativePath
})
}, {})
),
// create custom theme roots string
themeroots: JSON.stringify(
UI5_THEMES.reduce((oResult, oTheme) => {
const sThemePath = oTheme.path.replace(
new RegExp(`^${SRC}`),
IS_DEV_MODE ? DEV : DIST
)
// create path to theme relative to entry HTML
let sRelativePath = path.relative(
path.parse(sEntryHTMLPath).dir,
`${sThemePath}/UI5`
)
// on windows, the sRelativePath will contain backslashes. as the browser cannot handle
// the relative path included in the script tag containing backslashes, we have to replace
// them with normal slashes
sRelativePath = sRelativePath.includes('\\')
? sRelativePath.replace(/\\/g, '/')
: sRelativePath
// create path to theme relative to entry HTML
return Object.assign(oResult, {
[oTheme.name]: sRelativePath
})
}, {})
),
// // create favicons
// favicons: isFaviconDefined
// ? fs.readFileSync(
// `${IS_DEV_MODE ? DEV : DIST}/favicons_results.html`,
// 'utf8'
// )
// : '',
// define HOST used for API calls in case a proxy is used
devheader: ''
// process.env.DEV_API_PROXY && IS_DEV_MODE
// ? '<link id="dev-api-proxy-origin" href="https://localhost" />'
// : ''
}
}
// [helper function]
function getRelativeUI5SrcURL(sEntryHTMLPath) {
const sEntryPath = path.dirname(sEntryHTMLPath)
//const sSourceID = pkg.ui5.src
//const oSource = pkg.ui5.srcLinks[sSourceID]
//const sCompiledURL = handlebars.compile(oSource.url)(oSource)
//const isRemoteLink = sCompiledURL.startsWith('http')
//const sLocalPath = oSource.path || ''
// const sOpenUI5PathNaked = path.resolve(
// __dirname,
// path.join(`${UI5}/${getUI5Version()}`, 'sap-ui-core.js')
// )
const sOpenUI5PathWrapped = path.resolve(
__dirname,
path.join(`${UI5}/${getUI5Version()}/resources`, 'sap-ui-core.js')
)
let sRelativeUI5Path = path.relative(sEntryPath, sOpenUI5PathWrapped)
// if (oSource.isArchive && isRemoteLink && !oSource.isPrebuild) {
// // ui5/version/sap-ui-core.js
// sRelativeUI5Path = path.relative(sEntryPath, sOpenUI5PathNaked)
// } else if (oSource.isArchive && isRemoteLink && oSource.isPrebuild) {
// // ui5/version/resources/sap-ui-core.js (wrapped) OR ui5/version/sap-ui-core.js (naked)
// sRelativeUI5Path = path.relative(
// sEntryPath,
// fs.existsSync(sOpenUI5PathWrapped)
// ? sOpenUI5PathWrapped
// : sOpenUI5PathNaked
// )
// } else if (!oSource.isArchive && isRemoteLink) {
// // direct remote link
// sRelativeUI5Path = sCompiledURL
// } else if (!isRemoteLink) {
// // direct local link
// sRelativeUI5Path = path.relative(sEntryPath, sCompiledURL)
// }
// on windows, the sRelativeUI5Path will contain backslashes. as the browser cannot handle
// the relative path included in the script tag containing backslashes, we have to replace
// them with normal slashes
sRelativeUI5Path = sRelativeUI5Path.includes('\\')
? sRelativeUI5Path.replace(/\\/g, '/')
: sRelativeUI5Path
return sRelativeUI5Path
}
// [development build]
function entry() {
try {
// update spinner state
spinner.text = 'Compiling project resources...'
const aEntries = paths.entry.src.map(
sEntry =>
new Promise((resolve, reject) =>
gulp
.src(
[sEntry],
// filter out unchanged files between runs
{
base: SRC,
since: gulp.lastRun(entry)
}
)
// don't exit the running watcher task on errors
.pipe(plumber())
// compile handlebars to HTML
.pipe(
hdlbars(
getHandlebarsProps(
path.resolve(
__dirname,
sEntry.replace(new RegExp(`^${SRC}`), DEV)
)
)
)
)
.pipe(
rename({
extname: '.html'
})
)
.pipe(gulp.dest(DEV))
.on('error', reject)
.on('end', resolve)
)
)
return Promise.all(aEntries)
} catch (error) {
spinner.fail(error)
}
}
// [production build]
function entryDist() {
try {
// update spinner state
spinner.text = 'Compiling project resources...'
const aEntries = paths.entry.src.map(
sEntry =>
new Promise((resolve, reject) =>
gulp
.src(
[sEntry],
// filter out unchanged files between runs
{
base: SRC,
since: gulp.lastRun(entry)
}
)
.pipe(plumber(buildErrorHandler))
// compile handlebars to HTML
.pipe(
hdlbars(
getHandlebarsProps(
path.resolve(
__dirname,
sEntry.replace(new RegExp(`^${SRC}`), DIST)
)
)
)
)
// minify HTML (disabled, cause data-sap-ui-theme-roots gets removed)
// .pipe(htmlmin())
.pipe(
rename({
extname: '.html'
})
)
.pipe(gulp.dest(DIST))
.on('error', reject)
.on('end', resolve)
.pipe(touch())
)
)
return Promise.all(aEntries)
} catch (error) {
spinner.fail(error)
}
}
/* ----------------------------------------------------------- *
* copy assets to destination folder (.png, .jpg, .json, ...)
* ----------------------------------------------------------- */
// [development build]
function assets() {
try {
return paths.assets.src.length === 0
? Promise.resolve()
: gulp
.src(
paths.assets.src,
// filter out unchanged files between runs
{
base: SRC,
since: gulp.lastRun(assets)
}
)
// don't exit the running watcher task on errors
.pipe(plumber())
// do not optimize size and quality of images in dev mode
// transpile JS: babel will run with the settings defined in `.babelrc` file
.pipe(gulpif(/.*\.js$/, sourcemaps.init()))
.pipe(gulpif(/.*\.js$/, babel()))
.pipe(gulpif(/.*\.js$/, sourcemaps.write('../.maps')))
.pipe(gulp.dest(DEV))
} catch (error) {
spinner.fail(error)
}
}
// [production build]
function assetsDist() {
try {
return paths.assets.src.length === 0
? Promise.resolve()
: gulp
.src(paths.assets.src, {
base: SRC
})
.pipe(plumber(buildErrorHandler))
// optimize size and quality of images