@sencha/ext-webpack-plugin
Version:
A webpack plugin for ext-* applications
913 lines (889 loc) • 164 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports._afterCompile = _afterCompile;
exports._buildExtBundle = _buildExtBundle;
exports._compilation = _compilation;
exports._constructor = _constructor;
exports._done = _done;
exports._emit = _emit;
exports._executeAsync = _executeAsync;
exports._getApp = _getApp;
exports._getVersions = _getVersions;
exports._prepareForBuild = _prepareForBuild;
exports._thisCompilation = _thisCompilation;
exports._toXtype = _toXtype;
exports.log = log;
exports.logh = logh;
exports.logv = logv;
exports.smartFlowPing = smartFlowPing;
function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function () { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function (t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == typeof h && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function (t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(typeof e + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function (e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function () { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function (e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function (t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function (t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function (t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function (t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function (e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
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; }
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) { _defineProperty(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; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
//**********
function _constructor(initialOptions) {
const fs = require('fs');
var vars = {};
var options = {};
try {
if (initialOptions.framework == undefined) {
vars.pluginErrors = [];
vars.pluginErrors.push('webpack config: framework parameter on ext-webpack-plugin is not defined - values: react, angular, extjs, web-components');
var result = {
vars: vars
};
return result;
}
var framework = initialOptions.framework;
var treeshake = initialOptions.treeshake;
var verbose = initialOptions.verbose;
const validateOptions = require('schema-utils');
validateOptions(_getValidateOptions(), initialOptions, '');
const rc = fs.existsSync(`.ext-${framework}rc`) && JSON.parse(fs.readFileSync(`.ext-${framework}rc`, 'utf-8')) || {};
options = _objectSpread(_objectSpread(_objectSpread({}, _getDefaultOptions()), initialOptions), rc);
vars = require(`./${framework}Util`)._getDefaultVars();
vars.pluginName = 'ext-webpack-plugin';
vars.app = _getApp();
var pluginName = vars.pluginName;
var app = vars.app;
vars.testing = false;
logv(verbose, 'FUNCTION _constructor');
logv(verbose, `pluginName - ${pluginName}`);
logv(verbose, `app - ${app}`);
if (options.environment == 'production' || options.cmdopts.includes('--production') || options.cmdopts.includes('-pr') || options.cmdopts.includes('--environment=production') || options.cmdopts.includes('-e=production')) {
vars.production = true;
options.browser = 'no';
options.watch = 'no';
options.buildEnvironment = 'production';
} else if (options.cmdopts && (options.cmdopts.includes('--testing') || options.cmdopts.includes('-te') || options.cmdopts.includes('--environment=testing') || options.cmdopts.includes('-e=testing'))) {
vars.production = false;
vars.testing = true;
options.browser = 'no';
options.watch = 'no';
options.buildEnvironment = 'testing';
} else {
options.buildEnvironment = 'development';
vars.production = false;
}
log(app, _getVersions(pluginName, framework));
//mjg added for angular cli build
if (framework == 'angular' && options.intellishake == 'no' && vars.production == true && treeshake == 'yes') {
vars.buildstep = '1 of 1';
log(app, 'Starting production build for ' + framework);
} else if (framework == 'react' || framework == 'extjs' || framework == 'web-components') {
if (vars.production == true) {
vars.buildstep = '1 of 1';
log(app, 'Starting production build for ' + framework);
} else if (vars.testing == true) {
vars.buildstep = '1 of 1';
log(app, 'Starting testing build for ' + framework);
} else {
vars.buildstep = '1 of 1';
log(app, 'Starting development build for ' + framework);
}
} else if (vars.production == true) {
if (treeshake == 'yes') {
vars.buildstep = '1 of 2';
log(app, 'Starting production build for ' + framework + ' - ' + vars.buildstep);
require(`./${framework}Util`)._toProd(vars, options);
} else {
vars.buildstep = '2 of 2';
log(app, 'Continuing production build for ' + framework + ' - ' + vars.buildstep);
}
} else {
vars.buildstep = '1 of 1';
log(app, 'Starting development build for ' + framework);
}
logv(verbose, 'Building for ' + options.buildEnvironment + ', ' + 'treeshake is ' + options.treeshake + ', ' + 'intellishake is ' + options.intellishake);
var configObj = {
vars: vars,
options: options
};
return configObj;
} catch (e) {
throw '_constructor: ' + e.toString();
}
}
//**********
function _thisCompilation(compiler, compilation, vars, options) {
try {
var app = vars.app;
var verbose = options.verbose;
logv(verbose, 'FUNCTION _thisCompilation');
logv(verbose, `options.script: ${options.script}`);
logv(verbose, `buildstep: ${vars.buildstep}`);
if (vars.buildstep === '1 of 1' || vars.buildstep === '1 of 2') {
if (options.script != undefined && options.script != null && options.script != '') {
log(app, `Started running ${options.script}`);
runScript(options.script, function (err) {
if (err) {
throw err;
}
log(app, `Finished running ${options.script}`);
});
}
}
} catch (e) {
throw '_thisCompilation: ' + e.toString();
}
}
//**********
function _compilation(compiler, compilation, vars, options) {
try {
var app = vars.app;
var verbose = options.verbose;
var framework = options.framework;
logv(verbose, 'FUNCTION _compilation');
if (framework != 'extjs') {
if (options.treeshake === 'yes' && options.buildEnvironment === 'production') {
var extComponents = [];
//mjg for 1 step build
if (vars.buildstep == '1 of 1' && framework === 'angular' && options.intellishake == 'no') {
extComponents = require(`./${framework}Util`)._getAllComponents(vars, options);
}
if (vars.buildstep == '1 of 2' || vars.buildstep == '1 of 1' && framework === 'web-components') {
extComponents = require(`./${framework}Util`)._getAllComponents(vars, options);
}
compilation.hooks.succeedModule.tap(`ext-succeed-module`, module => {
if (module.resource && !module.resource.match(/node_modules/)) {
try {
if (module.resource.match(/\.html$/) != null && module._source._value.toLowerCase().includes('doctype html') == false) {
vars.deps = [...(vars.deps || []), ...require(`./${framework}Util`)._extractFromSource(module, options, compilation, extComponents)];
} else {
vars.deps = [...(vars.deps || []), ...require(`./${framework}Util`)._extractFromSource(module, options, compilation, extComponents)];
}
} catch (e) {
console.log(e);
}
}
});
}
if (vars.buildstep == '1 of 2') {
compilation.hooks.finishModules.tap(`ext-finish-modules`, modules => {
require(`./${framework}Util`)._writeFilesToProdFolder(vars, options);
});
}
if (vars.buildstep == '1 of 1' || vars.buildstep == '2 of 2') {
if (options.inject === 'yes') {
if (compilation.hooks.htmlWebpackPluginBeforeHtmlGeneration != undefined) {
compilation.hooks.htmlWebpackPluginBeforeHtmlGeneration.tap(`ext-html-generation`, data => {
const path = require('path');
var jsPath = path.join(vars.extPath, 'ext.js');
var cssPath = path.join(vars.extPath, 'ext.css');
//var jsPath = vars.extPath + '/' + 'ext.js';
//var cssPath = vars.extPath + '/' + 'ext.css';
data.assets.js.unshift(jsPath);
data.assets.css.unshift(cssPath);
log(app, `Adding ${jsPath} and ${cssPath} to index.html`);
});
}
}
}
}
} catch (e) {
throw '_compilation: ' + e.toString();
// logv(options.verbose,e)
// compilation.errors.push('_compilation: ' + e)
}
}
//**********
function _afterCompile(compiler, compilation, vars, options) {
try {
var app = vars.app;
var verbose = options.verbose;
var framework = options.framework;
logv(verbose, 'FUNCTION _afterCompile');
if (framework == 'extjs') {
require(`./extjsUtil`)._afterCompile(compilation, vars, options);
} else {
logv(verbose, 'FUNCTION _afterCompile not run');
}
} catch (e) {
throw '_afterCompile: ' + e.toString();
}
}
//**********
function _emit(_x, _x2, _x3, _x4, _x5) {
return _emit2.apply(this, arguments);
} //**********
function _emit2() {
_emit2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(compiler, compilation, vars, options, callback) {
var path, app, verbose, emit, framework, outputPath, command, parms;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
_context.prev = 0;
path = require('path');
app = vars.app;
verbose = options.verbose;
emit = options.emit;
framework = options.framework;
vars.callback = callback;
logv(verbose, 'FUNCTION _emit');
if (!(emit == 'yes')) {
_context.next = 38;
break;
}
if (!(vars.buildstep == '1 of 1' || vars.buildstep == '1 of 2')) {
_context.next = 34;
break;
}
outputPath = path.join(compiler.outputPath, vars.extPath);
if (compiler.outputPath === '/' && compiler.options.devServer) {
outputPath = path.join(compiler.options.devServer.contentBase, outputPath);
}
logv(verbose, 'outputPath: ' + outputPath);
logv(verbose, 'framework: ' + framework);
if (framework != 'extjs') {
_prepareForBuild(app, vars, options, outputPath, compilation);
}
command = '';
if (options.watch == 'yes' && vars.production == false) {
command = 'watch';
} else {
command = 'build';
}
if (!(vars.rebuild == true)) {
_context.next = 31;
break;
}
parms = [];
if (!Array.isArray(options.cmdopts)) {
options.cmdopts = options.cmdopts.split(' ');
}
if (options.profile == undefined || options.profile == '' || options.profile == null) {
if (command == 'build') {
parms = ['app', command, options.buildEnvironment];
} else {
parms = ['app', command, '--web-server', 'false', options.buildEnvironment];
}
} else {
if (command == 'build') {
parms = ['app', command, options.profile, options.buildEnvironment];
} else {
parms = ['app', command, '--web-server', 'false', options.profile, options.buildEnvironment];
}
}
options.cmdopts.forEach(function (element) {
parms.splice(parms.indexOf(command) + 1, 0, element);
});
// if (vars.watchStarted == false) {
// await _buildExtBundle(app, compilation, outputPath, parms, vars, options)
// vars.watchStarted = true
// }
if (!(vars.watchStarted == false)) {
_context.next = 28;
break;
}
_context.next = 25;
return _buildExtBundle(app, compilation, outputPath, parms, vars, options);
case 25:
if (command == 'watch') {
vars.watchStarted = true;
} else {
vars.callback();
}
_context.next = 29;
break;
case 28:
vars.callback();
case 29:
_context.next = 32;
break;
case 31:
vars.callback();
case 32:
_context.next = 36;
break;
case 34:
logv(verbose, 'NOT running emit');
vars.callback();
case 36:
_context.next = 40;
break;
case 38:
logv(verbose, 'emit is no');
vars.callback();
case 40:
_context.next = 46;
break;
case 42:
_context.prev = 42;
_context.t0 = _context["catch"](0);
vars.callback();
throw '_emit: ' + _context.t0.toString();
case 46:
case "end":
return _context.stop();
}
}, _callee, null, [[0, 42]]);
}));
return _emit2.apply(this, arguments);
}
function _done(stats, vars, options) {
try {
var verbose = options.verbose;
var framework = options.framework;
logv(verbose, 'FUNCTION _done');
if (stats.compilation.errors && stats.compilation.errors.length)
// && process.argv.indexOf('--watch') == -1)
{
var chalk = require('chalk');
console.log(chalk.red('******************************************'));
console.log(stats.compilation.errors[0]);
console.log(chalk.red('******************************************'));
//process.exit(0);
}
//mjg refactor
if (vars.production == true && options.treeshake == 'no' && framework == 'angular') {
require(`./${options.framework}Util`)._toDev(vars, options);
}
try {
if (options.browser == 'yes' && options.watch == 'yes' && vars.production == false) {
if (vars.browserCount == 0) {
var url = 'http://localhost:' + options.port;
require('./pluginUtil').log(vars.app, `Opening browser at ${url}`);
vars.browserCount++;
const opn = require('opn');
opn(url);
}
}
} catch (e) {
console.log(e);
}
if (vars.buildstep == '1 of 1') {
if (vars.production == true) {
require('./pluginUtil').log(vars.app, `Ending production build for ${framework}`);
} else if (vars.testing == true) {
require('./pluginUtil').log(vars.app, `Ending testing build for ${framework}`);
} else {
require('./pluginUtil').log(vars.app, `Ending development build for ${framework}`);
}
}
if (vars.buildstep == '2 of 2') {
if (vars.testing == true) {
require('./pluginUtil').log(vars.app, `Ending testing build for ${framework}`);
}
require('./pluginUtil').log(vars.app, `Ending production build for ${framework}`);
}
} catch (e) {
// require('./pluginUtil').logv(options.verbose,e)
throw '_done: ' + e.toString();
}
}
//**********
function _prepareForBuild(app, vars, options, output, compilation) {
try {
var verbose = options.verbose;
var packages = options.packages;
var toolkit = options.toolkit;
var theme = options.theme;
logv(verbose, 'FUNCTION _prepareForBuild');
const rimraf = require('rimraf');
const mkdirp = require('mkdirp');
const fsx = require('fs-extra');
const fs = require('fs');
const path = require('path');
theme = theme || (toolkit === 'classic' ? 'theme-triton' : 'theme-material');
logv(verbose, 'firstTime: ' + vars.firstTime);
if (vars.firstTime) {
rimraf.sync(output);
mkdirp.sync(output);
const buildXML = require('./artifacts').buildXML;
const createAppJson = require('./artifacts').createAppJson;
const createWorkspaceJson = require('./artifacts').createWorkspaceJson;
const createJSDOMEnvironment = require('./artifacts').createJSDOMEnvironment;
fs.writeFileSync(path.join(output, 'build.xml'), buildXML(vars.production, options, output), 'utf8');
fs.writeFileSync(path.join(output, 'app.json'), createAppJson(theme, packages, toolkit, options, output), 'utf8');
fs.writeFileSync(path.join(output, 'jsdom-environment.js'), createJSDOMEnvironment(options, output), 'utf8');
fs.writeFileSync(path.join(output, 'workspace.json'), createWorkspaceJson(options, output), 'utf8');
var framework = vars.framework;
//because of a problem with colorpicker
if (fs.existsSync(path.join(process.cwd(), `ext-${framework}/ux/`))) {
var fromPath = path.join(process.cwd(), `ext-${framework}/ux/`);
var toPath = path.join(output, 'ux');
fsx.copySync(fromPath, toPath);
log(app, 'Copying (ux) ' + fromPath.replace(process.cwd(), '') + ' to: ' + toPath.replace(process.cwd(), ''));
}
if (fs.existsSync(path.join(process.cwd(), `ext-${framework}/packages/`))) {
var fromPath = path.join(process.cwd(), `ext-${framework}/packages/`);
var toPath = path.join(output, 'packages');
fsx.copySync(fromPath, toPath);
log(app, 'Copying ' + fromPath.replace(process.cwd(), '') + ' to: ' + toPath.replace(process.cwd(), ''));
}
if (fs.existsSync(path.join(process.cwd(), `ext-${framework}/overrides/`))) {
var fromPath = path.join(process.cwd(), `ext-${framework}/overrides/`);
var toPath = path.join(output, 'overrides');
fsx.copySync(fromPath, toPath);
log(app, 'Copying ' + fromPath.replace(process.cwd(), '') + ' to: ' + toPath.replace(process.cwd(), ''));
}
if (fs.existsSync(path.join(process.cwd(), 'resources/'))) {
var fromResources = path.join(process.cwd(), 'resources/');
var toResources = path.join(output, '../resources');
fsx.copySync(fromResources, toResources);
log(app, 'Copying ' + fromResources.replace(process.cwd(), '') + ' to: ' + toResources.replace(process.cwd(), ''));
}
}
vars.firstTime = false;
var js = '';
if (vars.production) {
vars.deps = vars.deps.filter(function (value, index) {
return vars.deps.indexOf(value) == index;
});
js = vars.deps.join(';\n');
} else {
js = `Ext.require(["Ext.*","Ext.data.TreeStore"])`;
}
js = `Ext.require(["Ext.*","Ext.data.TreeStore"])`; //for now
if (vars.manifest === null || js !== vars.manifest) {
vars.manifest = js + ';\nExt.require(["Ext.layout.*"]);\n';
const manifest = path.join(output, 'manifest.js');
fs.writeFileSync(manifest, vars.manifest, 'utf8');
vars.rebuild = true;
var bundleDir = output.replace(process.cwd(), '');
if (bundleDir.trim() == '') {
bundleDir = './';
}
log(app, 'Building Ext bundle at: ' + bundleDir);
} else {
vars.rebuild = false;
log(app, 'Ext rebuild NOT needed');
}
} catch (e) {
require('./pluginUtil').logv(options.verbose, e);
compilation.errors.push('_prepareForBuild: ' + e);
}
}
//**********
function _buildExtBundle(app, compilation, outputPath, parms, vars, options) {
var verbose = options.verbose;
const fs = require('fs');
logv(verbose, 'FUNCTION _buildExtBundle');
let sencha;
try {
sencha = require('@sencha/cmd');
} catch (e) {
sencha = 'sencha';
}
if (fs.existsSync(sencha)) {
logv(verbose, 'sencha folder exists');
} else {
logv(verbose, 'sencha folder DOES NOT exist');
}
return new Promise((resolve, reject) => {
const onBuildDone = () => {
logv(verbose, 'onBuildDone');
resolve();
};
var opts = {
cwd: outputPath,
silent: true,
stdio: 'pipe',
encoding: 'utf-8'
};
_executeAsync(app, sencha, parms, opts, compilation, vars, options).then(function () {
onBuildDone();
}, function (reason) {
reject(reason);
});
});
}
//**********
function _executeAsync(_x6, _x7, _x8, _x9, _x10, _x11, _x12) {
return _executeAsync2.apply(this, arguments);
} //**********
function _executeAsync2() {
_executeAsync2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(app, command, parms, opts, compilation, vars, options) {
var verbose, framework, DEFAULT_SUBSTRS, substrings, chalk, crossSpawn;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
verbose = options.verbose;
framework = options.framework; //const DEFAULT_SUBSTRS = ['[INF] Loading', '[INF] Processing', '[LOG] Fashion build complete', '[ERR]', '[WRN]', "[INF] Server", "[INF] Writing", "[INF] Loading Build", "[INF] Waiting", "[LOG] Fashion waiting"];
DEFAULT_SUBSTRS = ["[INF] xServer", '[INF] Loading', '[INF] Append', '[INF] Processing', '[INF] Processing Build', '[LOG] Fashion build complete', '[ERR]', '[WRN]', "[INF] Writing", "[INF] Loading Build", "[INF] Waiting", "[LOG] Fashion waiting"];
substrings = DEFAULT_SUBSTRS;
chalk = require('chalk');
crossSpawn = require('cross-spawn-with-kill');
logv(verbose, 'FUNCTION _executeAsync');
_context2.next = 9;
return new Promise((resolve, reject) => {
logv(verbose, `command - ${command}`);
logv(verbose, `parms - ${parms}`);
logv(verbose, `opts - ${JSON.stringify(opts)}`);
vars.child = crossSpawn(command, parms, opts);
vars.child.on('close', (code, signal) => {
logv(verbose, `on close: ` + code);
if (code === 0) {
resolve(0);
} else {
compilation.errors.push(new Error(code));
resolve(0);
}
});
vars.child.on('error', error => {
logv(verbose, `on error`);
compilation.errors.push(error);
resolve(0);
});
vars.child.stdout.on('data', data => {
var str = data.toString().replace(/\r?\n|\r/g, " ").trim();
logv(verbose, `${str}`);
//if (data && data.toString().match(/Fashion waiting for changes\.\.\./)) {
if (data && data.toString().match(/aiting for changes\.\.\./)) {
// const fs = require('fs');
// var filename = process.cwd() + vars.touchFile;
// try {
// var d = new Date().toLocaleString()
// var data = fs.readFileSync(filename);
// fs.writeFileSync(filename, '//' + d, 'utf8');
// logv(app, `touching ${filename}`);
// }
// catch(e) {
// logv(app, `NOT touching ${filename}`);
// }
str = str.replace("[INF]", "");
str = str.replace("[LOG]", "");
str = str.replace(process.cwd(), '').trim();
if (str.includes("[ERR]")) {
compilation.errors.push(app + str.replace(/^\[ERR\] /gi, ''));
str = str.replace("[ERR]", `${chalk.red("[ERR]")}`);
}
log(app, str);
vars.callback();
resolve(0);
} else {
if (substrings.some(function (v) {
return data.indexOf(v) >= 0;
})) {
str = str.replace("[INF]", "");
str = str.replace("[LOG]", "");
str = str.replace(process.cwd(), '').trim();
if (str.includes("[ERR]")) {
compilation.errors.push(app + str.replace(/^\[ERR\] /gi, ''));
str = str.replace("[ERR]", `${chalk.red("[ERR]")}`);
}
log(app, str);
}
}
});
vars.child.stderr.on('data', data => {
logv(options, `error on close: ` + data);
var str = data.toString().replace(/\r?\n|\r/g, " ").trim();
var strJavaOpts = "Picked up _JAVA_OPTIONS";
var includes = str.includes(strJavaOpts);
if (!includes) {
console.log(`${app} ${chalk.red("[ERR]")} ${str}`);
}
});
});
case 9:
case "end":
return _context2.stop();
}
}, _callee2);
}));
return _executeAsync2.apply(this, arguments);
}
function runScript(scriptPath, callback) {
var childProcess = require('child_process');
// keep track of whether callback has been invoked to prevent multiple invocations
var invoked = false;
var process = childProcess.fork(scriptPath, [], {
execArgv: ['--inspect=0']
});
// listen for errors as they may prevent the exit event from firing
process.on('error', function (err) {
if (invoked) return;
invoked = true;
callback(err);
});
// execute the callback once the process has finished running
process.on('exit', function (code) {
if (invoked) return;
invoked = true;
var err = code === 0 ? null : new Error('exit code ' + code);
callback(err);
});
}
//**********
function _toXtype(str) {
return str.toLowerCase().replace(/_/g, '-');
}
//**********
function _getApp() {
var chalk = require('chalk');
var prefix = ``;
const platform = require('os').platform();
if (platform == 'darwin') {
prefix = `ℹ 「ext」:`;
} else {
prefix = `i [ext]:`;
}
return `${chalk.green(prefix)} `;
}
//**********
function _getVersions(pluginName, frameworkName) {
try {
const path = require('path');
const fs = require('fs');
var v = {};
var frameworkInfo = 'n/a';
v.pluginVersion = 'n/a';
v.extVersion = 'n/a';
v.edition = 'n/a';
v.cmdVersion = 'n/a';
v.webpackVersion = 'n/a';
var pluginPath = path.resolve(process.cwd(), 'node_modules/@sencha', pluginName);
var pluginPkg = fs.existsSync(pluginPath + '/package.json') && JSON.parse(fs.readFileSync(pluginPath + '/package.json', 'utf-8')) || {};
v.pluginVersion = pluginPkg.version;
v._resolved = pluginPkg._resolved;
if (v._resolved == undefined) {
v.edition = `Commercial`;
} else {
if (-1 == v._resolved.indexOf('community')) {
v.edition = `Commercial`;
} else {
v.edition = `Community`;
}
}
var webpackPath = path.resolve(process.cwd(), 'node_modules/webpack');
var webpackPkg = fs.existsSync(webpackPath + '/package.json') && JSON.parse(fs.readFileSync(webpackPath + '/package.json', 'utf-8')) || {};
v.webpackVersion = webpackPkg.version;
var extPath = path.resolve(process.cwd(), 'node_modules/@sencha/ext');
var extPkg = fs.existsSync(extPath + '/package.json') && JSON.parse(fs.readFileSync(extPath + '/package.json', 'utf-8')) || {};
v.extVersion = extPkg.sencha.version;
var cmdPath = path.resolve(process.cwd(), `node_modules/@sencha/cmd`);
var cmdPkg = fs.existsSync(cmdPath + '/package.json') && JSON.parse(fs.readFileSync(cmdPath + '/package.json', 'utf-8')) || {};
v.cmdVersion = cmdPkg.version_full;
if (v.cmdVersion == undefined) {
var cmdPath = path.resolve(process.cwd(), `node_modules/@sencha/${pluginName}/node_modules/@sencha/cmd`);
var cmdPkg = fs.existsSync(cmdPath + '/package.json') && JSON.parse(fs.readFileSync(cmdPath + '/package.json', 'utf-8')) || {};
v.cmdVersion = cmdPkg.version_full;
}
if (frameworkName != undefined && frameworkName != 'extjs') {
var frameworkPath = '';
if (frameworkName == 'react') {
frameworkPath = path.resolve(process.cwd(), 'node_modules/react');
}
if (frameworkName == 'angular') {
frameworkPath = path.resolve(process.cwd(), 'node_modules/@angular/core');
}
var frameworkPkg = fs.existsSync(frameworkPath + '/package.json') && JSON.parse(fs.readFileSync(frameworkPath + '/package.json', 'utf-8')) || {};
v.frameworkVersion = frameworkPkg.version;
if (v.frameworkVersion == undefined) {
frameworkInfo = ', ' + frameworkName;
} else {
frameworkInfo = ', ' + frameworkName + ' v' + v.frameworkVersion;
}
}
return 'ext-webpack-plugin v' + v.pluginVersion + ', Ext JS v' + v.extVersion + ' ' + v.edition + ' Edition, Sencha Cmd v' + v.cmdVersion + ', webpack v' + v.webpackVersion + frameworkInfo;
} catch (e) {
return 'ext-webpack-plugin v' + v.pluginVersion + ', Ext JS v' + v.extVersion + ' ' + v.edition + ' Edition, Sencha Cmd v' + v.cmdVersion + ', webpack v' + v.webpackVersion + frameworkInfo;
}
}
//**********
function log(app, message) {
var s = app + message;
require('readline').cursorTo(process.stdout, 0);
try {
process.stdout.clearLine();
} catch (e) {}
process.stdout.write(s);
process.stdout.write('\n');
}
//**********
function logh(app, message) {
var h = false;
var s = app + message;
if (h == true) {
require('readline').cursorTo(process.stdout, 0);
try {
process.stdout.clearLine();
} catch (e) {}
process.stdout.write(s);
process.stdout.write('\n');
}
}
//**********
function logv(verbose, s) {
if (verbose == 'yes') {
require('readline').cursorTo(process.stdout, 0);
try {
process.stdout.clearLine();
} catch (e) {}
process.stdout.write(`-verbose: ${s}`);
process.stdout.write('\n');
}
}
function _getValidateOptions() {
return {
"type": "object",
"properties": {
"framework": {
"type": ["string"]
},
"toolkit": {
"type": ["string"]
},
"theme": {
"type": ["string"]
},
"emit": {
"errorMessage": "should be 'yes' or 'no' string value (NOT true or false)",
"type": ["string"]
},
"script": {
"type": ["string"]
},
"port": {
"type": ["integer"]
},
"packages": {
"type": ["string", "array"]
},
"profile": {
"type": ["string"]
},
"environment": {
"errorMessage": "should be 'development' or 'production' string value",
"type": ["string"]
},
"treeshake": {
"errorMessage": "should be 'yes' or 'no' string value (NOT true or false)",
"type": ["string"]
},
"browser": {
"errorMessage": "should be 'yes' or 'no' string value (NOT true or false)",
"type": ["string"]
},
"watch": {
"errorMessage": "should be 'yes' or 'no' string value (NOT true or false)",
"type": ["string"]
},
"verbose": {
"errorMessage": "should be 'yes' or 'no' string value (NOT true or false)",
"type": ["string"]
},
"inject": {
"errorMessage": "should be 'yes' or 'no' string value (NOT true or false)",
"type": ["string"]
},
"intellishake": {
"errorMessage": "should be 'yes' or 'no' string value (NOT true or false)",
"type": ["string"]
},
"cmdopts": {
"errorMessage": "should be a sencha cmd option or argument string",
"type": ["string", "array"]
}
},
"additionalProperties": false
};
}
function _getDefaultOptions() {
return {
framework: 'extjs',
toolkit: 'modern',
theme: 'theme-material',
emit: 'yes',
script: null,
port: 1962,
packages: [],
profile: '',
environment: 'development',
treeshake: 'no',
browser: 'yes',
watch: 'yes',
verbose: 'no',
inject: 'yes',
intellishake: 'yes',
cmdopts: ''
};
}
function smartFlowPing(packageJsonPath, appJsonPath) {
const {
exec
} = require('child_process');
const path = require('path');
const fs = require('fs');
fs.readFile(packageJsonPath, 'utf8', (errPackage, dataPackage) => {
if (errPackage) {
return;
}
const packageJson = JSON.parse(dataPackage);
fs.readFile(appJsonPath, 'utf8', (errApp, dataApp) => {
if (errApp) {
return;
}
const appJson = JSON.parse(dataApp);
const requiresArray = appJson.requires; // Assuming appJson.requires is an array
// Convert the array to a string
const modifiedString = requiresArray[0].replace(/[\[\]']+/g, '');
const homeDirectory = process.env.HOME || process.env.USERPROFILE;
// Specify the relative path from the home directory to your file
const relativeFilePath = '.npmrc';
// Combine the home directory and relative file path to get the generalized file path
const filePath = path.join(homeDirectory, relativeFilePath);
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
console.error(`Error reading file: ${err.message}`);
return;
}
const registryRegex = /@sencha:registry=(.+)/;
// Extract the registry URL using the regular expression
const match = data.match(registryRegex);
// Check if a match is found
if (match && match[1]) {
const registryUrl = match[1];
// Use npm-config to set the registry temporarily for the current process
process.env.npm_config_registry = registryUrl;
// Run the npm whoami command
exec(`npm --registry ${registryUrl} whoami`, (error, stdout, stderr) => {
if (error) {
return;
}
const username = `${stdout.trim().replace('..', '@')}`;
let additionalLicenseInfo = '';
let licensedFeature = '';
if (username != null) {
additionalLicenseInfo = 'This version of Sencha Ext-gen is licensed commercially';
licensedFeature = 'LEGAL';
} else {
additionalLicenseInfo = 'This version of Sencha Ext-gen is not licensed commercially';
licensedFeature = 'UNLICENSED';
}
const scriptType = process.env.npm_lifecycle_event;
let triggerevent = 'build';
if (scriptType === 'dev' || scriptType === 'dev:desktop') {
triggerevent = `npm start`;
} else if (scriptType === 'build' || scriptType === 'build:desktop') {
triggerevent = `npm run build`;
} else {
triggerevent = `null`;
}
const licenseinfo = `"license=Commercial, framework=EXTJS, License Content Text=Sencha RapidExtJS-JavaScript Library Copyright, Sencha Inc. All rights reserved. licensing@sencha.com options:http://www.sencha.com/license license: http://www.sencha.com/legal/sencha-software-license-agreement Commercial License.-----------------------------------------------------------------------------------------Sencha RapidExtJS is licensed commercially. See http://www.sencha.com/legal/sencha-software-license-agreement for license terms.Beta License------------------------------------------------------------------------------------------ If this is a Beta version , use is permitted for internal evaluation and review purposes and not use for production purposes. See http://www.sencha.com/legal/sencha-software-license-agreement (Beta License) for license terms. Third Party Content------------------------------------------------------------------------------------------The following third party software is distributed with RapidExtJS and is provided under other licenses and/or has source available from other locations. Library: YUI 0.6 (BSD Licensed) for drag-and-drop code. Location: http://developer.yahoo.com/yui License: http://developer.yahoo.com/yui/license.html (BSD 3-Clause License) Library: JSON parser Location: http://www.JSON.org/js.html License: http://www.json.org/license.html (MIT License) Library: flexible-js-formatting Location: http://code.google.com/p/flexible-js-formatting/ License: http://www.opensource.org/licenses/mit-license.php (MIT License) Library: sparkline.js Location: http://omnipotent.net/jquery.sparkline License http://omnipotent.net/jquery.sparkline (BSD 3-Clause License) Library: DeftJS Location: http://deftjs.org/ License: http://www.opensource.org/licenses/mit-license.php (MIT License) Library: Open-Sans Location: http://www.fontsquirrel.com/fonts/open-sans License: http://www.fontsquirrel.com/fonts/open-sans (Apache 2.0 License) Examples: Library: Silk Icons Location: http://www.famfamfam.com/lab/icons/silk/ License: http://www.famfamfam.com/lab/icons/silk/ (Creative Commons Attribution 2.5 License) Library: Font Awesome CSS Location: http://fontawesome.io/ License: http://fontawesome.io/3.2.1/license/ (MIT) Library: Material Design Icons Location: https://github.com/google/material-design-icons License: https://github.com/google/material-design-icons/blob/master/LICENSE (Apache) THIS SOFTWARE IS DISTRIBUTED 'AS-IS' WITHOUT ANY WARRANTIES, CONDITIONS AND REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. , message=This version of Sencha RapidExtJS is licensed commercially "`;
const jarPath = path.join(__dirname, '..', 'resources', 'utils.jar');
const featuresUsed = `ext-gen, ${modifiedString}`;
const encryptedLicense = btoa(licenseinfo);
const command = `java -jar ${jarPath} ` + `-product ext-gen -productVersion ${packageJson.version} ` + `-eventType LEGAL -trigger ${triggerevent} ` + `-licensedTo ${username} ` + `-custom2 isValid=true -custom3 isTrial=false -custom4 isExpired=false -mode rapid ` + `-validLicenseInfo ${encryptedLicense} -featuresUsed ${featuresUsed} -licensedFeature ${licensedFeature} -piracyLicenseInfo ${additionalLicenseInfo}`;
exec(command, (error, stdout, stderr) => {
if (error) {
return;
}
if (stderr) {
return;
}
});
});
}
});
});
});
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJfcmVnZW5lcmF0b3JSdW50aW1lIiwiZSIsInQiLCJyIiwiT2JqZWN0IiwicHJvdG90eXBlIiwibiIsImhhc093blByb3BlcnR5IiwibyIsImRlZmluZVByb3BlcnR5IiwidmFsdWUiLCJpIiwiU3ltYm9sIiwiYSIsIml0ZXJhdG9yIiwiYyIsImFzeW5jSXRlcmF0b3IiLCJ1IiwidG9TdHJpbmdUYWciLCJkZWZpbmUiLCJlbnVtZXJhYmxlIiwiY29uZmlndXJhYmxlIiwid3JpdGFibGUiLCJ3cmFwIiwiR2VuZXJhdG9yIiwiY3JlYXRlIiwiQ29udGV4dCIsIm1ha2VJbnZva2VNZXRob2QiLCJ0cnlDYXRjaCIsInR5cGUiLCJhcmciLCJjYWxsIiwiaCIsImwiLCJmIiwicyIsInkiLCJHZW5lcmF0b3JGdW5jdGlvbiIsIkdlbmVyYXRvckZ1bmN0aW9uUHJvdG90eXBlIiwicCIsImQiLCJnZXRQcm90b3R5cGVPZiIsInYiLCJ2YWx1ZXMiLCJnIiwiZGVmaW5lSXRlcmF0b3JNZXRob2RzIiwiZm9yRWFjaCIsIl9pbnZva2UiLCJBc3luY0l0ZXJhdG9yIiwiaW52b2tlIiwicmVzb2x2ZSIsIl9fYXdhaXQiLCJ0aGVuIiwiY2FsbEludm9rZVdpdGhNZXRob2RBbmRBcmciLCJFcnJvciIsImRvbmUiLCJtZXRob2QiLCJkZWxlZ2F0ZSIsIm1heWJlSW52b2tlRGVsZWdhdGUiLCJzZW50IiwiX3NlbnQiLCJkaXNwYXRjaEV4Y2VwdGlvbiIsImFicnVwdCIsInJldHVybiIsIlR5cGVFcnJvciIsInJlc3VsdE5hbWUiLCJuZXh0IiwibmV4dExvYyIsInB1c2hUcnlFbnRyeSIsInRyeUxvYyIsImNhdGNoTG9jIiwiZmluYWxseUxvYyIsImFmdGVyTG9jIiwidHJ5RW50cmllcyIsInB1c2giLCJyZXNldFRyeUVudHJ5IiwiY29tcGxldGlvbiIsInJlc2V0IiwiaXNOYU4iLCJsZW5ndGgiLCJkaXNwbGF5TmFtZSIsImlzR2VuZXJhdG9yRnVuY3Rpb24iLCJjb25zdHJ1Y3RvciIsIm5hbWUiLCJtYXJrIiwic2V0UHJvdG90eXBlT2YiLCJfX3Byb3RvX18iLCJhd3JhcCIsImFzeW5jIiwiUHJvbWlzZSIsImtleXMiLCJyZXZlcnNlIiwicG9wIiwicHJldiIsImNoYXJBdCIsInNsaWNlIiwic3Rv