npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

prompt-template-engine

v2.0.2

Published

Modern Nunjucks-based prompt template engine with security-first design

Readme

Prompt Template Engine

A modern, security-first template engine built on Nunjucks with advanced function preprocessing. Create dynamic prompts using powerful template syntax, file inclusion, command execution, and data extraction capabilities.

TypeScript Node.js License: ISC Version

Features

🚀 Modern Architecture (v2.0.0)

  • Nunjucks-Based Engine - Powerful template processing with full Nunjucks syntax support
  • Async Function Pipeline - Advanced preprocessing for {{ file() }}, {{ exec() }}, {{ env() }} functions
  • Double Extension Convention - template.ext.njk → template.ext automatic output path generation
  • Engine Modes - Lightweight, Development, Production, and Watch modes for different use cases
  • Template Compilation Caching - 10x performance improvement through compiled template caching

🔧 Template Functions & Syntax

  • {{ file('path') }} - Include file contents with automatic path resolution
  • {{ exec('command') }} - Execute commands safely with timeout protection
  • {{ env('VAR') }} - Access environment variables with validation
  • Nunjucks Features - Full support for variables, filters, loops, conditionals, and macros
  • Custom Filters - Built-in from_json and from_yaml filters for data transformation
  • Context Variables - Access template metadata via __template and __engine variables

🛡️ Security & Reliability

  • SecurityManager - Comprehensive security validation for files and commands
  • Path Traversal Protection - Prevents access outside template directory
  • Command Sandboxing - Whitelist/blacklist command execution with timeout protection
  • File Size Limits - Configurable limits to prevent resource exhaustion
  • Template Validation - Comprehensive validation including syntax, security, and best practices
  • Circular Dependency Detection - Automatic detection and prevention of infinite recursion

⚡ Performance & Developer Experience

  • Multi-Engine Architecture - Choose optimal engine mode for your use case
  • File Watching - Auto-regenerate templates on file changes with dependency tracking
  • Template Caching - Intelligent caching with modification time tracking
  • Verbose Logging - Detailed debugging information with configurable log levels
  • Configuration Profiles - Environment-specific configurations (dev, prod, ci) with profile management
  • Configuration Management - YAML/JSON configuration with context loading
  • Error Context - Enhanced error reporting with template line numbers and context

Quick Start

# Create a simple Nunjucks template (note the .njk extension)
echo "Hello {{ file('name.txt') }}!" > greeting.md.njk
echo "World" > name.txt

# Render template
npx prompt-template-engine render greeting.md.njk
# Output: Hello World! (saved to greeting.md)

# Preview without creating file
npx prompt-template-engine preview greeting.md.njk
# Output: Hello World! (printed to stdout)

Installation

NPM Package (Recommended)

# Install globally
npm install -g prompt-template-engine

# Or use with npx (no installation required)
npx prompt-template-engine generate template.md

From Git Repository

# Install directly from git repository
npm install -g git+https://github.com/username/prompt-template-engine.git

# For SSH access (if you have SSH keys set up)
npm install -g git+ssh://[email protected]/username/prompt-template-engine.git

# For private repositories with token
npm install -g git+https://[email protected]/username/prompt-template-engine.git

Local Development

# Clone the repository
git clone <repository-url>
cd prompt-template-engine

# Install dependencies
npm install

# Build the project
npm run build

# Link globally for command-line usage
npm link

Verify Installation

prompt --version
prompt --help

Usage

Basic Commands

# Render template to file (using double extension convention)
prompt-engine render template.md.njk

# Render template with explicit output path
prompt-engine render template.md.njk -o custom-output.txt

# Preview template content (no file creation)
prompt-engine preview template.md.njk

# Validate template syntax and security
prompt-engine validate template.md.njk

# Watch template for changes with auto-regeneration
prompt-engine watch template.md.njk -o output.txt

Command Options

