@bitrix/cli
Version:
Bitrix CLI tools
313 lines (302 loc) • 11.9 kB
JavaScript
;
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var jsdom = require('jsdom');
var mocha = _interopDefault(require('mocha'));
var assert = _interopDefault(require('assert'));
var sinon = _interopDefault(require('sinon'));
var v8 = _interopDefault(require('v8'));
var vm = _interopDefault(require('vm'));
var os = _interopDefault(require('os'));
var fs = _interopDefault(require('fs'));
var slash = _interopDefault(require('slash'));
var path = _interopDefault(require('path'));
const appRoot = path.resolve(__dirname, '../');
const lockFile = path.resolve(os.homedir(), '.bitrix.lock');
function resolvePackageModule(moduleName) {
return path.resolve(appRoot, 'node_modules', moduleName);
}
function resolveRootDirectoryByCwd(cwd) {
if (typeof cwd === 'string' && cwd.length > 0) {
if (cwd.includes('modules')) {
const [modulesPath] = /.*modules/.exec(cwd);
if (typeof modulesPath === 'string' && fs.existsSync(path.join(modulesPath, 'main')) && fs.existsSync(path.join(modulesPath, 'ui'))) {
return {
rootPath: modulesPath,
type: 'modules'
};
}
}
if (cwd.includes('local')) {
const localPath = path.dirname(/.*local/.exec(cwd)[0]);
if (typeof localPath === 'string' && fs.existsSync(path.join(localPath, 'bitrix'))) {
return {
rootPath: localPath,
type: 'product'
};
}
}
if (cwd.includes('bitrix')) {
const productPath = path.dirname(/.*bitrix/.exec(cwd)[0]);
if (typeof productPath === 'string' && fs.existsSync(path.join(productPath, 'bitrix')) && fs.existsSync(path.join(productPath, 'bitrix', 'js')) && fs.existsSync(path.join(productPath, 'bitrix', 'modules'))) {
return {
rootPath: productPath,
type: 'product'
};
}
}
const productPath = path.dirname(cwd);
if (fs.existsSync(path.join(productPath, 'bitrix')) && fs.existsSync(path.join(productPath, 'bitrix', 'js')) && fs.existsSync(path.join(productPath, 'bitrix', 'modules'))) {
return {
rootPath: productPath,
type: 'product'
};
}
if (productPath !== path.sep && !/^[A-Z]:\\$/.test(productPath)) {
return resolveRootDirectoryByCwd(productPath);
}
}
return null;
}
function resolveExtension(options) {
const extensionPath = (() => {
const rootDirectory = (() => {
if (options.cwd) {
return resolveRootDirectoryByCwd(options.cwd);
}
return resolveRootDirectoryByCwd(path.dirname(options.sourcePath));
})();
if (rootDirectory) {
const nameSegments = options.name.split('.');
const [moduleName] = nameSegments;
if (rootDirectory.type === 'modules') {
return path.join(rootDirectory.rootPath, moduleName, 'install', 'js', ...nameSegments);
}
if (rootDirectory.type === 'product') {
const localExtension = path.join(rootDirectory.rootPath, 'local', 'js', ...nameSegments);
if (fs.existsSync(localExtension)) {
return localExtension;
}
const productExtension = path.join(rootDirectory.rootPath, 'bitrix', 'js', ...nameSegments);
if (fs.existsSync(productExtension)) {
return productExtension;
}
}
}
return null;
})();
if (typeof extensionPath === 'string') {
const configPath = path.join(extensionPath, 'bundle.config.js');
if (fs.existsSync(configPath)) {
const config = require(configPath);
if (config) {
return {
context: extensionPath,
input: path.join(extensionPath, config.input),
bundleConfig: configPath
};
}
}
}
return null;
}
function fetchMessages(filePath) {
const result = {};
if (fs.existsSync(filePath)) {
const contents = fs.readFileSync(filePath, 'ascii');
const regex = /\$MESS\[['"](?<code>.+?)['"]]\s*=\s*['"](?<phrase>.*?)['"]/gm;
let match;
while ((match = regex.exec(contents)) !== null) {
if (match.index === regex.lastIndex) {
regex.lastIndex++;
}
result[match.groups.code] = match.groups.phrase;
}
}
return result;
}
function loadMessages(options = {}) {
if (Object.hasOwn(options, 'extension')) {
const extensions = [options.extension].flat();
extensions.forEach(extension => {
const resolverResult = resolveExtension(extension);
if (resolverResult) {
loadMessages({
langFile: path.join(resolverResult.context, 'lang', extension.lang, 'config.php')
});
}
});
}
if (typeof options.langFile === 'string') {
const messages = fetchMessages(options.langFile);
const setMessage = (() => {
var _global$window, _global$window$BX, _global$window$BX$Loc;
if ((_global$window = global.window) !== null && _global$window !== void 0 && (_global$window$BX = _global$window.BX) !== null && _global$window$BX !== void 0 && (_global$window$BX$Loc = _global$window$BX.Loc) !== null && _global$window$BX$Loc !== void 0 && _global$window$BX$Loc.setMessage) {
var _global$window2, _global$window2$BX, _global$window2$BX$Lo;
return (_global$window2 = global.window) === null || _global$window2 === void 0 ? void 0 : (_global$window2$BX = _global$window2.BX) === null || _global$window2$BX === void 0 ? void 0 : (_global$window2$BX$Lo = _global$window2$BX.Loc) === null || _global$window2$BX$Lo === void 0 ? void 0 : _global$window2$BX$Lo.setMessage;
}
if (!global.window.BX) {
global.window.BX = {};
}
if (!global.window.BX.message) {
global.window.BX.message = messages => {
if (typeof messages === 'object' && messages !== null) {
Object.assign(global.window.BX.message, messages);
}
};
}
return global.window.BX.message;
})();
if (setMessage) {
setMessage(messages);
}
}
if (Array.isArray(options.langFile)) {
options.langFile.forEach(filePath => {
loadMessages({
langFile: filePath
});
});
}
}
const maxDepth = 10;
function findExtensionContext(sourcePath, depth = 0) {
const configPath = path.join(sourcePath, 'bundle.config.js');
if (fs.existsSync(configPath)) {
return sourcePath;
}
if (sourcePath.length > 1 && depth < maxDepth) {
const nextDepth = depth + 1;
const dirname = path.dirname(sourcePath);
return findExtensionContext(dirname, nextDepth);
}
return null;
}
function buildExtensionName(filePath, context) {
const moduleExp = new RegExp('/(.[a-z0-9_-]+)/install/js/(.[a-z0-9_-]+)/');
const moduleRes = `${slash(filePath)}`.match(moduleExp);
if (Array.isArray(moduleRes)) {
const fragments = `${slash(context)}`.split(`${moduleRes[1]}/install/js/${moduleRes[2]}/`);
return `${moduleRes[2]}.${fragments[fragments.length - 1].replace(/\/$/, '').split('/').join('.')}`;
}
const localExp = new RegExp('/local/js/(.[a-z0-9_-]+)/(.[a-z0-9_-]+)/');
const localRes = `${slash(filePath)}`.match(localExp);
if (!Array.isArray(localRes)) {
return path.basename(context);
}
const fragments = `${slash(context)}`.split(`/local/js/${localRes[1]}/`);
return `${localRes[1]}.${fragments[fragments.length - 1].replace(/\/$/, '').split('/').join('.')}`;
}
v8.setFlagsFromString('--expose-gc');
global.gc = vm.runInNewContext('gc');
let weak;
try {
// eslint-disable-next-line global-require,import/no-extraneous-dependencies
weak = require('weak');
} catch (e) {
weak = (obj, callback) => {
callback();
console.warn('@bitrix/cli: weak is not installed');
};
}
global.sinon = sinon;
global.assert = assert;
global.describe = mocha.describe;
global.it = mocha.it;
global.xit = mocha.xit;
global.before = mocha.before;
global.beforeEach = mocha.beforeEach;
global.after = mocha.after;
global.afterEach = mocha.afterEach;
global.setup = mocha.setup;
global.suite = mocha.suite;
global.suiteSetup = mocha.suiteSetup;
global.suiteTeardown = mocha.suiteTeardown;
global.teardown = mocha.teardown;
global.test = mocha.test;
global.run = mocha.run;
global.weak = weak;
global.loadMessages = loadMessages;
const DOM = new jsdom.JSDOM('', {
url: 'https://example.org/',
referrer: 'https://example.com/',
contentType: 'text/html',
includeNodeLocations: true,
storageQuota: 10000000,
pretendToBeVisual: true
});
global.window = DOM.window;
global.document = DOM.window.document;
global.Node = DOM.window.Node;
global.Element = DOM.window.Element;
global.DOMParser = DOM.window.DOMParser;
global.FormData = DOM.window.FormData;
global.File = DOM.window.File;
global.Blob = DOM.window.Blob;
global.BlobBuilder = DOM.window.BlobBuilder;
global.FileReader = DOM.window.FileReader;
Object.keys(DOM.window).forEach(property => {
if (typeof global[property] === 'undefined') {
global[property] = DOM.window[property];
}
});
require('../public/babel-regenerator-runtime');
require.extensions['.css'] = () => null;
require.extensions['.png'] = () => null;
require.extensions['.jpg'] = () => null;
function isExtensionName(value) {
return /(^\w+)\.(.*)/.test(String(value));
}
const langPhrasesLoaded = new Set();
function moduleResolver(sourcePath, currentFile) {
if (isExtensionName(sourcePath)) {
const resolverResult = resolveExtension({
name: sourcePath,
sourcePath: currentFile
});
if (resolverResult) {
if (fs.existsSync(resolverResult.bundleConfig)) {
var _config$tests, _config$tests$localiz;
const config = require(resolverResult.bundleConfig);
const extensionName = buildExtensionName(resolverResult.input, resolverResult.context);
if ((config === null || config === void 0 ? void 0 : (_config$tests = config.tests) === null || _config$tests === void 0 ? void 0 : (_config$tests$localiz = _config$tests.localization) === null || _config$tests$localiz === void 0 ? void 0 : _config$tests$localiz.autoLoad) !== false && !langPhrasesLoaded.has(extensionName)) {
var _config$tests$localiz2, _config$tests2, _config$tests2$locali;
langPhrasesLoaded.add(extensionName);
loadMessages({
extension: {
name: extensionName,
lang: (_config$tests$localiz2 = config === null || config === void 0 ? void 0 : (_config$tests2 = config.tests) === null || _config$tests2 === void 0 ? void 0 : (_config$tests2$locali = _config$tests2.localization) === null || _config$tests2$locali === void 0 ? void 0 : _config$tests2$locali.languageId) !== null && _config$tests$localiz2 !== void 0 ? _config$tests$localiz2 : 'en',
cwd: resolverResult.context
}
});
}
}
return resolverResult.input;
}
return 'assert';
}
if (!sourcePath.startsWith('.') && !currentFile.includes('@bitrix') && !currentFile.includes('node_modules') && !currentFile.endsWith('.test.js')) {
const context = findExtensionContext(currentFile);
if (context && fs.existsSync(path.join(context, 'node_modules', sourcePath))) {
return sourcePath;
}
return 'assert';
}
return '';
}
require('@babel/register')({
cwd: (() => {
const cwd = process.cwd();
if (cwd.includes('/modules')) {
return path.resolve(cwd.split('/modules')[0], '../../../../../');
}
if (cwd.includes('/bitrix')) {
return path.resolve(cwd.split('/bitrix')[0], '../../../../../');
}
return path.resolve(cwd, '../../../../../');
})(),
presets: [resolvePackageModule('@babel/preset-env')],
plugins: [[resolvePackageModule('babel-plugin-module-resolver'), {
resolvePath: moduleResolver
}], resolvePackageModule('@babel/plugin-transform-flow-strip-types'), resolvePackageModule('@babel/plugin-proposal-class-properties'), resolvePackageModule('@babel/plugin-proposal-private-methods')],
cache: false
});