Sets up formatting and main

This commit is contained in:
Ben 2025-02-25 13:59:26 +01:00
parent a2467e3ff1
commit ef589cf085
No known key found for this signature in database
GPG Key ID: 0F16E812E736C24B
19 changed files with 2829 additions and 1146 deletions

1302
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -8,13 +8,19 @@
"codexstorage": "./index.js"
},
"scripts": {
"start": "node index.js"
"start": "node index.js",
"test": "vitest run",
"test:watch": "vitest",
"format": "prettier --write ./src"
},
"keywords": [
"codex",
"storage",
"cli"
],
"engines": {
"node": ">=20"
},
"author": "Codex Storage",
"license": "MIT",
"dependencies": {
@ -27,5 +33,9 @@
"fs-extra": "^11.3.0",
"fs-filesystem": "^2.1.2",
"open": "^10.1.0"
},
"devDependencies": {
"prettier": "^3.4.2",
"vitest": "^3.0.5"
}
}

View File

@ -1,4 +1,4 @@
import { showErrorMessage } from '../utils/messages.js';
import { showErrorMessage } from "../utils/messages.js";
export function handleCommandLineOperation() {
return process.argv.length > 2;
@ -9,27 +9,33 @@ export function parseCommandLineArgs() {
if (args.length === 0) return null;
switch (args[0]) {
case '--upload':
case "--upload":
if (args.length !== 2) {
console.log(showErrorMessage('Usage: npx codexstorage --upload <filename>'));
console.log(
showErrorMessage("Usage: npx codexstorage --upload <filename>"),
);
process.exit(1);
}
return { command: 'upload', value: args[1] };
return { command: "upload", value: args[1] };
case '--download':
case "--download":
if (args.length !== 2) {
console.log(showErrorMessage('Usage: npx codexstorage --download <cid>'));
console.log(
showErrorMessage("Usage: npx codexstorage --download <cid>"),
);
process.exit(1);
}
return { command: 'download', value: args[1] };
return { command: "download", value: args[1] };
default:
console.log(showErrorMessage(
'Invalid command. Available commands:\n\n' +
'npx codexstorage\n' +
'npx codexstorage --upload <filename>\n' +
'npx codexstorage --download <cid>'
));
console.log(
showErrorMessage(
"Invalid command. Available commands:\n\n" +
"npx codexstorage\n" +
"npx codexstorage --upload <filename>\n" +
"npx codexstorage --download <cid>",
),
);
process.exit(1);
}
}

View File

@ -1,13 +1,13 @@
import inquirer from 'inquirer';
import chalk from 'chalk';
import { showErrorMessage, showInfoMessage } from './utils/messages.js';
import { isDir, showPathSelector } from './utils/pathSelector.js';
import { saveConfig } from './services/config.js';
import { showNumberSelector } from './utils/numberSelector.js';
import fs from 'fs-extra';
import inquirer from "inquirer";
import chalk from "chalk";
import { showErrorMessage, showInfoMessage } from "./utils/messages.js";
import { isDir, showPathSelector } from "./utils/pathSelector.js";
import { saveConfig } from "./services/config.js";
import { showNumberSelector } from "./utils/numberSelector.js";
import fs from "fs-extra";
function bytesAmountToString(numBytes) {
const units = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const units = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
var value = numBytes;
var index = 0;
@ -22,8 +22,12 @@ function bytesAmountToString(numBytes) {
async function showStorageQuotaSelector(config) {
console.log(showInfoMessage('You can use: "GB" or "gb", etc.'));
const result = await showNumberSelector(config.storageQuota, "Storage quota", true);
if (result < (100 * 1024 * 1024)) {
const result = await showNumberSelector(
config.storageQuota,
"Storage quota",
true,
);
if (result < 100 * 1024 * 1024) {
console.log(showErrorMessage("Storage quote should be >= 100mb."));
return config.storageQuota;
}
@ -35,11 +39,12 @@ export async function showConfigMenu(config) {
try {
while (true) {
console.log(showInfoMessage("Codex Configuration"));
const { choice } = await inquirer.prompt([
const { choice } = await inquirer
.prompt([
{
type: 'list',
name: 'choice',
message: 'Select to edit:',
type: "list",
name: "choice",
message: "Select to edit:",
choices: [
`1. Data path = "${newDataDir}"`,
`2. Logs path = "${config.logsDir}"`,
@ -47,50 +52,67 @@ export async function showConfigMenu(config) {
`4. Discovery port = ${config.ports.discPort}`,
`5. P2P listen port = ${config.ports.listenPort}`,
`6. API port = ${config.ports.apiPort}`,
'7. Save changes and exit',
'8. Discard changes and exit'
"7. Save changes and exit",
"8. Discard changes and exit",
],
pageSize: 8,
loop: true
}
]).catch(() => {
loop: true,
},
])
.catch(() => {
return;
});
switch (choice.split('.')[0]) {
case '1':
switch (choice.split(".")[0]) {
case "1":
newDataDir = await showPathSelector(config.dataDir, false);
if (isDir(newDataDir)) {
console.log(showInfoMessage("Warning: The new data path already exists. Make sure you know what you're doing."));
console.log(
showInfoMessage(
"Warning: The new data path already exists. Make sure you know what you're doing.",
),
);
}
break;
case '2':
case "2":
config.logsDir = await showPathSelector(config.logsDir, true);
break;
case '3':
case "3":
config.storageQuota = await showStorageQuotaSelector(config);
break;
case '4':
config.ports.discPort = await showNumberSelector(config.ports.discPort, "Discovery Port (UDP)", false);
case "4":
config.ports.discPort = await showNumberSelector(
config.ports.discPort,
"Discovery Port (UDP)",
false,
);
break;
case '5':
config.ports.listenPort = await showNumberSelector(config.ports.listenPort, "Listen Port (TCP)", false);
case "5":
config.ports.listenPort = await showNumberSelector(
config.ports.listenPort,
"Listen Port (TCP)",
false,
);
break;
case '6':
config.ports.apiPort = await showNumberSelector(config.ports.apiPort, "API Port (TCP)", false);
case "6":
config.ports.apiPort = await showNumberSelector(
config.ports.apiPort,
"API Port (TCP)",
false,
);
break;
case '7':
case "7":
// save changes, back to main menu
config = updateDataDir(config, newDataDir);
saveConfig(config);
return;
case '8':
case "8":
// discard changes, back to main menu
return;
}
}
} catch (error) {
console.error(chalk.red('An error occurred:', error.message));
console.error(chalk.red("An error occurred:", error.message));
return;
}
}
@ -104,28 +126,34 @@ function updateDataDir(config, newDataDir) {
// If the old one does exist: We move it.
if (isDir(config.dataDir)) {
console.log(showInfoMessage(
'Moving Codex data folder...\n' +
console.log(
showInfoMessage(
"Moving Codex data folder...\n" +
`From: "${config.dataDir}"\n` +
`To: "${newDataDir}"`
));
`To: "${newDataDir}"`,
),
);
try {
fs.moveSync(config.dataDir, newDataDir);
} catch (error) {
console.log(showErrorMessage("Error while moving dataDir: " + error.message));
console.log(
showErrorMessage("Error while moving dataDir: " + error.message),
);
throw error;
}
} else {
// Old data dir does not exist.
if (isDir(newDataDir)) {
console.log(showInfoMessage(
console.log(
showInfoMessage(
"Warning: the selected data path already exists.\n" +
`New data path = "${newDataDir}"\n` +
"Codex may overwrite data in this folder.\n" +
"Codex will fail to start if this folder does not have the required\n" +
"security permissions."
));
"security permissions.",
),
);
}
}

View File

@ -1,43 +1,62 @@
import { createSpinner } from 'nanospinner';
import { runCommand } from '../utils/command.js';
import { showErrorMessage, showInfoMessage, showSuccessMessage } from '../utils/messages.js';
import { isNodeRunning } from '../services/nodeService.js';
import fs from 'fs/promises';
import boxen from 'boxen';
import chalk from 'chalk';
import inquirer from 'inquirer';
import path from 'path';
import mime from 'mime-types';
import axios from 'axios';
import { createSpinner } from "nanospinner";
import { runCommand } from "../utils/command.js";
import {
showErrorMessage,
showInfoMessage,
showSuccessMessage,
} from "../utils/messages.js";
import { isNodeRunning } from "../services/nodeService.js";
import fs from "fs/promises";
import boxen from "boxen";
import chalk from "chalk";
import inquirer from "inquirer";
import path from "path";
import mime from "mime-types";
import axios from "axios";
export async function uploadFile(config, filePath = null, handleCommandLineOperation, showNavigationMenu) {
export async function uploadFile(
config,
filePath = null,
handleCommandLineOperation,
showNavigationMenu,
) {
const nodeRunning = await isNodeRunning(config);
if (!nodeRunning) {
console.log(showErrorMessage('Codex node is not running. Try again after starting the node'));
return handleCommandLineOperation() ? process.exit(1) : showNavigationMenu();
console.log(
showErrorMessage(
"Codex node is not running. Try again after starting the node",
),
);
return handleCommandLineOperation()
? process.exit(1)
: showNavigationMenu();
}
console.log(boxen(
chalk.yellow('⚠️ Codex does not encrypt files. Anything uploaded will be available publicly on testnet.\nThe testnet does not provide any guarantees - please do not use in production.'),
console.log(
boxen(
chalk.yellow(
"⚠️ Codex does not encrypt files. Anything uploaded will be available publicly on testnet.\nThe testnet does not provide any guarantees - please do not use in production.",
),
{
padding: 1,
margin: 1,
borderStyle: 'round',
borderColor: 'yellow',
title: '⚠️ Warning',
titleAlignment: 'center'
}
));
borderStyle: "round",
borderColor: "yellow",
title: "⚠️ Warning",
titleAlignment: "center",
},
),
);
let fileToUpload = filePath;
if (!fileToUpload) {
const { inputPath } = await inquirer.prompt([
{
type: 'input',
name: 'inputPath',
message: 'Enter the file path to upload:',
validate: input => input.length > 0
}
type: "input",
name: "inputPath",
message: "Enter the file path to upload:",
validate: (input) => input.length > 0,
},
]);
fileToUpload = inputPath;
}
@ -46,93 +65,120 @@ export async function uploadFile(config, filePath = null, handleCommandLineOpera
await fs.access(fileToUpload);
const filename = path.basename(fileToUpload);
const contentType = mime.lookup(fileToUpload) || 'application/octet-stream';
const contentType = mime.lookup(fileToUpload) || "application/octet-stream";
const spinner = createSpinner('Uploading file').start();
const spinner = createSpinner("Uploading file").start();
try {
const result = await runCommand(
`curl -X POST http://localhost:${config.ports.apiPort}/api/codex/v1/data ` +
`-H 'Content-Type: ${contentType}' ` +
`-H 'Content-Disposition: attachment; filename="${filename}"' ` +
`-w '\\n' -T "${fileToUpload}"`
`-w '\\n' -T "${fileToUpload}"`,
);
spinner.success();
console.log(showSuccessMessage('Successfully uploaded!\n\nCID: ' + result.trim()));
console.log(
showSuccessMessage("Successfully uploaded!\n\nCID: " + result.trim()),
);
} catch (error) {
spinner.error();
throw new Error(`Failed to upload: ${error.message}`);
}
} catch (error) {
console.log(showErrorMessage(error.code === 'ENOENT'
console.log(
showErrorMessage(
error.code === "ENOENT"
? `File not found: ${fileToUpload}`
: `Error uploading file: ${error.message}`));
: `Error uploading file: ${error.message}`,
),
);
}
return handleCommandLineOperation() ? process.exit(0) : showNavigationMenu();
}
export async function downloadFile(config, cid = null, handleCommandLineOperation, showNavigationMenu) {
export async function downloadFile(
config,
cid = null,
handleCommandLineOperation,
showNavigationMenu,
) {
const nodeRunning = await isNodeRunning(config);
if (!nodeRunning) {
console.log(showErrorMessage('Codex node is not running. Try again after starting the node'));
return handleCommandLineOperation() ? process.exit(1) : showNavigationMenu();
console.log(
showErrorMessage(
"Codex node is not running. Try again after starting the node",
),
);
return handleCommandLineOperation()
? process.exit(1)
: showNavigationMenu();
}
let cidToDownload = cid;
if (!cidToDownload) {
const { inputCid } = await inquirer.prompt([
{
type: 'input',
name: 'inputCid',
message: 'Enter the CID:',
validate: input => input.length > 0
}
type: "input",
name: "inputCid",
message: "Enter the CID:",
validate: (input) => input.length > 0,
},
]);
cidToDownload = inputCid;
}
try {
const spinner = createSpinner('Fetching file metadata...').start();
const spinner = createSpinner("Fetching file metadata...").start();
try {
// First, get the file metadata
const metadataResponse = await axios.post(`http://localhost:${config.ports.apiPort}/api/codex/v1/data/${cidToDownload}/network`);
const metadataResponse = await axios.post(
`http://localhost:${config.ports.apiPort}/api/codex/v1/data/${cidToDownload}/network`,
);
const { manifest } = metadataResponse.data;
const { filename, mimetype } = manifest;
spinner.success();
spinner.start('Downloading file...');
spinner.start("Downloading file...");
// Then download the file with the correct filename
await runCommand(`curl "http://localhost:${config.ports.apiPort}/api/codex/v1/data/${cidToDownload}/network/stream" -o "${filename}"`);
await runCommand(
`curl "http://localhost:${config.ports.apiPort}/api/codex/v1/data/${cidToDownload}/network/stream" -o "${filename}"`,
);
spinner.success();
console.log(showSuccessMessage(
'Successfully downloaded!\n\n' +
console.log(
showSuccessMessage(
"Successfully downloaded!\n\n" +
`Filename: ${filename}\n` +
`Type: ${mimetype}`
));
`Type: ${mimetype}`,
),
);
// Show file details
console.log(boxen(
`${chalk.cyan('File Details')}\n\n` +
`${chalk.cyan('Filename:')} ${filename}\n` +
`${chalk.cyan('MIME Type:')} ${mimetype}\n` +
`${chalk.cyan('CID:')} ${cidToDownload}\n` +
`${chalk.cyan('Protected:')} ${manifest.protected ? chalk.green('Yes') : chalk.red('No')}\n` +
`${chalk.cyan('Uploaded:')} ${new Date(manifest.uploadedAt * 1000).toLocaleString()}`,
console.log(
boxen(
`${chalk.cyan("File Details")}\n\n` +
`${chalk.cyan("Filename:")} ${filename}\n` +
`${chalk.cyan("MIME Type:")} ${mimetype}\n` +
`${chalk.cyan("CID:")} ${cidToDownload}\n` +
`${chalk.cyan("Protected:")} ${manifest.protected ? chalk.green("Yes") : chalk.red("No")}\n` +
`${chalk.cyan("Uploaded:")} ${new Date(manifest.uploadedAt * 1000).toLocaleString()}`,
{
padding: 1,
margin: 1,
borderStyle: 'round',
borderColor: 'blue',
title: '📁 Download Complete',
titleAlignment: 'center'
}
));
borderStyle: "round",
borderColor: "blue",
title: "📁 Download Complete",
titleAlignment: "center",
},
),
);
} catch (error) {
spinner.error();
if (error.response) {
throw new Error(`Failed to download: ${error.response.data.message || 'File not found'}`);
throw new Error(
`Failed to download: ${error.response.data.message || "File not found"}`,
);
} else {
throw new Error(`Failed to download: ${error.message}`);
}
@ -147,50 +193,70 @@ export async function downloadFile(config, cid = null, handleCommandLineOperatio
export async function showLocalFiles(config, showNavigationMenu) {
const nodeRunning = await isNodeRunning(config);
if (!nodeRunning) {
console.log(showErrorMessage('Codex node is not running. Try again after starting the node'));
console.log(
showErrorMessage(
"Codex node is not running. Try again after starting the node",
),
);
await showNavigationMenu();
return;
}
try {
const spinner = createSpinner('Fetching local files...').start();
const filesResponse = await axios.get(`http://localhost:${config.ports.apiPort}/api/codex/v1/data`);
const spinner = createSpinner("Fetching local files...").start();
const filesResponse = await axios.get(
`http://localhost:${config.ports.apiPort}/api/codex/v1/data`,
);
const filesData = filesResponse.data;
spinner.success();
if (filesData.content && filesData.content.length > 0) {
console.log(showInfoMessage(`Found ${filesData.content.length} local file(s)`));
console.log(
showInfoMessage(`Found ${filesData.content.length} local file(s)`),
);
filesData.content.forEach((file, index) => {
const { cid, manifest } = file;
const { rootHash, originalBytes, blockSize, protected: isProtected, filename, mimetype, uploadedAt } = manifest;
const {
rootHash,
originalBytes,
blockSize,
protected: isProtected,
filename,
mimetype,
uploadedAt,
} = manifest;
const uploadedDate = new Date(uploadedAt * 1000).toLocaleString();
const fileSize = (originalBytes / 1024).toFixed(2);
console.log(boxen(
`${chalk.cyan('File')} ${index + 1} of ${filesData.content.length}\n\n` +
`${chalk.cyan('Filename:')} ${filename}\n` +
`${chalk.cyan('CID:')} ${cid}\n` +
`${chalk.cyan('Size:')} ${fileSize} KB\n` +
`${chalk.cyan('MIME Type:')} ${mimetype}\n` +
`${chalk.cyan('Uploaded:')} ${uploadedDate}\n` +
`${chalk.cyan('Protected:')} ${isProtected ? chalk.green('Yes') : chalk.red('No')}`,
console.log(
boxen(
`${chalk.cyan("File")} ${index + 1} of ${filesData.content.length}\n\n` +
`${chalk.cyan("Filename:")} ${filename}\n` +
`${chalk.cyan("CID:")} ${cid}\n` +
`${chalk.cyan("Size:")} ${fileSize} KB\n` +
`${chalk.cyan("MIME Type:")} ${mimetype}\n` +
`${chalk.cyan("Uploaded:")} ${uploadedDate}\n` +
`${chalk.cyan("Protected:")} ${isProtected ? chalk.green("Yes") : chalk.red("No")}`,
{
padding: 1,
margin: 1,
borderStyle: 'round',
borderColor: 'blue',
borderStyle: "round",
borderColor: "blue",
title: `📁 File Details`,
titleAlignment: 'center'
}
));
titleAlignment: "center",
},
),
);
});
} else {
console.log(showInfoMessage("Node contains no datasets."));
}
} catch (error) {
console.log(showErrorMessage(`Failed to fetch local files: ${error.message}`));
console.log(
showErrorMessage(`Failed to fetch local files: ${error.message}`),
);
}
await showNavigationMenu();

View File

@ -1,59 +1,66 @@
import path from 'path';
import inquirer from 'inquirer';
import boxen from 'boxen';
import chalk from 'chalk';
import os from 'os';
import fs from 'fs';
import { createSpinner } from 'nanospinner';
import { runCommand } from '../utils/command.js';
import { showErrorMessage, showInfoMessage, showSuccessMessage } from '../utils/messages.js';
import { checkDependencies } from '../services/nodeService.js';
import { saveConfig } from '../services/config.js';
import { getCodexRootPath, getCodexBinPath } from '../utils/appdata.js';
import path from "path";
import inquirer from "inquirer";
import boxen from "boxen";
import chalk from "chalk";
import os from "os";
import fs from "fs";
import { createSpinner } from "nanospinner";
import { runCommand } from "../utils/command.js";
import {
showErrorMessage,
showInfoMessage,
showSuccessMessage,
} from "../utils/messages.js";
import { checkDependencies } from "../services/nodeService.js";
import { saveConfig } from "../services/config.js";
import { getCodexRootPath, getCodexBinPath } from "../utils/appdata.js";
const platform = os.platform();
async function showPrivacyDisclaimer() {
const disclaimer = boxen(`
${chalk.yellow.bold('Privacy Disclaimer')}
const disclaimer = boxen(
`
${chalk.yellow.bold("Privacy Disclaimer")}
Codex is currently in testnet and to make your testnet experience better, we are currently tracking some of your node and network information such as:
${chalk.cyan('- Node ID')}
${chalk.cyan('- Peer ID')}
${chalk.cyan('- Public IP address')}
${chalk.cyan('- Codex node version')}
${chalk.cyan('- Number of connected peers')}
${chalk.cyan('- Discovery and listening ports')}
${chalk.cyan("- Node ID")}
${chalk.cyan("- Peer ID")}
${chalk.cyan("- Public IP address")}
${chalk.cyan("- Codex node version")}
${chalk.cyan("- Number of connected peers")}
${chalk.cyan("- Discovery and listening ports")}
These information will be used for calculating various metrics that can eventually make the Codex experience better. Please agree to the following disclaimer to continue using the Codex Storage CLI or alternatively, use the manual setup instructions at docs.codex.storage.
`, {
`,
{
padding: 1,
margin: 1,
borderStyle: 'double',
borderColor: 'yellow',
title: '📋 IMPORTANT',
titleAlignment: 'center'
});
borderStyle: "double",
borderColor: "yellow",
title: "📋 IMPORTANT",
titleAlignment: "center",
},
);
console.log(disclaimer);
const { agreement } = await inquirer.prompt([
{
type: 'input',
name: 'agreement',
message: 'Do you agree to the privacy disclaimer? (y/n):',
type: "input",
name: "agreement",
message: "Do you agree to the privacy disclaimer? (y/n):",
validate: (input) => {
const lowercased = input.toLowerCase();
if (lowercased === 'y' || lowercased === 'n') {
if (lowercased === "y" || lowercased === "n") {
return true;
}
return 'Please enter either y or n';
}
}
return "Please enter either y or n";
},
},
]);
return agreement.toLowerCase() === 'y';
return agreement.toLowerCase() === "y";
}
export async function getCodexVersion(config) {
@ -72,12 +79,16 @@ export async function installCodex(config, showNavigationMenu) {
const version = await getCodexVersion(config);
if (version.length > 0) {
console.log(chalk.green('Codex is already installed. Version:'));
console.log(chalk.green("Codex is already installed. Version:"));
console.log(chalk.green(version));
await showNavigationMenu();
return false;
} else {
console.log(chalk.cyanBright('Codex is not installed, proceeding with installation...'));
console.log(
chalk.cyanBright(
"Codex is not installed, proceeding with installation...",
),
);
return await performInstall(config);
}
}
@ -85,12 +96,18 @@ export async function installCodex(config, showNavigationMenu) {
async function saveCodexExePath(config, codexExePath) {
config.codexExe = codexExePath;
if (!fs.existsSync(config.codexExe)) {
console.log(showErrorMessage(`Codex executable not found in expected path: ${config.codexExe}`));
console.log(
showErrorMessage(
`Codex executable not found in expected path: ${config.codexExe}`,
),
);
throw new Error("Exe not found");
}
if (await getCodexVersion(config).length < 1) {
if ((await getCodexVersion(config).length) < 1) {
console.log(showInfoMessage("no"));
throw new Error(`Codex not found at path after install. Path: '${config.codexExe}'`);
throw new Error(
`Codex not found at path after install. Path: '${config.codexExe}'`,
);
}
saveConfig(config);
}
@ -103,38 +120,50 @@ async function clearCodexExePathFromConfig(config) {
async function performInstall(config) {
const agreed = await showPrivacyDisclaimer();
if (!agreed) {
console.log(showInfoMessage('You can find manual setup instructions at docs.codex.storage'));
console.log(
showInfoMessage(
"You can find manual setup instructions at docs.codex.storage",
),
);
process.exit(0);
}
const installPath = getCodexBinPath();
console.log(showInfoMessage("Install location: " + installPath));
const spinner = createSpinner('Installing Codex...').start();
const spinner = createSpinner("Installing Codex...").start();
try {
if (platform === 'win32') {
if (platform === "win32") {
try {
try {
await runCommand('curl --version');
await runCommand("curl --version");
} catch (error) {
throw new Error('curl is not available. Please install curl or update your Windows version.');
throw new Error(
"curl is not available. Please install curl or update your Windows version.",
);
}
await runCommand('curl -LO --ssl-no-revoke https://get.codex.storage/install.cmd');
await runCommand(`set "INSTALL_DIR=${installPath}" && "${process.cwd()}\\install.cmd"`);
await runCommand(
"curl -LO --ssl-no-revoke https://get.codex.storage/install.cmd",
);
await runCommand(
`set "INSTALL_DIR=${installPath}" && "${process.cwd()}\\install.cmd"`,
);
await saveCodexExePath(config, path.join(installPath, "codex.exe"));
try {
await runCommand('del /f install.cmd');
await runCommand("del /f install.cmd");
} catch (error) {
// Ignore cleanup errors
}
} catch (error) {
if (error.message.includes('Access is denied')) {
throw new Error('Installation failed. Please run the command prompt as Administrator and try again.');
} else if (error.message.includes('curl')) {
if (error.message.includes("Access is denied")) {
throw new Error(
"Installation failed. Please run the command prompt as Administrator and try again.",
);
} else if (error.message.includes("curl")) {
throw new Error(error.message);
} else {
throw new Error(`Installation failed: "${error.message}"`);
@ -144,14 +173,19 @@ async function performInstall(config) {
try {
const dependenciesInstalled = await checkDependencies();
if (!dependenciesInstalled) {
console.log(showInfoMessage('Please install the required dependencies and try again.'));
console.log(
showInfoMessage(
"Please install the required dependencies and try again.",
),
);
throw new Error("Missing dependencies.");
}
const downloadCommand = 'curl -# --connect-timeout 10 --max-time 60 -L https://get.codex.storage/install.sh -o install.sh && chmod +x install.sh';
const downloadCommand =
"curl -# --connect-timeout 10 --max-time 60 -L https://get.codex.storage/install.sh -o install.sh && chmod +x install.sh";
await runCommand(downloadCommand);
if (platform === 'darwin') {
if (platform === "darwin") {
const timeoutCommand = `perl -e '
eval {
local $SIG{ALRM} = sub { die "timeout\\n" };
@ -163,23 +197,35 @@ async function performInstall(config) {
'`;
await runCommand(timeoutCommand);
} else {
await runCommand(`INSTALL_DIR="${installPath}" timeout 120 bash install.sh`);
await runCommand(
`INSTALL_DIR="${installPath}" timeout 120 bash install.sh`,
);
}
await saveCodexExePath(config, path.join(installPath, "codex"));
} catch (error) {
if (error.message.includes('ECONNREFUSED') || error.message.includes('ETIMEDOUT')) {
throw new Error('Installation failed. Please check your internet connection and try again.');
} else if (error.message.includes('Permission denied')) {
throw new Error('Permission denied. Please try running the command with sudo.');
} else if (error.message.includes('timeout')) {
throw new Error('Installation is taking longer than expected. Please try running with sudo.');
if (
error.message.includes("ECONNREFUSED") ||
error.message.includes("ETIMEDOUT")
) {
throw new Error(
"Installation failed. Please check your internet connection and try again.",
);
} else if (error.message.includes("Permission denied")) {
throw new Error(
"Permission denied. Please try running the command with sudo.",
);
} else if (error.message.includes("timeout")) {
throw new Error(
"Installation is taking longer than expected. Please try running with sudo.",
);
} else {
throw new Error('Installation failed. Please try running with sudo if you haven\'t already.');
throw new Error(
"Installation failed. Please try running with sudo if you haven't already.",
);
}
} finally {
await runCommand('rm -f install.sh').catch(() => {});
await runCommand("rm -f install.sh").catch(() => {});
}
}
@ -187,19 +233,23 @@ async function performInstall(config) {
const version = await getCodexVersion(config);
console.log(chalk.green(version));
console.log(showSuccessMessage(
'Codex is successfully installed!\n' +
console.log(
showSuccessMessage(
"Codex is successfully installed!\n" +
`Install path: "${config.codexExe}"\n\n` +
'The default configuration should work for most platforms.\n' +
'Please review the configuration before starting Codex.\n'
));
"The default configuration should work for most platforms.\n" +
"Please review the configuration before starting Codex.\n",
),
);
} catch (error) {
throw new Error('Installation completed but Codex command is not available. Please restart your terminal and try again.');
throw new Error(
"Installation completed but Codex command is not available. Please restart your terminal and try again.",
);
}
console.log(showInfoMessage(
"Please review the configuration before starting Codex."
));
console.log(
showInfoMessage("Please review the configuration before starting Codex."),
);
spinner.success();
return true;
@ -217,18 +267,18 @@ function removeDir(dir) {
export async function uninstallCodex(config, showNavigationMenu) {
const { confirm } = await inquirer.prompt([
{
type: 'confirm',
name: 'confirm',
type: "confirm",
name: "confirm",
message: chalk.yellow(
'⚠️ Are you sure you want to uninstall Codex? This action cannot be undone. \n' +
'All data stored in the local Codex node will be deleted as well.'
"⚠️ Are you sure you want to uninstall Codex? This action cannot be undone. \n" +
"All data stored in the local Codex node will be deleted as well.",
),
default: false
}
default: false,
},
]);
if (!confirm) {
console.log(showInfoMessage('Uninstall cancelled.'));
console.log(showInfoMessage("Uninstall cancelled."));
await showNavigationMenu();
return;
}
@ -237,13 +287,19 @@ export async function uninstallCodex(config, showNavigationMenu) {
removeDir(getCodexRootPath());
clearCodexExePathFromConfig(config);
console.log(showSuccessMessage('Codex has been successfully uninstalled.'));
console.log(showSuccessMessage("Codex has been successfully uninstalled."));
await showNavigationMenu();
} catch (error) {
if (error.code === 'ENOENT') {
console.log(showInfoMessage('Codex binary not found, nothing to uninstall.'));
if (error.code === "ENOENT") {
console.log(
showInfoMessage("Codex binary not found, nothing to uninstall."),
);
} else {
console.log(showErrorMessage('Failed to uninstall Codex. Please make sure Codex is installed before trying to remove it.'));
console.log(
showErrorMessage(
"Failed to uninstall Codex. Please make sure Codex is installed before trying to remove it.",
),
);
}
await showNavigationMenu();
}

View File

@ -1,35 +1,47 @@
import path from 'path';
import { createSpinner } from 'nanospinner';
import { runCommand } from '../utils/command.js';
import { showErrorMessage, showInfoMessage, showSuccessMessage } from '../utils/messages.js';
import { isNodeRunning, isCodexInstalled, startPeriodicLogging, getWalletAddress, setWalletAddress } from '../services/nodeService.js';
import inquirer from 'inquirer';
import boxen from 'boxen';
import chalk from 'chalk';
import os from 'os';
import { exec } from 'child_process';
import axios from 'axios';
import path from "path";
import { createSpinner } from "nanospinner";
import { runCommand } from "../utils/command.js";
import {
showErrorMessage,
showInfoMessage,
showSuccessMessage,
} from "../utils/messages.js";
import {
isNodeRunning,
isCodexInstalled,
startPeriodicLogging,
getWalletAddress,
setWalletAddress,
} from "../services/nodeService.js";
import inquirer from "inquirer";
import boxen from "boxen";
import chalk from "chalk";
import os from "os";
import { exec } from "child_process";
import axios from "axios";
const platform = os.platform();
async function promptForWalletAddress() {
const { wallet } = await inquirer.prompt([
{
type: 'input',
name: 'wallet',
message: 'Please enter your ERC20 wallet address (or press enter to skip):',
type: "input",
name: "wallet",
message:
"Please enter your ERC20 wallet address (or press enter to skip):",
validate: (input) => {
if (!input) return true; // Allow empty input
if (/^0x[a-fA-F0-9]{40}$/.test(input)) return true;
return 'Please enter a valid ERC20 wallet address (0x followed by 40 hexadecimal characters) or press enter to skip';
}
}
return "Please enter a valid ERC20 wallet address (0x followed by 40 hexadecimal characters) or press enter to skip";
},
},
]);
return wallet || null;
}
function getCurrentLogFile(config) {
const timestamp = new Date().toISOString()
const timestamp = new Date()
.toISOString()
.replaceAll(":", "-")
.replaceAll(".", "-");
return path.join(config.logsDir, `codex_${timestamp}.log`);
@ -38,7 +50,11 @@ function getCurrentLogFile(config) {
export async function runCodex(config, showNavigationMenu) {
const isInstalled = await isCodexInstalled(config);
if (!isInstalled) {
console.log(showErrorMessage('Codex is not installed. Please install Codex first using option 1 from the main menu.'));
console.log(
showErrorMessage(
"Codex is not installed. Please install Codex first using option 1 from the main menu.",
),
);
await showNavigationMenu();
return;
}
@ -46,27 +62,31 @@ export async function runCodex(config, showNavigationMenu) {
const nodeAlreadyRunning = await isNodeRunning(config);
if (nodeAlreadyRunning) {
console.log(showInfoMessage('A Codex node is already running.'));
console.log(showInfoMessage("A Codex node is already running."));
await showNavigationMenu();
} else {
try {
let nat;
if (platform === 'win32') {
const result = await runCommand('for /f "delims=" %a in (\'curl -s --ssl-reqd ip.codex.storage\') do @echo %a');
if (platform === "win32") {
const result = await runCommand(
"for /f \"delims=\" %a in ('curl -s --ssl-reqd ip.codex.storage') do @echo %a",
);
nat = result.trim();
} else {
nat = await runCommand('curl -s https://ip.codex.storage');
nat = await runCommand("curl -s https://ip.codex.storage");
}
if (config.dataDir.length < 1) throw new Error("Missing config: dataDir");
if (config.logsDir.length < 1) throw new Error("Missing config: logsDir");
const logFilePath = getCurrentLogFile(config);
console.log(showInfoMessage(
console.log(
showInfoMessage(
`Data location: ${config.dataDir}\n` +
`Logs: ${logFilePath}\n` +
`API port: ${config.ports.apiPort}`
));
`API port: ${config.ports.apiPort}`,
),
);
const executable = config.codexExe;
const args = [
@ -79,78 +99,98 @@ export async function runCodex(config, showNavigationMenu) {
`--api-port=${config.ports.apiPort}`,
`--nat=${nat}`,
`--api-cors-origin="*"`,
`--bootstrap-node=spr:CiUIAhIhAiJvIcA_ZwPZ9ugVKDbmqwhJZaig5zKyLiuaicRcCGqLEgIDARo8CicAJQgCEiECIm8hwD9nA9n26BUoNuarCEllqKDnMrIuK5qJxFwIaosQ3d6esAYaCwoJBJ_f8zKRAnU6KkYwRAIgM0MvWNJL296kJ9gWvfatfmVvT-A7O2s8Mxp8l9c8EW0CIC-h-H-jBVSgFjg3Eny2u33qF7BDnWFzo7fGfZ7_qc9P`
`--bootstrap-node=spr:CiUIAhIhAiJvIcA_ZwPZ9ugVKDbmqwhJZaig5zKyLiuaicRcCGqLEgIDARo8CicAJQgCEiECIm8hwD9nA9n26BUoNuarCEllqKDnMrIuK5qJxFwIaosQ3d6esAYaCwoJBJ_f8zKRAnU6KkYwRAIgM0MvWNJL296kJ9gWvfatfmVvT-A7O2s8Mxp8l9c8EW0CIC-h-H-jBVSgFjg3Eny2u33qF7BDnWFzo7fGfZ7_qc9P`,
];
const command =
`"${executable}" ${args.join(" ")}`
const command = `"${executable}" ${args.join(" ")}`;
console.log(showInfoMessage(
'🚀 Codex node is running...\n\n' +
'If your firewall ask, be sure to allow Codex to receive connections. \n' +
'Please keep this terminal open. Start a new terminal to interact with the node.\n\n' +
'Press CTRL+C to stop the node'
));
console.log(
showInfoMessage(
"🚀 Codex node is running...\n\n" +
"If your firewall ask, be sure to allow Codex to receive connections. \n" +
"Please keep this terminal open. Start a new terminal to interact with the node.\n\n" +
"Press CTRL+C to stop the node",
),
);
const nodeProcess = exec(command);
await new Promise(resolve => setTimeout(resolve, 5000));
await new Promise((resolve) => setTimeout(resolve, 5000));
try {
const response = await axios.get(`http://localhost:${config.ports.apiPort}/api/codex/v1/debug/info`);
const response = await axios.get(
`http://localhost:${config.ports.apiPort}/api/codex/v1/debug/info`,
);
if (response.status === 200) {
// Check if wallet exists
try {
const existingWallet = await getWalletAddress();
if (!existingWallet) {
console.log(showInfoMessage('[OPTIONAL] Please provide your ERC20 wallet address.'));
console.log(
showInfoMessage(
"[OPTIONAL] Please provide your ERC20 wallet address.",
),
);
const wallet = await promptForWalletAddress();
if (wallet) {
await setWalletAddress(wallet);
console.log(showSuccessMessage('Wallet address saved successfully!'));
console.log(
showSuccessMessage("Wallet address saved successfully!"),
);
}
}
} catch (error) {
console.log(showErrorMessage('Failed to process wallet address. Continuing without wallet update.'));
console.log(
showErrorMessage(
"Failed to process wallet address. Continuing without wallet update.",
),
);
}
// Start periodic logging
const stopLogging = await startPeriodicLogging(config);
nodeProcess.on('exit', () => {
nodeProcess.on("exit", () => {
stopLogging();
});
console.log(boxen(
chalk.cyan('We are logging some of your node\'s public data for improving the Codex experience'),
console.log(
boxen(
chalk.cyan(
"We are logging some of your node's public data for improving the Codex experience",
),
{
padding: 1,
margin: 1,
borderStyle: 'round',
borderColor: 'cyan',
title: '🔒 Privacy Notice',
titleAlignment: 'center',
dimBorder: true
}
));
borderStyle: "round",
borderColor: "cyan",
title: "🔒 Privacy Notice",
titleAlignment: "center",
dimBorder: true,
},
),
);
}
} catch (error) {
// Silently handle any logging errors
}
await new Promise((resolve, reject) => {
nodeProcess.on('exit', (code) => {
nodeProcess.on("exit", (code) => {
if (code === 0) resolve();
else reject(new Error(`Node exited with code ${code}`));
});
});
if (platform === 'win32') {
console.log(showInfoMessage('Cleaning up firewall rules...'));
await runCommand('netsh advfirewall firewall delete rule name="Allow Codex (TCP-In)"');
await runCommand('netsh advfirewall firewall delete rule name="Allow Codex (UDP-In)"');
if (platform === "win32") {
console.log(showInfoMessage("Cleaning up firewall rules..."));
await runCommand(
'netsh advfirewall firewall delete rule name="Allow Codex (TCP-In)"',
);
await runCommand(
'netsh advfirewall firewall delete rule name="Allow Codex (UDP-In)"',
);
}
} catch (error) {
console.log(showErrorMessage(`Failed to run Codex: ${error.message}`));
}
@ -161,90 +201,100 @@ export async function runCodex(config, showNavigationMenu) {
async function showNodeDetails(data, showNavigationMenu) {
const { choice } = await inquirer.prompt([
{
type: 'list',
name: 'choice',
message: 'Select information to view:',
type: "list",
name: "choice",
message: "Select information to view:",
choices: [
'1. View Connected Peers',
'2. View Node Information',
'3. Update Wallet Address',
'4. Back to Main Menu',
'5. Exit'
"1. View Connected Peers",
"2. View Node Information",
"3. Update Wallet Address",
"4. Back to Main Menu",
"5. Exit",
],
pageSize: 5,
loop: true
}
loop: true,
},
]);
switch (choice.split('.')[0].trim()) {
case '1':
switch (choice.split(".")[0].trim()) {
case "1":
const peerCount = data.table.nodes.length;
if (peerCount > 0) {
console.log(showInfoMessage('Connected Peers'));
console.log(showInfoMessage("Connected Peers"));
data.table.nodes.forEach((node, index) => {
console.log(boxen(
console.log(
boxen(
`Peer ${index + 1}:\n` +
`${chalk.cyan('Peer ID:')} ${node.peerId}\n` +
`${chalk.cyan('Address:')} ${node.address}\n` +
`${chalk.cyan('Status:')} ${node.seen ? chalk.green('Active') : chalk.gray('Inactive')}`,
`${chalk.cyan("Peer ID:")} ${node.peerId}\n` +
`${chalk.cyan("Address:")} ${node.address}\n` +
`${chalk.cyan("Status:")} ${node.seen ? chalk.green("Active") : chalk.gray("Inactive")}`,
{
padding: 1,
margin: 1,
borderStyle: 'round',
borderColor: 'blue'
}
));
borderStyle: "round",
borderColor: "blue",
},
),
);
});
} else {
console.log(showInfoMessage('No connected peers found.'));
console.log(showInfoMessage("No connected peers found."));
}
return showNodeDetails(data, showNavigationMenu);
case '2':
console.log(boxen(
`${chalk.cyan('Version:')} ${data.codex.version}\n` +
`${chalk.cyan('Revision:')} ${data.codex.revision}\n\n` +
`${chalk.cyan('Node ID:')} ${data.table.localNode.nodeId}\n` +
`${chalk.cyan('Peer ID:')} ${data.table.localNode.peerId}\n` +
`${chalk.cyan('Listening Address:')} ${data.table.localNode.address}\n\n` +
`${chalk.cyan('Public IP:')} ${data.announceAddresses[0].split('/')[2]}\n` +
`${chalk.cyan('Port:')} ${data.announceAddresses[0].split('/')[4]}\n` +
`${chalk.cyan('Connected Peers:')} ${data.table.nodes.length}`,
case "2":
console.log(
boxen(
`${chalk.cyan("Version:")} ${data.codex.version}\n` +
`${chalk.cyan("Revision:")} ${data.codex.revision}\n\n` +
`${chalk.cyan("Node ID:")} ${data.table.localNode.nodeId}\n` +
`${chalk.cyan("Peer ID:")} ${data.table.localNode.peerId}\n` +
`${chalk.cyan("Listening Address:")} ${data.table.localNode.address}\n\n` +
`${chalk.cyan("Public IP:")} ${data.announceAddresses[0].split("/")[2]}\n` +
`${chalk.cyan("Port:")} ${data.announceAddresses[0].split("/")[4]}\n` +
`${chalk.cyan("Connected Peers:")} ${data.table.nodes.length}`,
{
padding: 1,
margin: 1,
borderStyle: 'round',
borderColor: 'yellow',
title: '📊 Node Information',
titleAlignment: 'center'
}
));
borderStyle: "round",
borderColor: "yellow",
title: "📊 Node Information",
titleAlignment: "center",
},
),
);
return showNodeDetails(data, showNavigationMenu);
case '3':
case "3":
try {
const existingWallet = await getWalletAddress();
console.log(boxen(
`${chalk.cyan('Current wallet address:')}\n${existingWallet || 'Not set'}`,
console.log(
boxen(
`${chalk.cyan("Current wallet address:")}\n${existingWallet || "Not set"}`,
{
padding: 1,
margin: 1,
borderStyle: 'round',
borderColor: 'blue'
}
));
borderStyle: "round",
borderColor: "blue",
},
),
);
const wallet = await promptForWalletAddress();
if (wallet) {
await setWalletAddress(wallet);
console.log(showSuccessMessage('Wallet address updated successfully!'));
console.log(
showSuccessMessage("Wallet address updated successfully!"),
);
}
} catch (error) {
console.log(showErrorMessage(`Failed to update wallet address: ${error.message}`));
console.log(
showErrorMessage(`Failed to update wallet address: ${error.message}`),
);
}
return showNodeDetails(data, showNavigationMenu);
case '4':
case "4":
return showNavigationMenu();
case '5':
case "5":
process.exit(0);
}
}
@ -254,8 +304,10 @@ export async function checkNodeStatus(config, showNavigationMenu) {
const nodeRunning = await isNodeRunning(config);
if (nodeRunning) {
const spinner = createSpinner('Checking node status...').start();
const response = await runCommand(`curl http://localhost:${config.ports.apiPort}/api/codex/v1/debug/info`);
const spinner = createSpinner("Checking node status...").start();
const response = await runCommand(
`curl http://localhost:${config.ports.apiPort}/api/codex/v1/debug/info`,
);
spinner.success();
const data = JSON.parse(response);
@ -263,27 +315,35 @@ export async function checkNodeStatus(config, showNavigationMenu) {
const peerCount = data.table.nodes.length;
const isOnline = peerCount > 2;
console.log(boxen(
console.log(
boxen(
isOnline
? chalk.green('Node is ONLINE & DISCOVERABLE')
: chalk.yellow('Node is ONLINE but has few peers'),
? chalk.green("Node is ONLINE & DISCOVERABLE")
: chalk.yellow("Node is ONLINE but has few peers"),
{
padding: 1,
margin: 1,
borderStyle: 'round',
borderColor: isOnline ? 'green' : 'yellow',
title: '🔌 Node Status',
titleAlignment: 'center'
}
));
borderStyle: "round",
borderColor: isOnline ? "green" : "yellow",
title: "🔌 Node Status",
titleAlignment: "center",
},
),
);
await showNodeDetails(data, showNavigationMenu);
} else {
console.log(showErrorMessage('Codex node is not running. Try again after starting the node'));
console.log(
showErrorMessage(
"Codex node is not running. Try again after starting the node",
),
);
await showNavigationMenu();
}
} catch (error) {
console.log(showErrorMessage(`Failed to check node status: ${error.message}`));
console.log(
showErrorMessage(`Failed to check node status: ${error.message}`),
);
await showNavigationMenu();
}
}

View File

@ -1,54 +1,66 @@
#!/usr/bin/env node
import inquirer from 'inquirer';
import chalk from 'chalk';
import boxen from 'boxen';
import { ASCII_ART } from './constants/ascii.js';
import { handleCommandLineOperation, parseCommandLineArgs } from './cli/commandParser.js';
import { uploadFile, downloadFile, showLocalFiles } from './handlers/fileHandlers.js';
import { installCodex, uninstallCodex } from './handlers/installationHandlers.js';
import { runCodex, checkNodeStatus } from './handlers/nodeHandlers.js';
import { showInfoMessage } from './utils/messages.js';
import { loadConfig } from './services/config.js';
import { showConfigMenu } from './configmenu.js';
import { openCodexApp } from './services/codexapp.js';
import inquirer from "inquirer";
import chalk from "chalk";
import boxen from "boxen";
import { ASCII_ART } from "./constants/ascii.js";
import {
handleCommandLineOperation,
parseCommandLineArgs,
} from "./cli/commandParser.js";
import {
uploadFile,
downloadFile,
showLocalFiles,
} from "./handlers/fileHandlers.js";
import {
installCodex,
uninstallCodex,
} from "./handlers/installationHandlers.js";
import { runCodex, checkNodeStatus } from "./handlers/nodeHandlers.js";
import { showInfoMessage } from "./utils/messages.js";
import { loadConfig } from "./services/config.js";
import { showConfigMenu } from "./configmenu.js";
import { openCodexApp } from "./services/codexapp.js";
import { MainMenu } from "./ui/mainmenu.js";
import { UiService } from "./services/uiservice.js";
async function showNavigationMenu() {
console.log('\n')
console.log("\n");
const { choice } = await inquirer.prompt([
{
type: 'list',
name: 'choice',
message: 'What would you like to do?',
choices: [
'1. Back to main menu',
'2. Exit'
],
type: "list",
name: "choice",
message: "What would you like to do?",
choices: ["1. Back to main menu", "2. Exit"],
pageSize: 2,
loop: true
}
loop: true,
},
]);
switch (choice.split('.')[0]) {
case '1':
switch (choice.split(".")[0]) {
case "1":
return main();
case '2':
case "2":
handleExit();
}
}
function handleExit() {
console.log(boxen(
chalk.cyanBright('👋 Thank you for using Codex Storage CLI! Goodbye!'),
console.log(
boxen(
chalk.cyanBright("👋 Thank you for using Codex Storage CLI! Goodbye!"),
{
padding: 1,
margin: 1,
borderStyle: 'round',
borderColor: 'cyan',
title: '👋 GOODBYE',
titleAlignment: 'center'
}
));
borderStyle: "round",
borderColor: "cyan",
title: "👋 GOODBYE",
titleAlignment: "center",
},
),
);
process.exit(0);
}
@ -56,99 +68,132 @@ export async function main() {
const commandArgs = parseCommandLineArgs();
if (commandArgs) {
switch (commandArgs.command) {
case 'upload':
await uploadFile(commandArgs.value, handleCommandLineOperation, showNavigationMenu);
case "upload":
await uploadFile(
commandArgs.value,
handleCommandLineOperation,
showNavigationMenu,
);
return;
case 'download':
await downloadFile(commandArgs.value, handleCommandLineOperation, showNavigationMenu);
case "download":
await downloadFile(
commandArgs.value,
handleCommandLineOperation,
showNavigationMenu,
);
return;
}
}
process.on('SIGINT', handleExit);
process.on('SIGTERM', handleExit);
process.on('SIGQUIT', handleExit);
process.on("SIGINT", handleExit);
process.on("SIGTERM", handleExit);
process.on("SIGQUIT", handleExit);
const uiService = new UiService();
const mainMenu = new MainMenu(uiService);
mainMenu.show();
return;
try {
const config = loadConfig();
while (true) {
console.log('\n' + chalk.cyanBright(ASCII_ART));
const { choice } = await inquirer.prompt([
console.log("\n" + chalk.cyanBright(ASCII_ART));
const { choice } = await inquirer
.prompt([
{
type: 'list',
name: 'choice',
message: 'Select an option:',
type: "list",
name: "choice",
message: "Select an option:",
choices: [
'1. Download and install Codex',
'2. Run Codex node',
'3. Check node status',
'4. Edit Codex configuration',
'5. Open Codex App',
'6. Upload a file',
'7. Download a file',
'8. Show local data',
'9. Uninstall Codex node',
'10. Submit feedback',
'11. Exit'
"1. Download and install Codex",
"2. Run Codex node",
"3. Check node status",
"4. Edit Codex configuration",
"5. Open Codex App",
"6. Upload a file",
"7. Download a file",
"8. Show local data",
"9. Uninstall Codex node",
"10. Submit feedback",
"11. Exit",
],
pageSize: 11,
loop: true
}
]).catch(() => {
loop: true,
},
])
.catch(() => {
handleExit();
return;
});
switch (choice.split('.')[0]) {
case '1':
switch (choice.split(".")[0]) {
case "1":
const installed = await installCodex(config, showNavigationMenu);
if (installed) {
await showConfigMenu(config);
}
break;
case '2':
case "2":
await runCodex(config, showNavigationMenu);
return;
case '3':
case "3":
await checkNodeStatus(config, showNavigationMenu);
break;
case '4':
case "4":
await showConfigMenu(config);
break;
case '5':
case "5":
openCodexApp(config);
break;
case '6':
await uploadFile(config, null, handleCommandLineOperation, showNavigationMenu);
case "6":
await uploadFile(
config,
null,
handleCommandLineOperation,
showNavigationMenu,
);
break;
case '7':
await downloadFile(config, null, handleCommandLineOperation, showNavigationMenu);
case "7":
await downloadFile(
config,
null,
handleCommandLineOperation,
showNavigationMenu,
);
break;
case '8':
case "8":
await showLocalFiles(config, showNavigationMenu);
break;
case '9':
case "9":
await uninstallCodex(config, showNavigationMenu);
break;
case '10':
const { exec } = await import('child_process');
const url = 'https://tally.so/r/w2DlXb';
const command = process.platform === 'win32' ? `start ${url}` : process.platform === 'darwin' ? `open ${url}` : `xdg-open ${url}`;
case "10":
const { exec } = await import("child_process");
const url = "https://tally.so/r/w2DlXb";
const command =
process.platform === "win32"
? `start ${url}`
: process.platform === "darwin"
? `open ${url}`
: `xdg-open ${url}`;
exec(command);
console.log(showInfoMessage('Opening feedback form in your browser...'));
console.log(
showInfoMessage("Opening feedback form in your browser..."),
);
break;
case '11':
case "11":
handleExit();
return;
}
console.log('\n');
console.log("\n");
}
} catch (error) {
if (error.message.includes('ExitPromptError')) {
if (error.message.includes("ExitPromptError")) {
handleExit();
} else {
console.error(chalk.red('An error occurred:', error.message));
console.error(chalk.red("An error occurred:", error.message));
handleExit();
}
}

View File

@ -1,4 +1,4 @@
import open from 'open';
import open from "open";
export function openCodexApp(config) {
// TODO: Update this to the main URL when the PR for adding api-port query parameter support
@ -6,10 +6,10 @@ export function openCodexApp(config) {
// See: https://github.com/codex-storage/codex-marketplace-ui/issues/92
const segments = [
'https://releases-v0-0-14.codex-marketplace-ui.pages.dev/',
'?',
`api-port=${config.ports.apiPort}`
]
"https://releases-v0-0-14.codex-marketplace-ui.pages.dev/",
"?",
`api-port=${config.ports.apiPort}`,
];
const url = segments.join("");

View File

@ -1,7 +1,10 @@
import fs from 'fs';
import path from 'path';
import { getAppDataDir } from '../utils/appdata.js';
import { getCodexDataDirDefaultPath, getCodexLogsDefaultPath } from '../utils/appdata.js';
import fs from "fs";
import path from "path";
import { getAppDataDir } from "../utils/appdata.js";
import {
getCodexDataDirDefaultPath,
getCodexLogsDefaultPath,
} from "../utils/appdata.js";
const defaultConfig = {
codexExe: "",
@ -12,8 +15,8 @@ const defaultConfig = {
ports: {
discPort: 8090,
listenPort: 8070,
apiPort: 8080
}
apiPort: 8080,
},
};
function getConfigFilename() {
@ -25,7 +28,9 @@ export function saveConfig(config) {
try {
fs.writeFileSync(filePath, JSON.stringify(config));
} catch (error) {
console.error(`Failed to save config file to '${filePath}' error: '${error}'.`);
console.error(
`Failed to save config file to '${filePath}' error: '${error}'.`,
);
throw error;
}
}
@ -39,7 +44,9 @@ export function loadConfig() {
}
return JSON.parse(fs.readFileSync(filePath));
} catch (error) {
console.error(`Failed to load config file from '${filePath}' error: '${error}'.`);
console.error(
`Failed to load config file from '${filePath}' error: '${error}'.`,
);
throw error;
}
}

View File

@ -1,8 +1,12 @@
import axios from 'axios';
import { runCommand } from '../utils/command.js';
import { showErrorMessage, showInfoMessage, showSuccessMessage } from '../utils/messages.js';
import os from 'os';
import { getCodexVersion } from '../handlers/installationHandlers.js';
import axios from "axios";
import { runCommand } from "../utils/command.js";
import {
showErrorMessage,
showInfoMessage,
showSuccessMessage,
} from "../utils/messages.js";
import os from "os";
import { getCodexVersion } from "../handlers/installationHandlers.js";
const platform = os.platform();
@ -12,7 +16,7 @@ let currentWallet = null;
export async function setWalletAddress(wallet) {
// Basic ERC20 address validation
if (wallet && !/^0x[a-fA-F0-9]{40}$/.test(wallet)) {
throw new Error('Invalid ERC20 wallet address format');
throw new Error("Invalid ERC20 wallet address format");
}
currentWallet = wallet;
}
@ -23,7 +27,9 @@ export async function getWalletAddress() {
export async function isNodeRunning(config) {
try {
const response = await axios.get(`http://localhost:${config.ports.apiPort}/api/codex/v1/debug/info`);
const response = await axios.get(
`http://localhost:${config.ports.apiPort}/api/codex/v1/debug/info`,
);
return response.status === 200;
} catch (error) {
return false;
@ -39,48 +45,66 @@ export async function isCodexInstalled(config) {
}
}
export async function logToSupabase(nodeData, retryCount = 3, retryDelay = 1000) {
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
export async function logToSupabase(
nodeData,
retryCount = 3,
retryDelay = 1000,
) {
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
for (let attempt = 1; attempt <= retryCount; attempt++) {
try {
const peerCount = nodeData.table.nodes ? nodeData.table.nodes.length : "0";
const peerCount = nodeData.table.nodes
? nodeData.table.nodes.length
: "0";
const payload = {
nodeId: nodeData.table.localNode.nodeId,
peerId: nodeData.table.localNode.peerId,
publicIp: nodeData.announceAddresses[0].split('/')[2],
publicIp: nodeData.announceAddresses[0].split("/")[2],
version: nodeData.codex.version,
peerCount: peerCount == 0 ? "0" : peerCount,
port: nodeData.announceAddresses[0].split('/')[4],
port: nodeData.announceAddresses[0].split("/")[4],
listeningAddress: nodeData.table.localNode.address,
timestamp: new Date().toISOString(),
wallet: currentWallet
wallet: currentWallet,
};
const response = await axios.post('https://vfcnsjxahocmzefhckfz.supabase.co/functions/v1/codexnodes', payload, {
const response = await axios.post(
"https://vfcnsjxahocmzefhckfz.supabase.co/functions/v1/codexnodes",
payload,
{
headers: {
'Content-Type': 'application/json'
"Content-Type": "application/json",
},
timeout: 5000
});
timeout: 5000,
},
);
return response.status === 200;
} catch (error) {
const isLastAttempt = attempt === retryCount;
const isNetworkError = error.code === 'ENOTFOUND' || error.code === 'ETIMEDOUT' || error.code === 'ECONNREFUSED';
const isNetworkError =
error.code === "ENOTFOUND" ||
error.code === "ETIMEDOUT" ||
error.code === "ECONNREFUSED";
if (isLastAttempt || !isNetworkError) {
console.error(`Failed to log node data (attempt ${attempt}/${retryCount}):`, error.message);
console.error(
`Failed to log node data (attempt ${attempt}/${retryCount}):`,
error.message,
);
if (error.response) {
console.error('Error response:', {
console.error("Error response:", {
status: error.response.status,
data: error.response.data
data: error.response.data,
});
}
if (isLastAttempt) return false;
} else {
// Only log retry attempts for network errors
console.log(`Retrying to log data (attempt ${attempt}/${retryCount})...`);
console.log(
`Retrying to log data (attempt ${attempt}/${retryCount})...`,
);
await delay(retryDelay);
}
}
@ -89,16 +113,20 @@ export async function logToSupabase(nodeData, retryCount = 3, retryDelay = 1000)
}
export async function checkDependencies() {
if (platform === 'linux') {
if (platform === "linux") {
try {
await runCommand('ldconfig -p | grep libgomp');
await runCommand("ldconfig -p | grep libgomp");
return true;
} catch (error) {
console.log(showErrorMessage('Required dependency libgomp1 is not installed.'));
console.log(showInfoMessage(
'For Debian-based Linux systems, please install it manually using:\n\n' +
'sudo apt update && sudo apt install libgomp1'
));
console.log(
showErrorMessage("Required dependency libgomp1 is not installed."),
);
console.log(
showInfoMessage(
"For Debian-based Linux systems, please install it manually using:\n\n" +
"sudo apt update && sudo apt install libgomp1",
),
);
return false;
}
}
@ -110,13 +138,15 @@ export async function startPeriodicLogging(config) {
const logNodeInfo = async () => {
try {
const response = await axios.get(`http://localhost:${config.ports.apiPort}/api/codex/v1/debug/info`);
const response = await axios.get(
`http://localhost:${config.ports.apiPort}/api/codex/v1/debug/info`,
);
if (response.status === 200) {
await logToSupabase(response.data);
}
} catch (error) {
// Silently handle any logging errors to not disrupt the node operation
console.error('Failed to log node data:', error.message);
console.error("Failed to log node data:", error.message);
}
};
@ -133,22 +163,26 @@ export async function startPeriodicLogging(config) {
export async function updateWalletAddress(nodeId, wallet) {
// Basic ERC20 address validation
if (!/^0x[a-fA-F0-9]{40}$/.test(wallet)) {
throw new Error('Invalid ERC20 wallet address format');
throw new Error("Invalid ERC20 wallet address format");
}
try {
const response = await axios.post('https://vfcnsjxahocmzefhckfz.supabase.co/functions/v1/wallet', {
const response = await axios.post(
"https://vfcnsjxahocmzefhckfz.supabase.co/functions/v1/wallet",
{
nodeId,
wallet
}, {
headers: {
'Content-Type': 'application/json'
wallet,
},
timeout: 5000
});
{
headers: {
"Content-Type": "application/json",
},
timeout: 5000,
},
);
return response.status === 200;
} catch (error) {
console.error('Failed to update wallet address:', error.message);
console.error("Failed to update wallet address:", error.message);
throw error;
}
}

47
src/services/uiservice.js Normal file
View File

@ -0,0 +1,47 @@
import boxen from "boxen";
import chalk from "chalk";
function show(msg) {
console.log(msg);
}
export class UiService {
showSuccessMessage = (message) => {
show(
boxen(chalk.green(message), {
padding: 1,
margin: 1,
borderStyle: "round",
borderColor: "green",
title: "✅ SUCCESS",
titleAlignment: "center",
}),
);
};
showErrorMessage = (message) => {
show(
boxen(chalk.red(message), {
padding: 1,
margin: 1,
borderStyle: "round",
borderColor: "red",
title: "❌ ERROR",
titleAlignment: "center",
}),
);
};
showInfoMessage(message) {
show(
boxen(chalk.cyan(message), {
padding: 1,
margin: 1,
borderStyle: "round",
borderColor: "cyan",
title: " INFO",
titleAlignment: "center",
}),
);
}
}

9
src/ui/mainmenu.js Normal file
View File

@ -0,0 +1,9 @@
export class MainMenu {
constructor(uiService) {
this.ui = uiService;
}
show = () => {
this.ui.showInfoMessage("hello");
};
}

View File

@ -1,5 +1,5 @@
import path from 'path';
import fs from 'fs';
import path from "path";
import fs from "fs";
export function getAppDataDir() {
return ensureExists(appData("codex-cli"));
@ -32,10 +32,15 @@ function ensureExists(dir) {
function appData(...app) {
let appData;
if (process.platform === 'win32') {
if (process.platform === "win32") {
appData = path.join(process.env.APPDATA, ...app);
} else if (process.platform === 'darwin') {
appData = path.join(process.env.HOME, 'Library', 'Application Support', ...app);
} else if (process.platform === "darwin") {
appData = path.join(
process.env.HOME,
"Library",
"Application Support",
...app,
);
} else {
appData = path.join(process.env.HOME, ...prependDot(...app));
}
@ -51,4 +56,3 @@ function prependDot(...app) {
}
});
}

View File

@ -1,5 +1,5 @@
import { exec } from 'child_process';
import { promisify } from 'util';
import { exec } from "child_process";
import { promisify } from "util";
export const execAsync = promisify(exec);
@ -8,7 +8,7 @@ export async function runCommand(command) {
const { stdout, stderr } = await execAsync(command);
return stdout;
} catch (error) {
console.error('Error:', error.message);
console.error("Error:", error.message);
throw error;
}
}

View File

@ -1,14 +1,14 @@
import boxen from 'boxen';
import chalk from 'chalk';
import boxen from "boxen";
import chalk from "chalk";
export function showSuccessMessage(message) {
return boxen(chalk.green(message), {
padding: 1,
margin: 1,
borderStyle: 'round',
borderColor: 'green',
title: '✅ SUCCESS',
titleAlignment: 'center'
borderStyle: "round",
borderColor: "green",
title: "✅ SUCCESS",
titleAlignment: "center",
});
}
@ -16,10 +16,10 @@ export function showErrorMessage(message) {
return boxen(chalk.red(message), {
padding: 1,
margin: 1,
borderStyle: 'round',
borderColor: 'red',
title: '❌ ERROR',
titleAlignment: 'center'
borderStyle: "round",
borderColor: "red",
title: "❌ ERROR",
titleAlignment: "center",
});
}
@ -27,9 +27,9 @@ export function showInfoMessage(message) {
return boxen(chalk.cyan(message), {
padding: 1,
margin: 1,
borderStyle: 'round',
borderColor: 'cyan',
title: ' INFO',
titleAlignment: 'center'
borderStyle: "round",
borderColor: "cyan",
title: " INFO",
titleAlignment: "center",
});
}

View File

@ -1,4 +1,4 @@
import inquirer from 'inquirer';
import inquirer from "inquirer";
function getMetricsMult(valueStr, allowMetricPostfixes) {
if (!allowMetricPostfixes) return 1;
@ -27,14 +27,19 @@ function getNumericValue(valueStr) {
async function promptForValueStr(promptMessage) {
const response = await inquirer.prompt([
{
type: 'input',
name: 'valueStr',
message: promptMessage
}]);
type: "input",
name: "valueStr",
message: promptMessage,
},
]);
return response.valueStr;
}
export async function showNumberSelector(currentValue, promptMessage, allowMetricPostfixes) {
export async function showNumberSelector(
currentValue,
promptMessage,
allowMetricPostfixes,
) {
try {
var valueStr = await promptForValueStr(promptMessage);
valueStr = valueStr.replaceAll(" ", "");

View File

@ -1,18 +1,20 @@
import path from 'path';
import inquirer from 'inquirer';
import boxen from 'boxen';
import chalk from 'chalk';
import fs from 'fs';
import { filesystemSync } from 'fs-filesystem';
import path from "path";
import inquirer from "inquirer";
import boxen from "boxen";
import chalk from "chalk";
import fs from "fs";
import { filesystemSync } from "fs-filesystem";
function showMsg(msg) {
console.log(boxen(chalk.white(msg), {
console.log(
boxen(chalk.white(msg), {
padding: 1,
margin: 1,
borderStyle: 'round',
borderColor: 'white',
titleAlignment: 'center'
}));
borderStyle: "round",
borderColor: "white",
titleAlignment: "center",
}),
);
}
function getAvailableRoots() {
@ -41,7 +43,7 @@ function dropEmptyParts(parts) {
if (part.length > 0) {
result.push(part);
}
})
});
return result;
}
@ -63,10 +65,10 @@ function showCurrent(currentPath) {
if (len < 2) {
showMsg(
'Warning - Known issue:\n' +
'Path selection does not work in root paths on some platforms.\n' +
"Warning - Known issue:\n" +
"Path selection does not work in root paths on some platforms.\n" +
'Use "Enter path" or "Create new folder" to navigate and create folders\n' +
'if this is the case for you.'
"if this is the case for you.",
);
}
}
@ -86,25 +88,27 @@ function hasValidRoot(roots, checkPath) {
async function showMain(currentPath) {
showCurrent(currentPath);
const { choice } = await inquirer.prompt([
const { choice } = await inquirer
.prompt([
{
type: 'list',
name: 'choice',
message: 'Select an option:',
type: "list",
name: "choice",
message: "Select an option:",
choices: [
'1. Enter path',
'2. Go up one',
'3. Go down one',
'4. Create new folder here',
'5. Select this path',
'6. Cancel'
"1. Enter path",
"2. Go up one",
"3. Go down one",
"4. Create new folder here",
"5. Select this path",
"6. Cancel",
],
pageSize: 6,
loop: true
}
]).catch(() => {
loop: true,
},
])
.catch(() => {
handleExit();
return { choice: '6' };
return { choice: "6" };
});
return choice;
@ -121,27 +125,27 @@ export async function showPathSelector(startingPath, pathMustExist) {
const choice = await showMain(currentPath);
var newCurrentPath = currentPath;
switch (choice.split('.')[0]) {
case '1':
switch (choice.split(".")[0]) {
case "1":
newCurrentPath = await enterPath(currentPath, pathMustExist);
break;
case '2':
case "2":
newCurrentPath = upOne(currentPath);
break;
case '3':
case "3":
newCurrentPath = await downOne(currentPath);
break;
case '4':
case "4":
newCurrentPath = await createSubDir(currentPath, pathMustExist);
break;
case '5':
case "5":
if (pathMustExist && !isDir(combine(currentPath))) {
console.log("Current path does not exist.");
break;
} else {
return combine(currentPath);
}
case '6':
case "6":
return combine(currentPath);
}
@ -156,10 +160,11 @@ export async function showPathSelector(startingPath, pathMustExist) {
async function enterPath(currentPath, pathMustExist) {
const response = await inquirer.prompt([
{
type: 'input',
name: 'path',
message: 'Enter Path:'
}]);
type: "input",
name: "path",
message: "Enter Path:",
},
]);
const newPath = response.path;
if (pathMustExist && !isDir(newPath)) {
@ -193,7 +198,7 @@ function getSubDirOptions(currentPath) {
var counter = 1;
entries.forEach(function (entry) {
if (isSubDir(currentPath, entry)) {
result.push(counter + '. ' + entry);
result.push(counter + ". " + entry);
counter = counter + 1;
}
});
@ -207,30 +212,33 @@ async function downOne(currentPath) {
return currentPath;
}
const { choice } = await inquirer.prompt([
const { choice } = await inquirer
.prompt([
{
type: 'list',
name: 'choice',
message: 'Select an subdir:',
type: "list",
name: "choice",
message: "Select an subdir:",
choices: options,
pageSize: options.length,
loop: true
}
]).catch(() => {
loop: true,
},
])
.catch(() => {
return currentPath;
});
const subDir = choice.split('. ')[1];
const subDir = choice.split(". ")[1];
return [...currentPath, subDir];
}
async function createSubDir(currentPath, pathMustExist) {
const response = await inquirer.prompt([
{
type: 'input',
name: 'name',
message: 'Enter name:'
}]);
type: "input",
name: "name",
message: "Enter name:",
},
]);
const name = response.name;
if (name.length < 1) return;