CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-vorpal

Node's first framework for building immersive CLI apps.

Pending
Overview
Eval results
Files

storage.mddocs/

History and Storage

Command history and local storage management for persistent data and user experience.

Capabilities

Command History Management

Sets an ID for command history, which enables history persistence across sessions.

/**
 * Sets an ID for command history persistence
 * @param id - Unique identifier for history storage
 * @returns Vorpal instance for chaining
 */
function history(id: string): Vorpal;

Usage Example:

const vorpal = require('vorpal')();

// Enable persistent history with unique ID
vorpal
  .history('my-cli-app')
  .delimiter('myapp$')
  .show();

// Users can now use up/down arrows to navigate command history
// History persists between application restarts

History Storage Path

Sets the storage path for command history files.

/**
 * Sets file path for history storage
 * @param path - File system path for storing history
 * @returns Vorpal instance for chaining
 */
function historyStoragePath(path: string): Vorpal;

Usage Example:

const vorpal = require('vorpal')();
const path = require('path');
const os = require('os');

// Set custom history storage location
const historyPath = path.join(os.homedir(), '.my-app', 'history');

vorpal
  .history('my-app')
  .historyStoragePath(historyPath)
  .delimiter('myapp$')
  .show();

Local Storage

Sets up local storage for the CLI application with a unique identifier.

/**
 * Sets up local storage for CLI application
 * @param id - Unique identifier for local storage
 * @returns Vorpal instance for chaining
 */
function localStorage(id: string): Vorpal;

Usage Example:

const vorpal = require('vorpal')();

// Enable local storage
vorpal
  .localStorage('my-app-storage')
  .command('set <key> <value>', 'Store a key-value pair')
  .action(function(args, callback) {
    // Access local storage through vorpal instance
    this.parent.localStorage.setItem(args.key, args.value);
    this.log(`Stored: ${args.key} = ${args.value}`);
    callback();
  });

vorpal
  .command('get <key>', 'Retrieve a stored value')
  .action(function(args, callback) {
    const value = this.parent.localStorage.getItem(args.key);
    if (value !== undefined) {
      this.log(`${args.key} = ${value}`);
    } else {
      this.log(`Key '${args.key}' not found`);
    }
    callback();
  });

vorpal
  .delimiter('storage$')
  .show();

Local Storage Operations

Store Item

Sets a value in local storage.

/**
 * Sets a key-value pair in local storage
 * @param key - Storage key
 * @param value - Value to store (any serializable type)
 * @returns Stored value
 */
function setItem(key: string, value: any): any;

Retrieve Item

Gets a value from local storage.

/**
 * Gets a value from local storage
 * @param key - Storage key to retrieve
 * @returns Retrieved value or undefined if not found
 */
function getItem(key: string): any;

Remove Item

Removes a key-value pair from local storage.

/**
 * Removes a key-value pair from local storage
 * @param key - Storage key to remove
 * @returns Removed value or undefined if not found
 */
function removeItem(key: string): any;

Complete Storage Example:

const vorpal = require('vorpal')();

vorpal
  .localStorage('settings-app')
  .command('config:set <key> <value>', 'Set configuration value')
  .action(function(args, callback) {
    this.parent.localStorage.setItem(args.key, args.value);
    this.log(`Configuration set: ${args.key} = ${args.value}`);
    callback();
  });

vorpal
  .command('config:get [key]', 'Get configuration value(s)')
  .action(function(args, callback) {
    if (args.key) {
      const value = this.parent.localStorage.getItem(args.key);
      if (value !== undefined) {
        this.log(`${args.key} = ${value}`);
      } else {
        this.log(`Configuration '${args.key}' not found`);
      }
    } else {
      // List all stored configurations
      const storage = this.parent.localStorage;
      this.log('All configurations:');
      // Note: Actual implementation would need to iterate storage
    }
    callback();
  });

vorpal
  .command('config:remove <key>', 'Remove configuration value')
  .action(function(args, callback) {
    const removed = this.parent.localStorage.removeItem(args.key);
    if (removed !== undefined) {
      this.log(`Removed configuration: ${args.key}`);
    } else {
      this.log(`Configuration '${args.key}' not found`);
    }
    callback();
  });

History Operations

History Class Methods

The History class provides methods for programmatic history management.

/**
 * Sets the ID for history storage
 * @param id - History identifier
 */
function setId(id: string): void;

/**
 * Sets custom storage path for history
 * @param path - File system path
 */
function setStoragePath(path: string): void;

/**
 * Gets previous command from history
 * @returns Previous command string
 */
function getPreviousHistory(): string;

/**
 * Gets next command from history  
 * @returns Next command string
 */
function getNextHistory(): string;

/**
 * Peeks at history without changing position
 * @param depth - How far back to look (optional)
 * @returns Command at specified depth
 */
function peek(depth?: number): string;

/**
 * Adds new command to history
 * @param cmd - Command string to add
 */
function newCommand(cmd: string): void;

/**
 * Handles mode entry for history
 */
function enterMode(): void;

/**
 * Handles mode exit for history
 */
function exitMode(): void;

/**
 * Clears command history
 */
function clear(): void;

Advanced History Usage:

const vorpal = require('vorpal')();

vorpal
  .history('advanced-app')
  .command('history:clear', 'Clear command history')
  .action(function(args, callback) {
    this.parent.cmdHistory.clear();
    this.log('Command history cleared');
    callback();
  });

