#!/usr/bin/env tsx
"use strict";
//The line above calls the TSX typescript executer as runtime, which extends node.js and supports running typescript
// see: https://www.npmjs.com/package/tsx
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
// import babelRegister from '@babel/register';
// babelRegister({extensions: ['.ts', '.tsx']});
const cli_methods_js_1 = require("./cli-methods.js");
// import {buildMetadata} from './metadata';
const commander_1 = require("commander");
const fs_extra_1 = __importDefault(require("fs-extra"));
const path_1 = __importDefault(require("path"));
require("require-extensions");
commander_1.program
    .command('create-app')
    .action((name, options) => {
    return (0, cli_methods_js_1.createApp)(name, process.cwd(), {
        appName: options.appName,
        appPrefix: options.appPrefix,
        appDomain: options.appDomain,
        skipInstall: options.skipInstall,
    });
})
    .description('Creates a new folder with all the required files for a Linked app')
    .argument('<name>', 'the name of your Linked app. To use spaces, wrap the name in double quotes.')
    .option('--app-name <name>', 'Display name for the app (skip interactive prompt)')
    .option('--app-prefix <prefix>', 'Short code prefix for data files (skip interactive prompt)')
    .option('--app-domain <domain>', 'Domain for the app (skip interactive prompt)')
    .option('--skip-install', 'Skip running yarn/npm install after scaffolding');
commander_1.program
    .command('start')
    .action(() => {
    return (0, cli_methods_js_1.startServer)();
})
    .option('--env', 'The node environment to use. Default is "development"')
    .description('Start the Linked node.js server. Use --initOnly to start the backend without http server');
commander_1.program
    .command('call')
    .action((packageName, method, options) => {
    return (0, cli_methods_js_1.runMethod)(packageName, method, { spawn: options.spawn });
})
    .option('--spawn', 'Start a new server instance instead of using an existing one')
    .option('--env', 'The node environment to use. Default is "development"')
    .description('Start the Linked node.js server but without http server. Instead it immediately calls the specified method of the specified package and exits afterwards')
    .argument('<package>', 'the package of the backend provider that contains this method')
    .argument('<method>', 'the name of the method you want to call');
commander_1.program
    .command('script')
    .action((scriptName, options) => {
    return (0, cli_methods_js_1.runScript)(scriptName, { spawn: options.spawn });
})
    .option('--spawn', 'Start a new server instance instead of using an existing one')
    .option('--env', 'The node environment to use. Default is "development"')
    .description('Start the Linked node.js server but without http server. Instead it immediately runs the specified script and exits afterwards')
    .argument('<scriptName>', 'the name of the script file inside the /scripts folder');
commander_1.program
    .command('create-package')
    .action((name, uriBase) => {
    return (0, cli_methods_js_1.createPackage)(name, uriBase);
})
    .description('Create a new folder with all the required files for a new Linked package')
    .argument('<name>', 'The name of the package. Will be used as package name in package.json')
    .argument('[uri_base]', 'The base URL used for data of this package. Leave blank to use the URL of your package on lincd.org after you register it');
commander_1.program
    .command('upgrade-packages')
    .action(() => {
    return (0, cli_methods_js_1.upgradePackages)();
})
    .description('Upgrade all linked packages in the workspace to ESM/CJS dual packages');
commander_1.program
    .command('create-shape')
    .action((name, uriBase) => {
    return (0, cli_methods_js_1.createShape)(name);
})
    .description('Creates a new ShapeClass file for your package. Execute this from your package folder.')
    .argument('<name>', 'The name of the shape. Will be used for the file name and the class name');
commander_1.program
    .command('create-component')
    .action((name, uriBase) => {
    return (0, cli_methods_js_1.createComponent)(name);
})
    .description('Creates a new Component file for your package. Execute this from your package folder.')
    .argument('<name>', 'The name of the component. Will be used for the file name and the export name');
commander_1.program
    .command('create-set-component')
    .action((name, uriBase) => {
    return (0, cli_methods_js_1.createSetComponent)(name);
})
    .description('Creates a new SetComponent file for your package. Execute this from your package folder.')
    .argument('<name>', 'The name of the component. Will be used for the file name and the export name');
