forked from andrewplummer/Sugar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gulpfile.js
4710 lines (4034 loc) · 141 KB
/
gulpfile.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
var fs = require('fs'),
gulp = require('gulp'),
path = require('path'),
args = require('yargs').argv,
gutil = require('gulp-util');
// -------------- Tasks ----------------
gulp.task('default', showTasks);
gulp.task('help', showTasks);
gulp.task('tasks', showTasks);
gulp.task('more', showMore);
gulp.task('build', buildDefault);
gulp.task('build:dev', buildDevelopment);
gulp.task('build:min', buildMinified);
gulp.task('build:qml', buildQml);
gulp.task('build:locales', buildLocales);
gulp.task('build:packages', buildPackagesDefault);
gulp.task('build:packages:core', buildPackagesCore);
gulp.task('build:packages:sugar', buildPackagesSugar);
gulp.task('build:packages:clean', buildPackagesClean);
gulp.task('build:release', buildRelease);
gulp.task('test', testRunDefault);
gulp.task('test:npm', testRunNpm);
gulp.task('test:all', testRunAll);
gulp.task('test:watch', testWatchDefault);
gulp.task('test:watch:npm', testWatchNpm);
gulp.task('test:watch:all', testWatchAll);
gulp.task('json:api', buildJSONAPI);
gulp.task('json:docs', buildJSONDocs);
gulp.task('json:source', buildJSONSource);
gulp.task('tsd', buildTypescriptDeclarations);
// -------------- Help ----------------
var MESSAGE_TASKS = `
# Usage
|gulp| [TASK] [OPTIONS]
# Tasks
|build| Create development and minified build.
|build:dev| Create development build (concatenate files only).
|build:min| Create minified build (closure compiler).
|build:packages| Builds modularized packages (all by default).
|build:packages:core| Builds the "sugar-core" package.
|build:packages:sugar| Builds the "sugar" npm package.
|build:packages:clean| Cleans package output directory ("packages" by default).
|build:qml| Creates a QML compatible build.
|build:locales| Exports locale files to "dist" directory.
|build:release| Create a release. Requires a version.
|test| Run tests against distributed build (build:dev).
|test:npm| Run tests against npm packages (build:npm:all).
|test:all| Run tests against distributed and npm (build:dev, build:packages).
|test:watch| Watch for changes and run "test".
|test:watch:npm| Watch for changes and run "test:npm".
|test:watch:all| Watch for changes and run "test:all".
|json:api| Builds API method list as JSON.
|json:docs| Builds full docs set as JSON.
|json:source| Builds modularized source as JSON.
|tsd| Builds typescript declarations (sugar.d.ts).
Run "gulp more" for more options.
|more| Show more help details.
# Options
|-m, --modules| Comma separated modules to include (dev/min tasks).
Run "gulp more" for modules (non-default marked with *).
|-l, --locales| Comma separated date locales to include (dev/min tasks).
Run "gulp more" for locales. English packaged with date module.
|-p, --packages| Comma separated packages to build ("packages" tasks).
Run "gulp more" for packages.
|-o, --output| Build output path (default is "dist/sugar.js" or "dist/sugar.min.js").
Also output file for JSON tasks.
|-v, --version| Version for "release" build.
|--es5| Include ES5 module in build (dev/min tasks).
|--no-polyfill| Exclude ES6/ES7 modules from build (dev/min tasks).
|--charset| Charset flag to pass to the compiler. Note that although "utf-8"
produces smaller output, default build is smaller after gzip.
|--source-map| Compiler source map filename. Default is "sugar.min.map".
|--no-source-map| Do not output a source map.
`;
var MESSAGE_EXTRA = `
# Modules
|es5 *| Full ES5 polyfill suite (adds IE6-8 support).
|es6| Partial ES6 polyfills, mostly for String/Array support.
|es7| Partial ES7 polyfills. Currently only Array#includes.
|date| Date parsing, manipulation, formatting, and locale support.
|string| String encoding, truncating, formatting, and more.
|array| Array sorting, uniquing, randomizing, and more.
|object| Object merging, manipulating, type checks, and more.
|enumerable| Traversing, mapping, finding, etc. Shared by Array and Object.
|function| Function throttling, memoizing, partial functions, and more.
|number| Number formatting, rounding, math aliases, and more.
|regexp| RegExp escaping and flag manipulation methods.
|range| Date, Number, and String ranges.
|language *| Script detection, half/full width conversion, kana.
|inflections *| Pluralizing and special character normalization.
|* Not included in default builds|
# Packages
|sugar-core| Core method defining functionality. Dependency for all other packages.
|sugar| All default modules and optional date locales.
|sugar-es5| ES5 polyfill methods only.
|sugar-es6| ES6 polyfill methods only.
|sugar-es7| ES7 polyfill methods only.
|sugar-string| String module and ES6 polyfills.
|sugar-number| Number module and ES6 polyfills.
|sugar-enumerable| Enumerable module and ES6/ES7 polyfills.
|sugar-date| Date module and optional locales.
|sugar-array| Array module.
|sugar-object| Object module.
|sugar-function| Function module.
|sugar-regexp| RegExp module.
|sugar-range| Range module.
|sugar-language| Language module.
|sugar-inflections| Inflections module.
# Locales
|Bundled:|
|en| Alias to "en-US" (sorry).
|en-US: American English| mm/dd/yyyy preferred, Sunday starts week.
|en-GB: British English| Slightly different output formats.
|en-CA: Canadian English| Slightly different output formats.
|en-AU: Australian English| Alias to "en-GB" for now.
|Optional:|
LOCALE_LIST
# Modular Builds
The npm build tasks split out all methods and dependencies in the
source code so that they can be consumed individually. The result
of these tasks will be identical to the packages hosted on npm.
For more information on how to include them, see the README.
Bower packages contain only the builds in the "dist/" directory.
As bower requires a public git endpoint, the result of these tasks
will be identical to the modularized repos on Github. This also means
that there is no separate "sugar" package for bower as it is identical
to this repo.
# Typescript Options
By default the "tsd" task builds Typescript declarations for Sugar in
extended mode, but without Object.prototype modifications. The task can
be modified to change these defaults, or include/exclude methods or modules:
|--no-extended-mode| When this flag is present, declarations for extended mode
(i.e. native objects) are not output.
|--modules| Filter exported methods by module. This argument
is required for non-default modules. Also accepts
"all" or "default".
--modules=String,Inflections
|--include| Whitelist methods or namespaces to be included:
--include=Array --include=Array:unique.
|--exclude| Blacklist methods or namespaces to be excluded:
--exclude=Array --exclude=Array:unique.
`;
function showTasks() {
if (args.help) {
showMore();
} else {
showMessage(MESSAGE_TASKS);
}
}
function showMore() {
showMessage(MESSAGE_TASKS + MESSAGE_EXTRA);
}
function showMessage(message) {
var msg = message.replace(/LOCALE_LIST/g, function() {
return getAllLocales().map(function(l) {
var code = l.match(/([\w-]+)\.js$/)[1];
var name = readFile(l).match(/\* (.+) locale definition/i)[1];
return gutil.colors.yellow(code + ': ' + name);
}).join('\n ');
})
.replace(/\[\w+\]/g, function(match) {
return gutil.colors.dim(match);
})
.replace(/# [\w ]+$/gm, function(match) {
return gutil.colors.underline(match.replace(/^# /g, ''));
})
.replace(/\|.+?\|/g, function(match) {
return gutil.colors.yellow(match.replace(/\|/g, ''));
})
.replace(/^\s{30,}/gm, function(match) {
return match.slice(2);
});
console.log(msg);
}
// -------------- Release ----------------
function buildRelease() {
var version = getVersion(), run = true;
if (!version.match(/^\d.\d+\.\d+$/)) {
warn('Release requires a valid x.x.x version!');
run = false;
}
if (!run) process.exit();
return mergeStreams([
buildDevelopment(),
buildMinified(),
buildPackagesDefault()
]);
}
// -------------- Compiler ----------------
var COMPILER_JAR_PATH = 'node_modules/google-closure-compiler/compiler.jar';
function compileSingle(path) {
var compiler = require('closure-compiler-stream');
var flags = getDefaultFlags();
flags.js_output_file = path;
if (args.sourceMap !== false) {
flags.create_source_map = args.sourceMap || path.replace(/\.js/, '.map');
}
if (args.charset) {
flags.charset = args.charset;
}
return compiler(flags);
}
function getDefaultFlags() {
return {
jar: COMPILER_JAR_PATH,
compilation_level: 'ADVANCED',
assume_function_wrapper: true,
rewrite_polyfills: false,
jscomp_off: ['globalThis', 'checkTypes'],
output_wrapper: LICENSE + "\n(function(){'use strict';%output%}).call(this);",
externs: 'lib/extras/externs.js'
};
}
// -------------- File Util ----------------
function readFile(path) {
return fs.readFileSync(path, 'utf-8');
}
function writeFile(outputPath, body) {
require('mkdirp').sync(path.dirname(outputPath));
fs.writeFileSync(outputPath, body, 'utf-8');
}
function outputJSON(outputPath, obj) {
var filename = args.o || args.output || outputPath;
writeFile(filename, JSON.stringify(obj));
notify('Wrote: ' + filename, false);
}
function cleanDir(dir) {
require('rimraf').sync(dir);
}
// -------------- Stream Util ----------------
function getEmptyStream() {
return require('merge-stream')();
}
function mergeStreams(streams) {
return require('merge-stream')(streams);
}
function addStream(target, src) {
if (!src.isEmpty || !src.isEmpty()) {
target.add(src);
}
return target;
}
function onStreamEnd(stream, fn) {
if (stream.isEmpty()) {
return fn();
}
return stream.pipe(require('through2').obj(function(file, enc, cb) {
fn();
cb();
}));
}
// -------------- Logging Util ----------------
function notify(text, ellipsis, block) {
log(gutil.colors.yellow(text + (ellipsis !== false ? '...' : '')), block);
}
function warn(text, block) {
log(gutil.colors.red(text), block);
}
function log(text, block) {
if (block) {
console.log(text);
} else {
gutil.log(text);
}
}
// -------------- Core Util ----------------
function uniq(arr) {
var result = [];
arr.forEach(function(el) {
if (result.indexOf(el) === -1) {
result.push(el);
}
});
return result;
}
function merge(obj1, obj2) {
iter(obj2, function(key, val) {
obj1[key] = val;
});
}
function groupBy(arr, field) {
var groups = {};
arr.forEach(function(el) {
var val = el[field];
if (!groups[val]) {
groups[val] = [];
}
groups[val].push(el);
});
return groups;
}
function compact(arr) {
return arr.filter(function(el) {
return el;
});
}
function iter(obj, fn) {
for (var key in obj) {
if (!obj.hasOwnProperty(key)) continue;
if (fn(key, obj[key]) === false) {
break;
}
}
}
function padNumber(n, place) {
var str = String(n);
while (str.length < place) {
str = '0' + str;
}
return str;
}
// Template tag
function block(strings) {
var result = strings.concat();
for (var i = 1, j = 1; i < arguments.length; i++) {
result.splice(j, 0, arguments[i]);
j += 2;
}
return result.join('').replace(/^\n|\n$/gm, '');
}
// -------------- Build ----------------
var CORE_MIN_VERSION = '^2.0.0';
var CLOSURE_WRAPPER = block`
(function() {
'use strict';
$1
}).call(this);
`;
var QML_WRAPPER = block`
.pragma library
var Sugar = (function() {
'use strict';
$1
return Sugar;
}).call(this);
`;
var DEFAULT_MODULES = [
'es6',
'es7',
'date',
'string',
'array',
'object',
'enumerable',
'number',
'function',
'regexp',
'range'
];
var ALL_MODULES = [
'es5',
'es6',
'es7',
'date',
'string',
'array',
'object',
'enumerable',
'number',
'function',
'regexp',
'range',
'inflections',
'language'
];
var SPLIT_MODULES = [
'es5',
'es6',
'es7',
'range'
];
var LICENSE = block`
/*
* Sugar ${getVersion(true)}
*
* Freely distributable and licensed under the MIT-style license.
* Copyright (c) Andrew Plummer
* https://sugarjs.com/
*
* ---------------------------- */
`;
var LOCALES_MODULE_COMMENT = block`
/***
* @module Locales
* @description Locale files for the Sugar Date module.
*
***/
`;
function buildDefault() {
notify('Exporting: ' + getBuildPath());
notify('Minifying: ' + getBuildPath(true));
buildLocales();
return logBuildResults(mergeStreams([createDevelopmentBuild(), createMinifiedBuild()]));
}
function buildDevelopment() {
notify('Exporting: ' + getBuildPath());
return logBuildResults(createDevelopmentBuild());
}
function buildMinified() {
notify('Minifying: ' + getBuildPath(true));
return logBuildResults(createMinifiedBuild());
}
function buildLocales() {
copyLocales('all', path.join('dist', 'locales'));
}
function buildQml() {
args.qml = true;
notify('Creating QML Build: ' + getBuildPath());
return logBuildResults(createDevelopmentBuild());
}
function getWrapper(qml) {
return qml ? getQmlWrapper() : getStandardWrapper();
}
function getStandardWrapper() {
return [LICENSE, CLOSURE_WRAPPER].join('\n');
}
function getQmlWrapper() {
return [LICENSE, QML_WRAPPER].join('\n');
}
function createDevelopmentBuild(outputPath, modules, locales) {
var gulpFile = require('gulp-file');
outputPath = outputPath || getBuildPath();
var src = getSource(modules, locales);
return gulpFile(path.basename(outputPath), src, { src: true })
.pipe(gulp.dest(path.dirname(outputPath)));
}
function createMinifiedBuild(outputPath, modules, locales) {
outputPath = outputPath || getBuildPath(true);
try {
fs.lstatSync(COMPILER_JAR_PATH);
} catch(e) {
gutil.log(gutil.colors.red('Closure compiler missing!'), 'Run', gutil.colors.yellow('npm install'));
return;
}
// closure-compiler-stream does not handle direct input,
// so need to write a temp file here to pass to compiler args.
// Ensure unique path in case multiple streams are compiling
// at the same time.
var tmpPath = path.join(path.dirname(outputPath), path.basename(outputPath, '.min.js')) + '.tmp.js';
writeFile(tmpPath, stripDocs(getSource(modules, locales)));
return gulp.src(tmpPath)
.pipe(compileSingle(outputPath))
.pipe(require('through2').obj(function(file, enc, cb) {
fs.unlinkSync(tmpPath);
cb();
}));
}
function getSource(m, l) {
// When the source is modularized variables defined in the core
// will be lost so they need to be redefined in common, however
// these re-defines aren't necessary when the core is bundled
// together, so we can strip them out.
var CORE_REDEFINES = [
'Core utility aliases',
'Internal reference to check if an object can be serialized.'
];
function replaceCoreRedefine(block, comment) {
if (CORE_REDEFINES.indexOf(comment) !== -1) {
block = '';
}
return block;
}
var src = '';
var modulePaths = getModulePaths(m);
var localePaths = getLocalePaths(l);
var namespaceConstraints = getNamespaceConstraints();
modulePaths.forEach(function(p) {
var content = readFile(p);
var moduleName = path.basename(p, '.js');
var constraints = namespaceConstraints[moduleName];
if (moduleName === 'core') {
content = content.replace(/\{VERSION\}/, getVersion());
} else if (constraints) {
content = getSplitModule(content, constraints);
}
src += content;
});
localePaths.forEach(function(p) {
src += readFile(p);
});
src = src.replace(/^'use strict';\n/gm, '');
src = src.replace(/^(?=.)/gm, ' ');
src = src.replace(/^([\s\S]+)$/m, getWrapper(args.qml));
src = src.replace(/^ \/\/ ([\w .]+)[\s\S]+?\n$\n/gm, replaceCoreRedefine);
// Allowing namespace constraints such as
// ES6:String to only build for that namespace.
function getNamespaceConstraints() {
var map = {};
getModuleNames(m).forEach(function(n) {
var split = n.split(':');
var moduleName = split[0];
var namespaceName = split[1];
if (namespaceName) {
if (SPLIT_MODULES.indexOf(moduleName) === -1) {
warn('Module ' + moduleName + ' is not ready to be split!');
warn('Exiting...');
process.exit();
}
var constraints = map[moduleName] || {};
constraints[namespaceName] = true;
map[moduleName] = constraints;
}
});
return map;
}
// Split the module into namespaces here and match on the allowed one.
function getSplitModule(content, constraints) {
var src = '', lastIdx = 0, currentNamespace;
content.replace(/\/\*\*\* @namespace (\w+) \*\*\*\/\n|$/g, function(match, nextNamespace, idx) {
if (!currentNamespace || constraints[currentNamespace]) {
src += content.slice(lastIdx, idx);
}
currentNamespace = (nextNamespace || '').toLowerCase();
lastIdx = idx;
});
return src;
}
return src;
}
// The closure compiler has issues with non-standard
// docs so strip all docs out here.
function stripDocs(str) {
return str.replace(/\/\*\*\*[\s\S]+?\*\*\*\//gm, '');
}
function logBuildResults(stream) {
stream.on('end', function() {
if (args.skipBuildResults) {
return;
}
var moduleNames = getModuleNames();
var localeCodes = getLocaleCodes();
if (moduleNames.indexOf('date') !== -1) {
localeCodes.unshift('en','en-US','en-GB','en-CA','en-AU');
}
notify('Done! Build info:', false);
notify('', false);
notify('Modules: ' + moduleNames.join(','), false);
if (localeCodes.length) {
notify('Locales: ' + localeCodes.join(','), false);
}
notify('', false);
});
return stream;
}
function getVersion(v) {
var ver = args.v || args.version || 'edge';
if (v && ver.match(/^[\d.]+$/)) {
ver = 'v' + ver;
}
if (buildHasCustomModules() || buildHasCustomLocales()) {
var d = new Date();
var df = [d.getFullYear(), padNumber(d.getMonth() + 1, 2), padNumber(d.getDate(), 2)].join('.');
ver = 'Custom ' + df;
}
return ver;
}
function getBuildPath(min) {
return args.o || args.output || getDefaultBuildPath(min);
}
function getDefaultBuildPath(min) {
var names = ['sugar'], dir = '';
if (buildHasCustomModules() || buildHasCustomLocales()) {
names.push('custom');
} else {
if (args.es5) {
names.push('es5');
}
dir = 'dist/';
}
return dir + names.join('-') + (min ? '.min' : '') + '.js';
}
function getModuleNames(m) {
var moduleNames, sortedModuleNames;
moduleNames = (m || args.m || args.module || args.modules || 'default').toLowerCase().split(',');
function alias(name, modules) {
var index = moduleNames.indexOf(name);
if (index !== -1) {
moduleNames.splice.apply(moduleNames, [index, 1].concat(modules));
}
}
function nameRank(moduleName) {
var rank = moduleIsPolyfill(moduleName) ? 0 : 10;
rank += moduleNames.indexOf(moduleName);
return rank;
}
alias('all', ALL_MODULES);
alias('default', DEFAULT_MODULES);
if (args.es5) {
moduleNames.unshift('es5');
}
if (args.polyfills === false) {
moduleNames = moduleNames.filter(function(moduleName) {
return !moduleIsPolyfill(moduleName);
});
}
// Keeping the names sorted as input except to push
// polyfill modules to the top where they need to be.
sortedModuleNames = moduleNames.concat();
sortedModuleNames.sort(function(a, b) {
var aRank = nameRank(a);
var bRank = nameRank(b);
return aRank - bRank;
});
return sortedModuleNames;
}
function getModulePaths(m) {
var names = getModuleNames(m);
function getPath(name) {
return path.join('lib', name.toLowerCase() + '.js');
}
names = names.map(function(n) {
var moduleName = n.split(':')[0];
try {
fs.lstatSync(getPath(moduleName));
} catch(e) {
warn('Cannot find module ' + moduleName + '!');
warn('Exiting...');
process.exit();
}
return moduleName;
});
if (!names.length || names[0] !== 'core') {
names.unshift('common');
}
names.unshift('core');
return uniq(names).map(getPath);
}
function getLocaleCodes(l) {
var names = typeof l === 'string' ? l : args.l || args.locale || args.locales;
if (names === 'all') {
names = getAllLocales().map(function(p) {
return p.match(/([\w-]+)\.js/)[1];
});
} else if (names) {
names = names.split(',');
}
return names || [];
}
function getLocalePaths(l) {
var codes = getLocaleCodes(l);
function getPath(l) {
return path.join('lib', 'locales', l.toLowerCase() + '.js');
}
codes.forEach(function(n) {
try {
fs.lstatSync(getPath(n));
} catch(e) {
warn('Cannot find locale ' + n + '!');
warn('Exiting...');
process.exit();
}
});
return codes.map(getPath);
}
function getAllLocales() {
return require('glob').sync('lib/locales/*.js');
}
function buildHasCustomModules() {
var moduleNames = getModuleNames().filter(function(n) {
// Not counting ES5 module as being custom as it is
// also used in the default build.
return n !== 'es5';
});
var hasNonDefault = moduleNames.some(function(n) {
return DEFAULT_MODULES.indexOf(n) === -1;
});
return moduleNames.length !== DEFAULT_MODULES.length || hasNonDefault;
}
function buildHasCustomLocales() {
return getLocaleCodes().length !== 0;
}
// -------------- Package Definitions ----------------
var PACKAGE_DEFINITIONS = {
'sugar': {
modules: 'ES5,ES6,ES7,String,Number,Array,Enumerable,Object,Date,Locales,Range,Function,RegExp',
keywords: ['date', 'time', 'polyfill']
},
'sugar-core': {
modules: 'Core',
description: 'Core module for the Sugar Javascript utility library.'
},
'sugar-es5': {
modules: 'ES5',
polyfill: true,
description: 'ES5 polyfill module for the Sugar Javascript utility library.',
keywords: ['polyfill']
},
'sugar-es6': {
modules: 'ES6',
polyfill: true,
description: 'ES6 polyfill module for the Sugar Javascript utility library.',
keywords: ['polyfill']
},
'sugar-string': {
modules: 'ES6:String,String,Range:String',
description: 'String module for the Sugar Javascript utility library.',
keywords: ['string']
},
'sugar-number': {
modules: 'ES6:Number,Number,Range:Number',
description: 'Number module for the Sugar Javascript utility library.',
keywords: ['number']
},
'sugar-enumerable': {
modules: 'ES6:Array,ES6:String,ES7:Array,Enumerable',
description: 'Enumerable module for the Sugar Javascript utility library.',
keywords: ['array', 'object']
},
'sugar-array': {
modules: 'ES6:Array,ES6:String,ES7:Array,Array',
description: 'Array module for the Sugar Javascript utility library.',
keywords: ['array']
},
'sugar-object': {
modules: 'Object',
extra: 'Object module.',
description: 'Object module for the Sugar Javascript utility library.',
keywords: ['object']
},
'sugar-date': {
modules: 'Date,Locales,Range:Date',
description: 'Date module for the Sugar Javascript utility library.',
keywords: ['date','time']
},
'sugar-range': {
modules: 'Range',
description: 'Range module for the Sugar Javascript utility library.',
keywords: ['range', 'number', 'string', 'date']
},
'sugar-function': {
modules: 'Function',
description: 'Function module for the Sugar Javascript utility library.',
keywords: ['function']
},
'sugar-regexp': {
modules: 'RegExp',
description: 'RegExp module for the Sugar Javascript utility library.',
keywords: ['regexp']
},
'sugar-inflections': {
modules: 'Inflections',
description: 'Inflections module for the Sugar Javascript utility library.',
keywords: ['inflections']
},
'sugar-language': {
modules: 'Language',
description: 'Language module for the Sugar Javascript utility library.',
keywords: ['language']
}
};
// -------------- Source Package Identities ----------------
var SOURCE_PACKAGE_LISTED_TYPES = [
'static',
'instance',
'prototype',
'accessor',
'global',
'namespace',
'locale',
'fix'
];
var SOURCE_PACKAGE_DEPENDENCY_TYPES = [
'internal',
'build',
'var'
];
function sourcePackageIsDependency(p) {
return SOURCE_PACKAGE_DEPENDENCY_TYPES.indexOf(p.type) !== -1;
}
function sourcePackageIsListed(p) {
return SOURCE_PACKAGE_LISTED_TYPES.indexOf(p.type) !== -1;
}
function sourcePackageExportsMethod(p) {
return p.type === 'static' || p.type === 'instance' || p.type === 'alias' || p.type === 'accessor';
}
function moduleIsPolyfill(moduleName) {
return /^ES[567]/i.test(moduleName);
}
// -------------- Package Util ----------------
function getPackageDefinition(packageName) {
var def = PACKAGE_DEFINITIONS[packageName];
if (!def) {
warn('Cannot find package ' + packageName + '!');
warn('Exiting...');
process.exit();
}
return def;
}
function copyPackageMeta(packageName, packageDir) {
function copyMeta(srcPath) {
writeFile(path.join(packageDir, path.basename(srcPath)), readFile(srcPath));
}
if (packageName === 'sugar-core') {
copyMeta('lib/extras/core/README.md');
} else if (packageName.match(/^sugar-/)) {
buildModuleReadme(packageName, packageDir);
} else {
copyMeta('README.md');
}
if (packageName !== 'sugar-core') {
copyMeta('CHANGELOG.md');
copyMeta('CAUTION.md');
}
copyMeta('LICENSE');
copyMeta('.npmignore');
}
function exportPackageDeclarations(packageName, packageDir) {
var allowedModules;
switch (packageName) {
case 'sugar':
allowedModules = 'all';
break;
case 'sugar-core':
allowedModules = 'none';
break;
default:
allowedModules = [packageName.replace(/^sugar-?/, '')];
}
exportTypescriptDeclarations(packageDir, allowedModules);
}
function copyLocales(l, dir) {
require('mkdirp').sync(dir);
getLocalePaths(l).forEach(function(src) {