vorpal
  .command('history:show [count]', 'Show recent commands')
  .action(function(args, callback) {
    const count = parseInt(args.count) || 10;
    this.log(`Last ${count} commands:`);
    
    // Note: Actual implementation would access history data
    for (let i = 0; i < count; i++) {
      const cmd = this.parent.cmdHistory.peek(i);
      if (cmd) {
        this.log(`${i + 1}: ${cmd}`);
      }
    }
    callback();
  });

Persistent Configuration Example

const vorpal = require('vorpal')();
const path = require('path');
const os = require('os');

// Setup persistent storage and history
const appDataPath = path.join(os.homedir(), '.my-cli-app');
const historyPath = path.join(appDataPath, 'history');

vorpal
  .history('my-cli-app')
  .historyStoragePath(historyPath)
  .localStorage('my-cli-app-config');

// User preferences command
vorpal
  .command('prefs:set <key> <value>', 'Set user preference')
  .action(function(args, callback) {
    const preferences = this.parent.localStorage.getItem('preferences') || {};
    preferences[args.key] = args.value;
    this.parent.localStorage.setItem('preferences', preferences);
    this.log(`Preference set: ${args.key} = ${args.value}`);
    callback();
  });

vorpal
  .command('prefs:get [key]', 'Get user preference(s)')
  .action(function(args, callback) {
    const preferences = this.parent.localStorage.getItem('preferences') || {};
    
    if (args.key) {
      const value = preferences[args.key];
      if (value !== undefined) {
        this.log(`${args.key} = ${value}`);
      } else {
        this.log(`Preference '${args.key}' not set`);
      }
    } else {
      this.log('All preferences:');
      Object.keys(preferences).forEach(key => {
        this.log(`  ${key} = ${preferences[key]}`);
      });
    }
    callback();
  });

// Session state management
vorpal
  .command('session:save', 'Save current session state')
  .action(function(args, callback) {
    const sessionState = {
      timestamp: new Date().toISOString(),
      delimiter: this.parent.session.delimiter(),
      commands: this.parent.commands.length
    };
    
    this.parent.localStorage.setItem('lastSession', sessionState);
    this.log('Session state saved');
    callback();
  });

vorpal
  .command('session:restore', 'Show last session info')
  .action(function(args, callback) {
    const sessionState = this.parent.localStorage.getItem('lastSession');
    
    if (sessionState) {
      this.log('Last session:');
      this.log('  Time:', sessionState.timestamp);
      this.log('  Delimiter:', sessionState.delimiter);
      this.log('  Commands available:', sessionState.commands);
    } else {
      this.log('No previous session found');
    }
    callback();
  });

// Usage tracking
vorpal
  .command('stats', 'Show usage statistics')
  .action(function(args, callback) {
    const stats = this.parent.localStorage.getItem('stats') || {
      commandsRun: 0,
      sessionsStarted: 0,
      firstUse: new Date().toISOString()
    };
    
    this.log('Usage Statistics:');
    this.log('  Commands run:', stats.commandsRun);
    this.log('  Sessions started:', stats.sessionsStarted);
    this.log('  First use:', stats.firstUse);
    callback();
  });

// Track command usage (hook into all command executions)
const originalExec = vorpal.exec;
vorpal.exec = function(command, args, callback) {
  // Update stats
  const stats = this.localStorage.getItem('stats') || {
    commandsRun: 0,
    sessionsStarted: 0,
    firstUse: new Date().toISOString()
  };
  
  stats.commandsRun++;
  this.localStorage.setItem('stats', stats);
  
  // Call original exec method  
  return originalExec.call(this, command, args, callback);
};

// Initialize session tracking
const stats = vorpal.localStorage.getItem('stats') || {
  commandsRun: 0,
  sessionsStarted: 0,
  firstUse: new Date().toISOString()
};

stats.sessionsStarted++;
vorpal.localStorage.setItem('stats', stats);

vorpal
  .delimiter('myapp$')
  .show();

Storage Best Practices

Data Serialization

Store complex objects properly:

// Storing objects
const complexData = {
  settings: { theme: 'dark', language: 'en' },
  history: ['command1', 'command2'],
  metadata: { version: '1.0.0' }
};

vorpal.localStorage.setItem('appData', JSON.stringify(complexData));

// Retrieving objects
const retrieved = JSON.parse(vorpal.localStorage.getItem('appData') || '{}');

Error Handling

Handle storage errors gracefully:

vorpal
  .command('safe-store <key> <value>', 'Safely store data')
  .action(function(args, callback) {
    try {
      this.parent.localStorage.setItem(args.key, args.value);
      this.log(`Stored: ${args.key}`);
    } catch (error) {
      this.log(`Storage error: ${error.message}`);
    }
    callback();
  });

Migration Support

Handle data format changes:

function migrateStorageData(vorpal) {
  const version = vorpal.localStorage.getItem('dataVersion') || '1.0';
  
  if (version === '1.0') {
    // Migrate from v1.0 to v2.0 format
    const oldData = vorpal.localStorage.getItem('userData');
    if (oldData) {
      const newData = transformDataV1ToV2(oldData);
      vorpal.localStorage.setItem('userData', newData);
      vorpal.localStorage.setItem('dataVersion', '2.0');
    }
  }
}

Install with Tessl CLI

npx tessl i tessl/npm-vorpal

docs

commands.md

configuration.md

events.md

execution.md

extensions.md

index.md

storage.md

ui.md

tile.json