burst-generate-files
Version:
package module for generate files
1,153 lines (1,079 loc) • 63.5 kB
JavaScript
var burstGenerateFiles;
/******/ (() => { // webpackBootstrap
/******/ "use strict";
/******/ var __webpack_modules__ = ({
/***/ 365:
/***/ ((module) => {
module.exports = require("enquirer");
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
/******/ /* webpack/runtime/compat get default export */
/******/ (() => {
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = (module) => {
/******/ var getter = module && module.__esModule ?
/******/ () => (module['default']) :
/******/ () => (module);
/******/ __webpack_require__.d(getter, { a: getter });
/******/ return getter;
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/define property getters */
/******/ (() => {
/******/ // define getter functions for harmony exports
/******/ __webpack_require__.d = (exports, definition) => {
/******/ for(var key in definition) {
/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ }
/******/ }
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/ (() => {
/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ })();
/******/
/******/ /* webpack/runtime/make namespace object */
/******/ (() => {
/******/ // define __esModule on exports
/******/ __webpack_require__.r = (exports) => {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/ })();
/******/
/************************************************************************/
var __webpack_exports__ = {};
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
CLIGen: () => (/* binding */ CLIGen),
customGen: () => (/* binding */ customGen),
markersGen: () => (/* binding */ markersGen)
});
;// external "fs"
const external_fs_namespaceObject = require("fs");
var external_fs_default = /*#__PURE__*/__webpack_require__.n(external_fs_namespaceObject);
;// external "path"
const external_path_namespaceObject = require("path");
var external_path_default = /*#__PURE__*/__webpack_require__.n(external_path_namespaceObject);
;// ./src/utils/makeAbsolutePath/index.ts
// Core
const ifExistsFileReturnAbsolutePath = ({ rootPath, path }) => {
const absolutePath = (0,external_path_namespaceObject.resolve)(rootPath, path);
if (external_fs_default().existsSync(absolutePath)) {
return absolutePath;
}
return path;
};
const makeAbsolutePath = ({ rootPath, setting }) => {
const newSetting = setting;
// Setting pathToTemplate
if (Array.isArray(newSetting.pathToTemplate)) {
newSetting.pathToTemplate = newSetting.pathToTemplate.map((path) => (0,external_path_namespaceObject.resolve)(rootPath, path));
}
if (typeof newSetting.pathToTemplate === 'string') {
newSetting.pathToTemplate = (0,external_path_namespaceObject.resolve)(rootPath, newSetting.pathToTemplate);
}
// Setting outputPath
if (Array.isArray(newSetting.outputPath)) {
newSetting.outputPath = newSetting.outputPath.map((path) => (0,external_path_namespaceObject.resolve)(rootPath, path));
}
if (typeof newSetting.outputPath === 'string') {
newSetting.outputPath = (0,external_path_namespaceObject.resolve)(rootPath, newSetting.outputPath);
}
// Setting markers
if (Array.isArray(newSetting.markers)) {
newSetting.markers = newSetting.markers.map((marker) => {
const newMarker = marker;
// Setting pathToMarker
if (Array.isArray(newMarker.pathToMarker)) {
newMarker.pathToMarker = newMarker.pathToMarker.map((path) => {
return ifExistsFileReturnAbsolutePath({ rootPath, path });
});
}
if (typeof newMarker.pathToMarker === 'string') {
newMarker.pathToMarker = (0,external_path_namespaceObject.resolve)(rootPath, newMarker.pathToMarker);
}
// Setting markerTemplate
if (Array.isArray(newMarker.markerTemplate)) {
newMarker.markerTemplate = newMarker.markerTemplate.map((string) => {
return ifExistsFileReturnAbsolutePath({ rootPath, path: string });
});
}
if (typeof newMarker.pathToMarker === 'string') {
const absolutePath = (0,external_path_namespaceObject.resolve)(rootPath, newMarker.pathToMarker);
if (external_fs_default().existsSync(absolutePath)) {
newMarker.pathToMarker = absolutePath;
}
}
return newMarker;
});
}
return newSetting;
};
;// ./src/constants.ts
// Core
const nameFolderForMarkers = '.genignore';
const nameConfigGenerateForOnceInsert = 'config.generate.files.json';
const PROJECT_ROOT = external_path_default().resolve();
const spaces = ' ';
const CUSTOM_ERROR = 'customError';
var PREFIXES;
(function (PREFIXES) {
PREFIXES["CASE"] = "Case";
})(PREFIXES || (PREFIXES = {}));
var DEFAULT_WORDS_CASES;
(function (DEFAULT_WORDS_CASES) {
DEFAULT_WORDS_CASES["CAMEL"] = "camelCase";
DEFAULT_WORDS_CASES["NO"] = "noCase";
DEFAULT_WORDS_CASES["PASCAL"] = "pascalCase";
DEFAULT_WORDS_CASES["CONSTANT"] = "constantCase";
DEFAULT_WORDS_CASES["KEBAB"] = "kebabCase";
DEFAULT_WORDS_CASES["DOT"] = "dotCase";
DEFAULT_WORDS_CASES["LOWER"] = "lowerCase";
DEFAULT_WORDS_CASES["PATH"] = "pathCase";
DEFAULT_WORDS_CASES["SENTENCE"] = "sentenceCase";
DEFAULT_WORDS_CASES["SNAKE"] = "snakeCase";
DEFAULT_WORDS_CASES["TITLE"] = "titleCase";
})(DEFAULT_WORDS_CASES || (DEFAULT_WORDS_CASES = {}));
const DEFAULT_WORDS_CASES_ARRAY = Object.values(DEFAULT_WORDS_CASES);
;// ./src/utils/replaceWordCase/index.ts
// Constants
const cases = ({ stringReplace, result }) => {
let newString = stringReplace.value.split(' ');
if (newString.length <= 1 && /.*[A-Z]/.test(stringReplace.value) && stringReplace.value.toUpperCase() !== stringReplace.value) {
const arrCamelCase = stringReplace.value.split('').map((letter, index) => {
if (index !== 0 && /[A-Z]/.test(letter)) {
return ' ' + letter;
}
return letter;
});
newString = arrCamelCase.join('').split(' ');
}
let newResult = result;
const camelCase = (word, indexWord) => {
if (indexWord === 0) {
return word
.split('')
.map((letter) => letter.toLowerCase())
.join('');
}
return (word[0].toUpperCase() +
word
.slice(1)
.split('')
.map((letter) => letter.toLowerCase())
.join(''));
};
const regexpNo = `${stringReplace.replaceVar}.${DEFAULT_WORDS_CASES.NO}.`;
if (result && new RegExp(regexpNo).test(result)) {
// lorem lorem => lorem lorem
const re = new RegExp(regexpNo, 'g');
const modifiedToPascalCase = newString.join(' ');
newResult = newResult.replace(re, modifiedToPascalCase);
}
const regexpCamel = `${stringReplace.replaceVar}.${DEFAULT_WORDS_CASES.CAMEL}.`;
if (result && new RegExp(regexpCamel).test(result)) {
// Lorem lorem => loremLorem
const re = new RegExp(regexpCamel, 'g');
const modifiedToPascalCase = newString.map((word, index) => camelCase(word, index)).join('');
newResult = newResult.replace(re, modifiedToPascalCase);
}
const regexpPascal = `${stringReplace.replaceVar}.${DEFAULT_WORDS_CASES.PASCAL}.`;
if (result && new RegExp(regexpPascal).test(result)) {
// lorem lorem => LoremLorem
const re = new RegExp(regexpPascal, 'g');
const modifiedToPascalCase = newString
.map((word) => word[0].toUpperCase() +
word
.slice(1)
.split('')
.map((latter) => latter.toLowerCase())
.join(''))
.join('');
newResult = newResult.replace(re, modifiedToPascalCase);
}
const regexpConstant = `${stringReplace.replaceVar}.${DEFAULT_WORDS_CASES.CONSTANT}.`;
if (result && new RegExp(regexpConstant).test(result)) {
// lorem lorem => LOREM_LOREM
const re = new RegExp(regexpConstant, 'g');
const modifiedToConstantCase = newString.map((word) => word.toUpperCase()).join('_');
newResult = newResult.replace(re, modifiedToConstantCase);
}
const regexpKebab = `${stringReplace.replaceVar}.${DEFAULT_WORDS_CASES.KEBAB}.`;
if (result && new RegExp(regexpKebab).test(result)) {
// lorem lorem => lorem-lorem
const re = new RegExp(regexpKebab, 'g');
const modifiedToKebabCase = newString.map((word) => word.toLowerCase()).join('-');
newResult = newResult.replace(re, modifiedToKebabCase);
}
const regexpDot = `${stringReplace.replaceVar}.${DEFAULT_WORDS_CASES.DOT}.`;
if (result && new RegExp(regexpDot).test(result)) {
// lorem lorem => lorem.lorem
const re = new RegExp(regexpDot, 'g');
const modifiedToKebabCase = newString.map((word) => word.toLowerCase()).join('.');
newResult = newResult.replace(re, modifiedToKebabCase);
}
const regexpLower = `${stringReplace.replaceVar}.${DEFAULT_WORDS_CASES.LOWER}.`;
if (result && new RegExp(regexpLower).test(result)) {
// LOREM LoRem => loremlorem
const re = new RegExp(regexpLower, 'g');
const modifiedToKebabCase = newString.map((word) => word.toLowerCase()).join('');
newResult = newResult.replace(re, modifiedToKebabCase);
}
const regexpPath = `${stringReplace.replaceVar}.${DEFAULT_WORDS_CASES.PATH}.`;
if (result && new RegExp(regexpPath).test(result)) {
// lorem lorem => lorem/lorem
const re = new RegExp(regexpPath, 'g');
const modifiedToKebabCase = newString.map((word) => word.toLowerCase()).join('/');
newResult = newResult.replace(re, modifiedToKebabCase);
}
const regexpSentence = `${stringReplace.replaceVar}.${DEFAULT_WORDS_CASES.SENTENCE}.`;
if (result && new RegExp(regexpSentence).test(result)) {
// lorem lorem => Lorem lorem
const re = new RegExp(regexpSentence, 'g');
const modifiedToKebabCase = newString
.map((word, index) => {
if (index === 0) {
return word
.split('')
.map((letter, index) => (index === 0 ? letter.toUpperCase() : letter))
.join('');
}
return word;
})
.join(' ');
newResult = newResult.replace(re, modifiedToKebabCase);
}
const regexpSnake = `${stringReplace.replaceVar}.${DEFAULT_WORDS_CASES.SNAKE}.`;
if (result && new RegExp(regexpSnake).test(result)) {
// lorem lorem => lorem_lorem
const re = new RegExp(regexpSnake, 'g');
const modifiedToKebabCase = newString.map((word) => word.toLowerCase()).join('_');
newResult = newResult.replace(re, modifiedToKebabCase);
}
const regexpTitle = `${stringReplace.replaceVar}.${DEFAULT_WORDS_CASES.TITLE}.`;
if (result && new RegExp(regexpTitle).test(result)) {
// lorem lorem => Lorem Lorem
const re = new RegExp(regexpTitle, 'g');
const modifiedToKebabCase = newString
.map((word) => word[0].toUpperCase() +
word
.slice(1)
.split('')
.map((letter) => letter.toLowerCase())
.join(''))
.join(' ');
newResult = newResult.replace(re, modifiedToKebabCase);
}
// DEFAULT_WORDS_CASES.CAMEL
const defaultCamel = stringReplace.replaceVar;
if (result && new RegExp(defaultCamel).test(result)) {
// lorem lorem => loremLorem
const re = new RegExp(defaultCamel, 'g');
const modifiedToDefault = newString.map((word, index) => camelCase(word, index)).join('');
newResult = newResult.replace(re, modifiedToDefault);
}
return newResult;
};
const replaceWordCase = ({ string, stringsForReplace }) => {
let result = string;
if (Array.isArray(stringsForReplace)) {
stringsForReplace.forEach((stringReplace) => {
result = cases({ stringReplace, result });
});
}
if (!Array.isArray(stringsForReplace) && stringsForReplace.replaceVar) {
result = cases({ stringReplace: stringsForReplace, result });
}
return result;
};
;// external "chalk"
const external_chalk_namespaceObject = require("chalk");
var external_chalk_default = /*#__PURE__*/__webpack_require__.n(external_chalk_namespaceObject);
;// ./src/utils/catchErrors/index.ts
// Core
// Constants
const catchErrors = ({ error, showFullError }) => {
const headerError = '\nErrors burst-generate-files:';
if (Array.isArray(error)) {
console.error(external_chalk_default().red(headerError));
for (let i = 0; i < error.length; i++) {
if (!showFullError && error[i].name === CUSTOM_ERROR) {
console.error(``);
console.error(error[i].message);
}
else {
console.error(``);
console.error(error[i]);
}
}
return;
}
if (error && typeof error === 'object') {
console.error(external_chalk_default().red(headerError));
if (!showFullError && 'name' in error && error.name === CUSTOM_ERROR && 'message' in error && error.message === CUSTOM_ERROR) {
console.error(``);
console.error(error.message);
}
else {
console.error(``);
console.error(error);
}
}
};
;// ./src/utils/removeDuplicateArray.ts
const removeDuplicateArray = (array) => {
return [...new Set(array)];
};
;// ./src/utils/createErrorsZod/index.ts
// Constants
const betweenTwoLines = `:\n`;
const createErrorsZod = ({ validationResult, whichParameter, errors }) => {
if (!validationResult.success) {
const result = [...errors];
validationResult.error.errors.forEach((objError) => {
const objErrorPath = `>>> at the ${whichParameter} parameter of the function: ${objError.path.join('.')} <<<`;
const causeOfCustomError = objError;
const newError = new Error(`${objError.code}: ${objError.message + betweenTwoLines + objErrorPath}`, {
cause: causeOfCustomError,
});
newError.name = CUSTOM_ERROR;
result.push(newError);
});
return result;
}
else {
return [];
}
};
;// ./src/utils/index.ts
;// external "zod"
const external_zod_namespaceObject = require("zod");
;// ./src/actions/checkError/utils.ts
// Core
const checkRefineCallback = (rootPath) => (path) => {
if (Array.isArray(path)) {
return path.every((p) => external_fs_default().existsSync((0,external_path_namespaceObject.resolve)(rootPath, p)));
}
return external_fs_default().existsSync((0,external_path_namespaceObject.resolve)(rootPath, path));
};
const getRefineParams = (rootPath, params) => (path) => {
const arrayPathToTemplate = [path].flat(Infinity);
const result = arrayPathToTemplate.flat(Infinity).filter((p) => typeof p === 'string' && !external_fs_default().existsSync((0,external_path_namespaceObject.resolve)(rootPath, p)));
return Object.assign({ message: `${result.join(', ')} ${result.length === 1 ? 'is' : 'are'} not exist`, path: [...((params === null || params === void 0 ? void 0 : params.path) || []), ...path] }, params);
};
const validateMarkerPattern = ({ rootPath, objectMarker, pathToMarker, ctx, pathCtx, }) => {
if (external_fs_default().existsSync((0,external_path_namespaceObject.resolve)(rootPath, pathToMarker))) {
const contentOfFile = external_fs_default().readFileSync(pathToMarker, 'utf-8');
if ((typeof objectMarker.pattern === 'string' && !contentOfFile.includes(objectMarker.pattern)) ||
(objectMarker.pattern === RegExp(objectMarker.pattern) && !objectMarker.pattern.test(contentOfFile))) {
ctx.addIssue({
code: external_zod_namespaceObject.z.ZodIssueCode.invalid_date,
path: [...ctx.path, ...pathCtx],
message: `the pattern "${objectMarker.pattern}" is not found in the file ${pathToMarker}`,
});
}
}
};
;// ./src/actions/checkError/schemas.ts
// Core
// Utils
const getSchemaMarkers = (rootPath, path) => external_zod_namespaceObject.z.array(external_zod_namespaceObject.z.object({
pattern: external_zod_namespaceObject.z.union([external_zod_namespaceObject.z.string(), external_zod_namespaceObject.z.instanceof(RegExp)]),
pathToMarker: external_zod_namespaceObject.z
.union([external_zod_namespaceObject.z.string(), external_zod_namespaceObject.z.array(external_zod_namespaceObject.z.string())])
.refine(checkRefineCallback(rootPath), getRefineParams(rootPath, { path })),
markerTemplate: external_zod_namespaceObject.z
.union([external_zod_namespaceObject.z.string(), external_zod_namespaceObject.z.array(external_zod_namespaceObject.z.string())])
.refine(checkRefineCallback(rootPath), getRefineParams(rootPath, { path })),
genDirection: external_zod_namespaceObject.z.enum(['after', 'before']).optional(),
onceInsert: external_zod_namespaceObject.z.boolean().optional(),
}));
const commonSchemaOfOptionalSettings = {
rootPath: external_zod_namespaceObject.z
.string()
.refine((path) => typeof path === 'string' && external_fs_default().existsSync((0,external_path_namespaceObject.resolve)(path)), (path) => ({ message: `${path} is not exist` }))
.optional(),
};
const schemaOutputPath = {
outputPath: external_zod_namespaceObject.z.union([external_zod_namespaceObject.z.string(), external_zod_namespaceObject.z.array(external_zod_namespaceObject.z.string())]),
};
const getCommonSchema = (rootPath) => (Object.assign(Object.assign({ pathToTemplate: external_zod_namespaceObject.z.union([external_zod_namespaceObject.z.string(), external_zod_namespaceObject.z.array(external_zod_namespaceObject.z.string())]) }, schemaOutputPath), { markers: getSchemaMarkers(rootPath).optional(), onComplete: external_zod_namespaceObject.z.function().args(external_zod_namespaceObject.z.unknown()).returns(external_zod_namespaceObject.z.void()).optional() }));
const validateMarkerPatterns = ({ settings, pathCtx, ctx, rootPath, }) => {
settings.forEach((template, indexTemplate) => {
if (template.markers && template.outputPath && !template.selectDirectory) {
template.markers.forEach((objectMarker, indexOfObjectMarker) => {
if (Array.isArray(objectMarker.pathToMarker)) {
objectMarker.pathToMarker.forEach((pathToMarker, indexOfPathToMarker) => {
validateMarkerPattern({
rootPath,
objectMarker,
pathToMarker,
ctx,
pathCtx: [...(pathCtx || []), indexTemplate, 'markers', indexOfObjectMarker, pathToMarker, indexOfPathToMarker],
});
});
}
else {
validateMarkerPattern({
rootPath,
objectMarker,
pathToMarker: objectMarker.pathToMarker,
ctx,
pathCtx: [...(pathCtx || []), indexTemplate, 'markers', indexOfObjectMarker, 'pathToMarker'],
});
}
});
}
});
};
;// ./src/actions/checkError/checkCustomGen/index.ts
// Core
// Utils
// Schemas
const checkCustomGen = ({ settings, optionalOfSettings, rootPath }) => {
const errors = [];
const schemaStringsReplacers = external_zod_namespaceObject.z.object({
replaceVar: external_zod_namespaceObject.z.string(),
value: external_zod_namespaceObject.z.string(),
});
const schemaSettings = external_zod_namespaceObject.z
.array(external_zod_namespaceObject.z.object(Object.assign({ stringsReplacers: external_zod_namespaceObject.z.union([schemaStringsReplacers, external_zod_namespaceObject.z.array(schemaStringsReplacers)]), selectDirectory: external_zod_namespaceObject.z.undefined() }, getCommonSchema(rootPath))))
.superRefine((arraySettings, ctx) => {
validateMarkerPatterns({
settings: arraySettings,
pathCtx: [],
ctx,
rootPath,
});
});
const schemaOptionalSettings = external_zod_namespaceObject.z
.object(Object.assign(Object.assign({}, commonSchemaOfOptionalSettings), { showFullError: external_zod_namespaceObject.z.boolean().optional() }))
.optional();
const validationResultSettings = schemaSettings.safeParse(settings);
const validationResultOptionalSettings = schemaOptionalSettings.safeParse(optionalOfSettings);
errors.push(...createErrorsZod({
validationResult: validationResultSettings,
whichParameter: 'first',
errors,
}), ...createErrorsZod({
validationResult: validationResultOptionalSettings,
whichParameter: 'second',
errors,
}));
// Errors
if (errors.length > 0) {
throw errors;
}
};
;// ./src/actions/checkError/checkCLIGen/index.ts
// Core
// Utils
// Schemas
const checkCLIGen = ({ settings, optionalOfSettings, rootPath }) => {
const errors = [];
const schemaSettings = external_zod_namespaceObject.z
.array(external_zod_namespaceObject.z.object({
name: external_zod_namespaceObject.z.string(),
templates: external_zod_namespaceObject.z.array(external_zod_namespaceObject.z.object(Object.assign({ stringsReplacers: external_zod_namespaceObject.z.union([external_zod_namespaceObject.z.string(), external_zod_namespaceObject.z.array(external_zod_namespaceObject.z.string())]), selectDirectory: external_zod_namespaceObject.z.boolean().optional() }, getCommonSchema(rootPath)))),
}))
.superRefine((arraySettings, ctx) => {
arraySettings.forEach((setting, indexSetting) => {
validateMarkerPatterns({
settings: setting.templates,
pathCtx: [indexSetting, 'templates'],
ctx,
rootPath,
});
});
});
const schemaOptionalSettings = external_zod_namespaceObject.z
.object(Object.assign(Object.assign({}, commonSchemaOfOptionalSettings), { showFullError: external_zod_namespaceObject.z.boolean().optional() }))
.optional();
const validationResultSettings = schemaSettings.safeParse(settings);
const validationResultOptionalSettings = schemaOptionalSettings.safeParse(optionalOfSettings);
errors.push(...createErrorsZod({
validationResult: validationResultSettings,
whichParameter: 'first',
errors,
}), ...createErrorsZod({
validationResult: validationResultOptionalSettings,
whichParameter: 'second',
errors,
}));
// Errors
if (errors.length > 0) {
throw errors;
}
};
const checkMarkersOfCLIGen = ({ settings: template, rootPath, index, }) => {
const errors = [];
const schema = external_zod_namespaceObject.z
.object(Object.assign(Object.assign({}, schemaOutputPath), { markers: getSchemaMarkers(rootPath).optional() }))
.superRefine((templateOfSuperRefine, ctx) => {
validateMarkerPatterns({
settings: [templateOfSuperRefine],
pathCtx: [index, 'templates'],
ctx,
rootPath,
});
});
const validationResultSettings = schema.safeParse(template);
errors.push(...createErrorsZod({
validationResult: validationResultSettings,
whichParameter: 'first',
errors,
}));
// Errors
if (errors.length > 0) {
throw errors;
}
};
;// ./src/actions/checkError/checkMarkersGen/index.ts
// Core
// Utils
// Schemas
const checkMarkersGen = ({ settings, optionalOfSettings, rootPath }) => {
const errors = [];
const selectedNamesSchema = external_zod_namespaceObject.z.object({
replaceVar: external_zod_namespaceObject.z.string(),
value: external_zod_namespaceObject.z.string(),
});
const schemaSettings = external_zod_namespaceObject.z.object({
selectedNames: selectedNamesSchema.or(external_zod_namespaceObject.z.array(selectedNamesSchema)),
markers: getSchemaMarkers(rootPath),
});
const schemaOptionalSettings = external_zod_namespaceObject.z
.object(Object.assign({}, commonSchemaOfOptionalSettings))
.optional();
const validationResultSettings = schemaSettings.safeParse(settings);
const validationResultOptionalSettings = schemaOptionalSettings.safeParse(optionalOfSettings);
errors.push(...createErrorsZod({
validationResult: validationResultSettings,
whichParameter: 'first',
errors,
}), ...createErrorsZod({
validationResult: validationResultOptionalSettings,
whichParameter: 'second',
errors,
}));
// Errors
if (errors.length > 0) {
throw errors;
}
};
;// ./src/actions/checkError/index.ts
// EXTERNAL MODULE: external "enquirer"
var external_enquirer_ = __webpack_require__(365);
var external_enquirer_default = /*#__PURE__*/__webpack_require__.n(external_enquirer_);
;// ./src/actions/getSelectedItem/index.ts
var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
// Core
const getSelectedItem = (settings) => __awaiter(void 0, void 0, void 0, function* () {
const getNamesForShowingInCLI = () => {
const result = settings.map((setting) => setting.name);
return result;
};
const gotValue = yield external_enquirer_default().prompt({
type: 'autocomplete',
name: 'settingChoice',
message: 'What do you want to generate?',
choices: getNamesForShowingInCLI(),
});
return settings.find((item) => item.name === gotValue.settingChoice);
});
;// ./src/actions/getSelectedName/index.ts
var getSelectedName_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __asyncValues = (undefined && undefined.__asyncValues) || function (o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
// Core
const getNameFromCLI = (_a) => getSelectedName_awaiter(void 0, [_a], void 0, function* ({ message, name }) {
const gotValue = yield external_enquirer_default().prompt({
type: 'input',
name: name,
message: message,
validate: (value) => {
const isValid = Boolean(value.trim());
return isValid || 'You must provide an answer!!!';
},
});
return gotValue.selectedName.trim();
});
const getSelectedName = (strings) => getSelectedName_awaiter(void 0, void 0, void 0, function* () {
var _a, strings_1, strings_1_1;
var _b, e_1, _c, _d;
let result = [];
if (Array.isArray(strings)) {
try {
for (_a = true, strings_1 = __asyncValues(strings); strings_1_1 = yield strings_1.next(), _b = strings_1_1.done, !_b; _a = true) {
_d = strings_1_1.value;
_a = false;
const string = _d;
result = [
...result,
{
replaceVar: string,
value: yield getNameFromCLI({ message: `Replace ${string} on`, name: 'selectedName' }),
},
];
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (!_a && !_b && (_c = strings_1.return)) yield _c.call(strings_1);
}
finally { if (e_1) throw e_1.error; }
}
}
if (!Array.isArray(strings)) {
result = [
...result,
{
replaceVar: strings,
value: yield getNameFromCLI({ message: `Replace ${strings} on`, name: 'selectedName' }),
},
];
}
return result;
});
;// ./src/actions/selectDirectory/askDirectory/constants.ts
const slash = '\\';
const firstPartOfMessage = 'Select a directory!\n Current directory: ';
const firstPartOfMessageForSelectingWordCase = 'Select a word case!\n Current directory: ';
var CONTROLLERS;
(function (CONTROLLERS) {
CONTROLLERS["BACK"] = "../";
CONTROLLERS["HERE"] = "./";
CONTROLLERS["OPTION_CANCEL"] = "# Back to select directory";
})(CONTROLLERS || (CONTROLLERS = {}));
var CONTROLLERS_CREATE_NEW_FOLDER;
(function (CONTROLLERS_CREATE_NEW_FOLDER) {
CONTROLLERS_CREATE_NEW_FOLDER["MAIN"] = "# Create new folder";
CONTROLLERS_CREATE_NEW_FOLDER["OPTION_CANCEL"] = "# Back to option \"Crete new folder\"";
})(CONTROLLERS_CREATE_NEW_FOLDER || (CONTROLLERS_CREATE_NEW_FOLDER = {}));
var CONTROLLERS_CREATE_NEW_FOLDER_BY_STRINGS_REPLACERS;
(function (CONTROLLERS_CREATE_NEW_FOLDER_BY_STRINGS_REPLACERS) {
CONTROLLERS_CREATE_NEW_FOLDER_BY_STRINGS_REPLACERS["MAIN"] = "# Create new folder by stringsReplacers";
CONTROLLERS_CREATE_NEW_FOLDER_BY_STRINGS_REPLACERS["OPTION_CANCEL"] = "# Back to option \"Create new folder by stringsReplacers\"";
})(CONTROLLERS_CREATE_NEW_FOLDER_BY_STRINGS_REPLACERS || (CONTROLLERS_CREATE_NEW_FOLDER_BY_STRINGS_REPLACERS = {}));
const controllersDirectories = [CONTROLLERS.BACK, CONTROLLERS.HERE, CONTROLLERS_CREATE_NEW_FOLDER.MAIN];
const getOptionsOfCreateNewFolder = (stringsReplacers) => [
CONTROLLERS_CREATE_NEW_FOLDER.OPTION_CANCEL,
...stringsReplacers,
];
;// ./src/actions/selectDirectory/askDirectory/getDirectories.ts
// Core
// Constants
// Utils
const getDirectories = ({ currentDirectory, outputAbsolutePath, selectedNames }) => {
const splittedOutputAbsolutePath = outputAbsolutePath.split(slash);
const splittedCurrentDirectory = currentDirectory.split('\\');
const lastFolderCurrentDirectory = splittedCurrentDirectory.at(-1);
const numberCurrentFolderOfOutputAbsolutePath = splittedOutputAbsolutePath.indexOf(lastFolderCurrentDirectory);
const nextFolder = numberCurrentFolderOfOutputAbsolutePath >= 0 ? splittedOutputAbsolutePath[numberCurrentFolderOfOutputAbsolutePath + 1] : null;
const getFolders = (directory) => external_fs_default().readdirSync(replaceWordCase({
string: directory,
stringsForReplace: selectedNames,
}), { withFileTypes: true })
.filter((dir) => dir.isDirectory())
.map((dir) => '/' + dir.name);
const isExistsDirectory = (directory) => external_fs_default().existsSync(replaceWordCase({
string: directory,
stringsForReplace: selectedNames,
}));
if (selectedNames.some((selectedName) => outputAbsolutePath.includes(selectedName.replaceVar))) {
if (currentDirectory !== outputAbsolutePath) {
if (isExistsDirectory(currentDirectory)) {
if (nextFolder && outputAbsolutePath.includes((0,external_path_namespaceObject.resolve)(currentDirectory, nextFolder))) {
return removeDuplicateArray([...controllersDirectories, `/${nextFolder}`, ...getFolders(currentDirectory)]);
}
return [...controllersDirectories, ...getFolders(currentDirectory)];
}
if (nextFolder) {
return [...controllersDirectories, `/${nextFolder}`];
}
return [...controllersDirectories];
}
if (currentDirectory === outputAbsolutePath) {
if (isExistsDirectory(currentDirectory)) {
return [...controllersDirectories, ...getFolders(currentDirectory)];
}
return [...controllersDirectories];
}
}
if (isExistsDirectory(currentDirectory)) {
return [...controllersDirectories, ...getFolders(currentDirectory)];
}
return [...controllersDirectories];
};
;// ./src/actions/selectDirectory/askDirectory/index.ts
var askDirectory_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
// Core
// eslint-disable-next-line @typescript-eslint/no-require-imports
const { AutoComplete } = __webpack_require__(365);
// Constants
// Functions
const askDirectory = (_a) => askDirectory_awaiter(void 0, [_a], void 0, function* ({ outputPath, selectedNames }) {
class CustomAutoComplete extends AutoComplete {
constructor(options) {
super(options);
this.outputPath = options.outputPath;
this.currentDirectory = options.outputPath;
this.mode = null;
}
focusOnFirstChoice() {
this.index = Math.max(0, Math.min(0, this.choices.length));
this.enable(this.find(this.index));
}
changeValue(string) {
if (string === './') {
return this.currentDirectory;
}
return string;
}
changeChoices(newChoices) {
super.choices = newChoices.map((nameNewChoice, index) => {
return Object.assign(Object.assign({}, super.choices[0]), { index: index, name: nameNewChoice, message: nameNewChoice, value: this.changeValue(nameNewChoice), path: nameNewChoice });
});
}
submit() {
// Core start
if (this.options.multiple) {
this.value = this.selected.map((ch) => ch.name);
}
// Core end
if (this.selected.name === controllersDirectories[0]) {
// ../
this.currentDirectory = (0,external_path_namespaceObject.resolve)(this.currentDirectory, '..');
this.options.message = firstPartOfMessage + this.currentDirectory;
const gotDirectories = getDirectories({
currentDirectory: this.currentDirectory,
outputAbsolutePath: this.outputPath,
selectedNames,
});
this.changeChoices(gotDirectories);
this.render();
return;
}
if (this.selected.name === controllersDirectories[1]) {
// ./
super.choices = [...super.choices].map((choice) => {
if (choice.name === controllersDirectories[1]) {
return Object.assign(Object.assign({}, choice), { value: this.currentDirectory });
}
return choice;
});
return super.submit();
}
if (this.selected.name === CONTROLLERS_CREATE_NEW_FOLDER.MAIN ||
this.selected.name === CONTROLLERS_CREATE_NEW_FOLDER.OPTION_CANCEL) {
// create new folder (system settings)
this.changeChoices([CONTROLLERS.OPTION_CANCEL, CONTROLLERS_CREATE_NEW_FOLDER_BY_STRINGS_REPLACERS.MAIN]);
this.focusOnFirstChoice();
this.render();
return;
}
else if (this.selected.name === CONTROLLERS.OPTION_CANCEL) {
// leave create new folder (system settings)
const gotDirectories = getDirectories({
currentDirectory: this.currentDirectory,
outputAbsolutePath: this.outputPath,
selectedNames,
});
this.changeChoices(gotDirectories);
this.focusOnFirstChoice();
this.render();
return;
}
else if (this.selected.name === CONTROLLERS_CREATE_NEW_FOLDER_BY_STRINGS_REPLACERS.MAIN ||
this.selected.name === CONTROLLERS_CREATE_NEW_FOLDER_BY_STRINGS_REPLACERS.OPTION_CANCEL) {
// go to Create new folder by stringsReplacers (list stringsReplacers)
this.mode = CONTROLLERS_CREATE_NEW_FOLDER_BY_STRINGS_REPLACERS.MAIN;
this.changeChoices(getOptionsOfCreateNewFolder(selectedNames.map((name) => '/' + name.replaceVar)));
this.focusOnFirstChoice();
this.render();
return;
}
else if (this.mode === CONTROLLERS_CREATE_NEW_FOLDER_BY_STRINGS_REPLACERS.MAIN &&
selectedNames.some((selectedName) => selectedName.replaceVar === this.selected.name.replace('/', ''))) {
// select word case
this.currentDirectory = (0,external_path_namespaceObject.resolve)(this.currentDirectory, this.selected.name.replace('/', ''));
this.options.message = firstPartOfMessageForSelectingWordCase + this.currentDirectory;
this.changeChoices([CONTROLLERS_CREATE_NEW_FOLDER_BY_STRINGS_REPLACERS.OPTION_CANCEL, ...DEFAULT_WORDS_CASES_ARRAY]);
this.focusOnFirstChoice();
this.render();
return;
}
else if (DEFAULT_WORDS_CASES_ARRAY.some((wordCase) => wordCase === this.selected.name)) {
this.mode = null;
this.currentDirectory += `(${this.selected.name})`;
this.options.message = firstPartOfMessage + this.currentDirectory;
const gotDirectories = getDirectories({
currentDirectory: this.currentDirectory,
outputAbsolutePath: this.outputPath,
selectedNames,
});
this.changeChoices(gotDirectories);
this.focusOnFirstChoice();
this.render();
return;
}
this.currentDirectory = (0,external_path_namespaceObject.resolve)(this.currentDirectory, this.selected.value.replace('/', ''));
this.options.message = firstPartOfMessage + this.currentDirectory;
const gotDirectories = getDirectories({
currentDirectory: this.currentDirectory,
outputAbsolutePath: this.outputPath,
selectedNames,
});
this.changeChoices(gotDirectories);
this.focusOnFirstChoice();
this.render();
}
}
const promptCustomAutoComplete = new CustomAutoComplete({
name: 'selectDirectory',
outputPath,
message: firstPartOfMessage + outputPath,
choices: getDirectories({
currentDirectory: outputPath,
outputAbsolutePath: outputPath,
selectedNames,
}),
});
const resultPrompt = yield promptCustomAutoComplete.run();
return resultPrompt;
});
;// ./src/actions/selectDirectory/index.ts
var selectDirectory_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var selectDirectory_asyncValues = (undefined && undefined.__asyncValues) || function (o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
// Core
// Constants
// Functions
const showWarningsAboutCheckMarkers = ({ template, newOutputPath }) => {
const messageForChanging = '\nYou changed outputPath:';
const log = (text) => {
console.warn(spaces + text);
};
const lastPartOfMessage = () => {
var _a;
console.warn(external_chalk_default().yellow('You have to check your markers !!!\nYour markers:'));
(_a = template.markers) === null || _a === void 0 ? void 0 : _a.forEach((marker) => {
if (typeof marker.pathToMarker === 'string') {
log(marker.pathToMarker);
}
if (Array.isArray(marker.pathToMarker)) {
marker.pathToMarker.forEach((pathToMarker) => {
log(pathToMarker);
});
}
});
};
if (typeof newOutputPath === 'string' && template.outputPath !== newOutputPath) {
console.warn(external_chalk_default().yellow(messageForChanging));
log(newOutputPath);
lastPartOfMessage();
}
if (Array.isArray(newOutputPath) && newOutputPath.some((newPath) => !template.outputPath.includes(newPath))) {
console.warn(external_chalk_default().yellow(messageForChanging));
newOutputPath.forEach((newPath) => {
if (!template.outputPath.includes(newPath)) {
log(newPath);
}
});
lastPartOfMessage();
}
};
const selectDirectory = (_a) => selectDirectory_awaiter(void 0, [_a], void 0, function* ({ template, selectedNames }) {
var _b, e_1, _c, _d;
if (typeof template.outputPath === 'string') {
yield askDirectory({
outputPath: template.outputPath,
selectedNames,
}).then((resultPromise) => {
if (template.markers) {
showWarningsAboutCheckMarkers({
template,
newOutputPath: resultPromise,
});
}
template.outputPath = resultPromise;
});
}
if (Array.isArray(template.outputPath)) {
const result = { value: [] };
try {
for (var _e = true, _f = selectDirectory_asyncValues(template.outputPath), _g; _g = yield _f.next(), _b = _g.done, !_b; _e = true) {
_d = _g.value;
_e = false;
const iteratorOutputPath = _d;
yield askDirectory({
outputPath: iteratorOutputPath,
selectedNames,
}).then((resultPromise) => {
result.value = [...result.value, resultPromise];
});
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (!_e && !_b && (_c = _f.return)) yield _c.call(_f);
}
finally { if (e_1) throw e_1.error; }
}
if (template.markers) {
showWarningsAboutCheckMarkers({
template,
newOutputPath: result.value,
});
}
template.outputPath = result.value;
}
});
;// ./src/actions/createFiles/index.ts
// Core
// Constants
// Utils
const createFiles = ({ pathToTemplate, outputPath, selectedNames }) => {
const copyDir = (copyDirSrc, copyDirDest) => {
const copy = (copySrc, copyDest) => {
const list = external_fs_default().readdirSync(copySrc);
list.forEach((item) => {
const ss = external_path_default().resolve(copySrc, item);
const stat = external_fs_default().statSync(ss);
const curSrc = external_path_default().resolve(copySrc, item);
const curDest = replaceWordCase({
string: external_path_default().resolve(copyDest, item),
stringsForReplace: selectedNames,
});
if (stat.isFile()) {
const content = external_fs_default().readFileSync(curSrc, 'utf-8');
const modifiedContent = replaceWordCase({
string: content,
stringsForReplace: selectedNames,
});
external_fs_default().writeFileSync(curDest, modifiedContent);
}
else if (stat.isDirectory() && external_path_default().basename(curSrc) !== nameFolderForMarkers) {
external_fs_default().mkdirSync(curDest, { recursive: true });
copy(curSrc, curDest);
}
});
};
if (Array.isArray(copyDirDest)) {
copyDirDest
.map((string) => replaceWordCase({
string,
stringsForReplace: selectedNames,
}))
.forEach((dest) => {
try {
external_fs_default().accessSync(dest);
}
catch (_a) {
external_fs_default().mkdirSync(dest, { recursive: true });
}
copy(copyDirSrc, dest);
});
}
if (typeof copyDirDest === 'string') {
const rightDest = replaceWordCase({
string: copyDirDest,
stringsForReplace: selectedNames,
});
try {
external_fs_default().accessSync(rightDest);
}
catch (_a) {
external_fs_default().mkdirSync(rightDest, { recursive: true });
}
copy(copyDirSrc, rightDest);
}
};
if (Array.isArray(pathToTemplate)) {
pathToTemplate.forEach((templatePath) => {
copyDir(templatePath, outputPath);
});
return;
}
copyDir(pathToTemplate, outputPath);
};
;// ./src/