"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.$Global = void 0;
//#region imports
const lib_1 = require("incremental-compiler/lib");
const semver = require("semver");
const lib_2 = require("tnp-core/lib");
const lib_3 = require("tnp-core/lib");
const lib_4 = require("tnp-core/lib");
const lib_5 = require("tnp-core/lib");
const lib_6 = require("tnp-core/lib");
const lib_7 = require("tnp-core/lib");
const lib_8 = require("tnp-core/lib");
const lib_9 = require("tnp-core/lib");
const lib_10 = require("tnp-core/lib");
const lib_11 = require("tnp-helpers/lib");
const lib_12 = require("tnp-helpers/lib");
const ts_json_schema_generator_1 = require("ts-json-schema-generator");
const build_info__auto_generated_1 = require("../../build-info._auto-generated_");
const constants_1 = require("../../constants");
const options_1 = require("../../options");
const project_1 = require("../abstract/project");
//#endregion
class $Global extends lib_11.BaseGlobalCommandLine {
    async _() {
        //#region @backendFunc
        await this.ins.taonProjectsWorker.terminalUI.infoScreen();
        //#endregion
    }
    async hasSudoCommand() {
        //#region @backendFunc
        const hasSudo = await lib_3.UtilsOs.commandExistsAsync('sudo');
        console.log(`Your os has sudo: ${hasSudo}`);
        this._exit();
        //#endregion
    }
    anymatch() {
        //#region @backendFunc
        // const anymatch = require('anymatch');
        // const f = '/home/dfilipiak/projects/npm/taon-dev/taon/tmp-all-assets-linked';
        // const exclude = anymatch([
        //   '/home/dfilipiak/projects/npm/taon-dev/taon/tmp-*/**',
        //   '/home/dfilipiak/projects/npm/taon-dev/taon/tmp-*',
        //   '/home/dfilipiak/projects/npm/taon-dev/taon/tmp-all-assets-linked',
        // ], path.basename(f));
        // Helpers.info(`
        //           exclude folder ${f} : ${exclude}`);
        // this._exit();
        //#endregion
    }
    //#region add etc hosts entry
    addEtcHostsEntry() {
        //#region @backendFunc
        const [ip, domain, comment] = this.args || [];
        lib_10.UtilsNetwork.setEtcHost(domain, ip, comment);
        lib_11.Helpers.info(`Added entry: ${lib_5.chalk.bold(`${ip} ${domain}`)} to ${lib_3.UtilsEtcHosts.getPath()} `);
        this._exit();
        //#endregion
    }
    //#endregion
    //#region simulate domain
    simulateDomain() {
        //#region @backendFunc
        if (this.project?.framework?.isStandaloneProject) {
            const domain = this.project.environmentConfig.getEnvMain()?.website?.domain;
            if (domain) {
                this.args = [domain, ...this.args];
                return super.simulateDomain();
            }
        }
        super.simulateDomain();
        //#endregion
    }
    //#endregion
    //#region detect packages
    async detectPackages() {
        //#region @backendFunc
        this.project.removeFile(constants_1.tmpIsomorphicPackagesJson);
        await this.project.packagesRecognition.start('detecting packages');
        // console.log(this.project.framework.a)
        this._exit();
        //#endregion
    }
    //#endregion
    //#region kill process on port
    async killonport() {
        //#region @backendFunc
        const port = parseInt(this.firstArg);
        await lib_11.Helpers.killProcessByPort(port);
        this._exit();
        //#endregion
    }
    //#endregion
    //#region kill all node processes
    killAllNode() {
        //#region @backendFunc
        lib_11.HelpersTaon.killAllNode();
        this._exit();
        //#endregion
    }
    //#endregion
    //#region kill all node
    async killAllJava() {
        //#region @backendFunc
        lib_11.Helpers.info('Killing all java processes...');
        await lib_4.UtilsProcess.killAllJava();
        lib_11.Helpers.info('DONE KILL ALL JAVA PROCESSES');
        this._exit();
        //#endregion
    }
    //#endregion
    //#region fork
    async fork() {
        //#region @backendFunc
        lib_11.Helpers.error(`Not implemented yet`, false, true);
        return; // TODO
        const argv = this.args;
        const githubUrl = lib_5._.first(argv);
        let projectName = lib_5._.last(githubUrl.replace('.git', '').split('/'));
        if (argv.length > 1) {
            projectName = argv[1];
        }
        lib_11.Helpers.info(`Forking ${githubUrl} with name ${projectName}`);
        await this.project.git.clone(githubUrl, projectName);
        let newProj = this.ins.From(lib_5.path.join(this.project.location, projectName));
        lib_11.HelpersTaon.setValueToJSON(lib_5.path.join(newProj.location, constants_1.packageJsonMainProject), 'name', projectName);
        lib_11.HelpersTaon.setValueToJSON(lib_5.path.join(newProj.location, constants_1.packageJsonMainProject), 'version', '0.0.0');
        lib_11.Helpers.writeFile(newProj.pathFor(constants_1.readmeMdMainProject), `
  # ${projectName}

  based on ${githubUrl}

    `);
        lib_11.Helpers.run(`${await this.ins.editor()} ${newProj.location}`).sync();
        lib_11.Helpers.info(`Done`);
        this._exit();
        //#endregion
    }
    //#endregion
    //#region watcher linux
    watchersfix() {
        //#region @backendFunc
        lib_11.Helpers.run(`echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p`).sync();
        this._exit();
        //#endregion
    }
    watchers() {
        //#region @backendFunc
        lib_11.Helpers.run(`find /proc/*/fd -user "$USER" -lname anon_inode:inotify -printf '%hinfo/%f\n' 2>/dev/null | xargs cat | grep -c '^inotify'`).sync();
        this._exit();
        //#endregion
    }
    //#endregion
    //#region code instal ext
    async code() {
        //#region @backendFunc
        this.project
            .run(`${await this.ins.editor()} --install-extension ${this.args.join(' ')}`)
            .sync();
        this._exit();
        //#endregion
    }
    //#endregion
    //#region proper watcher test
    async PROPERWATCHERTEST(engine) {
        //#region @backendFunc
        // const proj = this.project as Project;
        const cwd = this.cwd;
        const watchLocation = (0, lib_5.crossPlatformPath)([cwd, constants_1.srcMainProject]);
        const symlinkCatalog = (0, lib_5.crossPlatformPath)([cwd, 'symlinkCatalog']);
        const symlinkCatalogInWatch = (0, lib_5.crossPlatformPath)([watchLocation, 'symlink']);
        const symlinkCatalogFile = (0, lib_5.crossPlatformPath)([
            cwd,
            'symlinkCatalog',
            'aaa.txt',
        ]);
        const options = {
            name: `[taon]  properwatchtest (testing only)`,
            // ignoreInitial: true,
            followSymlinks: false,
        };
        lib_11.Helpers.remove(watchLocation);
        lib_11.Helpers.remove(symlinkCatalog);
        lib_11.Helpers.writeFile(symlinkCatalogFile, 'hello aaa');
        lib_11.Helpers.writeFile((0, lib_5.crossPlatformPath)([watchLocation, 'a1', 'aa']), 'asdasdasdhello aaa');
        lib_11.Helpers.writeFile((0, lib_5.crossPlatformPath)([watchLocation, 'a2', 'ccc']), 'heasdasdllo asdasd');
        lib_11.Helpers.createSymLink(symlinkCatalog, symlinkCatalogInWatch);
        (0, lib_1.incrementalWatcher)([watchLocation], { ...options, engine: 'chokidar' }).on('all', (a, b) => {
            console.log('CHOKIDAR', a, b);
        });
        (0, lib_1.incrementalWatcher)([watchLocation], {
            ...options,
            engine: '@parcel/watcher',
        }).on('all', (a, b) => {
            console.log('PARCEL', a, b);
        });
        //#endregion
    }
    //#endregion
    //#region add import src
    /**
     * @deprecated
     */
    ADD_IMPORT_SRC() {
        //#region @backendFunc
        const project = this.project;
        const regexEnd = /from\s+(\'|\").+(\'|\")/g;
        const singleLineImporrt = /import\((\'|\"|\`).+(\'|\"|\`)\)/g;
        const singleLineRequire = /require\((\'|\"|\`).+(\'|\"|\`)\)/g;
        const srcEnd = /\/src(\'|\"|\`)/;
        const betweenApos = /(\'|\"|\`).+(\'|\"|\`)/g;
        const commentMultilieStart = /^\/\*/;
        const commentSingleLineStart = /^\/\//;
        const processAddSrcAtEnd = (regexEnd, line, packages, matchType) => {
            const matches = line.match(regexEnd);
            const firstMatch = lib_5._.first(matches);
            const importMatch = lib_5._.first(firstMatch.match(betweenApos)).replace(/(\'|\"|\`)/g, '');
            const isOrg = importMatch.startsWith('@');
            const packageName = importMatch
                .split('/')
                .slice(0, isOrg ? 2 : 1)
                .join('/');
            if (packages.includes(packageName) && !srcEnd.test(firstMatch)) {
                let clean;
                if (matchType === 'require' || matchType === 'imports') {
                    const endCharacters = firstMatch.slice(-2);
                    clean =
                        firstMatch.slice(0, firstMatch.length - 2) + '/src' + endCharacters;
                }
                else {
                    let endCharacters = firstMatch.slice(-1);
                    clean =
                        firstMatch.slice(0, firstMatch.length - 1) + '/src' + endCharacters;
                }
                return line.replace(firstMatch, clean);
            }
            return line;
        };
        const changeImport = (content, packages) => {
            return (content
                .split(/\r?\n/)
                .map((line, index) => {
                const trimedLine = line.trimStart();
                if (commentMultilieStart.test(trimedLine) ||
                    commentSingleLineStart.test(trimedLine)) {
                    return line;
                }
                if (regexEnd.test(line)) {
                    return processAddSrcAtEnd(regexEnd, line, packages, 'from_import_export');
                }
                if (singleLineImporrt.test(line)) {
                    return processAddSrcAtEnd(singleLineImporrt, line, packages, 'imports');
                }
                if (singleLineRequire.test(line)) {
                    return processAddSrcAtEnd(singleLineRequire, line, packages, 'require');
                }
                return line;
            })
                .join('\n') + '\n');
        };
        const addImportSrc = (proj) => {
            const pacakges = [
                ...proj.packagesRecognition.allIsomorphicPackagesFromMemory,
            ];
            // console.log(pacakges)
            const files = lib_11.Helpers.filesFrom(proj.pathFor('src'), true).filter(f => f.endsWith('.ts'));
            for (const file of files) {
                const originalContent = lib_11.Helpers.readFile(file);
                const changed = changeImport(originalContent, pacakges);
                if (originalContent &&
                    changed &&
                    originalContent?.trim().replace(/\s/g, '') !==
                        changed?.trim().replace(/\s/g, '')) {
                    lib_11.Helpers.writeFile(file, changed);
                }
            }
        };
        if (project.framework.isStandaloneProject) {
            addImportSrc(project);
        }
        else if (project.framework.isContainer) {
            for (const child of project.children) {
                addImportSrc(child);
            }
        }
        this._exit();
        //#endregion
    }
    //#endregion
    //#region move js to ts
    $MOVE_JS_TO_TS(args) {
        //#region @backendFunc
        lib_11.Helpers.filesFrom((0, lib_5.crossPlatformPath)([this.cwd, args]), true).forEach(f => {
            if (lib_5.path.extname(f) === '.js') {
                lib_11.HelpersTaon.move(f, (0, lib_5.crossPlatformPath)([
                    lib_5.path.dirname(f),
                    lib_5.path.basename(f).replace('.js', '.ts'),
                ]));
            }
        });
        lib_11.Helpers.info('DONE');
        this._exit();
        //#endregion
    }
    //#endregion
    //#region show messages
    ASYNC_PROC = async (args) => {
        //#region @backendFunc
        global.tnpShowProgress = true;
        let p = lib_11.Helpers.run(`${lib_2.config.frameworkName} show:loop ${args}`, {
            output: false,
            cwd: this.cwd,
        }).async();
        p.stdout.on('data', chunk => {
            console.log('prod:' + chunk);
        });
        p.on('exit', c => {
            console.log('process exited with code: ' + c);
            this._exit();
        });
        //#endregion
    };
    SYNC_PROC = async (args) => {
        //#region @backendFunc
        global.tnpShowProgress = true;
        try {
            let p = lib_11.Helpers.run(`${lib_2.config.frameworkName} show:loop ${args}`, {
                output: false,
                cwd: this.cwd,
            }).sync();
            this._exit();
        }
        catch (err) {
            console.log('Erroroejk');
            this._exit(1);
        }
        //#endregion
    };
    async SHOW_RANDOM_HAMSTERS() {
        //#region @backendFunc
        while (true) {
            const arr = ['Pluszla', 'Łapczuch', 'Misia', 'Chrupka'];
            console.log(arr[lib_11.HelpersTaon.randomInteger(0, arr.length - 1)]);
            await lib_5.Utils.wait(1);
        }
        //#endregion
    }
    async showRandomHamstersTypes() {
        //#region @backendFunc
        while (true) {
            const arr = [
                lib_5.chalk.red('djungarian'),
                lib_5.chalk.magenta('syrian golden'),
                lib_5.chalk.bold('syrian teddy bear'),
                lib_5.chalk.red('dwarf roborowski'),
                lib_5.chalk.underline('dwarf russian'),
                'dwarf winter white',
                'chinese hamster',
            ];
            console.log(arr[lib_11.HelpersTaon.randomInteger(0, arr.length - 1)]);
            await lib_5.Utils.wait(1);
        }
        //#endregion
    }
    SHOW_LOOP_MESSAGES(args) {
        //#region @backendFunc
        console.log(`

    platform: ${process.platform}
    terminal: ${lib_4.UtilsProcess.getBashOrShellName()}

    `);
        global.tnpShowProgress = true;
        console.log('process pid', process.pid);
        console.log('process ppid', process.ppid);
        // process.on('SIGTERM', () => {
        //   this._exit()
        // })
        this._SHOW_LOOP_MESSAGES();
        //#endregion
    }
    async newTermMessages() {
        //#region @backendFunc
        lib_4.UtilsProcess.startInNewTerminalWindow(`tnp showloopmessages 10`);
        this._exit();
        //#endregion
    }
    _SHOW_LOOP(c = 0, maximum = Infinity, errExit = false) {
        //#region @backendFunc
        if (lib_5._.isString(c)) {
            var { max = Infinity, err = false } = require('minimist')(c.split(' '));
            maximum = max;
            errExit = err;
            // console.log('max',max)
            // console.log('err',err)
            c = 0;
        }
        if (c === maximum) {
            this._exit(errExit ? 1 : 0);
        }
        console.log(`counter: ${c}`);
        setTimeout(() => {
            this._SHOW_LOOP(++c, maximum, errExit);
        }, 1000);
        //#endregion
    }
    _SHOW_LOOP_MESSAGES(c = 0, maximum = Infinity, errExit = false, throwErr = false) {
        //#region @backendFunc
        if (lib_5._.isString(c)) {
            const obj = require('minimist')(c.split(' '));
            var { max = Infinity, err = false } = obj;
            maximum = lib_5._.isNumber(max) ? max : Infinity;
            errExit = err;
            throwErr = obj.throw;
            // console.log('max',max)
            // console.log('err',err)
            c = 0;
        }
        if (c === maximum) {
            if (throwErr) {
                throw new Error('Custom error!');
            }
            if (errExit) {
                this._exit(1);
            }
            this._exit();
        }
        console.log(`counter: ${c}`);
        lib_5.PROGRESS_DATA.log({ msg: `counter: ${c}`, value: c * 7 });
        setTimeout(() => {
            this._SHOW_LOOP_MESSAGES(++c, maximum, errExit, throwErr);
        }, 2000);
        //#endregion
    }
    //#endregion
    //#region dedupe
    dedupecore() {
        //#region @backendFunc
        const coreProject = project_1.Project.ins.by(lib_2.LibTypeEnum.CONTAINER);
        coreProject.nodeModules.dedupe(this.args.join(' ').trim() === '' ? void 0 : this.args);
        this._exit();
        //#endregion
    }
    dedupecorefake() {
        //#region @backendFunc
        const coreProject = project_1.Project.ins.by(lib_2.LibTypeEnum.CONTAINER);
        coreProject.nodeModules.dedupe(this.args.join(' ').trim() === '' ? void 0 : this.args, true);
        this._exit();
        //#endregion
    }
    DEDUPE() {
        //#region @backendFunc
        this.project.nodeModules.dedupe(this.args.join(' ').trim() === '' ? void 0 : this.args);
        this._exit();
        //#endregion
    }
    DEDUPE_FAKE() {
        //#region @backendFunc
        this.project.nodeModules.dedupe(this.args.join(' ').trim() === '' ? void 0 : this.args, true);
        this._exit();
        //#endregion
    }
    DEDUPE_COUNT() {
        //#region @backendFunc
        this.project.nodeModules.dedupeCount(this.args);
        this._exit();
        //#endregion
    }
    //#endregion
    //#region deps
    /**
     * generate deps json
     */
    DEPS_JSON() {
        //#region @backendFunc
        const node_moduels = (0, lib_5.crossPlatformPath)([this.cwd, constants_1.nodeModulesMainProject]);
        const result = {};
        lib_11.Helpers.foldersFrom(node_moduels)
            .filter(f => lib_5.path.basename(f) !== '.bin')
            .forEach(f => {
            const packageName = lib_5.path.basename(f);
            if (packageName.startsWith('@')) {
                const orgPackageRootName = packageName;
                lib_11.Helpers.foldersFrom(f).forEach(f2 => {
                    try {
                        result[`${orgPackageRootName}/${lib_5.path.basename(f2)}`] =
                            lib_11.HelpersTaon.readValueFromJson(lib_5.path.join(f2, constants_1.packageJsonMainProject), 'version', '');
                    }
                    catch (error) { }
                });
            }
            else {
                try {
                    result[packageName] = lib_11.HelpersTaon.readValueFromJson(lib_5.path.join(f, constants_1.packageJsonMainProject), 'version', '');
                }
                catch (error) { }
            }
        });
        lib_11.Helpers.writeJson(lib_5.path.join(this.cwd, constants_1.result_packages_json), result);
        this._exit();
        //#endregion
    }
    //#endregion
    //#region reinstall
    async reinstall() {
        //#region @backendFunc
        lib_11.Helpers.taskStarted(`Reinstalling ${this.project.genericName}...`);
        if (!this.project) {
            lib_11.Helpers.error(`Project not found in ${this.cwd}`, true, false);
            this._exit();
        }
        await this.project?.nodeModules?.reinstall();
        lib_11.Helpers.info(`Done reinstalling ${this.project.genericName}`);
        this._exit();
        //#endregion
    }
    //#endregion
    //#region reinstall core containers
    async reinstallCoreContainers() {
        //#region @backendFunc
        const toReinstallCoreContainers = (0, lib_5.crossPlatformPath)([
            project_1.Project.ins.by(lib_2.LibTypeEnum.CONTAINER).location,
            '..',
        ]);
        const ommitedVersion = ['v20'];
        const foldersAbsPaths = lib_11.Helpers.foldersFrom(toReinstallCoreContainers, {
            recursive: false,
        })
            .filter(f => lib_5.path.basename(f).startsWith(lib_2.LibTypeEnum.CONTAINER))
            .filter(f => {
            const project = this.ins.From(f);
            return (project &&
                project.framework.frameworkVersionAtLeast(`v${lib_5._.first(build_info__auto_generated_1.CURRENT_PACKAGE_VERSION.split('.'))}`) &&
                !ommitedVersion.includes(project.framework.frameworkVersion));
        });
        const projectsFoldersAbsPaths = foldersAbsPaths.length === 1
            ? foldersAbsPaths
            : await lib_7.UtilsTerminal.multiselect({
                question: `Select core containers to reinstall`,
                choices: foldersAbsPaths.map(absFolderPath => {
                    return {
                        name: lib_5.path.basename(absFolderPath),
                        value: absFolderPath,
                    };
                }),
            });
        for (let index = 0; index < projectsFoldersAbsPaths.length; index++) {
            const project = this.ins.From(projectsFoldersAbsPaths[index]);
            await project.nodeModules.reinstall();
        }
        lib_11.Helpers.info(`Done reinstalling core containers`);
        this._exit();
        //#endregion
    }
    //#endregion
    //#region file info
    FILEINFO = args => {
        //#region @backendFunc
        console.log(lib_11.HelpersTaon.getMostRecentFilesNames((0, lib_5.crossPlatformPath)(this.cwd)));
        this._exit();
        //#endregion
    };
    //#endregion
    //#region versions
    VERSIONS() {
        //#region @backendFunc
        const children = this.project.children;
        for (let index = 0; index < children.length; index++) {
            const child = children[index];
            lib_11.Helpers.info(`v${child.packageJson.version}\t - ${child.genericName}`);
        }
        this._exit();
        //#endregion
    }
    //#endregion
    //#region path
    path() {
        //#region @backendFunc
        console.log(this.ins.Tnp.location);
        this._exit();
        //#endregion
    }
    //#endregion
    //#region env
    ENV_CHECK(args) {
        //#region @backendFunc
        lib_11.HelpersTaon.checkEnvironment();
        this._exit();
        //#endregion
    }
    ENV_INSTALL() {
        //#region @backendFunc
        lib_6.CLI.installEnvironment(lib_4.requiredForDev);
        this._exit();
        //#endregion
    }
    //#endregion
    //#region throw error
    THROW_ERR() {
        //#region @backendFunc
        lib_11.Helpers.error(`Erororoororo here`, false, true);
        //#endregion
    }
    //#endregion
    //#region brew
    BREW(args) {
        //#region @backendFunc
        const isM1MacOS = lib_5.os.cpus()[0].model.includes('Apple M1');
        if (process.platform === 'darwin') {
            if (isM1MacOS) {
                lib_11.Helpers.run(`arch -x86_64 brew ${args}`).sync();
            }
            else {
                lib_11.Helpers.run(`brew ${args}`).sync();
            }
        }
        this._exit();
        //#endregion
    }
    //#endregion
    //#region run
    run() {
        //#region @backendFunc
        lib_11.Helpers.run(`node run.js`, {
            output: true,
            silence: false,
        }).sync();
        this._exit(0);
        //#endregion
    }
    //#endregion
    //#region ps info
    async PSINFO(args) {
        //#region @backendFunc
        const pid = Number(args);
        let ps = await (0, lib_3.psList)();
        let psinfo = ps.find(p => p.pid == pid);
        if (!psinfo) {
            lib_11.Helpers.error(`No process found with pid: ${args}`, false, true);
        }
        console.log(psinfo);
        this._exit();
        //#endregion
    }
    //#endregion
    //#region sync core repositories
    get absPathToLocalTaonContainers() {
        //#region @backendFunc
        if (!this.project) {
            return;
        }
        const localTaonRepoPath = (0, lib_5.crossPlatformPath)([
            this.project.location,
            this.project.ins.taonProjectsRelative,
        ]);
        return localTaonRepoPath;
        //#endregion
    }
    async TNP_SYNC() {
        //#region @backendFunc
        const currentFrameworkVersion = this.project.taonJson.frameworkVersion;
        const pathToTaonContainerNodeModules = (0, lib_5.crossPlatformPath)([
            lib_3.UtilsOs.getRealHomeDir(),
            lib_2.dotTaonFolder,
            lib_2.taonContainers,
            `${constants_1.containerPrefix}${currentFrameworkVersion}`,
            constants_1.nodeModulesMainProject,
        ]);
        lib_11.Helpers.taskStarted(`Syncing node_modules from taon container to tnp...`);
        //#region copy from .taon to tnp
        await lib_11.HelpersTaon.copyFolderOsNative(pathToTaonContainerNodeModules, this.project.nodeModules.path, { removeDestination: true });
        lib_11.HelpersTaon.copyFile((0, lib_5.crossPlatformPath)([
            pathToTaonContainerNodeModules,
            `../${constants_1.tmpIsomorphicPackagesJson}`,
        ]), this.project.pathFor(constants_1.tmpIsomorphicPackagesJson));
        //#endregion
        lib_11.Helpers.taskDone(`Done syncing node_modules from container to tnp...`);
        lib_11.Helpers.taskStarted(`Syncing node_modules from tnp to ../taon-container...`);
        //#region copy from tnp to ../taon
        await lib_11.HelpersTaon.copyFolderOsNative(this.project.nodeModules.path, (0, lib_5.crossPlatformPath)(`${this.absPathToLocalTaonContainers}/${constants_1.containerPrefix}${currentFrameworkVersion}/${constants_1.nodeModulesMainProject}`), { removeDestination: true });
        lib_11.HelpersTaon.copyFile(this.project.pathFor(constants_1.tmpIsomorphicPackagesJson), (0, lib_5.crossPlatformPath)(`${this.absPathToLocalTaonContainers}/${constants_1.containerPrefix}${currentFrameworkVersion}/${constants_1.tmpIsomorphicPackagesJson}`));
        //#endregion
        lib_11.Helpers.taskDone(`Done syncing node_modules from tnp to ../${lib_2.taonContainers} ...`);
        this._exit();
        //#endregion
    }
    async SYNC() {
        //#region @backendFunc
        const isInsideTnpAndTaonDev = this.project?.name === 'tnp' &&
            this.project?.parent.name === 'taon-dev' &&
            lib_11.Helpers.exists(this.absPathToLocalTaonContainers);
        if (isInsideTnpAndTaonDev) {
            lib_11.Helpers.info(`

        You are inside taon-dev/tnp project.

        `);
        }
        const updateTnpAndLocalTona = isInsideTnpAndTaonDev &&
            (await lib_7.UtilsTerminal.confirm({
                message: `Would you like to update tnp and ../${lib_2.taonContainers} (after sync command) ?`,
                defaultValue: true,
            }));
        this.ins.sync({ syncFromCommand: true });
        if (updateTnpAndLocalTona) {
            await this.TNP_SYNC();
        }
        this._exit();
        //#endregion
    }
    //#endregion
    //#region clear
    async CLEAN() {
        //#region @backendFunc
        await this.project.artifactsManager.clear(options_1.EnvOptions.from(this.params));
        this._exit();
        //#endregion
    }
    CLEAR() {
        //#region @backendFunc
        this.CLEAN();
        //#endregion
    }
    CL() {
        //#region @backendFunc
        this.CLEAN();
        //#endregion
    }
    //#endregion
    //#region show git in progress
    inprogress() {
        //#region @backendFunc
        lib_11.Helpers.info(`
    In progress
${this.project.children
            .filter(f => f.git
            .lastCommitMessage()
            .startsWith(lib_11.HelpersTaon.git.getACTION_MSG_RESET_GIT_HARD_COMMIT()))
            .map((c, index) => `${index + 1}. ${c.genericName}`)}

    `);
        this._exit();
        //#endregion
    }
    //#endregion
    //#region update deps for core container
    async depsupdate() {
        await this.updatedeps();
    }
    async updatedeps() {
        //#region @backendFunc
        if (!this.project || !this.project.framework.isCoreProject) {
            if (this.project && this.project.typeIs(lib_2.LibTypeEnum.ISOMORPHIC_LIB)) {
                // await this.project.init(
                //   EnvOptions.from({
                //     purpose: 'updating isomorphic-lib external deps',
                //   }),
                // );
                this.project.taonJson.detectAndUpdateNpmExternalDependencies();
                this.project.taonJson.detectAndUpdateIsomorphicExternalDependencies();
                lib_11.UtilsTypescript.formatFile(this.project.taonJson.path);
            }
            else {
                lib_11.Helpers.error(`This command can be used only inside:` +
                    `\n- core container projects` +
                    `\n-isomorphic-lib projects`, false, true);
            }
            this._exit();
        }
        await this.project.taonJson.updateDependenciesFromNpm({
            onlyPackageNames: this.args,
        });
        this._exit();
        //#endregion
    }
    //#endregion
    //#region compare containers
    compareContainers() {
        //#region @backendFunc
        lib_11.Helpers.clearConsole();
        const [c1ver, c2ver] = this.args;
        const c1 = this.ins.by(lib_2.LibTypeEnum.CONTAINER, `v${c1ver.replace('v', '')}`);
        const c2 = this.ins.by(lib_2.LibTypeEnum.CONTAINER, `v${c2ver.replace('v', '')}`);
        const c1Deps = c1.packageJson.allDependencies;
        const c2Deps = c2.packageJson.allDependencies;
        const displayCompare = (depName, c1depVer, c2depVer) => {
            // console.log(`Comparing ${depName} ${c1depVer} => ${c2depVer}`);
            c1depVer = lib_11.UtilsNpm.fixMajorVerNumber(c1depVer);
            c2depVer = lib_11.UtilsNpm.fixMajorVerNumber(c2depVer);
            if ([c1depVer, c2depVer].includes('latest')) {
                console.log(`${lib_5.chalk.gray(depName)}@(${c1depVer} => ${c2depVer})\t`);
            }
            else if (c2depVer && c1depVer) {
                if (semver.lt(c2depVer, c1depVer)) {
                    console.log(`${lib_5.chalk.red(depName)}@(${c1depVer} => ${c2depVer})\t`);
                }
                else if (semver.gte(c2depVer, c1depVer)) {
                    console.log(`${lib_5.chalk.gray(depName)}@(${c1depVer} => ${c2depVer})\t`);
                }
            }
            else {
                console.log(`${lib_5.chalk.bold(depName)}@(${c1depVer} => ${c2depVer})\t`);
            }
        };
        const allDepsKeys = Object.keys(c1Deps).concat(Object.keys(c2Deps));
        for (const packageName of allDepsKeys) {
            displayCompare(packageName, lib_11.UtilsNpm.clearVersion(c1Deps[packageName], { removePrefixes: true }), lib_11.UtilsNpm.clearVersion(c2Deps[packageName], { removePrefixes: true }));
        }
        this._exit();
        //#endregion
    }
    //#endregion
    //#region not for npm / get trusted
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    //#endregion
    //#region not for npm / tnp fix taon json
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    /* */
    //#endregion
    //#region start taon projects worker
    async startCliServiceTaonProjectsWorker() {
        //#region @backendFunc
        await this.ins.taonProjectsWorker.cliStartProcedure({
            methodOptions: {
                cliParams: {
                    ...this.params,
                    mode: lib_12.BaseCLiWorkerStartMode.IN_CURRENT_PROCESS,
                },
                calledFrom: 'cli-GLobal',
            },
        });
        //#endregion
    }
    //#endregion
    //#region json schema docs watcher
    async recreateDocsConfigJsonSchema() {
        //#region @backendFunc
        await this.project.init(options_1.EnvOptions.from({
            purpose: 'initing before json schema docs watch',
        }));
        if (this.project.name !== 'tnp') {
            lib_11.Helpers.error(`This command is only for tnp project`, false, true);
        }
        const fileToWatchRelative = 'src/lib/models.ts';
        const fileToWatch = this.project.pathFor(fileToWatchRelative);
        const recreate = async () => {
            const schema = await this._createJsonSchemaFrom({
                nameOfTypeOrInterface: 'Models.DocsConfig',
                project: this.project,
                relativePathToTsFile: fileToWatch,
            });
            lib_11.Helpers.writeFile(this.project.artifactsManager.artifact.docsWebapp.docs
                .docsConfigSchemaPath, schema);
            lib_11.Helpers.info(`DocsConfig schema updated ${(0, lib_4.dateformat)(new Date(), 'dd-mm-yyyy HH:MM:ss')}`);
        };
        const debounceRecreate = lib_5._.debounce(recreate, 100);
        lib_11.Helpers.taskStarted('Recreating... src/lib/models.ts');
        await recreate();
        lib_11.Helpers.taskDone('Recreation done src/lib/models.ts');
        lib_11.Helpers.taskStarted('Watching for changes in src/lib/models.ts');
        if (this.params.watch || this.params.w) {
            lib_4.chokidar.watch(fileToWatch).on('change', () => {
                debounceRecreate();
            });
        }
        else {
            await recreate();
            this._exit();
        }
        //#endregion
    }
    //#endregion
    //#region json schema taon watch
    async recreateTaonJsonSchema() {
        //#region @backendFunc
        // await this.project.init(
        //   EnvOptions.from({
        //     purpose: 'initing before json schema docs watch',
        //   }),
        // );
        if (this.project.name !== 'tnp') {
            lib_11.Helpers.error(`This command is only for tnp project`, false, true);
        }
        const fileToWatchRelative = 'src/lib/models.ts';
        const fileToWatch = this.project.pathFor(fileToWatchRelative);
        const recreate = async () => {
            await (async () => {
                const projectsOfInterestStandalone = [
                    this.project.framework.coreProject,
                    this.project,
                ];
                const schemaStandalone = await this._createJsonSchemaFrom({
                    nameOfTypeOrInterface: 'Models.TaonJsonCombined',
                    project: this.project,
                    relativePathToTsFile: fileToWatch,
                });
                for (const proj of projectsOfInterestStandalone) {
                    proj.vsCodeHelpers.recreateJsonSchemaForTaon();
                    lib_11.Helpers.writeFile(proj.pathFor(constants_1.taonConfigSchemaJsonStandalone), schemaStandalone);
                }
                const projectsOfInterestContainer = [
                    this.project.framework.coreContainer,
                    this.project.parent,
                ];
                // const schemaContainer = await this._createJsonSchemaFrom({
                //   nameOfTypeOrInterface: 'Models.TaonJsonContainer',
                //   project: this.project,
                //   relativePathToTsFile: fileToWatch,
                // });
                for (const proj of projectsOfInterestContainer) {
                    proj.vsCodeHelpers.recreateJsonSchemaForTaon();
                    lib_11.Helpers.writeFile(proj.pathFor(constants_1.taonConfigSchemaJsonContainer), schemaStandalone);
                }
            })();
            lib_11.Helpers.info(`TaonConfig schema updated ${(0, lib_4.dateformat)(new Date(), 'dd-mm-yyyy HH:MM:ss')}`);
        };
        const debounceRecreate = lib_5._.debounce(recreate, 100);
        lib_11.Helpers.taskStarted('Recreating... src/lib/models.ts');
        await recreate();
        lib_11.Helpers.taskDone('Recreation done src/lib/models.ts');
        if (this.params.watch || this.params.w) {
            lib_11.Helpers.taskStarted('Watching for changes in src/lib/models.ts');
            lib_4.chokidar.watch(fileToWatch).on('change', () => {
                debounceRecreate();
            });
        }
        else {
            await recreate();
            this._exit();
        }
        //#endregion
    }
    jsonSchema() {
        //#region @backendFunc
        return this.schemaJson();
        //#endregion
    }
    async _createJsonSchemaFrom(options) {
        //#region @backendFunc
        const { project, relativePathToTsFile, nameOfTypeOrInterface } = options;
        // Create the config for ts-json-schema-generator
        const config = {
            path: relativePathToTsFile, // Path to the TypeScript file
            tsconfig: project.pathFor(constants_1.tsconfigForSchemaJson), // Path to the tsconfig.json file
            type: nameOfTypeOrInterface, // Type or interface name
            skipTypeCheck: true, // Optional: Skip type checking
        };
        try {
            // Create the schema generator using the config
            const generator = (0, ts_json_schema_generator_1.createGenerator)(config);
            // Generate the schema
            const schema = generator.createSchema(config.type);
            // Convert the schema object to JSON string
            const schemaJson = JSON.stringify(schema, null, 2);
            return schemaJson;
        }
        catch (error) {
            const diagnostics = lib_11.UtilsTypescript.parseTsDiagnostic(error.diagnostic ?? error);
            for (const d of diagnostics) {
                if (d.file) {
                    console.error(`[TS ${d.category}] (${d.code})`, `${d.file}:${d.line}:${d.character}`, '\n' + d.message);
                }
                else {
                    console.error(`[TS ${d.category}] (${d.code})`, d.message);
                }
            }
        }
        return {};
        //#endregion
    }
    schemaJson() {
        //#region @backendFunc
        console.log(this._createJsonSchemaFrom({
            project: this.project,
            relativePathToTsFile: this.firstArg,
            nameOfTypeOrInterface: this.lastArg,
        }));
        this._exit();
        //#endregion
    }
    //#endregion
    //#region ts testing functions
    async ts() {
        //#region @backendFunc
        lib_11.Helpers.clearConsole();
        await lib_7.UtilsTerminal.selectActionAndExecute({
            recognizeImportExportRequire: {
                name: 'Recognize import/export/require',
                action: async () => {
                    const files = lib_11.Helpers.getFilesFrom([this.cwd, constants_1.srcMainProject], {
                        followSymlinks: false,
                        recursive: true,
                    });
                    const selectedFileAbsPath = await lib_7.UtilsTerminal.select({
                        question: 'Select file to recognize imports/exports/requires',
                        choices: files.map(f => {
                            return {
                                name: f,
                                value: f,
                            };
                        }),
                    });
                    const importsExports = lib_11.UtilsTypescript.recognizeImportsFromFile(lib_11.Helpers.readFile(selectedFileAbsPath)).map(i => {
                        return `(${i.type}) ${lib_5.chalk.bold(i.cleanEmbeddedPathToFile)}`;
                    });
                    console.log(importsExports.join('\n '));
                },
            },
        });
        this._exit();
        //#endregion
    }
    //#endregion
    //#region update core container deps
    async coreContainerDepsUpdate() {
        //#region @backendFunc
        if (this.project.name !== 'taon' &&
            this.project?.parent?.typeIsNot(lib_2.LibTypeEnum.CONTAINER)) {
            lib_11.Helpers.error(`This command is only for taon project in taon-dev container`, false, true);
        }
        const containerCore = this.project.framework.coreContainer;
        for (const child of this.project.parent.children.filter(f => f.framework.isStandaloneProject)) {
            lib_11.Helpers.info(`Updating ${child.name} version from npm...`);
            const foundVer = await child.npmHelpers.getPackageVersionFromNpmRegistry(child.nameForNpmPackage);
            console.info(`Found version: ${foundVer} for ${child.nameForNpmPackage}`);
            containerCore.taonJson.overridePackageJsonManager.updateDependency({
                packageName: child.nameForNpmPackage,
                version: `~${foundVer}`,
            });
        }
        lib_11.Helpers.info(`Container deps updated`);
        this._exit();
        //#endregion
    }
    //#endregion
    //#region wrapper for ng
    ng() {
        //#region @backendFunc
        // check if for example v18 in args
        const latest = 'latest';
        const version = this.args.find(arg => arg.startsWith('v')) || latest;
        let argsWithParams = this.argsWithParams;
        if (version !== latest) {
            this.args = this.args.filter(arg => !arg.startsWith('v'));
            argsWithParams = this.argsWithParams.replace(version, '');
        }
        lib_11.Helpers.run(`npx -p @angular/cli@${version.replace('v', '').replace('@', '')} ng ${argsWithParams}`, {
            output: true,
            silence: false,
        }).sync();
        this._exit();
        //#endregion
    }
    //#endregion
    //#region are linked node_modules
    isLinkNodeModules() {
        //#region @backendFunc
        console.log(this.project.nodeModules.isLink);
        this._exit();
        //#endregion
    }
    //#endregion
    //#region link node_modules from core container
    linkNodeModulesFromCoreContainer() {
        //#region @backendFunc
        const coreContainer = this.project.ins.by(lib_2.LibTypeEnum.CONTAINER, this.firstArg);
        if (!coreContainer) {
            lib_11.Helpers.error(`Please specify proper container version in argument`, false, true);
        }
        this.project.nodeModules.unlinkNodeModulesWhenLinked();
        coreContainer.nodeModules.linkToProject(this.project);
        this._exit();
        //#endregion
    }
    //#endregion
    //#region recognize imports from file
    /**
     * Display all imports from specific project file
     */
    imports() {
        //#region @backendFunc
        const imports = lib_11.UtilsTypescript.recognizeImportsFromFile(this.project.pathFor(this.firstArg));
        console.log(imports);
        this._exit();
        //#endregion
    }
    //#endregion
    //#region recognize imports from file
    /**
     * Display all imports from specific project
     */
    allImports() {
        //#region @backendFunc
        lib_11.Helpers.taskStarted(`Recognizing all imports from project...`);
        const displayList = this.project.framework
            .allDetectedExternalIsomorphicDependenciesForNpmLibCode;
        console.log(displayList.map(i => `"${i}"`).join('\n'));
        lib_11.Helpers.info(`Total unique imports found: ${displayList.length}`);
        this._exit();
        //#endregion
    }
    //#endregion
    //#region dirname for tnp
    dirnameForTnp() {
        //#region @backendFunc
        console.log(`cli method: ${lib_2.config.frameworkName} ${lib_9.UtilsCliClassMethod.getFrom($Global.prototype.dirnameForTnp, {
            globalMethod: true,
        })}`);
        console.log(lib_2.config.dirnameForTnp);
        this._exit();
        //#endregion
    }
    //#endregion
    //#region detect contexts
    contexts() {
        //#region @backendFunc
        lib_11.Helpers.taskStarted(`Detecting contexts...`);
        const contexts = this.project.framework.getAllDetectedTaonContexts();
        console.log(`Detected contexts: ${contexts.length} `);
        for (const context of contexts) {
            console.log(`- ${context.contextName} (${context.fileRelativePath})`);
        }
        lib_11.Helpers.taskDone(`Contexts detected`);
        this._exit();
        //#endregion
    }
    //#endregion
    //#region regenerate vscode settings colors
    _regenerateVscodeSettingsColors() {
        //#region @backendFunc
        const overrideBottomColor = this.project.vsCodeHelpers.getVscodeBottomColor();
        super._regenerateVscodeSettingsColors(overrideBottomColor);
        //#endregion
    }
    //#endregion
    //#region test messages
    messagesTest() {
        //#region @backendFunc
        console.log('-----1');
        lib_11.Helpers.log(`Helpers.log`);
        lib_11.Helpers.info(`Helpers.info`);
        lib_11.Helpers.error(`Helpers.error`, true, true);
        lib_11.Helpers.warn(`Helpers.warn`);
        lib_11.Helpers.success(`Helpers.success`);
        lib_11.Helpers.taskStarted(`Helpers.taskStarted`);
        lib_11.Helpers.taskDone(`Helpers.taskDone`);
        console.log('-----2');
        lib_11.Helpers.logInfo(`Helpers.logInfo`);
        lib_11.Helpers.logError(`Helpers.logError`, true, true);
        lib_11.Helpers.logWarn(`Helpers.logWarn`);
        lib_11.Helpers.logSuccess(`Helpers.logSuccess`);
        console.log('-----3');
        this._exit();
        //#endregion
    }
    //#endregion
    //#region extract string metadata
    // projectName|-|www-domgrubegozwierzaka-pl||--||releaseType|-|manual||--||version|-|0.0.8||--||
    // envName|-|__||--||envNumber|-|||--||targetArtifact|-|angular-node-app|||||-1759151320202-fa12e3a5cfdd
    extractStringMetadata() {
        //#region @backendFunc
        const str = this.firstArg || '';
        console.log(str);
        console.log(lib_8.FilePathMetaData.extractData(str, {
            keysMap: constants_1.keysMap,
        }));
        this._exit();
        //#endregion
    }
    //#endregion
    //#region aaa (test command)
    async aaa() {
        //#region @backendFunc
        // const stuff = await UtilsTerminal.select({
        //   choices: [],
        //   question: 'Select something',
        // });
        //   const coreProject1 = this.project.framework.coreProject;
        //   const coreProject2 = Project.ins.by(LibTypeEnum.ISOMORPHIC_LIB);
        //   console.log('coreProject2');
        //   console.log(coreProject1.pathFor(`docker-templates/terafik`));
        //   console.log('coreProject2');
        //   console.log(coreProject2.pathFor(`docker-templates/terafik`));
        // const wrap = UtilsProcessLogger.createStickyTopBox('AAA TEST');
        // const ui = UtilsProcessLogger.createStickyTopBox(
        //   '🐹 PROCESS OUTPUT — last 40 lines — Press ENTER to stop',
        // );
        // let iteration = 0;
        // const allLogs: string[] = [];
        // function makeChunk(chunkNo: number): string[] {
        //   const lines: string[] = [];
        //   for (let i = 0; i < 40; i++) {
        //     const now = new Date().toLocaleTimeString();
        //     lines.push(
        //       `[chunk ${chunkNo.toString().padStart(2, '0')}] line ${i
        //         .toString()
        //         .padStart(2, '0')} — ${now}`,
        //     );
        //   }
        //   return lines;
        // }
        // function feedChunk() {
        //   iteration++;
        //   allLogs.push(...makeChunk(iteration));
        //   ui.update(allLogs.join('\n'));
        // }
        // console.clear();
        // console.log('Starting stress test...\n');
        // // generate a new 40-line chunk every second
        // const timer = setInterval(feedChunk, 1000);
        // // stop after 10 chunks (≈ 400 lines)
        // setTimeout(() => {
        //   clearInterval(timer);
        //   console.log('\n\n✅ Finished streaming 10 chunks of 40 lines each.');
        // }, 10000);
        // this._exit();
        //#endregion
    }
    //#endregion
    //#region local sync
    async localSync() {
        //#region @backendFunc
        if (!this.project) {
            lib_11.Helpers.error(`No project found in cwd: ${this.cwd}`, false, true);
        }
        if (this.project.name !== 'taon-dev') {
            lib_11.Helpers.error(`This command is only for ${lib_5.chalk.bold('taon-dev')} project`, false, true);
        }
        await lib_4.UtilsProcess.killAllOtherNodeProcesses();
        const tnpProjectInTaonDev = this.project.children.find(c => c.name === lib_2.tnpPackageName);
        const taonContainersProj = this.project.ins.From(this.project.pathFor(lib_2.taonContainers));
        if (!taonContainersProj) {
            lib_11.Helpers.error(`No taon-containers project found in ${this.project.pathFor(lib_2.taonContainers)}`, false, true);
        }
        if (!tnpProjectInTaonDev) {
            lib_11.Helpers.error(`No tnp project found inside taon-dev`, false, true);
        }
        const tnpContainer = taonContainersProj.children.find(c => c.name ===
            `${constants_1.containerPrefix}${tnpProjectInTaonDev.taonJson.frameworkVersion}`);
        await tnpContainer.nodeModules.reinstall();
        tnpContainer.nodeModules.copyToProject(tnpProjectInTaonDev);
        // Helpers.info(`Done syncing node_modules from container to tnp...`);
        let children = this.project.children.filter(c => c.typeIs(lib_2.LibTypeEnum.ISOMORPHIC_LIB));
        for (const child of children) {
            child.git.meltActionCommits();
        }
        children = children.filter((c, i) => {
            const lastCommitMessage = c?.git?.lastCommitMessage()?.trim();
            return !lastCommitMessage?.startsWith('release: ');
        });
        children = this.ins // @ts-ignore BaseProject inheritace compatiblity with Project problem
            .sortGroupOfProject(children, proj => [
            ...proj.taonJson.dependenciesNamesForNpmLib,
            ...proj.taonJson.isomorphicDependenciesForNpmLib,
            ...proj.taonJson.peerDependenciesNamesForNpmLib,
        ], proj => proj.nameForNpmPackage, proj => proj.nameForNpmPackage, this.project.taonJson.overridePackagesOrder)
            .filter(d => d.framework.isStandaloneProject);
        if (children.length > 0) {
            lib_11.Helpers.info(`Found ${children.length} children isomorphic projects to rebuild...

${children.map((c, i) => `  ${i + 1}. ${c.name}`).join(',')}

        `);
        }
        await project_1.Project.ins.taonProjectsWorker.cliStartProcedure({
            methodOptions: {
                cliParams: {
                    mode: lib_12.BaseCLiWorkerStartMode.DETACHED_WINDOW,
                },
                calledFrom: 'start framework function',
            },
        });
        const rebuildChildren = await lib_7.UtilsTerminal.confirm({
            message: `Rebuild ${children.length} children isomorphic projects ?`,
            defaultValue: true,
        });
        if (rebuildChildren) {
            for (let index = 0; index < children.length; index++) {
                const child = children[index];
                lib_11.Helpers.info(`Rebuilding ${index + 1} / ${children.length}: ${child.name} ...`);
                await child.build(options_1.EnvOptions.from({
                    purpose: 'local-sync',
                    build: {
                        watch: false,
                    },
                    release: {
                        targetArtifact: options_1.ReleaseArtifactTaon.NPM_LIB_PKG_AND_CLI_TOOL,
                    },
                }));
            }
        }
        lib_11.Helpers.info(`Dony local sync of taon-dev`);
        this._exit();
        //#endregion
    }
    //#endregion
    tagsFor() {
        //#region @backendFunc
        const taonJsonContent = this.project.readFile(constants_1.taonJsonMainProject);
        const tags = lib_3.UtilsJson.getAtrributiesFromJsonWithComments(`[zone.js]`, taonJsonContent);
        console.log(tags);
        this._exit();
        //#endregion
    }
    testGlob() {
        //#region @backendFunc
        // Helpers.taskStarted('Testing glob...');
        // const fullPattern = `${this.project.location}/**/*`;
        // const ignorePatterns = [
        //   '**/node_modules/**/*.*',
        //   '**/node_modules',
        //   '**/.git/**/*.*',
        //   '**/.git',
        //   '**/tmp-*/**',
        //   '**/tmp-*',
        //   '**/dist/**',
        //   '**/dist',
        //   '**/dist-*/**',
        //   '**/browser/**',
        //   '**/browser',
        //   '**/websql/**',
        //   '**/websql',
        //   // '**/projects/**',
        //   // '**/projects',
        //   '**/.taon/**',
        //   '**/.taon',
        //   '**/.tnp/**',
        //   '**/.tnp',
        //   '**/src/**/*.ts',
        //   '**/src/**/*.js',
        //   '**/src/**/*.scss',
        //   '**/src/**/*.css',
        //   '**/src/**/*.html',
        // ];
        // const entries = fg.sync(fullPattern, {
        //   absolute: true,
        //   dot: true,
        //   extglob: true,
        //   globstar: true,
        //   followSymbolicLinks: false,
        //   ignore: [
        //     // ...IGNORE_BY_DEFAULT
        //     ...ignorePatterns,
        //   ],
        //   onlyFiles: false,
        //   stats: true, // This is key!
        // });
        // Helpers.taskDone(`Found entries: ${entries.length}`);
        //#endregion
    }
    async killOthers() {
        //#region @backendFunc
        await lib_4.UtilsProcess.killAllOtherNodeProcesses();
        //#endregion
    }
    copyimage() {
        //#region @backendFunc
        // let source = this.args[0];
        // let destination = this.args[1];
        // if(!path.isAbsolute(source)){
        //   source = this.project.pathFor(source);
        // }
        // if(!path.isAbsolute(destination)){
        //   destination = this.project.pathFor(destination);
        // }
        // const content = UtilsFilesFoldersSync.readFile(this.args[0], {
        //   readImagesWithoutEncodingUtf8: true,
        // });
        // UtilsFilesFoldersSync.writeFile(this.args[1], content,{
        //   writeImagesWithoutEncodingUtf8: true,
        // });
        // Helpers.info(`Image copied from ${this.args[0]} to ${this.args[1]}`);
        // this._exit();
        //#endregion
    }
    setDefaultAutoConfigTaskName() {
        //#region @backendFunc
        lib_11.Helpers.taskStarted(`Setting default autoReleaseConfig task names...`);
        this.project.children.forEach(child => {
            lib_11.Helpers.info(`Processing project: ${child.name}`);
            const items = child.taonJson.autoReleaseConfigAllowedItems;
            items.forEach(item => {
                if (!item.taskName && item.artifactName === 'npm-lib-and-cli-tool') {
                    item.taskName = 'npm';
                }
            });
            child.taonJson.autoReleaseConfigAllowedItems = items;
        });
        this._exit();
        //#endregion
    }
    setTsNoCheckForAppTs() {
        //#region @backendFunc
        lib_11.Helpers.taskStarted(`Setting default autoReleaseConfig task names...`);
        this.project.children.forEach(child => {
            lib_11.Helpers.info(`Processing project: ${child.name}`);
            const appTsPath = child.pathFor('src/app.ts');
            const fileContent = lib_11.Helpers.readFile(appTsPath) || '';
            if (fileContent) {
                if (!fileContent.startsWith(`// @ts-${'nocheck'}`)) {
                    const contentFixed = `// @ts-${'nocheck'}\n${fileContent}`;
                    if (fileContent !== contentFixed) {
                        lib_11.Helpers.writeFile(appTsPath, contentFixed);
                    }
                }
            }
        });
        this._exit();
        //#endregion
    }
    getFilesFrom() {
        //#region @backendFunc
        const pathForFiles = (0, lib_5.crossPlatformPath)([this.cwd, this.firstArg]);
        lib_11.Helpers.taskStarted(`Getting files from path...

      ${pathForFiles}

      `);
        const files = lib_2.UtilsFilesFoldersSync.getFilesFrom(pathForFiles, {
            recursive: true,
            followSymlinks: false,
            omitPatterns: lib_2.UtilsFilesFoldersSync.IGNORE_FOLDERS_FILES_PATTERNS,
        });
        lib_11.Helpers.taskDone(`Files found: ${files.length}`);
        this._exit();
        //#endregion
    }
    getFoldersFrom() {
        //#region @backendFunc
        const pathForFolders = (0, lib_5.crossPlatformPath)([this.cwd, this.firstArg]);
        lib_11.Helpers.taskStarted(`Getting folders from path...

      ${pathForFolders}

      `);
        const folders = lib_2.UtilsFilesFoldersSync.getFoldersFrom((0, lib_5.crossPlatformPath)([this.cwd, this.firstArg]), {
            recursive: true,
            followSymlinks: false,
            omitPatterns: lib_2.UtilsFilesFoldersSync.IGNORE_FOLDERS_FILES_PATTERNS,
        });
        lib_11.Helpers.taskDone(`Folders found: ${folders.length}`);
        this._exit();
        //#endregion
    }
    async devModeWorker() {
        //#region @backendFunc
        await this.ins.notifyMainWorkerThatDevMode(this.project, options_1.EnvOptions.from({}));
        lib_11.Helpers.info('waiting');
        await lib_7.UtilsTerminal.pressAnyKeyToContinueAsync();
        this._exit();
        //#endregion
    }
    // async aaaaa() {
    //   GlobalTaskManager.start('aaa');
    //   GlobalTaskManager.addProgress('aaa');
    //   GlobalTaskManager.addProgress('aaa');
    //   console.info('GLOBAL COMMAND WORKS!');
    //   GlobalTaskManager.stop('aaa', () => {
    //     this._exit();
    //   });
    // }
    // async bbbbb() {
    //   Helpers.error(
    //     `
    //       Not able to publish to npm registry project in ${this.project.location}
    //       `,
    //     true,
    //     true,
    //   );
    // }
    async notyficationTest() {
        //#region @backendFunc
        await lib_3.UtilsOs.sendNotification({
            title: 'hello ' + new Date().toString(),
            body: 'asdas' + new Date().toString(),
            subtitle: 'LOLLASLDLASLD ' + new Date().toString(),
            timeoutMs: 1000,
        });
        this._exit();
        //#endregion
    }
    async spinner() {
        //#region @backend
        console.info('starting spinner');
        constants_1.globalSpinner.instance.start();
        await lib_5.Utils.wait(2);
        constants_1.globalSpinner.instance.text = 'Hello world !';
        await lib_5.Utils.wait(2);
        console.info('stoppiong spinner and waiting 2 seconds');
        constants_1.globalSpinner.instance.stop();
        this._exit();
        //#endregion
    }
    notVerifiedBuilds() {
        //#region @backendFunc
        lib_11.Helpers.info(`Not verified isomorphic builds:`);
        const pkgs = this.project.framework.notVerifiedIsomorphicPackagesBuildsInNodeModules;
        lib_11.Helpers.info(`Found ${pkgs.length} `);
        console.log(pkgs);
        this._exit();
        //#endregion
    }
    async countWatchersLinux() {
        //#region @backendFunc
        console.log(await lib_3.UtilsOs.getInotifyWatchCount());
        this._exit();
        //#endregion
    }
}
exports.$Global = $Global;
__decorate([
    lib_9.UtilsCliClassMethod.decoratorMethod('addEtcHostsEntry'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", void 0)
], $Global.prototype, "addEtcHostsEntry", null);
__decorate([
    lib_9.UtilsCliClassMethod.decoratorMethod('showRandomHamstersTypes'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", Promise)
], $Global.prototype, "showRandomHamstersTypes", null);
__decorate([
    lib_9.UtilsCliClassMethod.decoratorMethod('reinstallCoreContainers'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", Promise)
], $Global.prototype, "reinstallCoreContainers", null);
__decorate([
    lib_9.UtilsCliClassMethod.decoratorMethod('ENV_INSTALL'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", void 0)
], $Global.prototype, "ENV_INSTALL", null);
__decorate([
    lib_9.UtilsCliClassMethod.decoratorMethod('startCliServiceTaonProjectsWorker'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", Promise)
], $Global.prototype, "startCliServiceTaonProjectsWorker", null);
__decorate([
    lib_9.UtilsCliClassMethod.decoratorMethod('dirnameForTnp'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", void 0)
], $Global.prototype, "dirnameForTnp", null);
exports.default = {
    // registerd as empty
    $Global: lib_11.HelpersTaon.CLIWRAP($Global, ''),
};
//# sourceMappingURL=cli-_GLOBAL_.js.map