UNPKG

llm-md

Version:

Convert JSON to Markdown optimized for LLM consumption

207 lines (202 loc) 6.79 kB
#!/usr/bin/env node "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const fs = __importStar(require("fs")); const minimist_1 = __importDefault(require("minimist")); const index_1 = require("./index"); const VERSION = require('../package.json').version; const HELP_TEXT = ` llm-md v${VERSION} Convert JSON to Markdown optimized for LLM consumption. Usage: llm-md [input.json] [options] cat data.json | llm-md [options] Options: -o, --output <file> Write output to file (default: stdout) --verbose Include metadata about conversion strategy --strategy <name> Force specific strategy (table, yaml-block, key-value, hybrid, numbered-list) --max-depth <n> Set maximum depth for analysis (default: 10) -h, --help Show this help message -v, --version Show version number Examples: cat test.json | llm-md > test.md llm-md input.json -o output.md llm-md data.json --verbose --strategy table llm-md nested.json --max-depth 15 `; function parseArgs() { return (0, minimist_1.default)(process.argv.slice(2), { string: ['output', 'o', 'strategy'], boolean: ['help', 'h', 'version', 'v', 'verbose'], alias: { h: 'help', v: 'version', o: 'output' } }); } function showHelp() { console.log(HELP_TEXT); process.exit(0); } function showVersion() { console.log(VERSION); process.exit(0); } async function readInput(filePath) { if (filePath) { // Read from file try { return fs.readFileSync(filePath, 'utf-8'); } catch (error) { throw new Error(`Failed to read file '${filePath}': ${error.message}`); } } else { // Read from stdin return new Promise((resolve, reject) => { let data = ''; process.stdin.setEncoding('utf-8'); process.stdin.on('data', (chunk) => { data += chunk; }); process.stdin.on('end', () => { if (!data) { reject(new Error('No input provided. Use --help for usage information.')); } else { resolve(data); } }); process.stdin.on('error', (error) => { reject(new Error(`Failed to read from stdin: ${error.message}`)); }); }); } } function writeOutput(content, filePath) { if (filePath) { // Write to file try { fs.writeFileSync(filePath, content, 'utf-8'); } catch (error) { throw new Error(`Failed to write to file '${filePath}': ${error.message}`); } } else { // Write to stdout process.stdout.write(content); } } function buildOptions(args) { const options = {}; if (args.verbose) { options.verbose = true; } if (args.strategy) { const validStrategies = ['table', 'yaml-block', 'key-value', 'hybrid', 'numbered-list']; if (!validStrategies.includes(args.strategy)) { throw new Error(`Invalid strategy '${args.strategy}'. Must be one of: ${validStrategies.join(', ')}`); } options.forceStrategy = args.strategy; } if (args['max-depth'] !== undefined) { const maxDepth = Number(args['max-depth']); if (isNaN(maxDepth) || maxDepth < 1 || !Number.isInteger(maxDepth)) { throw new Error(`Invalid max-depth '${args['max-depth']}'. Must be a positive integer.`); } options.maxDepth = maxDepth; } return options; } async function main() { try { const args = parseArgs(); // Handle help and version flags if (args.help) { showHelp(); return; } if (args.version) { showVersion(); return; } // Get input file path (first positional argument) const inputFile = args._[0]; // Read input const input = await readInput(inputFile); // Parse JSON let data; try { data = JSON.parse(input); } catch (error) { throw new Error(`Invalid JSON: ${error.message}`); } // Build conversion options const options = buildOptions(args); // Convert let output; if (args.verbose) { const result = (0, index_1.convertVerbose)(data, options); output = result.markdown; if (result.metadata) { output += `\n\n---\n\n**Conversion Metadata:**\n- Strategy: ${result.metadata.strategy}\n- Confidence: ${result.metadata.confidence.toFixed(2)}\n- Depth: ${result.metadata.depth}\n- Tokens: ${result.metadata.tokensEstimate}\n`; } } else { output = (0, index_1.convert)(data, options); } // Get output file path const outputFile = args.output; // Write output writeOutput(output, outputFile); // Exit successfully process.exit(0); } catch (error) { console.error(`Error: ${error.message}`); process.exit(1); } } // Run CLI main();