| Option | Description | Example | |--------|-------------|---------| | -o, --output <file> | Explicit output file path | prompt-engine render template.md.njk -o result.txt | | -v, --verbose | Enable verbose logging | prompt-engine render template.md.njk --verbose | | -c, --config <path> | Path to configuration file | prompt-engine render template.md.njk --config config.yaml | | -p, --profile <name> | Configuration profile to use | prompt-engine render template.md.njk --profile production |

Global Options

All commands support these global options:

  • --verbose - Enable detailed logging for debugging
  • --config <path> - Use custom configuration file
  • --profile <name> - Use specific configuration profile
  • --version - Show version information
  • --help - Show command help

Development Mode

# Run in development mode (from source)
npm run dev -- render template.md.njk
npm run dev -- validate template.md.njk
npm run dev -- watch template.md.njk --verbose

Configuration Management

The Prompt Template Engine features a powerful configuration profile system that allows you to manage environment-specific settings and easily switch between different configurations for development, production, CI/CD, and custom scenarios.

Configuration Profiles

Configuration profiles provide environment-specific settings that control security policies, performance parameters, logging levels, and handler configurations. Each profile is a self-contained configuration optimized for specific use cases.

Built-in Profile Templates

The engine provides four built-in profile templates:

| Profile | Description | Use Case | |---------|-------------|----------| | development | Permissive settings, debug logging, commands enabled | Local development and testing | | production | Security-focused, restricted handlers, minimal logging | Production deployment | | ci | CI/CD optimized, specific command allowlist, JSON logging | Automated pipelines | | default | Balanced configuration for general use | General purpose template processing |

Profile Management Commands

Create and Initialize Profiles

# Create a new profile from template
prompt-engine config init mydev --template development
prompt-engine config init prod --template production
prompt-engine config init ci --template ci

# List all available templates
prompt-engine config templates

List and Switch Profiles

# List all profiles
prompt-engine config list

# List profiles with detailed information
prompt-engine config list --show-details

# Switch to a different profile
prompt-engine config switch mydev
prompt-engine config switch production

# Show current active profile configuration
prompt-engine config show

# Show specific profile configuration  
prompt-engine config show production

Validate Profiles

# Validate active profile
prompt-engine config validate

# Validate specific profile
prompt-engine config validate production

# Example output:
# ✓ Profile 'production' is valid
# Warnings:
#   • Commands are disabled - exec() functions will not work

Edit Profile Properties

The engine provides multiple ways to edit configuration properties:

Single Property Updates:

# Set boolean values
prompt-engine config set security.allowCommands false
prompt-engine config set verbose true

# Set string values (JSON format)
prompt-engine config set logging.level '"debug"'
prompt-engine config set logging.format '"json"'

# Set numeric values
prompt-engine config set security.maxFileSize 5242880
prompt-engine config set security.timeoutMs 60000

# Set nested handler properties
prompt-engine config set handlers.exec.enabled true
prompt-engine config set handlers.file.maxSize 10485760

# Target specific profile
prompt-engine config set security.allowCommands false --profile production

Read Property Values:

# Get current property values
prompt-engine config get security.allowCommands
prompt-engine config get logging.level  
prompt-engine config get handlers.exec.enabled

# Get from specific profile
prompt-engine config get security.maxFileSize --profile production

# With verbose output showing source profile
prompt-engine config get security.allowCommands --verbose

Interactive Editor:

# Edit active profile in your default editor
prompt-engine config edit

# Edit specific profile
prompt-engine config edit production

# Uses $EDITOR environment variable (vim, nano, code, etc.)
# Automatic validation after save

Delete Profiles:

# Delete a profile (cannot delete active profile without --force)
prompt-engine config delete old-profile

# Force delete active profile (switches to default)
prompt-engine config delete current-profile --force

Using Profiles

Command Line Profile Selection

# Use specific profile for a single command
prompt-engine --profile production render template.njk
prompt-engine --profile development preview template.njk

# Environment variable (useful in CI/CD)
PROMPT_ENGINE_PROFILE=production prompt-engine render template.njk

Profile Resolution Order

