[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"similar-tonl-dev--tonl":3,"tool-tonl-dev--tonl":64},[4,17,27,35,43,56],{"id":5,"name":6,"github_repo":7,"description_zh":8,"stars":9,"difficulty_score":10,"last_commit_at":11,"category_tags":12,"status":16},3808,"stable-diffusion-webui","AUTOMATIC1111\u002Fstable-diffusion-webui","stable-diffusion-webui 是一个基于 Gradio 构建的网页版操作界面，旨在让用户能够轻松地在本地运行和使用强大的 Stable Diffusion 图像生成模型。它解决了原始模型依赖命令行、操作门槛高且功能分散的痛点，将复杂的 AI 绘图流程整合进一个直观易用的图形化平台。\n\n无论是希望快速上手的普通创作者、需要精细控制画面细节的设计师，还是想要深入探索模型潜力的开发者与研究人员，都能从中获益。其核心亮点在于极高的功能丰富度：不仅支持文生图、图生图、局部重绘（Inpainting）和外绘（Outpainting）等基础模式，还独创了注意力机制调整、提示词矩阵、负向提示词以及“高清修复”等高级功能。此外，它内置了 GFPGAN 和 CodeFormer 等人脸修复工具，支持多种神经网络放大算法，并允许用户通过插件系统无限扩展能力。即使是显存有限的设备，stable-diffusion-webui 也提供了相应的优化选项，让高质量的 AI 艺术创作变得触手可及。",162132,3,"2026-04-05T11:01:52",[13,14,15],"开发框架","图像","Agent","ready",{"id":18,"name":19,"github_repo":20,"description_zh":21,"stars":22,"difficulty_score":23,"last_commit_at":24,"category_tags":25,"status":16},1381,"everything-claude-code","affaan-m\u002Feverything-claude-code","everything-claude-code 是一套专为 AI 编程助手（如 Claude Code、Codex、Cursor 等）打造的高性能优化系统。它不仅仅是一组配置文件，而是一个经过长期实战打磨的完整框架，旨在解决 AI 代理在实际开发中面临的效率低下、记忆丢失、安全隐患及缺乏持续学习能力等核心痛点。\n\n通过引入技能模块化、直觉增强、记忆持久化机制以及内置的安全扫描功能，everything-claude-code 能显著提升 AI 在复杂任务中的表现，帮助开发者构建更稳定、更智能的生产级 AI 代理。其独特的“研究优先”开发理念和针对 Token 消耗的优化策略，使得模型响应更快、成本更低，同时有效防御潜在的攻击向量。\n\n这套工具特别适合软件开发者、AI 研究人员以及希望深度定制 AI 工作流的技术团队使用。无论您是在构建大型代码库，还是需要 AI 协助进行安全审计与自动化测试，everything-claude-code 都能提供强大的底层支持。作为一个曾荣获 Anthropic 黑客大奖的开源项目，它融合了多语言支持与丰富的实战钩子（hooks），让 AI 真正成长为懂上",140436,2,"2026-04-05T23:32:43",[13,15,26],"语言模型",{"id":28,"name":29,"github_repo":30,"description_zh":31,"stars":32,"difficulty_score":23,"last_commit_at":33,"category_tags":34,"status":16},2271,"ComfyUI","Comfy-Org\u002FComfyUI","ComfyUI 是一款功能强大且高度模块化的视觉 AI 引擎，专为设计和执行复杂的 Stable Diffusion 图像生成流程而打造。它摒弃了传统的代码编写模式，采用直观的节点式流程图界面，让用户通过连接不同的功能模块即可构建个性化的生成管线。\n\n这一设计巧妙解决了高级 AI 绘图工作流配置复杂、灵活性不足的痛点。用户无需具备编程背景，也能自由组合模型、调整参数并实时预览效果，轻松实现从基础文生图到多步骤高清修复等各类复杂任务。ComfyUI 拥有极佳的兼容性，不仅支持 Windows、macOS 和 Linux 全平台，还广泛适配 NVIDIA、AMD、Intel 及苹果 Silicon 等多种硬件架构，并率先支持 SDXL、Flux、SD3 等前沿模型。\n\n无论是希望深入探索算法潜力的研究人员和开发者，还是追求极致创作自由度的设计师与资深 AI 绘画爱好者，ComfyUI 都能提供强大的支持。其独特的模块化架构允许社区不断扩展新功能，使其成为当前最灵活、生态最丰富的开源扩散模型工具之一，帮助用户将创意高效转化为现实。",107662,"2026-04-03T11:11:01",[13,14,15],{"id":36,"name":37,"github_repo":38,"description_zh":39,"stars":40,"difficulty_score":23,"last_commit_at":41,"category_tags":42,"status":16},3704,"NextChat","ChatGPTNextWeb\u002FNextChat","NextChat 是一款轻量且极速的 AI 助手，旨在为用户提供流畅、跨平台的大模型交互体验。它完美解决了用户在多设备间切换时难以保持对话连续性，以及面对众多 AI 模型不知如何统一管理的痛点。无论是日常办公、学习辅助还是创意激发，NextChat 都能让用户随时随地通过网页、iOS、Android、Windows、MacOS 或 Linux 端无缝接入智能服务。\n\n这款工具非常适合普通用户、学生、职场人士以及需要私有化部署的企业团队使用。对于开发者而言，它也提供了便捷的自托管方案，支持一键部署到 Vercel 或 Zeabur 等平台。\n\nNextChat 的核心亮点在于其广泛的模型兼容性，原生支持 Claude、DeepSeek、GPT-4 及 Gemini Pro 等主流大模型，让用户在一个界面即可自由切换不同 AI 能力。此外，它还率先支持 MCP（Model Context Protocol）协议，增强了上下文处理能力。针对企业用户，NextChat 提供专业版解决方案，具备品牌定制、细粒度权限控制、内部知识库整合及安全审计等功能，满足公司对数据隐私和个性化管理的高标准要求。",87618,"2026-04-05T07:20:52",[13,26],{"id":44,"name":45,"github_repo":46,"description_zh":47,"stars":48,"difficulty_score":23,"last_commit_at":49,"category_tags":50,"status":16},2268,"ML-For-Beginners","microsoft\u002FML-For-Beginners","ML-For-Beginners 是由微软推出的一套系统化机器学习入门课程，旨在帮助零基础用户轻松掌握经典机器学习知识。这套课程将学习路径规划为 12 周，包含 26 节精炼课程和 52 道配套测验，内容涵盖从基础概念到实际应用的完整流程，有效解决了初学者面对庞大知识体系时无从下手、缺乏结构化指导的痛点。\n\n无论是希望转型的开发者、需要补充算法背景的研究人员，还是对人工智能充满好奇的普通爱好者，都能从中受益。课程不仅提供了清晰的理论讲解，还强调动手实践，让用户在循序渐进中建立扎实的技能基础。其独特的亮点在于强大的多语言支持，通过自动化机制提供了包括简体中文在内的 50 多种语言版本，极大地降低了全球不同背景用户的学习门槛。此外，项目采用开源协作模式，社区活跃且内容持续更新，确保学习者能获取前沿且准确的技术资讯。如果你正寻找一条清晰、友好且专业的机器学习入门之路，ML-For-Beginners 将是理想的起点。",84991,"2026-04-05T10:45:23",[14,51,52,53,15,54,26,13,55],"数据工具","视频","插件","其他","音频",{"id":57,"name":58,"github_repo":59,"description_zh":60,"stars":61,"difficulty_score":10,"last_commit_at":62,"category_tags":63,"status":16},3128,"ragflow","infiniflow\u002Fragflow","RAGFlow 是一款领先的开源检索增强生成（RAG）引擎，旨在为大语言模型构建更精准、可靠的上下文层。它巧妙地将前沿的 RAG 技术与智能体（Agent）能力相结合，不仅支持从各类文档中高效提取知识，还能让模型基于这些知识进行逻辑推理和任务执行。\n\n在大模型应用中，幻觉问题和知识滞后是常见痛点。RAGFlow 通过深度解析复杂文档结构（如表格、图表及混合排版），显著提升了信息检索的准确度，从而有效减少模型“胡编乱造”的现象，确保回答既有据可依又具备时效性。其内置的智能体机制更进一步，使系统不仅能回答问题，还能自主规划步骤解决复杂问题。\n\n这款工具特别适合开发者、企业技术团队以及 AI 研究人员使用。无论是希望快速搭建私有知识库问答系统，还是致力于探索大模型在垂直领域落地的创新者，都能从中受益。RAGFlow 提供了可视化的工作流编排界面和灵活的 API 接口，既降低了非算法背景用户的上手门槛，也满足了专业开发者对系统深度定制的需求。作为基于 Apache 2.0 协议开源的项目，它正成为连接通用大模型与行业专有知识之间的重要桥梁。",77062,"2026-04-04T04:44:48",[15,14,13,26,54],{"id":65,"github_repo":66,"name":67,"description_en":68,"description_zh":69,"ai_summary_zh":69,"readme_en":70,"readme_zh":71,"quickstart_zh":72,"use_case_zh":73,"hero_image_url":74,"owner_login":75,"owner_name":76,"owner_avatar_url":77,"owner_bio":78,"owner_company":79,"owner_location":79,"owner_email":80,"owner_twitter":79,"owner_website":81,"owner_url":82,"languages":83,"stars":100,"forks":101,"last_commit_at":102,"license":103,"difficulty_score":104,"env_os":105,"env_gpu":106,"env_ram":107,"env_deps":108,"category_tags":113,"github_topics":114,"view_count":23,"oss_zip_url":79,"oss_zip_packed_at":79,"status":16,"created_at":118,"updated_at":119,"faqs":120,"releases":151},2609,"tonl-dev\u002Ftonl","tonl","TONL (Token-Optimized Notation Language)","TONL（Token-Optimized Notation Language）是一款专为提升大语言模型（LLM）效率而设计的生产级数据平台。它核心解决的是传统 JSON 格式体积庞大、导致 LLM 处理时 Token 消耗过高及传输缓慢的痛点。通过一种紧凑且人类可读的文本序列化格式，TONL 能在保持数据清晰度的同时，将数据体积缩减高达 60%，显著降低 API 调用成本。\n\n除了高效的压缩能力，TONL 还提供了强大的数据处理功能。开发者可以直接在序列化数据上执行类似 JSONPath 的复杂查询、数据修改、聚合统计（如求和、平均值）以及模糊搜索，无需先将数据完全解析为对象，处理速度比传统方案快 10 到 1600 倍。\n\n该工具主要面向后端开发者、全栈工程师及 AI 应用构建者。其技术亮点包括纯 TypeScript 编写且零依赖，确保类型安全与轻量集成；支持浏览器端运行，打包后仅约 10.5 KB；并具备企业级的安全防护机制，能有效防止拒绝服务攻击等风险。无论是需要优化 Prompt 成本的 AI 项目，还是追求高性能数据流处理的实时应用，TONL 都是一个成熟且可靠的选择。","\u003Cdiv align=\"center\">\n\n![TONL - Token-Optimized Notation Language](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Ftonl-dev_tonl_readme_fe3c661f899c.png)\n\n\u003C\u002Fdiv>\n\n# TONL (Token-Optimized Notation Language)\n\n**TONL** is a production-ready data platform that combines compact serialization with powerful query, modification, indexing, and streaming capabilities. Designed for LLM token efficiency while providing a rich API for data access and manipulation.\n\n## 🎉 Latest Release: v2.5.2 - Documentation & Testing Excellence\n\n### 📚 **v2.5.2 (December 20, 2025)**\n- **216 new tests** - Total 698 tests across 162 suites with 100% pass rate\n- **Browser documentation** - Complete docs\u002FBROWSER.md and docs\u002FERROR_HANDLING.md\n- **4 browser examples** - React 18 and Vue 3 interactive demos\n- **5 security fixes** - All npm vulnerabilities resolved\n- **Updated dependencies** - All packages at latest versions\n\n### 🔧 **v2.5.1 (December 11, 2025)**\n- 8 critical bug fixes including DoS prevention and async handling\n\n### 🛡️ **v2.5.0 (December 3, 2025)**\n- Enterprise security hardening and optimization module\n\n### 🧪 **Testing Excellence:**\n- **698 Comprehensive Tests** - All passing with 100% success rate\n- **96 Security Tests** - Covering all attack vectors\n- **Concurrency Tests** - Thread safety validation\n- **Browser Tests** - Cross-platform compatibility\n\n[![npm version](https:\u002F\u002Fbadge.fury.io\u002Fjs\u002Ftonl.svg)](https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002Ftonl)\n[![License: MIT](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FLicense-MIT-yellow.svg)](https:\u002F\u002Fopensource.org\u002Flicenses\u002FMIT)\n[![TypeScript](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FTypeScript-100%25-blue.svg)](https:\u002F\u002Fwww.typescriptlang.org\u002F)\n\n**🏠 Homepage**: [tonl.dev](https:\u002F\u002Ftonl.dev)\n**📦 GitHub**: [github.com\u002Ftonl-dev\u002Ftonl](https:\u002F\u002Fgithub.com\u002Ftonl-dev\u002Ftonl)\n**📖 Documentation**: [Complete Guides](docs\u002F)\n\n## 📋 Table of Contents\n- [Why TONL?](#why-tonl)\n- [Quick Start](#-quick-start)\n- [Format Overview](#-format-overview)\n- [Feature Set](#-complete-feature-set)\n- [Performance](#-performance-comparison)\n- [Security](#-security--quality)\n- [Use Cases](#-use-cases)\n- [Browser Usage](#-browser-usage)\n- [API Reference](#-complete-api-reference)\n- [Development](#-development)\n- [Roadmap](#-roadmap)\n- [Documentation](#-documentation)\n- [Contributing](#-contributing)\n- [License](#-license)\n\n---\n\n## Why TONL?\n\n🗜️ **Up to 60% Smaller** - Reduce JSON size and LLM token costs\n👁️ **Human-Readable** - Clear text format, not binary\n🚀 **Blazingly Fast** - 10-1600x faster than targets\n🔒 **Production Secure** - 100% security hardened (v2.0.3)\n🛠️ **TypeScript-First** - Full type safety & IntelliSense\n📦 **Zero Dependencies** - Pure TypeScript, no bloat\n🌐 **Browser Ready** - 10.5 KB gzipped bundle (IIFE\u002FUMD)\n✅ **100% Tested** - 496\u002F496 tests passing (core functionality)\n\n---\n\n## 🚀 Quick Start\n\n### Installation\n\n```bash\nnpm install tonl\n```\n\n### Basic Usage\n\n```typescript\nimport { TONLDocument, encodeTONL, decodeTONL } from 'tonl';\n\n\u002F\u002F Create from JSON\nconst doc = TONLDocument.fromJSON({\n  users: [\n    { id: 1, name: \"Alice\", role: \"admin\", age: 30 },\n    { id: 2, name: \"Bob\", role: \"user\", age: 25 }\n  ]\n});\n\n\u002F\u002F Query with JSONPath-like syntax\ndoc.get('users[0].name');                          \u002F\u002F 'Alice'\ndoc.query('users[*].name');                        \u002F\u002F ['Alice', 'Bob']\ndoc.query('users[?(@.role == \"admin\")]');          \u002F\u002F [{ id: 1, ... }]\ndoc.query('$..age');                               \u002F\u002F All ages recursively\n\n\u002F\u002F Aggregation (v2.4.0)\ndoc.count('users[*]');                             \u002F\u002F 2\ndoc.sum('users[*]', 'age');                        \u002F\u002F 55\ndoc.avg('users[*]', 'age');                        \u002F\u002F 27.5\ndoc.groupBy('users[*]', 'role');                   \u002F\u002F { admin: [...], user: [...] }\ndoc.aggregate('users[*]').stats('age');            \u002F\u002F { count, sum, avg, min, max, stdDev }\n\n\u002F\u002F Fuzzy Matching (v2.4.0)\nimport { fuzzySearch, soundsLike } from 'tonl\u002Fquery';\nfuzzySearch('Jon', ['John', 'Jane', 'Bob']);       \u002F\u002F [{ value: 'John', score: 0.75 }]\nsoundsLike('Smith', 'Smyth');                      \u002F\u002F true\n\n\u002F\u002F Temporal Queries (v2.4.0)\nimport { parseTemporalLiteral, isDaysAgo } from 'tonl\u002Fquery';\nparseTemporalLiteral('@now-7d');                   \u002F\u002F 7 days ago\nisDaysAgo(someDate, 30);                           \u002F\u002F within last 30 days?\n\n\u002F\u002F Modify data\ndoc.set('users[0].age', 31);\ndoc.push('users', { id: 3, name: \"Carol\", role: \"editor\", age: 28 });\n\n\u002F\u002F Navigate and iterate\nfor (const [key, value] of doc.entries()) {\n  console.log(key, value);\n}\n\ndoc.walk((path, value, depth) => {\n  console.log(`${path}: ${value}`);\n});\n\n\u002F\u002F Export\nconst tonl = doc.toTONL();\nconst json = doc.toJSON();\nawait doc.save('output.tonl');\n\n\u002F\u002F Classic API (encode\u002Fdecode)\nconst data = { users: [{ id: 1, name: \"Alice\" }] };\nconst tonlText = encodeTONL(data);\nconst restored = decodeTONL(tonlText);\n\n\u002F\u002F Advanced Optimization (v2.0.1+)\nimport { AdaptiveOptimizer, BitPacker, DeltaEncoder } from 'tonl\u002Foptimization';\n\n\u002F\u002F Automatic optimization\nconst optimizer = new AdaptiveOptimizer();\nconst result = optimizer.optimize(data);  \u002F\u002F Auto-selects best strategies\n\n\u002F\u002F Specific optimizers\nconst packer = new BitPacker();\nconst packed = packer.packBooleans([true, false, true]);\n\nconst delta = new DeltaEncoder();\nconst timestamps = [1704067200000, 1704067201000, 1704067202000];\nconst compressed = delta.encode(timestamps, 'timestamp');\n```\n\n### CLI Usage\n\n#### 🎮 **Interactive CLI (NEW v2.3.1)**\n```bash\n# Interactive stats dashboard\ntonl stats data.json --interactive\ntonl stats data.json -i --theme neon\n\n# File comparison mode\ntonl stats data.json --compare --theme matrix\n\n# Interactive exploration\ntonl stats --interactive  # Launch without file for menu-driven exploration\n```\n\n#### 📊 **Standard Commands**\n```bash\n# Get started (shows help)\ntonl\n\n# Version info\ntonl --version\n\n# Encode JSON to TONL (perfect round-trip, quotes special keys)\ntonl encode data.json --out data.tonl --smart --stats\n\n# Encode with preprocessing (clean, readable keys)\ntonl encode data.json --preprocess --out data.tonl\n\n# Decode TONL to JSON\ntonl decode data.tonl --out data.json\n\n# Query data\ntonl query users.tonl \"users[?(@.role == 'admin')]\"\ntonl get data.json \"user.profile.email\"\n\n# Validate against schema\ntonl validate users.tonl --schema users.schema.tonl\n\n# Format and prettify\ntonl format data.tonl --pretty --out formatted.tonl\n\n# Compare token costs\ntonl stats data.json --tokenizer gpt-5\n```\n\n#### 🎨 **Interactive Themes (v2.3.1)**\n```bash\n# Available themes: default, neon, matrix, cyberpunk\ntonl stats data.json -i --theme neon        # Bright neon colors\ntonl stats data.json -i --theme matrix      # Green matrix style\ntonl stats data.json -i --theme cyberpunk   # Cyan\u002Fpurple cyberpunk\ntonl stats data.json -i --theme default     # Clean terminal colors\n```\n\n#### ⚖️ **File Comparison (v2.3.1)**\n```bash\n# Compare JSON and TONL files side-by-side\ntonl stats data.json --compare\ntonl stats data.json --compare --theme neon\n\n# Interactive comparison mode\ntonl stats data.json -i --compare\n```\n\n---\n\n## 📊 Format Overview\n\n### Arrays of Objects (Tabular Format)\n\n**JSON** (245 bytes, 89 tokens):\n```json\n{\n  \"users\": [\n    { \"id\": 1, \"name\": \"Alice\", \"role\": \"admin\" },\n    { \"id\": 2, \"name\": \"Bob, Jr.\", \"role\": \"user\" },\n    { \"id\": 3, \"name\": \"Carol\", \"role\": \"editor\" }\n  ]\n}\n```\n\n**TONL** (158 bytes, 49 tokens - **45% reduction**):\n```tonl\n#version 1.0\nusers[3]{id:u32,name:str,role:str}:\n  1, Alice, admin\n  2, \"Bob, Jr.\", user\n  3, Carol, editor\n```\n\n### Nested Objects\n\n**JSON**:\n```json\n{\n  \"user\": {\n    \"id\": 1,\n    \"name\": \"Alice\",\n    \"contact\": {\n      \"email\": \"alice@example.com\",\n      \"phone\": \"+123456789\"\n    },\n    \"roles\": [\"admin\", \"editor\"]\n  }\n}\n```\n\n**TONL**:\n```tonl\n#version 1.0\nuser{id:u32,name:str,contact:obj,roles:list}:\n  id: 1\n  name: Alice\n  contact{email:str,phone:str}:\n    email: alice@example.com\n    phone: +123456789\n  roles[2]: admin, editor\n```\n\n---\n\n## ✨ Complete Feature Set\n\n### 🔄 Core Serialization\n- **Compact Format** - 32-45% smaller than JSON (bytes + tokens)\n- **Human-Readable** - Clear text format with minimal syntax\n- **Round-Trip Safe** - Perfect bidirectional JSON conversion\n- **Smart Encoding** - Auto-selects optimal delimiters and formatting\n- **Type Hints** - Optional schema information for validation\n\n### 🔍 Query & Navigation API\n- **JSONPath Queries** - `users[?(@.age > 25)]`, `$..email`\n- **Filter Expressions** - `==`, `!=`, `>`, `\u003C`, `&&`, `||`, `contains`, `matches`\n- **Wildcard Support** - `users[*].name`, `**.email`\n- **Tree Traversal** - `entries()`, `keys()`, `values()`, `walk()`\n- **LRU Cache** - >90% cache hit rate on repeated queries\n\n### ✏️ Modification API\n- **CRUD Operations** - `set()`, `get()`, `delete()`, `push()`, `pop()`\n- **Bulk Operations** - `merge()`, `update()`, `removeAll()`\n- **Change Tracking** - `diff()` with detailed change reports\n- **Snapshots** - Document versioning and comparison\n- **Atomic File Edits** - Safe saves with automatic backups\n\n### ⚡ Performance & Indexing\n- **Hash Index** - O(1) exact match lookups\n- **BTree Index** - O(log n) range queries\n- **Compound Index** - Multi-field indexing\n- **Stream Processing** - Handle multi-GB files with \u003C100MB memory\n- **Pipeline Operations** - Chainable filter\u002Fmap\u002Freduce transformations\n\n### 🗜️ Advanced Optimization\n- **Dictionary Encoding** - Value compression via lookup tables (30-50% savings)\n- **Delta Encoding** - Sequential data compression (40-60% savings)\n- **Run-Length Encoding** - Repetitive value compression (50-80% savings)\n- **Bit Packing** - Boolean and small integer bit-level compression (87.5% savings)\n- **Numeric Quantization** - Precision reduction for floating-point numbers (20-40% savings)\n- **Schema Inheritance** - Reusable column schemas across data blocks (20-40% savings)\n- **Hierarchical Grouping** - Common field extraction for nested structures (15-30% savings)\n- **Tokenizer-Aware** - LLM tokenizer optimization for minimal token usage (5-15% savings)\n- **Column Reordering** - Entropy-based ordering for better compression\n- **Adaptive Optimizer** - Automatic strategy selection based on data patterns\n\n### ✅ Schema & Validation\n- **Schema Definition** - `.schema.tonl` files with TSL (TONL Schema Language)\n- **13 Constraints** - `required`, `min`, `max`, `pattern`, `unique`, `email`, etc.\n- **TypeScript Generation** - Auto-generate types from schemas\n- **Runtime Validation** - Validate data programmatically or via CLI\n- **Strict Mode** - Enforce schema compliance\n\n### 🛠️ Developer Tools\n- **🎮 Interactive CLI Dashboard** - Real-time file analysis with themes and progress visualization\n- **⚖️ File Comparison System** - Side-by-side JSON\u002FTONL comparison with detailed metrics\n- **🎨 Visual Customization** - Multiple terminal themes (default, neon, matrix, cyberpunk)\n- **Interactive REPL** - Explore data interactively in terminal\n- **Modular CLI Suite** - `encode`, `decode`, `query`, `validate`, `format`, `stats` with Command Pattern architecture\n- **Browser Support** - ESM, UMD, IIFE builds (8.84 KB gzipped)\n- **VS Code Extension** - Syntax highlighting for `.tonl` files\n- **TypeScript-First** - Full IntelliSense and type safety\n\n---\n\n## 📊 Performance Comparison\n\n| Metric | JSON | TONL | TONL Smart | Improvement |\n|--------|------|------|------------|-------------|\n| **Size (bytes)** | 245 | 167 | 158 | **36% smaller** |\n| **Tokens (GPT-5)** | 89 | 54 | 49 | **45% fewer** |\n| **Encoding Speed** | 1.0x | 15x | 12x | **12-15x faster** |\n| **Decoding Speed** | 1.0x | 10x | 10x | **10x faster** |\n| **Query Speed** | - | - | 1600x | **Target: \u003C1ms** |\n\n*Benchmarks based on typical e-commerce product catalog data*\n\n---\n\n## 🔒 Security & Quality\n\n```\n✅ Tests:          698+ tests passing (100% coverage)\n✅ Security:       All vulnerabilities fixed (100%)\n✅ Security Tests: 96 security tests passing\n✅ Code Quality:   TypeScript strict mode\n✅ Dependencies:   0 runtime dependencies\n✅ Bundle Size:    10.5 KB gzipped (browser)\n✅ Performance:    10-1600x faster than targets\n✅ Production:     Ready & Fully Secure\n```\n\n**Security:**\n- ✅ ReDoS, Path Traversal, Buffer Overflow protection\n- ✅ Prototype Pollution, Command Injection prevention\n- ✅ Integer Overflow, Type Coercion fixes\n- ✅ Comprehensive input validation and resource limits\n\nSee [SECURITY.md](SECURITY.md) and [CHANGELOG.md](CHANGELOG.md) for details.\n\n---\n\n## 🎯 Use Cases\n\n### LLM Prompts\nReduce token costs by 32-45% when including structured data in prompts:\n```typescript\nconst prompt = `Analyze this user data:\\n${doc.toTONL()}`;\n\u002F\u002F 45% fewer tokens = lower API costs\n```\n\n### Configuration Files\nHuman-readable configs that are compact yet clear:\n```tonl\nconfig{env:str,database:obj,features:list}:\n  env: production\n  database{host:str,port:u32,ssl:bool}:\n    host: db.example.com\n    port: 5432\n    ssl: true\n  features[3]: auth, analytics, caching\n```\n\n### API Responses\nEfficient data transmission with schema validation:\n```typescript\napp.get('\u002Fapi\u002Fusers', async (req, res) => {\n  const doc = await TONLDocument.load('users.tonl');\n  const filtered = doc.query('users[?(@.active == true)]');\n  res.type('text\u002Ftonl').send(encodeTONL(filtered));\n});\n```\n\n### Data Pipelines\nStream processing for large datasets:\n```typescript\nimport { createEncodeStream, createDecodeStream } from 'tonl\u002Fstream';\n\ncreateReadStream('huge.json')\n  .pipe(createDecodeStream())\n  .pipe(transformStream)\n  .pipe(createEncodeStream({ smart: true }))\n  .pipe(createWriteStream('output.tonl'));\n```\n\n### Log Aggregation\nCompact structured logs:\n```tonl\nlogs[1000]{timestamp:i64,level:str,message:str,metadata:obj}:\n  1699564800, INFO, \"User login\", {user_id:123,ip:\"192.168.1.1\"}\n  1699564801, ERROR, \"DB timeout\", {query:\"SELECT...\",duration:5000}\n  ...\n```\n\n---\n\n## 🌐 Browser Usage\n\n### ESM (Modern Browsers)\n```html\n\u003Cscript type=\"module\">\n  import { encodeTONL, decodeTONL } from 'https:\u002F\u002Fcdn.jsdelivr.net\u002Fnpm\u002Ftonl@2.4.1\u002F+esm';\n\n  const data = { users: [{ id: 1, name: \"Alice\" }] };\n  const tonl = encodeTONL(data);\n  console.log(tonl);\n\u003C\u002Fscript>\n```\n\n### UMD (Universal)\n```html\n\u003Cscript src=\"https:\u002F\u002Funpkg.com\u002Ftonl@2.4.1\u002Fdist\u002Fbrowser\u002Ftonl.umd.js\">\u003C\u002Fscript>\n\u003Cscript>\n  const tonl = TONL.encodeTONL({ hello: \"world\" });\n  console.log(tonl);\n\u003C\u002Fscript>\n```\n\n**Bundle Sizes:**\n- ESM: 15.5 KB gzipped\n- UMD: 10.7 KB gzipped\n- IIFE: 10.6 KB gzipped\n\n**Examples:**\nSee [examples\u002Fbrowser\u002F](examples\u002Fbrowser\u002F) for interactive React and Vue examples.\n\n---\n\n## 📚 Complete API Reference\n\n### TONLDocument Class\n\n```typescript\n\u002F\u002F Creation\nTONLDocument.fromJSON(data)\nTONLDocument.parse(text)                           \u002F\u002F Parse TONL string\nTONLDocument.fromFile(filepath)                    \u002F\u002F Async file load\nTONLDocument.fromFileSync(filepath)                \u002F\u002F Sync file load\n\n\u002F\u002F Query\ndoc.get(path: string)                              \u002F\u002F Single value\ndoc.query(query: string)                           \u002F\u002F Multiple values\ndoc.exists(path: string)                           \u002F\u002F Check existence\n\n\u002F\u002F Modification\ndoc.set(path: string, value: any)                  \u002F\u002F Set value\ndoc.delete(path: string)                           \u002F\u002F Delete value\ndoc.push(path: string, value: any)                 \u002F\u002F Append to array\ndoc.pop(path: string)                              \u002F\u002F Remove last from array\ndoc.merge(path: string, value: object)             \u002F\u002F Deep merge objects\n\n\u002F\u002F Navigation\ndoc.entries()                                      \u002F\u002F Iterator\u003C[key, value]>\ndoc.keys()                                         \u002F\u002F Iterator\u003Cstring>\ndoc.values()                                       \u002F\u002F Iterator\u003Cany>\ndoc.walk(callback: WalkCallback)                   \u002F\u002F Tree traversal\ndoc.find(predicate: Predicate)                     \u002F\u002F Find single value\ndoc.findAll(predicate: Predicate)                  \u002F\u002F Find all matching\ndoc.some(predicate: Predicate)                     \u002F\u002F Any match\ndoc.every(predicate: Predicate)                    \u002F\u002F All match\n\n\u002F\u002F Indexing\ndoc.createIndex(name: string, path: string, type?) \u002F\u002F Create index\ndoc.dropIndex(name: string)                        \u002F\u002F Remove index\ndoc.getIndex(name: string)                         \u002F\u002F Get index\n\n\u002F\u002F Export\ndoc.toTONL(options?: EncodeOptions)                \u002F\u002F Export as TONL\ndoc.toJSON()                                       \u002F\u002F Export as JSON\ndoc.save(filepath: string, options?)               \u002F\u002F Save to file\ndoc.size()                                         \u002F\u002F Size in bytes\ndoc.stats()                                        \u002F\u002F Statistics object\n```\n\n### Encode\u002FDecode API\n\n```typescript\n\u002F\u002F Encoding\nencodeTONL(data: any, options?: {\n  delimiter?: \",\" | \"|\" | \"\\t\" | \";\";\n  includeTypes?: boolean;\n  version?: string;\n  indent?: number;\n  singleLinePrimitiveLists?: boolean;\n}): string\n\n\u002F\u002F Smart encoding (auto-optimized)\nencodeSmart(data: any, options?: EncodeOptions): string\n\n\u002F\u002F Decoding\ndecodeTONL(text: string, options?: {\n  delimiter?: \",\" | \"|\" | \"\\t\" | \";\";\n  strict?: boolean;\n}): any\n```\n\n### Schema API\n\n```typescript\nimport { parseSchema, validateTONL } from 'tonl\u002Fschema';\n\n\u002F\u002F Parse schema\nconst schema = parseSchema(schemaText: string);\n\n\u002F\u002F Validate data\nconst result = validateTONL(data: any, schema: Schema);\n\nif (!result.valid) {\n  result.errors.forEach(err => {\n    console.error(`${err.field}: ${err.message}`);\n  });\n}\n```\n\n### Streaming API\n\n```typescript\nimport { createEncodeStream, createDecodeStream, encodeIterator, decodeIterator } from 'tonl\u002Fstream';\n\n\u002F\u002F Node.js streams\ncreateReadStream('input.json')\n  .pipe(createEncodeStream({ smart: true }))\n  .pipe(createWriteStream('output.tonl'));\n\n\u002F\u002F Async iterators\nfor await (const line of encodeIterator(dataStream)) {\n  console.log(line);\n}\n```\n\n---\n\n## ✅ Schema Validation\n\nDefine schemas with the TONL Schema Language (TSL):\n\n```tonl\n@schema v1\n@strict true\n@description \"User management schema\"\n\n# Define custom types\nUser: obj\n  id: u32 required\n  username: str required min:3 max:20 pattern:^[a-zA-Z0-9_]+$\n  email: str required pattern:email lowercase:true\n  age: u32? min:13 max:150\n  roles: list\u003Cstr> required min:1 unique:true\n\n# Root schema\nusers: list\u003CUser> required min:1\ntotalCount: u32 required\n```\n\n**13 Built-in Constraints:**\n- `required` - Field must exist\n- `min` \u002F `max` - Numeric range or string\u002Farray length\n- `length` - Exact length\n- `pattern` - Regex validation (or shortcuts: `email`, `url`, `uuid`)\n- `unique` - Array elements must be unique\n- `nonempty` - String\u002Farray cannot be empty\n- `positive` \u002F `negative` - Number sign\n- `integer` - Must be integer\n- `multipleOf` - Divisibility check\n- `lowercase` \u002F `uppercase` - String case enforcement\n\nSee [docs\u002FSCHEMA_SPECIFICATION.md](docs\u002FSCHEMA_SPECIFICATION.md) for complete reference.\n\n---\n\n## 🛠️ Development\n\n### Build & Test\n\n```bash\n# Install dependencies\nnpm install\n\n# Build TypeScript\nnpm run build\n\n# Run all tests (698+ tests)\nnpm test\n\n# Watch mode\nnpm run dev\n\n# Clean build artifacts\nnpm run clean\n```\n\n### Benchmarking\n\n```bash\n# Byte size comparison\nnpm run bench\n\n# Token estimation (GPT-5, Claude 3.5, Gemini 2.0, Llama 4)\nnpm run bench-tokens\n\n# Comprehensive performance analysis\nnpm run bench-comprehensive\n```\n\n### CLI Development\n\n```bash\n# Install CLI locally\nnpm run link\n\n# Test commands\ntonl encode test.json\ntonl query data.tonl \"users[*].name\"\ntonl format data.tonl --pretty\n\n# Test interactive features (v2.3.1+)\ntonl stats data.json --interactive\ntonl stats data.json -i --theme neon\ntonl stats data.json --compare\n```\n\n---\n\n## 🗺️ Roadmap\n\n**✅ v2.5.1 - Complete (Latest)**\n- ✅ Critical bug fixes (Array expansion DoS, JSON.stringify vulnerability, async handling)\n- ✅ 482 tests with 100% pass rate\n- ✅ Enhanced stability and error handling\n\n**✅ v2.5.0 - Complete**\n- ✅ Aggregation Functions (count, sum, avg, groupBy, stats, median, percentile)\n- ✅ Fuzzy String Matching (Levenshtein, Jaro-Winkler, Soundex, Metaphone)\n- ✅ Temporal Queries (@now-7d, before, after, sameDay, daysAgo)\n- ✅ 763+ comprehensive tests with 100% success rate\n\n**✅ v2.2+ - Complete**\n- ✅ Revolutionary Interactive CLI Dashboard with real-time analysis\n- ✅ Complete Modular Architecture Transformation (735→75 lines)\n- ✅ File Comparison System with side-by-side analysis\n- ✅ Visual Themes (default, neon, matrix, cyberpunk)\n\n**✅ v2.0+ - Complete**\n- ✅ Advanced optimization module (60% additional compression)\n- ✅ Complete query, modification, indexing, streaming APIs\n- ✅ Schema validation & TypeScript generation\n- ✅ Browser support (10.5 KB bundles)\n- ✅ 100% test coverage & security hardening\n\n**🚀 Future**\n- Enhanced VS Code extension (IntelliSense, debugging)\n- Web playground with live conversion\n- Python, Go, Rust implementations\n- Binary TONL format for extreme compression\n\nSee [ROADMAP.md](ROADMAP.md) for our comprehensive development vision.\n\n---\n\n## 📖 Documentation\n\n### For Users\n- **[Getting Started Guide](docs\u002FGETTING_STARTED.md)** - Beginner-friendly tutorial with examples\n- **[API Reference](docs\u002FAPI.md)** - Complete API documentation with examples\n- **[CLI Documentation](docs\u002FCLI.md)** - Command-line tool guide\n- **[Browser API](docs\u002FBROWSER.md)** - Browser usage with ESM, UMD, IIFE builds\n- **[Error Handling](docs\u002FERROR_HANDLING.md)** - Error classes and troubleshooting\n- **[Query API](docs\u002FQUERY_API.md)** - JSONPath-like query syntax reference\n- **[Modification API](docs\u002FMODIFICATION_API.md)** - CRUD operations guide\n- **[Navigation API](docs\u002FNAVIGATION_API.md)** - Tree traversal methods\n- **[Use Cases](docs\u002FUSE_CASES.md)** - Real-world scenarios and solutions\n\n### For Implementers (Other Languages)\n- **[Implementation Reference](docs\u002FIMPLEMENTATION_REFERENCE.md)** - Language-agnostic implementation guide\n- **[Transformation Examples](docs\u002FTRANSFORMATION_EXAMPLES.md)** - 20+ JSON↔TONL conversion examples\n- **[Format Specification](docs\u002FSPECIFICATION.md)** - Technical format specification\n- **[Schema Specification](docs\u002FSCHEMA_SPECIFICATION.md)** - TSL (TONL Schema Language) spec\n\n**Implementing TONL in Python, Go, Rust, or another language?** Check out the [Implementation Reference](docs\u002FIMPLEMENTATION_REFERENCE.md) for complete algorithms, pseudo-code, and test requirements!\n\n---\n\n## 🤝 Contributing\n\nContributions are welcome! Please read [CONTRIBUTING.md](CONTRIBUTING.md) for:\n- Development setup\n- Code style guidelines\n- Testing requirements\n- Pull request process\n- Architecture overview\n\n---\n\n## 📄 License\n\nMIT License - see [LICENSE](LICENSE) file for details.\n\n---\n\n## 🌟 Links\n\n- **Website**: [tonl.dev](https:\u002F\u002Ftonl.dev)\n- **npm Package**: [npmjs.com\u002Fpackage\u002Ftonl](https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002Ftonl)\n- **GitHub**: [github.com\u002Ftonl-dev\u002Ftonl](https:\u002F\u002Fgithub.com\u002Ftonl-dev\u002Ftonl)\n- **Issues**: [github.com\u002Ftonl-dev\u002Ftonl\u002Fissues](https:\u002F\u002Fgithub.com\u002Ftonl-dev\u002Ftonl\u002Fissues)\n- **Discussions**: [github.com\u002Ftonl-dev\u002Ftonl\u002Fdiscussions](https:\u002F\u002Fgithub.com\u002Ftonl-dev\u002Ftonl\u002Fdiscussions)\n- **VS Code Extension**: [Coming Soon]\n\n---\n\n\u003Cdiv align=\"center\">\n\n**TONL**: Making structured data LLM-friendly without sacrificing readability. 🚀\n\n*Built with ❤️ by [Ersin Koc](https:\u002F\u002Fgithub.com\u002Fersinkoc)*\n\n\u003C\u002Fdiv>\n","\u003Cdiv align=\"center\">\n\n![TONL - 令牌优化表示语言](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Ftonl-dev_tonl_readme_fe3c661f899c.png)\n\n\u003C\u002Fdiv>\n\n# TONL（令牌优化表示语言）\n\n**TONL** 是一个生产就绪的数据平台，结合了紧凑的序列化以及强大的查询、修改、索引和流式处理能力。它专为 LLM 的令牌效率而设计，同时提供丰富的 API 用于数据访问和操作。\n\n## 🎉 最新版本：v2.5.2 - 文档与测试卓越\n\n### 📚 **v2.5.2（2025年12月20日）**\n- **216项新测试** - 共计162个测试套件中的698项测试，通过率为100%\n- **浏览器文档** - 完整的docs\u002FBROWSER.md 和 docs\u002FERROR_HANDLING.md\n- **4个浏览器示例** - React 18 和 Vue 3 交互式演示\n- **5处安全修复** - 所有 npm 漏洞均已修复\n- **更新依赖项** - 所有包均升级至最新版本\n\n### 🔧 **v2.5.1（2025年12月11日）**\n- 8项关键错误修复，包括防止 DoS 攻击和异步处理问题\n\n### 🛡️ **v2.5.0（2025年12月3日）**\n- 企业级安全加固及优化模块\n\n### 🧪 **测试卓越：**\n- **698项全面测试** - 全部通过，成功率为100%\n- **96项安全测试** - 覆盖所有攻击向量\n- **并发测试** - 线程安全性验证\n- **浏览器测试** - 跨平台兼容性\n\n[![npm version](https:\u002F\u002Fbadge.fury.io\u002Fjs\u002Ftonl.svg)](https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002Ftonl)\n[![License: MIT](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FLicense-MIT-yellow.svg)](https:\u002F\u002Fopensource.org\u002Flicenses\u002FMIT)\n[![TypeScript](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FTypeScript-100%25-blue.svg)](https:\u002F\u002Fwww.typescriptlang.org\u002F)\n\n**🏠 主页**: [tonl.dev](https:\u002F\u002Ftonl.dev)\n**📦 GitHub**: [github.com\u002Ftonl-dev\u002Ftonl](https:\u002F\u002Fgithub.com\u002Ftonl-dev\u002Ftonl)\n**📖 文档**: [完整指南](docs\u002F)\n\n## 📋 目录\n- [为什么选择TONL？](#why-tonl)\n- [快速入门](#-quick-start)\n- [格式概述](#-format-overview)\n- [功能集](#-complete-feature-set)\n- [性能](#-performance-comparison)\n- [安全性](#-security--quality)\n- [用例](#-use-cases)\n- [浏览器使用](#-browser-usage)\n- [API 参考](#-complete-api-reference)\n- [开发](#-development)\n- [路线图](#-roadmap)\n- [文档](#-documentation)\n- [贡献](#-contributing)\n- [许可证](#-license)\n\n---\n\n## 为什么选择TONL？\n\n🗜️ **体积缩小多达60%** - 减少 JSON 大小及 LLM 令牌成本\n👁️ **人类可读** - 清晰的文本格式，而非二进制\n🚀 **极速高效** - 比目标快10到1600倍\n🔒 **生产级安全** - 100% 安全加固（v2.0.3）\n🛠️ **TypeScript优先** - 完整类型安全与智能感知\n📦 **零依赖** - 纯 TypeScript，无臃肿代码\n🌐 **浏览器就绪** - 压缩后仅10.5 KB（IIFE\u002FUMD）\n✅ **100% 测试覆盖** - 核心功能496项测试全部通过\n\n---\n\n## 🚀 快速入门\n\n### 安装\n\n```bash\nnpm install tonl\n```\n\n### 基本用法\n\n```typescript\nimport { TONLDocument, encodeTONL, decodeTONL } from 'tonl';\n\n\u002F\u002F 从 JSON 创建\nconst doc = TONLDocument.fromJSON({\n  users: [\n    { id: 1, name: \"Alice\", role: \"admin\", age: 30 },\n    { id: 2, name: \"Bob\", role: \"user\", age: 25 }\n  ]\n});\n\n\u002F\u002F 使用类似 JSONPath 的语法进行查询\ndoc.get('users[0].name');                          \u002F\u002F 'Alice'\ndoc.query('users[*].name');                        \u002F\u002F ['Alice', 'Bob']\ndoc.query('users[?(@.role == \"admin\")]');          \u002F\u002F [{ id: 1, ... }]\ndoc.query('$..age');                               \u002F\u002F 递归获取所有年龄\n\n\u002F\u002F 聚合（v2.4.0）\ndoc.count('users[*]');                             \u002F\u002F 2\ndoc.sum('users[*]', 'age');                        \u002F\u002F 55\ndoc.avg('users[*]', 'age');                        \u002F\u002F 27.5\ndoc.groupBy('users[*]', 'role');                   \u002F\u002F { admin: [...], user: [...] }\ndoc.aggregate('users[*]').stats('age');            \u002F\u002F { count, sum, avg, min, max, stdDev }\n\n\u002F\u002F 模糊匹配（v2.4.0）\nimport { fuzzySearch, soundsLike } from 'tonl\u002Fquery';\nfuzzySearch('Jon', ['John', 'Jane', 'Bob']);       \u002F\u002F [{ value: 'John', score: 0.75 }]\nsoundsLike('Smith', 'Smyth');                      \u002F\u002F true\n\n\u002F\u002F 时间查询（v2.4.0）\nimport { parseTemporalLiteral, isDaysAgo } from 'tonl\u002Fquery';\nparseTemporalLiteral('@now-7d');                   \u002F\u002F 7天前\nisDaysAgo(someDate, 30);                           \u002F\u002F 是否在过去30天内？\n\n\u002F\u002F 修改数据\ndoc.set('users[0].age', 31);\ndoc.push('users', { id: 3, name: \"Carol\", role: \"editor\", age: 28 });\n\n\u002F\u002F 导航与遍历\nfor (const [key, value] of doc.entries()) {\n  console.log(key, value);\n}\n\ndoc.walk((path, value, depth) => {\n  console.log(`${path}: ${value}`);\n});\n\n\u002F\u002F 导出\nconst tonl = doc.toTONL();\nconst json = doc.toJSON();\nawait doc.save('output.tonl');\n\n\u002F\u002F 经典 API（编码\u002F解码）\nconst data = { users: [{ id: 1, name: \"Alice\" }] };\nconst tonlText = encodeTONL(data);\nconst restored = decodeTONL(tonlText);\n\n\u002F\u002F 高级优化（v2.0.1+）\nimport { AdaptiveOptimizer, BitPacker, DeltaEncoder } from 'tonl\u002Foptimization';\n\n\u002F\u002F 自动优化\nconst optimizer = new AdaptiveOptimizer();\nconst result = optimizer.optimize(data);  \u002F\u002F 自动选择最佳策略\n\n\u002F\u002F 特定优化器\nconst packer = new BitPacker();\nconst packed = packer.packBooleans([true, false, true]);\n\nconst delta = new DeltaEncoder();\nconst timestamps = [1704067200000, 1704067201000, 1704067202000];\nconst compressed = delta.encode(timestamps, 'timestamp');\n```\n\n### CLI 使用\n\n#### 🎮 **交互式 CLI（全新 v2.3.1）**\n```bash\n# 交互式统计仪表盘\ntonl stats data.json --interactive\ntonl stats data.json -i --theme neon\n\n# 文件比较模式\ntonl stats data.json --compare --theme matrix\n\n# 交互式探索\ntonl stats --interactive  # 不需文件即可启动菜单驱动式探索\n```\n\n#### 📊 **标准命令**\n```bash\n# 开始使用（显示帮助）\ntonl\n\n# 版本信息\ntonl --version\n\n# 将 JSON 编码为 TONL（完美往返，特殊键加引号）\ntonl encode data.json --out data.tonl --smart --stats\n\n# 带预处理的编码（清理并使键更易读）\ntonl encode data.json --preprocess --out data.tonl\n\n# 将 TONL 解码为 JSON\ntonl decode data.tonl --out data.json\n\n# 查询数据\ntonl query users.tonl \"users[?(@.role == 'admin')]\"\ntonl get data.json \"user.profile.email\"\n\n# 根据模式验证\ntonl validate users.tonl --schema users.schema.tonl\n\n# 格式化并美化\ntonl format data.tonl --pretty --out formatted.tonl\n\n# 比较令牌成本\ntonl stats data.json --tokenizer gpt-5\n```\n\n#### 🎨 **交互式主题（v2.3.1）**\n```bash\n# 可用主题：默认、霓虹、矩阵、赛博朋克\ntonl stats data.json -i --theme neon        # 明亮的霓虹色\ntonl stats data.json -i --theme matrix      # 绿色矩阵风格\ntonl stats data.json -i --theme cyberpunk   # 青紫色赛博朋克风\ntonl stats data.json -i --theme default     # 干净的终端颜色\n```\n\n#### ⚖️ **文件比较（v2.3.1）**\n```bash\n# 并排比较 JSON 和 TONL 文件\ntonl stats data.json --compare\ntonl stats data.json --compare --theme neon\n\n# 交互式比较模式\ntonl stats data.json -i --compare\n```\n\n---\n\n## 📊 格式概述\n\n### 对象数组（表格格式）\n\n**JSON**（245字节，89个标记）：\n```json\n{\n  \"users\": [\n    { \"id\": 1, \"name\": \"Alice\", \"role\": \"admin\" },\n    { \"id\": 2, \"name\": \"Bob, Jr.\", \"role\": \"user\" },\n    { \"id\": 3, \"name\": \"Carol\", \"role\": \"editor\" }\n  ]\n}\n```\n\n**TONL**（158字节，49个标记——**减少45%**）：\n```tonl\n#version 1.0\nusers[3]{id:u32,name:str,role:str}:\n  1, Alice, admin\n  2, \"Bob, Jr.\", user\n  3, Carol, editor\n```\n\n### 嵌套对象\n\n**JSON**：\n```json\n{\n  \"user\": {\n    \"id\": 1,\n    \"name\": \"Alice\",\n    \"contact\": {\n      \"email\": \"alice@example.com\",\n      \"phone\": \"+123456789\"\n    },\n    \"roles\": [\"admin\", \"editor\"]\n  }\n}\n```\n\n**TONL**：\n```tonl\n#version 1.0\nuser{id:u32,name:str,contact:obj,roles:list}:\n  id: 1\n  name: Alice\n  contact{email:str,phone:str}:\n    email: alice@example.com\n    phone: +123456789\n  roles[2]: admin, editor\n```\n\n---\n\n## ✨ 完整功能集\n\n### 🔄 核心序列化\n- **紧凑格式**：比 JSON 小 32%-45%（字节数和标记数）\n- **可读性高**：清晰的文本格式，语法简洁\n- **双向兼容**：支持与 JSON 的完美互转\n- **智能编码**：自动选择最优分隔符和格式\n- **类型提示**：可选模式信息用于验证\n\n### 🔍 查询与导航 API\n- **JSONPath 查询**：`users[?(@.age > 25)]`、`$..email`\n- **过滤表达式**：`==`、`!=`、`>`、`\u003C`、`&&`、`||`、`contains`、`matches`\n- **通配符支持**：`users[*].name`、`**.email`\n- **树遍历**：`entries()`、`keys()`、`values()`、`walk()`\n- **LRU 缓存**：重复查询命中率超过 90%\n\n### ✏️ 修改 API\n- **CRUD 操作**：`set()`、`get()`、`delete()`、`push()`、`pop()`\n- **批量操作**：`merge()`、`update()`、`removeAll()`\n- **变更跟踪**：`diff()` 提供详细变更报告\n- **快照**：文档版本管理和对比\n- **原子文件编辑**：安全保存并自动备份\n\n### ⚡ 性能与索引\n- **哈希索引**：O(1) 精确匹配查找\n- **BTree 索引**：O(log n) 范围查询\n- **复合索引**：多字段索引\n- **流式处理**：处理数十 GB 文件仅需不到 100 MB 内存\n- **管道操作**：可链式执行过滤\u002F映射\u002F归约转换\n\n### 🗜️ 高级优化\n- **字典编码**：通过查找表压缩值（节省 30%-50%）\n- **差分编码**：顺序数据压缩（节省 40%-60%）\n- **游程编码**：重复值压缩（节省 50%-80%）\n- **位打包**：布尔值和小整数的位级压缩（节省 87.5%）\n- **数值量化**：降低浮点数精度（节省 20%-40%）\n- **模式继承**：跨数据块重用列模式（节省 20%-40%）\n- **层次分组**：提取嵌套结构中的公共字段（节省 15%-30%）\n- **分词器感知**：针对 LLM 分词器优化以减少标记使用（节省 5%-15%）\n- **列重排**：基于熵排序以提高压缩效率\n- **自适应优化器**：根据数据模式自动选择策略\n\n### ✅ 模式与验证\n- **模式定义**：`.schema.tonl` 文件，采用 TSL（TONL 模式语言）\n- **13 种约束**：`required`、`min`、`max`、`pattern`、`unique`、`email` 等\n- **TypeScript 生成**：从模式自动生成类型\n- **运行时验证**：可通过程序或 CLI 验证数据\n- **严格模式**：强制遵守模式要求\n\n### 🛠️ 开发者工具\n- **🎮 交互式 CLI 控制台**：实时文件分析，支持主题和进度可视化\n- **⚖️ 文件比较系统**：JSON 和 TONL 并排比较，提供详细指标\n- **🎨 可视化定制**：多种终端主题（默认、霓虹、矩阵、赛博朋克）\n- **交互式 REPL**：在终端中交互探索数据\n- **模块化 CLI 套件**：`encode`、`decode`、`query`、`validate`、`format`、`stats`，采用命令模式架构\n- **浏览器支持**：ESM、UMD、IIFE 构建（压缩后 8.84 KB）\n- **VS Code 扩展**：为 `.tonl` 文件提供语法高亮\n- **TypeScript 优先**：全面的 IntelliSense 和类型安全\n\n---\n\n## 📊 性能对比\n\n| 指标         | JSON   | TONL   | TONL Smart | 改善幅度 |\n|--------------|--------|--------|------------|----------|\n| **大小（字节）** | 245  | 167  | 158      | **更小 36%** |\n| **标记数（GPT-5）** | 89 | 54 | 49     | **减少 45%** |\n| **编码速度**   | 1.0x | 15x  | 12x      | **快 12-15 倍** |\n| **解码速度**   | 1.0x | 10x  | 10x      | **快 10 倍** |\n| **查询速度**   | -      | -      | 1600x    | **目标：\u003C1ms** |\n\n*基准测试基于典型的电商产品目录数据*\n\n---\n\n## 🔒 安全与质量\n\n```\n✅ 测试：          698+ 测试通过（100% 覆盖率）\n✅ 安全：           已修复所有漏洞（100%）\n✅ 安全测试：       96 项安全测试通过\n✅ 代码质量：       TypeScript 严格模式\n✅ 依赖项：         运行时无依赖\n✅ 包体积：         浏览器端压缩后 10.5 KB\n✅ 性能：           比目标快 10-1600 倍\n✅ 生产就绪：       已准备就绪且完全安全\n```\n\n**安全性：**\n- ✅ 防止 ReDoS、路径遍历、缓冲区溢出\n- ✅ 防范原型污染、命令注入\n- ✅ 修复整数溢出、类型强制转换问题\n- ✅ 全面的输入验证和资源限制\n\n详情请参阅 [SECURITY.md](SECURITY.md) 和 [CHANGELOG.md](CHANGELOG.md)。\n\n---\n\n## 🎯 使用场景\n\n### LLM 提示词\n在提示词中加入结构化数据时，可将标记成本降低 32%-45%：\n```typescript\nconst prompt = `分析以下用户数据：\\n${doc.toTONL()}`;\n\u002F\u002F 标记数减少 45% = API 成本降低\n```\n\n### 配置文件\n既紧凑又清晰的人类可读配置：\n```tonl\nconfig{env:str,database:obj,features:list}:\n  env: production\n  database{host:str,port:u32,ssl:bool}:\n    host: db.example.com\n    port: 5432\n    ssl: true\n  features[3]: auth, analytics, caching\n```\n\n### API 响应\n高效传输数据并进行模式验证：\n```typescript\napp.get('\u002Fapi\u002Fusers', async (req, res) => {\n  const doc = await TONLDocument.load('users.tonl');\n  const filtered = doc.query('users[?(@.active == true)]');\n  res.type('text\u002Ftonl').send(encodeTONL(filtered));\n});\n```\n\n### 数据管道\n大型数据集的流式处理：\n```typescript\nimport { createEncodeStream, createDecodeStream } from 'tonl\u002Fstream';\n\ncreateReadStream('huge.json')\n  .pipe(createDecodeStream())\n  .pipe(transformStream)\n  .pipe(createEncodeStream({ smart: true }))\n  .pipe(createWriteStream('output.tonl'));\n```\n\n### 日志聚合\n紧凑的结构化日志：\n```tonl\nlogs[1000]{timestamp:i64,level:str,message:str,metadata:obj}:\n  1699564800, INFO, \"用户登录\", {user_id:123,ip:\"192.168.1.1\"}\n  1699564801, ERROR, \"DB 超时\", {query:\"SELECT...\",duration:5000}\n  ...\n```\n\n---\n\n## 🌐 浏览器使用\n\n### ESM（现代浏览器）\n```html\n\u003Cscript type=\"module\">\n  import { encodeTONL, decodeTONL } from 'https:\u002F\u002Fcdn.jsdelivr.net\u002Fnpm\u002Ftonl@2.4.1\u002F+esm';\n\n  const data = { users: [{ id: 1, name: \"Alice\" }] };\n  const tonl = encodeTONL(data);\n  console.log(tonl);\n\u003C\u002Fscript>\n```\n\n### UMD（通用）\n```html\n\u003Cscript src=\"https:\u002F\u002Funpkg.com\u002Ftonl@2.4.1\u002Fdist\u002Fbrowser\u002Ftonl.umd.js\">\u003C\u002Fscript>\n\u003Cscript>\n  const tonl = TONL.encodeTONL({ hello: \"world\" });\n  console.log(tonl);\n\u003C\u002Fscript>\n```\n\n**打包大小：**\n- ESM：15.5 KB（压缩后）\n- UMD：10.7 KB（压缩后）\n- IIFE：10.6 KB（压缩后）\n\n**示例：**\n请参阅 [examples\u002Fbrowser\u002F](examples\u002Fbrowser\u002F)，以获取交互式的 React 和 Vue 示例。\n\n---\n\n## 📚 完整 API 参考\n\n### TONLDocument 类\n\n```typescript\n\u002F\u002F 创建\nTONLDocument.fromJSON(data)\nTONLDocument.parse(text)                           \u002F\u002F 解析 TONL 字符串\nTONLDocument.fromFile(filepath)                    \u002F\u002F 异步文件加载\nTONLDocument.fromFileSync(filepath)                \u002F\u002F 同步文件加载\n\n\u002F\u002F 查询\ndoc.get(path: string)                              \u002F\u002F 获取单个值\ndoc.query(query: string)                           \u002F\u002F 获取多个值\ndoc.exists(path: string)                           \u002F\u002F 检查是否存在\n\n\u002F\u002F 修改\ndoc.set(path: string, value: any)                  \u002F\u002F 设置值\ndoc.delete(path: string)                           \u002F\u002F 删除值\ndoc.push(path: string, value: any)                 \u002F\u002F 向数组追加元素\ndoc.pop(path: string)                              \u002F\u002F 从数组中移除最后一个元素\ndoc.merge(path: string, value: object)             \u002F\u002F 深度合并对象\n\n\u002F\u002F 导航\ndoc.entries()                                      \u002F\u002F 迭代器\u003C[key, value]>\ndoc.keys()                                         \u002F\u002F 迭代器\u003Cstring>\ndoc.values()                                       \u002F\u002F 迭代器\u003Cany>\ndoc.walk(callback: WalkCallback)                   \u002F\u002F 遍历树结构\ndoc.find(predicate: Predicate)                     \u002F\u002F 查找单个匹配项\ndoc.findAll(predicate: Predicate)                  \u002F\u002F 查找所有匹配项\ndoc.some(predicate: Predicate)                     \u002F\u002F 是否存在至少一个匹配项\ndoc.every(predicate: Predicate)                    \u002F\u002F 是否所有项都匹配\n\n\u002F\u002F 索引\ndoc.createIndex(name: string, path: string, type?) \u002F\u002F 创建索引\ndoc.dropIndex(name: string)                        \u002F\u002F 删除索引\ndoc.getIndex(name: string)                         \u002F\u002F 获取索引\n\n\u002F\u002F 导出\ndoc.toTONL(options?: EncodeOptions)                \u002F\u002F 导出为 TONL 格式\ndoc.toJSON()                                       \u002F\u002F 导出为 JSON 格式\ndoc.save(filepath: string, options?)               \u002F\u002F 保存到文件\ndoc.size()                                         \u002F\u002F 文件大小（字节）\ndoc.stats()                                        \u002F\u002F 统计信息对象\n```\n\n### 编码\u002F解码 API\n\n```typescript\n\u002F\u002F 编码\nencodeTONL(data: any, options?: {\n  delimiter?: \",\" | \"|\" | \"\\t\" | \";\";\n  includeTypes?: boolean;\n  version?: string;\n  indent?: number;\n  singleLinePrimitiveLists?: boolean;\n}): string\n\n\u002F\u002F 智能编码（自动优化）\nencodeSmart(data: any, options?: EncodeOptions): string\n\n\u002F\u002F 解码\ndecodeTONL(text: string, options?: {\n  delimiter?: \",\" | \"|\" | \"\\t\" | \";\";\n  strict?: boolean;\n}): any\n```\n\n### Schema API\n\n```typescript\nimport { parseSchema, validateTONL } from 'tonl\u002Fschema';\n\n\u002F\u002F 解析模式\nconst schema = parseSchema(schemaText: string);\n\n\u002F\u002F 验证数据\nconst result = validateTONL(data: any, schema: Schema);\n\nif (!result.valid) {\n  result.errors.forEach(err => {\n    console.error(`${err.field}: ${err.message}`);\n  });\n}\n```\n\n### 流式 API\n\n```typescript\nimport { createEncodeStream, createDecodeStream, encodeIterator, decodeIterator } from 'tonl\u002Fstream';\n\n\u002F\u002F Node.js 流\ncreateReadStream('input.json')\n  .pipe(createEncodeStream({ smart: true }))\n  .pipe(createWriteStream('output.tonl'));\n\n\u002F\u002F 异步迭代器\nfor await (const line of encodeIterator(dataStream)) {\n  console.log(line);\n}\n```\n\n---\n\n## ✅ 模式验证\n\n使用 TONL 模式语言（TSL）定义模式：\n\n```tonl\n@schema v1\n@strict true\n@description \"用户管理模式\"\n\n# 定义自定义类型\nUser: obj\n  id: u32 必填\n  username: str 必填，长度3-20，格式^[a-zA-Z0-9_]+$\n  email: str 必填，格式email，且全小写\n  age: u32? 范围13-150\n  roles: list\u003Cstr> 必填，至少1个，且唯一\n\n# 根模式\nusers: list\u003CUser> 必填，至少1个\ntotalCount: u32 必填\n```\n\n**13 种内置约束：**\n- `required` - 字段必须存在\n- `min` \u002F `max` - 数值范围或字符串\u002F数组长度限制\n- `length` - 精确长度\n- `pattern` - 正则表达式验证（或快捷方式：`email`、`url`、`uuid`）\n- `unique` - 数组元素必须唯一\n- `nonempty` - 字符串\u002F数组不能为空\n- `positive` \u002F `negative` - 数字的正负号\n- `integer` - 必须是整数\n- `multipleOf` - 整除性检查\n- `lowercase` \u002F `uppercase` - 强制字符串大小写\n\n完整参考请见 [docs\u002FSCHEMA_SPECIFICATION.md](docs\u002FSCHEMA_SPECIFICATION.md)。\n\n---\n\n## 🛠️ 开发\n\n### 构建与测试\n\n```bash\n# 安装依赖\nnpm install\n\n# 构建 TypeScript\nnpm run build\n\n# 运行所有测试（698+ 测试）\nnpm test\n\n# 监听模式\nnpm run dev\n\n# 清理构建产物\nnpm run clean\n```\n\n### 基准测试\n\n```bash\n# 字节大小比较\nnpm run bench\n\n# 令牌估算（GPT-5、Claude 3.5、Gemini 2.0、Llama 4）\nnpm run bench-tokens\n\n# 全面性能分析\nnpm run bench-comprehensive\n```\n\n### CLI 开发\n\n```bash\n# 在本地安装 CLI\nnpm run link\n\n# 测试命令\ntonl encode test.json\ntonl query data.tonl \"users[*].name\"\ntonl format data.tonl --pretty\n\n# 测试交互功能（v2.3.1+）\ntonl stats data.json --interactive\ntonl stats data.json -i --theme neon\ntonl stats data.json --compare\n```\n\n---\n\n## 🗺️ 路线图\n\n**✅ v2.5.1 - 已完成（最新版本）**\n- ✅ 修复关键漏洞（数组扩展 DoS、JSON.stringify 漏洞、异步处理问题）\n- ✅ 482 个测试，通过率 100%\n- ✅ 提升稳定性和错误处理能力\n\n**✅ v2.5.0 - 已完成**\n- ✅ 聚合函数（count、sum、avg、groupBy、stats、median、percentile）\n- ✅ 模糊字符串匹配（Levenshtein、Jaro-Winkler、Soundex、Metaphone）\n- ✅ 时间查询（@now-7d、before、after、sameDay、daysAgo）\n- ✅ 763+ 个全面测试，通过率 100%\n\n**✅ v2.2+ - 已完成**\n- ✅ 革命性的交互式 CLI 控制台，支持实时分析\n- ✅ 完成模块化架构改造（735→75 行代码）\n- ✅ 文件对比系统，支持并排分析\n- ✅ 多种视觉主题（默认、霓虹、矩阵、赛博朋克）\n\n**✅ v2.0+ - 已完成**\n- ✅ 高级优化模块（额外压缩 60%）\n- ✅ 完整的查询、修改、索引和流式 API\n- ✅ 模式验证与 TypeScript 生成\n- ✅ 浏览器支持（10.5 KB 打包文件）\n- ✅ 100% 测试覆盖率及安全性加固\n\n**🚀 未来**\n- 增强的 VS Code 插件（IntelliSense、调试）\n- 带有实时转换功能的在线 Playground\n- Python、Go、Rust 实现\n- 二进制 TONL 格式，用于极致压缩\n\n完整开发愿景请见 [ROADMAP.md](ROADMAP.md)。\n\n---\n\n## 📖 文档\n\n### 针对用户\n- **[入门指南](docs\u002FGETTING_STARTED.md)** - 适合初学者的教程，附带示例\n- **[API 参考文档](docs\u002FAPI.md)** - 包含示例的完整 API 文档\n- **[CLI 文档](docs\u002FCLI.md)** - 命令行工具使用指南\n- **[浏览器 API](docs\u002FBROWSER.md)** - 支持 ESM、UMD 和 IIFE 构建的浏览器端使用说明\n- **[错误处理](docs\u002FERROR_HANDLING.md)** - 错误类及故障排除\n- **[查询 API](docs\u002FQUERY_API.md)** - 类似 JSONPath 的查询语法参考\n- **[修改 API](docs\u002FMODIFICATION_API.md)** - CRUD 操作指南\n- **[导航 API](docs\u002FNAVIGATION_API.md)** - 树形结构遍历方法\n- **[用例](docs\u002FUSE_CASES.md)** - 现实场景与解决方案\n\n### 针对实现者（其他语言）\n- **[实现参考](docs\u002FIMPLEMENTATION_REFERENCE.md)** - 与语言无关的实现指南\n- **[转换示例](docs\u002FTRANSFORMATION_EXAMPLES.md)** - 超过 20 个 JSON↔TONL 转换示例\n- **[格式规范](docs\u002FSPECIFICATION.md)** - 技术格式规范\n- **[模式规范](docs\u002FSCHEMA_SPECIFICATION.md)** - TSL（TONL 模式语言）规范\n\n**想在 Python、Go、Rust 或其他语言中实现 TONL 吗？** 请查看 [实现参考](docs\u002FIMPLEMENTATION_REFERENCE.md)，其中包含完整的算法、伪代码和测试要求！\n\n---\n\n## 🤝 贡献\n我们欢迎各种贡献！请阅读 [CONTRIBUTING.md](CONTRIBUTING.md)，了解：\n- 开发环境搭建\n- 代码风格指南\n- 测试要求\n- 拉取请求流程\n- 架构概览\n\n---\n\n## 📄 许可证\nMIT 许可证 - 详情请参阅 [LICENSE](LICENSE) 文件。\n\n---\n\n## 🌟 链接\n- **官网**: [tonl.dev](https:\u002F\u002Ftonl.dev)\n- **npm 包**: [npmjs.com\u002Fpackage\u002Ftonl](https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002Ftonl)\n- **GitHub**: [github.com\u002Ftonl-dev\u002Ftonl](https:\u002F\u002Fgithub.com\u002Ftonl-dev\u002Ftonl)\n- **问题追踪**: [github.com\u002Ftonl-dev\u002Ftonl\u002Fissues](https:\u002F\u002Fgithub.com\u002Ftonl-dev\u002Ftonl\u002Fissues)\n- **讨论区**: [github.com\u002Ftonl-dev\u002Ftonl\u002Fdiscussions](https:\u002F\u002Fgithub.com\u002Ftonl-dev\u002Ftonl\u002Fdiscussions)\n- **VS Code 扩展**: [即将推出]\n\n---\n\n\u003Cdiv align=\"center\">\n\n**TONL**: 让结构化数据更易于大模型理解，同时不牺牲可读性。🚀\n\n*由 [Ersin Koc](https:\u002F\u002Fgithub.com\u002Fersinkoc) 用心打造*\n\n\u003C\u002Fdiv>","# TONL 快速上手指南\n\nTONL (Token-Optimized Notation Language) 是一个专为大语言模型（LLM）优化的数据平台，结合了紧凑的序列化格式与强大的查询、修改及流处理能力。它能显著减少 JSON 体积和 LLM Token 消耗，同时保持人类可读性。\n\n## 环境准备\n\n在开始之前，请确保您的开发环境满足以下要求：\n\n*   **操作系统**：Windows, macOS, 或 Linux\n*   **运行时环境**：\n    *   **Node.js**: 推荐 v18.0.0 或更高版本\n    *   **npm**: 随 Node.js 安装，建议升级至最新版\n*   **前置依赖**：无（TONL 是纯 TypeScript 编写，零运行时依赖）\n\n> 💡 **国内加速建议**：如果您在中国大陆地区，建议使用淘宝镜像源加速安装过程：\n> ```bash\n> npm config set registry https:\u002F\u002Fregistry.npmmirror.com\n> ```\n\n## 安装步骤\n\n通过 npm 包管理器安装 TONL：\n\n```bash\nnpm install tonl\n```\n\n若需使用命令行工具（CLI），可全局安装：\n\n```bash\nnpm install -g tonl\n```\n\n## 基本使用\n\n### 1. 代码集成 (TypeScript\u002FJavaScript)\n\n以下示例展示了如何创建文档、执行类 JSONPath 查询、聚合数据以及修改内容。\n\n```typescript\nimport { TONLDocument, encodeTONL, decodeTONL } from 'tonl';\n\n\u002F\u002F 1. 从 JSON 创建文档\nconst doc = TONLDocument.fromJSON({\n  users: [\n    { id: 1, name: \"Alice\", role: \"admin\", age: 30 },\n    { id: 2, name: \"Bob\", role: \"user\", age: 25 }\n  ]\n});\n\n\u002F\u002F 2. 查询数据 (支持 JSONPath 语法)\ndoc.get('users[0].name');                          \u002F\u002F 输出: 'Alice'\ndoc.query('users[*].name');                        \u002F\u002F 输出: ['Alice', 'Bob']\ndoc.query('users[?(@.role == \"admin\")]');          \u002F\u002F 输出: [{ id: 1, ... }]\ndoc.query('$..age');                               \u002F\u002F 递归获取所有年龄\n\n\u002F\u002F 3. 数据聚合 (v2.4.0+)\ndoc.count('users[*]');                             \u002F\u002F 输出: 2\ndoc.sum('users[*]', 'age');                        \u002F\u002F 输出: 55\ndoc.avg('users[*]', 'age');                        \u002F\u002F 输出: 27.5\ndoc.groupBy('users[*]', 'role');                   \u002F\u002F 按角色分组\n\n\u002F\u002F 4. 修改数据\ndoc.set('users[0].age', 31);\ndoc.push('users', { id: 3, name: \"Carol\", role: \"editor\", age: 28 });\n\n\u002F\u002F 5. 遍历文档\ndoc.walk((path, value, depth) => {\n  console.log(`${path}: ${value}`);\n});\n\n\u002F\u002F 6. 导出与序列化\nconst tonlText = doc.toTONL();   \u002F\u002F 转换为紧凑的 TONL 格式\nconst jsonData = doc.toJSON();   \u002F\u002F 转回标准 JSON\nawait doc.save('output.tonl');   \u002F\u002F 保存到文件\n\n\u002F\u002F 7. 经典编码\u002F解码 API\nconst data = { users: [{ id: 1, name: \"Alice\" }] };\nconst encoded = encodeTONL(data);\nconst decoded = decodeTONL(encoded);\n```\n\n### 2. 命令行工具 (CLI)\n\n安装全局包后，您可以在终端直接使用 `tonl` 命令进行文件处理、统计和分析。\n\n**查看帮助与版本：**\n```bash\ntonl\ntonl --version\n```\n\n**文件格式转换：**\n```bash\n# 将 JSON 编码为 TONL (智能优化模式，带统计信息)\ntonl encode data.json --out data.tonl --smart --stats\n\n# 将 TONL 解码回 JSON\ntonl decode data.tonl --out data.json\n```\n\n**数据查询：**\n```bash\n# 在 TONL 文件中查询特定条件\ntonl query users.tonl \"users[?(@.role == 'admin')]\"\n\n# 在 JSON 文件中获取特定字段\ntonl get data.json \"user.profile.email\"\n```\n\n**交互式统计面板 (推荐)：**\n```bash\n# 启动交互式仪表盘，分析文件大小与 Token 节省情况\ntonl stats data.json --interactive\n\n# 指定主题风格 (neon, matrix, cyberpunk, default)\ntonl stats data.json -i --theme neon\n\n# 对比 JSON 与 TONL 的文件大小差异\ntonl stats data.json --compare\n```\n\n**格式化与验证：**\n```bash\n# 美化输出 TONL 文件\ntonl format data.tonl --pretty --out formatted.tonl\n\n# 根据 Schema 验证数据\ntonl validate users.tonl --schema users.schema.tonl\n```","某电商初创团队正在构建实时用户行为分析系统，需要将海量前端埋点数据高效传输给后端大模型进行意图识别与个性化推荐。\n\n### 没有 tonl 时\n- **Token 成本高昂**：传统 JSON 格式冗余字符多，导致每次向 LLM 发送用户行为序列时，消耗的 Token 数量巨大，月度 API 账单居高不下。\n- **查询逻辑繁琐**：开发人员需先将数据反序列化为对象，再编写复杂的循环代码才能提取特定字段（如“所有加购未支付的商品”），代码冗长且易出错。\n- **实时响应延迟**：在大数据量下，JSON 的解析与序列化过程占用大量 CPU 资源，导致从数据采集到模型反馈的链路延迟超过 200 毫秒，影响用户体验。\n- **聚合统计困难**：若需即时计算某类行为的平均值或总和，必须在应用层手动遍历数组实现，缺乏内置的高效聚合能力。\n\n### 使用 tonl 后\n- **显著降低费用**：tonl 紧凑的序列化格式使数据体积缩小约 60%，直接大幅减少了 LLM 的输入 Token 消耗，每月节省数千元 API 成本。\n- **声明式数据提取**：利用 tonl 类 JSONPath 语法，一行代码即可精准定位目标数据（如 `doc.query('events[?(@.type==\"cart\")].itemId')`），开发效率提升显著。\n- **极致处理速度**：凭借比传统方案快数十倍的解析性能，数据预处理延迟降至 20 毫秒以内，确保了推荐系统的实时性。\n- **内置强大聚合**：直接调用 `doc.avg()` 或 `doc.groupBy()` 等原生接口即可完成复杂统计，无需额外编写遍历逻辑，代码更简洁健壮。\n\ntonl 通过极致的压缩率与强大的内建查询引擎，成功解决了大模型应用中数据传输成本高与处理效率低的双重难题。","https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Ftonl-dev_tonl_fe3c661f.png","tonl-dev","TONL","https:\u002F\u002Foss.gittoolsai.com\u002Favatars\u002Ftonl-dev_076fa17f.png","Token-Optimized Notation Language",null,"info@tonl.dev","https:\u002F\u002Ftonl.dev","https:\u002F\u002Fgithub.com\u002Ftonl-dev",[84,88,92,96],{"name":85,"color":86,"percentage":87},"TypeScript","#3178c6",70.8,{"name":89,"color":90,"percentage":91},"HTML","#e34c26",18.2,{"name":93,"color":94,"percentage":95},"JavaScript","#f1e05a",7,{"name":97,"color":98,"percentage":99},"CSS","#663399",4,830,32,"2026-04-02T17:06:58","MIT",1,"Linux, macOS, Windows","不需要 GPU","未说明（支持流式处理，多 GB 文件仅需 \u003C100MB 内存）",{"notes":109,"python":110,"dependencies":111},"该工具是基于 TypeScript 开发的纯软件库，无需 Python 环境或 GPU 加速。主要通过 npm 安装，提供浏览器端（压缩后约 10.5KB）和 Node.js\u002FCLI 两种运行方式。具备零运行时依赖特性，支持交互式 CLI 仪表盘和多种终端主题。","不需要 Python",[112],"无运行时依赖 (Zero Dependencies)",[13,26],[115,116,117],"json","llm","token","2026-03-27T02:49:30.150509","2026-04-06T11:30:48.920706",[121,126,131,136,141,146],{"id":122,"question_zh":123,"answer_zh":124,"source_url":125},12094,"TONL 中何时使用表格格式（Tabular）而非块格式（Block）来编码包含集合属性的对象？","选择规则如下：\n1. **表格格式**：仅当对象的所有属性值均为原始类型（primitives）时使用。\n2. **块格式**：只要对象的任意属性是数组（array）或嵌套对象（nested object），就必须使用块格式。\n编码器会自动检测：如果 `hasOnlyPrimitives` 检查失败，则自动回退到块格式。文档已更新，明确说明了这一行为，并提供了具体示例。","https:\u002F\u002Fgithub.com\u002Ftonl-dev\u002Ftonl\u002Fissues\u002F27",{"id":127,"question_zh":128,"answer_zh":129,"source_url":130},12095,"TONL 相比 CSV 格式有什么优势？是否应该直接用 TONL 替换 CSV？","CSV 仅适用于严格的平面表格数据集。对于嵌套、半表格化或树状结构的 JSON 数据，将其展平为 CSV 会导致语义丢失且效率低下。\nTONL 的核心优势包括：\n1. **Token 效率高**：更适合发送给大语言模型（LLM）。\n2. **保留嵌套结构**：无需展平，无语义损失。\n3. **功能丰富**：内置 CRUD、查询和索引能力。\n4. **类型安全**：包含 Schema 定义。\n因此，对于复杂数据结构，TONL 是更好的选择；但对于简单扁平表，CSV 仍有其价值。","https:\u002F\u002Fgithub.com\u002Ftonl-dev\u002Ftonl\u002Fissues\u002F24",{"id":132,"question_zh":133,"answer_zh":134,"source_url":135},12096,"如何处理字符串中包含换行符的情况？","这是一个已知的解析问题。在早期版本中，包含换行符的字符串（如 `\"test\\ntest\"`）在转换为 TONL 并使用三引号 `\"\"\"` 包裹后，反向转换回 JSON 时可能会出现转义错误，导致数据损坏。维护者确认这是编码\u002F解码过程中的 Bug，正在通过修复解析逻辑来解决此类特殊字符的处理问题。建议在使用包含多行文本的数据时，先验证往返转换（Round-trip）的正确性。","https:\u002F\u002Fgithub.com\u002Ftonl-dev\u002Ftonl\u002Fissues\u002F6",{"id":137,"question_zh":138,"answer_zh":139,"source_url":140},12097,"如果对象键（Key）中包含冒号（:）或花括号（{}），会发生什么？","这是一个解析缺陷。如果 JSON 对象的键包含特殊字符（如冒号 `:` 或花括号 `{}`），当前的 TONL 编码器可能无法正确转义或引用这些键，导致生成的 TONL 格式无效。例如，键 `\"te:st\"` 可能被错误解析，导致反向转换后的 JSON 数据结构错乱（如键被截断）。此问题同样存在于包含花括号的键中。在修复前，建议避免在键名中使用这些特殊字符，或手动检查输出结果。","https:\u002F\u002Fgithub.com\u002Ftonl-dev\u002Ftonl\u002Fissues\u002F5",{"id":142,"question_zh":143,"answer_zh":144,"source_url":145},12098,"字符串以双引号开头时会导致数据损坏吗？","是的，这是一个已知的严重 Bug。如果字符串值的第一个字符是双引号（例如邮箱地址 `\"alice@company.com`），在转换为 TONL 后再转回 JSON 时，解析器会错误地处理引号，导致该行后续的所有字段被合并到该字符串字段中，其他字段丢失。这表明当前的字符串定界符逻辑在处理起始引号时存在漏洞。在使用此类数据前，请务必进行往返测试验证。","https:\u002F\u002Fgithub.com\u002Ftonl-dev\u002Ftonl\u002Fissues\u002F4",{"id":147,"question_zh":148,"answer_zh":149,"source_url":150},12099,"是否有社区构建的工具列表或生态系统展示？","维护者计划在未来添加一个“基于 TONL 构建的工具”章节。实现方案是在仓库中创建一个 `tools.md` 文件，并在 README 中添加链接。社区贡献者可以通过提交 PR 来更新该文件，列出他们使用 TONL 开发的项目、框架或库。这将有助于展示社区采用情况并方便开发者发现实际用例。目前该功能尚未完全上线，但欢迎社区提前准备相关内容。","https:\u002F\u002Fgithub.com\u002Ftonl-dev\u002Ftonl\u002Fissues\u002F12",[]]