commander_1.program
    .command('create-ontology')
    .action((prefix, uriBase) => {
    return (0, cli_methods_js_1.createOntology)(prefix, uriBase);
})
    .description('Creates a new ontology file for your package. Execute this from your package folder.')
    .argument('<suggested-prefix>', 'The suggested prefix for your ontology. Also the shorthand code used for the file name and the exported ontology object')
    .argument('[uribase]', "Optional argument to set the URI base for the URI's of all entities in your ontology. Leave blank to use the URI's provided by lincd.org once you register this package");
commander_1.program.command('app [action]', { hidden: true }).action(() => {
    (0, cli_methods_js_1.register)('http://localhost:4101');
});
commander_1.program.command('register-local', { hidden: true }).action(() => {
    (0, cli_methods_js_1.register)('http://localhost:4101');
});
commander_1.program.command('register-dev', { hidden: true }).action(() => {
    (0, cli_methods_js_1.register)('https://dev-registry.lincd.org');
});
commander_1.program
    .command('register')
    .action(() => {
    (0, cli_methods_js_1.register)('https://registry.lincd.org');
})
    .description('Register (a new version of) this package to the Linked registry. If successful your package will appear on linked.cm');
commander_1.program
    .command('info')
    .action(() => {
    let localDir = (0, cli_methods_js_1.getScriptDir)();
    let packageJsonPath = path_1.default.join(localDir, 'package.json');
    try {
        var ownPackage = JSON.parse(fs_extra_1.default.readFileSync(packageJsonPath, 'utf8'));
    }
    catch (e) {
        console.warn('Could not read package.json at ' + packageJsonPath + ': ' + e);
        process.exit();
    }
    console.log(ownPackage.version);
    console.log('Running from: ' + localDir);
})
    .description("Log the version of this tool and the path that it's running from");
commander_1.program
    .command('build [target] [target2]', { isDefault: true })
    .action((target, target2, options) => {
    (0, cli_methods_js_1.buildPackage)(target, target2, process.cwd(), !(options === null || options === void 0 ? void 0 : options.silent));
})
    .option('--silent', 'No output to console unless errors occur');
commander_1.program
    .command('compile-only')
    .action(() => {
    (0, cli_methods_js_1.compilePackage)();
})
    .description('Compile the package without other build steps. Run this command from the package folder');
commander_1.program.command('build-metadata').action(() => {
    console.log('Needs to be reimplemented');
    // buildMetadata();
});
commander_1.program
    .command('build-app')
    .action(() => {
    (0, cli_methods_js_1.buildApp)();
})
    .option('--env', 'The node environment to use. Default is "development"')
    .description('Start the Linked node.js server. Use --initOnly to start the backend without http server');
commander_1.program.command('publish-updated').action(() => {
    return (0, cli_methods_js_1.publishUpdated)();
});
commander_1.program.command('publish [version]').action((version) => {
    (0, cli_methods_js_1.publishPackage)(null, false, null, version);
});
commander_1.program.command('status').action(() => {
    //log which packages need to be published
    return (0, cli_methods_js_1.publishUpdated)(true).then(() => {
        //log which packages need to be build
        return (0, cli_methods_js_1.buildUpdated)(undefined, '', '', true);
    });
});
commander_1.program
    .command('build-updated [target] [target2]')
    .action((target, target2, options) => {
    const { useGit } = options;
    return (0, cli_methods_js_1.buildUpdated)(1, target, target2, useGit || false);
})
    .option('--use-git', 'Use git commit timestamps to check which packages have been updated since the last build');
commander_1.program
    .command('build-updated-since [num-commits-back] [target] [target2]')
    .action((back, target, target2) => {
    return (0, cli_methods_js_1.buildUpdated)(back, target, target2);
});
commander_1.program
    .command('build-all')
    .action((options) => {
    (0, cli_methods_js_1.buildAll)(options);
})
    .option('--sync', 'build each package 1 by 1 - use this if you have build issues due to low available RAM memory')
    .option('--from <char>', 'start from a specific package');