Profiles are resolved using the following precedence (highest to lowest):

  1. CLI Flag: --profile <name>
  2. Environment Variable: PROMPT_ENGINE_PROFILE=<name>
  3. Active Profile: ~/.prompt-engine/active-profile.txt
  4. Configuration File: --config <path> (legacy fallback)
  5. Default Configuration: Built-in defaults

Configuration Properties

Security Settings

security.allowCommands             # Enable/disable command execution
security.allowedPathPatterns       # Array of allowed file path patterns
security.deniedPathPatterns        # Array of blocked file path patterns  
security.maxFileSize               # Maximum file size in bytes
security.maxTemplateSize           # Maximum template size in bytes
security.timeoutMs                 # Command timeout in milliseconds

Performance Settings

performance.renderTimeout          # Template render timeout (ms)
performance.maxConcurrentRenders   # Maximum concurrent template renders
performance.memoryLimit            # Memory limit (e.g., "512MB")

Logging Settings

logging.level                      # "debug", "info", "warn", "error"
logging.format                     # "text", "json"
logging.destination               # File path for log output

Handler Settings

handlers.file.enabled              # Enable file handler
handlers.file.maxSize             # Maximum file size for includes
handlers.http.enabled             # Enable HTTP handler  
handlers.http.timeout             # HTTP request timeout
handlers.exec.enabled             # Enable command execution
handlers.exec.allowedCommands     # Array of allowed commands
handlers.env.enabled              # Enable environment variable access

Profile Examples

Development Profile Configuration

{
  "verbose": true,
  "security": {
    "allowCommands": true,
    "allowedPathPatterns": ["**/*"],
    "maxFileSize": 5242880,
    "timeoutMs": 60000
  },
  "performance": {
    "renderTimeout": 60000,
    "maxConcurrentRenders": 20
  },
  "logging": {
    "level": "debug",
    "format": "text"
  },
  "handlers": {
    "file": { "enabled": true, "maxSize": 5242880 },
    "http": { "enabled": true, "timeout": 30000 },
    "exec": { "enabled": true },
    "env": { "enabled": true }
  }
}

Production Profile Configuration

{
  "verbose": false,
  "security": {
    "allowCommands": false,
    "allowedPathPatterns": ["./templates/**", "./content/**"],
    "deniedPathPatterns": ["/**/.git/**", "/**/.env*", "/etc/**"],
    "maxFileSize": 1048576,
    "timeoutMs": 15000
  },
  "performance": {
    "renderTimeout": 30000,
    "maxConcurrentRenders": 5
  },
  "logging": {
    "level": "warn",
    "format": "json"
  },
  "handlers": {
    "file": { "enabled": true, "maxSize": 1048576 },
    "http": { "enabled": false },
    "exec": { "enabled": false },
    "env": { "enabled": false }
  }
}

Configuration File Locations

Profiles are stored in a structured directory format:

~/.prompt-engine/
├── config/
│   ├── profiles/          # Profile configurations
│   │   ├── default.json
│   │   ├── development.json
│   │   ├── production.json
│   │   └── custom.json
│   └── metadata.json      # Profile metadata
├── active-profile.txt     # Currently active profile
└── cache/                 # Template cache directory

Environment-Specific Usage

Docker Deployment

# Set profile via environment variable
ENV PROMPT_ENGINE_PROFILE=production

# Or copy custom profile
COPY production-config.json /app/.prompt-engine/config/profiles/production.json

CI/CD Integration

# GitHub Actions example
- name: Generate documentation
  run: |
    PROMPT_ENGINE_PROFILE=ci prompt-engine render docs.njk
  env:
    PROMPT_ENGINE_PROFILE: ci

Team Collaboration

# Export profile for sharing
prompt-engine config show production > team-production.json

# Team members can recreate the profile
prompt-engine config init production --template production
prompt-engine config edit production  # Then paste shared config

Migration from Legacy Configuration

If you have existing configuration files, you can migrate them to the profile system:

# Create new profile from existing config
prompt-engine config init migrated --template default
prompt-engine config edit migrated  # Copy your existing settings

