weboptimizer 3.0.28 → 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -18,38 +18,27 @@
18
18
  endregion
19
19
  */
20
20
  // region imports
21
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
22
- var _typeof = require("@babel/runtime/helpers/typeof");
23
- Object.defineProperty(exports, "__esModule", {
24
- value: true
25
- });
26
- exports.log = exports["default"] = void 0;
27
- var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
28
- var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
29
- var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
30
- var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
31
- var _child_process = require("child_process");
32
- var _clientnode = require("clientnode");
33
- var _fs = require("fs");
34
- var _promises = require("fs/promises");
35
- var _globAll = require("glob-all");
36
- var _path = _interopRequireWildcard(require("path"));
37
- var _rimraf = require("rimraf");
38
- var _configurator = require("./configurator");
39
- var _helper = require("./helper");
40
- var _process$env$NODE_ENV;
41
- function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, "default": e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t9 in e) "default" !== _t9 && {}.hasOwnProperty.call(e, _t9) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t9)) && (i.get || i.set) ? o(f, _t9, i) : f[_t9] = e[_t9]); return f; })(e, t); }
42
- function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
43
- function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
44
- function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
45
- function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
46
- function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2["default"])(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
21
+ import "core-js/modules/es.array.push.js";
22
+ import "core-js/modules/es.iterator.constructor.js";
23
+ import "core-js/modules/es.iterator.filter.js";
24
+ import "core-js/modules/es.iterator.map.js";
25
+ import "core-js/modules/es.json.stringify.js";
26
+ import { ChildProcess, CommonSpawnOptions, exec as execChildProcess, ExecOptions, spawn as spawnChildProcess } from 'child_process';
27
+ import { AnyFunction, CLOSE_EVENT_NAMES, copyDirectoryRecursiveSync, copyFileSync, evaluate, EvaluationResult, File, getProcessCloseHandler, handleChildProcess, isDirectory, isDirectorySync, isFile, isFileSync, isPlainObject, Logger, Mapping, MAXIMAL_NUMBER_OF_ITERATIONS, NOOP, parseEncodedObject, PlainObject, PositiveEvaluationResult, ProcedureFunction, ProcessCloseCallback, ProcessCloseReason, ProcessError, ProcessErrorCallback, ProcessHandler, walkDirectoryRecursively } from 'clientnode';
28
+ import { chmodSync, unlinkSync } from 'fs';
29
+ import { writeFile, unlink } from 'fs/promises';
30
+ import { sync as globSync } from 'glob-all';
31
+ import path, { join, resolve } from 'path';
32
+ import { rimraf as removeDirectoryRecursively, sync as removeDirectoryRecursivelySync } from 'rimraf';
33
+ import { load as loadConfiguration } from './configurator';
34
+ import { determineAssetType, determineModuleFilePath, determineModuleLocations, isFilePathInLocation, renderFilePathTemplate, resolveBuildConfigurationFilePaths, stripLoader } from './helper';
35
+ import { Command, CommandLineArguments, GivenInjection, ResolvedBuildConfiguration, ResolvedBuildConfigurationItem, ResolvedConfiguration } from './type';
47
36
  // endregion
48
- var log = exports.log = new _clientnode.Logger({
49
- name: 'weboptimizer-main-logger'
37
+ export const log = new Logger({
38
+ name: 'weboptimizer'
50
39
  });
51
- _clientnode.Logger.configureAllInstances({
52
- level: ['debug', 'development'].includes((_process$env$NODE_ENV = process.env.NODE_ENV) !== null && _process$env$NODE_ENV !== void 0 ? _process$env$NODE_ENV : '') ? 'debug' : 'warn'
40
+ Logger.configureAllInstances({
41
+ level: ['debug', 'development'].includes(process.env.NODE_ENV ?? '') ? 'debug' : 'warn'
53
42
  });
54
43
  // NOTE: Environment variables can only be strings.
55
44
  process.env.UV_THREADPOOL_SIZE = '128';
@@ -63,562 +52,244 @@ process.env.UV_THREADPOOL_SIZE = '128';
63
52
  * @param environment - Environment variables to take into account.
64
53
  * @returns Nothing.
65
54
  */
66
- var main = function main(context) {
55
+ const main = async (context, currentWorkingDirectory = process.cwd(), commandLineArguments = process.argv, webOptimizerPath = __dirname,
56
+ /*
57
+ NOTE: We have to avoid that some pre-processor removes this
58
+ assignment.
59
+ */
60
+ environment = eval('process.env')) => {
61
+ if (environment.PATH && !environment.PATH.includes(':node_modules/.bin')) environment.PATH += ':node_modules/.bin';else environment.PATH = 'node_modules/.bin';
62
+ const configuration = loadConfiguration(context, currentWorkingDirectory, commandLineArguments, webOptimizerPath, environment);
63
+ let clear = NOOP();
67
64
  try {
68
- var currentWorkingDirectory = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : process.cwd();
69
- var commandLineArguments = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : process.argv;
70
- var webOptimizerPath = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : __dirname;
71
- var environment = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : eval('process.env');
72
- return (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee2() {
73
- var configuration, clear, processOptions, childProcessOptions, childProcesses, processPromises, possibleArguments, closeEventHandlers, dynamicConfiguration, count, filePath, additionalArguments, _iterator, _step, file, _iterator2, _step2, _filePath, buildConfigurations, tidiedUp, tidyUp, testModuleFilePaths, _iterator7, _step7, buildConfiguration, expression, _iterator8, _step8, _loop, handleTask, finished, closeHandler, _iterator1, _step1, closeEventName, _t3, _t4, _t5, _t6, _t7, _t8;
74
- return _regenerator["default"].wrap(function (_context3) {
75
- while (1) switch (_context3.prev = _context3.next) {
76
- case 0:
77
- if (environment.PATH && !environment.PATH.includes(':node_modules/.bin')) environment.PATH += ':node_modules/.bin';else environment.PATH = 'node_modules/.bin';
78
- configuration = (0, _configurator.load)(context, currentWorkingDirectory, commandLineArguments, webOptimizerPath, environment);
79
- clear = (0, _clientnode.NOOP)();
80
- _context3.prev = 1;
81
- // region controller
82
- processOptions = {
83
- cwd: configuration.path.context,
84
- env: environment
85
- };
86
- childProcessOptions = _objectSpread({
87
- shell: true,
88
- stdio: 'inherit'
89
- }, processOptions);
90
- childProcesses = [];
91
- processPromises = [];
92
- possibleArguments = ['build', 'build:types', 'check:types', 'clear', 'document', 'lint', 'preinstall', 'serve', 'test', 'test:browser', 'test:coverage', 'test:coverage:report', 'watch'];
93
- closeEventHandlers = [];
94
- if (!(configuration.givenCommandLineArguments.length > 2)) {
95
- _context3.next = 37;
96
- break;
97
- }
98
- // region temporary save dynamically given configurations
99
- // NOTE: We need a copy of given arguments array.
100
- dynamicConfiguration = {
101
- givenCommandLineArguments: configuration.givenCommandLineArguments.slice()
102
- };
103
- if (configuration.givenCommandLineArguments.length > 3 && (0, _clientnode.parseEncodedObject)(configuration.givenCommandLineArguments[configuration.givenCommandLineArguments.length - 1], configuration, 'configuration')) configuration.givenCommandLineArguments.pop();
104
- count = 0;
105
- filePath = (0, _path.resolve)(configuration.path.context, ".dynamicConfiguration-".concat(String(count), ".json"));
106
- case 2:
107
- if (!(count < _clientnode.MAXIMAL_NUMBER_OF_ITERATIONS.value)) {
108
- _context3.next = 5;
109
- break;
110
- }
111
- filePath = (0, _path.resolve)(configuration.path.context, ".dynamicConfiguration-".concat(String(count), ".json"));
112
- _context3.next = 3;
113
- return (0, _clientnode.isFile)(filePath);
114
- case 3:
115
- if (_context3.sent) {
116
- _context3.next = 4;
117
- break;
118
- }
119
- return _context3.abrupt("continue", 5);
120
- case 4:
121
- count++;
122
- _context3.next = 2;
123
- break;
124
- case 5:
125
- _context3.next = 6;
126
- return (0, _promises.writeFile)(filePath, JSON.stringify(dynamicConfiguration));
127
- case 6:
128
- additionalArguments = commandLineArguments.splice(3); /// region register exit handler to tidy up
129
- clear = function clear(error) {
130
- // NOTE: Close handler have to be synchronous.
131
- if ((0, _clientnode.isFileSync)(filePath)) (0, _fs.unlinkSync)(filePath);
132
- if (error) throw error;
133
- };
134
- closeEventHandlers.push(clear);
135
- /// endregion
136
- // endregion
137
- // region handle clear
138
- /*
139
- NOTE: Some tasks could depend on previously created artefacts
140
- packages so a preceding clear should not be performed in that
141
- cases.
142
- NOTE: If we have a dependency cycle we need to preserve files
143
- during pre-install phase.
144
- */
145
- if (!(possibleArguments.includes(configuration.givenCommandLineArguments[2]) && (!['build', 'build:types', 'lint', 'preinstall', 'test', 'test:browser', 'test:coverage', 'test:coverage:report', 'serve', 'watch'].includes(configuration.givenCommandLineArguments[2]) ||
146
- /*
147
- NOTE: If target artefacts are located next to their
148
- source files, we need to clear them first when running
149
- dev mode (watching source files and reloading build
150
- automatically).
151
- */
152
- ['serve', 'watch'].includes(configuration.givenCommandLineArguments[2]) && configuration.path.source.base === configuration.path.target.base))) {
153
- _context3.next = 20;
154
- break;
155
- }
156
- if (!((0, _path.resolve)(configuration.path.target.base) === (0, _path.resolve)(configuration.path.context))) {
157
- _context3.next = 16;
158
- break;
159
- }
160
- _context3.next = 7;
161
- return (0, _clientnode.walkDirectoryRecursively)(configuration.path.target.base, /*#__PURE__*/function () {
162
- var _ref2 = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee(file) {
163
- var type, _file$stats, _t, _t2;
164
- return _regenerator["default"].wrap(function (_context) {
165
- while (1) switch (_context.prev = _context.next) {
166
- case 0:
167
- if (!(0, _helper.isFilePathInLocation)(file.path, configuration.path.ignore.concat(configuration.module.directoryNames, configuration.loader.directoryNames).map(function (filePath) {
168
- return (0, _path.resolve)(configuration.path.context, filePath);
169
- }).filter(function (filePath) {
170
- return !configuration.path.context.startsWith(filePath);
171
- }))) {
172
- _context.next = 1;
173
- break;
174
- }
175
- return _context.abrupt("return", false);
176
- case 1:
177
- _t = _regenerator["default"].keys(configuration.buildContext.types);
178
- case 2:
179
- if ((_t2 = _t()).done) {
180
- _context.next = 7;
181
- break;
182
- }
183
- type = _t2.value;
184
- if (!new RegExp(configuration.buildContext.types[type].filePathPattern).test(file.path)) {
185
- _context.next = 6;
186
- break;
187
- }
188
- if (!((_file$stats = file.stats) !== null && _file$stats !== void 0 && _file$stats.isDirectory())) {
189
- _context.next = 4;
190
- break;
191
- }
192
- _context.next = 3;
193
- return (0, _rimraf.rimraf)(file.path);
194
- case 3:
195
- return _context.abrupt("return", false);
196
- case 4:
197
- _context.next = 5;
198
- return (0, _promises.unlink)(file.path);
199
- case 5:
200
- return _context.abrupt("continue", 7);
201
- case 6:
202
- _context.next = 2;
203
- break;
204
- case 7:
205
- case "end":
206
- return _context.stop();
207
- }
208
- }, _callee);
209
- }));
210
- return function (_x) {
211
- return _ref2.apply(this, arguments);
212
- };
213
- }());
214
- case 7:
215
- _t3 = _createForOfIteratorHelper;
216
- _context3.next = 8;
217
- return (0, _clientnode.walkDirectoryRecursively)(configuration.path.target.base, function () {
218
- return false;
219
- }, configuration.encoding);
220
- case 8:
221
- _iterator = _t3(_context3.sent);
222
- _context3.prev = 9;
223
- _iterator.s();
224
- case 10:
225
- if ((_step = _iterator.n()).done) {
226
- _context3.next = 12;
227
- break;
228
- }
229
- file = _step.value;
230
- if (!file.name.startsWith('npm-debug')) {
231
- _context3.next = 11;
232
- break;
233
- }
234
- _context3.next = 11;
235
- return (0, _promises.unlink)(file.path);
236
- case 11:
237
- _context3.next = 10;
238
- break;
239
- case 12:
240
- _context3.next = 14;
241
- break;
242
- case 13:
243
- _context3.prev = 13;
244
- _t4 = _context3["catch"](9);
245
- _iterator.e(_t4);
246
- case 14:
247
- _context3.prev = 14;
248
- _iterator.f();
249
- return _context3.finish(14);
250
- case 15:
251
- _context3.next = 17;
252
- break;
253
- case 16:
254
- _context3.next = 17;
255
- return (0, _rimraf.rimraf)(configuration.path.target.base);
256
- case 17:
257
- _context3.next = 18;
258
- return (0, _clientnode.isDirectory)(configuration.path.apiDocumentation);
259
- case 18:
260
- if (!_context3.sent) {
261
- _context3.next = 19;
262
- break;
263
- }
264
- _context3.next = 19;
265
- return (0, _rimraf.rimraf)(configuration.path.apiDocumentation);
266
- case 19:
267
- _iterator2 = _createForOfIteratorHelper(configuration.path.tidyUpOnClear);
268
- try {
269
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
270
- _filePath = _step2.value;
271
- if (_filePath) if ((0, _clientnode.isFileSync)(_filePath))
272
- // NOTE: Close handler have to be synchronous.
273
- (0, _fs.unlinkSync)(_filePath);else if ((0, _clientnode.isDirectorySync)(_filePath)) (0, _rimraf.sync)(_filePath);
65
+ // region controller
66
+ const processOptions = {
67
+ cwd: configuration.path.context,
68
+ env: environment
69
+ };
70
+ const childProcessOptions = {
71
+ shell: true,
72
+ stdio: 'inherit',
73
+ ...processOptions
74
+ };
75
+ const childProcesses = [];
76
+ const processPromises = [];
77
+ const possibleArguments = ['build', 'build:types', 'check:types', 'clear', 'document', 'lint', 'preinstall', 'serve', 'test', 'test:browser', 'test:coverage', 'test:coverage:report', 'watch'];
78
+ const closeEventHandlers = [];
79
+ if (configuration.givenCommandLineArguments.length > 2) {
80
+ // region temporary save dynamically given configurations
81
+ // NOTE: We need a copy of given arguments array.
82
+ const dynamicConfiguration = {
83
+ givenCommandLineArguments: configuration.givenCommandLineArguments.slice()
84
+ };
85
+ if (configuration.givenCommandLineArguments.length > 3 && parseEncodedObject(configuration.givenCommandLineArguments[configuration.givenCommandLineArguments.length - 1], configuration, 'configuration')) configuration.givenCommandLineArguments.pop();
86
+ let count = 0;
87
+ let filePath = resolve(configuration.path.context, `.dynamicConfiguration-${String(count)}.json`);
88
+ for (; count < MAXIMAL_NUMBER_OF_ITERATIONS.value; count++) {
89
+ filePath = resolve(configuration.path.context, `.dynamicConfiguration-${String(count)}.json`);
90
+ if (!(await isFile(filePath))) break;
91
+ }
92
+ await writeFile(filePath, JSON.stringify(dynamicConfiguration));
93
+ const additionalArguments = commandLineArguments.splice(3);
94
+ /// region register exit handler to tidy up
95
+ clear = error => {
96
+ // NOTE: Close handler have to be synchronous.
97
+ if (isFileSync(filePath)) unlinkSync(filePath);
98
+ if (error) throw error;
99
+ };
100
+ closeEventHandlers.push(clear);
101
+ /// endregion
102
+ // endregion
103
+ // region handle clear
104
+ /*
105
+ NOTE: Some tasks could depend on previously created artefacts
106
+ packages so a preceding clear should not be performed in that
107
+ cases.
108
+ NOTE: If we have a dependency cycle we need to preserve files
109
+ during pre-install phase.
110
+ */
111
+ if (possibleArguments.includes(configuration.givenCommandLineArguments[2]) && (!['build', 'build:types', 'lint', 'preinstall', 'test', 'test:browser', 'test:coverage', 'test:coverage:report', 'serve', 'watch'].includes(configuration.givenCommandLineArguments[2]) ||
112
+ /*
113
+ NOTE: If target artefacts are located next to their
114
+ source files, we need to clear them first when running
115
+ dev mode (watching source files and reloading build
116
+ automatically).
117
+ */
118
+ ['serve', 'watch'].includes(configuration.givenCommandLineArguments[2]) && configuration.path.source.base === configuration.path.target.base)) {
119
+ if (resolve(configuration.path.target.base) === resolve(configuration.path.context)) {
120
+ // Removes all compiled files.
121
+ await walkDirectoryRecursively(configuration.path.target.base, async file => {
122
+ if (isFilePathInLocation(file.path, configuration.path.ignore.concat(configuration.module.directoryNames, configuration.loader.directoryNames).map(filePath => resolve(configuration.path.context, filePath)).filter(filePath => !configuration.path.context.startsWith(filePath)))) return false;
123
+ for (const type in configuration.buildContext.types) if (new RegExp(configuration.buildContext.types[type].filePathPattern).test(file.path)) {
124
+ if (file.stats?.isDirectory()) {
125
+ await removeDirectoryRecursively(file.path);
126
+ return false;
274
127
  }
275
- } catch (err) {
276
- _iterator2.e(err);
277
- } finally {
278
- _iterator2.f();
279
- }
280
- (0, _rimraf.sync)((0, _globAll.sync)(configuration.path.tidyUpOnClearGlobs));
281
- case 20:
282
- // endregion
283
- // region handle build
284
- buildConfigurations = (0, _helper.resolveBuildConfigurationFilePaths)(configuration.buildContext.types, configuration.path.source.asset.base, configuration.path.ignore.concat(configuration.module.directoryNames, configuration.loader.directoryNames).map(function (filePath) {
285
- return (0, _path.resolve)(configuration.path.context, filePath);
286
- }).filter(function (filePath) {
287
- return !configuration.path.context.startsWith(filePath);
288
- }), configuration["package"].main.fileNames);
289
- if (!['build', 'document', 'test', 'test:coverage', 'test:coverage:report'].includes(commandLineArguments[2])) {
290
- _context3.next = 21;
128
+ await unlink(file.path);
291
129
  break;
292
130
  }
293
- tidiedUp = false;
294
- tidyUp = function tidyUp() {
131
+ });
132
+ for (const file of await walkDirectoryRecursively(configuration.path.target.base, () => false, configuration.encoding)) if (file.name.startsWith('npm-debug')) await unlink(file.path);
133
+ } else await removeDirectoryRecursively(configuration.path.target.base);
134
+ if (await isDirectory(configuration.path.apiDocumentation)) await removeDirectoryRecursively(configuration.path.apiDocumentation);
135
+ for (const filePath of configuration.path.tidyUpOnClear) if (filePath) if (isFileSync(filePath))
136
+ // NOTE: Close handler have to be synchronous.
137
+ unlinkSync(filePath);else if (isDirectorySync(filePath)) removeDirectoryRecursivelySync(filePath);
138
+ removeDirectoryRecursivelySync(globSync(configuration.path.tidyUpOnClearGlobs));
139
+ }
140
+ // endregion
141
+ // region handle build
142
+ const buildConfigurations = resolveBuildConfigurationFilePaths(configuration.buildContext.types, configuration.path.source.asset.base, configuration.path.ignore.concat(configuration.module.directoryNames, configuration.loader.directoryNames).map(filePath => resolve(configuration.path.context, filePath)).filter(filePath => !configuration.path.context.startsWith(filePath)), configuration.package.main.fileNames);
143
+ if (['build', 'document', 'test', 'test:coverage', 'test:coverage:report'].includes(commandLineArguments[2])) {
144
+ let tidiedUp = false;
145
+ const tidyUp = () => {
146
+ /*
147
+ Determines all none javaScript entities which have been
148
+ emitted as single module to remove.
149
+ */
150
+ if (tidiedUp) return;
151
+ tidiedUp = true;
152
+ for (const [chunkName, chunk] of Object.entries(configuration.injection.entry.normalized)) for (const moduleID of chunk) {
153
+ const filePath = determineModuleFilePath(moduleID, configuration.module.aliases, configuration.module.replacements.normal, {
154
+ file: configuration.extensions.file.internal
155
+ }, configuration.path.context, configuration.path.source.asset.base, configuration.path.ignore, configuration.module.directoryNames, configuration.package.main.fileNames, configuration.package.main.propertyNames, configuration.package.aliasPropertyNames, configuration.encoding);
156
+ let type = null;
157
+ if (filePath) type = determineAssetType(filePath, configuration.buildContext.types, configuration.path);
158
+ if (typeof type === 'string' && Object.prototype.hasOwnProperty.call(configuration.buildContext.types, type)) {
159
+ const filePath = renderFilePathTemplate(stripLoader(configuration.files.compose.javaScript), {
160
+ '[name]': chunkName
161
+ });
295
162
  /*
296
- Determines all none javaScript entities which have been
297
- emitted as single module to remove.
163
+ NOTE: Close handler have to be
164
+ synchronous.
298
165
  */
299
- if (tidiedUp) return;
300
- tidiedUp = true;
301
- for (var _i = 0, _Object$entries = Object.entries(configuration.injection.entry.normalized); _i < _Object$entries.length; _i++) {
302
- var _Object$entries$_i = (0, _slicedToArray2["default"])(_Object$entries[_i], 2),
303
- chunkName = _Object$entries$_i[0],
304
- chunk = _Object$entries$_i[1];
305
- var _iterator3 = _createForOfIteratorHelper(chunk),
306
- _step3;
307
- try {
308
- for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
309
- var moduleID = _step3.value;
310
- var _filePath2 = (0, _helper.determineModuleFilePath)(moduleID, configuration.module.aliases, configuration.module.replacements.normal, {
311
- file: configuration.extensions.file.internal
312
- }, configuration.path.context, configuration.path.source.asset.base, configuration.path.ignore, configuration.module.directoryNames, configuration["package"].main.fileNames, configuration["package"].main.propertyNames, configuration["package"].aliasPropertyNames, configuration.encoding);
313
- var type = null;
314
- if (_filePath2) type = (0, _helper.determineAssetType)(_filePath2, configuration.buildContext.types, configuration.path);
315
- if (typeof type === 'string' && Object.prototype.hasOwnProperty.call(configuration.buildContext.types, type)) {
316
- var _filePath3 = (0, _helper.renderFilePathTemplate)((0, _helper.stripLoader)(configuration.files.compose.javaScript), {
317
- '[name]': chunkName
318
- });
319
- /*
320
- NOTE: Close handler have to be
321
- synchronous.
322
- */
323
- if (configuration.buildContext.types[type].outputExtension === 'js' && (0, _clientnode.isFileSync)(_filePath3)) (0, _fs.chmodSync)(_filePath3, '755');
324
- }
325
- }
326
- } catch (err) {
327
- _iterator3.e(err);
328
- } finally {
329
- _iterator3.f();
330
- }
331
- }
332
- var _iterator4 = _createForOfIteratorHelper(configuration.path.tidyUp),
333
- _step4;
334
- try {
335
- for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
336
- var _filePath4 = _step4.value;
337
- if (_filePath4) if ((0, _clientnode.isFileSync)(_filePath4))
338
- // NOTE: Close handler have to be synchronous.
339
- (0, _fs.unlinkSync)(_filePath4);else if ((0, _clientnode.isDirectorySync)(_filePath4)) (0, _rimraf.sync)(_filePath4);
340
- }
341
- } catch (err) {
342
- _iterator4.e(err);
343
- } finally {
344
- _iterator4.f();
345
- }
346
- (0, _rimraf.sync)((0, _globAll.sync)(configuration.path.tidyUpGlobs));
347
- };
348
- closeEventHandlers.push(tidyUp);
166
+ if (configuration.buildContext.types[type].outputExtension === 'js' && isFileSync(filePath)) chmodSync(filePath, '755');
167
+ }
168
+ }
169
+ for (const filePath of configuration.path.tidyUp) if (filePath) if (isFileSync(filePath))
170
+ // NOTE: Close handler have to be synchronous.
171
+ unlinkSync(filePath);else if (isDirectorySync(filePath)) removeDirectoryRecursivelySync(filePath);
172
+ removeDirectoryRecursivelySync(globSync(configuration.path.tidyUpGlobs));
173
+ };
174
+ closeEventHandlers.push(tidyUp);
349
175
 
350
- /*
351
- Triggers complete asset compiling and bundles them into the
352
- final productive output.
353
- */
354
- processPromises.push(new Promise(function (resolve, reject) {
355
- var commandLineArguments = (configuration.commandLine.build.arguments || []).concat(additionalArguments);
356
- log.info('Running "' + ("".concat(configuration.commandLine.build.command, " ") + commandLineArguments.join(' ')).trim() + '"');
176
+ /*
177
+ Triggers complete asset compiling and bundles them into the
178
+ final productive output.
179
+ */
180
+ processPromises.push(new Promise((resolve, reject) => {
181
+ const commandLineArguments = (configuration.commandLine.build.arguments || []).concat(additionalArguments);
182
+ log.info('Running "' + (`${configuration.commandLine.build.command} ` + commandLineArguments.join(' ')).trim() + '"');
357
183
 
358
- /*
359
- NOTE: Take current weboptimizer's dependencies into
360
- account.
361
- */
362
- if (!childProcessOptions.env) childProcessOptions.env = {};
363
- if (typeof childProcessOptions.env.PATH !== 'string') childProcessOptions.env.PATH = '';
364
- childProcessOptions.env.PATH += ": ".concat(webOptimizerPath, "/node_modules/.bin");
365
- var childProcess = (0, _child_process.spawn)(configuration.commandLine.build.command, commandLineArguments, childProcessOptions);
366
- var copyAdditionalFilesAndTidyUp = function copyAdditionalFilesAndTidyUp() {
367
- var _iterator5 = _createForOfIteratorHelper(configuration.files.additionalPaths),
368
- _step5;
369
- try {
370
- for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
371
- var _filePath5 = _step5.value;
372
- var sourcePath = (0, _path.join)(configuration.path.source.base, _filePath5);
373
- var targetPath = (0, _path.join)(configuration.path.target.base, _filePath5);
184
+ /*
185
+ NOTE: Take current weboptimizer's dependencies into
186
+ account.
187
+ */
188
+ if (!childProcessOptions.env) childProcessOptions.env = {};
189
+ if (typeof childProcessOptions.env.PATH !== 'string') childProcessOptions.env.PATH = '';
190
+ childProcessOptions.env.PATH += `: ${webOptimizerPath}/node_modules/.bin`;
191
+ const childProcess = spawnChildProcess(configuration.commandLine.build.command, commandLineArguments, childProcessOptions);
192
+ const copyAdditionalFilesAndTidyUp = () => {
193
+ for (const filePath of configuration.files.additionalPaths) {
194
+ const sourcePath = join(configuration.path.source.base, filePath);
195
+ const targetPath = join(configuration.path.target.base, filePath);
374
196
 
375
- // NOTE: Close handler have to be synchronous.
376
- if ((0, _clientnode.isDirectorySync)(sourcePath)) {
377
- if ((0, _clientnode.isDirectorySync)(targetPath)) (0, _rimraf.sync)(targetPath);
378
- (0, _clientnode.copyDirectoryRecursiveSync)(sourcePath, targetPath);
379
- } else if ((0, _clientnode.isFileSync)(sourcePath)) (0, _clientnode.copyFileSync)(sourcePath, targetPath);
380
- }
381
- } catch (err) {
382
- _iterator5.e(err);
383
- } finally {
384
- _iterator5.f();
385
- }
386
- tidyUp();
387
- };
388
- var closeHandler = (0, _clientnode.getProcessCloseHandler)(resolve, reject, null, commandLineArguments[2] === 'build' ? copyAdditionalFilesAndTidyUp : tidyUp);
389
- var _iterator6 = _createForOfIteratorHelper(_clientnode.CLOSE_EVENT_NAMES),
390
- _step6;
391
- try {
392
- for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
393
- var closeEventName = _step6.value;
394
- childProcess.on(closeEventName, closeHandler);
395
- }
396
- } catch (err) {
397
- _iterator6.e(err);
398
- } finally {
399
- _iterator6.f();
400
- }
401
- childProcesses.push(childProcess);
402
- return childProcesses;
403
- }));
404
- // endregion
405
- // region handle pre-install
406
- _context3.next = 34;
407
- break;
408
- case 21:
409
- if (!(configuration.library && configuration.givenCommandLineArguments[2] === 'preinstall')) {
410
- _context3.next = 34;
411
- break;
412
- }
413
- // Perform all file specific preprocessing stuff.
414
- testModuleFilePaths = [];
415
- if ((0, _clientnode.isPlainObject)(configuration['test:browser'].injection) && configuration['test:browser'].injection.entry) testModuleFilePaths = (0, _helper.determineModuleLocations)(configuration['test:browser'].injection.entry, configuration.module.aliases, configuration.module.replacements.normal, {
416
- file: configuration.extensions.file.internal
417
- }, configuration.path.context, configuration.path.source.asset.base, configuration.path.ignore).filePaths;
418
- _iterator7 = _createForOfIteratorHelper(buildConfigurations);
419
- _context3.prev = 22;
420
- _iterator7.s();
421
- case 23:
422
- if ((_step7 = _iterator7.n()).done) {
423
- _context3.next = 31;
424
- break;
197
+ // NOTE: Close handler have to be synchronous.
198
+ if (isDirectorySync(sourcePath)) {
199
+ if (isDirectorySync(targetPath)) removeDirectoryRecursivelySync(targetPath);
200
+ copyDirectoryRecursiveSync(sourcePath, targetPath);
201
+ } else if (isFileSync(sourcePath)) copyFileSync(sourcePath, targetPath);
425
202
  }
426
- buildConfiguration = _step7.value;
427
- expression = buildConfiguration[configuration.givenCommandLineArguments[2]].trim();
428
- _iterator8 = _createForOfIteratorHelper(buildConfiguration.filePaths);
429
- _context3.prev = 24;
430
- _loop = /*#__PURE__*/_regenerator["default"].mark(function _loop() {
431
- var filePath, evaluated;
432
- return _regenerator["default"].wrap(function (_context2) {
433
- while (1) switch (_context2.prev = _context2.next) {
434
- case 0:
435
- filePath = _step8.value;
436
- if (testModuleFilePaths.includes(filePath)) {
437
- _context2.next = 2;
438
- break;
439
- }
440
- evaluated = (0, _clientnode.evaluate)("`".concat(expression, "`"), {
441
- global: global,
442
- self: configuration,
443
- buildConfiguration: buildConfiguration,
444
- path: _path["default"],
445
- additionalArguments: additionalArguments,
446
- filePath: filePath
447
- });
448
- if (!evaluated.error) {
449
- _context2.next = 1;
450
- break;
451
- }
452
- throw new Error('Error occurred during processing given ' + "command: ".concat(evaluated.error));
453
- case 1:
454
- log.info("Running \"".concat(evaluated.result, "\""));
455
- processPromises.push(new Promise(function (resolve, reject) {
456
- return [(0, _clientnode.handleChildProcess)((0, _child_process.exec)(evaluated.result, _objectSpread({
457
- encoding: configuration.encoding
458
- }, processOptions), function (error) {
459
- if (error) reject(error);else resolve({
460
- reason: 'Finished.',
461
- parameters: []
462
- });
463
- }))];
464
- }));
465
- case 2:
466
- case "end":
467
- return _context2.stop();
468
- }
469
- }, _loop);
203
+ tidyUp();
204
+ };
205
+ const closeHandler = getProcessCloseHandler(resolve, reject, null, commandLineArguments[2] === 'build' ? copyAdditionalFilesAndTidyUp : tidyUp);
206
+ for (const closeEventName of CLOSE_EVENT_NAMES) childProcess.on(closeEventName, closeHandler);
207
+ childProcesses.push(childProcess);
208
+ return childProcesses;
209
+ }));
210
+ // endregion
211
+ // region handle pre-install
212
+ } else if (configuration.library && configuration.givenCommandLineArguments[2] === 'preinstall') {
213
+ // Perform all file specific preprocessing stuff.
214
+ let testModuleFilePaths = [];
215
+ if (isPlainObject(configuration['test:browser'].injection) && configuration['test:browser'].injection.entry) testModuleFilePaths = determineModuleLocations(configuration['test:browser'].injection.entry, configuration.module.aliases, configuration.module.replacements.normal, {
216
+ file: configuration.extensions.file.internal
217
+ }, configuration.path.context, configuration.path.source.asset.base, configuration.path.ignore).filePaths;
218
+ for (const buildConfiguration of buildConfigurations) {
219
+ const expression = buildConfiguration[configuration.givenCommandLineArguments[2]].trim();
220
+ for (const filePath of buildConfiguration.filePaths) if (!testModuleFilePaths.includes(filePath)) {
221
+ const evaluated = evaluate(`\`${expression}\``, {
222
+ global,
223
+ self: configuration,
224
+ buildConfiguration,
225
+ path,
226
+ additionalArguments,
227
+ filePath
470
228
  });
471
- _iterator8.s();
472
- case 25:
473
- if ((_step8 = _iterator8.n()).done) {
474
- _context3.next = 27;
475
- break;
476
- }
477
- return _context3.delegateYield(_loop(), "t0", 26);
478
- case 26:
479
- _context3.next = 25;
480
- break;
481
- case 27:
482
- _context3.next = 29;
483
- break;
484
- case 28:
485
- _context3.prev = 28;
486
- _t5 = _context3["catch"](24);
487
- _iterator8.e(_t5);
488
- case 29:
489
- _context3.prev = 29;
490
- _iterator8.f();
491
- return _context3.finish(29);
492
- case 30:
493
- _context3.next = 23;
494
- break;
495
- case 31:
496
- _context3.next = 33;
497
- break;
498
- case 32:
499
- _context3.prev = 32;
500
- _t6 = _context3["catch"](22);
501
- _iterator7.e(_t6);
502
- case 33:
503
- _context3.prev = 33;
504
- _iterator7.f();
505
- return _context3.finish(33);
506
- case 34:
507
- // endregion
508
- // region handle remaining tasks
509
- handleTask = function handleTask(type) {
510
- var tasks = Array.isArray(configuration.commandLine[type]) ? configuration.commandLine[type] : [configuration.commandLine[type]];
511
- var _iterator9 = _createForOfIteratorHelper(tasks),
512
- _step9;
513
- try {
514
- var _loop2 = function _loop2() {
515
- var task = _step9.value;
516
- var evaluated = (0, _clientnode.evaluate)(Object.prototype.hasOwnProperty.call(task, 'indicator') ? task.indicator : 'true', {
517
- global: global,
518
- self: configuration,
519
- path: _path["default"]
520
- });
521
- if (evaluated.error) throw new Error('Error occurred during processing given task: ' + evaluated.error);
522
- if (evaluated.result) processPromises.push(new Promise(function (resolve, reject) {
523
- var commandLineArguments = (task.arguments || []).concat(additionalArguments);
524
- log.info('Running "' + ("".concat(task.command, " ") + commandLineArguments.join(' ')).trim() + '"');
525
- var childProcess = (0, _child_process.spawn)(task.command, commandLineArguments, childProcessOptions);
526
- var closeHandler = (0, _clientnode.getProcessCloseHandler)(resolve, reject);
527
- var _iterator0 = _createForOfIteratorHelper(_clientnode.CLOSE_EVENT_NAMES),
528
- _step0;
529
- try {
530
- for (_iterator0.s(); !(_step0 = _iterator0.n()).done;) {
531
- var closeEventName = _step0.value;
532
- childProcess.on(closeEventName, closeHandler);
533
- }
534
- } catch (err) {
535
- _iterator0.e(err);
536
- } finally {
537
- _iterator0.f();
538
- }
539
- childProcesses.push(childProcess);
540
- return childProcesses;
541
- }));
542
- };
543
- for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) {
544
- _loop2();
545
- }
546
- } catch (err) {
547
- _iterator9.e(err);
548
- } finally {
549
- _iterator9.f();
550
- }
551
- }; /// region a-/synchronous
552
- if (!['document', 'test', 'test:coverage', 'test:coverage:report'].includes(configuration.givenCommandLineArguments[2])) {
553
- _context3.next = 36;
554
- break;
555
- }
556
- _context3.next = 35;
557
- return Promise.all(processPromises);
558
- case 35:
559
- handleTask(configuration.givenCommandLineArguments[2]);
560
- _context3.next = 37;
561
- break;
562
- case 36:
563
- if (['build:types', 'check:types', 'lint', 'serve', 'test:browser'].includes(configuration.givenCommandLineArguments[2])) handleTask(configuration.givenCommandLineArguments[2]);
564
- case 37:
565
- finished = false;
566
- closeHandler = function closeHandler() {
567
- if (!finished) for (var _i2 = 0, _closeEventHandlers = closeEventHandlers; _i2 < _closeEventHandlers.length; _i2++) {
568
- var closeEventHandler = _closeEventHandlers[_i2];
569
- closeEventHandler.apply(void 0, arguments);
570
- }
571
- finished = true;
572
- };
573
- _iterator1 = _createForOfIteratorHelper(_clientnode.CLOSE_EVENT_NAMES);
574
- try {
575
- for (_iterator1.s(); !(_step1 = _iterator1.n()).done;) {
576
- closeEventName = _step1.value;
577
- process.on(closeEventName, closeHandler);
578
- }
579
- } catch (err) {
580
- _iterator1.e(err);
581
- } finally {
582
- _iterator1.f();
583
- }
584
- if (require.main === module && (configuration.givenCommandLineArguments.length < 3 || !possibleArguments.includes(configuration.givenCommandLineArguments[2]))) log.info("Give one of \"".concat(possibleArguments.join('", "'), "\" as command"), 'line argument. You can provide a json string as second', 'parameter to dynamically overwrite some configurations.\n');
585
- // endregion
586
- // region forward nested return codes
587
- _context3.prev = 38;
588
- _context3.next = 39;
589
- return Promise.all(processPromises);
590
- case 39:
591
- _context3.next = 41;
592
- break;
593
- case 40:
594
- _context3.prev = 40;
595
- _t7 = _context3["catch"](38);
596
- log.error(_t7);
597
- process.exit(_t7.returnCode);
598
- case 41:
599
- _context3.next = 44;
600
- break;
601
- case 42:
602
- _context3.prev = 42;
603
- _t8 = _context3["catch"](1);
604
- if (!configuration.debug) {
605
- _context3.next = 43;
606
- break;
607
- }
608
- throw _t8;
609
- case 43:
610
- log.error(_t8);
611
- case 44:
612
- return _context3.abrupt("return", clear);
613
- case 45:
614
- case "end":
615
- return _context3.stop();
229
+ if (evaluated.error) throw new Error('Error occurred during processing given ' + `command: ${evaluated.error}`);
230
+ log.info(`Running "${evaluated.result}"`);
231
+ processPromises.push(new Promise((resolve, reject) => [handleChildProcess(execChildProcess(evaluated.result, {
232
+ encoding: configuration.encoding,
233
+ ...processOptions
234
+ }, error => {
235
+ if (error) reject(error);else resolve({
236
+ reason: 'Finished.',
237
+ parameters: []
238
+ });
239
+ }))]));
240
+ }
241
+ }
242
+ }
243
+ // endregion
244
+ // region handle remaining tasks
245
+ const handleTask = type => {
246
+ const tasks = Array.isArray(configuration.commandLine[type]) ? configuration.commandLine[type] : [configuration.commandLine[type]];
247
+ for (const task of tasks) {
248
+ const evaluated = evaluate(Object.prototype.hasOwnProperty.call(task, 'indicator') ? task.indicator : 'true', {
249
+ global,
250
+ self: configuration,
251
+ path
252
+ });
253
+ if (evaluated.error) throw new Error('Error occurred during processing given task: ' + evaluated.error);
254
+ if (evaluated.result) processPromises.push(new Promise((resolve, reject) => {
255
+ const commandLineArguments = (task.arguments || []).concat(additionalArguments);
256
+ log.info('Running "' + (`${task.command} ` + commandLineArguments.join(' ')).trim() + '"');
257
+ const childProcess = spawnChildProcess(task.command, commandLineArguments, childProcessOptions);
258
+ const closeHandler = getProcessCloseHandler(resolve, reject);
259
+ for (const closeEventName of CLOSE_EVENT_NAMES) childProcess.on(closeEventName, closeHandler);
260
+ childProcesses.push(childProcess);
261
+ return childProcesses;
262
+ }));
616
263
  }
617
- }, _callee2, null, [[1, 42], [9, 13, 14, 15], [22, 32, 33, 34], [24, 28, 29, 30], [38, 40]]);
618
- }))();
619
- } catch (e) {
620
- return Promise.reject(e);
264
+ };
265
+ /// region a-/synchronous
266
+ if (['document', 'test', 'test:coverage', 'test:coverage:report'].includes(configuration.givenCommandLineArguments[2])) {
267
+ await Promise.all(processPromises);
268
+ handleTask(configuration.givenCommandLineArguments[2]);
269
+ } else if (['build:types', 'check:types', 'lint', 'serve', 'test:browser'].includes(configuration.givenCommandLineArguments[2])) handleTask(configuration.givenCommandLineArguments[2]);
270
+ /// endregion
271
+ // endregion
272
+ }
273
+ let finished = false;
274
+ const closeHandler = (...parameters) => {
275
+ if (!finished) for (const closeEventHandler of closeEventHandlers) closeEventHandler(...parameters);
276
+ finished = true;
277
+ };
278
+ for (const closeEventName of CLOSE_EVENT_NAMES) process.on(closeEventName, closeHandler);
279
+ if (require.main === module && (configuration.givenCommandLineArguments.length < 3 || !possibleArguments.includes(configuration.givenCommandLineArguments[2]))) log.info(`Give one of "${possibleArguments.join('", "')}" as command`, 'line argument. You can provide a json string as second', 'parameter to dynamically overwrite some configurations.\n');
280
+ // endregion
281
+ // region forward nested return codes
282
+ try {
283
+ await Promise.all(processPromises);
284
+ } catch (error) {
285
+ log.error(error);
286
+ process.exit(error.returnCode);
287
+ }
288
+ // endregion
289
+ } catch (error) {
290
+ if (configuration.debug) throw error;else log.error(error);
621
291
  }
292
+ return clear;
622
293
  };
623
294
  if (require.main === module) void main();
624
- var _default = exports["default"] = main;
295
+ export default main;