commander_1.program
    .command('build-workspace')
    .description('Build all linked packages in the current workspace in dependency order')
    .option('-u, --updated', 'Only build updated packages')
    .option('--use-git', 'Use git commit timestamps to determine which packages need updating')
    .action(async (options) => {
    if (options.updated) {
        return (0, cli_methods_js_1.buildUpdated)(1, undefined, undefined, !!options.useGit);
    }
    return (0, cli_methods_js_1.buildAll)(options);
});
commander_1.program
    .command('build-package <filepath>')
    .description('Given a file path, find its package.json and rebuild that package. Use for editor save hooks.')
    .action(async (filepath) => {
    const { buildPackageByPath } = await Promise.resolve().then(() => __importStar(require('./commands/build-package.js')));
    return buildPackageByPath(filepath);
});
commander_1.program
    .command('yarn')
    .description("Run yarn at the workspace root while preserving nested repositories' yarn.lock files. Forwards all extra args to yarn.")
    .allowUnknownOption(true)
    .action(async () => {
    const yarnArgs = commander_1.program.args.slice(1); // drop 'yarn' itself
    const { safeYarn } = await Promise.resolve().then(() => __importStar(require('./commands/safe-yarn.js')));
    return safeYarn(yarnArgs);
});
commander_1.program
    .command('setup-publish')
    .description('Set up a changesets publish workflow in the current package repo. Writes GitHub Actions workflows, changesets config, .gitignore entries, and patches package.json.')
    .option('--configure-github', 'Also configure GitHub branch protection on main (requires gh CLI installed and authenticated).')
    .option('--dual-branch', 'Use dual-branch (main + dev) flow with @next prereleases on dev. Default is single-branch (main only).')
    .option('--scope <scope>', 'Which NPM secret to reference in the publish workflow: "core" uses NPM_AUTH_TOKEN, "community" uses NPM_AUTH_TOKEN_CM. Defaults to "core".', 'core')
    .option('--grant-team <slug>', 'GitHub team slug to grant push access on the repo. Requires gh CLI.')
    .action(async (options) => {
    const { setupPublish } = await Promise.resolve().then(() => __importStar(require('./commands/setup-publish.js')));
    await setupPublish({
        configureGithub: !!options.configureGithub,
        dualBranch: !!options.dualBranch,
        scope: options.scope === 'community' ? 'community' : 'core',
        grantTeam: options.grantTeam,
    });
});
commander_1.program
    .command('all [action] [filter] [filter-value]')
    .action((command, filter, filterValue) => {
    (0, cli_methods_js_1.executeCommandForEachPackage)((0, cli_methods_js_1.getLincdPackages)(), command, filter, filterValue);
});
// program.command('all-except [excludedSpaces] [action]').action((excludedSpaces, command) => {
//   executeCommandForEachModule(getLincdModules(), command, null, excludedSpaces);
// });
commander_1.program.command('dev [target] [mode]').action((target, mode) => {
    (0, cli_methods_js_1.developPackage)(target, mode);
});
commander_1.program.command('depcheck').action((target, mode) => {
    (0, cli_methods_js_1.depCheck)();
});
commander_1.program.command('depcheck-staged').action((target, mode) => {
    (0, cli_methods_js_1.depCheckStaged)();
});
commander_1.program.command('check-imports').action((target, mode) => {
    (0, cli_methods_js_1.checkImports)();
});
commander_1.program
    .command('package')
    .action((name, command, args) => {
    let fullCommand = command
        ? command +
            ' ' +
            args
                .slice(0, 3)
                .filter((a) => a && true)
                .join(' ')
        : null;
    //TODO: call
    // let pkgName = process.argv[1];
    // console.log(pkgName);
    // let restArgs = process.argv.slice(2)
    // program.parse([],{from:'user'});
    // program.parse(['--port', '80'], { from: 'user' })
    (0, cli_methods_js_1.executeCommandForPackage)(name, fullCommand);
})
    .alias('p')
    .alias('pkg')
    .alias('m')
    .alias('module')
    .description('Searches for a package in this workspace with a partially matching name and executes a command for that package (without needing to execute it from the folder of the package)')
    .argument('<name>', 'the name of the package. Can be a part of the name.')
    .argument('[command]', 'the lincd command you want to execute. Like dev or build')
    .argument('[args...]', 'the additional arguments of that command');
commander_1.program.command('enable-capacitor').action(() => {
    (0, cli_methods_js_1.addCapacitor)();
});
commander_1.program.parse(process.argv);
//# sourceMappingURL=cli.js.map