### Install Example Hooks via Claude Code Plugin Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/PUBLISHING.md Commands to interact with the Claude Code Plugin Marketplace, including adding the marketplace, listing available plugins, and installing example hooks from the specified SDK. This is how end-users access ready-to-use hooks. ```bash # Add the marketplace /plugin marketplace add hgeldenhuys/claude-hooks-sdk # List available plugins /plugin list # Install example hooks /plugin install claude-hooks-sdk-examples ``` -------------------------------- ### Install claude-hooks-sdk Skill and Examples Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/README.md Provides bash commands to install the `claude-hooks-sdk` skill from the marketplace and its associated examples. This enables interactive guidance within Claude Code and provides working examples for reference. ```bash /plugin marketplace add hgeldenhuys/claude-hooks-sdk /plugin install claude-hooks-sdk-examples /skill claude-hooks-sdk ``` -------------------------------- ### Quick Start for Custom Backend Integration with Bun Server Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/README.md Provides instructions to set up and run a custom backend integration example using a mini Bun server and a real-time HTML dashboard. It includes steps for starting the server and configuring the hook in `.claude/settings.json`. ```bash # Start the server cd examples/custom-backend bun server.ts # Configure hook in .claude/settings.json { "hooks": { "SessionStart": [ { "type": "command", "command": "bun /path/to/examples/custom-backend/hook.ts" } ] } } # View dashboard at http://localhost:3030 ``` -------------------------------- ### Test Plugin Installation in Claude Code Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/PUBLISHING.md Steps to test the plugin installation process within Claude Code. This involves adding the marketplace, verifying the plugin listing, installing the examples, and checking for the presence of hooks. ```bash # In Claude Code, test marketplace /plugin marketplace add hgeldenhuys/claude-hooks-sdk # Verify plugin shows up /plugin list # Test installation /plugin install claude-hooks-sdk-examples # Check hook is available ls -la .claude/hooks/ ``` -------------------------------- ### Development Commands for Claude Hooks SDK using Bun Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/README.md This bash script outlines the essential development commands for the Claude Hooks SDK project using Bun as the package manager. It covers installing dependencies, building the project, performing type checks, and running example scripts. ```bash # Install dependencies bun install # Build bun run build # Type check bun run typecheck # Run examples bun examples/basic-hook.ts ``` -------------------------------- ### Run Transaction Logger Viewer Commands Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/examples/transaction-logger/README.md These are bash commands to run the transaction logger viewer utility. You can view all transactions, the latest ones, filter by session, enable watch mode for live updates, or display statistics. These commands assume you have 'bun' installed and the viewer script is accessible. ```bash # View all transactions bun examples/transaction-logger/viewer.ts # View latest 10 bun examples/transaction-logger/viewer.ts --latest 10 # Filter by session bun examples/transaction-logger/viewer.ts --session brave-elephant # Watch mode (live updates) bun examples/transaction-logger/viewer.ts --watch # Show statistics bun examples/transaction-logger/viewer.ts --stats ``` -------------------------------- ### General Hook Development - TypeScript Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/README.md Example of developing a general hook using 'claude-hooks-sdk'. It showcases blocking dangerous commands and logging session start events. Requires 'claude-hooks-sdk' and 'bun'. ```typescript #!/usr/bin/env bun import { HookManager, success, block } from 'claude-hooks-sdk'; const manager = new HookManager({ logEvents: true, // Enable automatic event logging clientId: 'my-hook', // Organize logs by client }); // Block dangerous bash commands manager.onPreToolUse(async (input) => { if (input.tool_name === 'Bash' && input.tool_input.command.includes('rm -rf /')) { return block('Dangerous command detected!'); } return success(); }); // Log session starts (with auto-generated session name) manager.onSessionStart(async (input) => { console.log(`Session started: ${input.session_name} (${input.session_id})`); // Example output: "Session started: brave-elephant (af13b3cd-5185-...)" return success(); }); manager.run(); ``` -------------------------------- ### Running Tests with Bun Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/CLAUDE.md Provides command-line examples for running tests using the Bun test runner. It covers how to execute all tests in the project or target specific test files for focused testing. ```bash bun test # Run all tests bun test tests/session-namer.test.ts # Run specific test ``` -------------------------------- ### Install Dependencies with Bun Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/CONTRIBUTING.md Installs project dependencies using the Bun package manager. This command should be run after cloning the repository. ```bash bun install ``` -------------------------------- ### API Integration Example (TypeScript) Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/docs/QUICK-REFERENCE.md Demonstrates a common pattern for integrating with external APIs within a hook's callback. This example uses `manager.onUserPromptSubmit` to send event and context data to an external API endpoint using the `fetch` function. It shows how to construct the request payload and handle the API interaction. ```typescript manager.onUserPromptSubmit(async (input) => { await fetch('https://api.example.com/track', { method: 'POST', body: JSON.stringify({ event: input.hook_event_name, context: input.context, }), }); return success(); }); ``` -------------------------------- ### Log to Separate Files using File System Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/examples/transforms/README.md Example of how to log different transform outputs to separate files, specifically demonstrating logging conversation turns to a JSONL file using Node.js's file system module. ```typescript import { appendFileSync } from 'fs'; import { join } from 'path'; // Assuming manager, conversationLogger, etc. are already initialized as in other examples // ... manager setup ... manager.onStop(async (input, context) => { const turn = await conversationLogger.recordStop(input, context); // Log to conversation.jsonl appendFileSync( join(process.cwd(), '.agent/conversation.jsonl'), JSON.stringify(turn) + '\n' ); return success(); }); // ... manager.run() ... ``` -------------------------------- ### Example Event Log Entry Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/sample-extension/INTEGRATION-GUIDE.md An example of a single log entry in JSON format, illustrating the structure and fields captured for each hook event. ```json { "timestamp": "2025-11-21T08:00:00.000Z", "event": "PreToolUse", "sessionId": "abc-123-def-456", "toolName": "Read", "cwd": "/path/to/your/project", "exitCode": 0, "success": true } ``` -------------------------------- ### Filter Transaction Logs with JQ (Bash) Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/examples/transaction-logger/README.md These examples show how to use the 'jq' command-line tool to filter and query transaction logs stored in a JSONL file. They cover finding transactions with file changes, identifying slow transactions, extracting unique tools, and counting transactions per session. No external dependencies beyond 'jq' are required. ```bash # Find transactions with file changes jq 'select(.summary.total_files_changed > 0)' .claude/logs/transactions.jsonl # Find slow transactions (>5s) jq 'select(.duration_ms > 5000)' .claude/logs/transactions.jsonl # Get all unique tools used jq -r '.summary.unique_tools[]' .claude/logs/transactions.jsonl | sort -u # Count transactions per session jq -r '.session_name // .session_id' .claude/logs/transactions.jsonl | sort | uniq -c ``` -------------------------------- ### Type-Safe Example Usage of claude-hooks-sdk Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/docs/releases/v0.4.1-SUMMARY.md A comprehensive example demonstrating the type-safe usage of `claude-hooks-sdk`. It shows how to initialize `HookManager`, handle the `onStop` event with proper type checking for `editedFiles`, `transactionId`, and `git.branch`, and includes returning a success status. ```typescript import { HookManager, success } from 'claude-hooks-sdk'; const manager = new HookManager({ trackEdits: true, logEvents: true, }); manager.onStop(async (input) => { // āœ… Full autocomplete and type checking if (input.context?.editedFiles && input.context.editedFiles.length > 0) { console.log(`Edited ${input.context.editedFiles.length} files:`); for (const file of input.context.editedFiles) { console.log(` - ${file}`); // ^? (parameter) file: string } } // āœ… All context fields are typed const txId = input.context?.transactionId; // ^? (property) transactionId?: string | undefined const gitBranch = input.context?.git?.branch; // ^? (property) branch?: string | undefined return success(); }); manager.run(); ``` -------------------------------- ### Test npm Package Locally Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/PUBLISHING.md Instructions for testing an npm package locally by creating a tarball, installing it in a test project, and verifying imports. This ensures the SDK functions correctly before wider distribution. ```bash # Create tarball npm pack # Install locally in test project cd /tmp/test-project npm install /path/to/claude-hooks-sdk-0.4.1.tgz # Test import cat > test.ts << 'EOF' import { HookManager, success } from 'claude-hooks-sdk'; console.log('Import works!'); EOF bun test.ts ``` -------------------------------- ### Login and Verify npm Access Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/PUBLISHING.md Commands to log in to your npm account and verify successful authentication. This is a prerequisite for publishing packages to npm. ```bash # Login to npm (first time only) npm login # Verify you're logged in npm whoami ``` -------------------------------- ### Build and Test npm Package Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/PUBLISHING.md Steps to build the project, perform type checking, and conduct a dry run test of the npm package before publishing. Ensures the package is ready for distribution. ```bash # 1. Ensure everything is built bun run build bun run typecheck # 2. Test the package npm pack --dry-run ``` -------------------------------- ### Creating a Custom Plugin in TypeScript Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/README.md Shows the structure for creating a custom plugin by implementing the `HookPlugin` interface. It includes example implementations for `onBeforeExecute` and `onAfterExecute` lifecycle methods, demonstrating how to hook into the execution process and access input, result, and context. ```typescript import { HookPlugin } from 'claude-hooks-sdk'; const myPlugin: HookPlugin = { name: 'my-plugin', async onBeforeExecute(input, context) { // Called before handlers execute console.log(`Event: ${input.hook_event_name}`); }, async onAfterExecute(input, result, context) { // Called after handlers execute if (result.exitCode !== 0) { console.error('Handler failed'); } } }; manager.use(myPlugin); ``` -------------------------------- ### Publish to npm Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/PUBLISHING.md The command to publish the built package to the npm registry. After successful publishing, a verification step is recommended. ```bash # 3. Publish to npm npm publish # 4. Verify npm view claude-hooks-sdk ``` -------------------------------- ### Sample Log Entry Structure (v0.4.1) Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/sample-extension/README.md This JSON object represents a typical log entry from the event logger, detailing the input event (hook details, conversation, context, timestamp) and the output of the hook execution (exit code, success status). It includes examples of git context and edited files. ```json { "input": { "hook": { "hook_event_name": "Stop", "session_id": "abc-123", "transcript_path": "/path/transcript.jsonl", "cwd": "/project" }, "conversation": {...}, "context": { "transactionId": "tx_1732195847123_abc123", "conversationId": "abc-123", "git": { "repo": "https://github.com/org/repo.git", "branch": "main", "commit": "abc123", "repoInstanceId": "repo_1732195847123_xyz789" }, "editedFiles": [ "/project/src/index.ts", "/project/README.md" ] }, "timestamp": "2025-11-21T19:58:02.789Z" }, "output": { "exitCode": 0, "success": true } } ``` -------------------------------- ### Analytics Example: Tracking Claude Prompts Across Checkouts (TypeScript) Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/docs/guides/REPO-INSTANCE-ID.md A comprehensive example showing how to initialize the HookManager and implement an analytics tracking function for prompt submissions. It sends detailed event data, including repoInstanceId, to an analytics endpoint. ```typescript import { HookManager, success } from 'claude-hooks-sdk'; const manager = new HookManager({ logEvents: true, clientId: 'analytics', }); manager.onUserPromptSubmit(async (input) => { const context = input.context; await fetch('https://analytics.example.com/track', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ event: 'claude_prompt', properties: { // Identify which checkout repoInstanceId: context?.git?.repoInstanceId, // Repo details repository: context?.git?.repo, branch: context?.git?.branch, // Developer details developer: context?.git?.user, email: context?.git?.email, // Correlation transactionId: context?.transactionId, sessionId: context?.conversationId, }, }), }); return success(); }); manager.run(); ``` -------------------------------- ### Test package locally before publishing Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/docs/reference/PUBLICATION-CHECKLIST.md Pack the npm package locally and install it into a test project to verify its functionality. This step helps catch any issues before they are published to the npm registry. ```bash # Pack the package npm pack # Install in test project cd /path/to/test-project npm install /path/to/claude-hooks-sdk-0.4.0.tgz # Test it works ``` -------------------------------- ### Renaming and Looking Up Sessions (Bash) Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/README.md Provides command-line examples for managing Claude Code sessions using the SDK's utility scripts. This includes finding a session ID by its name and renaming sessions by either their current name or their ID. ```bash # Find session ID by name bun .claude/scripts/session-lookup.ts brave-elephant # Output: af13b3cd-5185-42df-aa85-3bf6e52e1810 # Resume using that ID claude --resume $(bun .claude/scripts/session-lookup.ts brave-elephant) # Rename by current name bun .claude/scripts/session-rename.ts brave-elephant "refactor-sse" # Rename by session ID bun .claude/scripts/session-rename.ts af13b3cd "bugfix-viewer" ``` -------------------------------- ### Upgrade to the latest version of claude-hooks-sdk Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/docs/reference/PUBLICATION-CHECKLIST.md Install the latest version of the claude-hooks-sdk using npm. This command fetches the most recent stable release from the npm registry. ```bash # From v0.3.0 npm install claude-hooks-sdk@latest ``` -------------------------------- ### Verify Claude Hook Configuration and Logs Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/examples/transaction-logger/README.md Commands to check if the transaction-logger hook is configured in settings.json and to verify the existence of the transactions log file. ```bash cat .claude/settings.json | grep transaction-logger ``` ```bash ls -la .claude/logs/transactions.jsonl ``` -------------------------------- ### Connect and Push Code to GitHub Repository Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/.github-repo-info.md Commands to add a remote origin for the GitHub repository and push the local 'main' branch to it. This is essential for version control and collaboration. ```bash git remote add origin https://github.com/hgeldenhuys/claude-hooks-sdk.git git branch -M main git push -u origin main --tags ``` -------------------------------- ### Test Basic Hook with Bun Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/CONTRIBUTING.md Executes a basic hook example using Bun, simulating a hook event by piping JSON data to the script. This is used for manual testing. ```bash echo '{"hook_event_name":"SessionStart",...}' | bun examples/basic-hook.ts ``` -------------------------------- ### Extensible Plugin System for HookManager in TypeScript Source: https://context7.com/hgeldenhuys/claude-hooks-sdk/llms.txt Demonstrates how to create reusable plugins that extend the `HookManager` functionality using `onBeforeExecute` and `onAfterExecute` hooks. Examples include an analytics tracker and an event logger. ```typescript import { HookManager, success, HookPlugin } from 'claude-hooks-sdk'; // Create a custom plugin const analyticsPlugin: HookPlugin = { name: 'analytics-tracker', async onBeforeExecute(input, context) { console.log(`[Analytics] Event: ${input.hook_event_name}`); console.log(`[Analytics] Session: ${input.session_id}`); }, async onAfterExecute(input, result, context, conversation) { // Send to analytics backend await fetch('https://analytics.example.com/events', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ event: input.hook_event_name, sessionId: input.session_id, toolName: 'tool_name' in input ? input.tool_name : undefined, success: result.exitCode === 0, timestamp: new Date().toISOString() }) }); } }; // Logging plugin const loggingPlugin: HookPlugin = { name: 'event-logger', async onAfterExecute(input, result, context, conversation) { const logEntry = { event: input.hook_event_name, session: input.session_id, result: result.exitCode, conversation: conversation?.message?.content?.slice(0, 100) }; console.log(JSON.stringify(logEntry)); } }; const manager = new HookManager(); // Register plugins manager .use(analyticsPlugin) .use(loggingPlugin); manager.onPreToolUse((input) => success()); manager.run(); ``` -------------------------------- ### Automatic Session Naming on Session Start (TypeScript) Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/README.md Demonstrates how to use the HookManager to automatically assign user-friendly names to Claude Code sessions upon startup. The session name is automatically populated and can be logged. ```typescript import { HookManager, getSessionName, getSessionId } from 'claude-hooks-sdk'; const manager = new HookManager(); manager.onSessionStart(async (input) => { // session_name is auto-populated by the SDK console.log(`Session: ${input.session_name}`); // Output: "Session: brave-elephant" return { exitCode: 0 }; }); ``` -------------------------------- ### Initialize and Configure HookManager in TypeScript Source: https://context7.com/hgeldenhuys/claude-hooks-sdk/llms.txt Demonstrates how to initialize the HookManager with various configuration options for logging, error handling, and context tracking. This setup is crucial for managing Claude Code hook extensions. ```typescript #!/usr/bin/env bun import { HookManager, success, block, error } from 'claude-hooks-sdk'; const manager = new HookManager({ logEvents: true, // Enable automatic JSONL logging clientId: 'my-extension', trackEdits: true, // Track files modified by Claude enableFailureQueue: true, // Queue failed events for retry maxRetries: 3, // Max retry attempts blockOnFailure: false, // Don't block Claude on hook failures (default) enableContextTracking: true, // Add transaction IDs, git metadata (default) handlerTimeout: 30000, // Handler timeout in ms }); // Block dangerous bash commands manager.onPreToolUse(async (input) => { if (input.tool_name === 'Bash') { if (/rm\s+-rf\s+\//.test(input.tool_input.command)) { return block('Dangerous command: rm -rf / detected!'); } if (input.tool_input.command.includes('sudo')) { return { exitCode: 0, output: { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'ask', permissionDecisionReason: 'Requires elevated privileges' } } }; } } return success(); }); // Log file modifications manager.onPostToolUse(async (input) => { if (['Write', 'Edit', 'MultiEdit'].includes(input.tool_name)) { console.error(`File modified: ${input.tool_input.file_path}`); } return success(); }); // Track session lifecycle manager.onSessionStart(async (input) => { console.error(`Session: ${input.session_name} (${input.session_id})`); console.error(`Source: ${input.source}`); // 'startup' | 'resume' | 'clear' | 'compact' return success(); }); // Get edited files on stop manager.onStop(async (input) => { const editedFiles = (input as any).context?.editedFiles || []; if (editedFiles.length > 0) { console.error(`Files edited this turn: ${editedFiles.join(', ')}`); } return success(); }); manager.run(); // Logs saved to: .claude/hooks/my-extension/logs/events.jsonl ``` -------------------------------- ### HookManager Initialization with Failure Queue Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/README.md Demonstrates how to initialize the HookManager with the failure queue enabled and configure its options. ```APIDOC ## POST /initialize HookManager with Failure Queue ### Description Initialize the HookManager with the `enableFailureQueue` option set to `true` to activate the failure queue. Configure `clientId` for organization and `maxRetries` for automatic retries. Optionally, provide an `onErrorQueueNotEmpty` callback to be notified when the queue contains items. ### Method Initialization (Constructor) ### Endpoint N/A (Class Constructor) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body **HookManagerOptions** (`object`) - **enableFailureQueue** (`boolean`) - Required - Enable the failure queue for sequential event processing with retries. - **clientId** (`string`) - Required - A unique identifier for organizing logs and queues. - **maxRetries** (`number`) - Optional - The maximum number of retry attempts for failed events. Defaults to 3. - **onErrorQueueNotEmpty** (`function`) - Optional - A callback function executed when the failure queue is not empty. Receives `queueSize` and `failedEvents`. ### Request Example ```typescript const manager = new HookManager({ enableFailureQueue: true, clientId: 'my-extension', maxRetries: 3, onErrorQueueNotEmpty: async (queueSize, failedEvents) => { console.log(`āš ļø ${queueSize} events in error queue`); } }); ``` ### Response #### Success Response (200) N/A (Constructor does not return a response) #### Response Example N/A ``` -------------------------------- ### View Event Logs using Bash and jq Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/README.md Demonstrates how to view and filter event logs using command-line tools like `tail`, `cat`, and `jq`. These commands allow real-time monitoring and selective extraction of log data based on various criteria. ```bash # From project root (uses CLAUDE_PROJECT_DIR) tail -f .claude/hooks/my-extension/logs/events.jsonl | jq . # All events cat .claude/hooks/my-extension/logs/events.jsonl | jq . # Filter by event type cat .claude/hooks/my-extension/logs/events.jsonl | jq 'select(.input.hook.hook_event_name == "PreToolUse")' # View just context tail -f .claude/hooks/my-extension/logs/events.jsonl | jq '.input.context' # View event summary cat .claude/hooks/my-extension/logs/events.jsonl | jq -c '{event: .input.hook.hook_event_name, tool: .input.hook.tool_name, tx: .input.context.transactionId}' ``` -------------------------------- ### Initialize HookManager with Edit Tracking - TypeScript Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/docs/guides/EDIT-TRACKING.md Provides an example of how to initialize the `HookManager` with `trackEdits` enabled. This setup also includes enabling logging and context tracking. ```typescript const manager = new HookManager({ trackEdits: true, // Track edits logEvents: true, // Log to file enableContextTracking: true, // Enable correlation context clientId: 'my-app' }); ``` -------------------------------- ### Configure and View Transactions with TypeScript/Bun Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/README.md This snippet demonstrates how to configure the transaction logger in `.claude/settings.json` and view recorded transactions using the provided TypeScript viewer script with Bun. It covers basic viewing and watching for live updates. ```typescript // Configure in .claude/settings.json (UserPromptSubmit, PostToolUse, Stop hooks) // Then view transactions: bun examples/transaction-logger/viewer.ts --latest 10 bun examples/transaction-logger/viewer.ts --watch ``` -------------------------------- ### Filter Event Logs by Event Type with JQ Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/sample-extension/INTEGRATION-GUIDE.md Example using `jq` to filter log entries based on a specific event type, such as 'PreToolUse'. This is useful for targeted analysis. ```bash cat logs/events.jsonl | jq 'select(.event == "PreToolUse")' ``` -------------------------------- ### Execute event-logger-v2.ts with Bun Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/sample-extension/README.md This snippet demonstrates how to make the event-logger-v2.ts script executable and then run it using Bun, piping sample JSON input to it. This is a quick way to test the logger's functionality. ```bash chmod +x packages/claude-hooks-sdk/sample-extension/event-logger-v2.ts echo '{"hook_event_name":"SessionStart","session_id":"test","transcript_path":"/tmp/test.jsonl","cwd":"/tmp","source":"startup"}' | \ bun packages/claude-hooks-sdk/sample-extension/event-logger-v2.ts ``` -------------------------------- ### Log Real-time Events with tail and jq Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/sample-extension/README.md This bash command shows how to monitor log files in real-time using `tail -f` and format the JSON output with `jq '.'`. This is useful for observing the immediate effects of running Claude Code hooks. ```bash tail -f .claude/hooks/event-logger/logs/events.jsonl | jq '.' ``` -------------------------------- ### Schedule Cron Job to Drain Failure Queue Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/sample-extension/FAILURE-QUEUE-TEST.md Provides an example of a cron job entry to periodically drain the failure queue. This ensures that failed events are automatically processed or retried at regular intervals without manual intervention. ```bash */5 * * * * bun /path/to/drain-queue.ts my-production-hook ``` -------------------------------- ### Configure Hook Manager with Failure Queue and Notification Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/sample-extension/FAILURE-QUEUE-TEST.md Shows how to enable the failure queue and configure an `onErrorQueueNotEmpty` callback within the `HookManager` in TypeScript. This is intended for production setup, demonstrating how to handle queue events and trigger external monitoring alerts. ```typescript const manager = new HookManager({ enableFailureQueue: true, clientId: 'my-production-hook', maxRetries: 3, onErrorQueueNotEmpty: async (size, events) => { // Send alert to monitoring system await fetch('https://monitoring.com/alert', { method: 'POST', body: JSON.stringify({ queueSize: size, events }) }); } }); ``` -------------------------------- ### Creating a Hook with HookManager in TypeScript Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/CLAUDE.md Demonstrates how to initialize and configure the HookManager, including setting up lifecycle hooks like onPreToolUse to intercept and modify tool usage. It shows how to use helper functions like `block` and `success` to control the execution flow. ```typescript import { HookManager, success, block } from 'claude-hooks-sdk'; const manager = new HookManager({ logEvents: true, clientId: 'my-hook', trackEdits: true, enableFailureQueue: true, maxRetries: 3, }); manager.onPreToolUse(async (input) => { if (input.tool_name === 'Bash' && input.tool_input.command.includes('rm -rf /')) { return block('Dangerous command detected!'); } return success(); }); manager.run(); ``` -------------------------------- ### Create GitHub release Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/docs/reference/PUBLICATION-CHECKLIST.md Tag the current commit with the new version number and push the tag to origin. Then, create a GitHub release using the tag, a descriptive title, and the content from CHANGELOG.md. ```bash git tag v0.4.0 git push origin v0.4.0 ``` -------------------------------- ### Analyze Event Logs with jq and Shell Commands Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/sample-extension/README.md This collection of bash commands demonstrates various ways to analyze log files generated by the event logger. It includes filtering by event type, session ID, extracting edited files, and identifying unique repository instances. ```bash # Count events by type jq -r '.input.hook.hook_event_name' .claude/hooks/event-logger/logs/events.jsonl | \ sort | uniq -c | sort -rn # Filter by session jq 'select(.input.hook.session_id == "your-session-id")' \ .claude/hooks/event-logger/logs/events.jsonl # Show edited files from recent sessions jq -r 'select(.input.context.editedFiles) | .input.context.editedFiles[]' \ .claude/hooks/event-logger/logs/events.jsonl # Show repo instances jq -r '.input.context.git.repoInstanceId' \ .claude/hooks/event-logger/logs/events.jsonl | sort -u ``` -------------------------------- ### Complete Example: Auto-Commit Edits with Git - TypeScript & Bash Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/docs/guides/EDIT-TRACKING.md A full example demonstrating how to use the `HookManager` to automatically stage and commit files edited by Claude using Git commands. Includes TypeScript code for the hook and JSON for configuration. ```typescript #!/usr/bin/env bun import { HookManager, success } from 'claude-hooks-sdk'; import { execSync } from 'child_process'; const manager = new HookManager({ trackEdits: true, logEvents: true, clientId: 'git-auto-commit' }); manager.onStop(async (input) => { const context = (input as any).context; if (context?.editedFiles && context.editedFiles.length > 0) { console.log(`\nšŸ”§ Claude edited ${context.editedFiles.length} files:`); context.editedFiles.forEach(file => console.log(` ${file}`)); // Stage edited files const files = context.editedFiles.join(' '); execSync(`git add ${files}`); // Create commit with transaction ID const message = `Claude edits (tx: ${context.transactionId})`; execSync(`git commit -m "${message}"`); console.log(`\nāœ… Changes committed!`); } return success(); }); manager.run(); ``` ```json { "hooks": { "Stop": [{ "matcher": "*", "hooks": [{ "type": "command", "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/git-auto-commit.ts" }] }] } } ``` -------------------------------- ### Type Safety for editedFiles in TypeScript Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/docs/releases/v0.4.1-SUMMARY.md Demonstrates how to safely access `editedFiles` using TypeScript interfaces in the `claude-hooks-sdk`. The 'before' example shows unsafe type assertions, while the 'after' example utilizes the SDK's new types for full type safety and autocompletion. ```typescript // Before - No type safety āŒ manager.onStop(async (input) => { const files = (input as any).context?.editedFiles; // Unsafe! }); ``` ```typescript // After - Full type safety āœ… manager.onStop(async (input) => { const files = input.context?.editedFiles; // Fully typed! // ^? (property) editedFiles?: string[] | undefined }); ``` -------------------------------- ### Filter Specific Tools for Tracking (TypeScript) Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/examples/transaction-logger/README.md This TypeScript code snippet modifies the `recordToolUse()` function within `transformer.ts` to selectively track tools. The example filters out tools that are not 'Write', 'Edit', or 'MultiEdit', ensuring that only file operation tools are recorded. This allows for focused analysis on specific types of actions. ```typescript // Only track file operations if (!['Write', 'Edit', 'MultiEdit'].includes(toolName)) { return; // Skip } ``` -------------------------------- ### Build and typecheck project Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/docs/reference/PUBLICATION-CHECKLIST.md Execute the build and TypeScript type checking commands using Bun. These commands ensure the project is compiled correctly and all types are valid before packaging. ```bash bun run build bun run typecheck ``` -------------------------------- ### Send Event to Analytics (TypeScript) Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/sample-extension/README.md This example demonstrates how to send an event to an analytics service when a Claude session stops. It uses the `fetch` API to make a POST request to a specified analytics endpoint, including relevant session data from the input context. This functionality is useful for tracking user interactions and application events. ```typescript manager.onStop(async (input) => { await fetch('https://analytics.example.com/track', { method: 'POST', body: JSON.stringify({ event: 'claude_session_end', repoInstanceId: input.context?.git?.repoInstanceId, editedFiles: input.context?.editedFiles, transactionId: input.context?.transactionId, }), }); return success(); }); ``` -------------------------------- ### Bash: Copy Settings for Claude Code Integration Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/sample-extension/TEST-RESULTS.md Copies the sample extension's settings.json file to the user's .claude/settings.json directory to integrate the extension with Claude Code. ```bash # Copy settings to your project cp sample-extension/settings.json .claude/settings.json ``` -------------------------------- ### Unpublish from npm Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/PUBLISHING.md Command to remove a package version from the npm registry. This action is typically available only within a 72-hour window after publishing. ```bash npm unpublish claude-hooks-sdk@0.4.1 ``` -------------------------------- ### Configure Transaction Logger Hook Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/examples/transaction-logger/README.md This JSON configuration snippet shows how to set up the transaction logger hook in Claude Code. It specifies the command to run the hook script for different events: UserPromptSubmit, PostToolUse, and Stop. Ensure the path to the hook script is correct. ```json { "hooks": { "UserPromptSubmit": [ { "type": "command", "command": "bun \"$CLAUDE_PROJECT_DIR\"/examples/transaction-logger/hook.ts" } ], "PostToolUse": [ { "type": "command", "command": "bun \"$CLAUDE_PROJECT_DIR\"/examples/transaction-logger/hook.ts" } ], "Stop": [ { "type": "command", "command": "bun \"$CLAUDE_PROJECT_DIR\"/examples/transaction-logger/hook.ts" } ] } } ``` -------------------------------- ### Manually Test Claude Hook Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/examples/transaction-logger/README.md A command to manually test the hook by sending a sample JSON payload to the hook script. ```bash echo '{"hook_event_name":"UserPromptSubmit","transaction_id":"test-123","session_id":"test","timestamp":"2025-11-23T10:00:00Z"}' | bun hook.ts ``` -------------------------------- ### Register General Hooks - JSON Source: https://github.com/hgeldenhuys/claude-hooks-sdk/blob/main/README.md Configuration in '.claude/settings.json' to register 'PreToolUse' and 'SessionStart' hooks. It points to the hook script and specifies matchers for different event types. ```json { "hooks": { "PreToolUse": [ { "matcher": "Bash", "hooks": [ { "type": "command", "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/my-hook.ts" } ] } ], "SessionStart": [ { "hooks": [ { "type": "command", "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/my-hook.ts" } ] } ] } } ```