### Install js-toml with bun Source: https://github.com/sunnyadn/js-toml/blob/main/README.md Install the js-toml package using bun. ```bash bun add js-toml ``` -------------------------------- ### Run the Example with Bun Source: https://github.com/sunnyadn/js-toml/blob/main/examples/esm/README.md Execute the main script of the example project using the Bun runtime. ```bash bun run index.ts ``` -------------------------------- ### Date/Time Token Examples Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/api-reference/Lexer.md Provides examples of date, time, and datetime token formats. ```toml DateTime 2024-07-09T14:30:00Z 1979-05-27 (date only) 07:32:00 (time only) ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/sunnyadn/js-toml/blob/main/CONTRIBUTING.md Installs all necessary dependencies for the project using pnpm. This should be run after cloning the repository. ```bash pnpm install ``` -------------------------------- ### Install js-toml with npm Source: https://github.com/sunnyadn/js-toml/blob/main/README.md Install the js-toml package using npm. ```bash npm install js-toml ``` -------------------------------- ### Install js-toml with yarn Source: https://github.com/sunnyadn/js-toml/blob/main/README.md Install the js-toml package using yarn. ```bash yarn add js-toml ``` -------------------------------- ### Install Dependencies with Bun Source: https://github.com/sunnyadn/js-toml/blob/main/examples/esm/README.md Use this command to install project dependencies when using Bun as your package manager. ```bash bun install ``` -------------------------------- ### Install js-toml with pnpm Source: https://github.com/sunnyadn/js-toml/blob/main/README.md Install the js-toml package using pnpm. ```bash pnpm add js-toml ``` -------------------------------- ### Key Token Examples Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/api-reference/Lexer.md Illustrates the different types of keys, including simple, quoted, and unquoted. ```toml SimpleKey identifier QuotedKey "quoted identifier" UnquotedKey identifier DotSeparator . ``` -------------------------------- ### Boolean Token Examples Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/api-reference/Lexer.md Demonstrates the boolean token types. ```toml Boolean true, false True true False false ``` -------------------------------- ### Install js-toml with npm, yarn, pnpm, or bun Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/usage-guide.md Install the js-toml package using your preferred package manager. ```bash npm install js-toml # or yarn add js-toml # or pnpm add js-toml # or bun add js-toml ``` -------------------------------- ### Dotted Key Example Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/architecture.md Demonstrates how dotted keys are parsed into hierarchical key paths. This is useful for representing nested configurations. ```toml author.name = "John" ``` -------------------------------- ### String Token Examples Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/api-reference/Lexer.md Illustrates the different types of string tokens recognized by the lexer. ```toml BasicString "hello" LiteralString 'hello' MultiLineBasicString """multi line""" MultiLineLiteralString '''multi line''' TomlString (Any string type) ``` -------------------------------- ### Table Token Examples Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/api-reference/Lexer.md Shows the tokens used for defining standard and array tables. ```toml StdTableOpen [ StdTableClose ] ArrayTableOpen || ArrayTableClose ]] ``` -------------------------------- ### Whitespace and Comment Token Examples Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/api-reference/Lexer.md Details the tokens for whitespace, newlines, and comments. ```toml WhiteSpace (space, tab) Newline \n, \r\n ExpressionNewLine (blank lines, comments) Comment # comment text ``` -------------------------------- ### Numeric Token Examples Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/api-reference/Lexer.md Shows the various numeric token formats supported, including integers, decimals, and floats. ```toml Integer 42, 0xff, 0o755, 0b11 DecimalInteger 42 NonDecimalInteger 0xff, 0o755, 0b11 Float 3.14, 1e10, inf, nan ``` -------------------------------- ### Catching Specific Error Types Example Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/api-reference/SyntaxParseError.md Illustrates how to catch and differentiate between various subclasses of `SyntaxParseError`. ```typescript import { load, SyntaxParseError, DepthLimitError, LexerError, ParserError, InterpreterError } from 'js-toml'; const toml = ` a.b.c.d.e = 1 `; try { const data = load(toml, { maxDepth: 2 }); } catch (error) { if (error instanceof DepthLimitError) { console.error('Nesting too deep'); } else if (error instanceof LexerError) { console.error('Invalid token'); } else if (error instanceof ParserError) { console.error('Invalid grammar'); } else if (error instanceof InterpreterError) { console.error('Semantic error'); } } ``` -------------------------------- ### Structural Token Examples Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/api-reference/Lexer.md Lists the tokens used for structuring TOML data, such as arrays and inline tables. ```toml ArrayOpen [ ArrayClose ] ArraySep , InlineTableOpen { InlineTableClose } InlineTableSep , InlineTableKeyValSep = KeyValueSeparator = ``` -------------------------------- ### Load TOML with Custom Max Depth Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/types.md Example of loading TOML content using the load() function with a specified maximum nesting depth. ```typescript import { load } from 'js-toml'; const toml = ` deeply.nested.key.structure = 1 `; // Use custom maximum depth const data = load(toml, { maxDepth: 200 }); ``` -------------------------------- ### Dump TOML with Options Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/types.md Example of dumping a JavaScript object to TOML format, ignoring undefined values and using Windows line endings. ```typescript import { dump } from 'js-toml'; const config = { name: 'App', version: '1.0.0', optional: undefined, }; // Ignore undefined values with Windows line endings const toml = dump(config, { ignoreUndefined: true, newline: '\r\n', forceQuotes: false, }); ``` -------------------------------- ### TOML Duplicate Key Syntax Error Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/usage-guide.md This example illustrates a common TOML syntax error caused by duplicate keys within the same scope or redefining a table. ```toml title = "A" title = "B" # Error: duplicate key # or [table] [table] # Error: table already defined ``` -------------------------------- ### Basic dump() Usage Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/configuration.md Demonstrates default configuration and how to apply specific options for line endings, ignoring undefined values, and forcing quotes on string keys. ```typescript import { dump } from 'js-toml'; // Default configuration (Unix line endings, strict type checking, bare keys) const toml1 = dump(obj); // Windows line endings const toml2 = dump(obj, { newline: '\r\n' }); // Tolerate undefined values and always quote keys const toml3 = dump(obj, { ignoreUndefined: true, forceQuotes: true, }); // Combine all options const toml4 = dump(obj, { newline: '\r\n', ignoreUndefined: true, forceQuotes: false, }); ``` -------------------------------- ### Lexer Initialization Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/api-reference/Lexer.md Initializes the Lexer with all TOML tokens and configuration options. The constructor takes a list of all possible tokens and an optional configuration object. ```APIDOC ## Lexer Constructor ### Description Initializes a new instance of the Lexer. ### Signature ```typescript new Lexer(allTokens: TokenType[], config?: { ensureOptimizations?: boolean; skipValidations?: boolean; traceInitPerf?: boolean; }) ``` ### Parameters #### Arguments - **allTokens** (TokenType[]) - Required - An array of all possible TOML token types. - **config** (object) - Optional - Configuration options for the lexer. - **ensureOptimizations** (boolean) - Optional - Ensures optimizations are applied. - **skipValidations** (boolean) - Optional - Skips validation steps. - **traceInitPerf** (boolean) - Optional - Traces initialization performance. ``` -------------------------------- ### SyntaxParseError Hierarchy Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/types.md Illustrates the inheritance structure of parsing-related errors in js-toml, starting from the base SyntaxParseError. ```typescript Error └── SyntaxParseError ├── LexerError ├── ParserError ├── InterpreterError └── DepthLimitError ``` -------------------------------- ### Loading and Using TOML Configuration File Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/usage-guide.md Demonstrates loading a TOML configuration string into a typed JavaScript object and accessing its properties. This is a common pattern for application settings. ```typescript import { readFileSync } from 'fs'; import { load } from 'js-toml'; interface AppConfig { title: string; version: string; database: { host: string; port: number; credentials: { username: string; password: string; }; }; servers: Array<{ name: string; url: string }>; } // config.toml const tomlContent = ` title = "MyApplication" version = "2.1.0" [database] host = "db.example.com" port = 5432 [database.credentials] username = "admin" password = "secret123" [[servers]] name = "production" url = "https://prod.example.com" [[servers]] name = "staging" url = "https://staging.example.com" `; const config = load(tomlContent) as AppConfig; // Use the configuration console.log(`Starting ${config.title} v${config.version}`); console.log(`Connecting to ${config.database.host}:${config.database.port}`); config.servers.forEach((server) => { console.log(`Server: ${server.name} → ${server.url}`); }); ``` -------------------------------- ### Build the Library Source: https://github.com/sunnyadn/js-toml/blob/main/CLAUDE.md Builds the js-toml library, outputting both ESM and CJS formats. Use this command before distributing or testing the library. ```bash # Build the library (outputs ESM and CJS formats) pnpm run build ``` -------------------------------- ### Full Specification Configuration for Load and Dump Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/configuration.md Demonstrates explicit configuration of all documented options for both loading and dumping TOML, including maxDepth, newline, ignoreUndefined, and forceQuotes. ```typescript import { load, dump, DEFAULT_MAX_DEPTH } from 'js-toml'; // Explicit configuration with all documented options const parsedData = load(tomlString, { maxDepth: DEFAULT_MAX_DEPTH, // 100 }); const serializedToml = dump(parsedData, { newline: '\n', ignoreUndefined: false, forceQuotes: false, }); ``` -------------------------------- ### Usage of load() with maxDepth Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/configuration.md Demonstrates how to use the load() function with default and custom maxDepth configurations. ```typescript import { load } from 'js-toml'; // Default configuration (maxDepth = 100) const data1 = load(tomlString); // Custom depth limit const data2 = load(tomlString, { maxDepth: 50 }); // Very permissive (not recommended) const data3 = load(tomlString, { maxDepth: 1000 }); ``` -------------------------------- ### Walk the TOML Interpreter Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/api-reference/Interpreter.md Demonstrates the complete process of lexing TOML input, parsing it into a Concrete Syntax Tree (CST), and then interpreting the CST into a JavaScript object. Ensure the lexer and parser are imported correctly. ```typescript import { parser } from './parser.js'; import { lexer } from './lexer.js'; import { Interpreter } from './interpreter.js'; const toml = ` [package] name = "example" version = "1.0.0" `; // Lexer: tokenize const lexingResult = lexer.tokenize(toml); if (lexingResult.errors.length > 0) throw new Error('Lexing failed'); // Parser: build CST parser.input = lexingResult.tokens; const cst = parser.toml(); if (parser.errors.length > 0) throw new Error('Parsing failed'); // Interpreter: convert CST to JavaScript const interpreter = new Interpreter(); interpreter.maxDepth = 100; const result = interpreter.visit(cst); console.log(result); // { package: { name: 'example', version: '1.0.0' } } ``` -------------------------------- ### Handling ParserError in js-toml Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/errors.md Demonstrates how to catch and log ParserErrors, which are triggered by TOML grammar violations. This snippet shows an example of a missing closing bracket in an array. ```typescript import { load, ParserError } from 'js-toml'; const toml = ` [table name = "test" `; try { load(toml); } catch (error) { if (error instanceof ParserError) { console.error('Parser error:', error.message); } } ``` -------------------------------- ### Browser/Bundler Import Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/export-summary.md Illustrates how to import specific functions from js-toml when using web bundlers, enabling tree-shaking. ```typescript // Tree-shaking works automatically import { load } from 'js-toml'; // Only load() is included in bundle import { dump } from 'js-toml'; // Only dump() is included in bundle import { load, dump } from 'js-toml'; // Both included ``` -------------------------------- ### Handling Stack Overflow as SyntaxParseError in js-toml Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/errors.md This example demonstrates how js-toml catches native JavaScript stack overflow errors and converts them into `SyntaxParseError`. It's generally not recommended to disable the `maxDepth` limit. ```typescript import { load, SyntaxParseError } from 'js-toml'; const massiveToml = '[[[[...many nested arrays...]]]]]'; try { load(massiveToml, { maxDepth: Infinity }); // Disable limit (not recommended) } catch (error) { if (error instanceof SyntaxParseError) { // If stack overflows: "Maximum nesting depth exceeded (stack overflow)" console.error('Fatal parse error:', error.message); } } ``` -------------------------------- ### Accessing Detailed Lexer and Parser Error Information Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/api-reference/SyntaxParseError.md Illustrates how to access the detailed error properties (`errors`) of LexerError and ParserError instances to get granular information about parsing issues, including line and column numbers. ```typescript import { load, LexerError, ParserError } from 'js-toml'; const toml = ` title = "Missing closing quote `; try { const data = load(toml); } catch (error) { if (error instanceof LexerError) { // Access Chevrotain lexing errors for detailed context error.errors.forEach((lexError) => { console.log('Lexing error:', lexError.message); console.log('Line:', lexError.line, 'Column:', lexError.column); }); } else if (error instanceof ParserError) { // Access Chevrotain parser errors for detailed context error.errors.forEach((parseError) => { console.log('Parse error:', parseError.message); }); } } ``` -------------------------------- ### Lexer Initialization Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/api-reference/Lexer.md Initializes a new Lexer instance with specific configurations for optimizations, validations, and performance tracing. ```typescript const lexer = new Lexer(allTokens, { ensureOptimizations: true, skipValidations: !envs.isDebug(), traceInitPerf: envs.isDebug(), }) ``` -------------------------------- ### Generate Syntax Diagram Source: https://github.com/sunnyadn/js-toml/blob/main/CLAUDE.md Generates a visual diagram of the TOML syntax. This is helpful for understanding the grammar and structure of the language. ```bash # Generate syntax diagram pnpm run diagram ``` -------------------------------- ### Run Tests with Vitest Source: https://github.com/sunnyadn/js-toml/blob/main/CLAUDE.md Executes the test suite using Vitest. This is a standard command for verifying code integrity. ```bash # Run tests with Vitest pnpm test ``` -------------------------------- ### Run Benchmarks Source: https://github.com/sunnyadn/js-toml/blob/main/CLAUDE.md Executes benchmark tests to measure the performance of the TOML parser. Use this to identify performance bottlenecks. ```bash # Run benchmarks pnpm run benchmark ``` -------------------------------- ### ESM Dynamic Import Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/export-summary.md Demonstrates how to dynamically import the load and dump functions using ECMAScript Modules. ```typescript // Dynamic import supported const { load, dump } = await import('js-toml'); ``` -------------------------------- ### Importing js-toml Public API Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/export-summary.md Demonstrates how to import core functionalities like load, dump, and error types from the main js-toml entry point. This is the recommended way to use the library. ```typescript import { load, dump, SyntaxParseError, LoadOptions, DEFAULT_MAX_DEPTH, } from 'js-toml'; ``` -------------------------------- ### Run Tests with Coverage Source: https://github.com/sunnyadn/js-toml/blob/main/CONTRIBUTING.md Executes the project's test suite and generates a code coverage report. This helps identify areas of the code not covered by tests. ```bash pnpm run test:cov ``` -------------------------------- ### Direct Lexer Usage for Tokenization Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/api-reference/Lexer.md Demonstrates how to directly use the lexer to tokenize a TOML string and access token properties. Ensure the lexer is imported correctly. ```typescript import { lexer } from 'src/load/lexer.js'; const result = lexer.tokenize('title = "value"'); if (result.errors.length === 0) { const tokens = result.tokens; console.log(tokens[0].image); // 'title' console.log(tokens[0].tokenType); // SimpleKey console.log(tokens[0].line); // 1 console.log(tokens[0].column); // 1 } ``` -------------------------------- ### CJS Require Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/export-summary.md Shows how to import the load and dump functions using CommonJS require syntax. ```javascript // CommonJS require const { load, dump } = require('js-toml'); // Require with path const toml = require('js-toml'); const { load, dump } = toml; ``` -------------------------------- ### Integrating Lexer Output with Parser Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/api-reference/Lexer.md Shows how to tokenize TOML content and feed the resulting tokens to the parser. Handles potential lexer errors by throwing a LexerError. ```typescript import { lexer } from 'src/load/lexer.js'; import { parser } from 'src/load/parser.js'; const lexResult = lexer.tokenize(toml); if (lexResult.errors.length > 0) { throw new LexerError(lexResult.errors); } parser.input = lexResult.tokens; // Feed tokens to parser const cst = parser.toml(); ``` -------------------------------- ### Serialize TOML with Options Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/usage-guide.md Demonstrates serializing JavaScript objects to TOML using various options like forcing quotes, specifying newline characters, and ignoring undefined properties. ```typescript import { dump } from 'js-toml'; const obj = { 'app-name': 'MyApp', description: 'A sample application', }; // Default: bare keys when safe dump(obj); // app-name = "MyApp" // description = "A sample application" // Force quoting all keys dump(obj, { forceQuotes: true }); // "app-name" = "MyApp" // "description" = "A sample application" // Windows line endings dump(obj, { newline: '\r\n' }); // Ignore undefined properties dump(obj, { ignoreUndefined: true }); ``` -------------------------------- ### js-toml Three-Stage Pipeline Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/architecture.md Illustrates the flow of data through the js-toml transformation process, from TOML input to a JavaScript object. ```text TOML Input String ↓ [LEXER] — Tokenization ↓ Token Stream ↓ [PARSER] — Grammar Analysis (CST generation) ↓ Concrete Syntax Tree (CST) ↓ [INTERPRETER] — Semantic Analysis & Object Construction ↓ JavaScript Object (TOML Document) ``` -------------------------------- ### TOML Configuration Loading with Validation Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/usage-guide.md Load TOML configuration and perform basic validation on required fields like 'title' and 'version'. This ensures essential configuration parameters are present and correctly typed before use. ```typescript import { load, SyntaxParseError } from 'js-toml'; interface ConfigSchema { title: string; version: string; database?: { host: string; port: number; }; } function loadConfig(tomlString): ConfigSchema { try { const data = load(tomlString); // Validate required fields if (!data.title || typeof data.title !== 'string') { throw new Error('Invalid config: missing or invalid "title"'); } if (!data.version || typeof data.version !== 'string') { throw new Error('Invalid config: missing or invalid "version"'); } return data as ConfigSchema; } catch (error) { if (error instanceof SyntaxParseError) { throw new Error(`TOML parse error: ${error.message}`); } throw error; } } ``` -------------------------------- ### Import and Log Default Max Depth Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/configuration.md Demonstrates importing the DEFAULT_MAX_DEPTH constant and using it to explicitly set the maxDepth option during TOML loading. ```typescript import { DEFAULT_MAX_DEPTH, load } from 'js-toml'; console.log(DEFAULT_MAX_DEPTH); // 100 // Explicitly set to the documented default const data = load(toml, { maxDepth: DEFAULT_MAX_DEPTH }); ``` -------------------------------- ### CST Visitor Methods for TOML Interpretation Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/architecture.md Implements Chevrotain's CST visitor pattern with methods for each grammar rule. Used to walk the CST and convert it into JavaScript objects. ```typescript class Interpreter extends BaseCstVisitor { toml(ctx) { ... } expression(ctx, context) { ... } keyValue(ctx, object) { ... } key(ctx) { ... } value(ctx) { ... } array(ctx) { ... } inlineTable(ctx, object) { ... } table(ctx, root) { ... } ... } ``` -------------------------------- ### TOML Parsing Data Flow Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/architecture.md Illustrates the stages of parsing a TOML string, from lexing to building the Concrete Syntax Tree (CST) and finally interpreting it into a JavaScript object. ```typescript // Input const toml = ` title = "Example" [owner] name = "Tom" `; // Lexer tokenizes [ SimpleKey('title'), KeyValueSeparator('='), BasicString('"Example"'), Newline('\n'), StdTableOpen('['), SimpleKey('owner'), StdTableClose(']'), ... ] // Parser builds CST { type: 'toml', children: { expression: [ { type: 'keyValue', children: { key: [{ type: 'simpleKey', ... }], value: [{ type: 'string', ... }] } }, { type: 'table', children: { /* ... */ } } ] } } // Interpreter visits CST { title: "Example", owner: { name: "Tom" } } ``` -------------------------------- ### Catching Generic SyntaxParseError Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/api-reference/SyntaxParseError.md Demonstrates how to use a try-catch block to handle any SyntaxParseError that occurs during TOML loading. This is useful for general error handling of invalid TOML. ```typescript import { load, SyntaxParseError } from 'js-toml'; const toml = ` title = "Test" title = "Duplicate key" `; try { const data = load(toml); } catch (error) { if (error instanceof SyntaxParseError) { console.error('Parsing failed:', error.message); } } ``` -------------------------------- ### Organize TOML Data into Tables and Arrays Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/usage-guide.md Illustrates how to structure a JavaScript object for TOML serialization, organizing simple key-value pairs, nested tables, and arrays of tables. ```typescript import { dump } from 'js-toml'; const config = { // Simple values go first title: 'App', version: '1.0.0', // Nested tables server: { host: 'localhost', port: 8080, }, // Array of tables endpoints: [ { path: '/api', enabled: true }, { path: '/admin', enabled: false }, ], }; const toml = dump(config); // Output order: // 1. Simple key-value pairs // 2. Nested table sections // 3. Array-of-tables sections ``` -------------------------------- ### Array of Tables Header Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/architecture.md Illustrates the syntax for defining an array of tables. Each `[[array.of.tables]]` block represents an element in the array. ```toml [[array.of.tables]] key = value ``` -------------------------------- ### Configure Line Endings for dump() Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/configuration.md Shows how to set Unix-style ('\n') or Windows-style ('\r\n') line endings for the generated TOML string. ```typescript import { dump } from 'js-toml'; const config = { name: 'App', version: '1.0.0', }; // Unix line endings const unix = dump(config); console.log(unix === 'name = "App"\nversion = "1.0.0"\n'); // Windows line endings const windows = dump(config, { newline: '\r\n' }); console.log(windows === 'name = "App"\r\nversion = "1.0.0"\r\n'); ``` -------------------------------- ### key Visitor Method Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/api-reference/Interpreter.md Extracts and validates a key path, splitting dotted keys into segments. Throws a DepthLimitError if key segments exceed the maximum depth. ```typescript key(ctx: KeyCstNode): string[] ``` -------------------------------- ### Consistent Key Formatting with Force Quotes Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/configuration.md Enables consistent key formatting by ensuring all keys are always quoted, which can improve compatibility with other tools. ```typescript import { dump } from 'js-toml'; // All keys always quoted for consistency with other tools const toml = dump(data, { forceQuotes: true }); ``` -------------------------------- ### Strict Parsing and Dumping Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/configuration.md Demonstrates loading TOML with default strict settings, which rejects deeply nested input, and dumping data with strict type checking. ```typescript import { load, dump } from 'js-toml'; // Parsing with default settings - rejects deeply nested input const data = load(toml); // Dumping with strict type checking const output = dump(data); ``` -------------------------------- ### Read and parse TOML from a file Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/usage-guide.md Use Node.js `readFileSync` to read a TOML file and then `load` to parse its content. ```typescript import { readFileSync } from 'fs'; import { load } from 'js-toml'; const tomlContent = readFileSync('config.toml', 'utf-8'); const config = load(tomlContent); ``` -------------------------------- ### table Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/api-reference/Interpreter.md Processes standard TOML table headers `[table.name]`, creating nested tables as needed. ```APIDOC ## table(ctx, root) ### Description Processes standard table headers `[table.name]`. ### Parameters - `ctx` (TableCstNode) - The parse context for the table. - `root` (Record) - The root object, used for creating nested tables. ### Returns - `Record` - The table object. ### Behavior - Creates intermediate tables as needed. - Marks table as explicitly declared. - Prevents mixing of standard and array-of-tables declarations. - Updates the current context to the table. ``` -------------------------------- ### Standard Table Header Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/architecture.md Shows the syntax for defining a standard TOML table. Key-value pairs within this section belong to the 'table.name' scope. ```toml [table.name] key = value ``` -------------------------------- ### dump() Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/README.md Serializes a JavaScript object into a TOML formatted string. It takes a JavaScript object and optional configuration options. ```APIDOC ## dump() ### Description Serializes a JavaScript object into a TOML formatted string. ### Method dump(obj, options?) ### Parameters #### Path Parameters - **obj** (object) - Required - The JavaScript object to serialize. - **options** (DumpOptions) - Optional - Configuration options for serialization. ### Response #### Success Response (200) - **string** (string) - The TOML formatted string. ``` -------------------------------- ### toml Visitor Method Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/api-reference/Interpreter.md The root rule visitor for the Interpreter. It processes the entire TOML document and returns the root object representing the TOML document. ```typescript toml(ctx: TomlCstNode): Record ``` -------------------------------- ### load() Function Signature and Usage Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/api-reference/load.md The load() function parses a TOML string into a JavaScript object. It accepts the TOML string and optional configuration options. The returned object is a prototype-free plain JavaScript object. ```APIDOC ## load(toml: string, options?: LoadOptions): Record ### Description Parses a TOML string into a JavaScript object. The output object is created with `Object.create(null)` to prevent prototype pollution. ### Parameters #### Parameters - **toml** (string) - Required - A TOML-formatted string to parse - **options** (LoadOptions) - Optional - Configuration options for parsing behavior ### LoadOptions #### Options - **maxDepth** (number) - Optional - Default: 100 - Maximum nesting depth for arrays, inline tables, dotted keys, and table headers. Prevents stack overflow from deeply nested input. Must be greater than 0. ### Return Type `Record` — A plain JavaScript object representing the parsed TOML document. ### Throws - **SyntaxParseError** — Base error class for all parsing failures - **LexerError** (extends SyntaxParseError) — Invalid TOML syntax detected during tokenization. - **ParserError** (extends SyntaxParseError) — Invalid TOML grammar detected during parsing. - **DepthLimitError** (extends SyntaxParseError) — Input exceeds the specified `maxDepth` limit. - **InterpreterError** (extends SyntaxParseError) — Semantic error during interpretation. - **RangeError** — Converted to SyntaxParseError if native stack overflow occurs. ### Basic Usage Example ```typescript import { load } from 'js-toml'; const toml = ` title = "TOML Example" [owner] name = "Tom Preston-Werner" `; const data = load(toml); console.log(data.title); // "TOML Example" console.log(data.owner.name); // "Tom Preston-Werner" ``` ### With Options Example ```typescript import { load } from 'js-toml'; const deepToml = ` a.b.c.d.e.f = 1 `; // Default maxDepth of 100 allows this const data = load(deepToml); // Reject deeply nested input try { const data = load(deepToml, { maxDepth: 3 }); } catch (error) { console.error(error.message); // "Maximum nesting depth of 3 exceeded" } ``` ### Parsing TOML 1.1.0 Features Example ```typescript import { load } from 'js-toml'; const toml11 = ` # TOML 1.1.0 features: # Datetime without seconds (TOML 1.1) timestamp = 2024-07-09T14:30 # Multiline inline tables (TOML 1.1) point = { x = 1, y = 2, z = 3, } # Inline table with trailing comma (TOML 1.1) settings = { enabled = true, } [[ array.of.tables ]] value = 1 [[ array.of.tables ]] value = 2 `; const data = load(toml11); console.log(data.timestamp instanceof Date); // true console.log(data.point); // { x: 1, y: 2, z: 3 } console.log(Array.isArray(data.array.of.tables)); // true ``` ### Error Handling Example ```typescript import { load, SyntaxParseError } from 'js-toml'; const invalidToml = ` title = "Test name = "Invalid string `; try { const data = load(invalidToml); } catch (error) { if (error instanceof SyntaxParseError) { console.error('Parse error:', error.message); // Access detailed errors if available if ('errors' in error) { console.error('Details:', error.errors); } } } ``` ``` -------------------------------- ### TOML Version Handling in js-toml Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/configuration.md Demonstrates parsing TOML v1.1.0 input and serializing to TOML v1.0.0 compatible output. The library always parses according to TOML v1.1.0 but serializes to v1.0.0 syntax. ```typescript import { load, dump } from 'js-toml'; // TOML 1.1.0 input (datetime without seconds) const toml11Input = 'timestamp = 2024-07-09T14:30'; const data = load(toml11Input); // Parses successfully // Output is TOML 1.0.0 compatible (seconds added) const toml10Output = dump(data); // timestamp = 2024-07-09T14:30:00.000Z ``` -------------------------------- ### Handle Unsupported Types with ignoreUndefined Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/configuration.md Demonstrates how to either throw an error for unsupported types (undefined, Symbol, Function) or silently drop them when dumping an object. ```typescript import { dump } from 'js-toml'; const obj = { name: 'Test', description: undefined, handler: () => {}, sym: Symbol('key'), }; // Strict mode (default) - throws error try { dump(obj); } catch (error) { console.error(error.message); // Cannot dump unsupported value type } // Lenient mode - silently drops unsupported properties const toml = dump(obj, { ignoreUndefined: true }); // name = "Test" // (description, handler, sym are dropped) ``` -------------------------------- ### Configuration File Round-Trip Update Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/usage-guide.md Read a TOML configuration file, modify its content programmatically, and write the updated TOML back to the file. This pattern is useful for automated configuration management. ```typescript import { load, dump } from 'js-toml'; // Read, modify, and write back function updateConfig(filePath, updater) { const original = readFileSync(filePath, 'utf-8'); const config = load(original); // Modify updater(config); // Write back const updated = dump(config); writeFileSync(filePath, updated); } // Usage updateConfig('config.toml', (config) => { config.version = '2.0.0'; config.database.port = 5433; }); ``` -------------------------------- ### Generating TOML for Package Manifest Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/usage-guide.md Create a TOML string representing a package manifest from a JavaScript object. This is useful for generating metadata files like `package.toml`. ```typescript import { dump } from 'js-toml'; const manifest = { name: 'my-package', version: '1.0.0', description: 'A useful package', author: { name: 'John Doe', email: 'john@example.com', }, dependencies: { express: '^4.18.0', 'body-parser': '^1.20.0', }, devDependencies: { typescript: '^5.0.0', jest: '^29.0.0', }, }; const toml = dump(manifest); console.log(toml); ``` -------------------------------- ### arrayOfTables Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/api-reference/Interpreter.md Processes TOML array-of-tables headers `[[table.name]]`, creating or appending to arrays of tables. ```APIDOC ## arrayOfTables(ctx, root) ### Description Processes array-of-tables headers `[[table.name]]`. ### Parameters - `ctx` (ArrayOfTablesCstNode) - The parse context for the array of tables. - `root` (Record) - The root object, used for creating nested arrays. ### Returns - `Record` - The newly created table within the array. ### Behavior - Creates or appends to an array of tables. - Each `[[table]]` declaration creates a new table object in the array. - Intermediate tables are created as needed. - Marks table as explicitly declared. ``` -------------------------------- ### Import CommonJS (CJS) Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/README.md Import the necessary functions and types from the 'js-toml' library for use in CommonJS environments. ```javascript const { load, dump, SyntaxParseError } = require('js-toml'); ``` -------------------------------- ### Write TOML to File Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/usage-guide.md Serializes a JavaScript object to TOML format and writes it to a file named 'config.toml'. Requires 'fs' and 'js-toml' imports. ```typescript import { writeFileSync } from 'fs'; import { dump } from 'js-toml'; const config = { name: 'MyApp', version: '1.0.0', }; const toml = dump(config); writeFileSync('config.toml', toml); ``` -------------------------------- ### expression Visitor Method Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/api-reference/Interpreter.md Processes key-value pairs or table definitions within the TOML structure. It returns the updated current table context. ```typescript expression(ctx: ExpressionCstNode, context: VisitorContext): Record ``` -------------------------------- ### toml Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/api-reference/Interpreter.md The root visitor method that processes the entire TOML document and returns the resulting JavaScript object. ```APIDOC ## toml(ctx) ### Description Processes the entire TOML document. ### Parameters - `ctx` (TomlCstNode) - Parse context containing an array of expressions. ### Returns - `Record` - The root object representing the TOML document. ``` -------------------------------- ### Validate Configuration Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/README.md Loads TOML data and performs basic validation by checking for the presence of required fields. Throws an error if a required field is missing. ```typescript function loadConfig(toml) { const data = load(toml); if (!data.required_field) throw new Error('Missing required_field'); return data; } ``` -------------------------------- ### Handling Deeply Nested Input with maxDepth Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/configuration.md Shows how to use load() with a strict maxDepth limit and catch potential DepthLimitError exceptions. ```typescript import { load, DepthLimitError } from 'js-toml'; const nestedToml = "\ config.database.primary.host = \"localhost\" config.database.primary.port = 5432 config.database.replica.host = \"replica.local\" "; try { // Default (100) allows this const data = load(nestedToml); // Strict limit rejects it const data2 = load(nestedToml, { maxDepth: 2 }); } catch (error) { if (error instanceof DepthLimitError) { console.error('Input too deeply nested'); } } ``` -------------------------------- ### key Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/api-reference/Interpreter.md Extracts and validates a key path, splitting dotted keys and enforcing depth limits. ```APIDOC ## key(ctx) ### Description Extracts and validates a key path. ### Parameters - `ctx` (KeyCstNode) - The parse context for the key. ### Returns - `string[]` - Array of key segments (dotted keys are split). ### Throws - `DepthLimitError` - If key segments exceed `maxDepth`. ``` -------------------------------- ### keyValue Visitor Method Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/api-reference/Interpreter.md Assigns a key-value pair to an object. It parses the key, evaluates the value, and assigns it, handling nested paths and throwing an error on duplicate keys. ```typescript keyValue(ctx: KeyValueCstNode, object: Record): void ``` -------------------------------- ### Parse TOML 1.1.0 features Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/usage-guide.md Demonstrates parsing of new features introduced in TOML 1.1.0, including datetimes without seconds and multiline inline tables with trailing commas. ```typescript import { load } from 'js-toml'; const toml11 = ` # Datetime without seconds (TOML 1.1) start_time = 2024-07-09T14:30 # Multiline inline tables (TOML 1.1) config = { debug = true, timeout = 30, retries = 3, } # Trailing comma in inline table (TOML 1.1) point = { x = 1, y = 2, } `; const data = load(toml11); console.log(data.start_time); // Date object console.log(data.config.debug); // true ``` -------------------------------- ### Interpreting String and Integer Tokens Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/api-reference/Lexer.md Illustrates how to use `tokenInterpreters` to convert token images for strings and integers into their corresponding JavaScript values. Assumes `BasicString` and `Integer` token types are defined. ```typescript // String token with value "hello" const token = { image: '"hello"', tokenType: BasicString }; const value = tokenInterpreters[BasicString](token); // 'hello' // Integer token with value 42 const numToken = { image: '42', tokenType: Integer }; const numValue = tokenInterpreters[Integer](numToken); // 42 ``` -------------------------------- ### Import ES Modules (ESM) Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/README.md Import the necessary functions and types from the 'js-toml' library for use in ES Module environments. ```typescript import { load, dump, SyntaxParseError } from 'js-toml'; import type { LoadOptions, DumpOptions } from 'js-toml'; ``` -------------------------------- ### LoadOptions Interface Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/types.md Defines the configuration object for the load() function, specifying the maximum nesting depth for parsing. ```typescript interface LoadOptions { maxDepth?: number; } ``` -------------------------------- ### Lint Code with ESLint Source: https://github.com/sunnyadn/js-toml/blob/main/CLAUDE.md Lints the codebase using ESLint to enforce code style and identify potential issues. This command helps maintain code quality. ```bash # Lint code with ESLint pnpm run lint ``` -------------------------------- ### Fix Code Style Issues Source: https://github.com/sunnyadn/js-toml/blob/main/CONTRIBUTING.md Automatically formats code and fixes linting issues according to project standards. This should be run before committing changes. ```bash pnpm run lint:fix ``` -------------------------------- ### dump() Function Signature Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/api-reference/dump.md The dump function serializes a JavaScript object into a TOML string. It accepts the object to serialize and optional configuration options. ```APIDOC ## dump(obj: Record, options?: DumpOptions): string ### Description Serializes a JavaScript object into a TOML string. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **obj** (Record) - Required - A plain JavaScript object to serialize into TOML format. * **options** (DumpOptions) - Optional - Configuration options for serialization behavior. ### DumpOptions | Option | Type | Required | Default | Description | |---|---|---|---|---| | newline | '\n' | '\r\n' | No | '\n' | Newline sequence to use between lines. Use '\r\n' for Windows line endings. | | ignoreUndefined | boolean | No | false | If true, properties with unsupported types (undefined, Symbol, Function) are silently dropped instead of throwing an error. | | forceQuotes | boolean | No | false | If true, string keys are always quoted in double quotes, even when they only contain bare-key characters (letters, digits, underscores, hyphens). | ### Return Type `string` - A TOML-formatted string representation of the input object. ### Throws * **Error** - Thrown if input is not a plain object. * **Error** - Thrown if input contains unsupported value types (undefined, Symbol, Function) and `ignoreUndefined` is false or not set. * **Error** - Thrown if a Date object has an invalid time value (e.g., `new Date('invalid')`). ### Supported Types * **Primitives**: string, number, bigint, boolean * **Dates**: `Date` objects (serialized to ISO 8601 format) * **Collections**: Arrays and plain objects * **Special Numbers**: NaN → 'nan', Infinity → 'inf', -Infinity → '-inf', -0 → '-0.0' ### Request Example ```typescript import { dump } from 'js-toml'; const obj = { title: 'TOML Example', owner: { name: 'Tom Preston-Werner', dob: new Date('1979-05-27T07:32:00-08:00'), }, }; const toml = dump(obj); console.log(toml); ``` ### Response #### Success Response (200) `string` - A TOML-formatted string representation of the input object. #### Response Example ```toml title = "TOML Example" [owner] name = "Tom Preston-Werner" dob = 1979-05-27T07:32:00.000Z ``` ``` -------------------------------- ### Handle Lexer Errors Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/api-reference/Lexer.md Demonstrates how to tokenize a TOML string and iterate through any lexing errors found. This is useful for debugging invalid TOML input. ```typescript const result = lexer.tokenize('title = "unclosed'); if (result.errors.length > 0) { result.errors.forEach((error) => { console.error(`Line ${error.line}, Column ${error.column}: ${error.message}`); }); } ``` -------------------------------- ### Load Large TOML Files Efficiently Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/usage-guide.md For TOML files exceeding 1MB, use `createReadStream` to load the file in chunks and then join them before parsing. This avoids loading the entire file into memory at once. ```typescript import { load } from 'js-toml'; // Stream the file import { createReadStream } from 'fs'; import { Readable } from 'stream'; async function loadLargeFile(filePath) { const chunks: string[] = []; const stream = createReadStream(filePath, 'utf-8'); for await (const chunk of stream) { chunks.push(chunk); } const toml = chunks.join(''); return load(toml); } ``` -------------------------------- ### Serialization with Quoted Keys and Windows Newlines Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/api-reference/dump.md Demonstrates serializing an object with keys that require quoting and using Windows-style newline characters. The `forceQuotes` option ensures all keys are quoted, and `newline: '\r\n'` sets the line ending. ```typescript import { dump } from 'js-toml'; const obj = { 'user-name': 'Alice', email: 'alice@example.com', }; // Default: bare keys when possible dump(obj); // user-name = "Alice" // email = "alice@example.com" // Force all keys to be quoted dump(obj, { forceQuotes: true }); // "user-name" = "Alice" // "email" = "alice@example.com" // Windows line endings dump(obj, { newline: '\r\n' }); ``` -------------------------------- ### Parse a TOML File Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/README.md Reads a TOML configuration file and parses its content into a JavaScript object. Ensure the file exists and is accessible. ```typescript import { readFileSync } from 'fs'; import { load } from 'js-toml'; const toml = readFileSync('config.toml', 'utf-8'); const config = load(toml); ``` -------------------------------- ### DumpOptions Interface Source: https://github.com/sunnyadn/js-toml/blob/main/_autodocs/types.md Defines the configuration object for the dump() function, controlling line endings, handling of undefined values, and string quoting. ```typescript interface DumpOptions { newline?: '\n' | '\r\n'; ignoreUndefined?: boolean; forceQuotes?: boolean; } ``` -------------------------------- ### Run Tests in Watch Mode Source: https://github.com/sunnyadn/js-toml/blob/main/CONTRIBUTING.md Executes the project's test suite and automatically re-runs tests when file changes are detected. This is useful for TDD. ```bash pnpm test ```