@kubiklabs/wasmkit
Version:
Wasmkit is a development environment to compile, deploy, test, run cosmwasm contracts on different networks.
242 lines (241 loc) • 9.97 kB
JavaScript
;
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 (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__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 });
exports.installDependencies = exports.createConfirmationPrompt = exports.createProject = exports.printSuggestedCommands = exports.printWelcomeMessage = void 0;
/* eslint-disable @typescript-eslint/no-this-alias */
const chalk_1 = __importDefault(require("chalk"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const os_1 = __importDefault(require("os"));
const path_1 = __importDefault(require("path"));
const constants_1 = require("../../lib/constants");
const errors_1 = require("../core/errors");
const errors_list_1 = require("../core/errors-list");
const execution_mode_1 = require("../core/execution-mode");
const packageInfo_1 = require("../util/packageInfo");
const initialize_template_1 = require("./initialize-template");
const SAMPLE_PROJECT_DEPENDENCIES = [
"chai"
];
async function printWelcomeMessage() {
const packageJson = await (0, packageInfo_1.getPackageJson)();
console.log(chalk_1.default.cyan(`★ Welcome to ${constants_1.WASMKIT_NAME} v${packageJson.version}`));
}
exports.printWelcomeMessage = printWelcomeMessage;
function copySampleProject(projectName) {
const packageRoot = (0, packageInfo_1.getPackageRoot)();
const sampleProjDir = path_1.default.join(packageRoot, "sample-project");
const currDir = process.cwd();
const projectPath = path_1.default.join(currDir, projectName);
console.log(chalk_1.default.greenBright("Initializing new project in " + projectPath + "."));
fs_extra_1.default.copySync(sampleProjDir, projectPath, {
// User doesn't choose the directory so overwrite should be avoided
overwrite: false,
filter: (src, dest) => {
const relPath = path_1.default.relative(process.cwd(), dest);
if (relPath === '') {
return true;
}
if (path_1.default.basename(dest) === ".gitkeep") {
return false;
}
if (fs_extra_1.default.pathExistsSync(dest)) {
throw new errors_1.WasmkitError(errors_list_1.ERRORS.GENERAL.INIT_INSIDE_PROJECT, {
clashingFile: relPath
});
}
return true;
}
});
}
function printSuggestedCommands(projectName) {
const currDir = process.cwd();
const projectPath = path_1.default.join(currDir, projectName);
console.log(`Success! Created project at ${chalk_1.default.greenBright(projectPath)}.`);
// TODO: console.log(`Inside that directory, you can run several commands:`);
// list commands and respective description
console.log(`Begin by typing:`);
console.log(` cd ${projectName}`);
console.log(` ${constants_1.WASMKIT_NAME} help`);
console.log(` ${constants_1.WASMKIT_NAME} compile`);
}
exports.printSuggestedCommands = printSuggestedCommands;
async function printPluginInstallationInstructions() {
console.log(`You need to install these dependencies to run the sample project:`);
const cmd = await npmInstallCmd();
console.log(` ${cmd.join(" ")}`);
}
// eslint-disable-next-line
async function createProject(projectName, templateName, destination) {
if (templateName !== undefined) {
const currDir = process.cwd();
const projectPath = destination ?? path_1.default.join(currDir, projectName);
await (0, initialize_template_1.initialize)({
force: false,
projectName: projectName,
templateName: templateName,
destination: projectPath
});
return;
}
await printWelcomeMessage();
copySampleProject(projectName);
let shouldShowInstallationInstructions = true;
if (await canInstallPlugin()) {
const installedRecommendedDeps = SAMPLE_PROJECT_DEPENDENCIES.filter(isInstalled);
if (installedRecommendedDeps.length === SAMPLE_PROJECT_DEPENDENCIES.length) {
shouldShowInstallationInstructions = false;
}
else if (installedRecommendedDeps.length === 0) {
const shouldInstall = await confirmPluginInstallation();
if (shouldInstall) {
const installed = await installRecommendedDependencies();
if (!installed) {
console.warn(chalk_1.default.red("Failed to install the sample project's dependencies"));
}
shouldShowInstallationInstructions = !installed;
}
}
}
console.log("\n★", chalk_1.default.cyan("Project created"), "★\n");
if (shouldShowInstallationInstructions) {
await printPluginInstallationInstructions();
console.log(``);
}
printSuggestedCommands(projectName);
}
exports.createProject = createProject;
function createConfirmationPrompt(name, message) {
return {
type: "confirm",
name,
message,
initial: "y",
default: "(Y/n)",
isTrue(input) {
if (typeof input === "string") {
return input.toLowerCase() === "y";
}
return input;
},
isFalse(input) {
if (typeof input === "string") {
return input.toLowerCase() === "n";
}
return input;
},
format() {
const that = this; // eslint-disable-line @typescript-eslint/no-explicit-any
const value = that.value === true ? "y" : "n";
if (that.state.submitted === true) {
return that.styles.submitted(value);
}
return value;
}
};
}
exports.createConfirmationPrompt = createConfirmationPrompt;
async function canInstallPlugin() {
return ((await fs_extra_1.default.pathExists("package.json")) &&
((0, execution_mode_1.getExecutionMode)() === execution_mode_1.ExecutionMode.EXECUTION_MODE_LOCAL_INSTALLATION ||
(0, execution_mode_1.getExecutionMode)() === execution_mode_1.ExecutionMode.EXECUTION_MODE_LINKED) &&
// TODO: Figure out why this doesn't work on Win
os_1.default.type() !== "Windows_NT");
}
function isInstalled(dep) {
const packageJson = fs_extra_1.default.readJSONSync("package.json");
const allDependencies = {
...packageJson.dependencies,
...packageJson.devDependencies,
...packageJson.optionalDependencies
};
return dep in allDependencies;
}
function isYarnProject() {
return fs_extra_1.default.pathExistsSync("yarn.lock");
}
async function installRecommendedDependencies() {
console.log("");
const installCmd = await npmInstallCmd();
return await installDependencies(installCmd[0], installCmd.slice(1));
}
async function confirmPluginInstallation() {
const { default: enquirer } = await Promise.resolve().then(() => __importStar(require("enquirer")));
let responses;
const packageManager = isYarnProject() ? "yarn" : "npm";
try {
responses = await enquirer.prompt([
createConfirmationPrompt("shouldInstallPlugin", `Do you want to install the sample project's dependencies with ${packageManager} (${SAMPLE_PROJECT_DEPENDENCIES.join(" ")})?`)
]);
}
catch (e) {
if (e === "") {
return false;
}
throw e;
}
return responses.shouldInstallPlugin;
}
async function installDependencies(packageManager, args, location) {
const { spawn } = await Promise.resolve().then(() => __importStar(require("child_process")));
console.log(`${packageManager} ${args.join(" ")}`);
const childProcess = spawn(packageManager, args, {
stdio: "inherit",
cwd: location
});
return await new Promise((resolve, reject) => {
childProcess.once("close", (status) => {
childProcess.removeAllListeners("error");
if (status === 0) {
resolve(true);
return;
}
reject(new Error("script process returned not 0 status"));
});
childProcess.once("error", (status) => {
childProcess.removeAllListeners("close");
reject(new Error("script process returned not 0 status"));
});
});
}
exports.installDependencies = installDependencies;
async function npmInstallCmd() {
const isGlobal = (0, execution_mode_1.getExecutionMode)() === execution_mode_1.ExecutionMode.EXECUTION_MODE_GLOBAL_INSTALLATION;
if (isYarnProject()) {
const cmd = ["yarn"];
if (isGlobal) {
cmd.push("global");
}
cmd.push("add", "--dev", ...SAMPLE_PROJECT_DEPENDENCIES);
return cmd;
}
const npmInstall = ["npm", "install"];
if (isGlobal) {
npmInstall.push("--global");
}
return [...npmInstall, "--save-dev", ...SAMPLE_PROJECT_DEPENDENCIES];
}