# Or continue using legacy config alongside profiles
prompt-engine --config legacy-config.yaml render template.njk

Template Syntax

The engine uses Nunjucks template syntax with custom function preprocessing. All templates must have .njk extension and follow the double extension convention for output files.

Function Syntax

The engine provides three main functions that are preprocessed before Nunjucks rendering:

File Inclusion

Include content from any file with automatic path resolution:

{{ file('relative/path/to/file.txt') }}

Advanced usage with filters:

{# Set variable with file content #}
{% set config = file('config.yaml') | from_yaml %}
{% set package = file('package.json') | from_json %}

{# Use the loaded data #}
Project: {{ config.project.name }}
Version: {{ package.version }}

Example:

# System Prompt
{{ file('prompts/system.txt') }}

# Project Configuration  
{% set config = file('config.yaml') | from_yaml %}
Environment: {{ config.environment }}

Command Execution

Execute commands safely with security validation and timeout protection:

{{ exec('command here') }}

Examples:

Current files:
{{ exec('ls -la') }}

Git status:
{{ exec('git status --short') }}

System info:
{{ exec('uname -a') }}

{# Using with conditionals #}
{% if exec('which docker') %}
Docker version: {{ exec('docker --version') }}
{% endif %}

Security Features:

  • 30-second timeout protection
  • Command validation through SecurityManager
  • Working directory restricted to template directory
  • Configurable whitelist/blacklist command filtering

Environment Variables

Access environment variables with validation:

{{ env('VARIABLE_NAME') }}

Examples:

Environment: {{ env('NODE_ENV') }}
User: {{ env('USER') }}
Path: {{ env('PATH') }}

{# With fallbacks and conditionals #}
{% set nodeEnv = env('NODE_ENV') or 'development' %}
Running in {{ nodeEnv }} mode

{% if env('CI') %}
Running in CI environment
{% endif %}

Security Features:

  • Variable name format validation (uppercase letters, digits, underscores)
  • Returns empty string for undefined variables (no template errors)
  • No access to dangerous environment variables

Nunjucks Template Features

The engine provides full Nunjucks functionality including:

Variables and Filters

{# Built-in context variables #}
Template: {{ __template.path }}
Engine: {{ __engine.version }}
Timestamp: {{ __engine.timestamp }}

{# Custom filters #}
{% set config = file('config.yaml') | from_yaml %}
{% set data = file('data.json') | from_json %}

Loops and Conditionals

{# Conditionals #}
{% if env('NODE_ENV') == 'production' %}
Production configuration active
{% else %}
Development configuration active
{% endif %}

{# Loops with file data #}
{% set packages = file('package.json') | from_json %}
Dependencies:
{% for dep, version in packages.dependencies %}
- {{ dep }}: {{ version }}
{% endfor %}

{# Complex conditionals with command output #}
{% if 'main' in exec('git branch') %}
On main branch
{% endif %}

Macros and Includes

{# Define reusable macros #}
{% macro renderSection(title, content) %}
## {{ title }}
{{ content }}
{% endmacro %}

{# Use macros #}
{{ renderSection('Configuration', file('config.yaml')) }}

{# Include other templates #}
{% include 'shared/header.njk' %}

Comments and Whitespace Control

{# This is a comment - won't appear in output #}

{# Whitespace control #}
{%- if condition -%}
  Content without extra whitespace
{%- endif -%}

Real-World Examples

AI Assistant Configuration Template

Template file: ai-assistant.md.njk

# AI Assistant Configuration

## System Instructions
{{ file('system/base-prompt.txt') }}

## Project Context
{% set pkg = file('package.json') | from_json %}
Project: {{ pkg.name }} v{{ pkg.version }}

Current TypeScript/JavaScript files:
{{ exec('find . -name "*.ts" -o -name "*.js" | head -10') }}

## Configuration
{% set config = file('config.yaml') | from_yaml %}
Assistant Mode: {{ config.assistant.mode }}
Max Tokens: {{ config.assistant.maxTokens }}

## Environment Information
- Node: {{ exec('node --version') }}
- NPM: {{ exec('npm --version') }}
- OS: {{ exec('uname -s') }}
- Generated: {{ __engine.timestamp }}

Dynamic Multi-File Template

Main template (project-summary.md.njk):

# {{ pkg.name | title }} Project Summary

{% set pkg = file('package.json') | from_json %}
{% set readme = file('README.md') %}

## Overview
**Version:** {{ pkg.version }}
**Description:** {{ pkg.description }}

## Recent Changes
{{ exec('git log --oneline -5') }}

## Project Structure
{{ exec('find src -type f -name "*.ts" | head -20') }}

## Dependencies
{% for dep, version in pkg.dependencies %}
- {{ dep }}: {{ version }}
{% endfor %}

{% if env('NODE_ENV') == 'development' %}
## Development Notes
This is a development build with debugging enabled.
{% endif %}

Configuration-Driven Template

Configuration file (config.yaml):

template:
  title: "Dynamic AI Assistant"
  sections:
    - system
    - context
    - examples
environment:
  type: "development"
  debug: true
features:
  ai_assistant: true
  code_analysis: true

Template (dynamic-prompt.md.njk):

{% set config = file('config.yaml') | from_yaml %}

# {{ config.template.title }}

{% for section in config.template.sections %}
{% if section == 'system' %}
## System Instructions
{{ file('prompts/system.txt') }}

{% elif section == 'context' %}
## Context
Environment: {{ config.environment.type }}
Debug Mode: {{ config.environment.debug }}
Features: {{ config.features.keys() | join(', ') }}

{% elif section == 'examples' %}
## Examples
{{ file('examples/basic-usage.md') }}
{% endif %}
{% endfor %}

---
Generated: {{ __engine.timestamp }}
Template: {{ __template.path }}

Error Handling

The engine provides detailed error messages for common issues:

# Missing template file
Error: Generation failed: Template file not found: missing.md

# Missing include file  
Error: Generation failed: Failed to process txt source: Failed to read file "missing.txt": ENOENT: no such file or directory

# Invalid YAML/JSON selector
Error: Generation failed: Failed to process yaml source: Selector "invalid.path" not found in YAML file

# Command execution failure
Error: Generation failed: Failed to process cmd source: Command execution failed: Command 'invalid-command' not found

# Circular dependencies
Error: Generation failed: Circular dependency detected: /path/to/template.md

Validation

Use the validate command to check templates without generating output:

prompt validate my-template.md
# ✓ Template is valid

prompt validate broken-template.md  
# ✗ Template validation failed:
#   - Failed to include file "missing.txt": ENOENT: no such file or directory

Project Structure

src/
├── index.ts             # Public API exports and main engine interface
├── cli/
│   └── cli.ts          # Command-line interface with Commander.js
├── core/               # Core engine components
│   ├── engine.ts       # NunjucksEngine - main template processor
│   ├── functions.ts    # PromptEngineFunctions for file/exec/env
│   ├── preprocessor.ts # CustomSyntaxPreprocessor for async functions
│   ├── function-executor.ts # AsyncFunctionExecutor pipeline
│   ├── template-parser.ts   # TemplateParser for function extraction
│   ├── security.ts     # SecurityManager with validation policies
│   ├── validator.ts    # TemplateValidator for comprehensive validation
│   ├── cache.ts        # TemplateCache with mtime-based invalidation
│   └── watcher.ts      # TemplateWatcher for file change monitoring
├── utils/              # Utilities and configuration
│   ├── types.ts        # TypeScript interfaces and engine modes
│   ├── logger.ts       # Winston-based logging with levels
│   ├── config-loader.ts # Configuration file loading with profile support
│   ├── config-profile-manager.ts # Configuration profile management system
│   └── context-loader.ts # Template context loading
└── errors.ts           # Custom error classes with context

tests/                  # Comprehensive test suite (95%+ coverage)
├── setup.ts           # Test environment setup and globals
├── mocks/             # Mock implementations for testing
├── unit/              # Unit tests for individual components
├── integration/       # Integration tests for full workflows
└── __mocks__/         # Jest module mocks

docs/                  # Architecture documentation
├── adr/               # Architecture Decision Records
├── idr/               # Implementation Decision Records
├── examples/          # Example templates and configurations
├── getting-started/   # Getting started guides
└── philosophy/        # Design philosophy and principles

API Usage

The engine can be used programmatically with full TypeScript support:

import { 
  NunjucksEngine, 
  ENGINE_MODES,
  EngineConfig,
  ConfigProfileManager 
} from 'prompt-template-engine';

// Basic usage with lightweight mode
const engine = new NunjucksEngine('./templates');
const content = await engine.render('template.md.njk');
console.log(content);

// Advanced usage with custom configuration
const config: EngineConfig = {
  verbose: true,
  development: true,
  renderTimeout: 60000,
  security: {
    allowCommands: true,
    maxFileSize: 10 * 1024 * 1024
  }
};

const engine = new NunjucksEngine('./templates', config, ENGINE_MODES.PRODUCTION);

// Render with custom context
const result = await engine.render('dynamic.njk', './output.md', {
  customVar: 'value',
  config: { debug: true }
});

// Validate template before rendering
const validation = await engine.validate('template.njk');
if (validation.valid) {
  const content = await engine.render('template.njk');
} else {
  console.error('Template validation failed:', validation);
}

// Preview without file creation
const preview = await engine.preview('template.njk', { env: 'test' });
console.log(preview);

// Configuration profile management
const profileManager = new ConfigProfileManager();

// Create profiles programmatically
await profileManager.initProfile('api-prod', 'production');
await profileManager.setProperty('api-prod', 'security.allowCommands', false);
await profileManager.setProperty('api-prod', 'logging.level', 'error');

// Load and use profile configuration
const prodConfig = await profileManager.loadProfileConfig('api-prod');
const prodEngine = new NunjucksEngine('./templates', prodConfig, ENGINE_MODES.PRODUCTION);

// Switch profiles
await profileManager.switchProfile('api-prod');

Configuration Options

interface EngineConfig {
  verbose?: boolean;           // Enable debug logging
  development?: boolean;       // Enable development features
  renderTimeout?: number;      // Template render timeout (ms)
  cache?: CacheConfig;         // Cache configuration
  security?: SecurityConfig;   // Security policies
  handlers?: Record<string, HandlerConfig>; // Handler settings
}

// Engine modes for different use cases
const modes = {
  LIGHTWEIGHT: { /* minimal features */ },
  DEVELOPMENT: { /* full debugging */ },
  PRODUCTION:  { /* optimized for speed */ },
  WATCH:       { /* all features enabled */ }
};

Advanced Features

Engine Modes

The NunjucksEngine supports different modes optimized for specific use cases:

Lightweight Mode - Minimal overhead for simple operations:

const engine = new NunjucksEngine('./templates', {}, ENGINE_MODES.LIGHTWEIGHT);
// Features: Basic rendering, no caching, minimal security, no async functions

Development Mode - Full debugging and validation:

const engine = new NunjucksEngine('./templates', {}, ENGINE_MODES.DEVELOPMENT);
// Features: All validation, performance monitoring, no caching, full async pipeline

Production Mode - Optimized for performance:

const engine = new NunjucksEngine('./templates', {}, ENGINE_MODES.PRODUCTION);
// Features: Template caching, security validation, async functions, minimal logging

Watch Mode - All features for development workflows:

const engine = new NunjucksEngine('./templates', {}, ENGINE_MODES.WATCH);
// Features: Everything enabled - caching, validation, monitoring, async functions

Template Watching

Monitor templates and dependencies for automatic regeneration:

# Watch template with auto-regeneration
prompt-engine watch template.md.njk -o output.md

# Watch with verbose logging
prompt-engine watch template.md.njk --verbose

Watch Features:

  • Dependency tracking for included files
  • Intelligent debouncing to prevent excessive regeneration
  • Real-time validation feedback
  • Automatic cache invalidation on changes

Template Validation

Comprehensive template validation without rendering:

# Validate template syntax and security
prompt-engine validate template.md.njk

# Example output for valid template:
# ✓ Template validation passed

# Example output for invalid template:
# ✗ Template validation failed:
#   Syntax Errors:
#     • Unexpected token in template at line 15
#   Security Issues:
#     • [HIGH] Dangerous command 'rm' detected in exec() function
#     • [MEDIUM] Large file inclusion may impact performance

Security Features

Built-in security protections for safe template processing:

Command Security:

  • Blocks dangerous commands (rm, sudo, chmod, etc.)
  • Prevents command injection patterns
  • Configurable allowed/blocked command lists
  • Command timeout enforcement (max 1 minute)

File Security:

  • Path traversal protection (no ../../../etc/passwd)
  • File size limits (default 10MB)
  • Extension filtering (blocks .exe, .sh, .bat, etc.)
  • Access restricted to template directory

Configuration:

// Programmatic security configuration
const security = new SecurityManager({
  allowCommandExecution: true,
  allowedCommands: ['ls', 'echo', 'date'],
  maxFileSize: 5 * 1024 * 1024, // 5MB
  allowPathTraversal: false
});

Security Considerations

  • Enhanced Security: Built-in protection against dangerous commands and path traversal
  • Sandboxed Execution: Commands run with restricted permissions and timeouts
  • Configurable Policies: Customize security settings per project requirements
  • File Access Control: Strict file access limited to template directory
  • Validation: Always validate templates before using them in production

Package Installation Details

The package is designed to work with npx and npm install -g from git repositories through these mechanisms:

  • prepare script: Automatically builds TypeScript files when installed from git
  • bin field: Links the prompt command to dist/cli.js
  • files field: Includes both source and compiled files in the package
  • Executable permissions: The CLI script has proper shebang and permissions

What happens during installation:

  1. npm downloads the repository
  2. npm runs npm run prepare (which runs npm run build)
  3. TypeScript compiles to dist/ directory
  4. The prompt command becomes available globally

Troubleshooting

Common Issues

Template not found:

Error: Template file not found: template.md
  • Ensure the template file exists and the path is correct
  • Check file permissions

Include file not found:

Error: Failed to process txt source: Failed to read file "missing.txt"
  • Verify all included files exist relative to the template location
  • Use prompt validate template.md to check all dependencies

Command execution blocked:

Error: Command 'rm' is blocked for security reasons
  • The command is blocked by security policies
  • Use --verbose to see which commands are allowed/blocked

Permission denied:

Error: EACCES: permission denied
  • Check file and directory permissions
  • Ensure the template directory is readable

Profile configuration issues:

Error: Profile 'production' not found
  • Use prompt-engine config list to see available profiles
  • Create the profile with prompt-engine config init production --template production
  • Check for typos in profile names

Configuration validation errors:

Error: Profile configuration is invalid: maxFileSize cannot exceed 10MB
  • Use prompt-engine config validate <profile> to check configuration
  • Fix invalid settings with prompt-engine config set or prompt-engine config edit
  • Check the documentation for valid configuration values

Performance Tips

  • Use caching for repeated template generation: prompt cache --stats
  • For large files, consider breaking them into smaller includes
  • Use --no-cache for debugging to ensure fresh data
  • Watch mode is optimized for development workflows

Contributing

We welcome contributions! Please follow these steps:

  1. Fork the repository and create a feature branch
  2. Add tests for any new functionality
  3. Ensure all tests pass: npm test
  4. Check TypeScript compilation: npm run build
  5. Follow the existing code style and conventions
  6. Update documentation if needed
  7. Submit a pull request with a clear description

Development Setup

git clone <your-fork>
cd prompt-template-engine
npm install
npm run build
npm test

Running Tests

npm test              # Run all tests
npm run test:unit     # Run unit tests only
npm run test:watch    # Run tests in watch mode

License

ISC License - see LICENSE file for details.