tambahannya
This commit is contained in:
55
bin/g3n.ts
55
bin/g3n.ts
@@ -1,7 +1,16 @@
|
||||
#!/usr/bin/env bun
|
||||
import minimist from "minimist";
|
||||
import path from "path";
|
||||
import { generateEnvTypes } from "../generate/env.generate.js";
|
||||
|
||||
import { generateEnvTypes } from "../generate/env.generate";
|
||||
import checkPort from "./src/port";
|
||||
import route from "./src/route";
|
||||
import not3 from "./src/not3";
|
||||
|
||||
interface CheckPortResult {
|
||||
port: number;
|
||||
open: boolean;
|
||||
}
|
||||
|
||||
const args = minimist(process.argv.slice(2));
|
||||
|
||||
@@ -10,13 +19,19 @@ g3n [command] [options]
|
||||
|
||||
Commands:
|
||||
env Generate env.d.ts from .env file
|
||||
|
||||
scan-port Scan port range (default 3000-4000)
|
||||
route Generate routes.ts from AppRoutes.tsx
|
||||
Options:
|
||||
--env Path ke file .env (default: .env)
|
||||
--out Path file output (default: types/env.d.ts)
|
||||
--start Port awal scan (default: 3000)
|
||||
--end Port akhir scan (default: 4000)
|
||||
--host Host/IP target (default: 127.0.0.1)
|
||||
|
||||
Examples:
|
||||
g3n env --env .env.local --out src/types/env.d.ts
|
||||
g3n scan-port --start 7700 --end 7800 --host 127.0.0.1
|
||||
g3n route
|
||||
`;
|
||||
|
||||
(async () => {
|
||||
@@ -31,5 +46,41 @@ Examples:
|
||||
return;
|
||||
}
|
||||
|
||||
if (cmd === "scan-port") {
|
||||
const start: number = args.start ? parseInt(args.start, 10) : 3000;
|
||||
const end: number = args.end ? parseInt(args.end, 10) : 4000;
|
||||
const host: string = args.host || "localhost";
|
||||
|
||||
console.log(`🔍 Scan port ${start}-${end} di host ${host} ...`);
|
||||
|
||||
const ports: number[] = Array.from(
|
||||
{ length: end - start + 1 },
|
||||
(_, i) => start + i
|
||||
);
|
||||
|
||||
const results: CheckPortResult[] = await Promise.all(
|
||||
ports.map((p) => checkPort(p, host))
|
||||
);
|
||||
|
||||
results.filter((r) => r.open).forEach((r) => {
|
||||
console.log(`✅ Port ${r.port} sedang digunakan`);
|
||||
});
|
||||
|
||||
console.log("✅ Selesai");
|
||||
return;
|
||||
}
|
||||
|
||||
if(cmd === "route") {
|
||||
route();
|
||||
return;
|
||||
}
|
||||
|
||||
if(cmd === "note") {
|
||||
not3()
|
||||
return;
|
||||
}
|
||||
|
||||
console.error(help);
|
||||
})();
|
||||
|
||||
|
||||
|
||||
275
bin/not3.ts
Executable file
275
bin/not3.ts
Executable file
@@ -0,0 +1,275 @@
|
||||
#!/usr/bin/env bun
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import * as os from 'os';
|
||||
import { execSync } from 'child_process';
|
||||
|
||||
const CONFIG_FILE = path.join(os.homedir(), '.note.conf');
|
||||
|
||||
interface Config {
|
||||
TOKEN?: string;
|
||||
REPO?: string;
|
||||
URL?: string;
|
||||
}
|
||||
|
||||
// --- Check dependencies ---
|
||||
function checkDependency(cmd: string): boolean {
|
||||
try {
|
||||
execSync(`command -v ${cmd}`, { stdio: 'ignore' });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function checkDependencies(): void {
|
||||
const deps = ['curl', 'jq'];
|
||||
for (const cmd of deps) {
|
||||
if (!checkDependency(cmd)) {
|
||||
console.error(`❌ Missing dependency: ${cmd} (please install it)`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Config management ---
|
||||
function createDefaultConfig(): void {
|
||||
const defaultConfig = `TOKEN=
|
||||
REPO=
|
||||
URL=https://cld-dkr-makuro-seafile.wibudev.com/api2
|
||||
`;
|
||||
fs.writeFileSync(CONFIG_FILE, defaultConfig);
|
||||
}
|
||||
|
||||
function editConfig(): void {
|
||||
if (!fs.existsSync(CONFIG_FILE)) {
|
||||
createDefaultConfig();
|
||||
}
|
||||
|
||||
const editor = process.env.EDITOR || 'vim';
|
||||
try {
|
||||
execSync(`${editor} "${CONFIG_FILE}"`, { stdio: 'inherit' });
|
||||
} catch (error) {
|
||||
console.error('❌ Failed to open editor');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
function loadConfig(): Config {
|
||||
if (!fs.existsSync(CONFIG_FILE)) {
|
||||
console.error(`⚠️ Config file not found at ${CONFIG_FILE}`);
|
||||
console.error('Run: node note.ts config to create/edit it.');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const configContent = fs.readFileSync(CONFIG_FILE, 'utf8');
|
||||
const config: Config = {};
|
||||
|
||||
for (const line of configContent.split('\n')) {
|
||||
const trimmed = line.trim();
|
||||
if (trimmed && !trimmed.startsWith('#')) {
|
||||
const [key, ...valueParts] = trimmed.split('=');
|
||||
if (key && valueParts.length > 0) {
|
||||
const value = valueParts.join('=');
|
||||
config[key as keyof Config] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!config.TOKEN || !config.REPO) {
|
||||
console.error(`❌ Config invalid. Please set TOKEN=... and REPO=... inside ${CONFIG_FILE}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Set default URL if not provided
|
||||
if (!config.URL) {
|
||||
console.error(`❌ Config invalid. Please set URL=... inside ${CONFIG_FILE}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
// --- HTTP helpers ---
|
||||
function curlCommand(config: Config, options: string): string {
|
||||
try {
|
||||
return execSync(`curl -s -H "Authorization: Token ${config.TOKEN}" ${options}`,
|
||||
{ encoding: 'utf8' });
|
||||
} catch (error) {
|
||||
console.error('❌ Request failed');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
function curlCommandSilent(config: Config, options: string): void {
|
||||
try {
|
||||
execSync(`curl -s -H "Authorization: Token ${config.TOKEN}" ${options} >/dev/null`,
|
||||
{ stdio: 'ignore' });
|
||||
} catch (error) {
|
||||
console.error('❌ Request failed');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Commands ---
|
||||
function listFiles(config: Config): void {
|
||||
const response = curlCommand(config, `"${config.URL}/${config.REPO}/dir/?p=/"`);
|
||||
try {
|
||||
const files = JSON.parse(response);
|
||||
for (const file of files) {
|
||||
console.log(file.name);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('❌ Failed to parse response');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
function catFile(config: Config, fileName: string): void {
|
||||
const downloadUrlResponse = curlCommand(config, `"${config.URL}/${config.REPO}/file/?p=/${fileName}"`);
|
||||
const downloadUrl = downloadUrlResponse.replace(/"/g, '');
|
||||
const content = curlCommand(config, `"${downloadUrl}"`);
|
||||
console.log(content);
|
||||
}
|
||||
|
||||
function uploadFile(config: Config, localFile: string, remoteFile?: string): void {
|
||||
if (!fs.existsSync(localFile)) {
|
||||
console.error(`❌ File not found: ${localFile}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const remoteName = remoteFile || path.basename(localFile);
|
||||
const uploadUrlResponse = curlCommand(config, `"${config.URL}/${config.REPO}/upload-link/?p=/"`);
|
||||
const uploadUrl = uploadUrlResponse.replace(/"/g, '');
|
||||
|
||||
try {
|
||||
execSync(`curl -s -H "Authorization: Token ${config.TOKEN}" \
|
||||
-F "file=@${localFile}" \
|
||||
-F "filename=${remoteName}" \
|
||||
-F "parent_dir=/" \
|
||||
"${uploadUrl}" >/dev/null`, { stdio: 'ignore' });
|
||||
console.log(`✅ Uploaded ${localFile} → ${remoteName}`);
|
||||
} catch (error) {
|
||||
console.error('❌ Upload failed');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
function removeFile(config: Config, fileName: string): void {
|
||||
curlCommandSilent(config, `-X DELETE "${config.URL}/${config.REPO}/file/?p=/${fileName}"`);
|
||||
console.log(`🗑️ Removed ${fileName}`);
|
||||
}
|
||||
|
||||
function moveFile(config: Config, oldName: string, newName: string): void {
|
||||
try {
|
||||
execSync(`curl -s -X POST -H "Authorization: Token ${config.TOKEN}" \
|
||||
-d "operation=rename" \
|
||||
-d "newname=${newName}" \
|
||||
"${config.URL}/${config.REPO}/file/?p=/${oldName}" >/dev/null`, { stdio: 'ignore' });
|
||||
console.log(`✏️ Renamed ${oldName} → ${newName}`);
|
||||
} catch (error) {
|
||||
console.error('❌ Rename failed');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
function downloadFile(config: Config, remoteFile: string, localFile?: string): void {
|
||||
const localName = localFile || remoteFile;
|
||||
const downloadUrlResponse = curlCommand(config, `"${config.URL}/${config.REPO}/file/?p=/${remoteFile}"`);
|
||||
const downloadUrl = downloadUrlResponse.replace(/"/g, '');
|
||||
|
||||
try {
|
||||
execSync(`curl -s -H "Authorization: Token ${config.TOKEN}" "${downloadUrl}" -o "${localName}"`,
|
||||
{ stdio: 'ignore' });
|
||||
console.log(`⬇️ Downloaded ${remoteFile} → ${localName}`);
|
||||
} catch (error) {
|
||||
console.error('❌ Download failed');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
function showHelp(): void {
|
||||
console.log(`note - simple CLI for Seafile notes
|
||||
Usage:
|
||||
node note.ts ls List files
|
||||
node note.ts cat <file> Show file content
|
||||
node note.ts cp <local> [remote] Upload file
|
||||
node note.ts rm <remote> Remove file
|
||||
node note.ts mv <old> <new> Rename/move file
|
||||
node note.ts get <remote> [local] Download file
|
||||
node note.ts config Edit config (~/.note.conf)
|
||||
|
||||
Config (~/.note.conf):
|
||||
TOKEN=your_seafile_token
|
||||
REPO=repos/<repo-id>
|
||||
URL=your_seafile_url/api2`);
|
||||
}
|
||||
|
||||
// --- Main ---
|
||||
function not3(): void {
|
||||
const args = process.argv.slice(2);
|
||||
const cmd = args[0] || 'help';
|
||||
|
||||
// Handle config command without dependency check
|
||||
if (cmd === 'config') {
|
||||
editConfig();
|
||||
return;
|
||||
}
|
||||
|
||||
// Check dependencies for other commands
|
||||
checkDependencies();
|
||||
|
||||
// Load config for other commands
|
||||
const config = loadConfig();
|
||||
|
||||
switch (cmd) {
|
||||
case 'ls':
|
||||
listFiles(config);
|
||||
break;
|
||||
|
||||
case 'cat':
|
||||
if (!args[1]) {
|
||||
console.error('Usage: node note.ts cat <file>');
|
||||
process.exit(1);
|
||||
}
|
||||
catFile(config, args[1]);
|
||||
break;
|
||||
|
||||
case 'cp':
|
||||
if (!args[1]) {
|
||||
console.error('Usage: node note.ts cp <local_file> [remote_file]');
|
||||
process.exit(1);
|
||||
}
|
||||
uploadFile(config, args[1], args[2]);
|
||||
break;
|
||||
|
||||
case 'rm':
|
||||
if (!args[1]) {
|
||||
console.error('Usage: node note.ts rm <remote_file>');
|
||||
process.exit(1);
|
||||
}
|
||||
removeFile(config, args[1]);
|
||||
break;
|
||||
|
||||
case 'mv':
|
||||
if (!args[1] || !args[2]) {
|
||||
console.error('Usage: node note.ts mv <old_name> <new_name>');
|
||||
process.exit(1);
|
||||
}
|
||||
moveFile(config, args[1], args[2]);
|
||||
break;
|
||||
|
||||
case 'get':
|
||||
if (!args[1]) {
|
||||
console.error('Usage: node note.ts get <remote_file> [local_file]');
|
||||
process.exit(1);
|
||||
}
|
||||
downloadFile(config, args[1], args[2]);
|
||||
break;
|
||||
|
||||
case 'help':
|
||||
default:
|
||||
showHelp();
|
||||
break;
|
||||
}
|
||||
}
|
||||
277
bin/src/not3.ts
Normal file
277
bin/src/not3.ts
Normal file
@@ -0,0 +1,277 @@
|
||||
#!/usr/bin/env bun
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import * as os from 'os';
|
||||
import { execSync } from 'child_process';
|
||||
|
||||
const CONFIG_FILE = path.join(os.homedir(), '.note.conf');
|
||||
|
||||
interface Config {
|
||||
TOKEN?: string;
|
||||
REPO?: string;
|
||||
URL?: string;
|
||||
}
|
||||
|
||||
// --- Check dependencies ---
|
||||
function checkDependency(cmd: string): boolean {
|
||||
try {
|
||||
execSync(`command -v ${cmd}`, { stdio: 'ignore' });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function checkDependencies(): void {
|
||||
const deps = ['curl', 'jq'];
|
||||
for (const cmd of deps) {
|
||||
if (!checkDependency(cmd)) {
|
||||
console.error(`❌ Missing dependency: ${cmd} (please install it)`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Config management ---
|
||||
function createDefaultConfig(): void {
|
||||
const defaultConfig = `TOKEN=
|
||||
REPO=
|
||||
URL=https://cld-dkr-makuro-seafile.wibudev.com/api2
|
||||
`;
|
||||
fs.writeFileSync(CONFIG_FILE, defaultConfig);
|
||||
}
|
||||
|
||||
function editConfig(): void {
|
||||
if (!fs.existsSync(CONFIG_FILE)) {
|
||||
createDefaultConfig();
|
||||
}
|
||||
|
||||
const editor = process.env.EDITOR || 'vim';
|
||||
try {
|
||||
execSync(`${editor} "${CONFIG_FILE}"`, { stdio: 'inherit' });
|
||||
} catch (error) {
|
||||
console.error('❌ Failed to open editor');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
function loadConfig(): Config {
|
||||
if (!fs.existsSync(CONFIG_FILE)) {
|
||||
console.error(`⚠️ Config file not found at ${CONFIG_FILE}`);
|
||||
console.error('Run: node note.ts config to create/edit it.');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const configContent = fs.readFileSync(CONFIG_FILE, 'utf8');
|
||||
const config: Config = {};
|
||||
|
||||
for (const line of configContent.split('\n')) {
|
||||
const trimmed = line.trim();
|
||||
if (trimmed && !trimmed.startsWith('#')) {
|
||||
const [key, ...valueParts] = trimmed.split('=');
|
||||
if (key && valueParts.length > 0) {
|
||||
const value = valueParts.join('=');
|
||||
config[key as keyof Config] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!config.TOKEN || !config.REPO) {
|
||||
console.error(`❌ Config invalid. Please set TOKEN=... and REPO=... inside ${CONFIG_FILE}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Set default URL if not provided
|
||||
if (!config.URL) {
|
||||
console.error(`❌ Config invalid. Please set URL=... inside ${CONFIG_FILE}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
// --- HTTP helpers ---
|
||||
function curlCommand(config: Config, options: string): string {
|
||||
try {
|
||||
return execSync(`curl -s -H "Authorization: Token ${config.TOKEN}" ${options}`,
|
||||
{ encoding: 'utf8' });
|
||||
} catch (error) {
|
||||
console.error('❌ Request failed');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
function curlCommandSilent(config: Config, options: string): void {
|
||||
try {
|
||||
execSync(`curl -s -H "Authorization: Token ${config.TOKEN}" ${options} >/dev/null`,
|
||||
{ stdio: 'ignore' });
|
||||
} catch (error) {
|
||||
console.error('❌ Request failed');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Commands ---
|
||||
function listFiles(config: Config): void {
|
||||
const response = curlCommand(config, `"${config.URL}/${config.REPO}/dir/?p=/"`);
|
||||
try {
|
||||
const files = JSON.parse(response);
|
||||
for (const file of files) {
|
||||
console.log(file.name);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('❌ Failed to parse response');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
function catFile(config: Config, fileName: string): void {
|
||||
const downloadUrlResponse = curlCommand(config, `"${config.URL}/${config.REPO}/file/?p=/${fileName}"`);
|
||||
const downloadUrl = downloadUrlResponse.replace(/"/g, '');
|
||||
const content = curlCommand(config, `"${downloadUrl}"`);
|
||||
console.log(content);
|
||||
}
|
||||
|
||||
function uploadFile(config: Config, localFile: string, remoteFile?: string): void {
|
||||
if (!fs.existsSync(localFile)) {
|
||||
console.error(`❌ File not found: ${localFile}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const remoteName = remoteFile || path.basename(localFile);
|
||||
const uploadUrlResponse = curlCommand(config, `"${config.URL}/${config.REPO}/upload-link/?p=/"`);
|
||||
const uploadUrl = uploadUrlResponse.replace(/"/g, '');
|
||||
|
||||
try {
|
||||
execSync(`curl -s -H "Authorization: Token ${config.TOKEN}" \
|
||||
-F "file=@${localFile}" \
|
||||
-F "filename=${remoteName}" \
|
||||
-F "parent_dir=/" \
|
||||
"${uploadUrl}" >/dev/null`, { stdio: 'ignore' });
|
||||
console.log(`✅ Uploaded ${localFile} → ${remoteName}`);
|
||||
} catch (error) {
|
||||
console.error('❌ Upload failed');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
function removeFile(config: Config, fileName: string): void {
|
||||
curlCommandSilent(config, `-X DELETE "${config.URL}/${config.REPO}/file/?p=/${fileName}"`);
|
||||
console.log(`🗑️ Removed ${fileName}`);
|
||||
}
|
||||
|
||||
function moveFile(config: Config, oldName: string, newName: string): void {
|
||||
try {
|
||||
execSync(`curl -s -X POST -H "Authorization: Token ${config.TOKEN}" \
|
||||
-d "operation=rename" \
|
||||
-d "newname=${newName}" \
|
||||
"${config.URL}/${config.REPO}/file/?p=/${oldName}" >/dev/null`, { stdio: 'ignore' });
|
||||
console.log(`✏️ Renamed ${oldName} → ${newName}`);
|
||||
} catch (error) {
|
||||
console.error('❌ Rename failed');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
function downloadFile(config: Config, remoteFile: string, localFile?: string): void {
|
||||
const localName = localFile || remoteFile;
|
||||
const downloadUrlResponse = curlCommand(config, `"${config.URL}/${config.REPO}/file/?p=/${remoteFile}"`);
|
||||
const downloadUrl = downloadUrlResponse.replace(/"/g, '');
|
||||
|
||||
try {
|
||||
execSync(`curl -s -H "Authorization: Token ${config.TOKEN}" "${downloadUrl}" -o "${localName}"`,
|
||||
{ stdio: 'ignore' });
|
||||
console.log(`⬇️ Downloaded ${remoteFile} → ${localName}`);
|
||||
} catch (error) {
|
||||
console.error('❌ Download failed');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
function showHelp(): void {
|
||||
console.log(`note - simple CLI for Seafile notes
|
||||
Usage:
|
||||
node note.ts ls List files
|
||||
node note.ts cat <file> Show file content
|
||||
node note.ts cp <local> [remote] Upload file
|
||||
node note.ts rm <remote> Remove file
|
||||
node note.ts mv <old> <new> Rename/move file
|
||||
node note.ts get <remote> [local] Download file
|
||||
node note.ts config Edit config (~/.note.conf)
|
||||
|
||||
Config (~/.note.conf):
|
||||
TOKEN=your_seafile_token
|
||||
REPO=repos/<repo-id>
|
||||
URL=your_seafile_url/api2`);
|
||||
}
|
||||
|
||||
// --- Main ---
|
||||
function not3(): void {
|
||||
const args = process.argv.slice(2);
|
||||
const cmd = args[0] || 'help';
|
||||
|
||||
// Handle config command without dependency check
|
||||
if (cmd === 'config') {
|
||||
editConfig();
|
||||
return;
|
||||
}
|
||||
|
||||
// Check dependencies for other commands
|
||||
checkDependencies();
|
||||
|
||||
// Load config for other commands
|
||||
const config = loadConfig();
|
||||
|
||||
switch (cmd) {
|
||||
case 'ls':
|
||||
listFiles(config);
|
||||
break;
|
||||
|
||||
case 'cat':
|
||||
if (!args[1]) {
|
||||
console.error('Usage: node note.ts cat <file>');
|
||||
process.exit(1);
|
||||
}
|
||||
catFile(config, args[1]);
|
||||
break;
|
||||
|
||||
case 'cp':
|
||||
if (!args[1]) {
|
||||
console.error('Usage: node note.ts cp <local_file> [remote_file]');
|
||||
process.exit(1);
|
||||
}
|
||||
uploadFile(config, args[1], args[2]);
|
||||
break;
|
||||
|
||||
case 'rm':
|
||||
if (!args[1]) {
|
||||
console.error('Usage: node note.ts rm <remote_file>');
|
||||
process.exit(1);
|
||||
}
|
||||
removeFile(config, args[1]);
|
||||
break;
|
||||
|
||||
case 'mv':
|
||||
if (!args[1] || !args[2]) {
|
||||
console.error('Usage: node note.ts mv <old_name> <new_name>');
|
||||
process.exit(1);
|
||||
}
|
||||
moveFile(config, args[1], args[2]);
|
||||
break;
|
||||
|
||||
case 'get':
|
||||
if (!args[1]) {
|
||||
console.error('Usage: node note.ts get <remote_file> [local_file]');
|
||||
process.exit(1);
|
||||
}
|
||||
downloadFile(config, args[1], args[2]);
|
||||
break;
|
||||
|
||||
case 'help':
|
||||
default:
|
||||
showHelp();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
export default not3;
|
||||
31
bin/src/port.ts
Normal file
31
bin/src/port.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
#!/usr/bin/env bun
|
||||
import net from "net";
|
||||
|
||||
interface CheckPortResult {
|
||||
port: number;
|
||||
open: boolean;
|
||||
}
|
||||
|
||||
export default function checkPort(port: number, host: string): Promise<CheckPortResult> {
|
||||
return new Promise((resolve) => {
|
||||
const socket = new net.Socket();
|
||||
socket.setTimeout(200);
|
||||
|
||||
socket.once("connect", () => {
|
||||
socket.destroy();
|
||||
resolve({ port, open: true });
|
||||
});
|
||||
|
||||
socket.once("timeout", () => {
|
||||
socket.destroy();
|
||||
resolve({ port, open: false });
|
||||
});
|
||||
|
||||
socket.once("error", () => {
|
||||
socket.destroy();
|
||||
resolve({ port, open: false });
|
||||
});
|
||||
|
||||
socket.connect(port, host);
|
||||
});
|
||||
}
|
||||
138
bin/src/route.ts
Normal file
138
bin/src/route.ts
Normal file
@@ -0,0 +1,138 @@
|
||||
#!/usr/bin/env bun
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import * as parser from "@babel/parser";
|
||||
import traverse from "@babel/traverse";
|
||||
import * as t from "@babel/types";
|
||||
|
||||
const SRC_DIR = path.resolve(process.cwd(), "src");
|
||||
const APP_ROUTES_FILE = path.join(SRC_DIR, "AppRoutes.tsx");
|
||||
|
||||
interface RouteNode {
|
||||
path: string;
|
||||
children: RouteNode[];
|
||||
}
|
||||
|
||||
function getAttributePath(attrs: (t.JSXAttribute | t.JSXSpreadAttribute)[]) {
|
||||
const pathAttr = attrs.find(
|
||||
(attr) =>
|
||||
t.isJSXAttribute(attr) &&
|
||||
t.isJSXIdentifier(attr.name, { name: "path" })
|
||||
) as t.JSXAttribute | undefined;
|
||||
|
||||
if (pathAttr && t.isStringLiteral(pathAttr.value)) {
|
||||
return pathAttr.value.value;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Rekursif baca node <Route> beserta anak-anaknya
|
||||
*/
|
||||
function extractRouteNodes(node: t.JSXElement): RouteNode | null {
|
||||
const opening = node.openingElement;
|
||||
|
||||
if (!t.isJSXIdentifier(opening.name) || opening.name.name !== "Route") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const currentPath = getAttributePath(opening.attributes);
|
||||
|
||||
// cari anak-anak <Route>
|
||||
const children: RouteNode[] = [];
|
||||
for (const child of node.children) {
|
||||
if (t.isJSXElement(child)) {
|
||||
const childNode = extractRouteNodes(child);
|
||||
if (childNode) children.push(childNode);
|
||||
}
|
||||
}
|
||||
|
||||
return { path: currentPath, children };
|
||||
}
|
||||
|
||||
/**
|
||||
* Flatten hasil rekursif jadi list path full
|
||||
*/
|
||||
function flattenRoutes(
|
||||
node: RouteNode,
|
||||
parentPath = ""
|
||||
): Record<string, string> {
|
||||
const record: Record<string, string> = {};
|
||||
|
||||
// gabung path parent + child
|
||||
let fullPath = node.path;
|
||||
if (fullPath) {
|
||||
if (parentPath) {
|
||||
if (fullPath === "/") {
|
||||
fullPath = parentPath;
|
||||
} else {
|
||||
fullPath = `${parentPath.replace(/\/$/, "")}/${fullPath.replace(
|
||||
/^\//,
|
||||
""
|
||||
)}`;
|
||||
}
|
||||
}
|
||||
if (!fullPath.startsWith("/")) {
|
||||
fullPath = `/${fullPath}`;
|
||||
}
|
||||
record[fullPath] = fullPath;
|
||||
}
|
||||
|
||||
for (const child of node.children) {
|
||||
Object.assign(record, flattenRoutes(child, fullPath || parentPath));
|
||||
}
|
||||
|
||||
return record;
|
||||
}
|
||||
|
||||
function extractRoutes(code: string): Record<string, string> {
|
||||
const ast = parser.parse(code, {
|
||||
sourceType: "module",
|
||||
plugins: ["typescript", "jsx"],
|
||||
});
|
||||
|
||||
const routes: Record<string, string> = {};
|
||||
|
||||
traverse(ast, {
|
||||
JSXElement(path) {
|
||||
const node = path.node;
|
||||
const opening = node.openingElement;
|
||||
if (t.isJSXIdentifier(opening.name) && opening.name.name === "Routes") {
|
||||
for (const child of node.children) {
|
||||
if (t.isJSXElement(child)) {
|
||||
const routeNode = extractRouteNodes(child);
|
||||
if (routeNode) {
|
||||
Object.assign(routes, flattenRoutes(routeNode));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
return routes;
|
||||
}
|
||||
|
||||
export default function route() {
|
||||
if (!fs.existsSync(APP_ROUTES_FILE)) {
|
||||
console.error("❌ AppRoutes.tsx not found in src/");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const code = fs.readFileSync(APP_ROUTES_FILE, "utf-8");
|
||||
const routes = extractRoutes(code);
|
||||
|
||||
console.log("✅ Generated Routes:");
|
||||
console.log(routes);
|
||||
|
||||
const outPath = path.join(SRC_DIR, "clientRoutes.ts");
|
||||
fs.writeFileSync(
|
||||
outPath,
|
||||
`// AUTO-GENERATED FILE\nconst clientRoutes = ${JSON.stringify(
|
||||
routes,
|
||||
null,
|
||||
2
|
||||
)} as const;\n\nexport default clientRoutes;`
|
||||
);
|
||||
console.log(`📄 clientRoutes.ts generated at ${outPath}`);
|
||||
}
|
||||
53
bun.lock
53
bun.lock
@@ -4,37 +4,64 @@
|
||||
"": {
|
||||
"name": "g3n",
|
||||
"dependencies": {
|
||||
"@babel/parser": "^7.28.3",
|
||||
"@babel/traverse": "^7.28.3",
|
||||
"@babel/types": "^7.28.2",
|
||||
"@types/babel__traverse": "^7.28.0",
|
||||
"@types/minimist": "^1.2.5",
|
||||
"dotenv": "^17.2.1",
|
||||
"minimist": "^1.2.8",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bun": "latest",
|
||||
},
|
||||
"peerDependencies": {
|
||||
"typescript": "^5",
|
||||
},
|
||||
},
|
||||
},
|
||||
"packages": {
|
||||
"@types/bun": ["@types/bun@1.2.20", "", { "dependencies": { "bun-types": "1.2.20" } }, "sha512-dX3RGzQ8+KgmMw7CsW4xT5ITBSCrSbfHc36SNT31EOUg/LA9JWq0VDdEXDRSe1InVWpd2yLUM1FUF/kEOyTzYA=="],
|
||||
"@babel/code-frame": ["@babel/code-frame@7.27.1", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.27.1", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-cjQ7ZlQ0Mv3b47hABuTevyTuYN4i+loJKGeV9flcCgIK37cCXRh+L1bd3iBHlynerhQ7BhCkn2BPbQUL+rGqFg=="],
|
||||
|
||||
"@babel/generator": ["@babel/generator@7.28.3", "", { "dependencies": { "@babel/parser": "^7.28.3", "@babel/types": "^7.28.2", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "jsesc": "^3.0.2" } }, "sha512-3lSpxGgvnmZznmBkCRnVREPUFJv2wrv9iAoFDvADJc0ypmdOxdUtcLeBgBJ6zE0PMeTKnxeQzyk0xTBq4Ep7zw=="],
|
||||
|
||||
"@babel/helper-globals": ["@babel/helper-globals@7.28.0", "", {}, "sha512-+W6cISkXFa1jXsDEdYA8HeevQT/FULhxzR99pxphltZcVaugps53THCeiWA8SguxxpSp3gKPiuYfSWopkLQ4hw=="],
|
||||
|
||||
"@babel/helper-string-parser": ["@babel/helper-string-parser@7.27.1", "", {}, "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA=="],
|
||||
|
||||
"@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.27.1", "", {}, "sha512-D2hP9eA+Sqx1kBZgzxZh0y1trbuU+JoDkiEwqhQ36nodYqJwyEIhPSdMNd7lOm/4io72luTPWH20Yda0xOuUow=="],
|
||||
|
||||
"@babel/parser": ["@babel/parser@7.28.3", "", { "dependencies": { "@babel/types": "^7.28.2" }, "bin": "./bin/babel-parser.js" }, "sha512-7+Ey1mAgYqFAx2h0RuoxcQT5+MlG3GTV0TQrgr7/ZliKsm/MNDxVVutlWaziMq7wJNAz8MTqz55XLpWvva6StA=="],
|
||||
|
||||
"@babel/template": ["@babel/template@7.27.2", "", { "dependencies": { "@babel/code-frame": "^7.27.1", "@babel/parser": "^7.27.2", "@babel/types": "^7.27.1" } }, "sha512-LPDZ85aEJyYSd18/DkjNh4/y1ntkE5KwUHWTiqgRxruuZL2F1yuHligVHLvcHY2vMHXttKFpJn6LwfI7cw7ODw=="],
|
||||
|
||||
"@babel/traverse": ["@babel/traverse@7.28.3", "", { "dependencies": { "@babel/code-frame": "^7.27.1", "@babel/generator": "^7.28.3", "@babel/helper-globals": "^7.28.0", "@babel/parser": "^7.28.3", "@babel/template": "^7.27.2", "@babel/types": "^7.28.2", "debug": "^4.3.1" } }, "sha512-7w4kZYHneL3A6NP2nxzHvT3HCZ7puDZZjFMqDpBPECub79sTtSO5CGXDkKrTQq8ksAwfD/XI2MRFX23njdDaIQ=="],
|
||||
|
||||
"@babel/types": ["@babel/types@7.28.2", "", { "dependencies": { "@babel/helper-string-parser": "^7.27.1", "@babel/helper-validator-identifier": "^7.27.1" } }, "sha512-ruv7Ae4J5dUYULmeXw1gmb7rYRz57OWCPM57pHojnLq/3Z1CK2lNSLTCVjxVk1F/TZHwOZZrOWi0ur95BbLxNQ=="],
|
||||
|
||||
"@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.3.13", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA=="],
|
||||
|
||||
"@jridgewell/resolve-uri": ["@jridgewell/resolve-uri@3.1.2", "", {}, "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw=="],
|
||||
|
||||
"@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.5.5", "", {}, "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og=="],
|
||||
|
||||
"@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.30", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-GQ7Nw5G2lTu/BtHTKfXhKHok2WGetd4XYcVKGx00SjAk8GMwgJM3zr6zORiPGuOE+/vkc90KtTosSSvaCjKb2Q=="],
|
||||
|
||||
"@types/babel__traverse": ["@types/babel__traverse@7.28.0", "", { "dependencies": { "@babel/types": "^7.28.2" } }, "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q=="],
|
||||
|
||||
"@types/minimist": ["@types/minimist@1.2.5", "", {}, "sha512-hov8bUuiLiyFPGyFPE1lwWhmzYbirOXQNNo40+y3zow8aFVTeyn3VWL0VFFfdNddA8S4Vf0Tc062rzyNr7Paag=="],
|
||||
|
||||
"@types/node": ["@types/node@24.3.0", "", { "dependencies": { "undici-types": "~7.10.0" } }, "sha512-aPTXCrfwnDLj4VvXrm+UUCQjNEvJgNA8s5F1cvwQU+3KNltTOkBm1j30uNLyqqPNe7gE3KFzImYoZEfLhp4Yow=="],
|
||||
|
||||
"@types/react": ["@types/react@19.1.10", "", { "dependencies": { "csstype": "^3.0.2" } }, "sha512-EhBeSYX0Y6ye8pNebpKrwFJq7BoQ8J5SO6NlvNwwHjSj6adXJViPQrKlsyPw7hLBLvckEMO1yxeGdR82YBBlDg=="],
|
||||
|
||||
"bun-types": ["bun-types@1.2.20", "", { "dependencies": { "@types/node": "*" }, "peerDependencies": { "@types/react": "^19" } }, "sha512-pxTnQYOrKvdOwyiyd/7sMt9yFOenN004Y6O4lCcCUoKVej48FS5cvTw9geRaEcB9TsDZaJKAxPTVvi8tFsVuXA=="],
|
||||
|
||||
"csstype": ["csstype@3.1.3", "", {}, "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw=="],
|
||||
"debug": ["debug@4.4.1", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ=="],
|
||||
|
||||
"dotenv": ["dotenv@17.2.1", "", {}, "sha512-kQhDYKZecqnM0fCnzI5eIv5L4cAe/iRI+HqMbO/hbRdTAeXDG+M9FjipUxNfbARuEg4iHIbhnhs78BCHNbSxEQ=="],
|
||||
|
||||
"js-tokens": ["js-tokens@4.0.0", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="],
|
||||
|
||||
"jsesc": ["jsesc@3.1.0", "", { "bin": { "jsesc": "bin/jsesc" } }, "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA=="],
|
||||
|
||||
"minimist": ["minimist@1.2.8", "", {}, "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA=="],
|
||||
|
||||
"typescript": ["typescript@5.9.2", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-CWBzXQrc/qOkhidw1OzBTQuYRbfyxDXJMVJ1XNwUHGROVmuaeiEm3OslpZ1RV96d7SKKjZKrSJu3+t/xlw3R9A=="],
|
||||
"ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
|
||||
|
||||
"undici-types": ["undici-types@7.10.0", "", {}, "sha512-t5Fy/nfn+14LuOc2KNYg75vZqClpAiqscVvMygNnlsHBFpSXdJaYtXMcdNLpl/Qvc3P2cB3s6lOV51nqsFq4ag=="],
|
||||
"picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="],
|
||||
|
||||
"typescript": ["typescript@5.9.2", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-CWBzXQrc/qOkhidw1OzBTQuYRbfyxDXJMVJ1XNwUHGROVmuaeiEm3OslpZ1RV96d7SKKjZKrSJu3+t/xlw3R9A=="],
|
||||
}
|
||||
}
|
||||
|
||||
59
index.ts
59
index.ts
@@ -2,6 +2,12 @@
|
||||
import minimist from "minimist";
|
||||
import { generateEnvTypes } from "./generate/env.generate.js";
|
||||
import path from "path";
|
||||
import net from "net";
|
||||
|
||||
interface CheckPortResult {
|
||||
port: number;
|
||||
open: boolean;
|
||||
}
|
||||
|
||||
const args = minimist(process.argv.slice(2));
|
||||
|
||||
@@ -10,13 +16,18 @@ g3n [command] [options]
|
||||
|
||||
Commands:
|
||||
env Generate env.d.ts from .env file
|
||||
scan Scan port range (default 3000-4000)
|
||||
|
||||
Options:
|
||||
--env Path ke file .env (default: .env)
|
||||
--out Path file output (default: types/env.d.ts)
|
||||
--start Port awal scan (default: 3000)
|
||||
--end Port akhir scan (default: 4000)
|
||||
--host Host/IP target (default: 127.0.0.1)
|
||||
|
||||
Examples:
|
||||
g3n env --env .env.local --out src/types/env.d.ts
|
||||
g3n scan --start 7700 --end 7800 --host 127.0.0.1
|
||||
`;
|
||||
|
||||
(async () => {
|
||||
@@ -31,5 +42,53 @@ Examples:
|
||||
return;
|
||||
}
|
||||
|
||||
if (cmd === "scan") {
|
||||
const start: number = args.start ? parseInt(args.start, 10) : 3000;
|
||||
const end: number = args.end ? parseInt(args.end, 10) : 4000;
|
||||
const host: string = args.host || "127.0.0.1";
|
||||
|
||||
console.log(`🔍 Scan port ${start}-${end} di host ${host} ...`);
|
||||
|
||||
const ports: number[] = Array.from(
|
||||
{ length: end - start + 1 },
|
||||
(_, i) => start + i
|
||||
);
|
||||
|
||||
const results: CheckPortResult[] = await Promise.all(
|
||||
ports.map((p) => checkPort(p, host))
|
||||
);
|
||||
|
||||
results.filter((r) => r.open).forEach((r) => {
|
||||
console.log(`✅ Port ${r.port} sedang digunakan`);
|
||||
});
|
||||
|
||||
console.log("✅ Selesai");
|
||||
return;
|
||||
}
|
||||
|
||||
console.error(help);
|
||||
})();
|
||||
|
||||
function checkPort(port: number, host: string): Promise<CheckPortResult> {
|
||||
return new Promise((resolve) => {
|
||||
const socket = new net.Socket();
|
||||
socket.setTimeout(200);
|
||||
|
||||
socket.once("connect", () => {
|
||||
socket.destroy();
|
||||
resolve({ port, open: true });
|
||||
});
|
||||
|
||||
socket.once("timeout", () => {
|
||||
socket.destroy();
|
||||
resolve({ port, open: false });
|
||||
});
|
||||
|
||||
socket.once("error", () => {
|
||||
socket.destroy();
|
||||
resolve({ port, open: false });
|
||||
});
|
||||
|
||||
socket.connect(port, host);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,14 +1,19 @@
|
||||
{
|
||||
"name": "g3n",
|
||||
"version": "1.0.0",
|
||||
"version": "1.0.4",
|
||||
"type": "module",
|
||||
"bin": {
|
||||
"g3n": "./bin/g3n.ts"
|
||||
"g3n": "./bin/g3n.ts",
|
||||
"not3": "./bin/not3.ts"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"typescript": "^5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@babel/parser": "^7.28.3",
|
||||
"@babel/traverse": "^7.28.3",
|
||||
"@babel/types": "^7.28.2",
|
||||
"@types/babel__traverse": "^7.28.0",
|
||||
"@types/minimist": "^1.2.5",
|
||||
"dotenv": "^17.2.1",
|
||||
"minimist": "^1.2.8"
|
||||
|
||||
336
x.ts
336
x.ts
@@ -0,0 +1,336 @@
|
||||
#!/usr/bin/env bun
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import * as os from 'os';
|
||||
import { execSync } from 'child_process';
|
||||
|
||||
const CONFIG_FILE = path.join(os.homedir(), '.note.conf');
|
||||
|
||||
interface Config {
|
||||
TOKEN?: string;
|
||||
REPO?: string;
|
||||
URL?: string;
|
||||
}
|
||||
|
||||
// --- Config management ---
|
||||
function createDefaultConfig(): void {
|
||||
const defaultConfig = `TOKEN=
|
||||
REPO=
|
||||
URL=https://cld-dkr-makuro-seafile.wibudev.com/api2
|
||||
`;
|
||||
fs.writeFileSync(CONFIG_FILE, defaultConfig);
|
||||
}
|
||||
|
||||
function editConfig(): void {
|
||||
if (!fs.existsSync(CONFIG_FILE)) {
|
||||
createDefaultConfig();
|
||||
}
|
||||
|
||||
const editor = process.env.EDITOR || 'vim';
|
||||
try {
|
||||
execSync(`${editor} "${CONFIG_FILE}"`, { stdio: 'inherit' });
|
||||
} catch (error) {
|
||||
console.error('❌ Failed to open editor');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
function loadConfig(): Config {
|
||||
if (!fs.existsSync(CONFIG_FILE)) {
|
||||
console.error(`⚠️ Config file not found at ${CONFIG_FILE}`);
|
||||
console.error('Run: bun note.ts config to create/edit it.');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const configContent = fs.readFileSync(CONFIG_FILE, 'utf8');
|
||||
const config: Config = {};
|
||||
|
||||
for (const line of configContent.split('\n')) {
|
||||
const trimmed = line.trim();
|
||||
if (trimmed && !trimmed.startsWith('#')) {
|
||||
const [key, ...valueParts] = trimmed.split('=');
|
||||
if (key && valueParts.length > 0) {
|
||||
let value = valueParts.join('=');
|
||||
// Remove surrounding quotes if present
|
||||
if ((value.startsWith('"') && value.endsWith('"')) ||
|
||||
(value.startsWith("'") && value.endsWith("'"))) {
|
||||
value = value.slice(1, -1);
|
||||
}
|
||||
config[key as keyof Config] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Debug: show loaded config (without showing actual token for security)
|
||||
// console.log(`🔍 Config loaded:`);
|
||||
// console.log(` TOKEN: ${config.TOKEN ? '[SET]' : '[NOT SET]'}`);
|
||||
// console.log(` REPO: ${config.REPO || '[NOT SET]'}`);
|
||||
// console.log(` URL: ${config.URL || '[NOT SET]'}`);
|
||||
|
||||
if (!config.TOKEN || !config.REPO) {
|
||||
console.error(`❌ Config invalid. Please set TOKEN=... and REPO=... inside ${CONFIG_FILE}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (!config.URL) {
|
||||
console.error(`❌ Config invalid. Please set URL=... inside ${CONFIG_FILE}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
// --- HTTP helpers ---
|
||||
async function fetchWithAuth(config: Config, url: string, options: RequestInit = {}): Promise<Response> {
|
||||
const headers = {
|
||||
'Authorization': `Token ${config.TOKEN}`,
|
||||
...options.headers
|
||||
};
|
||||
|
||||
// Debug: log the URL being called
|
||||
// console.log(`🔍 Calling URL: ${url}`);
|
||||
|
||||
try {
|
||||
const response = await fetch(url, { ...options, headers });
|
||||
if (!response.ok) {
|
||||
console.error(`❌ Request failed: ${response.status} ${response.statusText}`);
|
||||
console.error(`🔍 URL: ${url}`);
|
||||
console.error(`🔍 Headers:`, headers);
|
||||
|
||||
// Try to get response body for more details
|
||||
try {
|
||||
const errorText = await response.text();
|
||||
console.error(`🔍 Response body: ${errorText}`);
|
||||
} catch (e) {
|
||||
console.error('🔍 Could not read response body');
|
||||
}
|
||||
|
||||
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
||||
}
|
||||
return response;
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message.includes('HTTP')) {
|
||||
// Already handled above
|
||||
process.exit(1);
|
||||
}
|
||||
console.error('❌ Network request failed:', error);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Commands ---
|
||||
async function testConnection(config: Config): Promise<void> {
|
||||
console.log('🔍 Testing connection...');
|
||||
try {
|
||||
// Test basic API endpoint
|
||||
const response = await fetchWithAuth(config, `${config.URL}/ping/`);
|
||||
const result = await response.text();
|
||||
console.log(`✅ API connection successful: ${result}`);
|
||||
} catch (error) {
|
||||
console.log('⚠️ API ping failed, trying repo access...');
|
||||
try {
|
||||
// Try accessing the repo directly
|
||||
const response = await fetchWithAuth(config, `${config.URL}/${config.REPO}/`);
|
||||
const result = await response.text();
|
||||
console.log(`✅ Repo access successful`);
|
||||
} catch (error) {
|
||||
console.error('❌ Both API ping and repo access failed');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function listFiles(config: Config): Promise<void> {
|
||||
const url = `${config.URL}/${config.REPO}/dir/?p=/`;
|
||||
const response = await fetchWithAuth(config, url);
|
||||
|
||||
try {
|
||||
const files = await response.json();
|
||||
for (const file of files as { name: string }[]) {
|
||||
console.log(file.name);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('❌ Failed to parse response');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
async function catFile(config: Config, fileName: string): Promise<void> {
|
||||
const downloadUrlResponse = await fetchWithAuth(config, `${config.URL}/${config.REPO}/file/?p=/${fileName}`);
|
||||
const downloadUrl = (await downloadUrlResponse.text()).replace(/"/g, '');
|
||||
|
||||
const contentResponse = await fetchWithAuth(config, downloadUrl);
|
||||
const content = await contentResponse.text();
|
||||
console.log(content);
|
||||
}
|
||||
|
||||
async function uploadFile(config: Config, localFile: string, remoteFile?: string): Promise<void> {
|
||||
if (!fs.existsSync(localFile)) {
|
||||
console.error(`❌ File not found: ${localFile}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const remoteName = remoteFile || path.basename(localFile);
|
||||
|
||||
// Get upload URL
|
||||
const uploadUrlResponse = await fetchWithAuth(config, `${config.URL}/${config.REPO}/upload-link/?p=/`);
|
||||
const uploadUrl = (await uploadUrlResponse.text()).replace(/"/g, '');
|
||||
|
||||
// Create FormData
|
||||
const formData = new FormData();
|
||||
const fileContent = fs.readFileSync(localFile);
|
||||
const blob = new Blob([fileContent]);
|
||||
formData.append('file', blob, remoteName);
|
||||
formData.append('filename', remoteName);
|
||||
formData.append('parent_dir', '/');
|
||||
|
||||
try {
|
||||
await fetchWithAuth(config, uploadUrl, {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
});
|
||||
console.log(`✅ Uploaded ${localFile} → ${remoteName}`);
|
||||
} catch (error) {
|
||||
console.error('❌ Upload failed');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
async function removeFile(config: Config, fileName: string): Promise<void> {
|
||||
const url = `${config.URL}/${config.REPO}/file/?p=/${fileName}`;
|
||||
await fetchWithAuth(config, url, { method: 'DELETE' });
|
||||
console.log(`🗑️ Removed ${fileName}`);
|
||||
}
|
||||
|
||||
async function moveFile(config: Config, oldName: string, newName: string): Promise<void> {
|
||||
const url = `${config.URL}/${config.REPO}/file/?p=/${oldName}`;
|
||||
const formData = new FormData();
|
||||
formData.append('operation', 'rename');
|
||||
formData.append('newname', newName);
|
||||
|
||||
try {
|
||||
await fetchWithAuth(config, url, {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
});
|
||||
console.log(`✏️ Renamed ${oldName} → ${newName}`);
|
||||
} catch (error) {
|
||||
console.error('❌ Rename failed');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
async function downloadFile(config: Config, remoteFile: string, localFile?: string): Promise<void> {
|
||||
const localName = localFile || remoteFile;
|
||||
|
||||
// Get download URL
|
||||
const downloadUrlResponse = await fetchWithAuth(config, `${config.URL}/${config.REPO}/file/?p=/${remoteFile}`);
|
||||
const downloadUrl = (await downloadUrlResponse.text()).replace(/"/g, '');
|
||||
|
||||
try {
|
||||
const fileResponse = await fetchWithAuth(config, downloadUrl);
|
||||
const arrayBuffer = await fileResponse.arrayBuffer();
|
||||
const buffer = Buffer.from(arrayBuffer);
|
||||
|
||||
fs.writeFileSync(localName, buffer);
|
||||
console.log(`⬇️ Downloaded ${remoteFile} → ${localName}`);
|
||||
} catch (error) {
|
||||
console.error('❌ Download failed');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
function showHelp(): void {
|
||||
console.log(`note - simple CLI for Seafile notes
|
||||
Usage:
|
||||
bun note.ts ls List files
|
||||
bun note.ts cat <file> Show file content
|
||||
bun note.ts cp <local> [remote] Upload file
|
||||
bun note.ts rm <remote> Remove file
|
||||
bun note.ts mv <old> <new> Rename/move file
|
||||
bun note.ts get <remote> [local] Download file
|
||||
bun note.ts test Test API connection
|
||||
bun note.ts config Edit config (~/.note.conf)
|
||||
|
||||
Config (~/.note.conf):
|
||||
TOKEN=your_seafile_token
|
||||
REPO=repos/<repo-id>
|
||||
URL=your_seafile_url/api2`);
|
||||
}
|
||||
|
||||
// --- Main ---
|
||||
async function not3(): Promise<void> {
|
||||
const args = process.argv.slice(2);
|
||||
const cmd = args[0] || 'help';
|
||||
|
||||
// Handle config command
|
||||
if (cmd === 'config') {
|
||||
editConfig();
|
||||
return;
|
||||
}
|
||||
|
||||
// Load config for other commands
|
||||
const config = loadConfig();
|
||||
|
||||
switch (cmd) {
|
||||
case 'test':
|
||||
await testConnection(config);
|
||||
break;
|
||||
|
||||
case 'ls':
|
||||
await listFiles(config);
|
||||
break;
|
||||
|
||||
case 'cat':
|
||||
if (!args[1]) {
|
||||
console.error('Usage: bun note.ts cat <file>');
|
||||
process.exit(1);
|
||||
}
|
||||
await catFile(config, args[1]);
|
||||
break;
|
||||
|
||||
case 'cp':
|
||||
if (!args[1]) {
|
||||
console.error('Usage: bun note.ts cp <local_file> [remote_file]');
|
||||
process.exit(1);
|
||||
}
|
||||
await uploadFile(config, args[1], args[2]);
|
||||
break;
|
||||
|
||||
case 'rm':
|
||||
if (!args[1]) {
|
||||
console.error('Usage: bun note.ts rm <remote_file>');
|
||||
process.exit(1);
|
||||
}
|
||||
await removeFile(config, args[1]);
|
||||
break;
|
||||
|
||||
case 'mv':
|
||||
if (!args[1] || !args[2]) {
|
||||
console.error('Usage: bun note.ts mv <old_name> <new_name>');
|
||||
process.exit(1);
|
||||
}
|
||||
await moveFile(config, args[1], args[2]);
|
||||
break;
|
||||
|
||||
case 'get':
|
||||
if (!args[1]) {
|
||||
console.error('Usage: bun note.ts get <remote_file> [local_file]');
|
||||
process.exit(1);
|
||||
}
|
||||
await downloadFile(config, args[1], args[2]);
|
||||
break;
|
||||
|
||||
case 'help':
|
||||
default:
|
||||
showHelp();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Run the main function
|
||||
not3().catch((error) => {
|
||||
console.error('❌ Error:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
export default not3;
|
||||
Reference in New Issue
Block a user