| name | developer-tools |
| description | CLI tools, SDKs, and developer experience patterns |
| domain | domain-applications |
| version | 1.0.0 |
| tags | ["cli","sdk","api-client","devtools","dx"] |
| triggers | {"keywords":{"primary":["cli","sdk","developer tool","api client","dx","developer experience"],"secondary":["commander","chalk","api documentation","developer portal","openapi"]},"context_boost":["tool","library","package","npm","developer"],"context_penalty":["frontend","ui","design","mobile"],"priority":"medium"} |
Developer Tools
Overview
Building command-line interfaces, SDKs, and tools that enhance developer experience.
CLI Development
CLI Framework (Commander)
#!/usr/bin/env node
import { Command } from 'commander';
import chalk from 'chalk';
import ora from 'ora';
import inquirer from 'inquirer';
const program = new Command();
program
.name('myctl')
.description('CLI tool for managing resources')
.version('1.0.0');
program
.command('init')
.description('Initialize a new project')
.option('-t, --template <name>', 'Template to use', 'default')
.option('-d, --directory <path>', 'Target directory', '.')
.action(async (options) => {
const spinner = ora('Initializing project...').start();
try {
await initProject(options.template, options.directory);
spinner.succeed(chalk.green('Project initialized successfully!'));
} catch (error) {
spinner.fail(chalk.red(`Failed: ${error.message}`));
process.exit(1);
}
});
program
.command('create <name>')
.description('Create a new resource')
.action(async (name) => {
const answers = await inquirer.prompt([
{
type: 'list',
name: 'type',
message: 'Select resource type:',
choices: ['api', 'worker', 'database'],
},
{
type: 'input',
name: 'description',
message: 'Description:',
},
{
type: 'confirm',
name: 'public',
message: 'Make it public?',
default: false,
},
]);
await createResource(name, answers);
console.log(chalk.green(`Created ${answers.type}: ${name}`));
});
const configCmd = program.command('config').description('Manage configuration');
configCmd
.command('set <key> <value>')
.description('Set a config value')
.action(async (key, value) => {
await setConfig(key, value);
console.log(`Set ${key}=${value}`);
});
configCmd
.command('get <key>')
.description('Get a config value')
.action(async (key) => {
const value = await getConfig(key);
console.log(value);
});
configCmd
.command('list')
.description('List all config values')
.action(async () => {
const config = await getAllConfig();
console.table(config);
});
program
.option('--debug', 'Enable debug mode')
.option('--json', 'Output as JSON')
.hook('preAction', (thisCommand) => {
if (thisCommand.opts().debug) {
process.env.DEBUG = 'true';
}
});
program.parse();
CLI Output Formatting
import Table from 'cli-table3';
import boxen from 'boxen';
function printTable(data: Array<Record<string, any>>, columns: string[]) {
const table = new Table({
head: columns.map((c) => chalk.bold(c)),
style: { head: ['cyan'] },
});
data.forEach((row) => {
table.push(columns.map((col) => row[col] ?? ''));
});
console.log(table.toString());
}
function printJson(data: any) {
console.log(JSON.stringify(data, null, 2));
}
function () {
.(
(message, {
: ,
: ,
: ,
title,
: ,
})
);
}
cliProgress ;
withProgress<T>(
: T[],
: <>,
:
) {
bar = cliProgress.({
: ,
: ,
: ,
});
bar.(items., );
( item items) {
(item);
bar.();
}
bar.();
}
SDK Development
TypeScript SDK
export class MyServiceClient {
private baseUrl: string;
private apiKey: string;
constructor(options: { apiKey: string; baseUrl?: string }) {
this.apiKey = options.apiKey;
this.baseUrl = options.baseUrl || 'https://api.example.com';
}
private async request<T>(
method: string,
path: string,
data?: any
): Promise<T> {
const response = await fetch(`${this.baseUrl}${path}`, {
method,
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${this.apiKey}`,
},
body: data ? JSON.stringify(data) : undefined,
});
if (!response.ok) {
const error = response.().( ({}));
(response., error. || );
}
response.();
}
users = {
:
.<<>>(, + (params)),
: .<>(, ),
:
.<>(, , data),
:
.<>(, , data),
: .<>(, ),
};
projects = {
: .<[]>(, ),
: .<>(, ),
:
.<>(, , data),
};
}
{
() {
(message);
. = ;
}
}
{
: ;
: ;
: ;
: ;
}
{
: ;
: ;
}
{
?: ;
}
<T> {
: T[];
: {
: ;
: ;
: ;
};
}
client = ({ : });
users = client..({ : , : });
user = client..({ : , : });
SDK with Retry and Rate Limiting
import pRetry from 'p-retry';
import pThrottle from 'p-throttle';
class RobustClient {
private throttle = pThrottle({
limit: 100,
interval: 60000,
});
private async requestWithRetry<T>(
fn: () => Promise<T>,
options?: { retries?: number }
): Promise<T> {
return pRetry(
async () => {
try {
return await fn();
} catch (error) {
if (error instanceof ApiError) {
if (error.status >= 400 && error.status < 500) {
throw new pRetry.AbortError(error);
}
}
throw error;
}
},
{
retries: options?.retries ?? 3,
onFailedAttempt: () => {
.(
);
},
}
);
}
request = .( <T>(
: ,
: ,
?:
): <T> => {
.( () => {
response = (, {
method,
: .(),
: data ? .(data) : ,
});
(response. === ) {
retryAfter = response..();
delay = retryAfter ? (retryAfter) * : ;
(delay);
();
}
(!response.) {
(response., response.());
}
response.();
});
});
}
API Documentation
OpenAPI Spec Generation
import { generateOpenApi } from '@ts-rest/open-api';
import { contract } from './contract';
const openApiDocument = generateOpenApi(contract, {
info: {
title: 'My API',
version: '1.0.0',
description: 'API for managing resources',
},
servers: [
{ url: 'https://api.example.com', description: 'Production' },
{ url: 'https://staging-api.example.com', description: 'Staging' },
],
});
export { openApiDocument };
Interactive Documentation
import SwaggerUI from 'swagger-ui-react';
import 'swagger-ui-react/swagger-ui.css';
function ApiDocs() {
return (
<SwaggerUI
url="/api/openapi.json"
docExpansion="list"
defaultModelsExpandDepth={3}
/>
);
}
import { RedocStandalone } from 'redoc';
function ApiDocs() {
return <RedocStandalone specUrl="/api/openapi.json" />;
}
Developer Portal
function ApiKeyManager() {
const [keys, setKeys] = useState<ApiKey[]>([]);
async function createKey(name: string) {
const key = await api.createApiKey({ name });
showModal({
title: 'API Key Created',
content: (
<div>
<p>Save this key - it won't be shown again:</p>
<code className="bg-gray-100 p-2 block">{key.secret}</code>
</div>
),
});
setKeys([...keys, key]);
}
async function revokeKey(keyId: string) {
await api.revokeApiKey(keyId);
setKeys(keys.filter((k) => k.id !== keyId));
}
return (
<div>
<>API Keys
Name
Created
Last Used
Actions
{keys.map((key) => (
{key.name}
{formatDate(key.createdAt)}
{key.lastUsedAt ? formatDate(key.lastUsedAt) : 'Never'}
revokeKey(key.id)}>Revoke
))}
createKey(prompt('Key name:') || 'Unnamed')}>
Create New Key
);
}
Related Skills
- [[api-design]] - API design patterns
- [[documentation]] - Technical writing
- [[automation-scripts]] - Build automation